<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Tom Gotsman on Medium]]></title>
        <description><![CDATA[Stories by Tom Gotsman on Medium]]></description>
        <link>https://medium.com/@tgotsman12?source=rss-9e381e082139------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*uIStUV67opx_3bQgzoE-RA.png</url>
            <title>Stories by Tom Gotsman on Medium</title>
            <link>https://medium.com/@tgotsman12?source=rss-9e381e082139------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 08:03:37 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@tgotsman12/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Getting Started with Powerful Data Tables in your Python Web Apps]]></title>
            <link>https://medium.com/data-science/getting-started-with-powerful-data-tables-in-your-python-web-apps-1e48dc44caf2?source=rss-9e381e082139------2</link>
            <guid isPermaLink="false">https://medium.com/p/1e48dc44caf2</guid>
            <category><![CDATA[ag-grid]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[web-app-development]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Tom Gotsman]]></dc:creator>
            <pubDate>Sun, 06 Oct 2024 17:02:00 GMT</pubDate>
            <atom:updated>2024-10-06T17:02:00.923Z</atom:updated>
            <content:encoded><![CDATA[<h3>Getting Started with Powerful Data Tables in Your Python Web Apps</h3><h4>Using AG Grid to build a Finance app in pure Python with Reflex</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7slerBx3BxMwkHBxM-2_mQ.gif" /></figure><p>These past few months, I’ve been exploring various data visualization and manipulation tools for web applications. As a Python developer, I often need to handle large datasets and display them in interactive, customizable tables. One question that consistently bothered me was: How can I build a powerful data grid UI that integrates seamlessly with my Python backend?</p><p>There are countless options out there to build sophisticated data grids, but as a Python engineer, I have limited experience with JavaScript or any front-end framework. I was looking for a way to create a feature-rich data grid using only the language I’m most comfortable with — Python!</p><p>I decided to use Reflex, an open-source framework that lets me build web apps entirely in Python. What’s more, Reflex now offers integration with <a href="https://www.ag-grid.com/">AG Grid</a>, a feature-rich data grid library designed for displaying and manipulating tabular data in web applications which offers a wide array of functionalities including:</p><p>- In-place cell editing</p><p>- Real-time data updates</p><p>- Pagination and infinite scrolling</p><p>- Column filtering, reordering, resizing, and hiding</p><p>- Row grouping and aggregation</p><p>- Built-in theming</p><p><strong><em>Disclaimer:</em></strong><em> I work as a Founding Engineer at Reflex where I contribute to the open-source framework.</em></p><p>In this tutorial we will cover how to build a full Finance app from scratch in pure Python to display stock data in an interactive grid and graph with advanced features like sorting, filtering, and pagination — Check out the full live <a href="https://ag-grid-app.reflex.run/">app</a> and <a href="https://github.com/reflex-dev/reflex-examples/tree/main/ag_grid_finance">code</a>.</p><p><strong>Setup</strong></p><p>First we import the necessary libraries, including yfinance for fetching the stock data.</p><pre>import reflex as rx<br>from reflex_ag_grid import ag_grid<br>import yfinance as yf<br>from datetime import datetime, timedelta<br>import pandas as pd</pre><p><strong>Fetching and transforming data</strong></p><p>Next, we define the State class, which contains the application’s state and logic. The fetch_stock_data function fetches stock data for the specified companies and transforms it into a format suitable for display in AG Grid. We call this function when clicking on a button, by linking the on_click trigger of the button to this state function.</p><p>We define state variables, any fields in your app that may change over time (A State Var is directly rendered into the frontend of the app).</p><p>The data state variable stores the raw stock data fetched from Yahoo Finance. We transform this data to round the values and store it as a list of dictionaries, which is the format that AG Grid expects. The transformed data is sorted by date and ticker in descending order and stored in the dict_data state variable.</p><p>The datetime_now state variable stores the current datetime when the data was fetched.</p><pre># The list of companies to fetch data for<br>companies = [&quot;AAPL&quot;, &quot;MSFT&quot;, &quot;GOOGL&quot;, &quot;AMZN&quot;, &quot;META&quot;]<br><br>class State(rx.State):<br>    # The data fetched from Yahoo Finance<br>    data: pd.DataFrame<br>    # The data to be displayed in the AG Grid<br>    dict_data: list[dict] = [\{}]<br>    # The datetime of the current fetched data<br>    datetime_now: datetime = datetime.now()<br><br>    def fetch_stock_data(self):<br>        self.datetime_now = datetime.now()<br>        start_date = self.datetime_now - timedelta(days=180)<br><br>        # Fetch data for all tickers in a single download<br>        self.data = yf.download(companies, start=start_date, end=self.datetime_now, group_by=&#39;ticker&#39;)<br>        rows = []<br>        for ticker in companies:<br>            # Check if the DataFrame has a multi-level column index (for multiple tickers)<br>            if isinstance(self.data.columns, pd.MultiIndex):<br>                ticker_data = self.data[ticker]  # Select the data for the current ticker<br>            else:<br>                ticker_data = self.data  # If only one ticker, no multi-level index exists<br><br>            for date, row in ticker_data.iterrows():<br>                rows.append({<br>                    &quot;ticker&quot;: ticker,<br>                    &quot;date&quot;: date.strftime(&quot;%Y-%m-%d&quot;),<br>                    &quot;open&quot;: round(row[&quot;Open&quot;], 2),<br>                    &quot;high&quot;: round(row[&quot;High&quot;], 2),<br>                    &quot;mid&quot;: round((row[&quot;High&quot;] + row[&quot;Low&quot;]) / 2, 2),<br>                    &quot;low&quot;: round(row[&quot;Low&quot;], 2),<br>                    &quot;close&quot;: round(row[&quot;Close&quot;], 2),<br>                    &quot;volume&quot;: int(row[&quot;Volume&quot;]),<br>                })<br>        <br>        self.dict_data = sorted(rows, key=lambda x: (x[&quot;date&quot;], x[&quot;ticker&quot;]), reverse=True)</pre><pre>rx.button(<br>    &quot;Fetch Latest Data&quot;, <br>    on_click=State.fetch_stock_data, <br>)</pre><p><strong>Defining the AG Grid columns</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cJKsTAZTKvw9GA0D16y0CA.png" /><figcaption>Columns of AG Grid by Author</figcaption></figure><p>The column_defs list defines the columns to be displayed in the AG Grid. The header_name is used to set the header title for each column. The field key represents the id of each column. The filter key is used to insert the filter feature.</p><pre>column_defs = [<br>    ag_grid.column_def(field=&quot;ticker&quot;, header_name=&quot;Ticker&quot;, filter=ag_grid.filters.text, checkbox_selection=True),<br>    ag_grid.column_def(field=&quot;date&quot;, header_name=&quot;Date&quot;, filter=ag_grid.filters.date),<br>    ag_grid.column_def(field=&quot;open&quot;, header_name=&quot;Open&quot;, filter=ag_grid.filters.number),<br>    ag_grid.column_def(field=&quot;high&quot;, header_name=&quot;High&quot;, filter=ag_grid.filters.number),<br>    ag_grid.column_def(field=&quot;low&quot;, header_name=&quot;Low&quot;, filter=ag_grid.filters.number),<br>    ag_grid.column_def(field=&quot;close&quot;, header_name=&quot;Close&quot;, filter=ag_grid.filters.number),<br>    ag_grid.column_def(field=&quot;volume&quot;, header_name=&quot;Volume&quot;, filter=ag_grid.filters.number),<br>]</pre><p><strong>Displaying AG Grid</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dNm352B_sCIW7wJKW04x_Q.png" /><figcaption>AG Grid by Author</figcaption></figure><p>Now for the most important part of our app, AG Grid itself!</p><p>• id is required because it uniquely identifies the Ag-Grid instance on the page</p><p>• column_defs is the list of column definitions we defined earlier</p><p>• row_data is the data to be displayed in the grid, which is stored in the dict_data State var</p><p>• pagination, pagination_page_size and pagination_page_size_selector parameters enable pagination with specific variables in the grid</p><p>• theme enables you to set the theme of the grid</p><pre>ag_grid(<br>    id=&quot;myAgGrid&quot;,<br>    column_defs=column_defs,<br>    row_data=State.dict_data,<br>    pagination=True,<br>    pagination_page_size=20,<br>    pagination_page_size_selector=[10, 20, 50, 100],<br>    theme=State.grid_theme,<br>    on_selection_changed=State.handle_selection,<br>    width=&quot;100%&quot;,<br>    height=&quot;60vh&quot;,<br>)</pre><p><strong>Changing AG Grid Theming</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*b1NFCJyVbuLvM2h5PaZ2GA.png" /><figcaption>Changing AG Grid Theme by Author</figcaption></figure><p>We set theme using the grid_theme State var in the rx.select component.</p><p>Every state var has a built-in function to set it’s value for convenience, called set_VARNAME, in this case set_grid_theme.</p><pre>class State(rx.State):<br>    ...<br>    # The theme of the AG Grid<br>    grid_theme: str = &quot;quartz&quot;<br>    # The list of themes for the AG Grid<br>    themes: list[str] = [&quot;quartz&quot;, &quot;balham&quot;, &quot;alpine&quot;, &quot;material&quot;]<br><br>rx.select(<br>    State.themes,<br>    value=State.grid_theme,<br>    on_change=State.set_grid_theme,<br>    size=&quot;1&quot;,<br>)</pre><p><strong>Showing Company Data in a Graph</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nz9yLQiKGCReYOFEuypZxQ.png" /><figcaption>Showing 6 Months of Selected Company Data by Author</figcaption></figure><p>The on_selection_changed event trigger, shown in the AG grid code above, is called when the user selects a row in the grid. This calls the function handle_selection method in the State class, which sets the selected_rows state var to the new selected row and calls the function update_line_graph.</p><p>The update_line_graph function gets the relevant ticker and uses it to set the company state var. The Date, Mid, and DateDifference data for that company for the past 6 months is then set to the state var dff_ticker_hist.</p><p>Finally it is rendered in an rx.recharts.line_chart, using rx.recharts.error_bar to show the DateDifference data which are the highs and the lows for the day.</p><pre>class State(rx.State):<br>    ...<br>    # The selected rows in the AG Grid<br>    selected_rows: list[dict] = None<br>    # The currently selected company in AG Grid<br>    company: str<br>    # The data fetched from Yahoo Finance<br>    data: pd.DataFrame<br>    # The data to be displayed in the line graph<br>    dff_ticker_hist: list[dict] = None<br><br>    def handle_selection(self, selected_rows, _, __):<br>        self.selected_rows = selected_rows<br>        self.update_line_graph()<br>    <br>    def update_line_graph(self):<br>        if self.selected_rows:<br>            ticker = self.selected_rows[0][&quot;ticker&quot;]<br>        else:<br>            self.dff_ticker_hist = None<br>            return<br>        self.company = ticker<br>        <br>        dff_ticker_hist = self.data[ticker].reset_index()<br>        dff_ticker_hist[&quot;Date&quot;] = pd.to_datetime(dff_ticker_hist[&quot;Date&quot;]).dt.strftime(&quot;%Y-%m-%d&quot;)<br>        <br>        dff_ticker_hist[&quot;Mid&quot;] = (dff_ticker_hist[&quot;Open&quot;] + dff_ticker_hist[&quot;Close&quot;]) / 2<br>        dff_ticker_hist[&quot;DayDifference&quot;] = dff_ticker_hist.apply(<br>            lambda row: [row[&quot;High&quot;] - row[&quot;Mid&quot;], row[&quot;Mid&quot;] - row[&quot;Low&quot;]], axis=1<br>        )<br>        <br>        self.dff_ticker_hist = dff_ticker_hist.to_dict(orient=&quot;records&quot;)<br><br><br>rx.recharts.line_chart(<br>    rx.recharts.line(<br>        rx.recharts.error_bar(<br>            data_key=&quot;DayDifference&quot;,<br>            direction=&quot;y&quot;,<br>            width=4,<br>            stroke_width=2,<br>            stroke=&quot;red&quot;,<br>        ),<br>        data_key=&quot;Mid&quot;,<br>    ),<br>    rx.recharts.x_axis(data_key=&quot;Date&quot;),<br>    rx.recharts.y_axis(domain=[&quot;auto&quot;, &quot;auto&quot;]),<br>    data=State.dff_ticker_hist,<br>    width=&quot;100%&quot;,<br>    height=300,<br>)</pre><h4>Conclusion</h4><p>Using AG Grid inside the Reflex ecosystem empowered me as a Python developer to create sophisticated, data-rich web applications with ease. Whether you’re building complex dashboards, data analysis tools, or an application that demands powerful data grid capabilities, Reflex AG Grid has you covered.</p><p>I’m excited to see what you’ll build with Reflex AG Grid! Share your projects, ask questions, and join the discussion in our <a href="https://forum.reflex.dev/">community forums</a>. Together, let’s push the boundaries of what’s possible with Python web development!</p><p>If you have questions, please comment them below or message me on Twitter at <a href="https://twitter.com/tgotsman12">@tgotsman12</a> or on <a href="https://www.linkedin.com/in/tom-gotsman/">LinkedIn</a>. Share your app creations on social media and tag me, and I’ll be happy to provide feedback or help retweet!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1e48dc44caf2" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/getting-started-with-powerful-data-tables-in-your-python-web-apps-1e48dc44caf2">Getting Started with Powerful Data Tables in your Python Web Apps</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Build a ChatGPT-esque Web App in Pure Python using Reflex]]></title>
            <link>https://medium.com/data-science/build-a-chatgpt-esque-web-app-in-pure-python-using-reflex-bdc585038110?source=rss-9e381e082139------2</link>
            <guid isPermaLink="false">https://medium.com/p/bdc585038110</guid>
            <category><![CDATA[chatgpt]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[large-language-models]]></category>
            <category><![CDATA[reflex]]></category>
            <dc:creator><![CDATA[Tom Gotsman]]></dc:creator>
            <pubDate>Tue, 07 Nov 2023 13:56:58 GMT</pubDate>
            <atom:updated>2023-11-07T13:56:58.313Z</atom:updated>
            <content:encoded><![CDATA[<h4>Use OpenAI’s API to build a chat web app in pure Python with one line deployment</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/724/1*k6mWPhN50QEVEZA16IZwlg.gif" /><figcaption>Chat app GIF by Author</figcaption></figure><p>These past few months I have been playing around with all the incredible new LLM chatbots, including Llama 2, GPT-4, Falcon 40B and Claude 2. One question that consistently bothers me is how can I build my own chatbot UI that calls all these great LLMs as APIs?</p><p>There are countless options out there to build beautiful user interfaces, but as an ML engineer I have no experience with Javascript or any front-end language for that matter. I was looking for a way to build my web app using only the language that I currently know, Python!</p><p>I decided to use a fairly new open-source framework called Reflex, that let me build both my back-end and front-end purely in Python.</p><p><strong><em>Disclaimer:</em></strong><em> I work as a Founding Engineer at Reflex where I contribute to the open-source framework.</em></p><p>In this tutorial we will cover how to build a full AI chat app from scratch in pure Python — you can also find all the code at this <a href="https://github.com/reflex-dev/reflex-chat">Github repo</a>.</p><p>You’ll learn how to:</p><ol><li>Install reflex and set up your development environment.</li><li>Create components to define and style your UI.</li><li>Use state to add interactivity to your app.</li><li>Deploy your app with a one line command to share with others.</li></ol><h4><strong>Setting up Your Project</strong></h4><p>We will start by creating a new project and setting up our development environment. First, create a new directory for your project and navigate to it.</p><pre>~ $ mkdir chatapp<br>~ $ cd chatapp</pre><p>Next, we will create a virtual environment for our project. In this example, we will use <a href="https://docs.python.org/3/library/venv.html">venv</a> to create our virtual environment.</p><pre>chatapp $ python3 -m venv .venv<br>$ source .venv/bin/activate</pre><p>Now, we will install Reflex and create a new project. This will create a new directory structure in our project directory.</p><pre>chatapp $ pip install reflex<br>chatapp $ reflex init<br>────────────────────────────────── Initializing chatapp ───────────────────────────────────<br>Success: Initialized chatapp<br>chatapp $ ls<br>assets          chatapp         rxconfig.py     .venv</pre><p>You can run the template app to make sure everything is working.</p><pre>chatapp $ reflex run<br>─────────────────────────────────── Starting Reflex App ───────────────────────────────────<br>Compiling:  ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 100% 1/1 0:00:00<br>─────────────────────────────────────── App Running ───────────────────────────────────────<br>App running at: http://localhost:3000</pre><p>You should see your app running at <a href="http://localhost:3000/">http://localhost:3000 </a>.</p><p>Reflex also starts the backend server which handles all the state management and communication with the frontend. You can test the backend server is running by navigating to <a href="http://localhost:8000/ping">http://localhost:8000/ping </a>.</p><p>Now that we have our project set up, let’s build our app!</p><h4>Basic Frontend</h4><p>Let’s start with defining the frontend for our chat app. In Reflex, the frontend can be broken down into independent, reusable components. See the <a href="https://reflex.dev/docs/components/overview">components docs </a>for more information.</p><p><strong>Display A Question And Answer</strong></p><p>We will modify the index function in chatapp/chatapp.py file to return a component that displays a single question and answer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/643/1*r9qwOTRVWwNjXC-kpXe8vw.png" /><figcaption>Image by Author (code below)</figcaption></figure><pre># chatapp.py<br><br>import reflex as rx<br><br>def index() -&gt; rx.Component:<br>    return rx.container(<br>        rx.box(<br>            &quot;What is Reflex?&quot;,<br>            # The user&#39;s question is on the right.<br>            text_align=&quot;right&quot;,<br>        ),<br>        rx.box(<br>            &quot;A way to build web apps in pure Python!&quot;,<br>            # The answer is on the left.<br>            text_align=&quot;left&quot;,<br>        ),<br>    )<br><br># Add state and page to the app.<br>app = rx.App()<br>app.add_page(index)<br>app.compile()</pre><p>Components can be nested inside each other to create complex layouts. Here we create a parent container that contains two boxes for the question and answer.</p><p>We also add some basic styling to the components. Components take in keyword arguments, called <a href="https://reflex.dev/docs/components/props">props</a>, that modify the appearance and functionality of the component. We use the text_align prop to align the text to the left and right.</p><p><strong>Reusing Components</strong></p><p>Now that we have a component that displays a single question and answer, we can reuse it to display multiple questions and answers. We will move the component to a separate function question_answer and call it from the index function.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/644/1*5zsmqHQstQczCwqX4sCl7Q.png" /><figcaption>Image by Author (code below)</figcaption></figure><pre>def qa(question: str, answer: str) -&gt; rx.Component:<br>    return rx.box(<br>        rx.box(question, text_align=&quot;right&quot;),<br>        rx.box(answer, text_align=&quot;left&quot;),<br>        margin_y=&quot;1em&quot;,<br>    )<br><br><br>def chat() -&gt; rx.Component:<br>    qa_pairs = [<br>        (<br>            &quot;What is Reflex?&quot;,<br>            &quot;A way to build web apps in pure Python!&quot;,<br>        ),<br>        (<br>            &quot;What can I make with it?&quot;,<br>            &quot;Anything from a simple website to a complex web app!&quot;,<br>        ),<br>    ]<br>    return rx.box(<br>        *[<br>            qa(question, answer)<br>            for question, answer in qa_pairs<br>        ]<br>    )<br><br><br>def index() -&gt; rx.Component:<br>    return rx.container(chat())</pre><p><strong>Chat Input</strong></p><p>Now we want a way for the user to input a question. For this, we will use the <a href="https://reflex.dev/docs/library/forms/input">input </a>component to have the user add text and a <a href="https://reflex.dev/docs/library/forms/button">button </a>component to submit the question.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/648/1*54_QdmCmsBSOs0vWgKE8ZA.png" /><figcaption>Image by Author (code below)</figcaption></figure><pre>def action_bar() -&gt; rx.Component:<br>    return rx.hstack(<br>        rx.input(placeholder=&quot;Ask a question&quot;),<br>        rx.button(&quot;Ask&quot;),<br>    )<br><br><br>def index() -&gt; rx.Component:<br>    return rx.container(<br>        chat(),<br>        action_bar(),<br>    )</pre><p><strong>Styling</strong></p><p>Let’s add some styling to the app. More information on styling can be found in the <a href="https://reflex.dev/docs/styling/overview">styling docs</a>. To keep our code clean, we will move the styling to a separate file chatapp/style.py.</p><pre># style.py<br><br># Common styles for questions and answers.<br>shadow = &quot;rgba(0, 0, 0, 0.15) 0px 2px 8px&quot;<br>chat_margin = &quot;20%&quot;<br>message_style = dict(<br>    padding=&quot;1em&quot;,<br>    border_radius=&quot;5px&quot;,<br>    margin_y=&quot;0.5em&quot;,<br>    box_shadow=shadow,<br>    max_width=&quot;30em&quot;,<br>    display=&quot;inline-block&quot;,<br>)<br># Set specific styles for questions and answers.<br>question_style = message_style | dict(<br>    bg=&quot;#F5EFFE&quot;, margin_left=chat_margin<br>)<br>answer_style = message_style | dict(<br>    bg=&quot;#DEEAFD&quot;, margin_right=chat_margin<br>)<br># Styles for the action bar.<br>input_style = dict(<br>    border_width=&quot;1px&quot;, padding=&quot;1em&quot;, box_shadow=shadow<br>)<br>button_style = dict(bg=&quot;#CEFFEE&quot;, box_shadow=shadow)</pre><p>We will import the styles in chatapp.py and use them in the components. At this point, the app should look like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/646/1*y2zlPR6_1OQ4z9Ghk4dOaw.png" /><figcaption>Image by Author</figcaption></figure><pre># chatapp.py<br>import reflex as rx<br><br>from chatapp import style<br><br>def qa(question: str, answer: str) -&gt; rx.Component:<br>    return rx.box(<br>        rx.box(<br>            rx.text(question, style=style.question_style),<br>            text_align=&quot;right&quot;,<br>        ),<br>        rx.box(<br>            rx.text(answer, style=style.answer_style),<br>            text_align=&quot;left&quot;,<br>        ),<br>        margin_y=&quot;1em&quot;,<br>    )<br><br>def chat() -&gt; rx.Component:<br>    qa_pairs = [<br>        (<br>            &quot;What is Reflex?&quot;,<br>            &quot;A way to build web apps in pure Python!&quot;,<br>        ),<br>        (<br>            &quot;What can I make with it?&quot;,<br>            &quot;Anything from a simple website to a complex web app!&quot;,<br>        ),<br>    ]<br>    return rx.box(<br>        *[<br>            qa(question, answer)<br>            for question, answer in qa_pairs<br>        ]<br>    )<br><br>def action_bar() -&gt; rx.Component:<br>    return rx.hstack(<br>        rx.input(<br>            placeholder=&quot;Ask a question&quot;,<br>            style=style.input_style,<br>        ),<br>        rx.button(&quot;Ask&quot;, style=style.button_style),<br>    )<br><br>def index() -&gt; rx.Component:<br>    return rx.container(<br>        chat(),<br>        action_bar(),<br>    )<br><br>app = rx.App()<br>app.add_page(index)<br>app.compile()</pre><p>The app is looking good, but it’s not very useful yet! Now let’s add some functionality.</p><h4>State</h4><p>Now let’s make the chat app interactive by adding state. The state is where we define all the variables that can change in the app and all the functions that can modify them. You can learn more about state in the <a href="https://reflex.dev/docs/state/overview">state docs</a>.</p><p><strong>Defining State</strong></p><p>We will create a new file called state.py in the chatapp directory. Our state will keep track of the current question being asked and the chat history. We will also define an event handler answerwhich will process the current question and add the answer to the chat history.</p><pre># state.py<br><br>import reflex as rx<br><br><br>class State(rx.State):<br>    # The current question being asked.<br>    question: str<br>    # Keep track of the chat history as a list of (question, answer) tuples.<br>    chat_history: list[tuple[str, str]]<br>    def answer(self):<br>        # Our chatbot is not very smart right now...<br>        answer = &quot;I don&#39;t know!&quot;<br>        self.chat_history.append((self.question, answer))</pre><p><strong>Binding State to Components</strong></p><p>Now we can import the state in chatapp.py and reference it in our frontend components. We will modify the chat component to use the state instead of the current fixed questions and answers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/644/1*w58kZZ3q-juomLxPR3BBQg.png" /><figcaption>Image by Author</figcaption></figure><pre># chatapp.py<br><br>from chatapp.state import State<br><br><br>...<br><br><br>def chat() -&gt; rx.Component:<br>    return rx.box(<br>        rx.foreach(<br>            State.chat_history,<br>            lambda messages: qa(messages[0], messages[1]),<br>        )<br>    )<br><br><br>...<br><br><br>def action_bar() -&gt; rx.Component:<br>    return rx.hstack(<br>        rx.input(<br>            placeholder=&quot;Ask a question&quot;,<br>            on_change=State.set_question,<br>            style=style.input_style,<br>        ),<br>        rx.button(<br>            &quot;Ask&quot;,<br>            on_click=State.answer,<br>            style=style.button_style,<br>        ),<br>    )</pre><p>Normal Python for loops don&#39;t work for iterating over state vars because these values can change and aren&#39;t known at compile time. Instead, we use the <a href="https://reflex.dev/docs/library/layout/foreach">foreach</a> component to iterate over the chat history.</p><p>We also bind the input’s on_change event to the set_question event handler, which will update the question state var while the user types in the input. We bind the button&#39;s on_click event to the answer event handler, which will process the question and add the answer to the chat history. The set_question event handler is a built-in implicitly defined event handler. Every base var has one. Learn more in the <a href="https://reflex.dev/docs/state/events">events docs</a> under the Setters section.</p><p><strong>Clearing the Input</strong></p><p>Currently the input doesn’t clear after the user clicks the button. We can fix this by binding the value of the input to question, with value=State.question, and clear it when we run the event handler for answer, with self.question = &#39;&#39;.</p><pre># chatapp.py<br><br><br>def action_bar() -&gt; rx.Component:<br>    return rx.hstack(<br>        rx.input(<br>            value=State.question,<br>            placeholder=&quot;Ask a question&quot;,<br>            on_change=State.set_question,<br>            style=style.input_style,<br>        ),<br>        rx.button(<br>            &quot;Ask&quot;,<br>            on_click=State.answer,<br>            style=style.button_style,<br>        ),<br>    )</pre><pre># state.py<br><br><br>def answer(self):<br>    # Our chatbot is not very smart right now...<br>    answer = &quot;I don&#39;t know!&quot;<br>    self.chat_history.append((self.question, answer))<br>    self.question = &quot;&quot;</pre><p><strong>Streaming Text</strong></p><p>Normally state updates are sent to the frontend when an event handler returns. However, we want to stream the text from the chatbot as it is generated. We can do this by yielding from the event handler. See the <a href="https://reflex.dev/docs/state/events#yielding-multiple-updates">event yield docs</a> for more info.</p><pre># state.py<br>import asyncio<br><br><br>...<br><br><br>async def answer(self):<br>    # Our chatbot is not very smart right now...<br>    answer = &quot;I don&#39;t know!&quot;<br>    self.chat_history.append((self.question, &quot;&quot;))<br>    # Clear the question input.<br>    self.question = &quot;&quot;<br>    # Yield here to clear the frontend input before continuing.<br>    yield<br>    for i in range(len(answer)):<br>        # Pause to show the streaming effect.<br>        await asyncio.sleep(0.1)<br>        # Add one letter at a time to the output.<br>        self.chat_history[-1] = (<br>            self.chat_history[-1][0],<br>            answer[: i + 1],<br>        )<br>        yield</pre><h4>Using the API</h4><p>We will use OpenAI’s API to give our chatbot some intelligence. We need to modify our event handler to send a request to the API.</p><pre># state.py<br><br>import os<br>import openai<br><br>openai.api_key = os.environ[&quot;OPENAI_API_KEY&quot;]<br><br><br>...<br><br><br>def answer(self):<br>    # Our chatbot has some brains now!<br>    session = openai.ChatCompletion.create(<br>        model=&quot;gpt-3.5-turbo&quot;,<br>        messages=[<br>            {&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: self.question}<br>        ],<br>        stop=None,<br>        temperature=0.7,<br>        stream=True,<br>    )<br><br>    # Add to the answer as the chatbot responds.<br>    answer = &quot;&quot;<br>    self.chat_history.append((self.question, answer))<br><br>    # Clear the question input.<br>    self.question = &quot;&quot;<br>    # Yield here to clear the frontend input before continuing.<br>    yield<br><br>    for item in session:<br>        if hasattr(item.choices[0].delta, &quot;content&quot;):<br>            answer += item.choices[0].delta.content<br>            self.chat_history[-1] = (<br>                self.chat_history[-1][0],<br>                answer,<br>            )<br>            yield</pre><p>Finally, we have our AI chatbot!</p><h4>Conclusion</h4><p>Following this tutorial we have successfully created our Chat App using OpenAI’s API key, purely in Python.</p><p>To run this app now we can run the simple command:</p><pre>$ reflex run</pre><p>To deploy it, so that we can share it with other users, we can run the command:</p><pre>$ reflex deploy</pre><p>I hope this tutorial inspires you to build your own LLM based apps. I’m eager to see what you all end up building, so please reach out on social media or in the comments.</p><p>If you have questions, please comment them below or message me on Twitter at <a href="https://twitter.com/tgotsman12">@tgotsman12</a> or on <a href="https://www.linkedin.com/in/tom-gotsman/">LinkedIn</a>. Share your app creations on social media and tag me, and I’ll be happy to provide feedback or help retweet!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bdc585038110" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/build-a-chatgpt-esque-web-app-in-pure-python-using-reflex-bdc585038110">Build a ChatGPT-esque Web App in Pure Python using Reflex</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Reflex | Bridging the Gap: Bringing Web Development to Python]]></title>
            <link>https://medium.com/@tgotsman12/reflex-bridging-the-gap-bringing-web-development-to-python-68945e0fc5f4?source=rss-9e381e082139------2</link>
            <guid isPermaLink="false">https://medium.com/p/68945e0fc5f4</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[python-web-developer]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[reflex]]></category>
            <dc:creator><![CDATA[Tom Gotsman]]></dc:creator>
            <pubDate>Thu, 05 Oct 2023 20:57:34 GMT</pubDate>
            <atom:updated>2023-10-06T19:27:49.558Z</atom:updated>
            <content:encoded><![CDATA[<h4>Why can’t we make full-stack web apps using just Python?</h4><h4>The Problem</h4><p>Python is one of the most popular programming languages in the world. Webdev is one of the most popular applications of programming. So why can’t we make full-stack web apps using just Python?</p><p><strong>1. Too Many New Languages are Needed</strong></p><p>Traditional frontend tools like HTML / CSS / Javascript are overwhelming and time consuming to learn. HTML helps you structure your content, CSS makes it look nice, and JavaScript adds interactivity. Lacking knowledge of these languages makes building web apps extremely difficult.</p><p><strong>2. Low Code Solutions are Limiting</strong></p><p>Recent no code and low code alternatives have issues. No code solutions that save time in the development process lack the flexibility and robustness of traditional web development. Low code frameworks are often confusing and only solve part of the problem forcing you to use multiple tools to get the job done.</p><p><strong>3. Deploying Your App is Confusing</strong></p><p>Once you’ve built your web app, it’s time to share it with the world. It can be a nightmare to understand how to put your app on a server so others can use it. On top of hosting your frontend/backend you need to learn how to configure and maintain SSL, CDNs, and monitoring/analytics. And if your app becomes really popular, it can be even harder to handle lots of users at once.</p><p>In a nutshell, building web apps can be challenging, especially if you’re new to web development.</p><h4>The Solution</h4><p>Meet <a href="https://reflex.dev/">Reflex</a>, a newcomer to the Python framework family. Reflex is here to make web development easier. It’s like a bridge between easy-to-use tools and the more complex ones.</p><p><strong>1. One Language for Your Whole App</strong></p><p>Reflex is open-source and designed for python people. The framework unifies the front-end and back-end allowing you to create both using purely python. It makes creating web apps simple, so developers new to web development don’t have to learn all the complicated stuff right away.</p><p><strong>2. Keep the Full Functionality of Traditional Web Development</strong></p><p>Since Reflex leverages the current web ecosystem, the framework can handle anything traditional web development can, but still be kept extremely simple. And with Reflex’s templates you can have an app up and running in minutes, rather than hours or days.</p><p><strong>3. Batteries Included Hosting</strong></p><p>Reflex can provide all hosting out of the box with zero configuration. With a single reflex deploy command your infrastructure will automatically be set up so you can share your ideas faster.</p><p>With Reflex, you’re on your way to becoming a web development pro. Whether you’re making a small tool for data science or a big web app, Reflex can help. It’s great at making your apps run smoothly and handling lots of users, so you can focus on making them look amazing and fun to use. So, let’s get started on this exciting journey! 🚀</p><p>For the rest of this article we will walk through a tutorial to create your first Reflex web app. We are going to build a Chat App that responds to messages in a ChatGPT format.</p><p>A quick demo from the app is shown below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/724/1*k6mWPhN50QEVEZA16IZwlg.gif" /></figure><p><strong>Installation and Setup</strong></p><p>Python 3.8+ is required to install Reflex. We recommend using a virtual environment, such as <a href="https://docs.python.org/3/library/venv.html">venv</a>, <a href="https://docs.conda.io/en/latest/">conda</a> or <a href="https://python-poetry.org/">poetry</a>, to prevent package conflicts. You can install Reflex as a pip package.</p><pre>$ pip install reflex</pre><p>You can test this installation out by creating a new project folder and using the initialization commands as below:</p><pre>$ mkdir chatapp<br>$ cd chatapp<br>$ reflex init</pre><p>Th reflex init command initializes a template app in your directory. You then can test everything is working by running the app in development mode with the reflex run command.</p><pre>$ reflex run</pre><p>After executing this command, you should see the template app displayed locally at <a href="http://localhost:3000/">http://localhost:3000</a>. The chatapp.py file, located in the chatapp folder, is used to display the content of your app. This file contains all the written code for your app and it is where the frontend and backend are combined.</p><h4><strong>My First Reflex Chat App</strong></h4><p><strong>Display a Question and Answer</strong></p><p>Let’s start by just modifying the index function, which defines the frontend of the app, in the chatapp/chatapp.py file to return a component that displays a single question and answer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/755/1*Y9MC7-Ha197x0XBzyUiEoA.png" /></figure><pre># chatapp.py<br>import reflex as rx<br><br><br>def index() -&gt; rx.Component:<br>    return rx.container(<br>        rx.box(<br>            &quot;What is Reflex?&quot;,<br>            # The user&#39;s question is on the right.<br>            text_align=&quot;right&quot;,<br>        ),<br>        rx.box(<br>            &quot;A way to build web apps in pure Python!&quot;,<br>            # The answer is on the left.<br>            text_align=&quot;left&quot;,<br>        ),<br>    )<br><br><br># Add state and page to the app.<br>app = rx.App()<br>app.add_page(index)<br>app.compile()</pre><p>Components can be nested inside each other to create complex layouts. Here we create a parent container that contains two boxes for the question and answer.</p><p>Reflex comes with an arsenal of built in <a href="https://reflex.dev/docs/library/">components</a> to help users get started. Unlike other low code frameworks, Reflex’s layout and components are fully customizable.</p><p>We also add some basic styling to the components. Components take in keyword arguments, called <a href="https://reflex.dev/docs/components/props/">props</a>, that modify the appearance and functionality of the component. We use the text_align prop to align the text to the left and right.</p><p>In addition, we also need to define our app, add a route to the index component and finally compile our app.</p><p><strong>Reusing Components</strong></p><p>Now that we have a component that displays a single question and answer, we can reuse it to display multiple questions and answers. We will move the component to a separate function question_answerand call it from the index function.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/752/1*IAZOALj_bO74fFv7Nfjnkg.png" /></figure><pre>def qa(question: str, answer: str) -&gt; rx.Component:<br>    return rx.box(<br>        rx.box(question, text_align=&quot;right&quot;),<br>        rx.box(answer, text_align=&quot;left&quot;),<br>        margin_y=&quot;1em&quot;,<br>    )<br><br><br>def chat() -&gt; rx.Component:<br>    qa_pairs = [<br>        (<br>            &quot;What is Reflex?&quot;,<br>            &quot;A way to build web apps in pure Python!&quot;,<br>        ),<br>        (<br>            &quot;What can I make with it?&quot;,<br>            &quot;Anything from a simple website to a complex web app!&quot;,<br>        ),<br>    ]<br>    return rx.box(<br>        *[<br>            qa(question, answer)<br>            for question, answer in qa_pairs<br>        ]<br>    )<br><br><br>def index() -&gt; rx.Component:<br>    return rx.container(chat())</pre><p><strong>Chat Input</strong></p><p>Now we want a way for the user to input a question. For this, we will use the <a href="https://reflex.dev/docs/library/forms/input/">input</a> component to have the user add text and a <a href="https://reflex.dev/docs/library/forms/button/">button</a> component to submit the question.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/755/1*wce6ONAV6xr0CUgsehaEvA.png" /></figure><pre>def action_bar() -&gt; rx.Component:<br>    return rx.hstack(<br>        rx.input(placeholder=&quot;Ask a question&quot;),<br>        rx.button(&quot;Ask&quot;),<br>    )<br><br><br>def index() -&gt; rx.Component:<br>    return rx.container(<br>        chat(),<br>        action_bar(),<br>    )</pre><p><strong>Styling</strong></p><p>Let’s add some styling to the app. Reflex components can be easily styled using the full power of CSS by passing them in as Python keyword arguments. More information on styling can be found in the <a href="https://reflex.dev/docs/styling/overview/">styling docs</a>. To keep our code clean, we will move the styling to a separate file chatapp/style.py.</p><pre># style.py<br><br># Common styles for questions and answers.<br>shadow = &quot;rgba(0, 0, 0, 0.15) 0px 2px 8px&quot;<br>chat_margin = &quot;20%&quot;<br>message_style = dict(<br>    padding=&quot;1em&quot;,<br>    border_radius=&quot;5px&quot;,<br>    margin_y=&quot;0.5em&quot;,<br>    box_shadow=shadow,<br>    max_width=&quot;30em&quot;,<br>    display=&quot;inline-block&quot;,<br>)<br><br># Set specific styles for questions and answers.<br>question_style = message_style | dict(<br>    bg=&quot;#F5EFFE&quot;, margin_left=chat_margin<br>)<br>answer_style = message_style | dict(<br>    bg=&quot;#DEEAFD&quot;, margin_right=chat_margin<br>)<br><br># Styles for the action bar.<br>input_style = dict(<br>    border_width=&quot;1px&quot;, padding=&quot;1em&quot;, box_shadow=shadow<br>)<br>button_style = dict(bg=&quot;#CEFFEE&quot;, box_shadow=shadow)</pre><p>We will import the styles in chatapp.py and use them in the components. At this point, the app should look like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/756/1*7yQBRHdYFs5bkweG4MjvvA.png" /></figure><pre># chatapp.py<br>import reflex as rx<br><br>from chatapp import style<br><br><br>def qa(question: str, answer: str) -&gt; rx.Component:<br>    return rx.box(<br>        rx.box(<br>            rx.text(question, style=style.question_style),<br>            text_align=&quot;right&quot;,<br>        ),<br>        rx.box(<br>            rx.text(answer, style=style.answer_style),<br>            text_align=&quot;left&quot;,<br>        ),<br>        margin_y=&quot;1em&quot;,<br>    )<br><br><br>def chat() -&gt; rx.Component:<br>    qa_pairs = [<br>        (<br>            &quot;What is Reflex?&quot;,<br>            &quot;A way to build web apps in pure Python!&quot;,<br>        ),<br>        (<br>            &quot;What can I make with it?&quot;,<br>            &quot;Anything from a simple website to a complex web app!&quot;,<br>        ),<br>    ]<br>    return rx.box(<br>        *[<br>            qa(question, answer)<br>            for question, answer in qa_pairs<br>        ]<br>    )<br><br><br>def action_bar() -&gt; rx.Component:<br>    return rx.hstack(<br>        rx.input(<br>            placeholder=&quot;Ask a question&quot;,<br>            style=style.input_style,<br>        ),<br>        rx.button(&quot;Ask&quot;, style=style.button_style),<br>    )<br><br><br>def index() -&gt; rx.Component:<br>    return rx.container(<br>        chat(),<br>        action_bar(),<br>    )<br><br><br>app = rx.App()<br>app.add_page(index)<br>app.compile()</pre><p>The app is looking good, but it’s not very useful yet! In the next section, we will add some functionality to the app.</p><h4>State</h4><p>Now let’s make the chat app interactive by adding state. The state is where we define all the variables that can change in the app and all the functions that can modify them.</p><p><strong>Defining State</strong></p><p>We will create a new file called state.py in the chatapp directory. Our state will keep track of the current question being asked and the chat history. We will also define an event handler answer which will process the current question and add the answer to the chat history.</p><pre># state.py<br>class State(rx.State):<br><br>    # The current question being asked.<br>    question: str<br><br>    # Keep track of the chat history as a list of (question, answer) tuples.<br>    chat_history: list[tuple[str, str]]<br><br>    def answer(self):<br>        # Our chatbot is not very smart right now...<br>        answer = &quot;I don&#39;t know!&quot;<br>        self.chat_history.append((self.question, answer))</pre><p><strong>Binding State to Components</strong></p><p>Now we can import the state in chatapp.py and reference it in our frontend components. We will modify the chat component to use the state instead of the current fixed questions and answers.</p><pre># chatapp.py<br>from chatapp.state import State<br><br>...<br><br><br>def chat() -&gt; rx.Component:<br>    return rx.box(<br>        rx.foreach(<br>            State.chat_history,<br>            lambda messages: qa(messages[0], messages[1]),<br>        )<br>    )<br><br><br>...<br><br><br>def action_bar() -&gt; rx.Component:<br>    return rx.hstack(<br>        rx.input(<br>            placeholder=&quot;Ask a question&quot;,<br>            on_change=State.set_question,<br>            style=style.input_style,<br>        ),<br>        rx.button(<br>            &quot;Ask&quot;,<br>            on_click=State.answer,<br>            style=style.button_style,<br>        ),<br>    )</pre><p>Normal Python for loops don&#39;t work for iterating over state vars because these values can change and aren&#39;t known at compile time. Instead, we use the <a href="https://reflex.dev/docs/library/layout/foreach/">foreach</a> component to iterate over the chat history.</p><p>We also bind the input’s on_change event to the set_question event handler, which will update the question state var while the user types in the input. We bind the button&#39;s on_click event to the answer event handler, which will process the question and add the answer to the chat history. The set_question event handler is a built-in implicitly defined event handler. Every base var has one. Learn more in the <a href="https://reflex.dev/docs/state/events/">events docs</a> under the Setters section.</p><p><strong>Clearing the Input</strong></p><p>Currently the input doesn’t clear after the user clicks the button. We can fix this by binding the value of the input to question, with value=State.question, and clear it when we run the event handler for answer, with self.question = &#39;&#39;.</p><pre># chatapp.py<br>def action_bar() -&gt; rx.Component:<br>    return rx.hstack(<br>        rx.input(<br>            value=State.question,<br>            placeholder=&quot;Ask a question&quot;,<br>            on_change=State.set_question,<br>            style=style.input_style,<br>        ),<br>        rx.button(<br>            &quot;Ask&quot;,<br>            on_click=State.answer,<br>            style=style.button_style,<br>        ),<br>    )</pre><pre># state.py<br>def answer(self):<br>    # Our chatbot is not very smart right now...<br>    answer = &quot;I don&#39;t know!&quot;<br>    self.chat_history.append((self.question, answer))<br>    self.question = &quot;&quot;</pre><p><strong>Streaming Text</strong></p><p>Normally state updates are sent to the frontend when an event handler returns. However, we want to stream the text from the chatbot as it is generated. We can do this by yielding from the event handler. See the <a href="https://reflex.dev/docs/state/events/#yielding-multiple-updates">event yield docs</a> for more info.</p><pre># state.py<br>import asyncio<br><br>...<br><br><br>async def answer(self):<br>    # Our chatbot is not very smart right now...<br>    answer = &quot;I don&#39;t know!&quot;<br>    self.chat_history.append((self.question, &quot;&quot;))<br><br>    # Clear the question input.<br>    self.question = &quot;&quot;<br>    # Yield here to clear the frontend input before continuing.<br>    yield<br><br>    for i in range(len(answer)):<br>        # Pause to show the streaming effect.<br>        await asyncio.sleep(0.1)<br>        # Add one letter at a time to the output.<br>        self.chat_history[-1] = (<br>            self.chat_history[-1][0],<br>            answer[: i + 1],<br>        )<br>        yield</pre><p><strong>Using the API</strong></p><p>Finally, we will use OpenAI’s API to give our chatbot some intelligence. We need to modify our event handler to send a request to the API.</p><pre># state.py<br>import os<br>import openai<br><br>openai.api_key = os.environ[&quot;OPENAI_API_KEY&quot;]<br><br>...<br><br><br>def answer(self):<br>    # Our chatbot has some brains now!<br>    session = openai.ChatCompletion.create(<br>        model=&quot;gpt-3.5-turbo&quot;,<br>        messages=[<br>            {&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: self.question}<br>        ],<br>        stop=None,<br>        temperature=0.7,<br>        stream=True,<br>    )<br><br>    # Add to the answer as the chatbot responds.<br>    answer = &quot;&quot;<br>    self.chat_history.append((self.question, answer))<br><br>    # Clear the question input.<br>    self.question = &quot;&quot;<br>    # Yield here to clear the frontend input before continuing.<br>    yield<br><br>    for item in session:<br>        if hasattr(item.choices[0].delta, &quot;content&quot;):<br>            answer += item.choices[0].delta.content<br>            self.chat_history[-1] = (<br>                self.chat_history[-1][0],<br>                answer,<br>            )<br>            yield</pre><p>Finally, we have our AI chatbot web app, built purely in python.</p><h4>Final Code</h4><p>We wrote all our code in three files, which you can find below.</p><pre># chatapp.py<br>import reflex as rx<br><br>from chatapp import style<br>from chatapp.state import State<br><br><br>def qa(question: str, answer: str) -&gt; rx.Component:<br>    return rx.box(<br>        rx.box(<br>            rx.text(question, text_align=&quot;right&quot;),<br>            style=style.question_style,<br>        ),<br>        rx.box(<br>            rx.text(answer, text_align=&quot;left&quot;),<br>            style=style.answer_style,<br>        ),<br>        margin_y=&quot;1em&quot;,<br>    )<br><br><br>def chat() -&gt; rx.Component:<br>    return rx.box(<br>        rx.foreach(<br>            State.chat_history,<br>            lambda messages: qa(messages[0], messages[1]),<br>        )<br>    )<br><br><br>def action_bar() -&gt; rx.Component:<br>    return rx.hstack(<br>        rx.input(<br>            value=State.question,<br>            placeholder=&quot;Ask a question&quot;,<br>            on_change=State.set_question,<br>            style=style.input_style,<br>        ),<br>        rx.button(<br>            &quot;Ask&quot;,<br>            on_click=State.answer,<br>            style=style.button_style,<br>        ),<br>    )<br><br><br>def index() -&gt; rx.Component:<br>    return rx.container(<br>        chat(),<br>        action_bar(),<br>    )<br><br><br>app = rx.App()<br>app.add_page(index)<br>app.compile()</pre><pre># state.py<br>import reflex as rx<br>import os<br>import openai<br><br><br>openai.api_key = os.environ[&quot;OPENAI_API_KEY&quot;]<br><br><br>class State(rx.State):<br><br>    # The current question being asked.<br>    question: str<br><br>    # Keep track of the chat history as a list of (question, answer) tuples.<br>    chat_history: list[tuple[str, str]]<br><br>    def answer(self):<br>        # Our chatbot has some brains now!<br>        session = openai.ChatCompletion.create(<br>            model=&quot;gpt-3.5-turbo&quot;,<br>            messages=[<br>                {&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: self.question}<br>            ],<br>            stop=None,<br>            temperature=0.7,<br>            stream=True,<br>        )<br><br>        # Add to the answer as the chatbot responds.<br>        answer = &quot;&quot;<br>        self.chat_history.append((self.question, answer))<br><br>        # Clear the question input.<br>        self.question = &quot;&quot;<br>        # Yield here to clear the frontend input before continuing.<br>        yield<br><br>        for item in session:<br>            if hasattr(item.choices[0].delta, &quot;content&quot;):<br>                answer += item.choices[0].delta.content<br>                self.chat_history[-1] = (<br>                    self.chat_history[-1][0],<br>                    answer,<br>                )<br>                yield</pre><pre># style.py<br><br># Common styles for questions and answers.<br>shadow = &quot;rgba(0, 0, 0, 0.15) 0px 2px 8px&quot;<br>chat_margin = &quot;20%&quot;<br>message_style = dict(<br>    padding=&quot;1em&quot;,<br>    border_radius=&quot;5px&quot;,<br>    margin_y=&quot;0.5em&quot;,<br>    box_shadow=shadow,<br>)<br><br># Set specific styles for questions and answers.<br>question_style = message_style | dict(<br>    bg=&quot;#F5EFFE&quot;, margin_left=chat_margin<br>)<br>answer_style = message_style | dict(<br>    bg=&quot;#DEEAFD&quot;, margin_right=chat_margin<br>)<br><br># Styles for the action bar.<br>input_style = dict(<br>    border_width=&quot;1px&quot;, padding=&quot;1em&quot;, box_shadow=shadow<br>)<br>button_style = dict(bg=&quot;#CEFFEE&quot;, box_shadow=shadow)</pre><p><a href="https://reflex.dev/">Reflex</a> is a powerful tool for building web apps in Python without the need for extensive knowledge of web-specific technologies. Its user-friendly and intuitive interface liberates developers to concentrate on crafting compelling and functional web applications, sparing them from the intricacies that often accompany traditional web development. With Reflex, the path to web app creation becomes more accessible and creativity-driven.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=68945e0fc5f4" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>