<?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 Charan Kumar on Medium]]></title>
        <description><![CDATA[Stories by Charan Kumar on Medium]]></description>
        <link>https://medium.com/@charan.datascientist?source=rss-473e6d0f7286------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*NS69jc6QoigWPJar8k9u1Q.jpeg</url>
            <title>Stories by Charan Kumar on Medium</title>
            <link>https://medium.com/@charan.datascientist?source=rss-473e6d0f7286------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 08:36:34 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@charan.datascientist/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[Building a Serverless RAG based Q&A app with AWS Bedrock, knowledgebase, Lambda, API Gateway and…]]></title>
            <link>https://medium.com/@charan.datascientist/building-a-serverless-rag-based-q-a-app-with-aws-bedrock-knowledgebase-lambda-api-gateway-and-75fa7e88ef77?source=rss-473e6d0f7286------2</link>
            <guid isPermaLink="false">https://medium.com/p/75fa7e88ef77</guid>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[rags]]></category>
            <category><![CDATA[aws-bedrock]]></category>
            <category><![CDATA[streamlit]]></category>
            <dc:creator><![CDATA[Charan Kumar]]></dc:creator>
            <pubDate>Fri, 10 Jan 2025 13:14:28 GMT</pubDate>
            <atom:updated>2025-01-11T03:52:54.084Z</atom:updated>
            <content:encoded><![CDATA[<h3>Building a Serverless RAG based Q&amp;A app with AWS Bedrock, knowledgebase, Lambda, API Gateway and Streamlit — Part-1</h3><p>In today’s world, knowledge is power, but retrieving the right knowledge at the right time is even more powerful. Imagine a chatbot that can interact with a vast repository of information, provide precise answers, and cite reliable sources — all while being serverless. That’s what I’ve built using <strong>AWS Bedrock</strong>, <strong>Knowledgebase</strong>, <strong>Opensearch</strong>, <strong>Lambda</strong>, <strong>API Gateway</strong>, and <strong>Streamlit</strong>.</p><h3>The Objective</h3><p>The goal was simple: create a conversational Q&amp;A application (soon will convert this to chatbot) that interacts with an AWS Bedrock Knowledge Base. This app can retrieve or generate responses using Bedrock’s <strong>Retrieve API</strong> and <strong>RetrieveAndGenerate API</strong>. It’s designed to handle FAQs, documentation queries, and other knowledge retrieval tasks.</p><h3>Architecture Overview</h3><p>Here’s a simplified view of the architecture powering the chatbot:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/851/1*Fi2XEzqIQD-EI1in_bgyEA.jpeg" /></figure><h3>How It Works</h3><p>The chatbot operates using a seamless integration of AWS services and a user-friendly frontend. Here’s a step-by-step explanation of how the system works:</p><h4>1. User Interaction</h4><ul><li>A user interacts with the chatbot through the <strong>Streamlit frontend</strong>.</li><li>The user enters a query in the input field, which is then submitted to the backend for processing.</li></ul><h4>2. API Gateway</h4><ul><li>The <strong>Streamlit frontend</strong> sends the user’s query to <strong>AWS API Gateway</strong> using an HTTP GET request.</li><li>API Gateway acts as a secure entry point, forwarding the request to the <strong>AWS Lambda function</strong>.</li><li>Query parameters (e.g., prompt) are passed as part of the HTTP request.</li></ul><h4>3. Lambda Function</h4><ul><li><strong>AWS Lambda</strong> is triggered by API Gateway and receives the query as an event payload.</li><li>Inside the Lambda function:</li></ul><p>The prompt is extracted from the event.</p><p>The function interacts with the <strong>AWS Bedrock Knowledge Base</strong> via the <strong>RetrieveAndGenerate API</strong>.</p><p>The RetrieveAndGenerate API retrieves relevant information from the Knowledge Base and generates a contextual response using the selected <strong>foundation model</strong>.</p><h4>4. Bedrock Knowledge Base</h4><ul><li>The <strong>AWS Bedrock Knowledge Base</strong> is the core of the system. It processes the query in the following steps:</li></ul><blockquote><strong>Chunking</strong>: Documents stored in an <strong>Amazon S3 bucket</strong> are broken into smaller chunks for easier processing.</blockquote><blockquote><strong><em>Embeddings</em></strong><em>: </em><strong><em>AWS Titan Embedding Model</em></strong><em> converts the document chunks into vectorized representations.</em></blockquote><blockquote><strong><em>Vector Search</em></strong><em>: The query is matched against the vectorized data using </em><strong><em>OpenSearch (Vector Store)</em></strong><em> to retrieve the most relevant context.</em></blockquote><blockquote><strong><em>Response Generation</em></strong><em>: The retrieved context is sent to the foundation model (e.g., Claude or Titan) to generate a detailed response.</em></blockquote><blockquote><strong><em>Citations</em></strong><em>: The response includes up to five sources from the Knowledge Base to ensure reliability.</em></blockquote><h3>5. Response Delivery</h3><ul><li>The Lambda function receives the response and sends it back to the <strong>API Gateway</strong>.</li><li>The API Gateway forwards the response to the <strong>Streamlit frontend</strong>.</li></ul><h3>6. Displaying the Response</h3><ul><li>The chatbot interface displays the generated response to the user in real-time.</li><li>The user can ask follow-up questions, creating a conversational experience.</li></ul><h3>Key Data Flows</h3><ol><li><strong>Input Flow</strong>:User → Streamlit Frontend → API Gateway → Lambda Function → Bedrock Knowledge Base.</li><li><strong>Output Flow</strong>:Bedrock Knowledge Base → Lambda Function → API Gateway → Streamlit Frontend → User.</li></ol><p>This detailed flow ensures a highly modular and scalable architecture, leveraging the strengths of AWS services for seamless knowledge retrieval and response generation.</p><h3>Pre-requisites</h3><p><strong>Python Environment Setup</strong>:</p><ul><li>Install Python 3.8+ and create a virtual environment:</li></ul><pre>python -m venv venv<br>source venv/bin/activate  # On Windows: venv\Scripts\activate</pre><p><strong>Install AWS CLI</strong>:</p><ul><li>Download and install the AWS CLI:</li></ul><pre>curl &quot;https://awscli.amazonaws.com/awscli-exe-linux-x86_64.zip&quot; -o &quot;awscliv2.zip&quot; <br>unzip awscliv2.zip <br>sudo ./aws/install</pre><ul><li>Verify installation:</li></ul><pre>aws --version</pre><p><strong>AWS IAM User Setup</strong>:</p><ul><li>Create an IAM user with the following permissions:</li><li>AmazonBedrockFullAccess</li><li>AmazonS3ReadOnlyAccess</li><li>AWSLambdaBasicExecutionRole</li><li>AmazonAPIGatewayAdministrator</li><li>CloudWatchLogsFullAccess</li><li>Configure AWS CLI:</li></ul><pre>aws configure</pre><p>Provide access/secret keys, region (ap-southeast-2), and set output to json.</p><p><strong>Bedrock Access</strong>:</p><ul><li>Ensure Bedrock is enabled in your account. Verify with:</li></ul><pre>aws bedrock list-foundation-models --region &lt;your-region&gt;</pre><p><strong>Test Permissions</strong>:</p><ul><li>Check access to S3:</li></ul><pre>aws s3 ls</pre><ul><li>Verify Bedrock access:</li></ul><pre>aws bedrock list-supported-regions</pre><p>This ensures you’re ready to execute the project.</p><h3>Building the Q&amp;A app</h3><h3>Step 1: Setting Up the Knowledge Base</h3><ul><li>Create an Amazon S3 bucket to store your documents (e.g., PDFs, text files).</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gwqMOrV3MHV1PsBcjB2KCQ.png" /></figure><ul><li>Upload the documents and configure chunking, embedding, and vector storage in <strong>AWS Bedrock Knowledge Base</strong>.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YCMFn6YtFUWdHhwR4ENVsA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1ri6mm91k8goHpstotJqaQ.png" /></figure><p><strong>Configured Data Source</strong>:</p><ul><li>Selected <strong>Amazon S3</strong> as the data source.</li><li>Linked the S3 bucket containing the uploaded documents.</li><li>Used the <strong>Amazon Bedrock Default Parser</strong> for parsing text from documents.</li><li>Enabled <strong>Default Chunking</strong> to automatically split text into chunks of approximately 300 tokens for efficient processing.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rEPpvAXHXskxpJYnkW9kPA.png" /></figure><p><strong>Selected Embeddings Model</strong>:</p><ul><li>Chose <strong>Titan Text Embeddings v2</strong> by Amazon for vectorizing the data.</li><li>Configured the embedding process to convert text chunks into vectorized representations.</li></ul><p><strong>Set Up Vector Store</strong>:</p><ul><li>Used the recommended <strong>Quick Create New Vector Store</strong> option.</li><li>Selected <strong>Amazon OpenSearch Serverless</strong> as the vector store for managing embeddings and performing vector searches.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*i9XxomK2fVIpVD8g-oLmDg.png" /></figure><p>This is how it looks after creating the knowledgebase. Knowledge Base ID is important in the below screen. We use this in our lambda function.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zg59COJP3ICUs1ckDl0N9Q.png" /></figure><h3>Step 2: Writing the Lambda Function</h3><p>The Lambda function processes user queries and interacts with AWS Bedrock. Here’s the core code:</p><pre>import json<br>import boto3<br><br># Initialize Bedrock client<br>client_bedrock = boto3.client(&#39;bedrock-agent-runtime&#39;, region_name=&#39;ap-southeast-2&#39;)<br><br>def lambda_handler(event, context):<br>    &quot;&quot;&quot;Lambda function to handle queries to AWS Bedrock Knowledge Base.&quot;&quot;&quot;<br>    try:<br>        # Validate input<br>        user_prompt = event.get(&quot;prompt&quot;)<br>        if not user_prompt:<br>            return {<br>                &#39;statusCode&#39;: 400,<br>                &#39;body&#39;: json.dumps({&quot;error&quot;: &quot;Missing &#39;prompt&#39; in the event payload&quot;})<br>            }<br>        <br>        # Query AWS Bedrock<br>        response = client_bedrock.retrieve_and_generate(<br>            input={&#39;text&#39;: user_prompt},<br>            retrieveAndGenerateConfiguration={<br>                &#39;type&#39;: &#39;KNOWLEDGE_BASE&#39;,<br>                &#39;knowledgeBaseConfiguration&#39;: {<br>                    &#39;knowledgeBaseId&#39;: &#39;&lt;your knowledgeBaseId&gt;&#39;,<br>                    &#39;modelArn&#39;: &#39;&lt;your inference ModelArn&gt;&#39;<br>                }<br>            }<br>        )<br>        response_text = response[&#39;output&#39;][&#39;text&#39;]<br><br>        return {<br>            &#39;statusCode&#39;: 200,<br>            &#39;body&#39;: response_text<br>        }<br><br>    except Exception as e:<br>        return {<br>            &#39;statusCode&#39;: 500,<br>            &#39;body&#39;: json.dumps({&quot;error&quot;: str(e)})<br>        }</pre><h3>Step 3: Create REST API</h3><ul><li>Use <strong>AWS API Gateway</strong> to expose the Lambda function as a REST API.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CxVk5Nt7NBuOb62ddrfGLQ.png" /></figure><ul><li>Create Method — Get as a method type and select the lambda function that is already created with above code.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hEsJrf7aoX7u409q51I1yw.png" /></figure><ul><li>Configure query string parameters to accept user inputs like prompt.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2aOxV2whYeHVLl28Eo8TAw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6EhUMJm7p0pGsU4MDM-sdA.png" /></figure><ul><li>Map the inputs to the Lambda function and deploy the API.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yQQ2B-z4b1_OVfxXsyBtkg.png" /></figure><ul><li>Quickly test the API</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*h-OkkHTLTpUaRUVBKhlm4w.png" /></figure><h3>Step 4: Building the Q&amp;A Interface</h3><p>Using <strong>Streamlit</strong>, I created an interactive UI for the chatbot. Here’s how:</p><pre>import streamlit as st<br>import requests<br></pre><pre>st.title(&quot;Knowledge Base Chatbot&quot;)<br>st.markdown(&quot;Ask me anything!&quot;)</pre><pre>user_prompt = st.text_input(&quot;Enter your question:&quot;)<br>if st.button(&quot;Submit&quot;):<br>    if user_prompt:<br>        with st.spinner(&quot;Thinking...&quot;):<br>            response = requests.get(<br>                &quot;https://YOUR_API_GATEWAY_URL&quot;,<br>                params={&quot;prompt&quot;: user_prompt}<br>            )<br>            if response.status_code == 200:<br>                st.success(response.json())<br>            else:<br>                st.error(&quot;Error fetching response&quot;)<br>    else:<br>        st.warning(&quot;Please enter a question.&quot;)</pre><h3>Running Locally</h3><p>To run the chatbot locally:</p><ol><li>Clone the repository.</li></ol><p><a href="https://github.com/charan-datascientist/aiknowledgebase">GitHub - charan-datascientist/aiknowledgebase</a></p><pre>git clone https://github.com/charan-datascientist/aiknowledgebase.git</pre><p>2. Install dependencies:</p><pre>pip install -r requirements.txt</pre><p>3. Run the Streamlit app locally</p><pre>streamlit run app.py</pre><p>4. Streamlit UI: Few things has to be addressed. I will take up in next part.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NDd4LH1lpBO0JrsZOkscSw.png" /></figure><h3>Challenges</h3><ul><li><strong>Timeouts</strong>: Initially faced Lambda timeout issues, resolved by increasing the timeout limit from default (3 sec) to 2 mins.</li><li>Using Inference-Profile ARN instead of ModelARN in Lambda function.</li></ul><p>If you encounter the error below when using a <strong>Model ARN</strong> in your Lambda function:</p><pre>&quot;errorMessage&quot;: &quot;An error occurred (ValidationException) when calling the RetrieveAndGenerate operation: Invocation of model ID anthropic.claude-3-5-sonnet-20240620-v1:0 with on-demand throughput isn’t supported. Retry your request with the ID or ARN of an inference profile that contains this model.&quot;errorMessage&quot;: n error occurred (ValidationException) when calling the RetrieveAndGenerate operation: Invocation of model ID anthropic.claude-3-5-sonnet-20240620-v1:0 with on-demand throughput isn’t supported. Retry your request with the ID or ARN of an inference profile that contains this model.&quot;</pre><p>This error indicates that the <strong>Model ARN</strong> does not support on-demand throughput directly, and you must use an <strong>Inference-Profile ARN</strong> instead.</p><p><strong>What is an Inference-Profile ARN?</strong></p><p>An <strong>Inference-Profile ARN</strong> is a unique identifier for a pre-configured resource in AWS Bedrock that specifies the compute resources (throughput and other configurations) needed to invoke a specific model. Using an inference-profile ARN allows you to:</p><ul><li>Avoid issues with on-demand throughput limitations.</li><li>Use provisioned resources for consistent performance.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Jaaqk0OHm1creksrVhoURA.png" /></figure><h3>Important Reminder: Clean Up Resources to Avoid Unnecessary Costs</h3><p>When working with <strong>AWS Bedrock</strong>, it’s crucial to ensure that all associated resources are deleted once they are no longer needed. Leaving resources like <strong>Knowledge Bases</strong>, <strong>Vector Stores</strong>, or <strong>Data Sources</strong> active can lead to ongoing charges, potentially resulting in significant costs.</p><h3>Conclusion</h3><p>This Q&amp;A app demonstrates the power of combining <strong>AWS Bedrock</strong> with serverless technologies like <strong>Lambda</strong> and <strong>API Gateway</strong>. With the scalability of AWS and the simplicity of Streamlit, you can create a robust solution for knowledge retrieval tasks. Whether for FAQs, documentation, or e-learning, this architecture can be adapted to various use cases.</p><h3>References</h3><ul><li><a href="https://docs.aws.amazon.com/bedrock/latest/APIReference/API_agent-runtime_Retrieve.html">Retrieve</a></li><li><a href="https://docs.aws.amazon.com/bedrock/latest/APIReference/API_agent-runtime_RetrieveAndGenerate.html">RetrieveAndGenerate</a></li><li><a href="https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/bedrock-agent-runtime/client/retrieve_and_generate.html">retrieve_and_generate - Boto3 1.35.96 documentation</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=75fa7e88ef77" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deep Learning Series: A Step-by-Step Guide to Setting Up Your Workspace]]></title>
            <link>https://medium.com/@charan.datascientist/deep-learning-series-a-step-by-step-guide-to-setting-up-your-workspace-23ea07b59903?source=rss-473e6d0f7286------2</link>
            <guid isPermaLink="false">https://medium.com/p/23ea07b59903</guid>
            <category><![CDATA[pytorch]]></category>
            <category><![CDATA[vscode]]></category>
            <category><![CDATA[anaconda]]></category>
            <category><![CDATA[deep-learning]]></category>
            <dc:creator><![CDATA[Charan Kumar]]></dc:creator>
            <pubDate>Wed, 31 Jul 2024 06:44:26 GMT</pubDate>
            <atom:updated>2024-07-31T06:44:26.943Z</atom:updated>
            <content:encoded><![CDATA[<p>In this series, we will explore deep learning concepts with programmatic examples. Most theoretical parts will be explained in layman’s terms, and reference links will be provided for technical details (e.g., mathematical concepts).</p><h4><strong>Setup Workspace</strong></h4><p><strong>Step-1: </strong>Download &amp; Install Anaconda from <a href="https://www.anaconda.com/">here</a></p><p><strong>Step-2:</strong> Download &amp;Install VSCode from <a href="https://code.visualstudio.com/download">here</a></p><p>Open the terminal in VSCode. It should look like this when you first open it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1022/1*PDXaZ0rjAyyBklqlMwxwaA.png" /></figure><p><strong>Step-3: Create an Environment</strong></p><p>Create a new environment for this tutorial. It’s always good to have separate environments for different projects to manage dependencies easily. To understand virtual environments better, check out this <a href="https://www.geeksforgeeks.org/python-virtual-environment/">guide</a>.</p><p>You can create environments in two ways: using the Anaconda Navigator UI or through the terminal (either in VSCode or your system’s terminal).</p><p><strong>Using Anaconda Navigator UI:</strong></p><ul><li>Open Anaconda Navigator.</li><li>Click on “Create”.</li><li>Provide the name of the environment and choose the Python version.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jQzz9aDck7J0qMKFuNMNWw.png" /></figure><p><strong>Using Terminal (in VSCode):</strong></p><p>To create an environment using the terminal, run the following command:</p><pre>conda create - name deeplearning python=3.12.4</pre><p>You should see a command prompt indicating the creation of the deeplearning environment. To activate this environment, run:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*u0PeexzhxqVH4L0A7z66ig.png" /></figure><pre>conda activate deeplearning</pre><p>After activating the environment, your prompt should indicate that you are in the deeplearning environment.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/591/1*TuKrwYIeZI8uRMSLdH9lfA.png" /></figure><p><strong>Step -4:</strong> Install libraries in the created environment.</p><p>For this series, we will use PyTorch</p><p><strong>Installing PyTorch</strong><br>Visit the PyTorch official website and select your operating system, package manager (Conda or pip), and compute platform (e.g., CPU or CUDA). Based on your selections, the website will provide a specific installation command. For example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/807/1*L8uWv7G8D_I76sKCbYJ7yQ.png" /></figure><pre>conda install pytorch::pytorch torchvision torchaudio -c pytorch</pre><blockquote>torchvision provides utilities for image data, including datasets (CIFAR-10, ImageNet), transforms (resizing, normalization), pre-trained models (ResNet, VGG), and image processing utilities. torchaudio offers tools for audio data, featuring I/O functions, audio transforms (spectrogram, MFCC), pre-built datasets (LibriSpeech), and pre-trained models for tasks like speech recognition. Both integrate seamlessly with PyTorch for deep learning tasks.</blockquote><p><strong>Installing other dependent packages:</strong></p><p>Run the following command to install additional libraries:</p><pre>conda install numpy pandas scipy scikit-learn seaborn matplotlib </pre><p><strong>Step-5: Configure VSCode to Use the Conda Environment(deeplearning)</strong></p><p>Add the following snippet to VSCode to use the deeplearning environment&#39;s Python interpreter:</p><ol><li>Open the Command Palette by pressing Cmd+Shift+P (macOS) or Ctrl+Shift+P (Windows/Linux).</li><li>Type and select Preferences: Open User Settings (JSON).</li></ol><p>In the settings.json file, add or modify the following line:</p><pre>&quot;python.pythonPath&quot;: &quot;/Users/&lt;username&gt;/anaconda3/envs/&lt;envname&gt;/bin/python&quot;,</pre><p>Replace &lt;username&gt; with your actual username and &lt;envname&gt; with the name of your environment (e.g., deeplearning).</p><p><strong>Step-6:</strong> <strong>Set the Python Interpreter in VSCode</strong></p><ul><li><strong>Open the Command Palette</strong> by pressing Cmd+Shift+P (macOS) or Ctrl+Shift+P (Windows/Linux).</li><li><strong>Type and select </strong><strong>Python: Select Interpreter</strong>.</li><li><strong>Select your Anaconda environment</strong> from the list. Ensure it matches the environment your python &amp; libraries are installed.</li></ul><p>By following these steps, you can set up your workspace for exploring deep learning concepts using VSCode and Anaconda. Stay tuned for more programmatic examples and in-depth explanations of deep learning topics!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=23ea07b59903" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>