<?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 Ojas Kapre on Medium]]></title>
        <description><![CDATA[Stories by Ojas Kapre on Medium]]></description>
        <link>https://medium.com/@ojasskapre?source=rss-3a9917adb75b------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*0xLNmgjpZL0knYUU_sHXUw.jpeg</url>
            <title>Stories by Ojas Kapre on Medium</title>
            <link>https://medium.com/@ojasskapre?source=rss-3a9917adb75b------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 08:50:44 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ojasskapre/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[Implementing Stripe Subscriptions with Supabase, Next.js, and FastAPI]]></title>
            <link>https://medium.com/@ojasskapre/implementing-stripe-subscriptions-with-supabase-next-js-and-fastapi-666e1aada1b5?source=rss-3a9917adb75b------2</link>
            <guid isPermaLink="false">https://medium.com/p/666e1aada1b5</guid>
            <category><![CDATA[fastapi]]></category>
            <category><![CDATA[stripe]]></category>
            <category><![CDATA[supabase]]></category>
            <category><![CDATA[nextjs]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Ojas Kapre]]></dc:creator>
            <pubDate>Sat, 24 Aug 2024 07:18:48 GMT</pubDate>
            <atom:updated>2024-08-24T07:18:48.734Z</atom:updated>
            <content:encoded><![CDATA[<p>In this blog, I’ll walk you through how to set up a subscription service using Stripe, with Next.js for the frontend, FastAPI for the backend, and Supabase as the database. This setup was used in my LLM (Large Language Model) project, where users could make a certain number of API calls and access different models based on their subscription tier.</p><p>To have a basic setup ready — follow the steps in the <a href="https://github.com/ojasskapre/nextjs-starter-template?tab=readme-ov-file#overview">Readme of the GitHub repository</a>. You can also follow <a href="https://medium.com/gopenai/building-llm-saas-products-made-easy-5966be94d8d2">my blog</a> to have understanding on my project.</p><h3>Project Demo</h3><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2Fo5G4-wve8I8%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3Do5G4-wve8I8&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2Fo5G4-wve8I8%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/692bf87d9d05fba4ff99da52f10f714a/href">https://medium.com/media/692bf87d9d05fba4ff99da52f10f714a/href</a></iframe><h3>Step-by-Step Process for Stripe Subscription Integration</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6k8JddfeTahaAjMHg7eIog.png" /></figure><p><strong>1. User Initiates the Subscription</strong></p><ul><li>The user clicks the “Buy Now” button on the frontend to purchase the “Premium Plan.”</li></ul><p><strong>2. Frontend Calls </strong><strong>create-checkout-session API</strong></p><ul><li>The frontend sends a request to the backend via the /api/create-checkout-session endpoint to create a Stripe Checkout session.</li></ul><p><strong>3. Backend Creates Stripe Checkout Session</strong></p><ul><li>The backend uses the Stripe library to create a checkout session and returns the session_id to the frontend.</li></ul><p><strong>4. Redirect User to Stripe Checkout</strong></p><ul><li>The frontend redirects the user to the Stripe Checkout page using the session_id.</li></ul><p><strong>5. User Completes Payment</strong></p><ul><li>The user completes the payment on the Stripe Checkout page.</li></ul><p><strong>6. Stripe Sends </strong><strong>checkout.session.completed Event to Webhook</strong></p><ul><li>Once the payment is completed, Stripe triggers the checkout.session.completed event and sends it to the backend webhook.</li></ul><p><strong>7. Backend Updates User Profile</strong></p><ul><li>The backend processes the webhook, updates the user’s subscription details in the database, and marks the subscription as active.</li></ul><p><strong>8. Stripe Redirects User Back to Success Page</strong></p><ul><li>Stripe redirects the user to the success URL, typically a confirmation page.</li><li>If the payment fails, the webhook is not called and the user is redirected to the cancel URL page.</li></ul><p><strong>9. Frontend Requests Updated Profile</strong></p><ul><li>After the user is redirected back, the frontend makes an API call to fetch the updated subscription details.</li></ul><p><strong>10. Display Active Subscription Plan</strong></p><ul><li>The frontend displays the active subscription plan to the user.</li></ul><p><strong>11. User Cancels Subscription</strong></p><ul><li>If the user decides to cancel the subscription, they click on the “Cancel” button, which triggers an API call to /api/cancel-subscription.</li></ul><p><strong>12. Frontend Sends Cancellation Request to Backend</strong></p><ul><li>The frontend sends a request to the backend to cancel the subscription.</li></ul><p><strong>13. Backend Cancels Subscription on Stripe</strong></p><ul><li>The backend uses the Stripe API to cancel the subscription.</li></ul><p><strong>14. Backend Updates Subscription Details</strong></p><ul><li>The backend updates the user’s subscription status to “canceled” in the database.</li></ul><p><strong>15. Frontend Requests Updated Profile</strong></p><ul><li>The frontend makes another API call to get the updated profile details after cancellation.</li></ul><p><strong>16. Display Updated Subscription Status</strong></p><ul><li>The frontend displays the updated (canceled) subscription status to the user.</li></ul><h3>Project Structure</h3><p>First, let’s take a look at the project structure:</p><pre>.<br>├── backend/<br>│   ├── main.py<br>│   ├── models.py<br>│   ├── routes/<br>│   │   ├── __init__.py<br>│   │   ├── stripe_checkout_session.py<br>│   │   ├── stripe_webhook.py<br>│   ├── .env<br>│   └── ...<br>├── frontend/<br>│   ├── src/<br>│   │   ├── app/<br>│   │   │   ├── plans/<br>│   │   │   │   ├── page.tsx<br>│   │   ├── components/<br>│   │   │   ├── Pricing.tsx<br>│   ├── .env<br>│   └── ...</pre><h3>Database Setup with Supabase</h3><p>In Supabase, I created a profiles table with the following structure:</p><pre>id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)<br>email = Column(String, nullable=False, unique=True)<br>created_at = Column(DateTime, server_default=func.now())<br><br># Stripe subscription-related columns<br>subscription_plan = Column(String, nullable=True)  # e.g., &quot;free&quot;, &quot;basic&quot;, &quot;pro&quot;<br>subscription_status = Column(String, nullable=True)  # e.g., &quot;active&quot;, &quot;canceled&quot;<br>stripe_customer_id = Column(String, nullable=True, unique=True)<br>stripe_subscription_id = Column(String, nullable=True, unique=True)<br>current_period_end = Column(DateTime, nullable=True)<br>trial_end = Column(DateTime, nullable=True)  # Optional, if you offer trials</pre><p>In my project, I had created a trigger which would create a new profile when new user sign’s up through supabase authentication and the user is created in supabase autth.users table.</p><h3>Installing Stripe</h3><p>To integrate Stripe, I installed the following:</p><h4>Frontend:</h4><pre>npm install @stripe/stripe-js</pre><h4>Backend:</h4><p>Using Poetry:</p><pre>poetry add stripe</pre><p>Or using pip:</p><pre>pip install stripe</pre><h3>Setting Up API Keys</h3><p>You’ll need to generate API keys from your Stripe Dashboard:</p><ul><li>Go to the <a href="https://dashboard.stripe.com/">Stripe Dashboard</a> -&gt; Developers -&gt; API keys.</li></ul><h4>Frontend .env:</h4><pre>NEXT_PUBLIC_STRIPE_PRO_MONTHLY_PLAN_PRICE_ID=price_...<br>STRIPE_PUBLISHABLE_KEY=pk_test_...</pre><h4>Backend .env:</h4><pre>STRIPE_SECRET_KEY=sk_test_...<br>STRIPE_WEBHOOK_SECRET=whsec_...</pre><h3>Stripe Dashboard Setup</h3><p>First, create products in the <a href="https://dashboard.stripe.com/test/products">Stripe Dashboard</a>:</p><ol><li>Name: Premium</li><li>Description: A plan with unlimited GPT-3.5 Turbo calls and 20 GPT-4o calls.</li><li>Amount: $20</li><li>Billing Period: Monthly</li><li>Set it as a recurring product.</li></ol><p>Copy the price ID from the Pricing table in the products page and update the value in the frontend .env file.</p><h3>Frontend Implementation</h3><p>Create a page to display all plans, located at src/app/plans/page.tsx:</p><h4>PlansPage Component:</h4><pre>&#39;use client&#39;;<br><br>import Pricing from &#39;@/components/Pricing&#39;;<br>const PlansPage = () =&gt; {<br>  return (<br>    &lt;div className=&quot;flex items-center justify-center h-full&quot;&gt;<br>      &lt;Pricing /&gt;<br>    &lt;/div&gt;<br>  );<br>};<br>export default PlansPage;</pre><h4>Pricing Component</h4><pre>&#39;use client&#39;;<br><br>import { useAuth } from &#39;@/context/AuthContext&#39;;<br>import { useRouter } from &#39;next/navigation&#39;;<br>import { loadStripe } from &#39;@stripe/stripe-js&#39;;<br>import { useState, useEffect } from &#39;react&#39;;<br>import { createCheckoutSession, cancelSubscription, getMyProfile } from &#39;@/utils/api&#39;;<br>import { Loader2 } from &#39;lucide-react&#39;;<br><br>...<br><br>// Load Stripe with your publishable key<br>const stripePromise = loadStripe(process.env.NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY!);<br><br>export default function Pricing() {<br>  const { user, getToken } = useAuth();<br>  const router = useRouter();<br><br>  const [subscriptionPlan, setSubscriptionPlan] = useState&lt;string&gt;(&#39;Free&#39;);<br>  const [loading, setLoading] = useState&lt;boolean&gt;(true);<br>  const [cancelLoading, setCancelLoading] = useState&lt;boolean&gt;(false);<br><br>  useEffect(() =&gt; {<br>    const fetchUserProfile = async () =&gt; {<br>      setLoading(true);<br>      const token = await getToken();<br>      if (token &amp;&amp; user) {<br>        try {<br>          const data = await getMyProfile(token);<br>          setSubscriptionPlan(data.subscription_plan || &#39;Free&#39;);<br>        } catch (error) {<br>          console.error(&#39;Failed to fetch profile:&#39;, error);<br>        }<br>      }<br>      setLoading(false);<br>    };<br>    fetchUserProfile();<br>  }, [getToken, user]);<br><br>  const handleCheckout = async (plan: Plan) =&gt; {<br>    if (!user) {<br>      router.push(&#39;/login&#39;);<br>    } else if (plan.title === subscriptionPlan) {<br>      await cancelSubscriptionHandler();<br>    } else if (plan.priceId) {<br>      try {<br>        const token = await getToken();<br>        const stripe = await stripePromise;<br>        const { sessionId } = await createCheckoutSession(plan.priceId, user.email, token!);<br><br>        // Redirect to Stripe Checkout<br>        const { error } = await stripe!.redirectToCheckout({ sessionId });<br>        if (error) {<br>          console.error(&#39;Error redirecting to checkout:&#39;, error);<br>        }<br>      } catch (error) {<br>        console.error(&#39;Failed to initiate checkout:&#39;, error);<br>      }<br>    }<br>  };<br><br>  const cancelSubscriptionHandler = async () =&gt; {<br>    setCancelLoading(true);<br>    try {<br>      const token = await getToken();<br>      if (token) {<br>        await cancelSubscription(token);<br>        setSubscriptionPlan(&#39;Free&#39;);<br>      }<br>    } catch (error) {<br>      console.error(&#39;Failed to cancel subscription:&#39;, error);<br>    }<br>    setCancelLoading(false);<br>  };<br><br>  if (loading) {<br>    return (<br>      &lt;div className=&quot;flex items-center justify-center min-h-screen bg-background&quot;&gt;<br>        &lt;Loader2 className=&quot;animate-spin text-blue-500 w-10 h-10&quot; /&gt;<br>      &lt;/div&gt;<br>    );<br>  }<br><br>  ...<br>}</pre><p>The Pricing component in this project is designed to manage subscription plans using Stripe on the frontend, with Next.js and Supabase. Here&#39;s what it does:</p><p><strong>Initialization</strong>:</p><ul><li>Stripe is initialized with loadStripe using the publishable key from the environment variables.</li><li>The component uses state variables to track the user’s current subscription plan, loading states, and cancellation states.</li></ul><p><strong>Fetching User Profile</strong>:</p><ul><li>On component mount, it fetches the user’s profile information from the backend, including the current subscription plan, using a JWT token for authentication.</li></ul><p><strong>Handling Subscriptions</strong>:</p><ul><li><strong>Subscription Purchase</strong>: When a user selects a plan, the handleCheckout function checks if the user is logged in, creates a Stripe checkout session via the backend if needed, and redirects the user to Stripe&#39;s payment page.</li><li><strong>Subscription Cancellation</strong>: If the user is already subscribed to the selected plan, the cancelSubscriptionHandler function cancels the subscription by making an API call to the backend.</li></ul><p><strong>API Calls</strong>:</p><ul><li>The createCheckoutSession and cancelSubscription functions are responsible for communicating with the backend to handle Stripe operations. For example, createCheckoutSession initiates a new checkout session and redirects the user to the Stripe payment page.</li></ul><p>createCheckoutSession API Call:</p><pre>export async function createCheckoutSession(priceId: string, email: string, token: string) {<br>  const response = await fetch(&#39;/api/stripe/create-checkout-session&#39;, {<br>    method: &#39;POST&#39;,<br>    headers: {<br>      &#39;Content-Type&#39;: &#39;application/json&#39;,<br>      Authorization: `Bearer ${token}`,<br>    },<br>    body: JSON.stringify({ priceId, email }),<br>  });<br><br>  if (!response.ok) {<br>    throw new Error(&#39;Failed to create checkout session&#39;);<br>  }<br><br>  return response.json();<br>}</pre><p>The UI of plans page, i.e. Pricing component is as follows</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GUjIWYrEpDyk-jdIgHta4Q.png" /></figure><h3>Backend Implementation</h3><p>In this section, we’ll set up a webhook in the FastAPI backend to listen for Stripe payment events. Once a subscription payment is completed, the webhook will be triggered to save the subscription information in the profile table in the database. Here&#39;s how you can implement it:</p><h4>Implementing APIs for creating checkout session and canceling subscriptions</h4><p><strong>Creating a Checkout Session</strong></p><p>The create_checkout_session API is used to create a new checkout session with Stripe. This is the first step when a user selects a plan and initiates the payment process. The session created will redirect the user to the Stripe-hosted payment page.</p><pre>from fastapi import APIRouter, HTTPException, Request<br>import stripe<br>import os<br>from dotenv import load_dotenv, find_dotenv<br><br>_ = load_dotenv(find_dotenv())  # Load environment variables from .env file<br>stripe.api_key = os.environ[&#39;STRIPE_SECRET_KEY&#39;]<br><br>router = APIRouter()<br><br>@router.post(&quot;/create-checkout-session&quot;)<br>async def create_checkout_session(request: Request):<br>    data = await request.json()<br>    try:<br>        checkout_session = stripe.checkout.Session.create(<br>            payment_method_types=[&#39;card&#39;],<br>            mode=&#39;subscription&#39;,<br>            line_items=[{<br>                &#39;price&#39;: data[&#39;priceId&#39;],  # Price ID from the Stripe dashboard<br>                &#39;quantity&#39;: 1,<br>            }],<br>            success_url=f&quot;{data[&#39;successUrl&#39;]}?session_id={{CHECKOUT_SESSION_ID}}&quot;,<br>            cancel_url=data[&#39;cancelUrl&#39;],<br>            metadata={<br>                &#39;app_email&#39;: data[&#39;user_email&#39;],  # Custom metadata to link Stripe data to your user<br>            }<br>        )<br>        return {&quot;sessionId&quot;: checkout_session[&#39;id&#39;]}<br>    except Exception as e:<br>        raise HTTPException(status_code=400, detail=str(e))</pre><p><strong>Explanation:</strong></p><ul><li>The API receives a JSON payload with the price ID, success URL, and cancel URL.</li><li>It creates a checkout session using the stripe.checkout.Session.create method.</li><li>The session includes metadata such as the user’s email to help link Stripe’s records with your database.</li><li>The user is redirected to the Stripe checkout page using the session ID returned from this API.</li></ul><p><strong>Canceling a Subscription</strong></p><p>The cancel_subscription API is used to cancel a user&#39;s active subscription. This can be triggered by the user from the frontend when they decide to cancel their subscription.</p><pre>from fastapi import APIRouter, HTTPException, Depends<br>from sqlalchemy.orm import Session<br>from app.models.profile import Profile<br>from app.dependencies import verify_jwt<br>from app.database import get_db<br>import stripe<br>import os<br>from dotenv import load_dotenv, find_dotenv<br><br>_ = load_dotenv(find_dotenv())  # Load environment variables from .env file<br>stripe.api_key = os.environ[&#39;STRIPE_SECRET_KEY&#39;]<br><br>router = APIRouter()<br><br>@router.put(&quot;/cancel-subscription&quot;)<br>async def cancel_subscription(user=Depends(verify_jwt), db: Session = Depends(get_db)):<br>    # Fetch the user&#39;s profile from the database<br>    profile = db.query(Profile).filter_by(id=user.user.id).first()<br>    if not profile or not profile.stripe_subscription_id:<br>        raise HTTPException(status_code=404, detail=&quot;Subscription not found&quot;)<br><br>    # Cancel the subscription on Stripe<br>    try:<br>        stripe.Subscription.delete(profile.stripe_subscription_id)<br>        profile.stripe_subscription_id = None<br>        profile.stripe_customer_id = None<br>        profile.subscription_plan = None<br>        profile.subscription_status = &quot;canceled&quot;<br>        profile.current_period_end = None<br>        profile.trial_end = None<br>        db.commit()<br>        return {&quot;message&quot;: &quot;Subscription canceled successfully&quot;}<br>    except Exception as e:<br>        raise HTTPException(status_code=500, detail=str(e))</pre><p><strong>Explanation:</strong></p><ul><li>The API authenticates the user and retrieves their profile from the database.</li><li>It checks if the user has an active subscription by verifying stripe_subscription_id.</li><li>If the user has an active subscription, it cancels it using stripe.Subscription.delete.</li><li>The user’s profile in the database is updated to reflect the canceled subscription.</li></ul><h4>Setting Up the Stripe Webhook in FastAPI</h4><pre>import os<br>import stripe<br>from fastapi import APIRouter, HTTPException, Request, Depends<br>from sqlalchemy.orm import Session<br>from app.database import get_db<br>from app.models.profile import Profile<br>from dotenv import load_dotenv, find_dotenv<br>from datetime import datetime<br><br>_ = load_dotenv(find_dotenv())  # Load environment variables from .env file<br><br>router = APIRouter()<br><br>stripe.api_key = os.environ[&#39;STRIPE_SECRET_KEY&#39;]<br><br>@router.post(&quot;/stripe-webhook&quot;)<br>async def stripe_webhook(request: Request, db: Session = Depends(get_db)):<br>    payload = await request.body()<br>    sig_header = request.headers.get(&quot;stripe-signature&quot;)<br>    endpoint_secret = os.environ[&#39;STRIPE_WEBHOOK_SECRET&#39;]<br><br>    try:<br>        event = stripe.Webhook.construct_event(<br>            payload, sig_header, endpoint_secret<br>        )<br>    except ValueError:<br>        # Invalid payload<br>        raise HTTPException(status_code=400, detail=&quot;Invalid payload&quot;)<br>    except stripe.error.SignatureVerificationError:<br>        # Invalid signature<br>        raise HTTPException(status_code=400, detail=&quot;Invalid signature&quot;)<br><br>    if event[&#39;type&#39;] == &#39;checkout.session.completed&#39;:<br>        session = event[&#39;data&#39;][&#39;object&#39;]<br><br>        # Extract relevant data<br>        customer_email = session[&#39;metadata&#39;][&#39;app_email&#39;]  # Extract email from metadata as email entered on stripe can be different<br>        subscription_id = session.get(&#39;subscription&#39;)<br>        customer_id = session[&#39;customer&#39;]<br>        <br>        # Retrieve the subscription<br>        subscription = stripe.Subscription.retrieve(subscription_id)<br><br>        # Extract subscription details<br>        current_period_end = datetime.fromtimestamp(subscription[&#39;current_period_end&#39;])<br>        trial_end = datetime.fromtimestamp(subscription[&#39;trial_end&#39;]) if subscription[&#39;trial_end&#39;] else None<br>        subscription_status = subscription[&#39;status&#39;]<br><br>        # Retrieve the product associated with the subscription item<br>        product_id = subscription[&#39;plan&#39;][&#39;product&#39;]<br>        product = stripe.Product.retrieve(product_id)<br><br>        # Extract product details<br>        product_name = product[&#39;name&#39;]<br><br>        # Fetch profile from the database using email<br>        profile = db.query(Profile).filter(Profile.email == customer_email).first()<br><br>        if profile:<br>            # Update profile with Stripe details<br>            profile.stripe_customer_id = customer_id<br>            profile.stripe_subscription_id = subscription_id<br>            profile.subscription_plan = product_name<br>            profile.subscription_status = subscription_status<br>            profile.current_period_end = current_period_end<br>            profile.trial_end = trial_end<br><br>            # Commit the changes to the database<br>            db.commit()<br>        else:<br>            raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=&quot;Profile not found&quot;)<br><br>    # Additional event types can be handled here<br>    else:<br>        print(f&quot;Unhandled event type: {event[&#39;type&#39;]}&quot;)<br><br>    db.commit()<br><br>    return {&quot;status&quot;: &quot;success&quot;}</pre><h4>FastAPI Main File</h4><p>Your main.py or the entry point of your FastAPI application should include the necessary routers:</p><pre>from fastapi import FastAPI<br>from app.routers import stripe_webhook  # Import the router we created<br><br>...<br><br>app = FastAPI()<br># Include the Stripe webhook router<br>app.include_router(stripe_webhook.router, prefix=&quot;/api&quot;)<br><br># Other routers and app configurations<br>...</pre><h3>Testing the Webhook in Isolation</h3><p>To test the webhook in isolation, you can use the Stripe CLI:</p><p><strong>Install Stripe CLI:</strong></p><pre>brew install stripe/stripe-cli/stripe</pre><p><strong>Login to Stripe CLI:</strong></p><pre>stripe login</pre><p><strong>Start a Listener:</strong></p><pre>stripe listen --forward-to localhost:8000/api/stripe-webhook</pre><p>This will give you a webhook secret key. Copy that key and paste it into your backend .env file:</p><pre>STRIPE_WEBHOOK_SECRET=your-webhook-secret</pre><p><strong>Trigger an Event for Testing:</strong> In another terminal, you can trigger a test event to see if the webhook is functioning properly.</p><pre>stripe trigger checkout.session.completed</pre><h3>Testing the Entire Process</h3><p>To test the entire subscription process, you can host your backend using ngrok:</p><p><strong>Install Ngrok:</strong></p><pre>brew install --cask ngrok</pre><p><strong>Start Ngrok Server:</strong></p><pre>ngrok http 8000</pre><p><strong>Create a Webhook in Stripe Dashboard:</strong></p><ul><li>Go to the Stripe dashboard.</li><li>Create a new webhook endpoint with your ngrok URL.</li><li>Select the events you want to listen to, such as checkout.session.completed and customer.subscription.deleted.</li><li>customer.subscription.deleted event is triggered when subscription is canceled. In our case, we are having a separate endpoint to handle cancellation. So, this event is not necessary. The reason for keeping this endpoint is to handle subscription cancellation when the cancellation is done from Stripe dashboard.</li><li>Copy the webhook secret key and add it to your backend .env file:</li></ul><pre>STRIPE_WEBHOOK_SECRET=your-webhook-secret</pre><p>By following these steps, you can test the Stripe webhook in isolation or as part of the entire subscription process, ensuring everything works smoothly from payment to subscription management in your application.</p><h3>Summary</h3><p>In this blog, we explored how to implement subscription services using Stripe, Supabase, Next.js, and FastAPI. We started by setting up Stripe in the frontend using Next.js, where users can select a subscription plan and initiate the payment process. We also implemented backend APIs in FastAPI to handle the creation of Stripe checkout sessions and subscription cancellations. Additionally, we set up a Stripe webhook in the FastAPI backend to listen for successful payment events and update the user’s subscription status in the Supabase database. The entire process was tested using Stripe CLI and ngrok for local development. This guide provides a comprehensive approach to managing subscriptions in a modern web application.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=666e1aada1b5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building LLM SaaS Products Made Easy]]></title>
            <link>https://blog.gopenai.com/building-llm-saas-products-made-easy-5966be94d8d2?source=rss-3a9917adb75b------2</link>
            <guid isPermaLink="false">https://medium.com/p/5966be94d8d2</guid>
            <category><![CDATA[supabase]]></category>
            <category><![CDATA[nextjs]]></category>
            <category><![CDATA[openai]]></category>
            <category><![CDATA[fastapi]]></category>
            <category><![CDATA[langchain]]></category>
            <dc:creator><![CDATA[Ojas Kapre]]></dc:creator>
            <pubDate>Wed, 21 Aug 2024 05:28:07 GMT</pubDate>
            <atom:updated>2024-08-23T10:36:25.262Z</atom:updated>
            <content:encoded><![CDATA[<p>In this blog, we’ll walk through building a Language Learning Model (LLM) Software-as-a-Service (SaaS) product using a comprehensive starter template that combines Next.js, Supabase, Langchain, and FastAPI. This setup allows developers to quickly build and deploy applications that leverage powerful LLM models from OpenAI. We’ll explore the tools used, the end-to-end flow, key features, and database schemas, providing a clear guide to creating your own LLM-based SaaS products.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FS9gz3kuqgXM&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DS9gz3kuqgXM&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=google" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/2084c4d3f49f135e87b136d8124a8acb/href">https://medium.com/media/2084c4d3f49f135e87b136d8124a8acb/href</a></iframe><p>This application is designed to provide a strong foundation for building LLM (Large Language Model) SaaS products with minimal setup and customization. The frontend is ready to use out of the box, featuring a fully functional interface with built-in user authentication, chat functionality, and other essential features like Markdown support, chat history, and more. You don’t need to make any changes to the frontend; it’s already equipped to support a wide range of LLM applications.</p><h4>Backend Customization</h4><p>The only customization required is in the backend, specifically in the chat_service.py file located in the /app/service folder. This file currently implements a simple chain using Langchain, but you can easily replace or extend this to build more complex RAGs (Retrieval-Augmented Generation) or any other LLM applications. By modifying this single file, you can tailor the application&#39;s behavior to fit your specific use case, whether it&#39;s question-answering, content generation, or any other AI-driven functionality.</p><h3>Overview</h3><p>The project is a fully-fledged chatbot application with a modern tech stack that includes:</p><ul><li><strong>Next.js</strong>: Handles the frontend and server-side rendering.</li><li><strong>TypeScript</strong>: Adds static types, making the development process more robust.</li><li><strong>Supabase</strong>: Manages user authentication and real-time database services.</li><li><strong>Langchain</strong>: Facilitates working with language models in a structured way.</li><li><strong>FastAPI</strong>: Powers the backend API, handling requests and responses to/from OpenAI’s GPT model.</li><li><strong>SQLAlchemy</strong>: Manages the database layer, ensuring data integrity and easy interaction with the database.</li></ul><p>This architecture ensures a clean separation of concerns, with the frontend managing user interactions and the backend focusing on processing data and communicating with the AI model.</p><h4>Alternative Setup</h4><p>If needed, you don’t have to use the FastAPI backend at all. All LLM requests can be made directly using langchain.js, @langchain/openai, @langchain/community, openai, and the Vercel AI SDK. This alternative setup simplifies the architecture by keeping everything within the frontend, which can be advantageous for certain use cases where you want to minimize backend complexity.</p><p>For alternative set up, follow these <a href="https://github.com/ojasskapre/nextjs-starter-template/tree/main?tab=readme-ov-file#alternative-setup-not-using-fastapi">steps in the Readme</a></p><h3>Key Features</h3><ul><li><strong>Real-time Chat</strong>: Users can interact with the AI model in real time.</li><li><strong>User Authentication</strong>: Includes robust user management with Supabase for sign-up, login, and session handling.</li><li><strong>Stop Answer Streaming</strong>: Users can stop the AI’s response while it’s streaming.</li><li><strong>Chat History Management</strong>: Users can save chat history, access previous chats, and continue conversations from where they left off. Users can also delete a particular chat conversation or change the title for conversation for easy recollection.</li><li><strong>Markdown Support</strong>: Supports Markdown formatting, including LaTeX for mathematical expressions.</li><li><strong>API Backend</strong>: The FastAPI backend is responsible for chat processing and managing interactions with the GPT model.</li></ul><h3>Getting Started</h3><p>The repository is divided into two main sections: the frontend (Next.js) and the backend (FastAPI). The steps to set up the application is mentioned in the Readme files — <a href="https://github.com/ojasskapre/nextjs-starter-template/tree/main/backend#database-schema">Database Set Up</a>, <a href="https://github.com/ojasskapre/nextjs-starter-template/tree/main?tab=readme-ov-file#getting-started">Application Set Up</a>.</p><h3>Tools and Technologies</h3><p>This project leverages several key technologies:</p><ul><li><strong>Supabase</strong>: Provides a PostgreSQL database with authentication and real-time capabilities. It’s a crucial component for managing user data and chat histories.</li><li><strong>Langchain</strong>: Facilitates the interaction with language models, making it easier to build applications that use AI models for text generation, conversation, and more.</li><li><strong>FastAPI</strong>: A modern, high-performance web framework for building APIs with Python 3.11+. It’s used here to handle API requests, manage the database, and interact with the OpenAI model.</li><li><strong>SQLAlchemy</strong>: This ORM tool manages database models and queries, making it easier to work with relational databases in Python.</li><li><strong>Tailwind CSS</strong>: A utility-first CSS framework for styling.</li><li><strong>Shadcn</strong>: A component library for creating accessible and consistent UI components.</li><li><strong>Vercel AI SDK</strong>: A set of tools and utilities provided by Vercel for building AI-driven applications.</li></ul><h3>Database Schema</h3><p>The database schema is designed to support user authentication and chat management. Here’s a brief overview:</p><ul><li><strong>Profiles Table</strong>: Stores essential user information, linked to Supabase’s auth.users table.</li><li><strong>Chat Sessions Table</strong>: Each chat session represents a distinct conversation, with a unique ID, user ID, title, and timestamps for creation and updates.</li><li><strong>Messages Table</strong>: Stores messages exchanged during chat sessions, including the role (user or assistant) and content of each message.</li></ul><p>For more detailed information about the database schema, visit the backend’s README file in the <a href="https://github.com/ojasskapre/nextjs-starter-template/tree/main/backend#database-schema">GitHub repository</a>.</p><h3>API Routes</h3><p>The application includes several API routes to manage chat sessions and messages. These routes are protected by JWT authentication, ensuring that only authenticated users can access them.</p><p>Some key routes include:</p><ul><li><strong>Start a New Chat Session</strong>: Initiates a new conversation.<br>Path: /api/chat [POST]</li><li><strong>Get Chat History</strong>: Retrieves the message history for a specific chat session.<br>Path: /api/sessions/{session_id} [GET]</li><li><strong>Continue an Existing Chat Session</strong>: Adds a new message to an existing chat session.<br>Path: /api/sessions/{session_id} [POST]</li><li><strong>Get All Chat Sessions</strong>: Lists all chat sessions for the authenticated user.<br>Path: /api/sessions [GET]</li><li><strong>Update Chat Session Title</strong>: Allows users to rename their chat sessions.<br>Path: /api/sessions/{session_id}/title [PATCH]</li><li><strong>Delete a Chat Session</strong>: Removes a chat session and its associated messages.<br>Path: /api/sessions/{session_id} [DELETE]</li></ul><h3>Conclusion</h3><p>This blog has covered the end-to-end setup of an LLM SaaS product using Next.js, Supabase, Langchain, and FastAPI. By following the steps outlined above, you can quickly create a robust, scalable chatbot application with real-time chat capabilities, secure user authentication, and a clean separation of frontend and backend responsibilities. The starter template provided in the <a href="https://github.com/ojasskapre/nextjs-starter-template">GitHub repository</a> offers a solid foundation for building and extending your own LLM-based SaaS products.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5966be94d8d2" width="1" height="1" alt=""><hr><p><a href="https://blog.gopenai.com/building-llm-saas-products-made-easy-5966be94d8d2">Building LLM SaaS Products Made Easy</a> was originally published in <a href="https://blog.gopenai.com/">GoPenAI</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Implementing Supabase Authentication with Next.js and FastAPI]]></title>
            <link>https://medium.com/@ojasskapre/implementing-supabase-authentication-with-next-js-and-fastapi-5656881f449b?source=rss-3a9917adb75b------2</link>
            <guid isPermaLink="false">https://medium.com/p/5656881f449b</guid>
            <category><![CDATA[nextjs]]></category>
            <category><![CDATA[fastapi]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[authentication]]></category>
            <category><![CDATA[supabase]]></category>
            <dc:creator><![CDATA[Ojas Kapre]]></dc:creator>
            <pubDate>Wed, 21 Aug 2024 04:51:27 GMT</pubDate>
            <atom:updated>2024-08-21T04:51:27.488Z</atom:updated>
            <content:encoded><![CDATA[<p>In this blog, we’ll dive into how to set up authentication using Supabase in a Next.js application and handle JWT verification in a FastAPI backend. This approach ensures that your users are authenticated securely while enabling a seamless interaction between the frontend and backend.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TPAU0oM_7eIqaSuhG9QLTg.png" /></figure><p>We’ll walk through the following steps:</p><ol><li>Setting up Supabase in your Next.js application.</li><li>Handling user authentication in Next.js.</li><li>Verifying JWT tokens in FastAPI.</li></ol><p>Before diving into the authentication setup, ensure you have a Next.js application and Supabase project already set up and configured.</p><h3>Setting Supabase in Next.JS application</h3><p>In this section, we’ll dive into how Supabase authentication is set up in the Next.js application. The implementation leverages both @supabase/ssr and @supabase/supabase-js libraries to handle authentication seamlessly on both the server and client sides. Below, I’ll highlight the key files, functions, and concepts used to achieve this, with links to the corresponding code in the GitHub repository in order to keep this blog brief.</p><p>Don’t forget to fill in your .env file with the necessary SUPABASE_API_KEY and SUPABASE_ANON_KEYvalues to ensure proper configuration of Supabase in your application.</p><h4><strong>Why Use </strong><strong>@supabase/ssr and </strong><strong>@supabase/supabase-js?</strong></h4><ul><li><strong>@supabase/ssr</strong>: This library is essential for creating Supabase clients that handle server-side rendering (SSR) in Next.js, ensuring seamless session management across different environments.</li><li><strong>@supabase/supabase-js</strong>: The core JavaScript library from Supabase, which provides methods to interact with Supabase services, such as authentication, real-time databases, and more.</li></ul><h4><strong>Client-Side Supabase Client (</strong><strong>client.ts)</strong></h4><p><strong>Purpose</strong>: This file initializes and manages the Supabase client on the client side, allowing users to interact with Supabase services directly from the browser.</p><p><strong>Key Function</strong>:</p><ul><li>createBrowserClient: This function, imported from @supabase/ssr, is used to create a Supabase client specifically for browser environments. It’s crucial for handling actions like signing in and managing sessions on the client side.</li></ul><p>You can check out the complete implementation of the <a href="https://github.com/ojasskapre/nextjs-starter-template/blob/main/frontend/src/utils/supabase/client.ts">client-side Supabase client here</a>.</p><h4><strong>Server-Side Supabase Client (</strong><strong>server.ts)</strong></h4><p><strong>Purpose</strong>: This file is responsible for managing the Supabase client on the server side, ensuring secure and consistent session management across SSR pages and API routes.</p><p><strong>Key Function</strong>:</p><ul><li>createServerClient: This function, also from @supabase/ssr, creates a Supabase client for server-side operations. It handles cookies and session management on the server, which is crucial for SSR in Next.js.</li></ul><p>For the full code, see the <a href="https://github.com/ojasskapre/nextjs-starter-template/blob/main/frontend/src/utils/supabase/server.ts">server-side Supabase client implementation</a>.</p><h4><strong>Session Management Middleware (</strong><strong>middleware.ts)</strong></h4><p><strong>Purpose</strong>: This middleware manages user sessions and handles redirects based on the authentication state. It’s particularly useful for ensuring that logged-in users are redirected appropriately and that sessions are refreshed as needed.</p><p><strong>Key Function</strong>:</p><ul><li>createServerClient: Similar to server.ts, this function creates a server-side Supabase client to manage cookies and sessions.</li><li>NextResponse: A utility from Next.js used to manage HTTP responses, including redirects, based on authentication status.</li></ul><p>Check out the full <a href="https://github.com/ojasskapre/nextjs-starter-template/blob/main/frontend/src/utils/supabase/middleware.ts">middleware implementation here</a>.</p><h4>Authentication Components</h4><p><strong>Sign In Component (</strong><strong>Login.tsx)</strong></p><p><strong>Purpose</strong>: This component provides the UI and logic for user sign-in using email/password or OAuth providers like Google, Facebook, or GitHub.</p><p><strong>Key Functions</strong>:</p><ul><li>supabase.auth.signInWithPassword: Authenticates users with their email and password.</li><li>supabase.auth.signInWithOAuth: Handles OAuth sign-in for providers.</li></ul><p>For a detailed look at the sign-in process, see the <a href="https://github.com/ojasskapre/nextjs-starter-template/tree/main/frontend/src/app/login">Sign In component code</a>.</p><p><strong>Sign Up Component (</strong><strong>SignUp.tsx)</strong></p><p><strong>Purpose</strong>: This component allows users to create a new account using their email and password, with support for OAuth sign-ups.</p><p><strong>Key Functions</strong>:</p><ul><li>supabase.auth.signUp: Registers a new user and sends an activation link to their email.</li><li>supabase.auth.signInWithOAuth: Handles OAuth sign-up for providers.</li></ul><p>You can view the full <a href="https://github.com/ojasskapre/nextjs-starter-template/tree/main/frontend/src/app/signup">Sign Up component implementation here</a>.</p><p><strong>OAuth Button Component (</strong><strong>OAuthButton.tsx)</strong></p><p><strong>Purpose</strong>: This is a reusable button component for OAuth sign-ins. It dynamically changes its icon and label based on the selected provider (Google, GitHub, or Facebook).</p><p>Explore the <a href="https://github.com/ojasskapre/nextjs-starter-template/blob/main/frontend/src/components/OAuthButton.tsx">OAuth Button component</a>.</p><p><strong>Authentication Callback Handling (</strong><strong>auth/callback/route.ts)</strong></p><p><strong>Purpose</strong>: This route handles OAuth callback responses and exchanges the authorization code for a session token. This ensures that the user is authenticated and redirected to the appropriate page.</p><p>For the full implementation, visit the <a href="https://github.com/ojasskapre/nextjs-starter-template/blob/main/frontend/src/app/auth/callback/route.ts">authentication callback route code</a>.</p><p><strong>Managing User Sessions with Context (</strong><strong>AuthContext.tsx)</strong></p><p><strong>Purpose</strong>: This context provides a global state to manage user authentication across the application. It allows any component to access the user’s authentication state and perform actions like logging out or retrieving the session token.</p><p><strong>Key Functions</strong>:</p><ul><li>supabase.auth.getUser: Retrieves the current user’s session and authentication state.</li><li>supabase.auth.onAuthStateChange: Listens for changes in the user’s authentication state.</li></ul><p>Check out the full <a href="https://github.com/ojasskapre/nextjs-starter-template/blob/main/frontend/src/context/AuthContext.tsx">AuthContext implementation</a>.</p><h3>Verifying JSON Web Tokens in FastAPI</h3><p>In this section, we’ll walk through how to set up JSON Web Token (JWT) verification in FastAPI, using Supabase for authentication and integrating it with your chat application. We’ll use the supabase-py library to handle user authentication and verification seamlessly.</p><p>Before diving into the implementation, ensure you’ve set up the project by following the instructions in the <a href="https://github.com/ojasskapre/nextjs-starter-template/tree/main/backend">README file in the backend folder</a>.</p><p>For the purpose of this blog, you can ignore anything related to database initialization or database tables creation as it not relevant to setting up supabase auth verification</p><h4>Libraries Used</h4><ul><li><strong>supabase-py</strong>: This is a Python client library for Supabase, used to interact with the Supabase backend for user authentication, database interactions, and more.</li></ul><h4>Setting Up the FastAPI Application</h4><p>In the app/main.py file, the FastAPI application is initialized, CORS middleware is configured, and the necessary database tables are created using SQLAlchemy. This setup is crucial for enabling smooth communication between the frontend and backend, especially when they are hosted on different domains.</p><p><strong>Key Points:</strong></p><ul><li><strong>CORS Middleware</strong>: This middleware allows cross-origin requests, which is essential when the frontend and backend are not on the same domain.</li><li><strong>Database Initialization</strong>: The create_tables() function is called on startup to ensure that the database schema is ready, with tables for profiles, chat sessions, and messages.</li></ul><p>Check out the <a href="http://arter-template/blob/main/backend/app/main.py">FastAPI application setup code here</a>.</p><p><strong>1. Supabase Client Creation</strong></p><p>The first step in verifying JWTs is to create a Supabase client that can interact with Supabase’s authentication services. This is done using the create_client() function. The Supabase client is initialized with the Supabase URL and API key, which are retrieved from the environment variables.</p><pre>SUPABASE_URL = os.environ[&quot;SUPABASE_URL&quot;]<br>SUPABASE_KEY = os.environ[&quot;SUPABASE_ANON_KEY&quot;]<br><br>supabase: Client = create_client(SUPABASE_URL, SUPABASE_KEY)</pre><ul><li><strong>Why This is Important</strong>: The Supabase client acts as a bridge between your FastAPI backend and Supabase’s authentication services. It enables your backend to perform operations such as verifying JWTs and managing user sessions.</li></ul><p><strong>2. JWT Verification</strong></p><p>The core of the authentication process lies in the verify_jwt() function. This function is designed to extract the JWT from the request&#39;s Authorization header and verify its validity with Supabase.</p><pre>def verify_jwt(credentials: HTTPAuthorizationCredentials = Depends(security)):<br>    token = credentials.credentials<br>    try:<br>        user = supabase.auth.get_user(token)<br>        if not user:<br>            raise HTTPException(status_code=401, detail=&quot;Invalid token&quot;)<br>        return user<br>    except Exception as e:<br>        raise HTTPException(status_code=401, detail=str(e))</pre><p><strong>How It Works</strong>:</p><ol><li><strong>Token Extraction</strong>: The JWT is extracted from the Authorization header using the HTTPBearer security scheme.</li><li><strong>Token Verification</strong>: The extracted token is then passed to Supabase’s auth.get_user() method, which verifies the token&#39;s validity. If the token is valid, the user associated with the token is returned.</li><li><strong>Error Handling</strong>: If the token is invalid or expired, an HTTPException with a 401 status code is raised, indicating that the request is unauthorized.</li></ol><p><strong>Why This is Important</strong>: This function is crucial for securing your API endpoints. By verifying the JWT, you ensure that only authenticated users can access certain routes, protecting sensitive data and functionality from unauthorized access.</p><p>You can find the <a href="https://github.com/ojasskapre/nextjs-starter-template/blob/main/backend/app/dependencies.py">dependency code for JWT verification here</a>.</p><h4>Using JWT Verification dependency in API Routes</h4><p>In app/dependencies.py, JWT verification is implemented using the supabase-py library, ensuring that only authenticated users can access protected routes.</p><p><strong>Key Functionalities:</strong></p><ul><li><strong>Supabase Client Creation</strong>: The Supabase client is initialized with the create_client() function, using the Supabase URL and API key.</li><li><strong>JWT Verification</strong>: The verify_jwt() function extracts the JWT from the request&#39;s authorization header, verifies it with Supabase&#39;s auth.get_user() method, and ensures the token is valid. If the token is invalid, it raises an HTTP 401 Unauthorized error.</li></ul><p>This dependency is then used throughout the application to protect routes and ensure that only authenticated users can access certain endpoints.</p><h4>Using JWT Verification in API Routes</h4><p>In app/api/routers/chat.py, the verify_jwt dependency is applied to various API routes to ensure that only authenticated users can interact with the chat sessions and messages.</p><p><strong>Key Points:</strong></p><ul><li><strong>Route Protection</strong>: Each route that requires user authentication uses user=Depends(verify_jwt) to enforce JWT verification.</li><li><strong>User Verification</strong>: In routes like start_chat, continue_chat, and delete_chat_session, the authenticated user is verified against the session they are trying to interact with, ensuring that users can only manage their own sessions.</li></ul><p>By leveraging the verify_jwt dependency across your API routes, you ensure that your application securely handles user authentication and protects user data.</p><p>You can find the <a href="https://github.com/ojasskapre/nextjs-starter-template/blob/main/backend/app/api/routers/chat.py">full code for the protected routes here</a>.</p><p>This setup effectively ties together Supabase’s authentication capabilities with FastAPI’s powerful dependency injection system, creating a secure and scalable chat application.</p><h3>Conclusion</h3><p>In this blog, we walked through the implementation of authentication using Supabase in a Next.js application and how to handle JWT verification in a FastAPI backend. This setup ensures secure user authentication while enabling smooth interaction between the frontend and backend, creating a robust and scalable chat application.</p><p><strong>Key Takeaways:</strong></p><ol><li><strong>Setting Up Supabase in Next.js</strong>: We explored the process of integrating Supabase authentication into a Next.js application, using both @supabase/ssr and @supabase/supabase-js libraries to manage sessions and user authentication seamlessly across client and server environments.</li><li><strong>Verifying JWT Tokens in FastAPI</strong>: On the backend, we implemented JWT verification using the supabase-py library within FastAPI. This ensures that only authenticated users can access protected routes, securing the application’s sensitive data and functionality.</li><li><strong>Combining Frontend and Backend Security</strong>: By integrating Supabase with both Next.js and FastAPI, we created a secure, full-stack application where user authentication and session management are handled efficiently.</li></ol><p>This approach demonstrates the power of combining modern web frameworks like Next.js and FastAPI with Supabase’s comprehensive authentication services, providing a strong foundation for building secure, scalable applications.</p><p>For a complete code implementation and further details, refer to the respective files in the <a href="https://github.com/ojasskapre/nextjs-starter-template">GitHub repository</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5656881f449b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Fixing Input Focus Issues in a Shadcn/Radix UI Card & UI Dropdown Menu in Next.js]]></title>
            <link>https://medium.com/@ojasskapre/fixing-input-focus-issues-in-a-shadcn-radix-card-ui-dropdown-menu-in-next-js-7b5931e049c8?source=rss-3a9917adb75b------2</link>
            <guid isPermaLink="false">https://medium.com/p/7b5931e049c8</guid>
            <category><![CDATA[ui]]></category>
            <category><![CDATA[ux]]></category>
            <category><![CDATA[nextjs]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[tailwind-css]]></category>
            <dc:creator><![CDATA[Ojas Kapre]]></dc:creator>
            <pubDate>Tue, 20 Aug 2024 21:55:59 GMT</pubDate>
            <atom:updated>2024-08-20T22:03:27.486Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction:</h3><p>While building a feature in my Next.js project using Shadcn (Radix UI), and Tailwind CSS, I encountered a frustrating issue. I had a card component (as shown in below image) with a title and an options icon button. The button triggered a dropdown menu and a tooltip. One of the dropdown options was to rename the title, and I wanted the input field to focus automatically when “Rename” was clicked.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/452/1*dRFa_nqW3A0Frqeqx1B85g.png" /><figcaption>Card’s component layout</figcaption></figure><p><strong>What I Was Building:</strong> The card component’s layout included:</p><ul><li>A title displayed inside the card.</li><li>An options icon button (Ellipsis) within the card content, triggering both a dropdown menu and a tooltip.</li><li>The dropdown menu had options like “Rename” and “Delete.”</li><li>When “Rename” was clicked, an input field appeared, and I needed it to focus immediately.</li></ul><p><strong>Initial Solution:</strong> To achieve this, I used the useRef hook to reference the input field and useEffect to focus on it when &quot;Rename&quot; was clicked:</p><pre>...<br><br>const renameInputRef = useRef&lt;HTMLInputElement | null&gt;(null);<br><br>...<br><br>useEffect(() =&gt; {<br>  if (editingSessionId &amp;&amp; renameInputRef.current) {<br>    setTimeout(() =&gt; {<br>      renameInputRef.current.focus();<br>    }, 10);<br>  }<br>}, [editingSessionId]);</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/456/1*WEDAwyihLzEHRX8vXRdYvg.gif" /></figure><p><strong>The Issue:</strong> The input was getting focused, but immediately after, the focus shifted back to the options button. This issue became apparent after adding the setTimeout in the useEffect. The dropdown menu was closing and automatically focusing back on the trigger button.</p><p><strong>The Solution:</strong> After checking the <a href="https://www.radix-ui.com/primitives/docs/components/dropdown-menu#content">documentation</a> for Radix UI, I discovered the root cause. The DropdownMenuContent component has an onCloseAutoFocus prop, which controls the focus behavior when the dropdown closes. The default behavior was causing the focus to return to the button.</p><p>By preventing the default focus behavior in the onCloseAutoFocus handler, I ensured that the input field remained focused:</p><pre>&lt;DropdownMenuContent<br>  align=&quot;end&quot;<br>  className=&quot;dark:bg-neutral-900 p-2&quot;<br>  onCloseAutoFocus={(e) =&gt; e.preventDefault()}  // Prevent auto focus on close<br>&gt;<br>  {/* Menu items go here */}<br>&lt;/DropdownMenuContent&gt;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/456/1*y4kJxF2Q1U3gLl7YOPj-DQ.gif" /></figure><p><strong>Further Changes:</strong> If you still want the button to auto-focus when closing the dropdown in cases other than clicking “Rename,” you can add appropriate conditions in the onCloseAutoFocus handler to selectively prevent the default behavior.</p><p><strong>Conclusion:</strong> This simple adjustment in the onCloseAutoFocus prop resolved my issue and allowed the input field to remain focused after clicking &quot;Rename.&quot; Remember, reading the documentation is crucial — LLMs can assist with many problems, but they won’t always have the specific answers you need. If you&#39;re facing a similar problem, I hope this quick solution helps you out!</p><p>For more details on this prop, you can refer to the official documentation: <a href="https://www.radix-ui.com/primitives/docs/components/dropdown-menu#content">Radix UI DropdownMenuContent</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7b5931e049c8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building Video Q&A application using Langchain, OpenAI Whisper, GPT 3.5, Pinecone and Streamlit]]></title>
            <link>https://medium.com/@ojasskapre/building-video-q-a-application-using-langchain-openai-whisper-gpt-3-5-pinecone-and-streamlit-e24dabefb9f8?source=rss-3a9917adb75b------2</link>
            <guid isPermaLink="false">https://medium.com/p/e24dabefb9f8</guid>
            <category><![CDATA[streamlit]]></category>
            <category><![CDATA[openai]]></category>
            <category><![CDATA[gpt]]></category>
            <category><![CDATA[langchain]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Ojas Kapre]]></dc:creator>
            <pubDate>Wed, 29 May 2024 17:20:43 GMT</pubDate>
            <atom:updated>2024-05-29T17:20:43.038Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>In this blog post, we will build a Video Q&amp;A application using <strong>LangChain</strong>, <strong>OpenAI Whisper, GPT-3.5, Pinecone, and Streamlit</strong>. This application is a multi-page Streamlit application that allows users to upload videos, transcribe their audio, create embeddings for the transcriptions, and interact with the video content through a chat interface. By following along, you’ll learn how to process video uploads, generate transcriptions, and enable interactive querying of video content.</p><p><strong>GitHub Repository</strong> — <a href="https://github.com/ojasskapre/langchain-apps/tree/main/chat-with-video">https://github.com/ojasskapre/langchain-apps/tree/main/chat-with-video</a></p><p>In this blog, we will explore the overall approach, detailed installation and usage instructions, and the lessons learned during the development of this application.</p><h3>Demo</h3><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FjAmMG8sjI5c&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DjAmMG8sjI5c&amp;image=http%3A%2F%2Fi.ytimg.com%2Fvi%2FjAmMG8sjI5c%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/51121cfefc362fb26301835d59565f93/href">https://medium.com/media/51121cfefc362fb26301835d59565f93/href</a></iframe><p>Take a look at <a href="https://smith.langchain.com/public/966249c8-086b-47c7-9d34-71db94517ccc/r">LangSmith Trace</a> for observing the chain.</p><h3>Approach</h3><p>In this section, we will detail the two main components of the application: Video Processing and the QA Process. Each component involves multiple steps to ensure smooth and efficient operation.</p><p>For the application, I have used the following libraries:</p><pre>langchain<br>langchain_community<br>langchain-openai<br>openai<br>python-dotenv<br>ffmpeg<br>requests<br>streamlit<br>ffmpeg-python<br>langchain-pinecone</pre><h4>Video Processing Overview</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*7kejwYFrnbRm-lnU.png" /></figure><ul><li>User uploaded video is converted into audio first as Whisper API only accepts audio files. I have ffmpeg-python library for extracting audio from video</li></ul><pre>def extract_audio(video_path, audio_path):<br>    &quot;&quot;&quot;Extract audio from video and save it as a temporary file.&quot;&quot;&quot;<br>    try:<br>        (<br>            ffmpeg<br>            .input(video_path)<br>            .output(audio_path, format=&#39;mp3&#39;, acodec=&#39;mp3&#39;)<br>            .run(overwrite_output=True, quiet=True)<br>        )<br>        print(f&quot;Audio extracted to {audio_path}&quot;)<br>    except ffmpeg.Error as e:<br>        print(f&quot;Error extracting audio: {e}&quot;)<br>        raise</pre><ul><li>If the audio file size exceeds 25 MB, it is split into smaller chunks using ffmpeg-python as Whisper API has file size limit of 25MB</li></ul><pre>def split_audio(audio_path, chunk_dir, chunk_size=25*1024*1024):<br>    &quot;&quot;&quot;Split audio file into chunks less than 25MB.&quot;&quot;&quot;<br>    print(&quot;Splitting audio into chunks...&quot;)<br>    os.makedirs(chunk_dir, exist_ok=True)<br>    chunks = []<br>    try:<br>        input_audio = ffmpeg.input(audio_path)<br>        duration = float(ffmpeg.probe(audio_path)[&#39;format&#39;][&#39;duration&#39;])<br>        num_chunks = int(duration // (chunk_size / get_file_size(audio_path) * duration))<br>        print(&quot;Number of Chunks: &quot;, num_chunks)<br>        for i in range(num_chunks + 1):<br>            chunk_path = os.path.join(chunk_dir, f&quot;chunk_{i}.mp3&quot;)<br>            start_time = i * duration / (num_chunks + 1)<br>            ffmpeg.output(input_audio, chunk_path, ss=start_time, t=duration / (num_chunks + 1)).run(overwrite_output=True, quiet=True)<br>            chunks.append(chunk_path)<br>    except ffmpeg.Error as e:<br>        print(f&quot;Error splitting audio: {e}&quot;)<br>        raise<br>    return chunks</pre><ul><li>Each audio chunk is transcribed into text using the OpenAI Whisper API and is then combined to form complete transcription of the video</li><li>The transcription is splitted into smaller documents using Langchain&#39;s RecursiveCharacterTextSplitter with a chunk size of 1000 and an overlap of 100. This is useful for indexing the data and passing smaller chunks to the model ensuring precise answer to the query and to be within model’s context window.</li><li>Each text chunk is converted into embeddings using OpenAI’s text-embedding-ada-002 model.</li><li>Embeddings along with video name as metadata is stored in Pinecone Vector DB so that we can query that video anytime.</li></ul><h4>Q&amp;A Process Overview</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*4ZBiRZAiThaIMHwf.png" /></figure><ul><li>The user selects one or more videos and asks a question related to the video content.</li><li>The query is converted into embeddings using OpenAI’s text-embedding-ada-002 model.</li><li>The embedded query is used to retrieve similar documents from Pinecone, filtered based on the selected videos.</li></ul><pre>retriever = vectorstore.as_retriever(<br>    search_kwargs={&quot;filter&quot;: {&quot;video_filename&quot;: {&quot;$in&quot;: selected_videos}}}<br>)</pre><ul><li>The retrieved documents are compiled to form the context needed to answer the query.</li></ul><pre>def format_docs(docs):<br>  &quot;&quot;&quot;Format the documents for the RAG model.&quot;&quot;&quot;<br>  if not docs:<br>    return &quot;I&#39;m sorry, but I don&#39;t have enough information from the provided videos to answer that question.&quot;<br><br>  # Extract unique video filenames from the metadata<br>  video_filenames = {doc.metadata[&#39;video_filename&#39;] for doc in docs}<br><br>  # Join the page content of all documents<br>  formatted_text = &quot;\n\n&quot;.join(doc.page_content for doc in docs)<br>  <br>  # Format the video filenames as references<br>  references = &quot;\n\nReferences:\n&quot; + &quot;\n&quot;.join(video_filenames)<br>  <br>  return formatted_text + references</pre><ul><li>A custom ChatPromptTemplate and QAChain are used to process the context and query.</li></ul><p><strong>Prompts Explained</strong></p><p><strong><em>System Prompt</em></strong></p><blockquote>&quot;You are an intelligent assistant designed to help users answer questions based on the content of videos. &quot;<br>&quot;You have access to transcriptions of these videos, and you can search through these transcriptions to find the most relevant information. &quot;<br>&quot;Use the provided transcription texts to answer the user&#39;s questions accurately and concisely.&quot;</blockquote><p>The system prompt establishes the AI’s role and capabilities, indicating that it is an intelligent assistant designed to help users answer questions based on video content. It instructs the AI to use video transcriptions to find and provide accurate and concise answers.</p><p><strong><em>User Prompt</em></strong></p><blockquote>&#39;The user has selected the following video contexts for reference:\n\n&quot;&quot;&quot;{context}&quot;&quot;&quot;\n\n&#39;<br>&#39;Based on the above contexts, answer the following question:\n\n&#39;<br>&#39;&quot;{question}&quot;\n\n&#39;<br>&#39;The context also includes the video references at the end.&#39;<br>&#39;Return the answer in the json format with one key as &quot;answer&quot; and other key as &quot;references&quot; which is video references as list of strings:\n\n&#39;<br>&#39;Make sure to cover as much relevant information from the provided contexts in your answer.&#39;<br>&#39;If context is not provided or you don\&#39;t know the answer or the information is not available in the contexts, please respond with &quot;I\&#39;m sorry, but I don\&#39;t have enough information from the provided videos to answer that question.&quot; and return empty reference list.&#39;<br>&#39;Please do your best, this is very important to my career.&#39;</blockquote><p>The user prompt provides specific instructions for generating responses, including using selected video contexts to answer user questions. It specifies the response format (JSON with “answer” and “references”) and includes a fallback message if sufficient information is not available, ensuring structured and relevant answers.</p><ul><li>The context and query are passed to the prompt, which uses the OpenAI GPT-3.5 model to generate a response.</li><li>The response is returned in JSON format, including the answer and references to the relevant video segments.</li></ul><pre>response = {<br>  &quot;answer&quot;: &quot; ... &quot;,<br>  &quot;references&quot;: [&quot;video1.mp4&quot;, &quot;video2.mp4&quot;, ...]<br>}</pre><h3>Installation &amp; Usage</h3><ol><li>Clone the repository</li></ol><pre>git clone git@github.com:ojasskapre/langchain-apps.git<br>cd langchain-apps/chat-with-video</pre><p>2. Create a virtual environment and activate it</p><pre>python -m venv env<br>source env/bin/activate</pre><p>3. Install required dependencies</p><pre>pip install -r requirements.txt</pre><p>4. Setup environment variables for OpenAI API key and LangSmith key</p><pre>cp .env.example .env<br># Edit the .env file to include your OpenAI API key and LangSmith key</pre><p>5. Run the streamlit app</p><pre>streamlit run Home.py</pre><h3>Lessons Learned</h3><p>In this project, I learned the importance of effectively handling large files by splitting audio into manageable chunks for processing with the OpenAI Whisper API. We discovered that using Pinecone for storing and retrieving embeddings significantly enhances the speed and accuracy of information retrieval. Additionally, splitting transcriptions into smaller chunks using LangChain’s RecursiveCharacterTextSplitter helps manage context better for more relevant responses. Integrating various technologies like Streamlit for the user interface, OpenAI Whisper for transcription, and Pinecone for vector storage taught us how to seamlessly connect different tools to build a cohesive and efficient application.</p><p>Stay tuned for more exciting LangChain projects. I’ll be sharing additional LangChain developments and also posting more blogs about React and Next.js.</p><p><a href="https://www.linkedin.com/in/ojaskapre/">LinkedIn</a> | <a href="https://github.com/ojasskapre">GitHub</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e24dabefb9f8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a Research Assistant with Langchain, OpenAI GPT-3.5, and Streamlit]]></title>
            <link>https://medium.com/@ojasskapre/building-a-research-assistant-with-langchain-openai-gpt-3-5-and-streamlit-7b32c4bcdf03?source=rss-3a9917adb75b------2</link>
            <guid isPermaLink="false">https://medium.com/p/7b32c4bcdf03</guid>
            <category><![CDATA[openai]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[streamlit]]></category>
            <category><![CDATA[langchain]]></category>
            <dc:creator><![CDATA[Ojas Kapre]]></dc:creator>
            <pubDate>Sat, 25 May 2024 22:32:03 GMT</pubDate>
            <atom:updated>2024-05-29T17:22:05.910Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>Introduction</strong></h3><p>The goal was to understand and build a research assistant from scratch. This research assistant is similar to Tavily AI’s research assistant, but it is built from scratch using Langchain.</p><p>The research assistant works by taking in a topic and then generating a bunch of research questions for that topic. It will then look up these questions online and summarize the web pages that it finds. Finally, it will use all of these summaries to generate a final report.</p><p>My Langchain applications GitHub repo: <a href="https://github.com/ojasskapre/langchain-apps">ojasskapre/langchain-applications</a></p><p>The project was inspired and referred to by LangChain. <a href="https://youtu.be/DjuXACWYkkU?si=Bc9cY87AfYXBceW6">Langchain Youtube</a></p><p>The prompts were used as per the research assistant project on GitHub by assafelovic. <a href="https://github.com/assafelovic/gpt-researcher">GPT Researcher</a></p><h3>Demo</h3><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FCtzieIgcaIA&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DCtzieIgcaIA&amp;image=http%3A%2F%2Fi.ytimg.com%2Fvi%2FCtzieIgcaIA%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/a6b3fd831e3b0a6da3e49db56508c476/href">https://medium.com/media/a6b3fd831e3b0a6da3e49db56508c476/href</a></iframe><h3>Approach</h3><p>In LangChain, a “chain” is a sequence of operations where the output of one step becomes the input for the next. This helps in building complex workflows by linking together multiple functions.</p><p>Here’s an overview of how the different chains in the research assistant work:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*bsVWoADV7qIkY09A" /></figure><p>Let’s go through each chain used in the process, one by one.</p><p><strong>Scrape and Summarize Chain:</strong> The scrape_and_summarize_chain is responsible for extracting and summarizing text content from a given URL. Let’s break down how it works:</p><pre>scrape_and_summarize_chain = RunnablePassthrough.assign(<br>  summary=RunnablePassthrough.assign(<br>    text=lambda x: scrape_text(x[&quot;url&quot;])[:10000]<br>   ) | <br>  SUMMARY_PROMPT | <br>  ChatOpenAI(model=&quot;gpt-3.5-turbo-1106&quot;) | <br>  StrOutputParser()) | <br>  (lambda x: f&quot;URL: {x[&#39;url&#39;]}\n\nSummary: {x[&#39;summary&#39;]}&quot;<br>)</pre><ul><li>The chain starts by scraping the text content from the provided URL using the scrape_text function. The scraped text is then summarized using the gpt-3.5-turbo-1106 model.</li><li>The summary is generated based on the SUMMARY_PROMPT provided. Here’s the summary prompt used:</li></ul><blockquote>&quot;&quot;&quot;{text}<br> - - - - - - - - - -<br>Using the above text, answer in short the following question:<br>&gt; {question}<br> - - - - - - - - - -<br>if the question cannot be answered using the text, simply summarize the text. Include all factual information, numbers, stats, etc.<br>&quot;&quot;&quot;</blockquote><ul><li>Finally, the chain formats the output to include the URL and the generated summary. The result is returned in the following format:</li></ul><blockquote>URL: {url}<br>Summary:<br>{summary}</blockquote><p><strong>Web Search Chain: </strong>The web_search_chain is responsible for performing a web search based on a given question and then scraping and summarizing the results. Here’s how it works:</p><pre>web_search_chain = RunnablePassthrough.assign(<br>  urls=lambda x: web_search(x[&quot;question&quot;])<br>) | (lambda x: [{&quot;question&quot;: x[&quot;question&quot;], &quot;url&quot;: url} for url in x[&quot;urls&quot;]]) | scrape_and_summarize_chain.map()</pre><ul><li>The chain starts by taking a question as input and using the DuckDuckGo Search API to perform a web search. The web_search function returns a list of URLs that are relevant to the question.</li><li>The retrieved URLs are then formatted into a list of dictionaries, where each dictionary contains the original question and a URL. The format looks like this: [{&quot;question&quot;: question, &quot;url&quot;: url}, …]</li><li>Each dictionary in the list is passed to the scrape_and_summarize_chain, which scrapes the text from the URLs and summarizes the content.</li></ul><p><strong>Search Question Chain: </strong>The search_question_chain is designed to generate additional research questions based on a user-provided topic. Here’s how it works:</p><pre>search_question_chain = SEARCH_PROMPT | <br>   ChatOpenAI(model=&quot;gpt-3.5-turbo-1106&quot;, temperature=0) | <br>    StrOutputParser() | json.loads</pre><ul><li>The chain starts by taking a prompt (SEARCH_PROMPT) and uses the gpt-3.5-turbo-1106 model to generate search queries. The model runs with a temperature setting of 0 to ensure the output is deterministic and focused.</li><li>The generated output is then parsed using StrOutputParser to convert it into a string format.</li><li>Finally, the parsed string is converted into a JSON object using json.loads, resulting in a list of search queries. The result is a list of queries formatted as: [“query 1”, “query 2”, “query 3”]</li></ul><p>Here’s the prompt used for generating research questions:</p><blockquote>&#39;Write 3 google search queries to search online that form an objective opinion from the following task: &quot;{question}&quot;&#39; \<br>&#39;Also include in the queries specified task details such as locations, names, etc.\n&#39; \<br>&#39;You must respond with a list of search queries strictly in the following format: [&quot;query 1&quot;, &quot;query 2&quot;, &quot;query 3&quot;].&#39;</blockquote><p><strong>Full Research Chain:</strong> The full_research_chain integrates the previous chains to perform a comprehensive research task. Here’s how it works:</p><pre>full_research_chain = search_question_chain | <br>  (lambda x: [{&quot;question&quot;: q} for q in x]) | web_search_chain.map()</pre><ul><li>The chain begins by using the search_question_chain to generate additional research questions based on the user’s provided topic.</li><li>The generated questions are then formatted into a list of dictionaries, where each dictionary contains a single question. The format looks like this: [{“question”: q}]</li><li>Each formatted question is passed to the web_search_chain, which performs a web search, scrapes the resulting URLs, and summarizes the content. This step is applied to each question, resulting in a list of summaries for each generated question.</li></ul><p>The output of the full_research_chain is a list of lists, where each sublist contains the summarized content from various resource links related to a specific research question.</p><p><strong>Final execution chain: </strong>The chain is the final step in the process, where all the gathered and summarized information is compiled into a comprehensive research report. Here’s how it works:</p><pre>chain = RunnablePassthrough.assign(<br>  context = full_research_chain | flatten_list_of_list<br>) | prompt | ChatOpenAI(model=&quot;gpt-3.5-turbo-1106&quot;) | StrOutputParser()</pre><ul><li>The chain begins by flattening the list of lists returned by the full_research_chain. This step consolidates all the summarized information into a single list, making it easier to process and compile.</li><li>The flattened list of summaries is then passed to the prompt, which includes both the system and user prompts, and is processed by the gpt-3.5-turbo-1106 model to generate the final research report.</li></ul><p>Prompts Explained</p><ol><li>Writer Systems Prompt</li></ol><blockquote>“You are an AI critical thinker research assistant. Your sole purpose is to write well written, critically acclaimed, objective and structured reports on given text.”</blockquote><p>This system prompt sets the context for the AI, instructing it to adopt the role of a critical thinker and research assistant. It emphasizes the need for the AI to produce well-written, objective, and structured reports based on the provided text.</p><p>2. Research Report Prompt</p><blockquote>&#39;Information: &quot;&quot;&quot;{context}&quot;&quot;&quot;\n\n&#39; \<br>&#39;Using the above information, answer the following&#39; \<br>&#39; query or task: &quot;{question}&quot; in a detailed report - &#39; \<br>&quot; The report should focus on the answer to the query, should be well structured, informative,&quot; \<br>&quot; in depth and comprehensive, with facts and numbers if available and a minimum of 1200 words.\n&quot; \<br>&quot;You should strive to write the report as long as you can using all relevant and necessary information provided.\n&quot; \<br>&quot;You must write the report with markdown syntax.\n &quot; \<br>&quot;Use an unbiased and journalistic tone. \n&quot; \<br>&quot;You MUST determine your own concrete and valid opinion based on the given information. Do NOT deter to general and meaningless conclusions.\n&quot; \<br>&quot;You MUST write all used source urls at the end of the report as references, and make sure to not add duplicated sources, but only one reference for each.\n&quot; \<br>&quot;Every url should be hyperlinked: [url website](url)&quot;\<br>&quot;&quot;&quot;<br>Additionally, you MUST include hyperlinks to the relevant URLs wherever they are referenced in the report :<br>eg:<br># Report Header<br>This is a sample text. ([url website](url))<br>&quot;&quot;&quot;\<br>&quot;Cite search results using inline notations. Only cite the most \<br>relevant results that answer the query accurately. Place these citations at the end \<br>of the sentence or paragraph that reference them.\n&quot;\<br>&quot;Please do your best, this is very important to my career.&quot;</blockquote><p>This user prompt provides detailed instructions on how to generate the research report using the information gathered and summarized. It specifies the structure, tone, and formatting requirements for the report, ensuring it is comprehensive, well-organized, and includes all necessary references.</p><h3><strong>Installation and Usage</strong></h3><ol><li>Clone the repository</li></ol><pre>git clone git@github.com:ojasskapre/langchain-apps.git<br>cd langchain-apps/research-assistant</pre><p>2. Create a virtual environment and activate it</p><pre>python -m venv env<br>source env/bin/activate</pre><p>3. Install required dependencies</p><pre>pip install -r requirements.txt</pre><p>4. Setup environment variables for OpenAI API key and LangSmith key</p><pre>cp .env.example .env<br># Edit the .env file to include your OpenAI API key and LangSmith key</pre><p>5. Run the streamlit app</p><pre>streamlit run main.py</pre><h3>Lessons Learned</h3><p>Working on this project helped me deepen my understanding of LangChain and LangSmith, explore different OpenAI models, and develop simple proof-of-concept applications using Streamlit.</p><p>For further improvements, we can enable users to make and generate multiple revisions of the same report, rather than creating new reports each time.</p><p>Stay tuned for more exciting LangChain projects. I’ll be sharing additional LangChain developments and also posting more blogs about React and Next.js.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7b32c4bcdf03" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>