<?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 Ashwin Kumar on Medium]]></title>
        <description><![CDATA[Stories by Ashwin Kumar on Medium]]></description>
        <link>https://medium.com/@shwinda?source=rss-13ca56953261------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*JoevlVqjan0zc0r8KtmqPg.png</url>
            <title>Stories by Ashwin Kumar on Medium</title>
            <link>https://medium.com/@shwinda?source=rss-13ca56953261------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 04:10:18 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@shwinda/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[Build a full-stack LLM application with OpenAI, Flask, React, and Pinecone (Part 2)]]></title>
            <link>https://shwinda.medium.com/build-a-full-stack-llm-application-with-openai-flask-react-and-pinecone-part-2-ceda4e290c33?source=rss-13ca56953261------2</link>
            <guid isPermaLink="false">https://medium.com/p/ceda4e290c33</guid>
            <dc:creator><![CDATA[Ashwin Kumar]]></dc:creator>
            <pubDate>Tue, 28 Nov 2023 16:25:44 GMT</pubDate>
            <atom:updated>2023-11-28T16:25:44.371Z</atom:updated>
            <content:encoded><![CDATA[<p>Part 2: Frontend chat interface with React</p><p>Welcome to part 2 of our series on building a full-stack LLM application using OpenAI, Flask, React, and Pinecone. You can find part 1 <a href="https://shwinda.medium.com/build-a-full-stack-llm-application-with-openai-flask-react-and-pinecone-part-1-f3844429a5ef">here</a> (this post assumes you’ve already completed part 1 and have a functioning Flask backend).</p><p>In this post, we’ll build the front-end chat interface for our application using React.</p><h4>Posts in this series:</h4><ol><li><a href="https://shwinda.medium.com/build-a-full-stack-llm-application-with-openai-flask-react-and-pinecone-part-1-f3844429a5ef">Part 1: Backend and RAG with Python, OpenAI, and Pinecone</a></li><li><strong><em>Part 2 (this post): Front-end chat user interface with React</em></strong></li><li>Part 3 (coming): Tracking important metrics for an LLM application</li></ol><h3>What we’re building</h3><p>In this series, our journey will take us through the creation of a simple web application that allows a user to input a URL and ask questions about the content on that webpage. We’ve already built out the Flask (Python) backend in <a href="https://shwinda.medium.com/build-a-full-stack-llm-application-with-openai-flask-react-and-pinecone-part-1-f3844429a5ef">part 1</a>, so we’re focusing here on building the front-end.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bR80dqyugmxsfSI22COolw.gif" /><figcaption>Q&amp;A app with GPT-4</figcaption></figure><p><strong>Components of the frontend application:</strong></p><ul><li><strong>URL input: </strong>The user can enter any URL into the UI of the web application. The backend will embed the contents of that webpage and index them in a vector database.</li><li><strong>Chat interface: </strong>The user sees a ChatGPT-style interface to ask questions about the content of the website and get answers from OpenAI’s GPT-4. The frontend also sends the entire chat history to the backend to give GPT-4 context on the current conversation.</li><li><strong>Streaming responses: </strong>Instead of making the user wait for GPT-4 to generate a full response, we’ll stream its response token-by-token to the front-end as it’s being generated.</li></ul><h3>Step 2: Setting up App.js</h3><h4>Creating the React app</h4><p>To make things simple, we’ll use the <a href="https://create-react-app.dev/">Create React App</a> package. Run the following in your terminal, one command at a time:</p><pre># Enter the root project directory (where your Python backend is)<br>cd ./YourApp<br><br># Install the Create React App package globally<br>npm install -g create-react-app<br><br># Create the React app in a folder named &#39;client&#39;<br>npx create-react-app client</pre><p>After a few seconds, your app will be created!</p><h4>Install react-markdown</h4><p>To make the chat interface simpler for the user, we’ll be rendering the responses from GPT-4 in <a href="https://en.wikipedia.org/wiki/Markdown">Markdown</a> (we’ve specified in our prompt to GPT-4 to ensure that it returns responses in Markdown format). We’ll be using the <a href="https://www.npmjs.com/package/react-markdown">react-markdown</a> library to handle this. Type the following into your terminal:</p><pre># Enter the client directory<br>cd client<br><br># Install react-markdown<br>npm install --save react-markdown</pre><h4>Modify folder structure and copy in CSS</h4><p>We’re going to modify the React app’s folder structure slightly to make it more organized. Make sure your structure looks like this (create the empty files for ones that aren’t there yet):</p><pre>/YourApp<br>    /app  # from part 1<br>    /client<br>        /public # keep this as is<br>        /src<br>            /components # new folder<br>                ChatInterface.js # create empty files<br>                ChatMessage.js<br>                UrlInput.js<br>            /styles<br>                styles.css  # copy this file from GitHub<br>            App.js<br>            index.js<br>        .gitignore<br>        package.json<br>    .env<br>    .gitignore<br>    requirements.txt<br>    run.py</pre><p>Copy in the contents of the style.css file from the <a href="https://github.com/ashnkumar/llm_full_stack_tutorial/blob/part2_frontend/client/src/styles/styles.css">GitHub source code</a>.</p><h3>Step 2: Creating the App.js logic</h3><p>To keep things simple, our App.js file will be the main “controller” for the application. Since we have two screens (the URL input screen and the chat interface), we’ll implement logic inside App.js to handle showing the right component to the user:</p><pre>// YourApp/client/src/App.js<br><br>import React, { useState, useEffect } from &#39;react&#39;;<br>import UrlInput from &#39;./components/UrlInput&#39;;<br>import ChatInterface from &#39;./components/ChatInterface&#39;;<br><br>function App() {<br>  const [showChat, setShowChat] = useState(false); // Add state to control UI transition<br>  const handleUrlSubmitted = () =&gt; {<br>    setShowChat(true); // Transition to the ChatInterface<br>  };<br><br>  // Delete the Pinecone index when the user leaves the page<br>  useEffect(() =&gt; {<br>    return () =&gt; {<br>      fetch(&#39;http://localhost:5000/delete-index&#39;, {<br>        method: &#39;POST&#39;,<br>      })<br>        .then((response) =&gt; {<br>          if (!response.ok) {<br>            console.error(&#39;Error deleting index:&#39;, response.statusText);<br>          }<br>        })<br>        .catch((error) =&gt; {<br>          console.error(&#39;Error:&#39;, error);<br>        });<br>    };<br>  }, []);<br><br>  return (<br>    &lt;div className=&quot;App&quot;&gt;<br>      {!showChat ? (<br>        &lt;UrlInput onSubmit={handleUrlSubmitted} /&gt;<br>      ) : (<br>        &lt;ChatInterface /&gt;<br>      )}<br>    &lt;/div&gt;<br>  );<br>}<br><br>export default App;</pre><p>First, we’ll use a simple showChat state variable to determine which component to show the user. When the user submits the URL on the UrlInput.js component, the app will automatically switch to showing the ChatInterface.js component.</p><h4>Deleting the Pinecone index upon leaving the page</h4><p>You’ll notice a useEffect hook that runs whenever the App.js component unmounts (when the user leaves or refreshes the page). Since we’re using the free tier on Pinecone (this only allows one index) we’ll want to delete this and create it again for every new page visit. This is not how you’d handle this in production but we’re aiming for simplicity here!</p><p>Let’s set up the delete-index route on the Flask server to enable this functionality:</p><pre># YourApp/api/routes.py<br><br># (Keep existing code and add the following)<br>@api_blueprint.route(&#39;/delete-index&#39;, methods=[&#39;POST&#39;])<br>def delete_index():<br>    pinecone_service.delete_index(PINECONE_INDEX_NAME)<br>    return jsonify({&quot;message&quot;: f&quot;Index {PINECONE_INDEX_NAME} deleted successfully&quot;})</pre><p>Now let’s finish the implementation of the delete_index function within pinecone_service.py:</p><pre># YourApp/services/pinecone_service.py<br><br># (Keep existing code and add the following)<br>def delete_index(index_name):<br>  if index_name in pinecone.list_indexes():<br>    pinecone.delete_index(name=index_name)</pre><h3>Step 3: Handling the user’s URL input</h3><p>We’re finally ready for the meat of the application: taking a URL as input from the user and getting our app ready to answer the user’s questions about the content of that webpage!</p><p>Copy the following into your UrlInput.js file:</p><pre>// src/components/UrlInput.js<br><br>import React, { useState } from &#39;react&#39;;<br><br>function UrlInput({ onSubmit }) {<br>  const [url, setUrl] = useState(&#39;&#39;);<br>  const [loading, setLoading] = useState(false);<br>  const [responseMessage, setResponseMessage] = useState(&#39;&#39;);<br><br>  const handleSubmit = async (e) =&gt; {<br>    e.preventDefault();<br>    setLoading(true);<br>    try {<br>      const response = await fetch(&#39;http://localhost:5000/embed-and-store&#39;, {<br>        method: &#39;POST&#39;,<br>        headers: {<br>          &#39;Content-Type&#39;: &#39;application/json&#39;,<br>        },<br>        body: JSON.stringify({ url }),<br>      });<br>      if (response.ok) {<br>        const data = await response.json();<br>        setResponseMessage(data.message);<br>        onSubmit();<br>      } else {<br>        setResponseMessage(&#39;Error: Something went wrong.&#39;);<br>      }<br>    } catch (error) {<br>      console.error(&#39;Error:&#39;, error);<br>      setResponseMessage(&#39;Error: Something went wrong.&#39;);<br>    } finally {<br>      setLoading(false);<br>    }<br>  };<br><br>  return (<br>    &lt;div className=&quot;urlinput&quot;&gt;<br>      &lt;form onSubmit={handleSubmit}&gt;<br>        &lt;input<br>          type=&quot;text&quot;<br>          placeholder=&quot;Enter a URL&quot;<br>          value={url}<br>          onChange={(e) =&gt; setUrl(e.target.value)}<br>          required<br>        /&gt;<br>        &lt;button type=&quot;submit&quot; disabled={loading}&gt;<br>          {loading ? &#39;Building Index...&#39; : &#39;Submit&#39;}<br>        &lt;/button&gt;<br>      &lt;/form&gt;<br>      {responseMessage &amp;&amp; &lt;p&gt;{responseMessage}&lt;/p&gt;}<br>    &lt;/div&gt;<br>  );<br>}<br><br>export default UrlInput;</pre><p>The core of the code is in the handleSubmit method. Here, we’re calling the embed-and-store endpoint on our Flask server and providing it the URL from the user. Note that in production we’ll want to handle validating the URL before we send it to the server!</p><p>Once we hit the endpoint, we’ll need to wait several seconds for the backend to scrape the url’s contents, embed them using OpenAI’s <a href="https://platform.openai.com/docs/guides/embeddings">Embeddings API</a>, and store them in a Pinecone index. The user sees a loading state until the backend finishes, at which point it calls the onSubmit function provided by App.js to display the ChatInterface.js component to the user.</p><h3>Step 4: Create the chat interface UI</h3><p>Now our chatbot is ready to take questions from the user! Copy the following into ChatInterface.js:</p><pre>// src/components/ChatInterface.js<br><br>import React, { useState, useEffect, useRef } from &#39;react&#39;;<br>import ChatMessage from &#39;./ChatMessage&#39;;<br><br>function ChatInterface() {<br>  const [messages, setMessages] = useState([]);<br>  const [inputText, setInputText] = useState(&#39;&#39;);<br>  const messagesEndRef = useRef(null);<br>  const scrollToBottom = () =&gt; {<br>    messagesEndRef.current?.scrollIntoView({ behavior: &quot;smooth&quot; });<br>  };<br><br>  useEffect(scrollToBottom, [messages]);<br><br>  const handleSendMessage = async (event) =&gt; {<br>    event.preventDefault();<br>    if (!inputText.trim()) return; // Prevent sending empty messages<br>    const userMessage = { text: inputText, isBot: false };<br>    const body = {<br>      chatHistory: [...messages, userMessage],<br>      question: inputText,<br>    }    <br>    setMessages([...messages, userMessage]);<br>    setInputText(&#39;&#39;);<br>    const response = await fetch(&#39;http://localhost:5000/handle-query&#39;, {<br>      method: &#39;POST&#39;,<br>      headers: { &#39;Content-Type&#39;: &#39;application/json&#39; },<br>      body: JSON.stringify(body),<br>    });<br>    const data = await response.json();<br>    const botMessage = { text: data.answer, isBot: true };<br>    setMessages(currentMessages =&gt; [...currentMessages, botMessage]);<br>  };<br><br>  return (<br>    &lt;div className=&quot;chat-container&quot;&gt;<br>      &lt;header className=&quot;chat-header&quot;&gt;URL Question &amp; Answer&lt;/header&gt;<br>      {<br>        messages.length === 0 <br>          &amp;&amp; <br>        &lt;div className=&quot;chat-message bot-message&quot;&gt;<br>          &lt;p className=&quot;initial-message&quot;&gt;Hi there! I&#39;m a bot trained to answer questions about the URL you entered. Try asking me a question below!&lt;/p&gt;<br>        &lt;/div&gt;<br>      }<br>      &lt;div className=&quot;chat-messages&quot;&gt;<br>        {messages.map((message, index) =&gt; (<br>          &lt;ChatMessage key={index} message={message} /&gt;<br>        ))}<br>        &lt;div ref={messagesEndRef} /&gt;<br>      &lt;/div&gt;<br>      &lt;form className=&quot;chat-input&quot; onSubmit={handleSendMessage}&gt;<br>        &lt;input<br>          type=&quot;text&quot;<br>          placeholder=&quot;Type a question and press enter ...&quot;<br>          value={inputText}<br>          onChange={(e) =&gt; setInputText(e.target.value)}<br>        /&gt;<br>      &lt;/form&gt;<br>    &lt;/div&gt;<br>  );<br>}<br><br>export default ChatInterface;</pre><p>Notice that we have a messages state variable to store the history of our chat messages (both the user’s and the bot’s). This is necessary for us to (1) display the entire chat history to the user (mimicking the ChatGPT interface, and (2) provide the entire chat history to the backend to use as part of its payload to GPT-4 (we’ll cover this in the next section).</p><p>Our handleSendMessage function fires once the user inputs a question. It hits the handle-query endpoint which does its magic (see <a href="https://shwinda.medium.com/build-a-full-stack-llm-application-with-openai-flask-react-and-pinecone-part-1-f3844429a5ef">part 1</a>) and adds the bot’s response to the messages array once it’s fully generated. This is all rendered to the front-end.</p><p>Make sure to paste the following into the ChatMessage.js file:</p><pre>// src/components/ChatMessage.js<br><br>import React from &#39;react&#39;;<br>import ReactMarkdown from &#39;react-markdown&#39;;<br><br>function ChatMessage({ message }) {<br>  // Only parse markdown for bot messages<br>  const content = message.isBot ? (<br>    &lt;ReactMarkdown children={message.text} /&gt;<br>  ) : (<br>    message.text<br>  );<br><br>  return (<br>    &lt;div className={`chat-message ${message.isBot ? &#39;bot-message&#39; : &#39;user-message&#39;}`}&gt;<br>      {content}<br>    &lt;/div&gt;<br>  );<br>}<br><br>export default ChatMessage;</pre><h4>Modifying the backend to handle the entire chat history</h4><p>In <a href="https://shwinda.medium.com/build-a-full-stack-llm-application-with-openai-flask-react-and-pinecone-part-1-f3844429a5ef">part 1</a>, we made a simple call to OpenAI’s <a href="https://platform.openai.com/docs/guides/text-generation/chat-completions-api">ChatCompletions endpoint</a> with only the current prompt to get an answer. This meant that GPT-4 didn’t have context on the entire user conversation; to give it this context, we’ll be sending the entire chat history — provided by the frontend — to the ChatCompletions endpoint:</p><pre># YourApp/services/openai_service.py<br><br>def get_llm_answer(prompt, chat_history):<br>  <br>  messages = [{&quot;role&quot;: &quot;system&quot;, &quot;content&quot;: &quot;You are a helpful assistant.&quot;}]<br>  # Pass in the entire chat history<br><br>  for message in chat_history:<br>    if message[&#39;isBot&#39;]:<br>      messages.append({&quot;role&quot;: &quot;system&quot;, &quot;content&quot;: message[&quot;text&quot;]})<br>    else:<br>      messages.append({&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: message[&quot;text&quot;]})<br><br>  # Replace last message with the full prompt<br>  messages[-1][&quot;content&quot;] = prompt<br><br>  url = &#39;https://api.openai.com/v1/chat/completions&#39;<br>  headers = {<br>      &#39;content-type&#39;: &#39;application/json; charset=utf-8&#39;,<br>      &#39;Authorization&#39;: f&quot;Bearer {OPENAI_API_KEY}&quot;            <br>  }<br>  data = {<br>      &#39;model&#39;: CHATGPT_MODEL,<br>      &#39;messages&#39;: messages,<br>      &#39;temperature&#39;: 1, <br>      &#39;max_tokens&#39;: 1000<br>  }<br>  response = requests.post(url, headers=headers, data=json.dumps(data))<br>  response_json = response.json()<br>  completion = response_json[&quot;choices&quot;][0][&quot;message&quot;][&quot;content&quot;]<br>  return completion</pre><p>Here, we’re looping through the entire chat history to populate the messages array and we send this to the model so it has context on both the conversation <em>and</em> the retrieved chunks of text.</p><h3>Step 5: Streaming the response from GPT-4</h3><p>One wrinkle in our current setup is that the frontend waits for GPT-4 to generate its entire answer before it displays this to the user. Instead of making the user wait — and to mimic the ChatGPT interface — we’ll implement <strong>streaming</strong> so the answer is displayed to the user as each token is generated.</p><h4>Modifying the backend to handle streaming</h4><p>First, let’s add a new function inside helper_functions.py in the backend. We’re now abstracting away <em>all</em> the messages-building code away from the openai_service.py file:</p><pre># YourApp/utils/helper_functions.py<br><br># (keep current code in the file and add the following)<br>def construct_messages_list(chat_history, prompt):<br>    messages = [{&quot;role&quot;: &quot;system&quot;, &quot;content&quot;: &quot;You are a helpful assistant.&quot;}]<br>    <br>    # Populate the messages array with the current chat history<br>    for message in chat_history:<br>        if message[&#39;isBot&#39;]:<br>            messages.append({&quot;role&quot;: &quot;system&quot;, &quot;content&quot;: message[&quot;text&quot;]})<br>        else:<br>            messages.append({&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: message[&quot;text&quot;]})<br>    # Replace last message with the full prompt<br>    messages[-1][&quot;content&quot;] = prompt    <br>    <br>    return messages</pre><p>Now we’ll replace the get_llm_answer function inside openai_service.py with the following. This functions handles creating the headers and data to send as part of the payload to OpenAI’s ChatCompletions endpoint:</p><pre># YourApp/services/openai_service.py<br><br># (keep current code and replace get_llm_answer with the following)<br>def construct_llm_payload(question, context_chunks, chat_history):<br>  <br>  # Build the prompt with the context chunks and user&#39;s query<br>  prompt = build_prompt(question, context_chunks)<br>  print(&quot;\n==== PROMPT ====\n&quot;)<br>  print(prompt)<br><br>  # Construct messages array to send to OpenAI<br>  messages = construct_messages_list(chat_history, prompt)<br><br>  # Construct headers including the API key<br>  headers = {<br>      &#39;content-type&#39;: &#39;application/json; charset=utf-8&#39;,<br>      &#39;Authorization&#39;: f&quot;Bearer {OPENAI_API_KEY}&quot;            <br>  }  <br><br>  # Construct data payload<br>  data = {<br>      &#39;model&#39;: CHATGPT_MODEL,<br>      &#39;messages&#39;: messages,<br>      &#39;temperature&#39;: 1, <br>      &#39;max_tokens&#39;: 1000,<br>      &#39;stream&#39;: True<br>  }<br><br>  return headers, data</pre><p>Finally, let’s replace the handle_query route logic in routes.py to handle streaming the response back to the front-end:</p><pre># YourApp/api/routes.py (entire file)<br><br>from . import api_blueprint<br>import os<br>from flask import request, jsonify, Response, stream_with_context, json<br>import requests<br>import sseclient<br>from app.services import openai_service, pinecone_service, scraping_service<br>from app.utils.helper_functions import chunk_text, build_prompt, construct_messages_list<br><br>PINECONE_INDEX_NAME = &#39;index237&#39;<br><br>@api_blueprint.route(&#39;/handle-query&#39;, methods=[&#39;POST&#39;])<br>def handle_query():<br>    question = request.json[&#39;question&#39;]<br>    chat_history = request.json[&#39;chatHistory&#39;]<br>    <br>    # Get the most similar chunks from Pinecone<br>    context_chunks = pinecone_service.get_most_similar_chunks_for_query(question, PINECONE_INDEX_NAME)<br>    <br>    # Build the payload to send to OpenAI<br>    headers, data = openai_service.construct_llm_payload(question, context_chunks, chat_history)<br><br>    # Send to OpenAI&#39;s LLM to generate a completion<br>    def generate():<br>        url = &#39;https://api.openai.com/v1/chat/completions&#39;<br>        response = requests.post(url, headers=headers, data=json.dumps(data), stream=True)<br>        client = sseclient.SSEClient(response)<br>        for event in client.events():<br>            if event.data != &#39;[DONE]&#39;:<br>                try:<br>                    text = json.loads(event.data)[&#39;choices&#39;][0][&#39;delta&#39;][&#39;content&#39;]<br>                    yield(text)<br>                except:<br>                    yield(&#39;&#39;)<br>    <br>    # Return the streamed response from the LLM to the frontend<br>    return Response(stream_with_context(generate()))<br><br>@api_blueprint.route(&#39;/embed-and-store&#39;, methods=[&#39;POST&#39;])<br>def embed_and_store():<br>    url = request.json[&#39;url&#39;]<br>    url_text = scraping_service.scrape_website(url)<br>    chunks = chunk_text(url_text)<br>    pinecone_service.embed_chunks_and_upload_to_pinecone(chunks, PINECONE_INDEX_NAME)<br>    response_json = {<br>        &quot;message&quot;: &quot;Chunks embedded and stored successfully&quot;<br>    }<br>    return jsonify(response_json)<br><br>@api_blueprint.route(&#39;/delete-index&#39;, methods=[&#39;POST&#39;])<br>def delete_index():<br>    pinecone_service.delete_index(PINECONE_INDEX_NAME)<br>    return jsonify({&quot;message&quot;: f&quot;Index {PINECONE_INDEX_NAME} deleted successfully&quot;})</pre><p>Make sure that your requirements.txt file now looks like this and re-run pip install -r requirements.txt in your terminal. This will install the sseclient library that we’ll need to handle the streaming.</p><pre># YourApp/requirements.txt<br><br>flask<br>requests<br>beautifulsoup4<br>openai<br>pinecone-client<br>flask-cors<br>python-dotenv<br>gunicorn<br>sseclient-py  # new package</pre><h4>Modify the frontend to handle streaming</h4><p>Now our backend will stream the response from GPT-4 to the frontend one token at a time! Let’s make sure to handle this in the ChatInterface.js file:</p><pre>// src/components/ChatInterface.js<br><br>// (Keep the file contents and just replace the handleSendMessage function<br><br>const handleSendMessage = async (event) =&gt; {<br>    event.preventDefault();<br><br>    if (!inputText.trim()) return; <br><br>    const userMessage = { text: inputText, isBot: false };<br>    const body = {<br>      chatHistory: [...messages, userMessage],<br>      question: inputText,<br>    }    <br><br>    // Add a new empty bot message to the UI<br>    const botMessage = { text: &#39;&#39;, isBot: true };<br>    setMessages([...messages, userMessage, botMessage]);<br>    setInputText(&#39;&#39;);<br><br>    // Send the user&#39;s message to the server and wait for a response.<br>    // This response will be streamed to this component.<br>    const response = await fetch(&#39;http://localhost:5000/handle-query&#39;, {<br>      method: &#39;POST&#39;,<br>      headers: { &#39;Content-Type&#39;: &#39;application/json&#39; },<br>      body: JSON.stringify(body),<br>    });<br>    if (!response.body) return;<br><br>    // Set up the infrastructure to stream the response data<br>    let decoder = new TextDecoderStream();<br>    const reader = response.body.pipeThrough(decoder).getReader()    <br>    let accumulatedAnswer = &quot;&quot;<br><br>    while (true) {<br>      var { value, done } = await reader.read();<br>      if (done) break;<br>      accumulatedAnswer += value;<br>      setMessages(currentHistory =&gt; {<br>        const updatedHistory = [...currentHistory]<br>        const lastChatIndex = updatedHistory.length - 1<br>        updatedHistory[lastChatIndex] = {<br>          ...updatedHistory[lastChatIndex],<br>          text: accumulatedAnswer<br>        }<br>        return updatedHistory<br>      })<br>    }<br>  };</pre><p>Here we’re using the <a href="https://developer.mozilla.org/en-US/docs/Web/API/TextDecoderStream/TextDecoderStream">TextDecoderStream</a> pattern to read the response from the backend one token at a time. As we get each token, we update the messages array with the accumulated text of the answer so the response is shown to the user one token at a time!</p><h3>Conclusion and what’s next</h3><p>We’ve built a full-stack web application with OpenAI, Pinecone, Flask, and React!</p><p><strong>To try out the full app</strong>, run python run.py in your root folder and in a separate terminal window cd into your client finder and run npm start. This should open up the web UI in a new browser tab where you can try the app out yourself!</p><p>You can find the source code for this tutorial at <a href="https://github.com/ashnkumar/llm_full_stack_tutorial/tree/part2_frontend">this branch</a> on GitHub. In the next post, we’ll set our app up for production by adding tracking and evaluation to our application to make sure we’re iterating on our prompts properly based on user feedback!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ceda4e290c33" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Build a full-stack LLM application with OpenAI, Flask, React, and Pinecone (Part 1)]]></title>
            <link>https://shwinda.medium.com/build-a-full-stack-llm-application-with-openai-flask-react-and-pinecone-part-1-f3844429a5ef?source=rss-13ca56953261------2</link>
            <guid isPermaLink="false">https://medium.com/p/f3844429a5ef</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[gpt]]></category>
            <dc:creator><![CDATA[Ashwin Kumar]]></dc:creator>
            <pubDate>Tue, 28 Nov 2023 16:23:55 GMT</pubDate>
            <atom:updated>2023-11-28T16:27:14.684Z</atom:updated>
            <content:encoded><![CDATA[<h4>Part 1: Backend and RAG with Python, OpenAI, and Pinecone</h4><p>In the rapidly evolving realm of LLMs and AI, mastering the full spectrum of application building — from back-end to front-end, including metrics — is crucial. In this tutorial series, we’ll build a production-ready application end-to-end using Flask, React, OpenAI, and Pinecone and we’ll implement the <a href="https://blogs.nvidia.com/blog/what-is-retrieval-augmented-generation/">Retrieval Augmented Generation (RAG)</a> framework to give the LLM necessary context based on information it <em>wasn’t</em> trained on.</p><h4>Posts in this series:</h4><ol><li><strong><em>Part 1 (this post): Backend and RAG with Python, OpenAI, and Pinecone</em></strong></li><li><a href="https://shwinda.medium.com/ceda4e290c33">Part 2: Front-end chat user interface with React</a></li><li>Part 3 (coming): Tracking important metrics for an LLM application</li></ol><h3>What we’re building</h3><p>In this series, our journey will take us through the creation of a simple web application that allows a user to input a URL and ask questions about the content on that webpage. You can find the source code for part 1 <a href="https://github.com/ashnkumar/llm_full_stack_tutorial/tree/part1_backend">here</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1knuUKlY9qK5bogvBpGtXQ@2x.png" /></figure><p><strong>Components of the full application:</strong></p><ul><li><strong>Backend (Flask): </strong>This handles the logic to scrape the website and call <a href="https://platform.openai.com/docs/guides/embeddings">OpenAI’s Embeddings API</a> to create embeddings from the website’s text. It also stores these embeddings in the vector database (<a href="https://www.pinecone.io/">Pinecone</a>) and retrieves relevant text to help the LLM answer the user’s question.</li><li><strong>OpenAI: </strong>We’ll call two different API’s from OpenAI: (1) the Embeddings API to embed the text of the website as well as the user’s question, and (2) the <a href="https://platform.openai.com/docs/guides/text-generation/chat-completions-api">ChatCompletions API</a> to get an answer from GPT-4 to send back to the user.</li><li><strong>Pinecone: </strong>This is the vector database that we’ll use to (1) send the embeddings of the website’s text to, and (2) retrieve the most similar text chunks for constructing the prompt to send to the LLM in step 3.</li><li><strong>Frontend (React): </strong>This is the interface that the user interacts with to input a URL and ask questions about the webpage.</li></ul><p><strong>Features of the final web app:</strong></p><ul><li><strong>URL Submission:</strong> Users can enter any website URL to initiate the process.</li><li><strong>Contextual Querying:</strong> After submitting a URL, users can ask any question related to the content of that website.</li><li><strong>Real-time Responses:</strong> The application retrieves and streams answers in real-time, ensuring a dynamic user experience.</li><li><strong>Performance Metrics:</strong> In the final stage, users can track various metrics to evaluate the LLM’s effectiveness and accuracy in handling queries.</li></ul><h3>Step 1: The Flask skeleton</h3><p>We’ll only focus on the backend (Flask / Python) for part 1 of the tutorial. First we’ll set up our dev environment, build our Flask skeleton, and establish routes to expose to the frontend. You can find the source code for on <a href="https://github.com/ashnkumar/llm_full_stack_tutorial/tree/part1_backend">GitHub</a>.</p><h4>Setting up the development environment</h4><p>First, let’s set up a virtual environment and install all requirements for the application. Run the following commands in your terminal.</p><pre># Create the project directory and enter it<br>mkdir YourApp<br>cd ./YourApp<br><br># Create and activate a virtual environment<br># if virtualenv isn&#39;t installed, install it using<br># pip install virtualenv<br>python -m venv venv<br>source venv/bin/activate<br><br># Install dependencies from requirements.txt<br># Make sure you have a requirements.txt file in your project directory<br># See Github repository here: &lt;URL&gt; for the file<br>pip install -r requirements.txt</pre><h4>Build Flask skeleton</h4><p>Now let’s set up the folder structure as follows. This neatly separates the code to make it easier to maintain.</p><pre>/YourApp<br>    /app<br>        __init__.py<br>        /api<br>            __init__.py<br>            routes.py<br>        /services<br>            __init__.py<br>            openai_service.py<br>            pinecone_service.py<br>            scraping_service.py<br>        /utils<br>            __init__.py<br>            helper_functions.py<br>    .env<br>    .gitignore<br>    requirements.txt<br>    run.py</pre><p>See the contents of the run.py and requirements.txt and __init__ files in the <a href="https://github.com/ashnkumar/llm_full_stack_tutorial/tree/part1_backend">GitHub source code</a> and copy them into the relevant files. We’ll be writing the code for the other files throughout the course of this tutorial.</p><h4>Set up the .env file</h4><p>We’re going to store our API keys for OpenAI and Pinecone in an .env file. Create this file in the root of your directory and make sure to replace the placeholders with your actual API keys. You can sign up for OpenAI and get your key <a href="https://auth0.openai.com/u/signup/identifier?state=hKFo2SBaV05BSlpzcTI5N2psMjRtZWQyNndjXzliT0NGb3RfdaFur3VuaXZlcnNhbC1sb2dpbqN0aWTZIFJjQ3lhMTBxcE1yTnFlcnlMYjNOOUlIS05RcS1tLUpko2NpZNkgRFJpdnNubTJNdTQyVDNLT3BxZHR3QjNOWXZpSFl6d0Q">here</a>. And <a href="https://login.pinecone.io/login?state=hKFo2SBKNWo1Njk0U1d4ZzlYZkZpUGxQbFZxN1pGektZSGZhbKFupWxvZ2luo3RpZNkgalZnY2VQdFFWS3hfZV85YmZGZ2twRll1b1p6MkRNWHGjY2lk2SBUOEkyaEc2Q2FaazUwT05McWhmN3h6a1I0WmhMcVM0Qw&amp;client=T8I2hG6CaZk50ONLqhf7xzkR4ZhLqS4C&amp;protocol=oauth2&amp;audience=https%3A%2F%2Fblue-sea-697d.quartiers047.workers.dev%3A443%2Fhttps%2Fus-central1-production-console.cloudfunctions.net%2Fapi%2Fv1&amp;scope=openid%20profile%20email%20read%3Acurrent_user&amp;redirect_uri=https%3A%2F%2Fblue-sea-697d.quartiers047.workers.dev%3A443%2Fhttps%2Fapp.pinecone.io&amp;sessionType=signup&amp;response_type=code&amp;response_mode=query&amp;nonce=U3FUeTlrQnZQNFd0bXFFNWNYaVIwcUlIa1hOWGxmcDlkT0JYdkdJUnFuQQ%3D%3D&amp;code_challenge=hZ0OTu1HVhGxagjNsPkwIapRtZt2T4vlU4olxFOtbsk&amp;code_challenge_method=S256&amp;auth0Client=eyJuYW1lIjoiYXV0aDAtcmVhY3QiLCJ2ZXJzaW9uIjoiMS41LjAifQ%3D%3D">here’s</a> the same for Pinecone.</p><pre># YourApp/.env<br><br>OPENAI_API_KEY=&lt;YOUR_OPENAI_KEY&gt;<br>PINECONE_API_KEY=&lt;YOUR_PINECONE_KEY&gt;</pre><h4>Create REST routes for the application</h4><p>There are 2 routes for the React frontend to hit on our backend: (1) embed_and_store which handles the first phase of creating embeddings in Pinecone, and handle_query which gets an answer to the user’s questions.</p><p><em>🚨 Remember to create and populate the </em><em>run.py and </em><em>requirements.txt and </em><em>__init__ files in the GitHub </em><a href="https://github.com/ashnkumar/llm_full_stack_tutorial/tree/part1_backend"><em>source code</em></a><em>. Once populated, run </em><em>pip install -r requirements.txt to install all requirements.</em></p><pre># YourApp/api/routes.py<br><br>from . import api_blueprint<br><br>@api_blueprint.route(&#39;/embed-and-store&#39;, methods=[&#39;POST&#39;])<br>def embed_and_store():<br>  # handles scraping the URL, embedding the texts, and<br>  # uploading to the vector database.<br>  pass<br><br>@api_blueprint.route(&#39;/handle-query&#39;, methods=[&#39;POST&#39;])<br>def handle_query():<br>  # handles embedding the user&#39;s question,<br>  # finding relevant context from the vector database,<br>  # building the prompt for the LLM,<br>  # and sending the prompt to the LLM&#39;s API to get an answer.<br>  pass</pre><h3>Step 2: Embeddings and vector DB (Pinecone)</h3><p>Now that we have our basic backend skeleton in place, let’s build out the initial flow when the frontend provides the URL to the backend.</p><h4>Scraping the website using BeautifulSoup</h4><p>We’ll use the excellent <a href="https://pypi.org/project/beautifulsoup4/">BeautifulSoup</a> library to scrape the URL and retrieve the text contents of the page.</p><pre># YourApp/services/scraping_service.py<br><br>import requests<br>from bs4 import BeautifulSoup<br><br>def scrape_website(url):<br>    response = requests.get(url)<br>    soup = BeautifulSoup(response.content, &#39;html.parser&#39;)<br>    text = soup.get_text(separator=&#39;\n&#39;)<br>    return text</pre><h4>Chunk the text, create embeddings, and upload to Pinecone</h4><p>We want to split the text into chunks. This way we can create embeddings for each chunk and only retrieve the most relevant chunks of text from the vector DB when the user asks a question. Embeddings are critical for the RAG framework to work; read more about embeddings <a href="https://platform.openai.com/docs/guides/embeddings/what-are-embeddings">here</a>.</p><p>First, let’s create the chunk_text function in our helper_functions.py file.</p><pre># YourApp/utils/helper_functions.py<br><br>def chunk_text(text, chunk_size=200):<br>    # Split the text by sentences to avoid breaking in the middle of a sentence<br>    sentences = text.split(&#39;. &#39;)<br>    chunks = []<br>    current_chunk = &quot;&quot;<br>    for sentence in sentences:<br>        # Check if adding the next sentence exceeds the chunk size<br>        if len(current_chunk) + len(sentence) &lt;= chunk_size:<br>            current_chunk += sentence + &#39;. &#39;<br>        else:<br>            # If the chunk reaches the desired size, add it to the chunks list<br>            chunks.append(current_chunk)<br>            current_chunk = sentence + &#39;. &#39;<br>    # Add the last chunk if it&#39;s not empty<br>    if current_chunk:<br>        chunks.append(current_chunk)<br>    return chunks</pre><p>Now let’s build the function to get embeddings for a given chunk given OpenAI. These are what we’ll store in the vector database, along with the text for that chunk.</p><pre># YourApp/services/openai_service.py<br><br>import os<br>import json<br>import requests<br>from openai import OpenAI<br><br>OPENAI_API_KEY = os.environ.get(&#39;OPENAI_API_KEY&#39;)<br>OPENAI_EMBEDDING_MODEL = &#39;text-embedding-ada-002&#39;<br><br>def get_embedding(chunk):<br>  url = &#39;https://api.openai.com/v1/embeddings&#39;<br>  headers = {<br>      &#39;content-type&#39;: &#39;application/json; charset=utf-8&#39;,<br>      &#39;Authorization&#39;: f&quot;Bearer {OPENAI_API_KEY}&quot;            <br>  }<br>  data = {<br>      &#39;model&#39;: OPENAI_EMBEDDING_MODEL,<br>      &#39;input&#39;: chunk<br>  }<br>  response = requests.post(url, headers=headers, data=json.dumps(data))  <br>  response_json = response.json()<br>  embedding = response_json[&quot;data&quot;][0][&quot;embedding&quot;]<br>  return embedding</pre><p>Next, we’ll build the function to embed all these chunks and upload these embeddings to a vector database (Pinecone).</p><pre># YourApp/services/pinecone_service.py<br><br>import pinecone<br>from app.services.openai_service import get_embedding<br>import os<br><br>PINECONE_API_KEY = os.environ.get(&#39;PINECONE_API_KEY&#39;)<br><br># make sure to enter your actual Pinecone environment<br>pinecone.init(api_key=PINECONE_API_KEY, environment=&#39;gcp-starter&#39;) <br><br>EMBEDDING_DIMENSION = 1536<br><br>def embed_chunks_and_upload_to_pinecone(chunks, index_name):<br>    <br>    # delete the index if it already exists. <br>    # as Pinecone&#39;s free plan only allows one index<br>    if index_name in pinecone.list_indexes():<br>        pinecone.delete_index(name=index_name)<br>    <br>    # create a new index in Pinecone<br>    # the EMBEDDING_DIMENSION is based on what the<br>    # OpenAI embedding model outputs<br>    pinecone.create_index(name=index_name,<br>                          dimension=EMBEDDING_DIMENSION, metric=&#39;cosine&#39;)<br>    index = pinecone.Index(index_name)<br>    # embed each chunk and aggregate these embeddings<br>    embeddings_with_ids = []<br>    for i, chunk in enumerate(chunks):<br>        embedding = get_embedding(chunk)<br>        embeddings_with_ids.append((str(i), embedding, chunk))<br>    # upload the embeddings and relevant texts for each chunk<br>    # to the Pinecone index<br>    upserts = [(id, vec, {&quot;chunk_text&quot;: text}) for id, vec, text in embeddings_with_ids]<br>    index.upsert(vectors=upserts)</pre><p>That’s it! Our application can now handle scraping the website, creating text chunks from the content of the website, embedding these chunks, and uploading them to the vector database. Let’s put it all together in the embed_and_store route.</p><pre># Updated &quot;YourApp/api/routes.py&quot;<br><br>from . import api_blueprint<br>from flask import request, jsonify<br>from app.services import openai_service, pinecone_service, scraping_service<br>from app.utils.helper_functions import chunk_text<br><br># Sample index name since we&#39;re only creating a single index<br>PINECONE_INDEX_NAME = &#39;index237&#39;<br><br>@api_blueprint.route(&#39;/embed-and-store&#39;, methods=[&#39;POST&#39;])<br>def embed_and_store():<br>    url = request.json[&#39;url&#39;]<br>    url_text = scraping_service.scrape_website(url)<br>    chunks = chunk_text(url_text)<br>    pinecone_service.embed_chunks_and_upload_to_pinecone(chunks, PINECONE_INDEX_NAME)<br>    response_json = {<br>        &quot;message&quot;: &quot;Chunks embedded and stored successfully&quot;<br>    }<br>    return jsonify(response_json)<br><br>@api_blueprint.route(&#39;/handle-query&#39;, methods=[&#39;POST&#39;])<br>def handle_query():<br>  # handles embedding the user&#39;s question,<br>  # finding relevant context from the vector database,<br>  # building the prompt for the LLM,<br>  # and sending the prompt to the LLM&#39;s API to get an answer.<br>  pass</pre><h3>Step 3: RAG, prompt construction, and GPT-4</h3><p>Now that we’ve completed the first phase of our flow, let’s move onto the next phase when the user asks a question in the chat interface about the website.</p><h4>Retrieve context from the vector database</h4><p>Assuming the handle_query endpoint receives a url as part of it request payload, let’s first find the relevant chunks of context to provide to the LLM to help answer the question. This is the bulk of the work to implement the RAG framework — you can read a lot more about RAG <a href="https://blogs.nvidia.com/blog/what-is-retrieval-augmented-generation/">here</a>.</p><pre># YourApp/services/pinecone_service.py<br><br># ... leave the rest of the file unchanged<br># and add the following.<br><br>def get_most_similar_chunks_for_query(query, index_name):<br>    question_embedding = get_embedding(query)<br>    index = pinecone.Index(index_name)<br>    query_results = index.query(question_embedding, top_k=3, include_metadata=True)<br>    context_chunks = [x[&#39;metadata&#39;][&#39;chunk_text&#39;] for x in query_results[&#39;matches&#39;]]<br>    return context_chunks</pre><p>Here’s what’s going on in this code:</p><ol><li>First, we embed the question through OpenAI’s embedding model using the same get_embedding function that we’ve used before.</li><li>Then we query our Pinecone vector database that we created in Step 2 to find the top 3 chunks of text that are most similar to the embedded question from step 1. This is done through a cosine similarity algorithm.</li><li>The function returns the <em>texts</em> of those chunks as a list.</li></ol><h4>Build the prompt for the LLM using this context</h4><p>Now comes the fun part, commonly referred to as prompt engineering. We’re going to combine the user’s question, the relevant context, and some instructions for the LLM into a single text prompt.</p><pre># YourApp/utils/helper_functions.py<br><br># add this to the top of the file:<br>PROMPT_LIMIT = 3750<br><br># ... keep all the current content of the file<br><br># and add the following code<br>def build_prompt(query, context_chunks):<br><br>    # create the start and end of the prompt<br>    prompt_start = (<br>        &quot;Answer the question based on the context below. If you don&#39;t know the answer based on the context provided below, just respond with &#39;I don&#39;t know&#39; instead of making up an answer. Return just the answer to the question, don&#39;t add anything else. Don&#39;t start your response with the word &#39;Answer:&#39;. Make sure your response is in markdown format\n\n&quot;+<br>        &quot;Context:\n&quot;<br>    )<br>    prompt_end = (<br>        f&quot;\n\nQuestion: {query}\nAnswer:&quot;<br>    )<br><br>    # append context chunks until we hit the <br>    # limit of tokens we want to send to the prompt.   <br>    prompt = &quot;&quot;<br>    for i in range(1, len(context_chunks)):<br>        if len(&quot;\n\n---\n\n&quot;.join(context_chunks[:i])) &gt;= PROMPT_LIMIT:<br>            prompt = (<br>                prompt_start +<br>                &quot;\n\n---\n\n&quot;.join(context_chunks[:i-1]) +<br>                prompt_end<br>            )<br>            break<br>        elif i == len(context_chunks)-1:<br>            prompt = (<br>                prompt_start +<br>                &quot;\n\n---\n\n&quot;.join(context_chunks) +<br>                prompt_end<br>            )<br>    return prompt</pre><p>Now we have a full prompt that includes:</p><ol><li>Instructions for the LLM</li><li>Context to help the LLM answer the question</li><li>The user’s question itself</li></ol><h4>Getting an answer from the LLM (GPT-4)</h4><p>Now comes the part we’ve been waiting for: we’re going to provide the prompt to the LLM (OpenAI’s GPT-4) and get back the answer to the user’s question to display in the front-end!</p><pre># YourApp/services/openai_service.py<br><br># add this to the top of the file under the imports<br>CHATGPT_MODEL = &#39;gpt-4-1106-preview&#39;<br><br># ... keep the rest of the file unchanged<br># and add the following code:<br><br>def get_llm_answer(prompt):<br>  # Aggregate a messages array to send to the LLM<br>  messages = [{&quot;role&quot;: &quot;system&quot;, &quot;content&quot;: &quot;You are a helpful assistant.&quot;}]<br>  messages.append({&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: prompt})<br>  # Send the payload to the LLM to retrieve an answer<br>  url = &#39;https://api.openai.com/v1/chat/completions&#39;<br>  headers = {<br>      &#39;content-type&#39;: &#39;application/json; charset=utf-8&#39;,<br>      &#39;Authorization&#39;: f&quot;Bearer {OPENAI_API_KEY}&quot;            <br>  }<br>  data = {<br>      &#39;model&#39;: CHATGPT_MODEL,<br>      &#39;messages&#39;: messages,<br>      &#39;temperature&#39;: 1, <br>      &#39;max_tokens&#39;: 1000<br>  }<br>  response = requests.post(url, headers=headers, data=json.dumps(data))<br>  <br>  # return the final answer<br>  response_json = response.json()<br>  completion = response_json[&quot;choices&quot;][0][&quot;message&quot;][&quot;content&quot;]<br>  return completion</pre><p>Here’s what’s going on in this code:</p><ol><li>First, we create a messages array to send to the LLM as part of our request. Since we’re using the ChatCompletions API, we’ll need to treat this as if we’re sending a list of chat conversations even though we only have one question we need answered. This becomes important when we want to provide the entire chat history to the LLM (this will be covered in later tutorials).</li><li>Then we send this payload, including the messages of the constructed prompt, to the ChatCompletions API from OpenAI.</li><li>We get back a text response from the LLM with the answer to the question.</li></ol><p>That’s it! Putting it all together, here’s our completeroutes.py file:</p><pre># Updated &quot;YourApp/api/routes.py&quot;<br><br>from . import api_blueprint<br>from flask import request, jsonify<br>from app.services import openai_service, pinecone_service, scraping_service<br>from app.utils.helper_functions import chunk_text, build_prompt<br><br>PINECONE_INDEX_NAME = &#39;index237&#39;<br><br>@api_blueprint.route(&#39;/handle-query&#39;, methods=[&#39;POST&#39;])<br>def handle_query():<br>    question = request.json[&#39;question&#39;]<br>    context_chunks = pinecone_service.get_most_similar_chunks_for_query(question, PINECONE_INDEX_NAME)<br>    prompt = build_prompt(question, context_chunks)<br>    answer = openai_service.get_llm_answer(prompt)<br>    return jsonify({ &quot;question&quot;: question, &quot;answer&quot;: answer })    <br><br>@api_blueprint.route(&#39;/embed-and-store&#39;, methods=[&#39;POST&#39;])<br>def embed_and_store():<br>    url = request.json[&#39;url&#39;]<br>    url_text = scraping_service.scrape_website(url)<br>    chunks = chunk_text(url_text)<br>    pinecone_service.embed_chunks_and_upload_to_pinecone(chunks, PINECONE_INDEX_NAME)<br>    response_json = {<br>        &quot;message&quot;: &quot;Chunks embedded and stored successfully&quot;<br>    }<br>    return jsonify(response_json)</pre><h3>Test the implementation using cURL</h3><p>To make sure everything is working properly, let’s start the server locally and test that these endpoints work properly. We’ll be using a sample URL to test out the application (<a href="https://dev.to/bobur/how-to-build-a-custom-gpt-enabled-full-stack-app-for-real-time-data-38k8">https://dev.to/bobur/how-to-build-a-custom-gpt-enabled-full-stack-app-for-real-time-data-38k8</a>)</p><p>In a terminal window at the root of your application directory, run the python run.py command to start the server.</p><p>Now let’s test the embed_and_store endpoint. Open a new terminal window and perform the following command:</p><pre>curl -X POST http://localhost:5000/embed-and-store \<br>     -H &quot;Content-Type: application/json&quot; \<br>     -d &#39;{&quot;url&quot;:&quot;https://dev.to/bobur/how-to-build-a-custom-gpt-enabled-full-stack-app-for-real-time-data-38k8&quot;}&#39;<br><br><br># ... after a few seconds, you should see this in the terminal:<br>{<br>  &quot;message&quot;: &quot;Chunks embedded and stored successfully&quot;<br>}</pre><p>We have our vector store populated! Now let’s try asking a question using the handle-query endpoint:</p><pre>curl -X POST http://localhost:5000/handle-query \<br>     -H &quot;Content-Type: application/json&quot; \<br>     -d &#39;{&quot;question&quot;:&quot;Why do we provide ChatGPT with a custom knowledge base?&quot;}&#39;<br><br><br># ... after a few seconds, you should see this:<br>{<br>  &quot;answer&quot;: &quot;To enhance its ability to deliver more accurate and context-specific information in its responses, which is particularly useful for specialized applications such as the sample app designed for finding real-time discount prices.&quot;,<br>  &quot;question&quot;: &quot;Why do we provide ChatGPT with a custom knowledge base?&quot;<br>}</pre><h3>Conclusion and what’s next</h3><p>Our backend works! So far in this tutorial, we’ve implemented the following:</p><ul><li><strong>Backend (Flask): </strong>We set up the entire backend for the web application. This handles the tasks below.</li><li><strong>Scrape, embed, and store vectors: </strong>We used OpenAI’s Embeddings API to embed the contents of a given website (in chunks) and store them in the Pinecone vector database.</li><li><strong>RAG: </strong>When the user asks a question, our backend finds the most relevant context chunks from the vector database, builds a prompt, and gets an answer from an LLM (OpenAI’s GPT-4).</li></ul><p>You can find the source code for this tutorial at <a href="https://github.com/ashnkumar/llm_full_stack_tutorial/tree/part1_backend">this branch</a> on GitHub. In the next post, we’ll build the React frontend to interact with the backend we’ve built here. We’ll also learn how to stream responses from the LLM to the user and incorporate the entire chat history to send to the LLM.</p><p>See part 2 of this tutorial (frontend) <a href="https://shwinda.medium.com/ceda4e290c33">here</a>!</p><p>See the part 2 post here!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f3844429a5ef" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Shining a Light in the Darkness: How We Built Mental Health Hero, a Graph-Based Solution to Tackle…]]></title>
            <link>https://shwinda.medium.com/shining-a-light-in-the-darkness-how-we-built-mental-health-hero-a-graph-based-solution-to-tackle-7ba91af7c705?source=rss-13ca56953261------2</link>
            <guid isPermaLink="false">https://medium.com/p/7ba91af7c705</guid>
            <dc:creator><![CDATA[Ashwin Kumar]]></dc:creator>
            <pubDate>Tue, 01 Nov 2022 17:17:12 GMT</pubDate>
            <atom:updated>2022-11-01T17:17:12.635Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>Shining a Light in the Darkness: How We Built Mental Health Hero, a Graph-Based Solution to Tackle the Global Mental Health Epidemic</strong></h3><p><a href="https://www.theguardian.com/society/2022/jun/28/warnings-of-mental-health-crisis-among-covid-generation-of-students">“Warnings of Mental Health Crisis Among ‘Covid Generation’ of Students”</a></p><p><a href="https://abcnews.go.com/US/video/recession-impact-americans-mental-health-85807464">“How Recession Could Impact Americans’ Mental Health”</a></p><p><a href="https://thehill.com/changing-america/well-being/mental-health/3538130-how-will-the-roe-v-wade-overturn-impact-americans-mental-health/">“How Will the Roe v. Wade Overturn Impact Americans’ Mental Health?”</a></p><p>The recent headlines don’t lie, and neither do the statistics.<a href="https://www.nami.org/mhstats"> One in five U.S. adults</a> experience mental illness each year. Among those, less than half (46 percent) of adults with mental illness received treatment in 2020. And the pandemic has triggered a<a href="https://www.who.int/news/item/02-03-2022-covid-19-pandemic-triggers-25-increase-in-prevalence-of-anxiety-and-depression-worldwide"> 25 percent increase in the prevalence of anxiety and depression worldwide</a>, according to the World Health Organization.</p><p>The ongoing COVID-19 pandemic, global instability, and recession worries underscore that we are in the midst of a global mental health crisis. In fact, we consider mental health one of the largest (untreated) public health epidemics of modern times. We created “Mental Health Hero” to help healthcare organizations, therapists, and providers reach, diagnose, and support those in need.</p><p>The project began as an entry for TigerGraph’s<a href="https://www.tigergraph.com/graph-for-all/winners/grand-prize/"> Graph for All Million Dollar Challenge</a> contest, and has taken on a life of its own — as we have since started reaching out to healthcare organizations and public health officials. Here is a closer look at how we applied the power of graph technology to tackle a problem many call “the silent killer” — untreated mental health issues.</p><h3><strong><em>Bridging the Gap Between Patients and Mental Health Services with Graph</em></strong></h3><p>For a critical background on the state of mental health, we spoke with 10 psychologists who identified three primary barriers between people and the mental health services they need: finding the right treatment, being able to afford the cost of care, and managing the stigma associated with mental health issues.</p><p>We learned that obtaining a holistic view of a potential patient from a variety of different touch points would better help patients identify the appropriate mental health treatment. We were also reminded that the current approaches — which include everything from chatbots and mood trackers to crisis hotlines — are great steps toward <em>providing</em> care, but don’t help patients <em>choose</em> what care to pursue in the first place. Our aim was to build a solution that would address the care accessibility issue further upstream; our project would provide an accurate, holistic view of a patient so that the provider could easily recommend the right treatment (e.g. medication or a specific type of therapy).</p><p><em>How would we do this?</em> We knew that we needed to focus on the relationships of many variables to provide a full portrait; graph technology was ideal to achieve our project goal. We used graph databases to create a 360-degree view of a person from multiple modalities such as social media sentiment, therapy session attendance, and written entries. From here, we can recommend the best treatment based on what worked for similar people (much like how companies use graph to recommend products to similar customers).</p><p>A word about graph: Graph analytics is able to explore and analyze data across many disparate platforms, entities, and siloes. Think of graph technology as an engine that allows you to ask and answer specific<strong> </strong>questions with complex data, in real time, at scale.</p><h3><strong><em>Analyzing Relationships to Build a 360-Degree Patient View</em></strong></h3><p>We used graph to build our Patient 360 view of a potential mental health patient using social media sentiment (such as an “I couldn’t make it to the gym, rough day” tweet), adherence to scheduled therapy sessions, and written entries. We based our Patient 360 solution on the Customer 360 model. After building this 360-degree view of a potential patient, we use similarity algorithms to identify which treatments to recommend based on what has worked well for similar patients.</p><p>Connected data yields connected insights — and graph analytics is able to explore and analyze data across several different touchpoints, highlighting complex relationships and patterns. Then, we used similarity algorithms to recommend care based on the outcomes of other patients with similar behaviors.</p><p>Many different stakeholders in the mental health industry can use this base similarity algorithm in their work: therapists can adjust care plans for their patients, insurance companies can see who needs preventative help from their customer base, and governments can develop public health programs to deliver needed care.</p><p>Meanwhile, for the purpose of finding data for our project, we needed to work with the fact that mental health data isn’t readily accessible. To address this issue, we took existing disparate datasets for Twitter sentiment analysis and depression scale scores and built a semi-synthesized dataset to show what’s possible with our application. We would expect healthcare systems to have the actual data available to deploy Mental Health Hero at scale.</p><h3><strong><em>Mental Health Hero: In the Field and Beyond…</em></strong></h3><p>We designed<a href="https://mental-health-hero.herokuapp.com/"> Mental Health Hero</a> so that it can be easily deployed by healthcare organizations, public health centers, psychologists, digital health companies, health insurers, and more. The application is also flexible enough so that users can add new data to the holistic patient view (accelerometer data, prescription information, etc.). Mental Health Hero has the potential to help hundreds of millions of people around the world.</p><p>Our big goal is to see Mental Health Hero deployed around the globe. So far, we have reached out to multiple healthcare facilities that could be considering running a real-world pilot with actual patient data. We’ve also started reaching out to government agencies and are listening to their feedback about the application. The global mental health crisis is one with no singular solution, but we like to think our application will make a difference by connecting more people with the treatment, therapies, and support they need.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7ba91af7c705" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Stripe’s embedded finance products are a gamechanger for startup founders]]></title>
            <link>https://shwinda.medium.com/stripes-embedded-finance-products-are-a-gamechanger-for-startup-founders-5fab72ad2438?source=rss-13ca56953261------2</link>
            <guid isPermaLink="false">https://medium.com/p/5fab72ad2438</guid>
            <category><![CDATA[stripe]]></category>
            <category><![CDATA[fintech]]></category>
            <category><![CDATA[startup]]></category>
            <category><![CDATA[technology]]></category>
            <dc:creator><![CDATA[Ashwin Kumar]]></dc:creator>
            <pubDate>Fri, 09 Jul 2021 16:17:20 GMT</pubDate>
            <atom:updated>2021-07-09T16:17:20.904Z</atom:updated>
            <content:encoded><![CDATA[<p>The “AWS of fintech” is finally here</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OMWflievxVRgQ7doJRNCJg.gif" /></figure><p>In 2015, my cofounder and I built an ML-enabled <a href="https://venturebeat.com/2016/08/15/sway-finance-is-an-accounting-slack-bot-for-saas-companies/"><strong>accounting startup</strong></a><strong>. </strong>There was no <strong><em>“AWS of fintech”</em></strong> back then, and we faced friction at <em>every step:</em> integrating with our customers’ revenue pipelines, bank accounts, and credit card transactions. Getting a fintech company off the ground was <em>brutal.</em></p><p><strong>But in the past few months, that’s all changed! </strong>At their Sessions conference last month, <a href="https://stripe.com/"><strong>Stripe</strong></a> detailed their <strong>embedded finance</strong> products, which are a <em>complete gamechanger</em> for startup founders.</p><blockquote><strong><em>Stripe’s new tools have </em>greatly<em> expanded the scope of startups that can be built, and founders need to pay attention.</em></strong></blockquote><h3>Stripe’s building blocks</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZRY6p0jgweif9o5i7Je5QQ.png" /><figcaption>A small sampling of Stripe’s <a href="https://stripe.com/docs/products">growing product suite</a>.</figcaption></figure><p>Most startup founders think of Stripe as a “way to take payments”, but their recent products are moving toward something much larger: <strong>creating the infrastructure for your company to offer financial services to <em>your</em> customers.</strong></p><h3>Patrick Collison on Twitter: &quot;Mundane though it sounds, access to capital is the primary bottleneck that limits the growth and expansion of most small businesses.So we built Capital for platforms: https://t.co/3BvZhCz9Bo. Help *your* customers grow faster by using our lending infrastructure. pic.twitter.com/z7xxfM9GFD / Twitter&quot;</h3><p>Mundane though it sounds, access to capital is the primary bottleneck that limits the growth and expansion of most small businesses.So we built Capital for platforms: https://t.co/3BvZhCz9Bo. Help *your* customers grow faster by using our lending infrastructure. pic.twitter.com/z7xxfM9GFD</p><p><strong>This is critical. </strong>Before, if your startup wanted to offer financial services to your customers, you’d have to:</p><ul><li><strong>Build your own bank</strong> <strong>relationships</strong> before you could offer your customers a way to hold or transfer funds through your product.</li><li><strong>Underwrite your own loans</strong> and build in complex compliance mechanisms before you could offer a loan through your platform.</li><li><strong>Set up contracts with card issuing companies</strong> before you could launch a debit/credit card for your customers.</li></ul><p>With Stripe’s embedded finance products, you can:</p><ul><li><strong>Create instant bank accounts</strong> for your customers through <a href="https://stripe.com/treasury"><strong>Treasury</strong></a><strong>. </strong>Since Stripe maintains relationships with the banks on the back-end, your startup wouldn’t need to.</li><li><strong>Immediately offer business loans</strong> to your customers through <a href="https://stripe.com/capital/platforms"><strong>Capital for Platforms</strong></a><strong>. </strong>Stripe handles compliance, underwriting, issuing of the loan, and even absorbs the credit risk.</li><li><strong>Let your customers create cards</strong> off the bat with <a href="https://stripe.com/issuing"><strong>Issuing</strong></a><strong>. </strong>Stripe handles the creation of the cards (both virtual and physical), and you can build in code to customize the card behavior for your customers.</li></ul><p><strong>Now you can see why these embedded finance products are so exciting!</strong> As a startup founder, you can piece together these building blocks to build financial-enabled products in a <em>fraction</em> of the time it would have taken before.</p><h3>Startups that you can quickly build</h3><h3>🛍 The Shopify for X</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*_Q_epa0vN8SqZUMv.png" /></figure><p><a href="https://www.shopify.com/"><strong>Shopify</strong></a> is a general-purpose e-commerce platform that lets anyone easily create an online store, market products, take payments, and borrow capital.</p><p>But what if you’re targeting a market that has very specific needs that Shopify doesn’t address? Now you can quickly build a Shopify-like product tailored to your market vertical:</p><blockquote><strong><em>👩🏽‍💼 Your secret sauce<br></em></strong><em>You focus on making the most easy-to-use store building tools for your market niche, along with a simple onboarding flow and quick-start templates.</em></blockquote><blockquote><strong><em>— — — — — — — — <br>🔀 Stripe Connect<br></em></strong><em>You add in Stripe Connect so your customers can start charging for their products.</em></blockquote><blockquote><em>🏦 </em><strong><em>Stripe Treasury<br></em></strong><em>You create bank-like accounts for your customers when they sign up, so they can store and access their funds, and pay their vendors’ bills through ACH.</em></blockquote><blockquote><em>📈 </em><strong><em>Stripe Capital<br></em></strong><em>By measuring your customers’ sales (through </em><strong><em>Connect</em></strong><em>) and cash reserves (through </em><strong><em>Treasury</em></strong><em>), Stripe Capital lets you issue financing to your customers, and earn revenue on each loan extended — in addition to your core SaaS revenue.</em></blockquote><h3>📈 Quickbooks for X</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*H0PR_mHJ-LdfuvpP.png" /></figure><p><a href="https://quickbooks.intuit.com/"><strong>QuickBooks</strong></a> creates general-purpose accounting software for small businesses, and I can tell you from experience that companies — especially internet-native ones — have drastically different accounting needs.</p><p>Here’s how you could create a QuickBooks for a specific industry vertical:</p><blockquote><strong><em>👩🏽‍💼 Your secret sauce<br></em></strong><em>You focus on creating an intuitive accounting interface, with code to handle your market’s unique bookeeping needs like revenue recognition and depreciation.</em></blockquote><blockquote><strong><em>— — — — — — — — <br>🔀 Stripe Connect<br></em></strong><em>Set your customers up with Stripe for payments, so you can use Connect to pull in and categorize their revenue flow while reconciling their received payments with outstanding invoices in your accounting backend.</em></blockquote><blockquote><em>🏦 </em><strong><em>Stripe Treasury<br></em></strong><em>Set your customers up with a Treasury account. Now you can easily account for their bill payments and payroll outflow, while reconciling cash flows with their accounts payables and receivables.</em></blockquote><blockquote><em>💳 </em><strong><em>Stripe Issuing<br></em></strong><em>Use Issuing to let your customers create expense cards for their employees. Now instead of constantly asking your customers what a specific charge was, you can use the geolocation of the transaction to help categorize it in your software.</em></blockquote><h3>🏦 Clearbanc for X</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*umLkqlYJPwUw7LGN.png" /></figure><p><a href="https://clear.co/"><strong>Clearbanc</strong></a> extends growth capital to startups in the form of merchant cash advances, with fees that depend on how the capital is used (e.g. marketing-spend).</p><p>Business lending is a <em>massive</em> market, but by focusing on a specific vertical (like <a href="https://www.trykarat.com/"><strong>Karat</strong></a> for creators), you can build a lending startup and tailor your loans, rewards, and repayment structures for your market niche.</p><blockquote><strong><em>👩🏽‍💼 Your secret sauce<br></em></strong><em>You focus on building the analytics tools to help your customers understand their revenue flow, and the interface to let them apply for a loan. You can also decide a fee structure based on how they are spending the capital.</em></blockquote><blockquote><strong><em>— — — — — — — — <br></em></strong><em>💳 </em><strong><em>Stripe Issuing<br></em></strong><em>Set up your customers with cards through Stripe Issuing when they get approved for the loan, so you can set programmatic controls on how they spend the money.</em></blockquote><blockquote><em>📈 </em><strong><em>Stripe Capital<br></em></strong><em>Integrate with Stripe Capital to build your lending flow. Since Stripe handles the compliance, credit risk assessment, and loan disbursements, you can focus instead on building tools to help your customers </em>use<em> those funds in a way that provides them the highest ROI.</em></blockquote><blockquote><strong><em>🔀 Stripe Connect<br></em></strong><em>Onboard your customers to Stripe Connect, and let Stripe handle disbursement of the funds and collecting repayment. This also lets you access their revenue flow to build your core analytics product.</em></blockquote><h3>🚀 The next level of fintech</h3><p>Now you see why Stripe’s new products are so exciting for startup founders: they take complex financial infrastructure and expose them to entrepreneurs as tools to build with, similar to <a href="https://www.forbes.com/sites/forbestechcouncil/2019/08/27/how-cloud-computing-is-democratizing-development-and-accelerating-innovation/"><strong>AWS</strong></a> democratizing access to the cloud, or <a href="https://www.tensorflow.org/"><strong>TensorFlow</strong></a> simplifying the process of integrating machine learning into new products.</p><p><strong>The door has just blown wide open for new startups</strong> that can be built on these primitives, and I’m excited to see how founders piece them together to create completely new products and business models!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5fab72ad2438" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Nail Your Startup Pitch: Use Pixar’s Story Formula to Win Over Investors]]></title>
            <link>https://shwinda.medium.com/nail-your-startup-pitch-use-pixars-story-formula-to-win-over-investors-ea5e695fc0f7?source=rss-13ca56953261------2</link>
            <guid isPermaLink="false">https://medium.com/p/ea5e695fc0f7</guid>
            <category><![CDATA[startup]]></category>
            <category><![CDATA[venture-capital]]></category>
            <category><![CDATA[pitching]]></category>
            <category><![CDATA[fundraising]]></category>
            <category><![CDATA[entrepreneurship]]></category>
            <dc:creator><![CDATA[Ashwin Kumar]]></dc:creator>
            <pubDate>Wed, 23 Jun 2021 21:56:47 GMT</pubDate>
            <atom:updated>2021-06-23T21:58:28.896Z</atom:updated>
            <content:encoded><![CDATA[<p>A framework to make your pitch 10x more compelling in a few minutes</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_wY-8TPR5PhWtGcmR5SGlw.png" /></figure><blockquote><strong>As a startup founder, 90% of your job is storytelling.</strong></blockquote><p>You’re telling your company’s story <em>all the time: </em>when you’re fundraising, recruiting co-founders or employees, marketing to users, rallying your team, talking to the press, and communicating with your board. All these people are <em>begging </em>to hear a good story, one that inspires and moves them to act.</p><p><strong>But most of us never learned how to tell great stories!</strong> It’s the single highest leverage skill a founder can develop, and one that will elevate all aspects of the job.</p><h3>📕 Pitching = Storytelling</h3><p>The most obvious arena where you tell stories is during fundraising. Given that you have some level of conviction about your company and why it should exist, your job during fundraising is to <strong>succinctly </strong>tell investors a compelling story of your startup, and why it’s a <a href="https://twitter.com/paulg/status/1373562230403432449?lang=en"><strong>sufficiently good bet</strong></a> that’s too promising to ignore.</p><p><strong>We don’t need to reinvent the wheel here!</strong> People have iterated on storytelling for eons, and we can shamelessly borrow those learnings to tell better stories. In fact, we can use a story formula from one of the world’s best storytellers: <strong>Pixar.</strong></p><h3>🎥 The Pixar storytelling method</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0KD0PjkRYVzS8JReZ1tTNA.png" /></figure><p>Pixar has been one of the most successful studios in the film industry, making movies grossing over $14 billion at the box office, and winning 23 Academy Awards.</p><p>How can one studio have so many straight hits? Pixar is famous for its <a href="https://nofilmschool.com/2016/11/how-research-and-development-drive-story-creation-disney-pixar"><strong>rigorous and structured story creation process</strong></a><strong>, </strong>and at the heart of every Pixar movie is a story so tightly sequenced and calculated that it consistently tugs at heartstrings worldwide.</p><p>Emma Coates from Pixar published a set of<strong> </strong><a href="https://www.aerogrammestudio.com/2013/03/07/pixars-22-rules-of-storytelling/"><strong>story guidelines</strong></a>, which includes a <strong>Story Spine </strong>(pictured above)<strong>. </strong>This simple structure quickly conveys all the important pieces of a story: the initial conditions, inciting incident, resulting tension, and journey of the main character.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Mo5Yglge1_GVmchlYI3DnQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZNdznCX8AtPZKv5mggaM-Q.png" /></figure><h3>🚀 Applying the Pixar formula to your startup pitch</h3><p>You can use that same structure to describe the most important points about your company in a radically short amount of words that are easy to understand and digest. Here’s how the Story Spine maps to the essential components of a startup pitch:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mqf7I-WgxZzTTm6OPsgL9Q.png" /></figure><h3>🌎 1. “Once upon a time” ➡️ The problem</h3><p>These are the initial conditions of the world, regardless of your company’s existence. Who are the people you’re helping (your customers) and what is the <em>specific </em>job they need to get done?</p><p>You could also mention trends happening in the world to set the context for your company. What economic forces, social behaviors, or technological progress have you noticed related to how this problem is being solved? What waves are you riding?</p><p><strong>Deliver a strong insight here!</strong> Investors hear thousands of pitches from hundreds of domains. You know at least 10x as much as they do about your space, and the best pitches point out problems the investors might not have even known about, secrets that you know due to your unique background or experience.</p><blockquote><strong><em>🏠. Airbnb example</em><br></strong>Traveling is growing at X% but booking a hotel is one of the biggest concerns for travelers.<br><br><strong><em>💰 Coinbase example</em><br></strong>Bitcoin usage is growing quickly among early adopters, but it’s complicated to buy and store it.<br><br><em>🚀 </em><strong><em>SpaceX example</em><br></strong>As insurance against humanity’s existential risk, we need to develop rockets that can help us colonize Mars.</blockquote><h3>👎🏽 2. “And every day” ➡️ Why the current solutions suck</h3><p>Here you want to explain how those people from step 1 are solving their problem right now:</p><ul><li><strong>Are there hacks they’re using?</strong> Things they’re piecing together to solve this problem since there isn’t a good solution? Are there obvious incumbents in this space? Why don’t they do a great job of solving the problem?</li><li><strong>What are the biggest consequences of the current solutions?</strong> Time, money, energy? Complexity and headaches?</li></ul><p>This point is setting up point 4 below, where you’ll explain how your solution solves this problem so much better, so highlight the issues that current solutions have which <strong>directly correlate</strong> to your solution’s primary value proposition.</p><blockquote><strong><em>🏠 Airbnb</em><br></strong>Hotel booking is expensive and doesn’t let you really experience living in a city.</blockquote><blockquote><em>💰 </em><strong><em>Coinbase</em><br></strong>The current tools are hard to piece together and limit Bitcoin adoption to engineers and hackers.</blockquote><blockquote><em>🚀 </em><strong><em>SpaceX</em><br></strong>Current rockets aren’t powerful or affordable enough to get a critical mass of people to another planet.</blockquote><h3>📱 3. “Until one day” ➡️ Your solution</h3><p>Now that you’ve set up the customer, problem, current solutions, and why they’re not good enough, you finally introduce your own solution.</p><p>The biggest mistake founders make here is using <a href="https://www.ycombinator.com/library/4b-how-to-pitch-your-company"><strong>jargon, marketing speak, and ambiguous terms</strong></a><strong>.</strong> Be specific and matter-of-fact. What is the exact solution you’re proposing? Is it an app? Hardware? A marketplace that connects two parties?</p><p>It’s much better to be narrow and focused than broad and vague. Investors need an anchor of what your solution looks like so they can easily see why it’s better than what exists.</p><blockquote><strong><em>🏠 Airbnb</em><br></strong>We’re building a marketplace that lets travelers book rooms with local hosts.</blockquote><blockquote><em>💰 </em><strong><em>Coinbase</em><br></strong>We’re making a hosted Bitcoin wallet.</blockquote><blockquote><em>🚀 </em><strong><em>SpaceX</em><br></strong>We’re making rockets that are reusable and powerful enough to reliably get people to Mars.</blockquote><h3>👏🏽 4. “And because of that” ➡️ Why your solution is 10x better</h3><p>Now that I know what your solution is, I need to know why it’s <strong>10x better.</strong> What is the primary value proposition for your product?</p><p>Remember the “biggest issue with current solutions” you brought up in step 2? The value proposition you present here needs to directly correlate with that big issue:</p><ul><li>The current solutions are too expensive -&gt;<strong> your solution is affordable</strong></li><li>The current solutions are complex and for experts -&gt; <strong>your solution simplifies the process</strong></li><li>The current solutions are too slow -&gt; <strong>your solution is much faster</strong></li></ul><blockquote><strong><em>🏠 Airbnb</em><br></strong>This means travelers book cheaper accomodations, and hosts can make money off their spare rooms.</blockquote><blockquote><em>💰 </em><strong><em>Coinbase</em><br></strong>It makes it simple for ANYONE to buy, sell, and store their Bitcoin just by connecting their bank account.</blockquote><blockquote><em>🚀 </em><strong><em>SpaceX</em><br></strong>Since our rockets are reusable, we drastically reduce the cost of launch, and we’ll use our launches to develop rockets powerful enough to transport humans to Mars.</blockquote><h3>📈 5. “And because of that” ➡️ Your traction</h3><p>Now I know what your solution is and why it’s so much better.<strong> Let’s see the proof that you might be right.</strong> Do you have any traction with your product?</p><p>Traction can mean a lot of things, depending on your stage and industry. You have to show where you are on the<strong> </strong><a href="https://synbiobeta.com/the-ladder-of-proof-how-vcs-see-your-startup/"><strong>ladder of proof</strong></a><strong>, </strong>and especially how fast you’re growing.</p><p>If you haven’t launched your product, you can talk about why you’re so confident in your solution: <em>clear</em> interest from big-name customers, deep and relevant customer interviews, or a large waiting list.</p><blockquote><strong><em>🏠 Airbnb</em><br></strong>We’ve already had X bookings on the platform, and we’re growing at X% each month.</blockquote><blockquote><em>💰 </em><strong><em>Coinbase</em><br></strong>That’s why our user base has been growing at X% monthly, and we’re managing over $B in Bitcoin already.</blockquote><blockquote><em>🚀 </em><strong><em>SpaceX</em><br></strong>Our first step is making revenue by using our initial rockets to deliver satellites to orbit for paying customers. We’ve already booked $B in launches since we started.</blockquote><h3>💰 6. “Until finally” ➡️ The market you’re capturing</h3><p>If you’re solving a real problem for desperate customers in a way that is so much better than what exists out there, and you’re proving it out with your traction, <strong>seal the deal by telling me how big this can get.</strong></p><p>Due to the <a href="https://www.linkedin.com/pulse/vc-economics-why-fund-size-matters-companies-jim-hao/?trk=public_profile_article_view"><strong>economics of early-stage startup investing</strong></a><strong>,</strong> investors need to invest in companies that can become massively valuable. You want to take a <a href="https://www.quora.com/How-do-you-complete-a-bottoms-up-sizing-analysis-for-startup-due-diligence"><strong>bottom’s up</strong></a> approach: the amount you can charge each customer multiplied by how many customers fit into your market.</p><p>If the pitch up to this point is concise, you can add in a quick line here about any adjacent markets you can get into after your current one, and how big those markets are too.</p><blockquote><strong><em>🏠 Airbnb</em><br></strong>With the % fee we take on each transaction and _ million trips each year that would make sense to use our product for, we’re looking into a $_B market.</blockquote><blockquote><em>💰 </em><strong><em>Coinbase</em><br></strong>With the Bitcoin market at $B and % of new Bitcoin buyers fitting into our user profile, we’re going after a market worth $B.</blockquote><blockquote><em>🚀 </em><strong><em>SpaceX</em><br></strong>The commercial satellite launch industry is $B but we expect our lower cost of launch to grow it to $B in the next 10 years.</blockquote><h3>👇🏽 More Examples</h3><p>Here are a few examples of other companies and how they might use this way of telling their story. Note that these are just one way of telling their story, and that this structure can apply to any company in any space.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*b_J4uxpZxdMBUoKqg2xKFQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xVUorFXzydXOd_rLmGW2ZQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*31yRtFKWPqSull3ZEekKyQ.png" /></figure><h3>📈 Fix your story and win</h3><blockquote><strong>Just like Pixar, you won’t nail the story with the very first version. The best approach here is to try out one version of this story, see what works, and iterate.</strong></blockquote><p>One good approach is to use the <a href="https://www.ycombinator.com/library/4b-how-to-pitch-your-company"><strong>email test</strong></a><strong>: </strong>write up a version of the story in an email and send it to a few people that you know and trust to give good feedback. Ask them to reply back with some answers to see if that story sticks, and iterate based on whatever clarifying questions they have.</p><p><em>📨 Here’s an email template to use:</em></p><blockquote><strong>Subject: </strong>Feedback on my startup elevator pitch</blockquote><blockquote>Hi ____,</blockquote><blockquote>I’m trying to get my startup elevator pitch to be as compelling as possible. Here’s what I have right now. Could you take a quick read and reply back with answers to some of the questions I have below the pitch? I really appreciate it!</blockquote><blockquote><strong>[insert the story based on the Pixar template here]</strong><br><br>Based on this, could you tell me:<br>1. Who my target customer is and what problem I’m solving for them?<br>2. Why the current solutions aren’t great?<br>3. What makes my product so much better?<br>4. If there’s anything unclear about what I’m building and why?<br><br>Thanks so much,<br>[your name]</blockquote><p>Feel free to <a href="mailto:ashwin@ashwinkumar.xyz"><strong>email me</strong></a> your pitch with this template and I’ll give you some feedback. Also, <a href="https://startuppitch.substack.com/"><strong>subscribe to my newsletter</strong></a> so you won’t miss my next post!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ea5e695fc0f7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Automated front-end development using deep learning]]></title>
            <link>https://medium.com/insight-data/automated-front-end-development-using-deep-learning-3169dd086e82?source=rss-13ca56953261------2</link>
            <guid isPermaLink="false">https://medium.com/p/3169dd086e82</guid>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[insight-ai]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[design]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Ashwin Kumar]]></dc:creator>
            <pubDate>Tue, 20 Mar 2018 16:13:06 GMT</pubDate>
            <atom:updated>2018-03-20T16:26:44.391Z</atom:updated>
            <content:encoded><![CDATA[<h4>SketchCode: Go from idea to HTML in 5 seconds</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KdJXGE6_bPujcHTTxKJ5gg.png" /></figure><p><a href="https://www.linkedin.com/in/ashnkumar/"><em>Ashwin Kumar</em></a><em> was previously the co-founder of </em><a href="http://swayfinance.com/"><em>Sway Finance</em></a><em>, a Y Combinator-backed startup that used machine learning to automate accounting. At Insight, he developed a model that allows users to create working HTML websites from hand-drawn wireframes, significantly accelerating the design process. He is now a Deep Learning Scientist at </em><a href="http://www.mythic-ai.com/"><em>Mythic</em></a><em>.</em></p><p><a href="https://www.insightdatascience.com/apply"><strong><em>Apply now</em></strong></a><strong><em> to join the next cohort of researchers and engineers building cutting-edge Applied AI products. </em></strong><em>The deadline for the next Insight AI Fellowship (both Silicon Valley and New York) is March 26th.</em></p><p>Creating intuitive and engaging experiences for users is a critical goal for companies of <em>all</em> sizes, and it’s a process driven by quick cycles of prototyping, designing, and user testing. Large corporations like Facebook have the bandwidth to dedicate entire teams to the design process, which can take several weeks and involve multiple stakeholders; small businesses don’t have these resources, and their user interfaces may suffer as a result.</p><p>My goal at Insight was to use modern deep learning algorithms to significantly streamline the design workflow and empower <em>any</em> business to quickly create and test webpages.</p><h3>The design workflow today</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/722/1*zUhBTc7gJ985IGdjyinKGQ.png" /><figcaption>A design workflow goes through multiple stakeholders</figcaption></figure><p>A typical design workflow might look like the following:</p><ul><li>Product managers perform user research to generate a list of specifications</li><li>Designers take those requirements and explore low-fidelity prototypes, eventually creating high-fidelity mockups</li><li>Engineers implement those designs into code and finally ship the product to users</li></ul><p>The length of the development cycle can quickly turn into a bottleneck, and companies like Airbnb have <a href="https://airbnb.design/sketching-interfaces/">started to use machine learning</a> to make this process more efficient.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/961/1*5-RcoPbKibWGbBeGDOuo0A.png" /><figcaption>Airbnb’s demo of their internal AI tool to go from drawings to code</figcaption></figure><p>Though promising as an example of machine-assisted design, it’s unclear how much of this model is being fully trained end-to-end, and how much relies on hand-crafted image features. There’s no way to know for sure, because it’s a closed-source solution proprietary to the company. I wanted to create an open-source version of <strong>drawing-to-code</strong> technology that’s accessible to the wider community of developers and designers.</p><p>Ideally, my model would be able to take a simple hand-drawn prototype of a website design, and instantly generate a working HTML website from that image:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/716/1*PKL0GX-bQnHVJIqnPGUaVg.png" /><figcaption>The SketchCode model takes drawn wireframes and generates HTML code</figcaption></figure><p>In fact, the example above is an actual website generated from my model on a test set image! You can check out the code on my <a href="https://github.com/ashnkumar/sketch-code">Github</a> page.</p><h3>Drawing inspiration from image captioning</h3><p>The problem I was solving falls under a broader umbrella of tasks known as <a href="https://en.wikipedia.org/wiki/Program_synthesis">program synthesis</a>, the automated generation of working source code. Though much of program synthesis deals with code generated from natural language specifications or execution traces, in my case I could leverage the fact that I had a source image (the hand-drawn wireframe) to start with.</p><p>There’s a well-studied domain in machine learning called <a href="https://cs.stanford.edu/people/karpathy/deepimagesent/">image captioning</a> that seeks to learn models that tie together images and text, specifically to generate descriptions of the contents of a source image.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_sY92m24szeF5pFUCXWpNA.png" /><figcaption>Image captioning models generate descriptions of source images</figcaption></figure><p>Drawing inspiration from a <a href="https://arxiv.org/abs/1705.07962">recent paper called pix2code</a> and a <a href="https://blog.floydhub.com/turning-design-mockups-into-code-with-deep-learning/?source=techstories.org">related project </a>by Emil Wallner that used this approach, I decided to reframe my task into one of image captioning, with the drawn website wireframe as the input image and its corresponding HTML code as its output text.</p><h3>Getting the right dataset</h3><p>Given the image captioning approach, my ideal training dataset would have been thousands of pairs of hand-drawn wireframe sketches and their HTML code equivalents. Unsurprisingly, I couldn’t find that exact dataset, and I had to create my own data for the task.</p><p>I started with an <a href="https://github.com/tonybeltramelli/pix2code">open-source dataset</a> from the pix2code paper, which consists of 1,750 screenshots of synthetically generated websites and their relevant source code.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/801/1*GliJg1JaacB8S7H6oIrERw.png" /><figcaption>The pix2code dataset of generated website images and source code</figcaption></figure><p>This was a great dataset to start with, with a couple interesting points:</p><ul><li>Each generated website in the dataset consists of combinations of just a few simple <a href="http://getbootstrap.com/2.3.2/">Bootstrap</a> elements such as buttons, text boxes, and divs. Though this means my model would be limited to these few elements as its ‘vocabulary’ — the elements it can choose from to generate websites — the approach should easily generalize to a larger vocabulary of elements</li><li>The source code for each sample consists of tokens from a domain-specific-language (<a href="https://en.wikipedia.org/wiki/Domain-specific_language">DSL</a>) that the authors of the paper created for their task. Each token corresponds to a snippet of HTML and CSS, and a compiler is used to translate from the DSL to working HTML code</li></ul><h3><strong>Making the images look hand-drawn</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/817/1*E3gRTz00KXv4biyym-GIHg.png" /><figcaption>Turning colorful website images into hand-drawn versions</figcaption></figure><p>In order to modify the dataset for my own task, I needed to make the website images look like they were drawn by hand. I explored using tools like <a href="https://opencv.org/">OpenCV</a> and the <a href="https://pillow.readthedocs.io/en/stable/">PIL library</a> in python to make modifications to each image such as grayscale transformations and contour detection.</p><p>Ultimately, I decided to directly modify the CSS stylesheet of the original websites, performing a series of operations:</p><ul><li>Changed the border radius of elements on the page to curve the corners of buttons and divs</li><li>Adjusted the thickness of borders to mimic drawn sketches, and added drop shadows</li><li>Changed the font to one that looks like handwriting</li></ul><p>My final pipeline added one further step, which augmented these images by adding skews, shifts, and rotations to mimic the variability in actual drawn sketches.</p><h3>Using an image captioning model architecture</h3><p>Now that I had my data ready, I could finally feed it into the model!</p><p>I leveraged a <a href="https://github.com/emilwallner/Screenshot-to-code-in-Keras/blob/master/README.md">model architecture</a> used in image captioning that consists of three major parts:</p><ul><li>A computer vision model that uses a Convolutional Neural Network (CNN) to extract image features from the source images</li><li>A language model consisting of a Gated Recurrent Unit (GRU) that encodes sequences of source code tokens</li><li>A decoder model (also a GRU), which takes in the output from the previous two steps as its input, and predicts the next token in the sequence</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vZX3R1neqV6Rf9y_baJCYw.png" /><figcaption>Training the model using sequences of tokens as input</figcaption></figure><p>To train the model, I split the source code into sequences of tokens. A single input for the model is one of these sequences along with its source image, and its label is the next token in the document. The model uses the <a href="https://en.wikipedia.org/wiki/Cross_entropy">cross-entropy cost</a> as its loss function, which compares the model’s next token prediction with the actual next token.</p><p>At inference time when the model is tasked with generating code from scratch, the process is slightly different. The image is still processed through the CNN network, but the text process is seeded with just a starting sequence. At each step, the model’s prediction for the next token in the sequence is appended to the current input sequence, and fed into the model as a new input sequence. This is repeated until the model predicts an &lt;END&gt; token or the process reaches a predefined limit to the number of tokens per document.</p><p>Once the set of predicted tokens is generated from the model, a compiler converts the DSL tokens into HTML, which can be rendered in any browser.</p><h3><strong>Evaluating the model with the BLEU score</strong></h3><p>I decided to use the <a href="https://machinelearningmastery.com/calculate-bleu-score-for-text-python/">BLEU score</a> to evaluate the model. This is a common metric used in machine translation tasks, which seeks to measure how closely a machine-generated text resembles what a human would have generated, given the same input.</p><p>Essentially, the BLEU compares n-gram sequences of both the generated text and reference text to create a modified form of precision. It’s very suitable for this project since it factors in the actual elements in the generated HTML, as well as where they are in relation to each other.</p><p>And the best part — I could actually <em>see</em> the BLEU scores through examining the generated websites!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rN3zHT7FpBt-G5mMXryshg.png" /><figcaption>Visualizing the BLEU score</figcaption></figure><p>A perfect BLEU score of 1.0 would have the right elements in the right locations given the source image, while a lower score would predict the wrong elements and/or put them in the wrong locations relative to each other. The final model was able to get a BLEU score of 0.76<strong><em> </em></strong>on the evaluation set.</p><h3>Bonus — Custom styling</h3><p>An added bonus I realized was that since the model only generates the <strong>skeleton</strong> of the page (the tokens of the document), I could add in a custom CSS layer in the compilation process, and instantly have different styles of what the resulting website could look like.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/797/1*AHz84ILuLMHvA5WFG6REUw.png" /><figcaption>One drawing =&gt; many styles generated simultaneously</figcaption></figure><p>Having the styling decoupled from the model generation process gives a couple big advantages to using the model:</p><ul><li>A front-end engineer who wants to incorporate the SketchCode model into their own company’s product can use the model as-is and just change a single CSS file to comply with their company’s style guide</li><li>Scalability is built in — with a single source image the model outputs can instantly be compiled to 5, 10 or 50 different pre-defined styles, so users can visualize multiple versions of what their website might look like, and navigate around those websites in a browser</li></ul><h3>Conclusion and future directions</h3><p>By leveraging research in image captioning, SketchCode is able to take hand-drawn website wireframes and convert them into working HTML websites in a few seconds.</p><p>The model has some limitations, which inform possible next steps:</p><ul><li>Since the model was trained on a vocabulary of just 16 elements, it can’t predict tokens outside of what it’s seen in the data. One next step could be to generate additional website examples using more elements, such as images, dropdown menus, and forms — <a href="https://getbootstrap.com/docs/4.0/components/buttons/">Bootstrap components</a> are a great place to start</li><li>There’s a lot of variation in actual production websites. A great way to create a training dataset more reflective of this variation would be to scrape actual websites, capturing their HTML/CSS code as well as screenshots of the site content</li><li>Drawings also have a lot of variation that the CSS modification trick doesn’t fully catch. A great way to generate more variation in the hand-drawn sketch data could be to use a <a href="http://generative adversarial networks explained">Generative Adversarial Network</a> to create realistic-looking drawn website images</li></ul><p>You can find the code used for this project on my GitHub page <a href="https://github.com/ashnkumar/sketch-code">here</a>, and I’m excited to see where the project goes next!</p><p><strong><em>Want to learn applied Artificial Intelligence from top professionals in Silicon Valley or New York?</em></strong><em> </em>Learn more about the <a href="http://insightdata.ai/?utm_source=sketchcode&amp;utm_medium=blog&amp;utm_content=bottom">Artificial Intelligence</a> program.</p><p><strong><em>Are you a company working in AI and would like to get involved in the Insight AI Fellows Program?</em></strong><em> Feel free to </em><a href="http://insightdatascience.com/partnerships?utm_source=sketchcode&amp;utm_medium=blog&amp;utm_content=bottom"><em>get in touch</em></a><em>.</em></p><p>Thanks to <a href="https://medium.com/@emmanuelameisen?source=post_page">Emmanuel Ameisen</a>, <a href="https://medium.com/@ben_71772">Ben Regner</a>, and <a href="https://blog.insightdatascience.com/@jkarnows">Jeremy Karnowski</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3169dd086e82" width="1" height="1" alt=""><hr><p><a href="https://medium.com/insight-data/automated-front-end-development-using-deep-learning-3169dd086e82">Automated front-end development using deep learning</a> was originally published in <a href="https://medium.com/insight-data">Insight</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>