<?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 Debadatta Panda on Medium]]></title>
        <description><![CDATA[Stories by Debadatta Panda on Medium]]></description>
        <link>https://medium.com/@debadatta30?source=rss-318e9db4dae------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*degyRwuLbaNd76Nbd_z2ng.jpeg</url>
            <title>Stories by Debadatta Panda on Medium</title>
            <link>https://medium.com/@debadatta30?source=rss-318e9db4dae------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 03:56:41 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@debadatta30/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 Secure MCP Server on AWS ECS Fargate]]></title>
            <link>https://debadatta30.medium.com/building-a-secure-mcp-server-on-aws-ecs-fargate-b9d11d9e760e?source=rss-318e9db4dae------2</link>
            <guid isPermaLink="false">https://medium.com/p/b9d11d9e760e</guid>
            <category><![CDATA[auth0]]></category>
            <category><![CDATA[mcp-server]]></category>
            <category><![CDATA[claude-desktop]]></category>
            <category><![CDATA[elastic-container-service]]></category>
            <dc:creator><![CDATA[Debadatta Panda]]></dc:creator>
            <pubDate>Wed, 19 Aug 2026 09:34:02 GMT</pubDate>
            <atom:updated>2026-08-19T09:34:02.925Z</atom:updated>
            <content:encoded><![CDATA[<p>AI agents become genuinely useful the moment they can do something, not just talk about it pull data, take an action on a live system, call an API. The Model Context Protocol (MCP) makes this possible in a standardised way: it defines how an LLM can discover and call external tools, whether that’s a database, a SaaS API, or in this case, an AWS service.</p><p>Most MCP demos, though, run locally — a server spawned as a subprocess on your laptop, talking over stdin/stdout, with no authentication because it never leaves your machine. That’s fine for a proof of concept, but it doesn’t reflect how this would actually run inside a company: multiple users, a server that’s always available, and real access control on what the agent is allowed to touch.</p><p>So the question we set out to answer was simple: how do you take an MCP server out of “local demo” mode and run it as a proper, secured, always-on service in AWS — and have it manage something real, like <a href="https://aws.amazon.com/pm/serv-s3/?trk=aebc39a1-139c-43bb-8354-211ac811b83a&amp;sc_channel=ps&amp;ef_id=EAIaIQobChMIy8v73MiqlgMVgpRQBh23BDp5EAAYASAAEgLRrPD_BwE&amp;gads_camp=23523528411&amp;gads_ag=189966174142&amp;gads_ad=795841362691&amp;gads_kw=amazon%20s3&amp;gads_matchtype=e&amp;gads_network=g&amp;gads_device=c&amp;gads_geo=9215775&amp;gad_campaignid=23523528411&amp;gbraid=0AAAAADjHtp_TtXp5xL31VoY86ByF4CstM&amp;gclid=EAIaIQobChMIy8v73MiqlgMVgpRQBh23BDp5EAAYASAAEgLRrPD_BwE">Amazon S3</a>.</p><p>This post walks through how we built exactly that: an MCP server hosted on <a href="http://Amazon Elastic Container Service">Amazon Elastic Container Service</a> ( ECS Fargate ) , sitting behind <a href="https://aws.amazon.com/cloudfront/">Amazon CloudFront </a>and an Application Load Balancer, authenticated with Auth0 via OAuth PKCE, calling <a href="https://aws.amazon.com/pm/serv-s3/?trk=aebc39a1-139c-43bb-8354-211ac811b83a&amp;sc_channel=ps&amp;ef_id=EAIaIQobChMI6o284KyslgMVap1QBh3m_idHEAAYASAAEgLrt_D_BwE&amp;gads_camp=23523528411&amp;gads_ag=189966174142&amp;gads_ad=795841362691&amp;gads_kw=amazon%20s3&amp;gads_matchtype=e&amp;gads_network=g&amp;gads_device=c&amp;gads_geo=9215775&amp;gad_campaignid=23523528411&amp;gbraid=0AAAAADjHtp_6DaEUPXiLO1Umx1k0Fo9ZH&amp;gclid=EAIaIQobChMI6o284KyslgMVap1QBh3m_idHEAAYASAAEgLrt_D_BwE">Amazon S3 </a>through a least-privilege IAM task role and connected to Claude Desktop through its remote-connector UI.</p><p>The full code is on GitHub: <a href="https://github.com/debadatta30/s3-mcp-server">debadatta30/s3-mcp-server</a>.</p><h4>The use case:</h4><p>Give your team a safe, auditable way to let Claude inspect S3 from inside Claude Desktop — list buckets, read bucket ACLs and policies — without handing anyone AWS credentials and without Claude ever touching write operations. Auth0 decides <em>who</em> can connect; an IAM task role decides <em>what</em> the server can do; and the read-only tool surface means the blast radius is bounded by design.</p><p>Concretely, the server exposes tools like list_buckets, list_objects, get_bucket_public_access, and get_bucket_size. A user in Claude Desktop asks &quot;which of our buckets are publicly accessible?&quot; and Claude calls the tools to answer — but only after a real login, and only ever reading. You can build other use cases on the same design — swap S3 for any API or service the agent should reach.</p><h4>The architecture at a glance:</h4><p>There are two distinct planes, and keeping them separate is the key to understanding the whole system.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LC1mZ4RaDXD02K9I7vwXdQ.png" /><figcaption>Reference Architecture</figcaption></figure><p><strong>The data plane</strong> is where tool calls travel. CloudFront terminates TLS at the edge and forwards the request — crucially including the Host and Authorization headers — to an internal ALB over plain HTTP inside the VPC. The ALB hands it to the Fargate task on port 8080.</p><p><strong>The control plane</strong> is the OAuth handshake, and the MCP server is almost entirely absent from it. Claude Desktop discovers Auth0 from the server’s own metadata, then runs a standard PKCE code exchange <em>directly against Auth0</em>. The only artifact that ever reaches the MCP server is the resulting access token.</p><h4>The OAuth flow, step by step:</h4><p>This is the part worth getting precise, because when it breaks, it breaks <em>silently</em> in the MCP server’s logs — the server isn’t in the loop for most of it.</p><ol><li>Claude Desktop requests GET /.well-known/oauth-protected-resource from the MCP server.</li><li>The server responds with { resource, authorization_servers: [Auth0] } — pointing Claude at Auth0.</li><li>Claude Desktop calls GET /authorize on Auth0 with PKCE parameters, an audience, and scopes.</li><li>The user logs in and authenticates; Auth0 returns an authorization code.</li><li>Claude Desktop calls POST /oauth/token with the code, the PKCE verifier, and the client secret.</li><li>Auth0 returns an access_token — a JWT with aud set to .../sse.</li><li>Claude Desktop finally calls GET /sse on the MCP server with Authorization: Bearer &lt;token&gt;.</li></ol><p>Steps 3–6 happen entirely between Claude Desktop and Auth0. The MCP server only ever sees step 1, step 2, and step 7. This is <em>why</em> a failed token exchange never appears in the server’s logs — it was never a participant. When you’re debugging “login isn’t working,” you have to look at Auth0’s logs, not the server’s.</p><p>On step 7, the server verifies the token’s signature and audience <strong>locally</strong>, against Auth0’s JWKS which it caches for an hour. No network round-trip to Auth0 on every request.</p><h4>Connecting Claude Desktop:</h4><p>Claude Desktop supports remote MCP servers as connectors: you point it at the deployed /sse URL and give it the Auth0 Application&#39;s Client ID and Secret, and it handles the OAuth redirect and token exchange for you per the MCP authorization spec. From then on, the server only ever validates the resulting bearer token on each request — it never sees the login itself.</p><p>That division is exactly why the debugging advice above matters. Because Claude Desktop drives steps 3–6 directly against Auth0, a failed token exchange leaves no trace in the server’s logs. When login misbehaves, the useful signal is in Auth0’s tenant logs and in Claude Desktop’s own connector diagnostics, not in the container.</p><h4>Auth0 setup</h4><p>You need an Auth0 tenant (the free tier is enough) with two objects, and one linkage step that’s easy to miss.</p><ol><li><strong>Create an API.</strong> This is what makes Auth0 issue real JWT access tokens instead of opaque ones. Set its <strong>Identifier</strong> to the exact URL clients connect to — e.g. https://&lt;dist&gt;.cloudfront.net/sse. This becomes AUTH0_AUDIENCE and must match byte-for-byte what you deploy behind. Signing algorithm: RS256.</li><li><strong>Create an Application</strong> of type <em>Regular Web Application</em>. Set <strong>Allowed Callback URLs</strong> to your client’s redirect URI. Note the <strong>Domain</strong>, <strong>Client ID</strong>, and <strong>Client Secret</strong> — the client uses these; the server never needs the secret.</li><li><strong>Authorize the Application for the API.</strong> Go to the API → <strong>Application Access</strong> tab → toggle your Application on. Creating the two objects separately does <em>not</em> link them — skip this and every attempt fails with invalid_request / &quot;Client is not authorized to access resource server,&quot; <em>before the client ever sees a login page</em></li></ol><h4>Conclusion:</h4><p>The design principle threading through all of this is separation of authority. Auth0 owns identity; the IAM task role owns AWS permissions; the read-only tool surface owns the blast radius. The MCP server itself holds no long-lived secrets — not AWS keys, not user passwords — it just verifies a token it didn’t issue and signs S3 calls with a role it didn’t create. That’s what makes a remote MCP server safe enough to point a whole team at.</p><p>The full implementation, including the CDK stack, is at <a href="https://github.com/debadatta30/s3-mcp-server">debadatta30/s3-mcp-server</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b9d11d9e760e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[AgentCore Harness with a Github Pull Request Agent]]></title>
            <link>https://debadatta30.medium.com/agentcore-harness-with-a-github-pull-request-agent-ffb1d1fc210f?source=rss-318e9db4dae------2</link>
            <guid isPermaLink="false">https://medium.com/p/ffb1d1fc210f</guid>
            <category><![CDATA[agent-harness]]></category>
            <category><![CDATA[aws-bedrock-agent]]></category>
            <category><![CDATA[amazon-bedrock-agentcore]]></category>
            <dc:creator><![CDATA[Debadatta Panda]]></dc:creator>
            <pubDate>Wed, 08 Jul 2026 16:17:28 GMT</pubDate>
            <atom:updated>2026-07-08T16:17:28.446Z</atom:updated>
            <content:encoded><![CDATA[<p><a href="https://docs.aws.amazon.com/bedrock-agentcore/latest/devguide/harness.html">Amazon Bedrock AgentCore Harness</a> is a fully managed agent execution service. You define what an agent should be — its model, its system prompt, the tools it can call — and the service runs it.</p><p><strong><em>agent = model + harness.</em></strong> The model supplies the intelligence. The harness is everything that makes that intelligence usable in production: the execution loop, isolated compute, tool connectivity, memory, streaming, and observability.</p><p>Underneath, the harness is powered by Strands Agents — AWS’s own agent framework, already validated across many production workloads — and deployed on AgentCore Runtime. The harness isn’t a new, separate thing bolted on top. It’s a managed configuration layer over infrastructure that already exists and already works.</p><h4><strong>Harness Provides:</strong></h4><p><strong>Agent loop:</strong> Call the model, decide whether to use a tool, execute it, repeat until done. You don’t write this.</p><p><strong>Isolated compute per session</strong>: Each session runs in its own Firecracker microVM, with its own filesystem and shell.</p><p><strong>Tool connectivity:</strong> Point the harness at an MCP server or AgentCore Gateway target; the harness handles protocol and auth<strong>.</strong></p><p><strong>Streaming by default:</strong> Invocation responses arrive as a stream of events, so progress and tool calls are visible in real time.</p><p><strong>Built-in observability:</strong> every invocation is automatically traced as OpenTelemetry-compatible spans, with token counts and latency, no manual instrumentation needed.</p><p><strong>Config over redeploy:</strong> Changing the model, system prompt, or tools attached is a configuration update, not a container rebuild.</p><p><strong>Runtime capabilities inherited:</strong> Attach extra storage, execute shell commands, bring your own container — because the harness runs on AgentCore Runtime underneath.</p><p>All of that is what you get. None of it requires writing it yourself — it comes from one action: creating a harness. To explain this we will use-case of : reviewing a pull request on GitHub called PR Review Agent.</p><p><strong>PR Review Agent:</strong></p><p>When invoked with a PR number, the goal is for the agent to:</p><p>1. Read the PR diff and metadata via GitHub MCP</p><p>2. Read existing review comments, so it doesn’t repeat feedback</p><p>3. Reason over the actual code changes</p><p>4. Post a structured review back to GitHub</p><p>5. Reply with the full review text as its final message</p><p>Every team has the same problem with code review: PRs sit in a queue, reviewers are context-switching, and review depth depends entirely on how much attention a reviewer happens to have that day. It’s a good test for a harness-based agent because it requires a full READ → REASON → WRITE loop against an external system, not just a single tool call.</p><p><strong>Step 1 — Create the Harness:</strong></p><p>That’s the <strong>Create Harness</strong> step for our agent — model, system prompt, and the GitHub MCP tool flow into a single agent configuration, which the harness then runs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/927/1*UQ_fchh4xODghewgRsvhHw.png" /><figcaption>Create Harness</figcaption></figure><p>The minimum required to define an agent is a name, an execution role, and a model:</p><pre>resp = control.create_harness(<br>    harnessName=&#39;pr_review_agent&#39;,   # letters, numbers, underscores only<br>    executionRoleArn=ROLE_ARN,<br>    model={&#39;bedrockModelConfig&#39;: {&#39;modelId&#39;: &#39;us.anthropic.claude-sonnet-4-6&#39;}},<br>    systemPrompt=[{&#39;text&#39;: SYSTEM_PROMPT}],   # &#39;You are a senior engineer reviewing PRs...&#39;<br>    maxIterations=30,<br>    maxTokens=16384,<br>)<br>harness_arn = resp[&#39;harness&#39;][&#39;arn&#39;]</pre><p><strong>Step 2 — Invoking — and Overriding at Runtime</strong></p><p>Once a harness is READY , invoking it is a single call. What makes this genuinely useful is that almost everything — model, system prompt, tools, skills — can be overridden per invocation, without touching the harness’s stored configuration:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/769/1*HVZtBGN4FJ3-PVlxrvEtxA.png" /></figure><pre>response = data.invoke_harness(<br>    harnessArn=harness_arn,           # full ARN, not the short harnessId<br>    runtimeSessionId=session_id,      # 33+ chars, unique per session<br>    tools=[{<br>        &#39;type&#39;: &#39;remote_mcp&#39;,<br>        &#39;name&#39;: &#39;github&#39;,<br>        &#39;config&#39;: {&#39;remoteMcp&#39;: {<br>            &#39;url&#39;: &#39;https://api.githubcopilot.com/mcp/v1&#39;,<br>            &#39;headers&#39;: {&#39;Authorization&#39;: f&#39;Bearer {GITHUB_TOKEN}&#39;}<br>        }}<br>    }],<br>    messages=[{&#39;role&#39;: &#39;user&#39;, &#39;content&#39;: [{&#39;text&#39;: &#39;Review PR #1 in owner/repo&#39;}]}</pre><p>The complete flow, you create the harness one time and invoke this, Each invocation spins an isolated Firecracker microVM. The harness manages the full agent loop.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/809/1*hntfEgqhlF_LDD_buWstuQ.png" /><figcaption>Flow Diagram of he GitHub PR Agent</figcaption></figure><p><strong>Setup GitHub MCP</strong></p><p>Personal Access Token:</p><p>1. github.com → Settings → Developer settings → Fine-grained tokens</p><p>2. Generate new token, scoped to the repos you want reviewed</p><p>3. Permissions: Pull requests → Read and Write, Contents → Read-only</p><p>4. Generate and copy the token — it won’t be shown again</p><p>GitHub’s hosted MCP endpoint (beta as of June 2026):</p><p><a href="https://api.githubcopilot.com/mcp/v1">https://api.githubcopilot.com/mcp/v1</a></p><p><strong>The Concepts the PR Agent Just Demonstrated:</strong></p><p>Watching that build run end to end surfaces a handful of platform behaviours worth understanding properly — each one is the reason something in the walkthrough above worked the way it did.</p><p><strong>Runtime Overrides — Why the Tool Is Attached at Invoke, Not Create</strong></p><p>Almost everything about a harness — model, system prompt, tools, skills — can be overridden per invocation, without touching the harness’s stored configuration. That’s exactly what happened above: the GitHub MCP tool was never part of create_harness, only invoke_harness.</p><p>This isn’t just a convenience for testing. It does two distinct jobs:</p><p>•try a different model, a different system prompt, a new tool, without redeploying. Useful constantly during development.Faster iteration</p><p>• the same harness template can serve many different customers or tenants, each getting a different system prompt, a different set of allowed tools, or different branding, purely through what’s passed at invocation.Production personalization and multi-tenancy</p><p><em>Applied to the PR agent: the same harness could review PRs for different repos with different review standards, just by changing the prompt and token passed at invoke time — no new harness needed per repo.</em></p><p><strong>Context Management — Why Only One Tool Was Attached</strong></p><p>This is easy to miss: tool access isn’t just a capability switch, it’s also a cost control. If a tool isn’t passed to a given invocation, the agent cannot use it — full stop. That’s the most granular access control available: don’t share the tool at all, rather than relying on the model to decline using it.</p><p>There’s a second effect. Fewer tools attached means a smaller system prompt and a smaller context window per call, which means lower token cost and faster responses. The PR review agent only ever gets the GitHub MCP tool — not Jira, not Slack — because the task only ever needs GitHub. Attaching tools the task doesn’t need would only add cost and risk for no benefit.</p><p><strong>Models Beyond Bedrock</strong></p><p>The harness defaults to Bedrock models, but isn’t limited to them. OpenAI and Gemini models are supported directly, along with any provider that implements an OpenAI-compatible API. The PR agent above uses Claude Sonnet, but swapping modelId to a faster, cheaper model for small PRs (and keeping Sonnet for complex ones) is a one-line change, made per invocation if needed.</p><p><strong>Memory — What It Would Add Here</strong></p><p>The PR agent’s session already persists in its microVM for a period of time (up to roughly 8 hours), so within one run, short-term context is already there for free. Memory becomes relevant beyond that: if the agent should remember a repo’s coding conventions across separate PR reviews, days apart, attaching an AgentCore Memory resource is what bridges that gap — a configuration addition, not new code. Not exercised in this build, but the next thing worth trying.</p><p><strong>AgentCore Gateway</strong></p><p>GitHub’s MCP server already speaks the protocol the harness expects. Not every API does. AgentCore Gateway closes that gap: give it an OpenAPI schema for an API that isn’t MCP-native, and it exposes those endpoints as MCP tools automatically — no MCP server to write. Relevant the moment this agent needs to talk to something that doesn’t already have an MCP server, like an internal ticketing system.</p><p><strong>Observability — What’s Actually Traced</strong></p><p>Every harness invocation above is automatically traced. A single session produces multiple spans — tool calls, model calls — all OpenTelemetry-compatible, with full token counts and latency per step. In practice this means the PR review run’s entire decision trail is inspectable after the fact: not just “the agent posted a review,” but the specific tool call, the specific input, and the specific response that led there.</p><p><strong>Try It Yourself:</strong></p><p>The full code is on GitHub. You need Python 3.10+, an AWS account with Bedrock enabled, and a GitHub Personal Access Token with PR read/write permissions.</p><pre># Clone the repo<br>git clone https://github.com/debadatta30/agentcore-pr-review-agent<br>cd agentcore-pr-review-agent<br><br># Install dependencies<br>pip install -r requirements.txt<br><br># Run against a real PR<br>GITHUB_TOKEN=ghp_xxx python pr_review_agent.py \<br>  --owner your-org --repo your-repo --pr 1</pre><p><strong>Conclusion:</strong></p><p>Everything the harness provides — the managed loop, isolated compute, declarative tools, streaming, observability — isn’t a feature list to take on faith. It’s exactly what showed up while building one real, multi-step agent: reading a pull request, reasoning over it, and writing a review back, with nothing written but a system prompt and a tool URL.</p><p>That’s the case for harness engineering in one sentence: not faster AI, but a faster path from idea to a production agent doing real, multi-step work against real systems.</p><p><strong>Resources:</strong></p><p>• Full runnable script + setup notes: <a href="https://github.com/debadatta30/agentcore-pr-review-agent">github.com/debadatta30/agentcore-pr-review-agent</a></p><p>• AgentCore Harness docs: <a href="https://docs.aws.amazon.com/bedrock-agentcore/latest/devguide/harness.html">docs.aws.amazon.com/bedrock-agentcore/latest/devguide/harness.html</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ffb1d1fc210f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building Smarter AI Agents with AWS Strands and Claude Interleaved Thinking]]></title>
            <link>https://debadatta30.medium.com/building-smarter-ai-agents-with-aws-strands-and-claude-interleaved-thinking-304a3d1b15f2?source=rss-318e9db4dae------2</link>
            <guid isPermaLink="false">https://medium.com/p/304a3d1b15f2</guid>
            <dc:creator><![CDATA[Debadatta Panda]]></dc:creator>
            <pubDate>Fri, 15 May 2026 14:46:48 GMT</pubDate>
            <atom:updated>2026-05-15T14:46:48.814Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Building Smarter AI Agents with AWS Strands and Claude Interleaved Thinking</strong></p><p>AI agents have come a long way from simple chatbots that answer questions. Today, developers expect agents to perform multi-step tasks — fetching live data, making decisions based on results, and producing a coherent final output. But there’s a subtle problem that emerges as agents grow more complex: you can see what the agent did, but not why.</p><p>AWS Strands Agents SDK, combined with Claude 4’s interleaved thinking feature, changes that. Together, they make an agent’s reasoning visible between every tool call — not just at the end — so you can understand, audit, and trust every decision it makes. In this post, we’ll show exactly what that looks like using a real-world travel planning agent.</p><p><strong>The Problem with Traditional Agentic Loops</strong></p><p>Most AI agent frameworks follow a pattern called ReAct (Reason + Act). The model makes a plan, calls a tool, waits for the result, then starts a brand new reasoning loop to decide what to do next. This works — but has a fundamental limitation.</p><p>The model’s reasoning is invisible between steps. You see tool calls and tool results. You see the final output. But the logic connecting them — why the agent called tools in that order, how it interpreted a surprising result, what trade-offs it made — is completely hidden inside the model.</p><p>In development this is an inconvenience. In production, where you need to explain agent behaviour, catch decision errors early, and debug failures, it becomes a real problem.</p><p><strong>What is Interleaved Thinking?</strong></p><p>Interleaved thinking gives Claude the ability to reason immediately after receiving a tool result — before deciding the next action — all within the same loop iteration.</p><p>Instead of a rigid:</p><pre>Think → Act → (new loop) → Think → Act</pre><p>You get a continuous:</p><pre>Think → Act → Think → Act → Think → Act</pre><p>Crucially, those thinking blocks are visible in the output. Claude shows its reasoning after each result — what it noticed, what changed from its original plan, and why it’s making the next call. This is the difference between an agent that produces an answer and an agent whose entire reasoning chain you can read and verify.</p><p><strong>How It Works in AWS </strong><a href="https://strandsagents.com/"><strong>Strands</strong></a></p><p>Strands is built around a model-driven approach. You give the agent a model, a set of tools, and a prompt — and Strands manages the event loop automatically. There is no workflow engine to configure, no manual parsing of model responses, and no rigid step definitions to maintain.</p><p>Enabling interleaved thinking on Bedrock requires just a small configuration change:</p><pre>from strands import Agent, tool<br>from strands.models import BedrockModel<br>model = BedrockModel(<br>    model_id=&quot;us.anthropic.claude-sonnet-4-5-20250929-v1:0&quot;,<br>    max_tokens=8000,<br>    temperature=1,  # Required when thinking is enabled<br>    additional_request_fields={<br>        &quot;anthropic_beta&quot;: [&quot;interleaved-thinking-2025-05-14&quot;],<br>        &quot;reasoning_config&quot;: {<br>            &quot;type&quot;: &quot;enabled&quot;,<br>            &quot;budget_tokens&quot;: 5000<br>        }<br>    }<br>)<br>agent = Agent(model=model, tools=[...])</pre><p>Your agent logic, tools, and prompts stay exactly the same. The only change is that the model’s reasoning between tool calls becomes visible — and that single change meaningfully improves how you can observe, debug, and trust the agent.</p><p><strong>A Real Example: Weekend Itinerary Agent</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ask3kIL_YfJYT2guu-OTXA.png" /></figure><p>To make this concrete, let’s look at a travel planning agent tasked with building a Paris weekend itinerary. This sample code for this example can be found at <a href="https://github.com/debadatta30/interleaved-thinking-travel-agent/blob/main/interleaved-thinking-travel-planner.ipynb">interleaved-thinking-travel-agent.ipynb </a>. The agent needs to check weather, find accommodation within budget, research attractions, and produce a structured day-by-day plan. Two surprises are deliberately built into the mock data:</p><ol><li><strong>Weather returns heavy rain</strong> — an outdoor-focused plan must pivot to indoor attractions</li><li><strong>$95/night budget finds no hotels</strong> — accommodation must be handled with alternatives</li></ol><p>Here is the prompt:</p><pre>TRIP_REQUEST = &quot;&quot;&quot;<br>Plan a weekend trip to Paris (June 14-16, 2025) for two people.<br>Preferences: French cuisine, budget $95/night for accommodation.<br>Interests: art, history, food.<br>Deliver a complete day-by-day itinerary.<br>&quot;&quot;&quot;</pre><p><strong>Without Interleaved Thinking</strong></p><p>The agent calls weather, hotel availability, and restaurant tools, then waits for all results before calling the attractions tool. It produces a complete, coherent itinerary — correctly pivoting to indoor attractions after seeing the rain forecast, and correctly offering hotel alternatives when the $95 budget came back with no results.</p><p>The output is solid. But here’s what you can’t see: you have no visibility into why the agent chose to sequence tools the way it did, how it interpreted the hotel failure, or what logic it applied when deciding which alternatives to surface. If this agent were deployed in production and produced an unexpected result, tracing the cause back to a specific reasoning step would require re-running it and guessing.</p><p><strong>With Interleaved Thinking</strong></p><p>With interleaved thinking enabled, the agent produces an equivalent final itinerary — same quality, same handling of the rain and budget surprises. But now, between every tool call, a reasoning block appears:</p><blockquote>“The user wants Paris for June 14–16. I should check weather first since it drives attraction choices. I can check hotel availability and restaurants in parallel since those don’t depend on weather — but I need to wait for the weather result before calling get_top_attractions.”</blockquote><blockquote>“Heavy rain throughout the weekend. Outdoor activities are out — Eiffel Tower, Champs-Élysées, Seine cruise all need to go. I’ll pass the weather context to get_top_attractions and expect an indoor-focused list.”</blockquote><blockquote>“$95/night returns no availability. Paris minimum is $120. Rather than flagging this as a dead end, I should present tiered alternatives — hostels for the budget-strict traveler, a slightly-over-budget hotel for comfort, suburban options for flexibility.”</blockquote><p>The final itinerary is the same quality as the non-thinking version. The difference is that every decision along the way is visible, explained, and auditable. You can see exactly how the agent handled each surprise — not just that it did.</p><p><strong>The Real Benefits</strong></p><p><strong>Auditability.</strong> Every decision the agent makes is explained in the reasoning block that precedes it. When an agent behaves unexpectedly in production, you can trace the failure back to the exact reasoning step where things went wrong — rather than working backward from the output.</p><p><strong>Transparent tool sequencing.</strong> The interleaved version explicitly shows why it waits for weather before calling attractions, and why it runs hotel and restaurant lookups in parallel. In the non-thinking version the sequencing is identical, but the logic is invisible. As workflows grow more complex, this distinction matters.</p><p><strong>Graceful handling of unexpected results.</strong> When the hotel API returned no results at the $95 price point, the reasoning block fired immediately: “The budget isn’t achievable — I should present alternatives rather than fail.” The agent’s response to the surprise is visible and verifiable, not inferred after the fact.</p><p><strong>Better debugging in complex workflows.</strong> For a task with four or five interdependent tool calls, being able to read the agent’s reasoning after each result is the difference between understanding your agent and guessing at it. This compounds as workflows scale.</p><p><strong>Try It Yourself</strong></p><p>The full working example from this post is available on GitHub:</p><pre>git clone https://github.com/debadatta30/interleaved-thinking-travel-agent.git<br>cd interleaved-thinking-travel-agent<br>pip install strands-agents strands-agents-tools</pre><p>Open interleaved-thinking-travel-planner.ipynb and run all cells. You&#39;ll need an AWS account with Amazon Bedrock access and Claude Sonnet 4.5 enabled in your region.</p><p>The notebook runs the same Paris itinerary request twice — with and without interleaved thinking — so you can compare the reasoning blocks directly. It’s also a good starting point for more complex use cases: swap the mock tools for real APIs, add more interdependent steps, or increase budget_tokens to give the model more room to reason through harder problems.</p><p><strong>When to Use It</strong></p><p>Interleaved thinking adds token overhead per step, so it is not the right choice for every task. It is most valuable when:</p><ul><li>Tasks involve multiple tool calls with interdependent results</li><li>You need to audit or explain agent decisions in production</li><li>Errors in one step would silently affect all subsequent steps</li><li>The agent needs to adapt its plan based on what tools return — and you need to see that adaptation</li></ul><p>For simple, single-tool tasks, a standard agent loop is faster and cheaper. But for complex, multi-step agentic workflows — travel planning, research agents, financial analysis, content generation with multiple data sources — interleaved thinking gives you visibility into the agent’s reasoning chain with almost no change to your existing code. In production, that visibility is what separates an agent you can trust from one you can only hope works correctly.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=304a3d1b15f2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building UKFuelFinder: A Privacy-First, Serverless Fuel Price App for the UK]]></title>
            <link>https://debadatta30.medium.com/building-ukfuelfinder-a-privacy-first-serverless-fuel-price-app-for-the-uk-f5a515949cf6?source=rss-318e9db4dae------2</link>
            <guid isPermaLink="false">https://medium.com/p/f5a515949cf6</guid>
            <dc:creator><![CDATA[Debadatta Panda]]></dc:creator>
            <pubDate>Thu, 23 Apr 2026 10:04:59 GMT</pubDate>
            <atom:updated>2026-04-23T10:04:59.411Z</atom:updated>
            <content:encoded><![CDATA[<p>In early 2026, while filling up my car, I noticed something interesting: the UK government had just mandated that all fuel retailers publish their prices to an open database. I immediately thought: “This is perfect API material.”</p><p>I wanted to build something useful — a clean, fast tool that would help me (and other UK drivers) find cheaper fuel nearby using official data. No account required, no tracking, no ads. Just a simple tool that works.</p><p><strong>The Challenge I Set Myself:</strong></p><ul><li>Build a mobile app AND website</li><li>Use official UK Government fuel price data</li><li>Keep it completely privacy-focused (no login, no tracking, zero data collection)</li><li>Make it serverless and cheap to run</li></ul><h4>Architecture: Fully Serverless on AWS</h4><p>I chose a serverless architecture because:</p><ol><li><strong>Zero server maintenance</strong> — I wanted to build features, not manage infrastructure</li><li><strong>Pay-per-use pricing</strong> — Perfect for a side project with unpredictable traffic</li><li><strong>Auto-scaling</strong> — From 0 to 10,000 users without changing a line of code</li><li><strong>Reliability</strong> — AWS handles the availability and redundancy</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/890/1*zxEWHSGWiOPzoTiTzF-M6A.png" /><figcaption>Reference Architecture</figcaption></figure><h4>Part 1: Data Pipeline — Syncing 7,312 Fuel Stations</h4><h4>The Goal</h4><p>Pull the latest fuel prices from the UK Government API every 3 hours and store them in DynamoDB.</p><h4>Implementation</h4><p><strong>Tech Stack:</strong></p><ul><li><strong>Trigger:</strong> <a href="https://aws.amazon.com/eventbridge/">Amazon EventBridge </a>(cron schedule)</li><li><strong>Compute:</strong> <a href="https://aws.amazon.com/lambda/">AWS Lambda</a> (Python 3.11)</li><li><strong>Storage:</strong> <a href="https://aws.amazon.com/dynamodb/">Amazon DynamoDB</a> (NoSQL, on-demand billing)</li></ul><p>Sample Lambda code:</p><pre>import json<br>import boto3<br>import requests<br>from datetime import datetime<br><br>dynamodb = boto3.resource(&#39;dynamodb&#39;)<br>table = dynamodb.Table(&#39;fuel-stations&#39;)<br><br>def lambda_handler(event, context):<br>    &quot;&quot;&quot;Fetch all UK fuel stations and sync to DynamoDB&quot;&quot;&quot;<br>    <br>    # Government API endpoint<br>    api_url = &quot;GovtAPIURL&quot;<br>    <br>    try:<br>        # Fetch all stations from government API<br>        response = requests.get(api_url, timeout=30)<br>        response.raise_for_status()<br>        data = response.json()<br>        <br>        stations = data.get(&#39;stations&#39;, [])<br>        print(f&quot;Fetched {len(stations)} stations from government API&quot;)<br>        <br>        # Process and store each station<br>        for station in stations:<br>            # Transform to our schema<br>            item = {<br>                &#39;id&#39;: station[&#39;id&#39;],<br>                &#39;brand&#39;: station[&#39;brand&#39;],<br>                &#39;name&#39;: station[&#39;name&#39;],<br>                &#39;address&#39;: station[&#39;address&#39;],<br>                &#39;postcode&#39;: station[&#39;postcode&#39;],<br>                &#39;latitude&#39;: float(station[&#39;location&#39;][&#39;latitude&#39;]),<br>                &#39;longitude&#39;: float(station[&#39;location&#39;][&#39;longitude&#39;]),<br>                &#39;fuel_prices&#39;: station.get(&#39;prices&#39;, []),<br>                &#39;last_updated&#39;: datetime.utcnow().isoformat()<br>            }<br>            <br>            # Write to DynamoDB<br>            table.put_item(Item=item)<br>        <br>        return {<br>            &#39;statusCode&#39;: 200,<br>            &#39;body&#39;: json.dumps({<br>                &#39;message&#39;: f&#39;Successfully synced {len(stations)} stations&#39;,<br>                &#39;timestamp&#39;: datetime.utcnow().isoformat()<br>            })<br>        }<br>        <br>    except Exception as e:<br>        print(f&quot;Error: {str(e)}&quot;)<br>        return {<br>            &#39;statusCode&#39;: 500,<br>            &#39;body&#39;: json.dumps({&#39;error&#39;: str(e)})<br>        }</pre><h4>Part 2: Query API — Finding Nearby Stations Fast</h4><h4>The Goal</h4><p>Given a latitude/longitude, find all fuel stations within a 10km radius, sorted by price or distance.</p><h4>The Challenge</h4><p>DynamoDB doesn’t have built-in geospatial queries. I needed to:</p><ol><li>Scan all 7,312 stations</li><li>Calculate distance to each one</li><li>Filter by radius</li><li>Sort by price or distance</li><li>Return results in 300ms</li></ol><h4>The Haversine Formula</h4><p>To calculate distance between two GPS coordinates, I implemented the Haversine formula:</p><pre>from math import radians, sin, cos, sqrt, asin<br><br>def haversine_distance(lon1, lat1, lon2, lat2):<br>    &quot;&quot;&quot;<br>    Calculate the great-circle distance between two points<br>    on Earth using the Haversine formula.<br>    <br>    Returns distance in meters.<br>    &quot;&quot;&quot;<br>    R = 6371000  # Earth&#39;s radius in meters<br>    <br>    # Convert to radians<br>    lon1, lat1, lon2, lat2 = map(radians, [lon1, lat1, lon2, lat2])<br>    <br>    # Haversine formula<br>    dlon = lon2 - lon1<br>    dlat = lat2 - lat1<br>    <br>    a = sin(dlat/2)**2 + cos(lat1) * cos(lat2) * sin(dlon/2)**2<br>    c = 2 * asin(sqrt(a))<br>    <br>    distance = R * c<br>    return distance</pre><p><strong>Why Haversine?</strong></p><ul><li>Accurate for distances up to ~500km</li><li>Computationally simple (no complex trigonometry)</li><li>Perfect for “nearby search” use cases</li></ul><p>Sample Lambda code:</p><pre>import json<br>import boto3<br>from math import radians, sin, cos, sqrt, asin<br><br>dynamodb = boto3.resource(&#39;dynamodb&#39;)<br>table = dynamodb.Table(&#39;fuel-stations&#39;)<br><br>def lambda_handler(event, context):<br>    &quot;&quot;&quot;Find fuel stations near given coordinates&quot;&quot;&quot;<br>    <br>    # Parse query parameters<br>    params = event.get(&#39;queryStringParameters&#39;, {})<br>    user_lat = float(params.get(&#39;lat&#39;))<br>    user_lon = float(params.get(&#39;lon&#39;))<br>    radius = int(params.get(&#39;radius&#39;, 10000))  # Default 10km<br>    <br>    # Get all stations from DynamoDB<br>    stations = []<br>    response = table.scan()<br>    stations.extend(response[&#39;Items&#39;])<br>    <br>    # Handle pagination<br>    while &#39;LastEvaluatedKey&#39; in response:<br>        response = table.scan(<br>            ExclusiveStartKey=response[&#39;LastEvaluatedKey&#39;]<br>        )<br>        stations.extend(response[&#39;Items&#39;])<br>    <br>    # Calculate distances and filter<br>    nearby_stations = []<br>    for station in stations:<br>        distance = haversine_distance(<br>            user_lon, user_lat,<br>            station[&#39;longitude&#39;], station[&#39;latitude&#39;]<br>        )<br>        <br>        if distance &lt;= radius:<br>            # Find cheapest fuel price<br>            prices = station.get(&#39;fuel_prices&#39;, [])<br>            cheapest = min(prices, key=lambda x: x[&#39;price&#39;]) if prices else None<br>            <br>            nearby_stations.append({<br>                &#39;id&#39;: station[&#39;id&#39;],<br>                &#39;brand&#39;: station[&#39;brand&#39;],<br>                &#39;name&#39;: station[&#39;name&#39;],<br>                &#39;address&#39;: station[&#39;address&#39;],<br>                &#39;postcode&#39;: station[&#39;postcode&#39;],<br>                &#39;latitude&#39;: station[&#39;latitude&#39;],<br>                &#39;longitude&#39;: station[&#39;longitude&#39;],<br>                &#39;distance&#39;: round(distance),<br>                &#39;price&#39;: cheapest[&#39;price&#39;] if cheapest else None,<br>                &#39;fuelType&#39;: cheapest[&#39;fuelType&#39;] if cheapest else None,<br>                &#39;fuelPrices&#39;: prices<br>            })<br>    <br>    # Sort by price (cheapest first)<br>    nearby_stations.sort(key=lambda x: x[&#39;price&#39;] if x[&#39;price&#39;] else float(&#39;inf&#39;))<br>    <br>    # Return top 30 results<br>    return {<br>        &#39;statusCode&#39;: 200,<br>        &#39;headers&#39;: {<br>            &#39;Access-Control-Allow-Origin&#39;: &#39;*&#39;,<br>            &#39;Content-Type&#39;: &#39;application/json&#39;<br>        },<br>        &#39;body&#39;: json.dumps({<br>            &#39;success&#39;: True,<br>            &#39;count&#39;: len(nearby_stations),<br>            &#39;stations&#39;: nearby_stations[:30]<br>        })<br>    }</pre><h4>Part 3: Website — Mobile-First Responsive Design</h4><h4>Tech Stack</h4><ul><li><strong>Hosting:</strong> <a href="https://aws.amazon.com/s3/">Amazon S3</a> + <a href="https://aws.amazon.com/cloudfront/">Amazon CloudFront</a> (global CDN)</li><li><strong>Frontend:</strong> HTML, CSS, JavaScript (vanilla)</li><li><strong>Maps:</strong> Google Maps JavaScript API</li><li><strong>SSL:</strong> AWS Certificate Manager (free)</li><li><strong>DNS:</strong> Route 53</li></ul><pre>User → CloudFront CDN → S3 Bucket (static files)<br>           ↓<br>     API Gateway → Lambda → DynamoDB<br>           ↓<br>     Google Maps API</pre><h4>Part 4: iOS App — Native Swift Experience</h4><h4>Tech Stack</h4><ul><li><strong>Language:</strong> Swift</li><li><strong>UI Framework:</strong> SwiftUI</li><li><strong>Maps:</strong> MapKit (Apple Maps)</li><li><strong>Networking:</strong> URLSession</li><li><strong>Location:</strong> CoreLocation</li></ul><p><strong>Key Points:</strong></p><p>1. Serverless is Perfect for Side Projects</p><ul><li>No infrastructure to maintain — I spend zero time on DevOps</li><li>Auto-scaling — Handles traffic spikes without intervention</li><li>Cost-effective — Pay only for what you use</li><li>Fast iteration — Deploy changes in seconds</li></ul><p>2. DynamoDB Pagination is Critical</p><ul><li>Always implement LastEvaluatedKey pagination</li><li>Don’t assume all data fits in one response</li><li>Test with production-scale data (not just 10 test records)</li></ul><p>3. Haversine Formula is “Good Enough”</p><ul><li>For distances &lt;500km, Haversine is accurate enough</li><li>No need for complex geospatial databases for 7K points</li><li>In-memory filtering is faster than you think</li></ul><p>4. Privacy-First Wins Trust</p><ul><li>No analytics = No privacy policy complexity</li><li>No accounts = Lower development effort</li><li>No tracking = No GDPR headaches</li><li>Users appreciate apps that “just work” without asking for data</li></ul><p>5. Official Data Sources Matter</p><ul><li>Government data = authoritative and trustworthy</li><li>Users prefer official sources over crowdsourced data</li><li>Timestamps show data freshness transparently</li></ul><p>6. Multi-Platform is Worth It</p><ul><li>iOS app — Better UX, native Apple Maps, App Store distribution</li><li>Website — Instant access, no install required, SEO discoverability</li><li>Shared backend — One API serves both platforms</li></ul><h3>Conclusion:</h3><p><strong>What I Built:</strong></p><ul><li>iOS app + website, both using the same serverless backend</li><li>7,312 UK fuel stations updated every 3 hours</li><li>Zero data collection, zero tracking, zero ads</li></ul><p><strong>The Results:</strong></p><ul><li>✅ Live on App Store: <a href="https://apps.apple.com/app/ukfuelfinder/id6760478585">UKFuelFinder</a></li><li>✅ 100% serverless — no servers to maintain</li><li>✅ Privacy-first — no login, no personal data, no analytics</li></ul><p><strong>Tech Stack Summary:</strong> AWS Lambda, DynamoDB, API Gateway, S3, CloudFront | Swift, SwiftUI, MapKit | HTML/CSS/JS, Google Maps</p><p><strong>Try It:</strong></p><ul><li><strong>iOS App:</strong> <a href="https://apps.apple.com/app/ukfuelfinder/id6760478585">https://apps.apple.com/app/ukfuelfinder/id6760478585</a></li><li><strong>Website:</strong> <a href="https://drivetofuel.co.uk/">https://drivetofuel.co.uk</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f5a515949cf6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building an AI-Powered Product Chat with Amazon S3 Vectors and Nova Lite: A Serverless RAG…]]></title>
            <link>https://debadatta30.medium.com/building-an-ai-powered-product-chat-with-amazon-s3-vectors-and-nova-lite-a-serverless-rag-55f2b54dcd01?source=rss-318e9db4dae------2</link>
            <guid isPermaLink="false">https://medium.com/p/55f2b54dcd01</guid>
            <dc:creator><![CDATA[Debadatta Panda]]></dc:creator>
            <pubDate>Wed, 04 Mar 2026 13:44:50 GMT</pubDate>
            <atom:updated>2026-03-04T13:44:50.079Z</atom:updated>
            <content:encoded><![CDATA[<h3>Building an AI-Powered Product Chat with Amazon S3 Vectors and Nova Lite: A Serverless RAG Implementation</h3><p>Vector databases were supposed to solve semantic search. Instead, they introduced a new category of infrastructure most teams weren’t ready to manage — separate clusters, capacity planning, and bills that scaled faster than their product did. Amazon S3 Vectors changes the equation. Vector search is now a capability inside S3 — the storage layer your team already trusts and operates.</p><p>Some of the challenges when Building a vector search system has forced teams to choose between <strong>complexity and cost</strong>:</p><ul><li>Managed vector databases can cost thousands of dollars per month.</li><li>Self-hosted open-source solutions introduce operational challenges — cluster management, replication strategies, and infrastructure that scales linearly with data volume.</li></ul><p>With<a href="https://aws.amazon.com/s3/features/vectors/"> <strong>Amazon S3 Vectors</strong></a>, vector search becomes dramatically simpler and more cost-effective.S3 Vectors isn’t just another vector database — it brings <strong>vector search directly into Amazon S3</strong>, the storage service most teams already rely on.</p><ul><li>No separate infrastructure</li><li>No cluster management</li><li>No capacity planning</li></ul><p>You simply store your vectors in S3 and query them like any other data. To explore this capability, we will built an <strong>intelligent product chat assistant</strong> using Amazon S3 Vectors and AWS serverless services. The assistant understands natural language queries and delivers real-time response stored for the products</p><h3>Two-Phase Architecture</h3><p>Before diving into the step-by-step flow, it helps to understand the two phases this system operates in. Every RAG-based system — regardless of the tech stack — follows this same fundamental pattern.</p><h3>Phase 1: Data Ingestion — Teaching the System About Your Products</h3><p>Think of this phase as the system doing its homework before any user shows up.</p><blockquote><em>Every product in your catalog — its name, description, category, and price — is transformed into a vector embedding using Amazon Bedrock’s Titan Embed model. These embeddings aren’t just compressed text. They’re numerical representations that capture </em>meaning<em>. Two products that serve the same purpose will have vectors that sit close together in space, even if their descriptions use completely different words.</em></blockquote><p>Here’s what happens during ingestion:</p><ol><li><strong>Product data is read</strong> from your catalog</li><li><strong>Titan Embed converts each product description</strong> into a 1536-dimensional vector</li><li><strong>Each vector is stored in an S3 Vector Bucket</strong> alongside its metadata — name, price, category, image URL</li></ol><p>This phase runs once at setup, and again whenever you add or update products. Your users never see it — but everything in Phase 2 depends on it being done well.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/728/1*IcIha4CmYqfOM1U872dGFA.png" /></figure><h3>Phase 2: Data Query — Answering What the User Actually Needs</h3><p>This is the phase that runs every time a user sends a message.</p><blockquote><em>The key insight here is that the user’s query goes through the </em>exact same embedding process<em> as your products did in Phase 1. This puts the query and your product catalog into the same mathematical space — making comparison possible.</em></blockquote><p>Here’s what happens during a query:</p><ol><li><strong>User submits a natural language query</strong> — <em>“I need wireless headphones for running”</em></li><li><strong>Titan Embed converts the query</strong> into a 1536-dimensional vector — the same format as your product embeddings</li><li><strong>S3 Vectors performs a cosine similarity search</strong> — finding the products whose vectors are closest to the query vector</li><li><strong>The top matching products are retrieved</strong> along with their metadata</li><li><strong>Nova Lite receives the query + matched products</strong> and generates a natural, conversational response</li></ol><p>The result is a system that understands <em>intent</em>, not just keywords. A user asking for <em>“something to listen to music while jogging”</em> will surface the same products as <em>“wireless earbuds for running”</em> — because semantically, they mean the same thing.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/487/1*P7_KX0urQpSg3-SYcnZkbQ.png" /><figcaption>Reference Architecture</figcaption></figure><h3>The Complete Flow</h3><p>Let’s trace what actually happens when a user sends a message.</p><p>Step 1: User Interaction</p><p>The user types their query into the chat interface hosted as a static website on S3. The React app sends a POST request to API Gateway with the user’s message.</p><p>Step 2: <a href="https://aws.amazon.com/api-gateway/">Amazon API Gateway</a> Routes the Request</p><p>API Gateway receives the request, validates it, and triggers the AWS Lambda function. CORS headers are automatically added to allow the frontend to communicate with the backend.</p><p>Step 3: AWS Lambda Orchestration Begins</p><p>The Lambda function receives the user query and starts the RAG (Retrieval Augmented Generation) process. This is where the magic happens.</p><p>Step 4: Query Embedding with Titan</p><p>Lambda sends the user’s query to Amazon Bedrock’s Titan Embed model:</p><ul><li><strong>Input:</strong> “I need wireless headphones for running”</li><li><strong>Output:</strong> A 1536-dimensional vector representing the semantic meaning</li></ul><p>This vector captures not just the keywords, but the intent — the user wants audio devices that are wireless and suitable for physical activity.</p><p>Step 5: Vector Similarity Search in S3</p><p>Lambda queries S3 Vectors with the query embedding:</p><ul><li>S3 Vectors performs cosine similarity search across all product embeddings</li><li>Returns the top 3 most similar products based on semantic relevance</li><li>Each result includes the product metadata (name, price, description, category)</li></ul><p>The search happens in milliseconds, even with thousands of products, because S3 Vectors is optimized for high-performance vector operations.</p><p>Step 6: AI Response Generation with Nova Lite</p><p>Lambda takes the user query and matched products and sends them to Amazon Bedrock’s Nova Lite model with a carefully crafted prompt:</p><pre>You are a helpful product assistant.<br>User query: I need wireless headphones for running<br>Available products:<br>- Wireless Bluetooth Earbuds (Sports, $79.99)<br>- Running Headband Headphones (Sports, $49.99)<br>- Wireless Bluetooth Headphones (Electronics, $129.99)<br>Provide a friendly, helpful response recommending the best product based on the user&#39;s needs.</pre><p>Nova Lite generates a natural, conversational response explaining why certain products match the user’s requirements.</p><p>Step 7: Response Delivery</p><p>Lambda returns a JSON response containing:</p><ul><li>The AI-generated message</li><li>Product details (name, price, image, description)</li><li>Similarity scores (optional)</li></ul><p>API Gateway forwards this back to the React frontend.</p><p>Why This Architecture Works in Production:</p><p><strong>1. Operational Simplicity</strong> No clusters, no patching, no capacity planning. S3 Vectors removes the ops burden that makes vector search painful at scale. From code to production in minutes, not hours — with CloudWatch logs and metrics available out-of-the-box.</p><p><strong>2. Semantic Intelligence Without Hallucinations</strong> The RAG pattern grounds every response in real product data. Nova Lite never invents products that don’t exist. Users describe what they need in their own words, and the system finds meaning — not just matching keywords.</p><p><strong>3. Cost That Scales With Usage</strong> Serverless means you pay only when users are active. No idle infrastructure, no fixed monthly minimums. Compute only runs when needed, and costs scale linearly with actual usage — not with catalog size.</p><h3>Conclusion</h3><p>Amazon S3 Vectors doesn’t just simplify vector search — it removes the biggest barrier to building AI-powered applications: the infrastructure burden.</p><p>With a single Lambda function, Bedrock embeddings, and S3 Vectors, you have a production-ready semantic search system that scales automatically, costs almost nothing at rest, and takes hours — not weeks — to deploy.</p><p>🔗 <strong>Explore the code</strong> → <a href="https://github.com/debadatta30/awss3vector-productchat.git">GitHub Repo</a></p><p>▶️ <strong>Watch the walkthrough</strong> → <a href="https://youtu.be/yLfnRqcwEWo">YouTube</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=55f2b54dcd01" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Agentic AI with Strands to Create Video Ads from Your Prompts]]></title>
            <link>https://debadatta30.medium.com/agentic-ai-with-strands-to-create-video-ads-from-your-prompts-af5f16395125?source=rss-318e9db4dae------2</link>
            <guid isPermaLink="false">https://medium.com/p/af5f16395125</guid>
            <dc:creator><![CDATA[Debadatta Panda]]></dc:creator>
            <pubDate>Wed, 03 Sep 2025 12:25:53 GMT</pubDate>
            <atom:updated>2025-09-03T12:25:53.481Z</atom:updated>
            <content:encoded><![CDATA[<p>As AI continues to evolve, a major shift is underway — from simple chatbots and task-specific scripts to agentic AI: intelligent systems that can reason, make decisions, and take autonomous actions in pursuit of a goal. These agents aren’t just passive responders; they plan, reflect, use tools, and even collaborate with other agents to solve complex problems.</p><p>This shift has led to the creation of frameworks like <a href="https://strandsagents.com/latest/">Strands Agents </a>— an open-source SDK designed to make it dramatically easier to build such smart, autonomous systems. Strands Agents combine the powerful reasoning abilities of large language models (LLMs) with modular tools and workflows to create AI agents that can truly act.</p><p>With Strands Agents, developers can build and customize intelligent workflows with very little code, while retaining full control over tool integration, model selection, deployment environments, and agent behaviour.</p><p>In this post, we’ll take a closer look at what agentic AI really means, how Strands Agents simplify its development, and how teams are already applying it to solve real-world challenges across industries. Before we start the use case, let’s understand the Strands Agent framework.</p><h3>Core Components of the Strands Agent Framework:</h3><p><strong>Structured workflows:</strong> Automate decision-making, tool use, and response generation in a clear loop.</p><p><strong>Session &amp; memory support:</strong> Keep context across interactions for smarter, personalized behaviour.</p><p><strong>Multi-agent orchestration:</strong> Let specialized agents collaborate on complex tasks.</p><p><strong>Tool integration:</strong> Easily plug in MCP tools and APIs — functions that agents know when and how to use.</p><p><strong>Multi-model flexibility:</strong> Use and switch between different LLMs (e.g., GPT, Claude, Nova).</p><p><strong>Production-ready:</strong> Built-in logging, monitoring, and error handling for real-world use.</p><h3>Use Case:</h3><p>Traditional video ad creation is expensive, time-consuming, and requires multiple specialists (copywriters, designers, video editors, voice actors), often taking weeks and significant budgets to produce a single advertisement. This AWS architecture revolutionizes the entire creative workflow by using the Strands Agent to intelligently orchestrate five specialized AI tools — Amazon Nova Lite for content strategy, Nova Canvas for visuals, Nova Reel for video creation, Amazon Polly for voiceovers, and automated merging — all running on scalable Amazon ECS infrastructure.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TyQ0E5d18r1s7zPuDkatqg.png" /><figcaption>Reference Architecture Diagram</figcaption></figure><p>The above solution reference for automated video advertisement generation using AWS managed services and AI capabilities. Here’s a comprehensive breakdown:</p><h3>Entry Point &amp; Content Delivery</h3><p>The architecture begins with a <strong>Content Creator</strong> accessing the system through <a href="https://aws.amazon.com/cloudfront/"><strong>Amazon CloudFront</strong></a>, which provides global content delivery with low latency and high availability. CloudFront acts as the entry point, caching static assets and reducing load on backend services.</p><h3>Load Distribution &amp; Application Hosting</h3><p>Traffic flows through an <a href="https://aws.amazon.com/elasticloadbalancing/application-load-balancer/"><strong>Application Load Balancer (ALB)</strong></a>, which distributes incoming requests across multiple instances and provides health checking capabilities. The core application runs on <a href="https://aws.amazon.com/ecs/"><strong>Amazon ECS (Elastic Container Service)</strong></a>, offering a scalable, containerized environment that can automatically scale based on demand.</p><h3>AI Orchestration Layer</h3><p>The <a href="https://strandsagents.com/latest/"><strong>Strands Agent</strong> </a>serves as the intelligent orchestrator, managing the complex workflow of video generation. This agent coordinates between multiple AI services and handles the business logic for content creation pipelines.</p><h3>Multi-Modal AI Tool Integration</h3><p>The architecture leverages five specialized tools, each powered by different AWS AI services:</p><ol><li><strong>Content Strategy Tool</strong> (Amazon Nova Lite) — Generates strategic content frameworks and messaging</li><li><strong>Image Creation Tool</strong> (Amazon Nova Canvas) — Creates visual assets and graphics</li><li><strong>Video Creation Tool</strong> (Amazon Nova Reel) — Produces video content and animations</li><li><strong>Audio Creation Tool</strong> (Amazon Polly) — Generates voiceovers and audio tracks</li><li><strong>Video Merging Tool</strong> — Combines all elements into the final video product</li></ol><h3>Key Architectural Benefits</h3><p><strong>Intelligent Orchestration</strong>: The <strong>Strands Agent</strong> provides sophisticated workflow management, automatically determining the optimal sequence of tool execution, handling dependencies between AI services, and implementing fallback logic when individual tools encounter issues.</p><p><strong>Scalability</strong>: The containerized ECS approach allows the system to scale horizontally based on demand, while the Strands Agent efficiently manages resource allocation across multiple concurrent video generation requests.</p><p><strong>Reliability</strong>: Using managed AWS services (Bedrock AI models, Polly, S3) ensures high availability, while the Strands Agent provides error handling, retry mechanisms, and graceful degradation when services are temporarily unavailable.</p><p><strong>Performance</strong>: CloudFront and ALB ensure optimal performance and load distribution, while the Strands Agent optimizes AI tool execution by running parallel processes where possible and caching intermediate results.</p><p><strong>Modularity</strong>: Each AI tool operates independently under Strands Agent coordination, allowing for easy maintenance, updates, and potential replacement of individual components without disrupting the entire workflow.</p><p><strong>Adaptive Decision Making</strong>: The Strands Agent interprets natural language prompts and dynamically selects which tools to use based on content requirements, optimizing both quality and resource utilization.</p><p><strong>Cost Optimization</strong>: Pay-per-use pricing models for AI services combined with the Strands Agent’s intelligent resource management optimize costs by avoiding unnecessary tool executions and efficiently managing compute resources.</p><h3>Building Your VideoAdAgent:</h3><p>To showcase this architecture in action, we’ve deployed a working Streamlit application on Amazon ECS that implements the complete VideoAdAgent workflow. The Streamlit application serves as both a user interface and a practical reference implementation of the Strands Agent orchestration. Built using the same ECS infrastructure described in the architecture, it demonstrates how the agent coordinates between multiple AI services, you can use this as a reference for building. The CDK deployment handles provisioning of all AWS resources, including the ECS cluster configuration, Application Load Balancer setup, CloudFront distribution, and S3 bucket policies.</p><p><a href="https://github.com/debadatta30/aws-ai-video-orchestrator">https://github.com/debadatta30/aws-ai-video-orchestrator</a></p><p>The repository includes:</p><ul><li>Complete CDK infrastructure as code</li><li>Streamlit application</li><li>Strands Agent implementation</li><li>Step-by-step deployment instructions</li></ul><p>Clone the repository and follow the README to deployment.</p><h3>Conclusion</h3><p>The <strong>Strands Agent</strong> is the critical enabler that transforms this AWS architecture from a collection of individual AI services into a cohesive, intelligent video production system. Rather than requiring users to manually coordinate between Amazon Nova Lite, Nova Canvas, Nova Reel, and Polly, the agent serves as an intelligent conductor that interprets natural language creative briefs, automatically determines the optimal sequence of tool execution, manages complex dependencies between visual and audio elements, and handles error recovery — all while optimizing resource utilization across the containerized ECS infrastructure.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=af5f16395125" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Clinical data analysis with Amazon Bedrock]]></title>
            <link>https://debadatta30.medium.com/clinical-data-analysis-with-amazon-bedrock-f9ec8534675b?source=rss-318e9db4dae------2</link>
            <guid isPermaLink="false">https://medium.com/p/f9ec8534675b</guid>
            <dc:creator><![CDATA[Debadatta Panda]]></dc:creator>
            <pubDate>Tue, 15 Apr 2025 15:45:38 GMT</pubDate>
            <atom:updated>2025-04-15T15:45:38.763Z</atom:updated>
            <content:encoded><![CDATA[<p>The healthcare industry generates massive volumes of unstructured data, especially in clinical studies, research papers, and patient records. Extracting valuable insights from these documents is often a time-consuming and error-prone task.</p><p>In this blog, we will explore how <a href="https://aws.amazon.com/textract/">Amazon Textract</a>, an intelligent document processing service, helps extract structured data from complex clinical study reports. We will also delve into how <a href="https://aws.amazon.com/bedrock/">Amazon Bedrock</a> is a fully managed service that makes foundation models (FMs) from leading AI startups and Amazon available through an API, so you can choose from a wide range of FMs to find the model that is best suited for your use case. Amazon Bedrock offers a serverless experience, so you can get started quickly, privately customize FMs with your own data, and quickly integrate and deploy them into your applications using the AWS tools without having to manage the infrastructure. We will empowers researchers and healthcare professionals with generative AI capabilities, enabling deeper analysis and more meaningful insights.</p><p>we will explore using the <a href="https://aws.amazon.com/ai/generative-ai/nova/">Amazon Nova Pro</a> large language model (LLM). Amazon Bedrock provides access to several LLMs, such as Amazon Nova Pro, which can be used to generate semi-structured data relevant to extracting information from clinical research study.</p><p><strong>Solution Overview:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/742/1*x0FYaMxlk_l0n_IALHErZg.png" /></figure><p>The above diagram presents a reference serverless architecture that extracts information from diverse sources such as websites and documents, and delivers structured insights — enabling fast, scalable, and accurate information retrieval. Below is a more structured breakdown of the solution components and how they work together:</p><h4>solution components:</h4><ol><li><strong>Document Ingestion</strong></li></ol><p>The first step in the architecture involves ingesting clinical study documents, which may come in different formats like PDFs, scanned images, or digital text files.</p><p><strong>Amazon S3</strong>: Documents are uploaded to an S3 bucket.</p><p><strong>Public Published URL Content</strong>: For publicly available URL content, AWS Lambda acts as an Extractor to pull content from the website and store it in an S3 bucket.</p><p><strong>S3 Event Notification</strong>: Whenever a new document or content is uploaded to S3, an <strong>S3 event notification</strong> triggers an <strong>AWS Lambda function</strong> for further processing.</p><p>2<strong>. Text Extraction &amp; Processing</strong></p><p>Once the documents are ingested, the next step is to process and extract meaningful text and data from them.</p><p><strong>Amazon Textract (Async Jobs)</strong>: Amazon Textract handles the extraction of text from documents stored in S3.It runs <strong>a</strong>synchronous operations, which are ideal for processing large documents or multi-page PDFs.Upon completion of the Textract job, an SNS notification triggers a call-back to an AWS Lambda function, informing it that the extraction is complete.</p><p><strong>AWS Lambda for Textract Retrieva</strong>l: The Lambda function retrieves the extracted text from the completed Textract job and formats the data if needed. The Lambda then passes the relevant information to Amazon Bedrock for advanced NLP and analysis.</p><p>3.<strong> Advanced NLP &amp; Analysis</strong></p><p>After the text extraction, the next step is to perform more advanced processing, such as named entity recognition (NER) and other natural language tasks.</p><p><strong>Amazon Bedrock</strong>: Amazon Bedrock provides foundational models like Amazon Nova Pro to perform advanced NLP tasks.Using Amazon Bedrock, named entity recognition is applied to the extracted text to identify critical terms, such as: Drug names, Patient outcomes, Clinical terms and Other relevant entities</p><p>The key advantages the architecture provides :</p><p><strong>Scalability</strong>: Serverless architecture automatically scales to accommodate growing document volumes.</p><p><strong>Accuracy</strong>: Leveraging powerful AWS services (Textract for extraction, Bedrock for NLP), the system ensures high accuracy in the extraction and processing of clinical data</p><p><strong>Automation</strong>: The use of SNS, Lambda, and asynchronous Textract jobs ensures that the entire process is automated and efficient.</p><p><strong>Flexibility</strong>: Capable of handling diverse input types (PDFs, scanned images, URLs) and performing various NLP tasks (NER, sentiment analysis, etc.).</p><p>I will take you through some samples code to saw how the process work,</p><ol><li><strong>Document Ingestion:</strong></li></ol><p>Documents can be uploaded directly to an <strong>Amazon S3</strong> bucket. In cases where content is sourced from publicly available URLs (e.g., web pages or published clinical study links), the following <strong>AWS Lambda function</strong> template can be used to fetch the URL content and store it in an S3 bucket for further processing:</p><p>Sample Lambda Function to fetch URL content and save it to S3</p><pre>import json<br>import requests<br>from bs4 import BeautifulSoup<br>from fpdf import FPDF<br>import base64<br>from io import BytesIO<br><br>def lambda_handler(event, context):<br>    url = event.get(&#39;url&#39;)<br>    <br>    if not url:<br>        return {<br>            &#39;statusCode&#39;: 400,<br>            &#39;body&#39;: json.dumps(&#39;No URL provided&#39;)<br>        }<br><br>    try:<br>        # Fetch webpage<br>        html = requests.get(url).text<br>        soup = BeautifulSoup(html, &quot;html.parser&quot;)<br>        # Extract links<br>        links = list(map(lambda a: a.get(&quot;href&quot;), soup.find_all(&quot;a&quot;)))<br>        # Create a PDF in memory<br>        pdf = FPDF()<br>        pdf.add_page()<br>        pdf.set_font(&quot;Arial&quot;, size=12)<br>        pdf.cell(200, 10, txt=f&quot;Links extracted from {url}&quot;, ln=True)<br>        for link in links:<br>            if link:<br>                pdf.multi_cell(0, 10, txt=link)<br>        # Save PDF to memory buffer<br>        buffer = BytesIO()<br>        pdf.output(buffer)<br>        buffer.seek(0)<br><br>        # Base64 encode the PDF<br>        pdf_base64 = base64.b64encode(buffer.read()).decode(&#39;utf-8&#39;)<br>        return {<br>            &#39;statusCode&#39;: 200,<br>            &#39;isBase64Encoded&#39;: True,<br>            &#39;headers&#39;: {<br>                &#39;Content-Type&#39;: &#39;application/pdf&#39;,<br>                &#39;Content-Disposition&#39;: &#39;attachment; filename=&quot;links.pdf&quot;&#39;<br>            },<br>            &#39;body&#39;: pdf_base64<br>        }<br><br>    except Exception as e:<br>        return {<br>            &#39;statusCode&#39;: 500,<br>            &#39;body&#39;: json.dumps({&#39;error&#39;: str(e)})<br>        }</pre><p>S3 Notification on uploaded files : To automatically trigger downstream processing Lambda when a file is uploaded to your S3 bucket, you can configure an <strong>S3 Event Notification</strong>. Here’s how to set it up using the AWS Console:</p><p>Navigate to S3 Console and open your bucket , Click on the “Properties” tab, Scroll down to “Event notifications” , Click “Create event notification” as shown in the below diagram</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*ZzqSwKmuEMxtM0Ws.png" /><figcaption>Event generation on S3 upload</figcaption></figure><p>Create Event notification</p><p>Invoke a AWS Lambda function on the upload event , I have Lambda function which will initate the textract async job</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*kuGynJ-4K_th6bcy.png" /><figcaption>Lambda function on S3 bucket upload</figcaption></figure><p><strong>2. Building an Async Textract Pipeline with SNS Notifications</strong></p><p>Since Textract async jobs (like StartDocumentTextDetection or StartDocumentAnalysis) can take time depending on the size and complexity of the PDF, we’ll build a non-blocking, event-driven pipeline using Amazon SNS and AWS Lambda.</p><p><strong>TextractJobLambda</strong>: Triggered when a document is uploaded to S3 (via event notification).Starts a Textract asynchronous job using start_document_text_detection() or start_document_analysis().Passes an SNS topic ARN for job completion notification.</p><p><a href="https://aws.amazon.com/sns/"><strong>Amazon SNS</strong></a>: Acts as a bridge between the Textract job and downstream processing , extract will publish job completion events here.A Lambda function is <strong>subscribed</strong> to this topic.</p><p><strong>ResultProcessingLambda :</strong> Triggered by the SNS topic.Extracts the <strong>Job ID</strong> from the SNS message.Calls get_document_text_detection() or get_document_analysis() to retrieve results.</p><p>As a prerequisite we will set up the Create an SNS topic: textract-job-complete.Create an IAM role with sns:Publish for Textract. Subscribe your <strong>Lambda</strong> to this SNS topic</p><p>Sample code for TextractJobLambda:</p><pre>import boto3<br>import json<br><br>textract = boto3.client(&#39;textract&#39;)<br><br>def lambda_handler(event, context):<br>    bucket = event[&#39;bucket&#39;]<br>    key = event[&#39;key&#39;]<br><br>    response = textract.start_document_text_detection(<br>        DocumentLocation={<br>            &#39;S3Object&#39;: {<br>                &#39;Bucket&#39;: bucket,<br>                &#39;Name&#39;: key<br>            }<br>        },<br>        NotificationChannel={<br>            &#39;SNSTopicArn&#39;: &#39;arn&#39;,<br>            &#39;RoleArn&#39;: &#39;arn&#39;<br>        }<br>    )<br><br>    return {<br>        &#39;statusCode&#39;: 200,<br>        &#39;body&#39;: json.dumps({&#39;JobId&#39;: response[&#39;JobId&#39;]})<br>    }</pre><p>Sample code for ResultProcessingLambda:</p><pre>import boto3<br>import json<br><br>textract = boto3.client(&#39;textract&#39;)<br><br>def lambda_handler(event, context):<br>    print(&quot;Received SNS Event:&quot;, json.dumps(event))<br><br>    for record in event[&#39;Records&#39;]:<br>        message = json.loads(record[&#39;Sns&#39;][&#39;Message&#39;])<br><br>        job_id = message[&#39;JobId&#39;]<br>        status = message[&#39;Status&#39;]<br>        document_name = message.get(&#39;DocumentLocation&#39;, {}).get(&#39;S3ObjectName&#39;, &#39;unknown&#39;)<br><br>        print(f&quot;Textract Job ID: {job_id}, Status: {status}, Document: {document_name}&quot;)<br><br>        if status != &quot;SUCCEEDED&quot;:<br>            print(&quot;Textract job did not succeed.&quot;)<br>            return {&quot;status&quot;: &quot;failed&quot;, &quot;jobId&quot;: job_id}<br><br>        # Collect full results<br>        full_text = []<br>        next_token = None<br><br>        while True:<br>            if next_token:<br>                response = textract.get_document_text_detection(JobId=job_id, NextToken=next_token)<br>            else:<br>                response = textract.get_document_text_detection(JobId=job_id)<br><br>            # Extract lines of text<br>            blocks = response.get(&quot;Blocks&quot;, [])<br>            for block in blocks:<br>                if block[&quot;BlockType&quot;] == &quot;LINE&quot;:<br>                    full_text.append(block[&quot;Text&quot;])<br><br>            next_token = response.get(&quot;NextToken&quot;)<br>            if not next_token:<br>                break<br><br>        print(&quot;===== Extracted Text =====&quot;)<br>        for line in full_text:<br>            print(line)<br><br>        return {<br>            &quot;status&quot;: &quot;success&quot;,<br>            &quot;jobId&quot;: job_id,<br>            &quot;linesDetected&quot;: len(full_text),<br>            &quot;preview&quot;: full_text[:5]  # Show first few lines for brevity<br>        }</pre><p>3.<strong> Advanced NLP &amp; Analysis</strong></p><p>The output of the Textract will be given to Amazon Bedrock to process specific fields for the clinical study one of sample filed extract is given below:</p><p>1. Study Title &amp; Citation<br>2. Study Background &amp; Rationale<br>3. Study Design<br>4. Treatment &amp; Intervention<br>5. Key Endpoints &amp; Outcome Measures <br>6. Study Results <br>7. Clinical Implications <br>8. Key Takeaways</p><p>For the this demonstration I am using Amazon Nova Pro , as a prerequisite Amazon Nova model need to be enabled , you can do this from your console by accessing Amzon Bedrock console and goto the model access</p><p>Sample code to extract information from the textract output and save the output to S3.</p><pre>def nova_invoke(extracted_data, filename):<br>    try:<br>        # 1. Build Prompt<br>        prompt_data = (<br>            &quot;&quot;&quot;Objective: Extract key information from a medical study and structure it into a clear,<br>            concise summary of the context.&quot;&quot;&quot; + extracted_data + &quot;&quot;&quot;<br>            Instructions:<br>            Read the provided context of the medical study. Identify and extract relevant details using the following headings.<br>            Keep the summary concise, objective, and focused on clinical relevance.<br><br>            Structured Summary Template Headings:<br>            1. Study Title &amp; Citation<br>            2. Study Background &amp; Rationale<br>            3. Study Design<br>            4. Treatment &amp; Intervention<br>            5. Key Endpoints &amp; Outcome Measures <br>            6. Study Results <br>            7. Clinical Implications <br>            8. Key Takeaways<br><br>            Create 8 JSON sections output as per each heading.<br>            &quot;&quot;&quot;<br>        )<br><br>        # 2. Invoke Bedrock model<br>        body = json.dumps({<br>            &quot;messages&quot;: [<br>                {&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: [{&quot;text&quot;: prompt_data}]}<br>            ],<br>            &quot;inferenceConfig&quot;: {<br>                &quot;max_new_tokens&quot;: 5000,<br>                &quot;top_p&quot;: 0.9,<br>                &quot;top_k&quot;: 20,<br>                &quot;temperature&quot;: 0.7<br>            }<br>        })<br><br>        response = bedrock_runtime.invoke_model(<br>            body=body,<br>            modelId=&quot;amazon.nova-pro-v1:0&quot;,<br>            accept=&quot;application/json&quot;,<br>            contentType=&quot;application/json&quot;<br>        )<br><br>        # 3. Parse and log output<br>        response_body = json.loads(response.get(&quot;body&quot;).read())<br>        json_text = response_body[&quot;output&quot;][&quot;message&quot;][&quot;content&quot;][0][&quot;text&quot;]<br><br>        print(&quot;Summary preview:\n&quot;, json_text[:300], &quot;...&quot;)<br><br>        # 4. Save to S3<br>        file_key = f&quot;output/{filename.rsplit(&#39;.&#39;, 1)[0]}.json&quot;<br>        s3_client.put_object(<br>            Body=json.dumps(json_text),<br>            Bucket=bucket_name,<br>            Key=file_key<br>        )<br><br>        print(f&quot;Uploaded to s3://{bucket_name}/{file_key}&quot;)<br><br>    except botocore.exceptions.ClientError as e:<br>        print(f&quot;[ClientError] AWS service error: {e.response[&#39;Error&#39;][&#39;Message&#39;]}&quot;)<br>    except Exception as e:<br>        print(f&quot;[Unhandled Error] {str(e)}&quot;)<br>        traceback.print_exc()</pre><h3>Conclusion:</h3><p>Amazon Bedrock, paired with Amazon Textract, offers a powerful framework for extracting structured clinical insights from unstructured data. This solution:</p><p>Reduces manual review effort ,Accelerates research timelines, Increases data accuracy, Supports regulatory documentation.</p><p>By integrating these services into a serverless AWS pipeline, healthcare organizations and researchers can unlock the full value of clinical data at scale — with speed, flexibility, and intelligence.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f9ec8534675b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[AWS AppSync for Long Running Amazon Bedrock Invocation]]></title>
            <link>https://debadatta30.medium.com/aws-appsync-for-long-running-amazon-bedrock-invocation-e4c443b55c53?source=rss-318e9db4dae------2</link>
            <guid isPermaLink="false">https://medium.com/p/e4c443b55c53</guid>
            <dc:creator><![CDATA[Debadatta Panda]]></dc:creator>
            <pubDate>Thu, 05 Dec 2024 15:21:59 GMT</pubDate>
            <atom:updated>2025-01-24T11:30:57.105Z</atom:updated>
            <content:encoded><![CDATA[<p><a href="https://aws.amazon.com/bedrock/">Amazon Bedrock</a> is a generative AI service, and is the easiest way to build and scale generative AI applications with foundation models (FMs). GraphQL with<a href="https://aws.amazon.com/appsync/"> AWS AppSync</a> has always been a great way of better integrating and building application with an LLM. AWS AppSync has built in websocket support out of the box, via subscriptions, which makes streaming responses from LLM’s also a much simpler task.</p><p>I have implemented a use case where the AppSync mutations takes more than 30 seconds, since the synchronous lambda need to return a response one of the design pattern: invokes a Lambda synchronously which needs to put the contents of the query on a SQS queue, to avoid encountering a timeout. This message is then picked up and processed by another Lambda which feeds the prompt into Amazon Bedrock. This limitation can be eliminated by using asynchronous lambda. In this blog we will discuss how to implement this design. This will help in creating Responsive and scalability of bedrock application by executing the API in the backend</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/536/1*kDPW-az0I78J0pRhj62IUw.png" /><figcaption>Reference Architecture</figcaption></figure><p>The above diagram show a reference architecture for invoking the api in background. The Lambda function invoked asynchronously from AWS AppSync, the called Lambda function can respond immediately to AWS AppSync and then continue working on sending the prompt to Amazon Bedrock and then subsequently then start to invoke a mutation with the response tokens from Bedrock on AWS AppSync, which then sends those tokens to the user via WebSockets.</p><p>Flow of the architecture:</p><ol><li>User will have a subscription, which sets up a WebSocket, and makes a request to AWS AppSync to trigger the invocation.</li><li>AWS AppSync calls your AWS Lambda function in Event mode and immediately returns a response to the client.</li><li>Your Lambda function invokes the model on Amazon Bedrock. The Lambda function can use a synchronous API, such as InvokeModel, or a stream API, such as InvokeModelWithResponseStream, to get progressive updates.</li><li>As updates are received, or when the invocation completes, the Lambda function sends updates via mutations to your AWS AppSync API which triggers subscriptions.</li><li>The subscription events are sent in real-time and received by your client over the WebSocket.</li></ol><pre>export function request(ctx) {<br>    return {<br>        operation: &quot;Invoke&quot;,<br>        invocationType = &quot;Event&quot;,<br>        payload: {<br>            variables: ctx.arguments<br>        },<br>    };<br>}<br><br>export function response(ctx) {<br>    return &quot;OK&quot;;</pre><p>To implement an asynchronous invocation of an AWS Lambda function from AppSync we simply change the resolver call to the function .We can use the <strong>InvocationType</strong> of <strong>Event</strong> which will enable the resolver to call the Lambda asynchronously. The response function of the resolver can return a static response to indicate to the caller that AppSync has received the request for processing.</p><p>The Lambda data source allows you to define two invocation types: RequestResponse and Event. The invocation types are synonymous with the invocation types defined in the <a href="https://docs.aws.amazon.com/lambda/latest/api/API_Invoke.html">Lambda API</a>. The RequestResponse invocation type lets AWS AppSync call your Lambda function synchronously to wait for a response. The Event invocation allows you to invoke your Lambda function asynchronously. For more information on how Lambda handles Event invocation type requests, see <a href="https://docs.aws.amazon.com/lambda/latest/dg/invocation-async.html">Asynchronous invocation</a>. The invocationType field is optional. If this field is not included in the request, AWS AppSync will default to the RequestResponse invocation type.</p><p>The sample GraphQL schema can be defined as below:</p><pre>schema {<br> mutation: Mutation<br> subscription: Subscription<br>}<br><br>type Mutation {<br> ModelSet: Boolean!<br> sendChunk(chunk: String!): String<br>}<br><br>type Subscription {<br> chat: String @aws_subscribe(mutations: [&quot;sendChunk&quot;])<br>}</pre><p>The above sample setup ensures that our schema is valid while focusing on the mutations and subscriptions needed for the implementation. The ModelSet mutation is used to trigger our model, and the sendChunk mutation is used to handle streaming responses. The chat subscription listens for updates from the sendChunk mutation, allowing to emulate a streaming response.</p><h3>Conclusion</h3><p>AWS AppSync support for asynchronous Lambda invocations is a significant advancement in building modern, responsive, and scalable applications. The final response payload size for subscriptions cannot exceed 240K which means careful design considerations. provides architectural flexibility, allowing you to design applications that are robust, efficient, and future-proof.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e4c443b55c53" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Amazon Bedrock knowledgebases for structured data]]></title>
            <link>https://debadatta30.medium.com/amazon-bedrock-knowledgebases-for-structured-data-5862a29c942b?source=rss-318e9db4dae------2</link>
            <guid isPermaLink="false">https://medium.com/p/5862a29c942b</guid>
            <category><![CDATA[amazon-bedrock]]></category>
            <dc:creator><![CDATA[Debadatta Panda]]></dc:creator>
            <pubDate>Fri, 04 Oct 2024 11:28:53 GMT</pubDate>
            <atom:updated>2024-10-04T11:28:53.797Z</atom:updated>
            <content:encoded><![CDATA[<p><a href="https://aws.amazon.com/bedrock/knowledge-bases/">Amazon Bedrock Knowledge Bases</a> is a fully managed capability that helps you implement the entire RAG workflow, from ingestion to retrieval and prompt augmentation. For RAG-based applications, the accuracy of the generated responses from FMs depend on the context provided to the model. Contexts are retrieved from vector stores based on user queries. In this post, we discuss the new custom metadata filtering feature in Amazon Bedrock Knowledge Bases, which you can use to improve search results by pre-filtering your retrievals from vector stores for structed data.</p><h3><strong>Solution Flow :</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/905/1*mATSherPLVr4eYBF3436WA.png" /></figure><h4>Step 1 : Prepare the Dataset for Knowledgebases :</h4><p>With the new enhancement, you can now separate <em>content and metadata</em> within your CSV files, transforming the way you handle data ingestion. This feature allows you to designate specific columns as content fields while marking others as metadata fields. For the demonstration I will use a <a href="https://github.com/debadatta30/aws-csvknowledgebases/blob/main/data/movie_data.csv">sample movie dataset</a> to illustrate how to ingest and retrieve metadata using Amazon Bedrock Knowledge Bases. A sample code you can use for the pre-processing of data :</p><pre>import pandas as pd<br>import os, json, tqdm, boto3<br>#replace the path with your value<br>df = pd.read_csv(&#39;path/movie_data.csv&#39;)<br><br>for i in tqdm.trange(100):<br>    desc = str(df[&#39;label&#39;][i])<br>    meta = {<br>    &quot;metadataAttributes&quot;: {<br>        &quot;title&quot;: str(df[&#39;title&#39;][i]),<br>        &quot;runningtime&quot;: str(df[&#39;running_time&#39;][i]),<br>        &quot;actors&quot;: str(df[&#39;actors&#39;][i]),<br>        &quot;directors&quot;: str(df[&#39;directors&#39;][i]),<br>        &quot;genre&quot;: str(df[&#39;genre&#39;][i]),<br>    }<br>    }<br>    <br>    filename = &#39;path/outputs&#39;+&#39;/&#39; + str(df[&#39;title&#39;][i])+ &#39;.txt&#39;<br>    f = open(filename, &#39;w&#39;)<br>    f.write(desc)<br>    f.close()<br>    metafilename = filename+&#39;.metadata.json&#39;<br>    with open( metafilename, &#39;w&#39;) as f:<br>        json.dump(meta, f)</pre><p>Upload the files to S3 : The files created above need to be uploaded to S3 bucket for creation of Amazon Bedrock Knowledgebases</p><p>As a reference You can use the below sample code for uploading the all the files created in the data folder to S3</p><pre># Upload data to s3<br>s3_client = boto3.client(&quot;s3&quot;)<br>bucket_name = &quot;bucketname&quot;  #replace the bucket name<br>data_root = &quot;path&quot; #replace the path with the data directory<br>def uploadFiles(path,bucket_name):<br>    for root,dirs,files in os.walk(path):<br>        for file in tqdm.tqdm(files):<br>            s3_client.upload_file(os.path.join(root,file),bucket_name,file)<br><br></pre><h4>Step 2: Creation of Knowledgebases :</h4><p>Knowledge Bases for Amazon Bedrock enable you to ingest and store data sources into a central repository of information. In this case we will use the transformed data from above to ingest the data, knowledge base treat certain columns as content fields versus metadata fields. Metadata fields provided in your metadata.json are present as columns in your CSV.</p><p>I will use the Amazon Bedrock Console to configure the knowledge bases, this can be found in Buider tools option within the Amazon Bedrock console as shown below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pFUldP9M-79aZICM3jTyeg.png" /></figure><p>The KnowledgeBase source for this source s3 bucket, is defined with “NoChunking” strategy, which means that the .csv file in itself is a chunk and no further chunking is needed. In case the contents in the CSV in the embeddings fields are huge, a chunking strategy can be adopted, in which case the meta-data for the chunks would remain the same, but more fine grained documents would be created in VectorDB.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/859/1*Fr2fk66XitCJs_bm0u3LXg.png" /></figure><p>Once the knowledgebase is created you need to sync data</p><p>Select the data source and click the sync:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dRWkwV9u0RviSYRbuGxzAA.png" /></figure><h4>Step 3 : Retrieve data from the knowledge base using metadata filtering</h4><p>We will create a conversational chatbot using Streamlit, by leveraging the knowledge bases. We will use a single filter shown below for retrieval of information to retrieve , I will use a metadata filter to get movie with genres for the value “nan” and will use RetrieveAndGenerate API to test the knowledge base with the metadata filters</p><pre># genres = nan<br>single_filter= {<br>    &quot;equals&quot;: {<br>        &quot;key&quot;: &quot;genres&quot;,<br>        &quot;value&quot;: &quot;nan&quot;<br>    }<br>}</pre><pre>import boto3<br>import streamlit as st<br>st.subheader(&#39;RAG Using Knowledge Base from Amazon Bedrock&#39;)<br>if &#39;chat_history&#39; not in st.session_state:<br>    st.session_state.chat_history = []<br>for message in st.session_state.chat_history:<br>    with st.chat_message(message[&#39;role&#39;]):<br>        st.markdown(message[&#39;text&#39;])<br>bedrockClient = boto3.client(&#39;bedrock-agent-runtime&#39;)<br>def getResponse(query):<br>    knowledgeBaseResponse  = bedrockClient.retrieve_and_generate(<br>        input={&#39;text&#39;: query},<br>        retrievalConfiguration=single_filter, # the filter details<br>        retrieveAndGenerateConfiguration={<br>            &#39;knowledgeBaseConfiguration&#39;: {<br>                &#39;knowledgeBaseId&#39;: &#39;Knowlegebaseid&#39;,<br>                &#39;modelArn&#39;: &#39;modearn&#39;<br>            },<br>            &#39;type&#39;: &#39;KNOWLEDGE_BASE&#39;<br>        })<br>    return knowledgeBaseResponse<br><br>query= st.chat_input(&#39;Enter you query here...&#39;)<br>if query:<br>    with st.chat_message(&#39;user&#39;):<br>        st.markdown(query)<br>    st.session_state.chat_history.append({&quot;role&quot;:&#39;user&#39;, &quot;text&quot;:query})<br><br>    response = getResponse(query)<br>    # st.write(response)<br>    answer = response[&#39;output&#39;][&#39;text&#39;]<br><br>    with st.chat_message(&#39;assistant&#39;):<br>        st.markdown(answer)<br>    st.session_state.chat_history.append({&quot;role&quot;:&#39;assistant&#39;, &quot;text&quot;: answer})<br><br>    if len(response[&#39;citations&#39;][0][&#39;retrievedReferences&#39;]) != 0:<br>        context = response[&#39;citations&#39;][0][&#39;retrievedReferences&#39;][0][&#39;content&#39;][&#39;text&#39;]<br>        doc_url = response[&#39;citations&#39;][0][&#39;retrievedReferences&#39;][0][&#39;location&#39;][&#39;s3Location&#39;][&#39;uri&#39;]<br>        <br>        #Below lines are used to show the context and the document source for the latest Question Answer<br>        st.markdown(f&quot;&lt;span style=&#39;color:#FFDA33&#39;&gt;Context used: &lt;/span&gt;{context}&quot;, unsafe_allow_html=True)<br>        st.markdown(f&quot;&lt;span style=&#39;color:#FFDA33&#39;&gt;Source Document: &lt;/span&gt;{doc_url}&quot;, unsafe_allow_html=True)<br>    <br>    else:<br>        st.markdown(f&quot;&lt;span style=&#39;color:red&#39;&gt;No Context&lt;/span&gt;&quot;, unsafe_allow_html=True)</pre><h4>Conclusion:</h4><p>With metadata filtering feature in Amazon Bedrock Knowledge Bases this improve RAG output with meta-data filters . This approach helps the query responses more relevant while achieving a reduction in cost of querying the vector database.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5862a29c942b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[App-Log Queries with Amazon Bedrock Knowledge Bases]]></title>
            <link>https://debadatta30.medium.com/app-log-queries-with-amazon-bedrock-knowledge-bases-ce8deaf5b84b?source=rss-318e9db4dae------2</link>
            <guid isPermaLink="false">https://medium.com/p/ce8deaf5b84b</guid>
            <category><![CDATA[amazon-bedrock]]></category>
            <dc:creator><![CDATA[Debadatta Panda]]></dc:creator>
            <pubDate>Wed, 18 Sep 2024 11:01:12 GMT</pubDate>
            <atom:updated>2024-09-18T11:01:12.930Z</atom:updated>
            <content:encoded><![CDATA[<p><a href="https://aws.amazon.com/bedrock/knowledge-bases/">Amazon Bedrock Knowledge Bases </a>provides a fully managed Retrieval Augmented Generation (RAG) experience for businesses. This knowledge base can then be used to augment responses from foundation models through a popular technique called RAG. This helps in generating responses that are not only more accurate but also more tailored to the specific needs of your business.</p><p>In this blog post, I will explain how Knowledge Bases for Amazon Bedrock with <a href="https://www.pinecone.io/">Pinecone</a>, managed vector database on the cloud to query the details of application log files.</p><p><strong>Solution Diagram:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/905/1*jUSOoarXYiWib_v0V6Bm_Q.png" /><figcaption>Architecture Diagram</figcaption></figure><p>The solution has two part:</p><p>1 — Knowledge base indexing and synchronisation</p><p>2 — Retrieval and generation</p><h4><strong>Solution Component :</strong></h4><p><strong><em>Knowledge base indexing and synchronisation:</em></strong></p><ol><li><strong>Creation of Pinecone Index:</strong></li></ol><p>Pinecone index need to be created to store the vector embeddings. This can be done by signing up to Pinecone console and create your Pinecone index, and retrieve your index’s endpoint and <strong>apiKey</strong> from the Pinecone console.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*s9a_P0FvpE2_AnMe_q7WjA.png" /></figure><p>Create a API Key in the Pinecone which will be used by Knowledgebase to access vector DB.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LWFHsGBiS3dVHyCDvMs-Dg.png" /></figure><p>Store the apiKey in AWS Secrets Manager:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nZ6vKSkFZoRpYZQ1aLX3yA.png" /><figcaption>Store apiKey of Pinecone</figcaption></figure><p>Choose<strong> Other type</strong> for Secret type and set ‘apiKey’ as the key. Fill your Pinecone api key in the value box. This<strong> Secret ARN</strong> is required when creating Bedrock Knowledge Base.</p><p>2. <strong>Creation of Knowledgebase:</strong></p><p>Knowledge Bases for Amazon Bedrock enable you to ingest and store data sources into a central repository of information. Once you have pointed to your data in Amazon S3, Knowledge Bases for Amazon Bedrock automatically fetches the data, divides it into blocks of text, converts the text into embeddings, and stores the embeddings in your vector database.</p><p>To enhance data retrieval, the log files are divided into smaller segments, converted into embeddings, and stored in a vector index, maintaining a link to the original document. These embeddings enable semantic similarity comparisons for efficient query matching in data sources. This process is depicted in the accompanying image.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/956/1*OyJHY7VFhXnSsNse2b5-0w.png" /></figure><p>Creating the knowledge base involves the below key components:</p><ul><li>DATA SOURCE<br>Accepts a single S3 bucket as a data source , which holds the application log files</li><li>EMBEDDINGS MODEL<br>Titan Embeddings G1 — Text v1.2.</li><li>VECTOR DATABASE<br>Choose an existing vector database, Pinecone index will be used for this use case</li></ul><p>I will use the Amazon Bedrock Console to configure the knowledge bases, this can be found in Buider tools option within the Amazon Bedrock console as shown below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OxkTx9BfNP2s2THWHVCjVg.png" /><figcaption>Creation Knowledge base details</figcaption></figure><p>Configure the data source : The data source dictates how the content will be ingested, including the storage configuration and the content chunking strategy.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hz_-fHCASD7yOncYIN115w.png" /><figcaption>Data Source Configuration</figcaption></figure><p>configure Embedding model &amp; Vector Store</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/876/1*rj0_WR08mhTIj5Uzn8bL7A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*11Z2WXrn8lqbqAwWUWxBRA.png" /></figure><p>Select the data source and click the sync:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qoN8cEmVzfTdt2voc7ROrQ.png" /></figure><p><strong>3. Synchronize the dataset with the knowledge Base</strong></p><p>As the logfiles will be uploaded to the S3 bucket at regular interval, the Knowledge Bases need to be sync with the uploaded data, this can be done using S3 upload event notification invoking a AWS Lambda function to sync data</p><p>Creating S3 Notification on upload of log files : This can be done from the console using S3 bucket Properties and navigate to Event notifications and create an event notification on the put operation</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/741/1*lIhAH4Mn6juoiJRUkiskLQ.png" /><figcaption>Create Event notification</figcaption></figure><p>Invoke a AWS Lambda function on the upload event , I have given a sample Lambda function to sync the Knowledge Bases</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/727/1*uAbpdFYgMa93H8XqqwGojg.png" /><figcaption>Lambda ARN</figcaption></figure><p>Sample AWS Lambda Function to sync the Knowledge Base, replace the DATASOURCEID &amp; KNOWLEDGEBASEID with the details created earlier:</p><pre>import os<br>import json<br>import boto3<br><br><br>bedrockClient = boto3.client(&#39;bedrock-agent&#39;)<br><br>def lambda_handler(event, context):<br>    # TODO implement<br>    print(&#39;Inside Lambda Handler&#39;)<br>    print(&#39;event: &#39;, event)<br>    # Datasource <br>    dataSourceId = os.environ[&#39;DATASOURCEID&#39;]<br>    # Knowledge base id where to be updated<br>    knowledgeBaseId = os.environ[&#39;KNOWLEDGEBASEID&#39;]<br>    print(&#39;knowledgeBaseId: &#39;, knowledgeBaseId)<br>    print(&#39;dataSourceId: &#39;, dataSourceId)<br>    response = bedrockClient.start_ingestion_job(<br>        knowledgeBaseId=knowledgeBaseId,<br>        dataSourceId=dataSourceId<br>    )<br>    print(&#39;Ingestion Job Response: &#39;, response)<br>    return {<br>        &#39;statusCode&#39;: 200,<br>        &#39;body&#39;: json.dumps(&#39;response&#39;)<br>    }</pre><p><strong><em>Retrieval and generation :</em></strong></p><p><strong>4. Query the knowledge base with Streamlit :</strong></p><p>We will create a conversational chatbot using Streamlit, by leveraging the knowledge bases. We can utilize Streamlit’s chat elements to construct an interactive user experience. We will use the RetrieveAndGenerate API to test the knowledge base. Behind the scenes, RetrieveAndGenerate API converts queries into embeddings, searches the knowledge base, and then augments the foundation model prompt with the search results as context information and returns the FM-generated response to the question. For multi-turn conversations, Knowledge Bases manage short-term memory of the conversation to provide more contextual results.</p><pre>import boto3<br>import streamlit as st<br>st.subheader(&#39;RAG Using Knowledge Base from Amazon Bedrock&#39;)<br>if &#39;chat_history&#39; not in st.session_state:<br>    st.session_state.chat_history = []<br>for message in st.session_state.chat_history:<br>    with st.chat_message(message[&#39;role&#39;]):<br>        st.markdown(message[&#39;text&#39;])<br>bedrockClient = boto3.client(&#39;bedrock-agent-runtime&#39;)<br>def getResponse(query):<br>    knowledgeBaseResponse  = bedrockClient.retrieve_and_generate(<br>        input={&#39;text&#39;: query},<br>        retrieveAndGenerateConfiguration={<br>            &#39;knowledgeBaseConfiguration&#39;: {<br>                &#39;knowledgeBaseId&#39;: &#39;Knowlegebaseid&#39;,<br>                &#39;modelArn&#39;: &#39;modearn&#39;<br>            },<br>            &#39;type&#39;: &#39;KNOWLEDGE_BASE&#39;<br>        })<br>    return knowledgeBaseResponse<br><br>query= st.chat_input(&#39;Enter you query here...&#39;)<br>if query:<br>    with st.chat_message(&#39;user&#39;):<br>        st.markdown(query)<br>    st.session_state.chat_history.append({&quot;role&quot;:&#39;user&#39;, &quot;text&quot;:query})<br><br>    response = getResponse(query)<br>    # st.write(response)<br>    answer = response[&#39;output&#39;][&#39;text&#39;]<br><br>    with st.chat_message(&#39;assistant&#39;):<br>        st.markdown(answer)<br>    st.session_state.chat_history.append({&quot;role&quot;:&#39;assistant&#39;, &quot;text&quot;: answer})<br><br>    if len(response[&#39;citations&#39;][0][&#39;retrievedReferences&#39;]) != 0:<br>        context = response[&#39;citations&#39;][0][&#39;retrievedReferences&#39;][0][&#39;content&#39;][&#39;text&#39;]<br>        doc_url = response[&#39;citations&#39;][0][&#39;retrievedReferences&#39;][0][&#39;location&#39;][&#39;s3Location&#39;][&#39;uri&#39;]<br>        <br>        #Below lines are used to show the context and the document source for the latest Question Answer<br>        st.markdown(f&quot;&lt;span style=&#39;color:#FFDA33&#39;&gt;Context used: &lt;/span&gt;{context}&quot;, unsafe_allow_html=True)<br>        st.markdown(f&quot;&lt;span style=&#39;color:#FFDA33&#39;&gt;Source Document: &lt;/span&gt;{doc_url}&quot;, unsafe_allow_html=True)<br>    <br>    else:<br>        st.markdown(f&quot;&lt;span style=&#39;color:red&#39;&gt;No Context&lt;/span&gt;&quot;, unsafe_allow_html=True)</pre><h4>Conclusion :</h4><p>Integrating the log files with Amazon Bedrock significantly enhances the capabilities of your RAG applications to query useful information about application log analysis .we’ve enabled a powerful RAG system capable of retrieving highly relevant information for augmented generation tasks. With the use of Amazon Bedrock Knowledge Bases you can effortlessly integrate and manage data from various sources, empowering your applications to deliver more informed and contextually rich outputs.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ce8deaf5b84b" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>