<?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 Corentin Vanvyve on Medium]]></title>
        <description><![CDATA[Stories by Corentin Vanvyve on Medium]]></description>
        <link>https://medium.com/@corentin.vanvyve?source=rss-48def4c16ed3------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*2dPph-r6ZVdYvn1XvQuOcw.jpeg</url>
            <title>Stories by Corentin Vanvyve on Medium</title>
            <link>https://medium.com/@corentin.vanvyve?source=rss-48def4c16ed3------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 03:40:30 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@corentin.vanvyve/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Build a Slack RAG Agent that understands your codebase using AWS Bedrock, OpenSearch and Lambda]]></title>
            <link>https://medium.com/@corentin.vanvyve/build-a-slack-rag-agent-that-understands-your-codebase-using-aws-bedrock-opensearch-and-lambda-b0ee00d82f0c?source=rss-48def4c16ed3------2</link>
            <guid isPermaLink="false">https://medium.com/p/b0ee00d82f0c</guid>
            <category><![CDATA[opensearch]]></category>
            <category><![CDATA[aws-lambda]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[bedrock]]></category>
            <category><![CDATA[retrieval-augmented-gen]]></category>
            <dc:creator><![CDATA[Corentin Vanvyve]]></dc:creator>
            <pubDate>Sun, 17 Aug 2025 07:53:09 GMT</pubDate>
            <atom:updated>2025-08-17T07:53:09.478Z</atom:updated>
            <content:encoded><![CDATA[<ul><li>Use Ollama to locally generate summaries of your codebase.</li><li>Store processed files in S3 and index them with OpenSearch.</li><li>Create a Bedrock Knowledge Base and agent.</li><li>Build a Slack bot with basic messaging permissions.</li><li>Use Lambda to relay messages between Slack and Bedrock.</li></ul><h3><strong>Introduction</strong></h3><p>In this tutorial, you’ll learn how to build an intelligent <strong>Slack agent</strong> that can answer questions about <strong>your codebase</strong>.</p><p>This project was born out of a real need: I wanted to improve productivity at the startup where I work. Internal team members and external stakeholders frequently ask technical questions that require digging into the code.</p><p>For example:</p><ul><li>A product owner wants to know what product attributes are considered by an algorithm.</li><li>A frontend developer needs clarity on how a backend API works.</li><li>A new developer is attempting to comprehend a comprehensive web application comprising lines of code.</li></ul><p>Instead of manually searching through files or disturbing a busy developer, why not <strong>ask a Slack bot directly</strong>?</p><h3>What is RAG?</h3><p><strong>RAG</strong> stands for <strong>Retrieval-Augmented Generation</strong>. It’s an AI architecture that enhances a large language model (LLM) by feeding it external, domain-specific knowledge retrieved from a vector database.</p><h4>RAG = Retrieval + Augmented<strong> + </strong>Generation</h4><ul><li><strong>Retrieval </strong>: The system searches a knowledge base (your codebase) for relevant documents or context.</li><li><strong>Augmented</strong> : These documents are added to the prompt given to the AI.</li><li><strong>Generation </strong>: The AI (Claude, Titan, or any model on Bedrock) generates a response based on both the prompt and the retrieved documents.</li></ul><p>This enables the model to provide grounded, relevant answers based on your own data, rather than relying solely its pretraining.</p><h4>RAG Architecture Diagram</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ashxcz6pNo9mwBACQ9qKtQ.png" /></figure><h3>How this project works</h3><p>To make this Slack RAG agent functional, here’s the approach:</p><ol><li><strong>Data transformation and enrichment<br></strong> Every source file is transformed into plain text and then processed with a local LLM (using <a href="https://ollama.com/">Ollama</a>) to generate summaries or descriptions. These help the agent understand what each file does.</li><li><strong>Data Ingestion<br></strong>In the data ingestion phase, we take our enriched code summaries and store them in an optimised format for fast retrieval. Using Amazon S3 as a storage layer, combined with Amazon OpenSearch for vector-based search, allows us to quickly match user queries with relevant files from the codebase.</li><li><strong>Creating the AI agent in Amazon Bedrock<br></strong>We use Bedrock to build an AI agent with access to our knowledge base, defining its role, model, and behaviour.</li><li><strong>Configure Slack<br></strong>We create a Slack app with messaging permissions and event subscriptions to allow user interaction via chat.</li><li><strong>Connect Slack to AWS Lambda<br></strong>Slack events are routed to a Lambda that triggers a second one, which queries Bedrock and sends responses back to Slack.</li></ol><h4><strong>System architecture overview</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sg9J0OmrwKC3A_9sV14BKQ.png" /></figure><h3>Prerequisites</h3><p>Before starting, make sure you have the following:</p><ul><li>A <strong>Slack account</strong> with permission to create an app and bot</li><li>An <strong>AWS account</strong> with access to (S3, OpenSearch, Bedrock, Lambda IAM)</li><li>A local setup capable of running <strong>Ollama</strong> for offline LLM summarisation (optional but useful)</li><li>This <a href="https://github.com/CorentinVanvyve/rag_project">github project</a>.</li></ul><h3>1. Data transformation and enrichment</h3><h4>Set up your local model with Ollama</h4><p>The first step is to clone your code repository locally and install<a href="https://ollama.com/"> <strong>Ollama</strong></a>, a lightweight framework for running large language models on your machine.</p><p>Once installed, you can download and start a model, in this case, <strong>Llama 3.2</strong> with the following command:</p><pre>ollama run llama3.2</pre><p>You should now be able to chat with the model directly in your terminal. To exit the chat session, simply type:</p><pre>/bye</pre><p>Nice! You now have a local LLM up and running.</p><h4>Customize your own agent</h4><p>Instead of using a generic model, we’ll create a <strong>custom agent</strong> based on Llama 3.2, tailored for a specific task: <strong>generating summaries and descriptions of code files</strong>. This focused agent will produce more relevant output than a general-purpose model.</p><p>In your terminal, navigate to the <strong>rag_project</strong> <strong>folder</strong> (you can <a href="https://github.com/CorentinVanvyve/rag_project">download this repo</a> if you haven’t already). Inside, you’ll find a file called <strong>Modelfile</strong>, which defines:</p><ul><li>The base model to use</li><li>Parameters</li><li>How the agent behaves</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2WfMrRJXi-EQhcmTGQ7b3A.png" /></figure><p>To create your agent (we’ll name it <strong><em>codexpert</em></strong>), run:</p><pre>ollama create codexpert -f ./Modelfile</pre><p>You can verify that it was created successfully with:</p><pre>ollama list</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Qc2LRPJpdGO6qE4z3Bv9KA.png" /></figure><p>You should now see <em>codexpert</em> in the list of available models.</p><p>And you can interact with your new agent with :</p><pre>ollama run codexpert</pre><h4>Serve your agent &amp; process the codebase</h4><p>Next, we’ll launch a local API endpoint to interact with our agent programmatically.</p><p>Start the Ollama server:</p><pre>ollama serve</pre><p>Now open the <strong>repo_enhanced/main.py </strong>script in your favourite IDE.</p><p>Before running the script:</p><ol><li>Copy the repository you want to analyse into the <strong>original_repo folder</strong>.</li><li><strong>Run </strong>the script using your Python environment.</li></ol><p>What this script does:</p><ul><li><strong>Iterates</strong> through each file in your <strong>repo</strong></li><li><strong>Converts</strong> each file into<strong> .txt</strong> format</li><li>Prepends the file with its <strong>full path and a brief description</strong> of the file utility / functionality (using your local model)</li></ul><p>⚠️ <strong>Note:</strong> This process can be time consuming depending on the size of your codebase. In my case, it took the whole night to process a large repository, so plan accordingly!</p><p>Once this is done, your fully converted and improved repository will be located in the <strong><em>processed_files</em></strong> folder.</p><p>Now, upload your processed_files folder to a<strong> bucket on AWS S3</strong>.</p><h3>2. Data ingestion</h3><h4>Create a knowledge base with your codebase</h4><p>Now that we’ve enriched our codebase by converting each file to text and added the summaries, it’s time to <strong>make this data accessible to our AI agent</strong>. To do that, we’ll create a <strong>Knowledge Base in AWS Bedrock</strong>.</p><h4>Why do we need a Knowledge Base?</h4><p>Large Language Models (LLMs) are powerful but limited by their training data. They don’t know anything about your company’s code unless you explicitly give them that context.</p><p>That’s where <strong>Retrieval-Augmented Generation (RAG)</strong> comes in: instead of forcing the model to “guess,” we store the relevant documents (in this case, your codebase) in a <strong>vector database</strong>, then <strong>retrieve the most relevant files at query time</strong>. The model uses those files to generate an accurate response.</p><h4>How does a Bedrock Knowledge Base work?</h4><p>When you create a Knowledge Base in Bedrock, you provide:</p><ol><li>A <strong>data source : </strong>a folder in an <strong>Amazon S3</strong> bucket that contains all your documents (like your .txt code summaries).</li><li>A <strong>vector store : </strong>in our case, <strong>Amazon OpenSearch Service</strong>, which transforms your documents into embeddings (numerical vectors) and enables quick similarity search.</li><li>A <strong>model : </strong>from Bedrock (Claude, Titan, etc.) that uses retrieved context to generate answers.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5ld_mkW7082Z43X6txex1w.png" /></figure><p><a href="https://medium.com/@garyminglu"><em>Gary Lu</em></a><em> diagram</em></p><p>⚠️ <strong>Warning:</strong> Using Amazon Bedrock and Amazon OpenSearch Service incurs costs. Be sure to monitor your spending through the <strong>AWS Cost and Usage Dashboard</strong>. You can also set a spending limit by configuring an <strong>AWS Budget</strong> to avoid unexpected charges.</p><h4>Create a Knowledge Base with on AWS</h4><ol><li>Go to the <strong>AWS Console</strong> and search for “<strong>Bedrock”</strong> in the service search bar.</li><li>In the left-hand menu, click on “<strong>Knowledge base”</strong>.</li><li>Click the <strong>Create</strong> button, then select <strong>“Create a knowledge base with a vector store”</strong>.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gzqbWWR9r4gmngSSKrNrDg.png" /></figure><p><strong>Step 1: Knowledge base details</strong></p><p>In the first step, you’ll need to provide some basic information:</p><ul><li><strong>Name</strong>: Choose a name for your Knowledge Base.</li><li><strong>IAM Permissions</strong>: Select <strong>“Create and use a new service role”, </strong>this allows Bedrock to access other AWS services securely.</li><li><strong>Query Engine</strong>: Choose <strong>Amazon S3</strong> as the data source type.</li><li>Click <strong>Next</strong> to proceed.</li></ul><p><strong>Step 2: Choose the Data Source</strong></p><ul><li>Select the <strong>S3 bucket</strong> where you previously uploaded your enriched codebase files.</li><li>Click “<strong>Next”</strong>.</li></ul><p><strong>Step 3: Choose the Embedding Model</strong></p><p>Now you’ll select the model that Bedrock will use to generate vector embeddings from your documents:</p><ul><li>For this demo, I’m using <strong>Cohere Embed Multilingual v3</strong>, which works well.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Wexn3aKbfg0nM9HS1yDk8g.png" /></figure><ul><li>You can leave the other settings unchanged.</li></ul><p>Click “<strong>Next”</strong> once you’re ready.</p><p><strong>Step 4: Review and Create</strong></p><ul><li>Review all the configuration details.</li><li>If everything appears to be in order, click “<strong>Create Knowledge Base”</strong>.</li></ul><p><strong>Step 5: Sync the Data source</strong></p><ul><li>Go to Knowledge Base console, click on the one you just created and in the Data source section, select the appropriate data source and Sync</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KB8FMUEtghpQYbGr4Ev21w.png" /></figure><p>Bedrock will now start indexing your S3 documents into the vector store (powered by Amazon OpenSearch Service behind the scenes). This can take a few minutes, depending on your dataset size.</p><h3>3. Creating the AI Agent in Amazon Bedrock</h3><p>Now that our codebase is indexed and searchable, let’s build the AI agent that will use this data to generate intelligent responses.</p><p>In this step, we’ll create an <strong>LLM-powered agent</strong> using <strong>Amazon Bedrock</strong>. This pre-trained, serverless agent will be specifically dedicated to answering questions about your company’s codebase</p><h4>Create the Agent</h4><ol><li>Open the <strong>AWS Bedrock Console</strong>.</li><li>In the left-hand menu, click on <strong>Agents</strong>, then select <strong>Create Agent</strong>.</li><li>Give your agent a name and confirm the creation.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aIYE4W1w2ZiRjrKq7al2XQ.png" /></figure><p>You’ll be redirected to the agent configuration page.️</p><h4>Configure the Agent</h4><p>In the <strong>Details</strong> section, keep the default setting:</p><ul><li><strong>Create and use a new service role, </strong>which allows your agent to access other AWS resources securely.</li></ul><p>Select a foundation model that strikes a balance between cost and performance. For this tutorial, I’m using <strong>Claude 3.5 Sonnet</strong> (powerful).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zfCiTsB9LNeWbNG60lQxcA.png" /></figure><h4>Define the agent’s instructions</h4><p>The instructions define your agent’s <strong>persona, behaviour, and mission</strong>. These are crucial for getting relevant and useful answers tailored to your internal needs.</p><p>Here’s a sample you can copy and adapt:</p><pre>You are an internal AI assistant trained to answer technical questions about the web application codebase of our company. <br>Your responses help employees across departments understand how the system works.<br><br>Be clear and to the point. Start with a simple overview, then go deeper if needed. <br>Adjust your language based on the user&#39;s role plain for non-technical staff, technical for developers. <br>Always link code to its purpose or effect in the product.</pre><p>Scroll down to the <strong>Knowledge Bases</strong> section and <strong>attach the Knowledge Base</strong> that you created in the previous step.</p><p>You can leave the other settings at their defaults.</p><p>Click <strong>Save and Exit</strong> to finalise the agent setup.</p><h4>Test</h4><p>Once your agent is saved, you can <strong>prepare</strong> it for testing directly in the Bedrock console. You’ll be able to ask questions and tweak the configuration or instructions based on the responses.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rpwR9CliBOd4VmYlD9h2rA.png" /></figure><p>Create an alias to version your agent. This allows you to easily test different configurations.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LwTDx7tlCl5We1QVi4-JZw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_Q2muFDVn47vvTZ3Z9RUVQ.png" /></figure><h3>4. Configure Slack</h3><h4>Create a Slack App</h4><p>Start by heading to <a href="https://api.slack.com/apps">Slack API Apps</a> and clicking on <strong>“Create New App” </strong>from scratch.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iwuNfzeTY_0iGDUJVIZ8yg.png" /></figure><ul><li>Give your app a name</li><li>Select the workspace where it should be installed</li><li>Click <strong>Create App</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Q2PzCb-Qste74uYEILH3iA.png" /></figure><p>Once your app is created, navigate to <strong>OAuth &amp; Permissions</strong> on the left sidebar.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*E88R1KEf4r3VSt7ESFf_4Q.png" /></figure><h4>Add Required Scopes</h4><p>Scroll down to the <strong>Scopes</strong> section and under <strong>Bot Token Scopes</strong>, add the following permissions:</p><ul><li>im:read – to read messages sent to the bot</li><li>im:write – to open direct message conversations</li><li>chat:write – to send messages as the bot</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KUWN740aPsea-Bg1lzPUpQ.png" /></figure><p>Save changes and install the app in your Slack workspace.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mfufQDKuGqPXvsMQt_-sEA.png" /></figure><p>In the <strong>App Home</strong> menu, ensure that these options are selected.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nXz7OoBX8Si2El3CdhCRZA.png" /></figure><p>The bot should now appear in your company’s Slack environment.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AphaQk4FMmH4gm4tlKFRzQ.png" /></figure><h3>5. Connect Slack to AWS Lambda</h3><p>We’ll now create <strong>two AWS Lambda functions</strong> to handle the flow between Slack and Bedrock:</p><ul><li><strong>lambdaReceiver</strong>: A lightweight function that receives Slack events and immediately acknowledges them with an HTTP 200 response.</li><li><strong>lambdaSlackResponse</strong>: A background processor that sends the message to Bedrock and returns the response to Slack.</li></ul><p>This architecture ensures compliance with Slack’s timeout requirements, which would otherwise reject delayed responses.</p><h4>Create the lambdaReceiver function</h4><p>Go to the <strong>AWS Lambda Console. </strong>Click <strong>Create Function</strong>, name it lambdaReceiver, and select <strong>Python</strong> as the runtime.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DHO5Ocq-QJShr0bpwrW4yQ.png" /></figure><p>Copy the code below or from the github project (<a href="https://github.com/CorentinVanvyve/rag_project">rag_project</a>) into the code editor.</p><pre>import json<br><br>import boto3<br><br># def lambda_handler(event, context):<br>#     client = boto3.client(&#39;lambda&#39;)<br><br>#     response = client.invoke(<br>#         FunctionName=&#39;lambdaSlackResponse&#39;,<br>#         InvocationType=&#39;Event&#39;,<br>#         Payload=json.dumps(event)<br>#     )<br><br>#     return {<br>#         &#39;statusCode&#39;: 200,<br>#         &#39;body&#39;: json.dumps({&#39;msg&#39;: &quot;message recevied&quot;})<br>#     }<br><br><br>def lambda_handler(event, context):<br>    body = json.loads(event[&#39;body&#39;])<br><br>    return {<br>        &#39;statusCode&#39;: 200,<br>        &#39;body&#39;: body[&#39;challenge&#39;]<br>    }</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jebwd8MRiFrsSFN0jyXZsg.png" /></figure><blockquote><em>⚠️ Ensure your code handles Slack’s </em><em>challenge verification mechanism for the </em><strong><em>Event Subscription</em></strong><em> setup later.</em></blockquote><p>Click <strong>Deploy</strong> to save changes.</p><p>Next, go to the <strong>Configuration &gt; Function URL</strong> section and click <strong>Create function URL</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mKvtp4o2TsAtch-QxeLS4g.png" /></figure><p>Set the <strong>Auth type</strong> to NONE for now (acceptable for a proof of concept, but not recommended for production).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KQ3lblE-wiESM2d7xKP0Rw.png" /></figure><p>Copy this URL, we’ll use it when configuring Slack events.</p><h4>Add IAM permissions to invoke the other lambda function</h4><p>Your lambdaSlackResponse function needs permission to interact with the other lambda function. To grant access:</p><p>Go to the <strong>IAM Console &gt; Roles, </strong>locate and select the role attached to your lambdaReceiver function.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BrXU3x5QwKg5CacJK-yD5g.png" /></figure><p>Click <strong>Add inline policy</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0_9PGD3SPqLn9wJ3m5QFRw.png" /></figure><p>Choose the <strong>JSON</strong> tab and paste:</p><pre>{<br>  &quot;Version&quot;: &quot;2012-10-17&quot;,<br>  &quot;Statement&quot;: [<br>    {<br>      &quot;Effect&quot;: &quot;Allow&quot;,<br>      &quot;Action&quot;: &quot;lambda:InvokeFunction&quot;,<br>      &quot;Resource&quot;: &quot;arn:aws:lambda:&lt;region&gt;:&lt;account-id&gt;:function:&lt;target-function-name&gt;&quot;<br>    }<br>  ]<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bPYdsUsoFiIoxw0s7QQLew.png" /></figure><p>Replace ACCOUNT_ID , TARGET_FUNCTION_NAMEand REGION with your actual values, then save the policy.</p><h4>Create the lambdaSlackResponse function</h4><p>Create another Lambda named lambdaSlackResponseand select Python as the runtime</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*h29AeGOE_RCt8uq1fM2ARw.png" /></figure><p>Copy the code below or from the Github project (<a href="https://github.com/CorentinVanvyve/rag_project">rag_project</a>) into the code editor.</p><pre>import json<br>import logging<br>import os<br><br>import boto3<br>import urllib3<br>from botocore.exceptions import BotoCoreError, ClientError<br><br># Initialize logging<br>logger = logging.getLogger()<br>logger.setLevel(logging.INFO)<br><br># Load environment variables<br>SLACK_TOKEN = os.environ.get(&quot;slackToken&quot;) # you can get this from the slack app : OAuth &amp; Permissions &gt;<br>SLACK_URL = os.environ.get(&quot;slackUrl&quot;) # https://slack.com/api/chat.postMessage<br>REGION_NAME = os.environ.get(&quot;regionName&quot;) # you can get this from the bedrock agent<br>AGENT_ID = os.environ.get(&quot;agentId&quot;) # you can get this from the bedrock agent<br>AGENT_ALIAS_ID = os.environ.get(&quot;agentAliasId&quot;) # you can get this from the bedrock agent<br>BOT_USER_ID = &quot;U090ZPKV2JE&quot;  # Replace with your actual Bot User ID<br><br># Initialize HTTP connection pool<br>http = urllib3.PoolManager()<br><br><br>def send_message_to_slack(message: str, channel: str ) -&gt; dict:<br>    &quot;&quot;&quot;<br>    Sends a message to a Slack channel.<br><br>    Args:<br>        message (str): The text to send.<br>        channel (str): The Slack channel ID.<br><br>    Returns:<br>        dict: Slack API response.<br>    &quot;&quot;&quot;<br>    payload = {<br>        &quot;channel&quot;: channel,<br>        &quot;text&quot;: message<br>    }<br><br>    headers = {<br>        &quot;Authorization&quot;: f&quot;Bearer {SLACK_TOKEN}&quot;,<br>        &quot;Content-Type&quot;: &quot;application/json&quot;<br>    }<br><br>    try:<br>        response = http.request(&quot;POST&quot;, SLACK_URL, headers=headers, body=json.dumps(payload))<br>        return json.loads(response.data.decode(&quot;utf-8&quot;))<br>    except Exception as e:<br>        logger.error(f&quot;Failed to send message to Slack: {e}&quot;)<br>        return {&quot;ok&quot;: False, &quot;error&quot;: str(e)}<br><br><br>def query_bedrock_agent(question: str, session_id: str, channel: str ) -&gt; str:<br>    &quot;&quot;&quot;<br>    Sends a user question to the Bedrock agent and streams the response to Slack.<br><br>    Args:<br>        question (str): User input.<br>        session_id (str): Unique session ID.<br>        channel (str): Slack channel ID.<br><br>    Returns:<br>        str: Full concatenated agent response.<br>    &quot;&quot;&quot;<br>    client = boto3.client(&quot;bedrock-agent-runtime&quot;, region_name=REGION_NAME)<br>    full_response = &quot;&quot;<br><br>    try:<br>        response = client.invoke_agent(<br>            agentId=BEDROCK_AGENT_ID,<br>            agentAliasId=BEDROCK_AGENT_ALIAS_ID,<br>            sessionId=session_id,<br>            inputText=question<br>        )<br><br>        for event in response.get(&quot;completion&quot;, []):<br>            if &quot;chunk&quot; in event:<br>                part = event[&quot;chunk&quot;][&quot;bytes&quot;].decode(&quot;utf-8&quot;)<br>                send_message_to_slack(part, channel)<br>                full_response += part<br><br>    except (BotoCoreError, ClientError) as e:<br>        logger.error(f&quot;Bedrock agent invocation failed: {e}&quot;)<br>    return full_response<br><br><br>def lambda_handler(event, context):<br>    &quot;&quot;&quot;<br>    AWS Lambda function entry point.<br><br>    Args:<br>        event (dict): Lambda event payload.<br>        context (LambdaContext): Runtime information.<br><br>    Returns:<br>        dict: HTTP response.<br>    &quot;&quot;&quot;<br>    logger.info(f&quot;Received event: {event}&quot;)<br><br>    try:<br>        body = json.loads(event.get(&quot;body&quot;, &quot;{}&quot;))<br>        slack_event = body.get(&quot;event&quot;, {})<br>        event_type = slack_event.get(&quot;type&quot;)<br><br>        user_message = slack_event.get(&quot;text&quot;)<br>        channel_id = slack_event.get(&quot;channel&quot;)<br>        timestamp = slack_event.get(&quot;ts&quot;)<br>        user_id = slack_event.get(&quot;user&quot;)<br>        channel_type = slack_event.get(&quot;channel_type&quot;)<br><br>        # Process only direct messages from users (not from the bot itself)<br>        if (<br>            event_type == &quot;message&quot;<br>            and channel_type == &quot;im&quot;<br>            and user_id != BOT_USER_ID<br>        ):<br>            send_message_to_slack(&quot;Thinking ...&quot;, channel_id)<br>            query_bedrock_agent(user_message, timestamp, channel_id)<br><br>        return {<br>            &quot;statusCode&quot;: 200,<br>            &quot;body&quot;: json.dumps({&quot;msg&quot;: &quot;Message received&quot;})<br>        }<br><br>    except Exception as e:<br>        logger.error(f&quot;Error processing event: {e}&quot;)<br>        return {<br>            &quot;statusCode&quot;: 500,<br>            &quot;body&quot;: json.dumps({&quot;error&quot;: &quot;Internal Server Error&quot;})<br>        }</pre><p>Change the <strong>BOT_USER_ID</strong> to yours.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*T9VCmlT4sQGoeHZirHHOiA.png" /></figure><p>Click <strong>Deploy</strong></p><h4>Set environment variables</h4><p>Go to <strong>Configuration &gt; Environment variables</strong> and click <strong>Edit.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jNOWOJvgTxdWapyVfvjS3g.png" /></figure><p>Add your required variables.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3ThP6xOZexTrEwbzrQK1JA.png" /></figure><p>Go to the General Configuration tab and change the function’s Timeout from 3 seconds to 30 seconds.</p><p>Otherwise, the agent will not have time to send its entire response.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WmQTiALZN2LMEwPem7M2fw.png" /></figure><h4>Add IAM permissions to access Bedrock</h4><p>Your lambdaSlackResponse function needs permission to interact with Bedrock. To grant access:</p><p>Go to the <strong>IAM Console &gt; Roles, </strong>locate and select the role attached to your lambdaSlackResponse function.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Q2S_p6j1PArEiBIdY3HPdw.png" /></figure><p>Click <strong>Add inline policy</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZCJDYiKoyvGDFpxZqeLMZQ.png" /></figure><p>Choose the <strong>JSON</strong> tab and paste:</p><pre>{<br> &quot;Version&quot;: &quot;2012-10-17&quot;,<br> &quot;Statement&quot;: [<br>  {<br>   &quot;Effect&quot;: &quot;Allow&quot;,<br>   &quot;Action&quot;: [<br>    &quot;bedrock:InvokeAgent&quot;<br>   ],<br>   &quot;Resource&quot;: &quot;arn:aws:bedrock:REGION:YOUR_ACCOUNT_ID:agent-alias/AGENT_ID/ALIAS_ID&quot;<br>  },<br>  {<br>   &quot;Effect&quot;: &quot;Allow&quot;,<br>   &quot;Action&quot;: [<br>    &quot;bedrock:InvokeModel&quot;<br>   ],<br>   &quot;Resource&quot;: &quot;arn:aws:bedrock:*::foundation-model/*&quot;<br>  }<br> ]<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aM92VQYisoeAx6nfPkU1Wg.png" /></figure><p>Replace YOUR_ACCOUNT_ID , AGENT_ID, ALIAS_IDand REGION with your actual values, then save the policy.</p><h4>Setting up Slack Event Subscriptions</h4><p>Go back to the <strong>Slack API Console</strong> for your app:</p><p>Navigate to <strong>Event Subscriptions </strong>and toggle the feature <strong>ON.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SthgvsqwyP7TK-IV08hWiw.png" /></figure><p>In the <strong>Request URL</strong> field, paste the URL of your lambdaReceiver function.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jJLx1hP9mAuoNkFvZ09s-g.png" /></figure><p>Slack will send a test challenge event to verify the endpoint. If your Lambda code works as it should, a green “verify” status should be visible.</p><h4>Subscribe to events</h4><p>Under <strong>Subscribe to Bot Events</strong>, add:</p><ul><li>message.im – to receive direct messages</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*f_OfnnqQOoNbpYUDB6Ikng.png" /></figure><p>Save changes and <strong>reinstall</strong> the app.</p><p>Return to your lambdaReceiver code and uncomment the async logic that forwards the event to lambdaSlackResponse.Remove or comment out any placeholder logic used only for the challenge response.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6hZsm3mszUKJKBBcFd-Qnw.png" /></figure><p>Click “<strong>Deploy”</strong> to update the function.</p><p>Now you can go to Slack and ask questions about your codebase!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*06ntkMZx6xvN2C1NHffvIQ.png" /></figure><h4>Don’t forget to tear it all down</h4><p>Before you close your laptop and move on to the next thing, take a minute to clean up your AWS account. Trust me, forgetting to shut down cloud services can lead to unexpected charges during your next invoice.</p><p>Here’s what I made sure to delete once I was done:</p><ul><li>The <strong>Bedrock agent</strong></li><li>The <strong>Knowledge Base</strong> ( and the <strong>Collection</strong> in OpenSearch)</li><li>The <strong>S3 bucket</strong></li><li>Both <strong>Lambda functions</strong>: lambdaReceiver and lambdaSlackResponse</li><li><strong>IAM roles</strong></li><li>Optional but nice: <strong>CloudWatch log groups</strong></li><li>The <strong>Slack app</strong></li></ul><p>I recommend checking out the <strong>AWS Cost Explorer</strong> and setting up an <strong>AWS Budget alert</strong> if you’re playing around with multiple services. It’s a helpful safety net.</p><h4>Conclusion</h4><p>This whole project was an engaging and concise POC, a playground more than a production setup. There are definitely other ways to build something similar.</p><p>You could swap in Pinecone instead of OpenSearch, or try a different orchestration with Step Functions, or even layer in RAG pipelines with memory.</p><p>This report was a great exercise for me, I enjoyed breaking all the steps down and trying to understand it from its roots. This exercise helped me to better understand how AI services fit into real-world workflows. I also wanted to give other developers a hands-on, example of how to wire all this up.</p><p>If you’re like me and you learn best by breaking things down and connecting dots yourself, then, I hope this gave you a solid foundation to build on.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b0ee00d82f0c" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>