<?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 Abhishek Tiwary on Medium]]></title>
        <description><![CDATA[Stories by Abhishek Tiwary on Medium]]></description>
        <link>https://medium.com/@abhishek.01.09?source=rss-e3eda35f3bf9------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*PWoM3wo9n4fTMzLB.jpg</url>
            <title>Stories by Abhishek Tiwary on Medium</title>
            <link>https://medium.com/@abhishek.01.09?source=rss-e3eda35f3bf9------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 03 Dec 2026 00:54:41 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@abhishek.01.09/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 Customer Support Agent with Amazon Bedrock AgentCore Components: A Developer’s Journey]]></title>
            <link>https://medium.com/@abhishek.01.09/building-a-customer-support-agent-with-amazon-bedrock-agentcore-components-a-developers-journey-9e9ddf6a6a6a?source=rss-e3eda35f3bf9------2</link>
            <guid isPermaLink="false">https://medium.com/p/9e9ddf6a6a6a</guid>
            <dc:creator><![CDATA[Abhishek Tiwary]]></dc:creator>
            <pubDate>Wed, 05 Nov 2025 05:27:33 GMT</pubDate>
            <atom:updated>2025-11-05T05:27:33.299Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DK32mhynv-_7JGiFa5-0tw.png" /></figure><ol><li><strong>Introduction: The Challenge That Started It All</strong></li></ol><p>When I first started exploring Amazon Bedrock AgentCore, I was excited by its promise of simplifying AI agent development with managed infrastructure, built-in memory, and seamless integrations. However, like many developers venturing into new territory, I quickly discovered that while the individual components were well-documented, finding a complete, working example that tied everything together was surprisingly challenging. Few of my friends encouraged me to write a holistic view blog on AgentCore. I am here by sharing my learning so far.</p><p>I spent weeks piecing together fragments from different documentation sources, trying to understand how AgentCore Runtime, Memory, Gateway, Identity, and Observability components work together in a real-world scenario. The scattered examples left me with more questions than answers: How do you properly configure gateway targets? How does memory persistence actually work? What’s the right way to handle authentication between components?</p><p>This tutorial is the comprehensive guide I wish I had when starting my AgentCore journey. We’ll build a complete, production-ready customer support agent that demonstrates every AgentCore component working together seamlessly. By the end, you’ll have a fully functional system running on your local machine that you can deploy, test, and understand completely.</p><p><strong>2. What We’re Building: AgentCore in Action</strong></p><p><strong>2.1 Overview of Amazon Bedrock AgentCore</strong></p><p>Amazon Bedrock AgentCore is AWS’s managed platform for building and deploying AI agents at scale. It provides five core components:</p><blockquote>- <strong>AgentCore</strong> <strong>Runtime</strong>: Serverless agent hosting with automatic scaling and containerization</blockquote><blockquote>- <strong>AgentCore Gateway</strong>: MCP (Model Context Protocol) server for tool integrations</blockquote><blockquote>- <strong>AgentCore Memory</strong>: Managed conversation memory with short-term and long-term storage</blockquote><blockquote>- <strong>AgentCore Identity</strong>: Secure credential management and authentication</blockquote><blockquote>- <strong>AgentCore Observability</strong>: Built-in monitoring, logging, and tracing</blockquote><p><strong>2.2 System Architecture: Customer Support Agent</strong></p><p>Our example implements a sophisticated customer support system that showcases all AgentCore components working in harmony. The architecture follows a layered approach where each component has a specific responsibility while maintaining seamless integration with others.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0d-SSq86uWLPrBnLLgobzQ.png" /><figcaption>High-Level Architecture Building Blocks</figcaption></figure><p><strong>2.3 Key Features We’ll Implement</strong></p><p>The customer support agent we’re building demonstrates real-world complexity while remaining approachable for learning. Each feature showcases different AgentCore capabilities:</p><blockquote>a. <strong>Intelligent Customer Support</strong>: Our agent handles warranty checks, account lookups, and technical troubleshooting through a combination of local knowledge and external integrations</blockquote><blockquote>b. <strong>Memory Persistence</strong>: The system remembers customer context across conversations, creating a more natural and efficient support experience</blockquote><blockquote>c. <strong>Multi-Modal Tool Integration</strong>: We integrate both AWS Lambda functions for internal operations and external APIs for additional data sources</blockquote><blockquote>d. <strong>Complete Observability</strong>: Full monitoring and tracing capabilities provide insights into agent performance and user interactions</blockquote><blockquote>e. <strong>One-Click Deployment</strong>: Automated setup and teardown make it easy to experiment and learn without manual configuration</blockquote><p><strong>3. Prerequisites: Setting Up Your Environment</strong></p><p>Before diving into the implementation, let’s ensure your development environment is properly configured. This setup process is crucial for a smooth experience with AgentCore.</p><p><strong>3.1 Required Software Installation</strong></p><pre># Verify Python 3.10 or higher<br>python --version<br><br># Ensure Docker is installed and running<br>docker --version<br><br># Check AWS CLI configuration<br>aws configure list</pre><p>The Python requirement is specific because AgentCore uses modern Python features that aren’t available in older versions. Docker is essential because AgentCore Runtime packages your agent code into containers for serverless deployment. The AWS CLI must be properly configured with credentials that have sufficient permissions for the services we’ll be using.</p><p><strong>3.2 AWS Account Configuration</strong></p><p>Your AWS account needs specific permissions and configurations to work with AgentCore. The most common issues developers face stem from insufficient permissions or incorrect credential setup:</p><blockquote>- <strong>Programmatic Access</strong>: Ensure your AWS credentials are configured in `~/.aws/credentials`</blockquote><blockquote>- <strong>Service Permissions</strong>: Your IAM user or role needs permissions for Bedrock AgentCore, CloudFormation, Lambda, DynamoDB, S3, and IAM</blockquote><blockquote>- <strong>Regional Considerations</strong>: This example uses ‘us-east-1’ by default, but you can modify it for other regions where AgentCore is available</blockquote><p><strong>3.3 Project Structure Setup</strong></p><p>The project follows a logical structure that separates concerns and makes the codebase maintainable:</p><pre>agentcore-complete-example/<br>├── agents/                 # Agent implementations<br>├── infrastructure/         # CloudFormation and AWS resources<br>├── tools/                 # Custom tool definitions<br>├── utils/                 # Helper functions and utilities<br>├── deploy.py              # One-click deployment script<br>├── validate.py            # Comprehensive testing script<br>└── requirements.txt       # Python dependencies</pre><p>This organization reflects best practices for AgentCore projects, where infrastructure, agent logic, and utilities are clearly separated.</p><p><strong>4. Deep Dive: Understanding the Code Architecture</strong></p><p>Let us walk through the code architecture. I am going to share only the code snippets in this article, considering the length of it. I have shared full code <a href="https://github.com/Abhishek-Tiwary-Altran/agentcore-customer-support">here</a>.</p><p><strong>4.1 Agent Implementation: The Heart of Our System</strong></p><p>The core of our customer support system lies in the agent implementation, which transforms a powerful language model into a specialized customer service representative. Unlike simple chatbots that follow scripted responses, our AgentCore agent is designed to be stateful, context-aware, and capable of complex reasoning about customer needs while maintaining the empathy and professionalism expected in customer support interactions.</p><p><strong>Creating a Customer Support Personality</strong></p><p>The agent creation process begins with establishing a clear identity and operational framework. In customer support, this means creating an agent that not only has access to the right tools but also knows how to use them appropriately based on customer context and emotional state:</p><pre>def create_customer_support_agent():<br>    &quot;&quot;&quot;Create a sophisticated customer support agent with full AgentCore integration.&quot;&quot;&quot;<br>    <br>    system_prompt = f&quot;&quot;&quot;You are an intelligent customer support agent for a technology company.<br>    <br>    Customer Context:<br>    - Customer ID: {CUSTOMER_ID} (John Doe - Premium Customer)<br>    - Communication Preference: Email<br>    - Recent Orders: iPhone 15 Pro, Sennheiser headphones<br>    - Account Status: Premium (priority support)<br>    <br>    Your capabilities:<br>    ✅ Access customer profiles and complete order history<br>    ✅ Check warranty status and coverage details<br>    ✅ Search knowledge base for troubleshooting solutions<br>    ✅ Research current issues and solutions via web search<br>    <br>    Support Guidelines:<br>    - Always greet customers warmly and acknowledge their premium status<br>    - Listen carefully to understand the root cause, not just symptoms<br>    - Use customer tools to provide accurate, personalized information<br>    - Provide step-by-step troubleshooting with clear explanations<br>    - Escalate complex hardware issues to human specialists when needed<br>    - Reference previous orders and interactions when relevant<br>    - Maintain professional empathy, especially for frustrated customers&quot;&quot;&quot;<br>    <br>    agent = Agent(<br>        model=&quot;anthropic.claude-3-sonnet-20240229-v1:0&quot;,<br>        tools=tools,<br>        system_prompt=system_prompt<br>    )</pre><p>The system prompt is more than just instructions — it’s the agent’s personality and operational framework. We define not only what the agent can do but how it should approach problems, interact with customers, and make decisions about when to use different tools.</p><p><strong>The Power of Context-Aware Support</strong></p><p>This system prompt does much more than provide instructions — it creates a customer support agent with institutional knowledge and emotional intelligence. Notice how we include specific customer context (Premium status, recent purchases) that allows the agent to provide personalized service from the first interaction.</p><p>When a customer contacts support, the agent immediately knows:</p><blockquote>- <strong>Who they are</strong>: Premium customer John Doe with specific purchase history</blockquote><blockquote>- <strong>What they own</strong>: iPhone 15 Pro and Sennheiser headphones (potential support topics)</blockquote><blockquote>- <strong>How to help them</strong>: Access to warranty systems, knowledge base, and web search</blockquote><blockquote>- <strong>How to communicate</strong>: Professional but warm, acknowledging their premium status</blockquote><p><strong>Agent Configuration and Model Selection</strong></p><p>The technical configuration reflects the sophisticated requirements of customer support:</p><pre>agent = Agent(<br>        model=&quot;anthropic.claude-3-sonnet-20240229-v1:0&quot;,  # High-capability model for complex reasoning<br>        tools=customer_support_tools,                      # Comprehensive tool suite<br>        system_prompt=system_prompt,                       # Detailed personality and guidelines<br>        memory_session=memory_session                      # Conversation continuity<br>    )</pre><p>We chose Claude 3.7 Sonnet specifically for customer support because it excels at:</p><blockquote>- <strong>Emotional Intelligence</strong>: Understanding customer frustration and responding appropriately</blockquote><blockquote>- <strong>Complex Reasoning</strong>: Diagnosing technical issues through multi-step troubleshooting</blockquote><blockquote>- <strong>Tool Usage</strong>: Knowing when and how to use different tools based on customer needs</blockquote><blockquote>- <strong>Professional Communication</strong>: Maintaining appropriate tone while being helpful and informative</blockquote><p><strong>Memory Integration for Personalized Service</strong></p><p>The memory integration transforms individual support interactions into ongoing customer relationships:</p><pre># Memory enables the agent to remember:<br>    # - Previous issues and their resolutions<br>    # - Customer preferences and communication style<br>    # - Ongoing problems that span multiple conversations<br>    # - Successful troubleshooting approaches for this customer</pre><p>This means when John Doe contacts support again in a few weeks, the agent will remember that he previously had iPhone overheating issues, prefers detailed technical explanations, and successfully resolved problems using specific troubleshooting steps. This continuity creates a premium support experience that builds customer loyalty.</p><p><strong>4.2 Tool Definitions: Bridging AI and Business Logic</strong></p><p>Tools are where the magic happens in AgentCore. They represent the bridge between the AI agent’s reasoning capabilities and your actual business systems. My implementation demonstrates three different patterns for tool integration that you’ll commonly encounter in real-world applications.</p><p><strong>Internal Business System Integration</strong></p><p>The first and most critical pattern involves connecting your agent to internal business systems. In customer support, this means accessing customer databases, order management systems, and warranty information:</p><pre>@tool<br>def get_customer_profile(customer_id: str) -&gt; str:<br>    &quot;&quot;&quot;Retrieve comprehensive customer information from internal systems.&quot;&quot;&quot;<br>    # This tool routes through AgentCore Gateway to Lambda<br>    # Lambda function queries DynamoDB and returns formatted data<br>    pass</pre><p>This tool exemplifies how AgentCore enables secure access to sensitive business data. When a customer says “Can you check my account?”, the agent uses this tool to retrieve their complete profile, including purchase history, support tier (Premium, Standard), and communication preferences. The Lambda function handles the complex database queries and data formatting, while the agent focuses on conversational interaction.</p><pre>@tool  <br>def check_warranty_status(serial_number: str) -&gt; str:<br>    &quot;&quot;&quot;Check device warranty status and coverage details.&quot;&quot;&quot;<br>    # Demonstrates secure access to warranty database<br>    # Returns structured warranty information<br>    pass</pre><p>The warranty check tool demonstrates how AgentCore can handle complex business logic. When a customer provides a serial number like “MNO33333333”, the tool validates the format, queries the warranty database, calculates remaining coverage days, and provides actionable information about repair options or extended warranties.</p><p><strong>Local Knowledge Base Integration</strong></p><p>The second pattern involves local knowledge bases that contain frequently accessed information and troubleshooting procedures:</p><pre>@tool<br>def search_knowledge_base(query: str) -&gt; str:<br>    &quot;&quot;&quot;Search internal knowledge base for solutions and procedures.&quot;&quot;&quot;<br>    knowledge = {<br>        &quot;iphone hot&quot;: &quot;iPhone overheating solutions: Remove case, close apps...&quot;,<br>        &quot;charging&quot;: &quot;Charging issues: Try different cable, clean port...&quot;<br>    }<br>    # Pattern matching and response generation logic</pre><p>This tool handles the most common customer inquiries without requiring external API calls. When a customer says “My iPhone gets hot when charging”, the agent uses this tool to provide immediate, structured troubleshooting steps. This pattern is essential for customer support because it provides instant responses for common issues while reducing load on external systems.</p><p><strong>Web Search Integration for Enhanced Support</strong></p><p>The third pattern demonstrates how modern customer support agents can access real-time information to provide comprehensive assistance:</p><pre>@tool<br>def web_search_tool(query: str, max_results: int = 5) -&gt; str:<br>    &quot;&quot;&quot;Search the web for current information and solutions.&quot;&quot;&quot;<br>    # Uses DuckDuckGo search API for privacy-focused web search<br>    # Formats results with titles, descriptions, and source URLs<br>    # Handles rate limiting and error conditions gracefully</pre><p>This web search capability transforms our customer support agent from a static knowledge system into a dynamic problem-solving assistant. When a customer asks about “latest iOS update issues” or “iPhone 15 Pro known problems”, the agent can search for current information, recent forum discussions, and emerging solutions that might not be in the internal knowledge base yet.</p><p>The web search tool is particularly valuable for:</p><blockquote>- <strong>Emerging Issues</strong>: Finding solutions to problems that haven’t been documented internally yet</blockquote><blockquote>- <strong>Product Research</strong>: Helping customers understand new features or compatibility questions</blockquote><blockquote>- <strong>Competitive Information</strong>: Providing context about industry trends or alternative solutions</blockquote><blockquote>- <strong>Technical Updates</strong>: Accessing the latest firmware updates, driver releases, or compatibility information</blockquote><p><strong>External API Integration</strong></p><p>The fourth pattern shows how to integrate with external services through OpenAPI specifications:</p><pre># NASA Mars Weather API integration (demonstrates external API pattern)<br># Configured through AgentCore Gateway with API key authentication<br># Shows how to handle external service dependencies and error conditions</pre><p>While the Mars weather API might seem unrelated to customer support, it demonstrates a crucial pattern: integrating with external services that provide specialized data. In real customer support scenarios, this could be:</p><blockquote>- <strong>Shipping APIs</strong>: Tracking package delivery status</blockquote><blockquote>- <strong>Payment Processors</strong>: Checking transaction status or processing refunds</blockquote><blockquote>- <strong>Third-party Services</strong>: Integrating with partner systems or external databases</blockquote><blockquote>- <strong>Social Media APIs</strong>: Monitoring brand mentions or customer feedback</blockquote><p><strong>Tool Integration Strategy</strong></p><p>This multi-tool approach creates a comprehensive customer support experience:</p><blockquote><strong>Immediate Response</strong>: Local knowledge base provides instant answers for common issues</blockquote><blockquote><strong>Personalized Service</strong>: Customer profile and warranty tools deliver personalized information</blockquote><blockquote><strong>Current Information</strong>: Web search ensures access to the latest solutions and updates</blockquote><blockquote><strong>External Integration</strong>: API connections enable comprehensive service across multiple systems</blockquote><p>The beauty of AgentCore’s tool system is that the agent automatically selects the appropriate tool based on the customer’s query. When someone asks “My iPhone battery drains quickly”, the agent might use the knowledge base for standard troubleshooting steps, then use web search to find information about recent iOS updates that might be causing the issue.</p><p>This comprehensive tool strategy creates customer support agents that are both responsive and knowledgeable, capable of handling everything from routine inquiries to complex technical issues that require real-time research and personalized data access.</p><p><strong>4.3 Memory Integration: Creating Conversational Continuity</strong></p><p>One of AgentCore’s most powerful features is its managed memory system. Unlike traditional chatbots that treat each interaction as isolated, AgentCore Memory enables true conversational continuity that makes interactions feel natural and efficient.</p><p>The memory integration process involves connecting your agent to AgentCore’s memory services and configuring how conversation context should be stored and retrieved:</p><pre>def setup_memory_integration():<br>    &quot;&quot;&quot;Configure AgentCore Memory for conversation continuity.&quot;&quot;&quot;<br>    memory_client = MemoryClient(region_name=REGION)<br>    <br>    # Find or create customer support memory instance<br>    memories = memory_client.list_memories()<br>    customer_memory = find_customer_support_memory(memories)<br>    <br>    if customer_memory:<br>        memory_session = MemorySession(<br>            memory_id=customer_memory[&#39;memoryId&#39;],<br>            actor_id=CUSTOMER_ID,<br>            session_id=SESSION_ID<br>        )<br>        return memory_session</pre><p>The memory system works on multiple levels. Short-term memory maintains context within a conversation session, allowing the agent to reference earlier parts of the conversation naturally. Long-term memory can store customer preferences, previous issues, and interaction patterns that inform future conversations.</p><p><strong>4.4 Infrastructure as Code: CloudFormation Foundation</strong></p><p>The infrastructure layer demonstrates how to properly architect AWS resources for AgentCore applications. Our CloudFormation template creates a complete ecosystem that supports the agent’s operations while following AWS best practices for security and scalability.</p><p>The template defines several key resource types that work together:</p><pre># DynamoDB tables for customer data with proper indexing<br>CustomerProfileTable:<br>  Type: AWS::DynamoDB::Table<br>  Properties:<br>    BillingMode: PAY_PER_REQUEST<br>    GlobalSecondaryIndexes:<br>      - IndexName: email-index<br>        # Enables customer lookup by email<br><br># Lambda function with comprehensive business logic<br>CustomerSupportLambda:<br>  Type: AWS::Lambda::Function<br>  Properties:<br>    Runtime: python3.12<br>    Environment:<br>      Variables:<br>        CUSTOMER_PROFILE_TABLE_NAME: !Ref CustomerProfileTable</pre><p>The infrastructure design reflects real-world considerations like data access patterns, security boundaries, and operational requirements. Each resource is configured with appropriate permissions and monitoring capabilities.</p><p><strong>4.5 Gateway Configuration: The Integration Hub</strong></p><p>AgentCore Gateway serves as the central hub for all external integrations. It implements the Model Context Protocol (MCP), which provides a standardized way for AI agents to interact with external systems and APIs.</p><p>Our gateway configuration demonstrates two primary integration patterns that cover most real-world scenarios:</p><p><strong>Lambda Target Integration</strong> handles internal business operations:</p><pre>lambda_target_config = {<br>    &quot;mcp&quot;: {<br>        &quot;lambda&quot;: {<br>            &quot;lambdaArn&quot;: lambda_function_arn,<br>            &quot;toolSchema&quot;: {<br>                &quot;inlinePayload&quot;: [{<br>                    &quot;name&quot;: &quot;get_customer_profile&quot;,<br>                    &quot;description&quot;: &quot;Get customer profile information&quot;,<br>                    &quot;inputSchema&quot;: {<br>                        &quot;type&quot;: &quot;object&quot;,<br>                        &quot;properties&quot;: {&quot;customer_id&quot;: {&quot;type&quot;: &quot;string&quot;}},<br>                        &quot;required&quot;: [&quot;customer_id&quot;]<br>                    }<br>                }]<br>            }<br>        }<br>    }<br>}</pre><p><strong>OpenAPI Target Integration</strong> connects to external services:</p><pre>openapi_target_config = {<br>    &quot;mcp&quot;: {<br>        &quot;openApiSchema&quot;: {<br>            &quot;s3&quot;: {&quot;uri&quot;: &quot;s3://bucket/nasa_mars_insights.json&quot;}<br>        }<br>    }<br>}</pre><p>This dual approach allows your agents to seamlessly access both internal business systems and external data sources through a unified interface.</p><p><strong>5. Deployment Deep Dive: The <em>deploy.py</em> Script</strong></p><p>The deployment process orchestrates the creation of all necessary AWS resources and AgentCore components in a specific sequence that ensures dependencies are properly resolved. Understanding this process is crucial for adapting the example to your own use cases.</p><p><strong>5.1 Phase 1: Infrastructure Foundation</strong></p><p>The deployment begins by establishing the AWS infrastructure foundation through CloudFormation. This approach ensures that all resources are created with proper dependencies and can be easily managed as a unit:</p><pre>def deploy_cloudformation_stack():<br>    &quot;&quot;&quot;Deploy the complete AWS infrastructure stack.&quot;&quot;&quot;<br>    cf_client = boto3.client(&#39;cloudformation&#39;)<br>    <br>    # Handle existing stacks gracefully<br>    try:<br>        cf_client.create_stack(<br>            StackName=&quot;agentcore-customer-support&quot;,<br>            TemplateBody=template_body,<br>            Capabilities=[&#39;CAPABILITY_IAM&#39;, &#39;CAPABILITY_NAMED_IAM&#39;]<br>        )<br>    except AlreadyExistsException:<br>        print(&quot;Stack exists, using existing resources...&quot;)</pre><p>The CloudFormation approach provides several advantages: it creates resources in the correct order, handles rollbacks automatically if something fails, and makes cleanup straightforward. The template includes comprehensive error handling and follows AWS best practices for resource naming and tagging.</p><p><strong>5.2 Phase 2: Gateway and Integration Setup</strong></p><p>Once the infrastructure is in place, the deployment process configures AgentCore Gateway with the appropriate targets. This phase demonstrates how to properly configure both Lambda and OpenAPI integrations:</p><pre>def create_gateway_and_targets():<br>    &quot;&quot;&quot;Configure AgentCore Gateway with Lambda and OpenAPI targets.&quot;&quot;&quot;<br>    <br>    # Create gateway with proper authentication<br>    gateway_response = agentcore_client.create_gateway(<br>        name=&quot;customer-support-gateway&quot;,<br>        protocolType=&quot;MCP&quot;,<br>        authorizerType=&quot;AWS_IAM&quot;<br>    )<br>    <br>    # Add Lambda target for internal operations<br>    agentcore_client.create_gateway_target(<br>        gatewayIdentifier=gateway_id,<br>        name=&quot;CustomerSupportLambda&quot;,<br>        targetConfiguration=lambda_target_config<br>    )</pre><p>The gateway configuration includes proper authentication setup, credential management for external APIs, and error handling for various failure scenarios. This phase also demonstrates how to manage API keys securely using AgentCore’s credential provider system.</p><p><strong>5.3 Phase 3: Runtime Deployment</strong></p><p>The final deployment phase packages and deploys the agent code to AgentCore Runtime. This process involves containerization, dependency management, and environment configuration:</p><pre>def deploy_agent_to_runtime():<br>    &quot;&quot;&quot;Deploy the agent to AgentCore Runtime with proper configuration.&quot;&quot;&quot;<br>    <br>    runtime = Runtime()<br>    runtime.configure(<br>        entrypoint=&quot;runtime_agent.py&quot;,<br>        auto_create_execution_role=True,<br>        auto_create_ecr=True,<br>        requirements_file=&quot;requirements.txt&quot;<br>    )<br>    <br>    launch_result = runtime.launch(env_vars={<br>        &quot;GATEWAY_URL&quot;: gateway_url,<br>        &quot;GATEWAY_REGION&quot;: &quot;us-east-1&quot;<br>    })</pre><p>The runtime deployment process handles Docker containerization automatically, creates necessary IAM roles, and configures environment variables that allow the agent to connect to the gateway and other AWS services.</p><p><strong>6. Validation and Testing: Ensuring Everything Works</strong></p><p>The validation process is designed to comprehensively test all AgentCore components and their interactions. This systematic approach helps identify issues early and provides confidence that the deployment is working correctly.</p><p><strong>Runtime Validation: Core Agent Functionality</strong></p><p>The runtime validation tests focus on the fundamental agent capabilities — can it receive requests, process them using its tools, and return appropriate responses:</p><pre>def test_runtime_queries():<br>    &quot;&quot;&quot;Test core agent functionality through AgentCore Runtime.&quot;&quot;&quot;<br>    <br>    test_queries = [<br>        &quot;Hello, can you help me?&quot;,<br>        &quot;What tools do you have available?&quot;, <br>        &quot;Can you check customer information?&quot;<br>    ]<br>    <br>    for query in test_queries:<br>        response = runtime.invoke_agent(<br>            agent_arn=agent_arn,<br>            prompt=query<br>        )<br>        # Validate response structure and content</pre><p>These tests verify that the agent can handle basic interactions, access its configured tools, and maintain appropriate conversational behavior. The validation includes checks for response format, timing, and error handling.</p><p><strong>Gateway Integration Testing: Tool Connectivity</strong></p><p>Gateway integration tests verify that the agent can successfully communicate with external systems through the configured targets:</p><pre>def test_gateway_integration():<br>    &quot;&quot;&quot;Verify gateway targets are properly configured and accessible.&quot;&quot;&quot;<br>    <br>    gateway_tests = [<br>        {<br>            &quot;query&quot;: &quot;Check warranty for serial MNO33333333&quot;,<br>            &quot;expected_tool&quot;: &quot;check_warranty_status&quot;,<br>            &quot;target_type&quot;: &quot;Lambda&quot;<br>        },<br>        {<br>            &quot;query&quot;: &quot;What&#39;s the weather on Mars?&quot;,<br>            &quot;expected_tool&quot;: &quot;mars_weather_api&quot;,<br>            &quot;target_type&quot;: &quot;OpenAPI&quot;<br>        }<br>    ]</pre><p>These tests ensure that the gateway routing works correctly, authentication is properly configured, and both Lambda and OpenAPI targets respond as expected.</p><p><strong>Memory Feature Validation: Conversation Continuity</strong></p><p>Memory validation tests verify that the agent can maintain context across multiple interactions and recall information from previous conversations:</p><pre>def test_memory_features():<br>    &quot;&quot;&quot;Test AgentCore Memory capabilities and context retention.&quot;&quot;&quot;<br>    <br>    # Test conversation continuity<br>    agent(&quot;My name is Alex and I&#39;m interested in AI.&quot;)<br>    response = agent(&quot;What was my name again?&quot;)<br>    <br>    # Verify the agent recalls &quot;Alex&quot; from previous interaction<br>    assert &quot;Alex&quot; in response</pre><p>These tests demonstrate one of AgentCore’s most powerful features — the ability to create truly conversational experiences that feel natural and contextually aware.</p><p><strong>7. Interactive Testing: Real-World Usage Patterns</strong></p><p>The interactive testing script (`run_queries_example.py`) demonstrates how the complete system works in realistic scenarios. This script is designed to showcase the agent’s capabilities while providing a foundation you can build upon for your own use cases.</p><p><strong>Memory Features in Action</strong></p><p>The memory demonstration shows how AgentCore Memory creates conversational continuity that makes interactions feel natural and efficient:</p><pre># Initial context setting<br>&quot;My name is Alex and I&#39;m interested in learning about AI.&quot;<br><br># Context extension  <br>&quot;I&#39;m particularly interested in machine learning applications.&quot;<br><br># Memory recall test<br>&quot;What was my name again?&quot;<br># Expected: Agent recalls &quot;Alex&quot; from earlier in conversation</pre><p>When you run these tests, you’ll see how the agent maintains context across multiple interactions, creating a more natural conversational flow than traditional stateless chatbots.</p><p><strong>Gateway Integration Demonstrations</strong></p><p>The gateway integration tests show how the agent seamlessly accesses different types of external systems:</p><pre># Lambda target usage<br>&quot;I have a Gaming Console Pro, warranty serial MNO33333333&quot;<br># Routes to Lambda function for warranty database lookup<br><br># OpenAPI target usage  <br>&quot;What&#39;s the weather in northern Mars?&quot;<br># Routes to NASA Mars weather API through OpenAPI specification</pre><p>These demonstrations highlight how AgentCore Gateway abstracts the complexity of different integration types, allowing your agent to work with various external systems through a unified interface.</p><p><strong>8. Sample Execution Results</strong></p><p>When you run the complete test suite, you’ll see output that demonstrates all components working together:</p><pre>## MEMORY FEATURES DEMONSTRATION<br>Testing short-term memory and conversation continuity...<br><br>Memory Query: My name is Alex and I&#39;m interested in learning about AI.<br>Response: Hello Alex! I&#39;m excited to help you learn about AI...<br><br>Memory Query: What was my name again?  <br>Response: Your name is Alex! You introduced yourself earlier...<br>Memory Feature: Agent should recall &#39;Alex&#39; from earlier conversation<br><br>## GATEWAY INTEGRATION DEMONSTRATION<br>Testing Lambda and OpenAPI targets through gateway...<br><br>Gateway Query: Check warranty for Gaming Console Pro serial MNO33333333<br>Response: I&#39;ve checked the warranty status for your Gaming Console Pro...<br>Gateway Feature: Should use Lambda target for warranty check</pre><p>This output demonstrates the seamless integration of all AgentCore components working together to create a sophisticated, context-aware customer support experience.</p><p><strong>8. Cleanup: Managing Resources Responsibly</strong></p><p>The cleanup process is designed to remove all created resources efficiently while providing clear feedback about what’s being deleted. This is crucial for managing AWS costs and maintaining a clean development environment.</p><p><strong>Comprehensive Resource Removal</strong></p><p>The cleanup script handles all resource types created during deployment:</p><pre>def cleanup_all_resources():<br>    &quot;&quot;&quot;Remove all AgentCore and AWS resources created by deployment.&quot;&quot;&quot;<br>    <br>    # AgentCore Runtime cleanup<br>    cleanup_runtime_agents()<br>    <br>    # AgentCore Gateway cleanup  <br>    cleanup_gateway_and_targets()<br>    <br>    # AWS Infrastructure cleanup<br>    cleanup_cloudformation_stack()<br>    <br>    # Local artifacts cleanup<br>    cleanup_local_files()</pre><p>The cleanup process follows the reverse order of deployment, ensuring that dependencies are properly handled and no resources are left orphaned.</p><p><strong>Optional but Recommended</strong></p><p>While cleanup is optional, it’s strongly recommended for several reasons:</p><blockquote>- <strong>Cost Management</strong>: Prevents ongoing charges for unused resources</blockquote><blockquote>- <strong>Account Hygiene</strong>: Keeps your AWS account organized and manageable</blockquote><blockquote>- <strong>Learning Environment</strong>: Allows you to experiment freely without accumulating resources</blockquote><blockquote>- <strong>Best Practices</strong>: Demonstrates proper resource lifecycle management</blockquote><p>The cleanup script includes confirmation prompts and detailed logging so you can see exactly what’s being removed and why.</p><p><strong>9. Conclusion: Simplifying Your AgentCore Journey</strong></p><p>This comprehensive example addresses the fundamental challenge I faced when starting with AgentCore: the lack of a complete, working example that demonstrates how all components work together in a realistic scenario.</p><p><strong>9.1 What You’ve Gained</strong></p><p>Through this tutorial, you’ve gained several valuable assets for your AgentCore development:</p><blockquote><strong>Complete Understanding</strong>: You now understand how AgentCore Runtime, Gateway, Memory, Identity, and Observability components work together to create sophisticated AI agents. This holistic view is crucial for designing effective agent architectures.</blockquote><blockquote><strong>Production-Ready Foundation</strong>: The code provided isn’t just a demo — it’s a foundation you can build upon for real-world applications. The patterns demonstrated here scale to enterprise use cases.</blockquote><blockquote><strong>Best Practices Implementation</strong>: From security and authentication to error handling and observability, the example demonstrates industry best practices that will serve you well in production environments.</blockquote><blockquote><strong>Troubleshooting Knowledge</strong>: By working through the complete deployment and testing process, you’ve gained experience with common issues and their solutions.</blockquote><p><strong>9.2 Key Takeaways for Your Projects</strong></p><p>Several important principles emerge from this implementation that will guide your own AgentCore projects:</p><blockquote><strong>Infrastructure First</strong>: Always start with a solid infrastructure foundation. Use Infrastructure as Code tools like CloudFormation to ensure reproducible, manageable deployments.</blockquote><blockquote><strong>Security by Design</strong>: Implement proper authentication and authorization from the beginning. AgentCore’s integration with AWS IAM provides robust security when configured correctly.</blockquote><blockquote><strong>Observability Matters</strong>: Build monitoring and logging into your agents from day one. AgentCore’s built-in observability features make this straightforward, but you need to plan for it.</blockquote><blockquote><strong>Memory Strategy</strong>: Think carefully about how your agent should use memory. The combination of short-term conversational memory and long-term context storage creates powerful user experiences.</blockquote><p><strong>9.3 Next Steps and Enhancements</strong></p><p>Now that you have a working foundation, consider these enhancements to expand your AgentCore capabilities:</p><p><strong>Enhanced Tool Integration</strong>: Add connections to your existing business systems, CRM platforms, or specialized APIs that are relevant to your use case.</p><p><strong>Advanced Memory Patterns</strong>: Implement semantic search capabilities, user preference learning, and cross-session context retention for more sophisticated memory usage.</p><p><strong>Multi-Agent Architectures</strong>: Deploy multiple specialized agents that can collaborate on complex tasks, each with their own expertise areas.</p><p><strong>Production Monitoring</strong>: Set up comprehensive monitoring dashboards, alerting systems, and performance optimization based on real usage patterns.</p><p><strong>CI/CD Integration</strong>: Implement automated testing and deployment pipelines that allow you to iterate quickly while maintaining quality.</p><p><strong>9.4 Making AgentCore Accessible</strong></p><p>The goal of this tutorial was to create the comprehensive resource I wished I had when starting with AgentCore. By providing a complete, working example with detailed explanations, I hope to eliminate the weeks of trial and error that many developers experience.</p><p>AgentCore’s true power lies not in its individual components, but in how they work together to enable sophisticated AI applications that can scale with your business needs. The patterns and practices demonstrated here provide a solid foundation for building production-ready AI agents that deliver real business value.</p><p>Whether you’re building customer support systems, content creation tools, workflow automation, or entirely new categories of AI applications, the architectural patterns and implementation techniques shown here will serve as a reliable foundation for your AgentCore journey.</p><p>The future of AI application development lies in platforms like AgentCore that abstract away infrastructure complexity while providing the flexibility and power needed for sophisticated use cases. With this foundation, you’re well-equipped to build the next generation of AI-powered applications.</p><p><strong>10. References and Additional Resources</strong></p><p><strong>AWS Official Documentation</strong></p><ul><li>[Amazon Bedrock AgentCore Developer Guide] (<a href="https://docs.aws.amazon.com/bedrock/latest/userguide/agentcore.htm">https://docs.aws.amazon.com/bedrock/latest/userguide/agentcore.htm</a>)</li><li>[AgentCore Runtime Documentation](<a href="https://docs.aws.amazon.com/bedrock/latest/userguide/agentcore-runtime.html">https://docs.aws.amazon.com/bedrock/latest/userguide/agentcore-runtime.html</a>)</li><li>[AgentCore Gateway MCP Protocol](<a href="https://docs.aws.amazon.com/bedrock/latest/userguide/agentcore-gateway.html">https://docs.aws.amazon.com/bedrock/latest/userguide/agentcore-gateway.html</a>)</li><li>[AgentCore Memory Management](<a href="https://docs.aws.amazon.com/bedrock/latest/userguide/agentcore-memory.html">https://docs.aws.amazon.com/bedrock/latest/userguide/agentcore-memory.html</a>)</li><li>[AgentCore Sample Examples] (<a href="https://github.com/awslabs/amazon-bedrock-agentcore-samples">https://github.com/awslabs/amazon-bedrock-agentcore-samples</a>)</li><li>[Amazon Bedrock Foundation Models](<a href="https://docs.aws.amazon.com/bedrock/latest/userguide/models-supported.html">https://docs.aws.amazon.com/bedrock/latest/userguide/models-supported.html</a>)</li><li>[AWS Lambda Developer Guide](<a href="https://docs.aws.amazon.com/lambda/latest/dg/">https://docs.aws.amazon.com/lambda/latest/dg/</a>)</li><li>[Amazon DynamoDB Developer Guide](<a href="https://docs.aws.amazon.com/dynamodb/latest/developerguide/">https://docs.aws.amazon.com/dynamodb/latest/developerguide/</a>)</li><li>[AWS CloudFormation User Guide](<a href="https://docs.aws.amazon.com/cloudformation/latest/userguide/">https://docs.aws.amazon.com/cloudformation/latest/userguide/</a>)</li></ul><p><strong>11. Project Repository</strong></p><ul><li><strong>Complete Source Code</strong>: [GitHub Repository Link] (<a href="https://github.com/Abhishek-Tiwary-Altran/agentcore-customer-support">https://github.com/Abhishek-Tiwary-Altran/agentcore-customer-support</a>)</li></ul><p><strong>Author and Acknowledgments</strong></p><ul><li><strong>Author</strong>: Abhishek Tiwary, Sr. Solution Architect, AWS</li><li><strong>LinkedIn</strong>: <a href="http://www.linkedin.com/in/abhishek-tiwary-710a7818">www.linkedin.com/in/abhishek-tiwary-710a7818</a></li><li><strong>Blogs:</strong></li></ul><ul><li><a href="https://medium.com/@abhishek.01.09/building-an-enterprise-grade-agentic-rag-chatbot-with-langgraph-and-aws-bedrock-agentcore-69789499f56e"># Building an Enterprise-Grade Agentic RAG Chatbot with LangGraph and AWS Bedrock AgentCore</a></li><li><a href="https://medium.com/@abhishek.01.09/building-an-advanced-rag-chatbot-with-multi-modal-document-processing-part-1-problem-analysis-dffd06498d8a">Building an Advanced RAG Chatbot with Multi-Modal Document Processing — Part 1: Problem Analysis…</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9e9ddf6a6a6a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building an Advanced RAG Chatbot with Multi-Modal Document Processing — Part 1: Problem Analysis…]]></title>
            <link>https://medium.com/@abhishek.01.09/building-an-advanced-rag-chatbot-with-multi-modal-document-processing-part-1-problem-analysis-dffd06498d8a?source=rss-e3eda35f3bf9------2</link>
            <guid isPermaLink="false">https://medium.com/p/dffd06498d8a</guid>
            <category><![CDATA[data-extraction]]></category>
            <category><![CDATA[agentic-rag]]></category>
            <category><![CDATA[bedrock]]></category>
            <category><![CDATA[unstructured]]></category>
            <category><![CDATA[mcp-protocol]]></category>
            <dc:creator><![CDATA[Abhishek Tiwary]]></dc:creator>
            <pubDate>Wed, 13 Aug 2025 16:21:27 GMT</pubDate>
            <atom:updated>2025-08-13T16:21:27.143Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>Building an Advanced RAG Chatbot with Multi-Modal Document Processing — Part 1: Problem Analysis and Solution Architecture</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GVELv1ltGy9DPFTP1HD_XA.png" /><figcaption><strong><em>Figure - 1</em></strong></figcaption></figure><h3><strong>Introduction</strong></h3><p>In the rapidly evolving landscape of artificial intelligence, the ability to process and understand multi-modal documents — combining text, images, and tables — has become crucial for building intelligent systems. Traditional RAG (Retrieval-Augmented Generation) systems have long struggled with the complexity of real-world documents that contain rich visual and structural information alongside textual content.</p><p>This technical blog series explores the development of a sophisticated RAG chatbot that leverages the Model Context Protocol (MCP), AWS Bedrock, and advanced document processing techniques to create a truly intelligent document analysis system. In Part 1, we examine the fundamental challenges facing traditional RAG systems and present our comprehensive solution architecture that addresses these limitations through innovative technology integration.</p><h4><strong>Evolution from LangGraph to MCP Architecture</strong></h4><p>Building upon our previous work with [<a href="https://medium.com/@abhishek.01.09/building-an-enterprise-grade-agentic-rag-chatbot-with-langgraph-and-aws-bedrock-agentcore-69789499f56e">LangGraph and AWS Bedrock AgentCore</a>] (where I developed an enterprise-grade agentic RAG chatbot with persistent memory and observability, this project represents a significant architectural evolution. While our previous implementation used LangGraph’s state-based workflow management with AgentCore for conversational memory, this new system adopts the Model Context Protocol (MCP) for more modular, scalable tool integration.</p><p>The key advancement lies in moving from a monolithic workflow approach to a distributed, tool-based architecture that enables:</p><ul><li><strong>Modular AI Tool Integration:</strong> MCP’s standardized protocol allows seamless integration of specialized AI capabilities</li><li><strong>Multi-Modal Document Understanding: </strong>Advanced processing of text, images, and tables in complex documents</li><li><strong>Intelligent Query Routing:</strong> Automatic routing between local knowledge base and real-time web search</li><li><strong>Scalable Architecture: </strong>Server-client separation for better performance and maintainability</li></ul><p>Our system goes beyond traditional text-based RAG implementations by incorporating AI-powered image analysis, intelligent table processing, and adaptive query routing. By utilizing cutting-edge technologies like unstructured.io for high-resolution document extraction and Claude-3 Sonnet for visual content analysis, we’ve created a system that can understand and reason about complex documents in ways previously impossible.</p><h3><strong>Problem Statement</strong></h3><p>Imagine walking into a world-class research library, only to discover that all the books have been stripped of their diagrams, charts, and illustrations, leaving behind only plain text. The carefully designed layouts that help readers understand complex concepts have been flattened into linear streams of words. The visual elements that make technical manuals comprehensible, the charts that reveal data patterns, and the flowcharts that explain processes have all vanished. This is the reality that most organizations face when trying to extract knowledge from their document repositories using traditional RAG systems.</p><h4><strong>The Document Blindness Crisis</strong></h4><p>Traditional RAG systems suffer from a fundamental form of “document blindness” — they can read words but cannot see meaning. When a financial analyst uploads an annual report filled with performance charts, market analysis graphs, and strategic diagrams, these systems extract only the surrounding text, completely ignoring the visual insights that often contain the most critical information. It’s like having a research assistant who can transcribe every word of a scientific paper but skips over all the experimental data visualizations, molecular diagrams, and statistical charts that actually prove the research findings.</p><p>This limitation becomes particularly devastating in technical fields where visual information is not supplementary but essential. Engineering documentation relies heavily on technical diagrams to explain component relationships and assembly procedures. Medical research papers use complex visualizations to demonstrate treatment efficacy and biological processes. Financial reports depend on charts and graphs to communicate performance trends and market analysis. When RAG systems ignore these visual elements, they’re essentially discarding the most valuable and informative parts of the documents.</p><h4><strong>The Integration Isolation Problem</strong></h4><p>Even when systems attempt to handle different content types, they typically treat them as isolated islands of information rather than interconnected elements of a cohesive narrative. This approach is like having a team of specialists — a text reader, an image viewer, and a data analyst — who work in separate rooms and never communicate with each other. The text specialist might read about a “significant increase in performance metrics,” while the chart analyst sees the actual 40% improvement graph, but neither understands how their information relates to the other’s findings.</p><p>This isolation becomes particularly problematic in complex documents where understanding depends on the relationship between different content types. A technical manual might describe a procedure in text while showing the visual steps in accompanying diagrams and providing specification details in reference tables. Traditional systems process these elements separately, losing the critical connections that make the information actionable.</p><h4><strong>The Static Knowledge Trap</strong></h4><p>Perhaps the most limiting aspect of traditional RAG systems is their static nature — they’re like libraries that never acquire new books and have no connection to the outside world. These systems can only answer questions about information that was available when they were last updated, leaving users stranded when they need current information or insights about recent developments.</p><p>This limitation creates a particularly frustrating user experience. Imagine asking a research assistant about “recent developments in renewable energy policy” only to receive information from six months ago, or inquiring about “current market trends” and getting outdated data that no longer reflects reality. Traditional RAG systems lack the intelligence to recognize when a query requires current information versus established knowledge, and they have no mechanism to automatically search external sources when their local knowledge is insufficient.</p><p>The routing problem extends beyond simple currency issues. These systems cannot distinguish between queries that require deep, domain-specific expertise (best served by carefully curated local knowledge) and questions that need broad, current information (better answered through web search). They treat all queries the same way, often providing irrelevant or outdated responses when users need timely, contextual information.</p><h4><strong>The Scale and Performance Bottleneck</strong></h4><p>As organizations grow and their document repositories expand, traditional RAG systems begin to buckle under the weight of inefficient processing and poor architectural decisions. It’s like trying to manage a growing library with the same manual filing system that worked when you had a few dozen books — the approach that seemed adequate for small-scale operations becomes a significant bottleneck as complexity increases.</p><p>These systems typically lack intelligent caching mechanisms, meaning they repeatedly process the same documents without learning from previous work. Every time a user uploads a complex technical manual, the system starts from scratch, wasting computational resources and time. The performance issues become particularly acute when dealing with large, complex documents that contain multiple content types, often taking hours to process comprehensive reports with no way to resume if the process fails partway through.</p><h3><strong>The Challenges and Our Technology Solutions</strong></h3><p>Building an advanced multi-modal RAG system is like constructing a sophisticated orchestra where each instrument must play in perfect harmony. The journey began with recognizing five fundamental challenges that traditional RAG systems face, and then carefully selecting technologies that could address each challenge while working seamlessly together.</p><h4><strong>Challenge 1: High-Quality Multi-Modal Extraction — Solved with unstructured.io and Advanced Document Processing</strong></h4><p>The first challenge we encountered was extracting meaningful content from complex documents while preserving the intricate relationships between text, images, and tables. Traditional PDF parsers often treat documents as flat text streams, completely missing the rich visual and structural information that makes documents truly valuable. We needed a solution that could understand documents the way humans do — recognizing that a diagram explains the adjacent text, that tables contain structured data requiring special handling, and that the spatial layout of elements carries semantic meaning.</p><p>This led us to <strong>**unstructured.io**</strong>, a revolutionary document processing library that treats documents as multi-modal entities rather than simple text containers. Unlike conventional parsers that strip away formatting and visual elements, unstructured.io’s “hi_res” strategy employs advanced OCR and layout detection algorithms to preserve document structure and identify different content types automatically. In the real world, law firms use this technology to process thousands of legal documents during discovery, maintaining the critical relationships between evidence photos, witness statements, and legal precedents. Financial institutions leverage it to analyze annual reports where charts and tables are as important as the narrative text.</p><p>To complement unstructured.io’s capabilities, we integrated <strong>**pdfplumber**</strong> as our specialized table extraction engine. While unstructured.io excels at overall document understanding, pdfplumber brings surgical precision to tabular data extraction, maintaining cell relationships and table structure that are crucial for accurate data analysis. This dual approach ensures we capture every piece of valuable information, whether it’s embedded in complex layouts or structured in precise tables.</p><h4><strong>Challenge 2: AI-Powered Content Analysis — Addressed with Claude-3 Sonnet’s Vision Capabilities</strong></h4><p>Once we could extract multi-modal content, the next challenge was understanding what it all meant. A technical diagram isn’t just pixels and lines — it represents processes, relationships, and knowledge that must be made searchable and understandable. Similarly, tables aren’t just rows and columns — they contain patterns, trends, and insights that traditional text-based systems completely miss.</p><p>This challenge led us to <strong>Claude-3 Sonnet</strong>, Anthropic’s most advanced vision-capable model. Sonnet doesn’t just see images — it understands them with remarkable sophistication. When analyzing a technical diagram, it identifies components, explains relationships, describes processes, and extracts key insights that make the visual content as searchable as text. Healthcare providers use Sonnet to analyze medical images and generate detailed reports, while engineering companies leverage it to interpret complex technical drawings and specifications.</p><h4><strong>Challenge 3: Intelligent Query Routing — Solved with Claude-3 Haiku and Hybrid Search Strategy</strong></h4><p>The third challenge was perhaps the most architecturally significant: determining whether a user’s query should be answered from our local knowledge base or from real-time web search. Traditional RAG systems are static — they can only answer questions about their pre-indexed content, leaving users stranded when they need current information or topics outside the knowledge base.</p><p>We solved this with <strong>Claude-3 Haiku</strong>, a model optimized for speed and efficiency, perfect for the split-second routing decisions our system requires. Haiku analyzes each incoming query against a configurable knowledge base of topics, understanding not just keywords but intent and context. Customer support companies use Haiku for real-time chat routing, ensuring complex technical questions reach specialists while simple queries get immediate automated responses.</p><p>Our routing system is complemented by <strong>Tavily API</strong>, a search service designed specifically for AI applications. Unlike traditional search APIs that return raw web results, Tavily provides curated, high-quality information optimized for AI processing. News organizations use Tavily for real-time information aggregation, while financial firms leverage it for gathering current market intelligence.</p><h4><strong>Challenge 4: Scalable Architecture Design — Addressed with Model Context Protocol (MCP)</strong></h4><p>The fourth challenge was architectural: how do you build a system that can handle multiple concurrent users while maintaining performance and enabling easy extension with new capabilities? Traditional monolithic approaches become bottlenecks as complexity grows, while microservices can become unwieldy without proper coordination.</p><p>Our solution was to adopt the <strong>Model Context Protocol (MCP)</strong>, an emerging standard that represents a paradigm shift in AI system architecture. MCP provides a standardized way to connect AI models with external tools and data sources, enabling true modularity and scalability. Large corporations are beginning to adopt MCP for standardizing their AI tool integration, recognizing that the future of AI systems lies in composable, interoperable components rather than monolithic applications.</p><p>We implemented our MCP server using <strong>FastMCP</strong>, a high-performance implementation optimized for enterprise-scale deployments. FastMCP supports Server-Sent Events (SSE) for real-time communication and includes comprehensive debugging capabilities that proved invaluable during development.</p><h4><strong>Challenge 5: Context Preservation and Performance — Solved with ChromaDB and AWS Bedrock</strong></h4><p>The final challenge was maintaining semantic relationships between different content types while ensuring efficient storage, retrieval, and processing. Multi-modal documents create complex webs of relationships that must be preserved throughout the processing pipeline, and the system must perform these operations at scale without sacrificing speed or accuracy.</p><p>For vector storage and semantic search, we chose <strong>ChromaDB</strong>, a database designed specifically for AI applications. Unlike traditional databases adapted for vector operations, ChromaDB is built from the ground up for embedding storage and similarity search. E-commerce platforms use ChromaDB for product recommendations, while knowledge management systems leverage it for intelligent document discovery.</p><p>The intelligence behind our embeddings comes from <strong>AWS Bedrock</strong>, Amazon’s managed AI service that provides enterprise-grade access to foundation models. Bedrock eliminates the complexity of managing GPU clusters and model serving infrastructure while providing the security and compliance certifications required for enterprise deployment. Within Bedrock, we use <strong>Titan Embeddings</strong> to generate high-quality vector representations that understand not just keywords but meaning and context.</p><p>Tying everything together is <strong>Streamlit</strong>, our choice for the user interface layer. Streamlit’s Python-native approach means our entire stack uses a single programming language, eliminating context switching and integration complexity. Companies like Uber use Streamlit for internal analytics dashboards, proving its enterprise readiness while enabling rapid development cycles.</p><h3><strong>Technology Stack Deep Dive</strong></h3><h4><strong>Model Context Protocol (MCP) — The Architectural Foundation</strong></h4><p>At the heart of our system lies the Model Context Protocol, a revolutionary approach that fundamentally changes how AI applications are architected. Think of MCP as the conductor of our technological orchestra, ensuring that every component communicates seamlessly while maintaining the flexibility to evolve independently. Unlike traditional monolithic AI systems where capabilities are tightly coupled, MCP creates a standardized language that allows different AI tools to work together without losing their individual strengths.</p><p>Our MCP implementation transforms what could have been a complex, interdependent system into an elegant collection of specialized services. The protocol serves as more than just a communication layer; it’s the foundation that enables our system to scale horizontally, adapt to new requirements, and maintain reliability even as individual components are updated or replaced. This architectural choice reflects our understanding that the future of AI systems lies not in building larger monoliths, but in creating intelligent, composable ecosystems.</p><ul><li><strong>MCP Server: The Intelligent Tooling Ecosystem</strong></li></ul><p>Our MCP server represents a paradigm shift from traditional API servers to an intelligent tooling ecosystem. Rather than hosting simple endpoints, our server orchestrates six sophisticated AI tools, each designed as a specialized expert in its domain. The AI-Enhanced PDF Extractor Tool exemplifies this approach, combining unstructured.io’s advanced parsing capabilities with Claude-3 Sonnet’s vision intelligence to transform static documents into rich, multi-modal content. This tool doesn’t just extract text; it understands document structure, preserves spatial relationships, and generates intelligent explanations of visual elements.</p><p>The AI-Enhanced DOCX Extractor Tool brings similar sophistication to Word documents, handling the complex challenge of embedded content analysis while maintaining the integrity of tables and images. These extractors work in harmony with our Route Question Tool, which implements a sophisticated decision-making process that analyzes query intent and context to determine the optimal information source. This routing intelligence represents a fundamental advancement over static RAG systems, enabling dynamic adaptation to user needs.</p><p>Our Generate Answer Tool and Grade Relevance Tool work as a quality assurance partnership, ensuring that responses are not only contextually appropriate but also grounded in reliable sources. The Web Search Tool completes this ecosystem by providing real-time access to current information, seamlessly integrating external knowledge with our local expertise. Together, these tools create a comprehensive AI capability that exceeds the sum of its parts.</p><ul><li><strong>MCP Client: The Orchestration Intelligence</strong></li></ul><p>The MCP client serves as the intelligent conductor of our document processing symphony, managing complex workflows that span multiple specialized tools while maintaining system coherence and performance. This client represents sophisticated orchestration logic that coordinates document processing workflows based on file type complexity, content characteristics, and processing requirements. Rather than following rigid pipelines, the client adapts its approach based on real-time analysis of document structure and user needs.</p><p>The client’s query processing pipeline implements adaptive routing with comprehensive fallback mechanisms, ensuring users receive relevant information regardless of query complexity or data source availability. This intelligence extends to vector store management, where the client handles the intricate process of document chunking, embedding generation, and similarity search operations while maintaining semantic relationships across different content types.</p><p>Perhaps most importantly, the client implements robust error handling and recovery strategies that ensure system resilience. When individual tools encounter issues, the client gracefully degrades functionality while maintaining core capabilities, ensuring users always receive meaningful responses even when optimal processing isn’t possible. The MCP architecture’s modularity means each tool can be independently developed, tested, and deployed, while the server-client separation enables horizontal scaling and load distribution that traditional monolithic systems cannot achieve.</p><h4><strong>AWS Bedrock — The Enterprise AI Foundation</strong></h4><p>AWS Bedrock serves as our enterprise-grade AI foundation, providing the computational intelligence that powers our multi-modal understanding capabilities. Bedrock represents more than just model access; it’s a comprehensive AI infrastructure that eliminates the complexity of managing GPU clusters, model serving, and scaling challenges while providing the security and compliance certifications essential for enterprise deployment.</p><p>Within this managed environment, Claude-3 Haiku emerges as our speed specialist, optimized for the split-second routing decisions that keep our system responsive. Haiku’s efficiency makes it perfect for high-frequency operations like query classification and initial response generation, where speed and cost-effectiveness are paramount. Its consistent output formatting and reliable JSON responses ensure our routing logic remains robust and predictable.</p><p>Claude-3 Sonnet represents the analytical powerhouse of our system, bringing sophisticated vision capabilities and complex reasoning to bear on multi-modal content. Sonnet’s ability to understand technical diagrams, analyze complex tables, and generate comprehensive explanations transforms static visual content into searchable, understandable knowledge. This model’s technical accuracy and detailed analysis capabilities make it indispensable for processing the complex documents our users depend on.</p><p>Titan Embeddings completes our Bedrock integration by generating high-quality vector representations that capture semantic meaning beyond simple keyword matching. These embeddings understand context, domain-specific terminology, and conceptual relationships, enabling our similarity search to find relevant content even when queries use different terminology than the source documents.</p><h4><strong>unstructured.io — The Document Understanding Engine</strong></h4><p>unstructured.io represents a fundamental breakthrough in document processing technology, moving beyond traditional text extraction to true document understanding. The library’s “hi_res” strategy employs advanced OCR and layout detection algorithms that preserve the spatial relationships and structural elements that give documents their meaning. This approach recognizes that documents are more than collections of words; they’re carefully structured information artifacts where layout, formatting, and visual elements carry semantic significance.</p><p>The library’s element classification capabilities automatically identify and categorize different content types within documents, distinguishing between headers, body text, tables, images, and other structural elements. This classification enables our system to apply appropriate processing strategies to each content type, ensuring that tables receive tabular analysis, images get visual interpretation, and text maintains its contextual relationships. In our implementation, unstructured.io serves as the primary engine for PDF document parsing and content extraction, handling the complex challenge of maintaining document fidelity while enabling downstream AI processing.</p><h4><strong>ChromaDB — The Semantic Memory System</strong></h4><p>ChromaDB represents our choice for semantic memory, designed from the ground up for AI applications rather than adapted from traditional database architectures. This vector database understands the unique requirements of embedding storage and similarity search, providing optimized performance for high-dimensional vector operations that form the backbone of semantic search.</p><p>The database’s AI-native design means it handles the complexities of vector similarity calculations, metadata filtering, and persistent storage with the efficiency that modern AI applications demand. ChromaDB’s Python integration provides a seamless development experience that aligns with our technology stack, while its simple setup and management reduce operational complexity compared to traditional database solutions. In our system, ChromaDB stores the vector representations of all processed document chunks, creating a semantic index that enables intelligent content retrieval based on meaning rather than keyword matching.</p><h4><strong>Streamlit — The Rapid Development Interface</strong></h4><p>Streamlit serves as our user interface foundation, chosen for its unique ability to create sophisticated web applications using pure Python. This framework eliminates the traditional complexity of web development, allowing us to focus on AI functionality rather than frontend intricacies. Streamlit’s component-based architecture provides pre-built widgets for file uploads, chat interfaces, and real-time data visualization that align perfectly with our multi-modal document processing requirements.</p><p>The framework’s real-time update capabilities ensure that users see immediate feedback as documents are processed and queries are answered, creating an engaging experience that keeps users informed about system status. Streamlit’s session state management handles the complexities of maintaining user context across interactions, while its caching mechanisms optimize performance for repeated operations. The framework’s Python-native approach means our entire technology stack uses a single programming language, eliminating context switching and reducing integration complexity.</p><h3><strong>High-Level Architecture Block Diagram</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xnnaL9t20v2oAJ3nZdqKAw.png" /></figure><h3><strong>Solution Approach</strong></h3><p>Our solution approach can be likened to building a world-class research library combined with a team of expert librarians, translators, and research assistants. Just as a modern library doesn’t simply store books but creates an intelligent ecosystem for knowledge discovery, our system transforms static documents into a living, searchable knowledge base that understands context, meaning, and user intent.</p><h4><strong>1. Advanced Document Processing Pipeline — The Master Archivist’s Workshop</strong></h4><p>Imagine a master archivist who doesn’t just file documents but truly understands their content, structure, and hidden meanings. Our document processing pipeline operates like this expert archivist’s workshop, where every document undergoes a meticulous transformation process that preserves not just the words, but the relationships, visual elements, and contextual significance that make information truly valuable.</p><p>The pipeline begins with unstructured.io’s “hi_res” strategy, which functions like having a team of expert document analysts who understand that a technical manual isn’t just text on pages, but a carefully orchestrated combination of instructions, diagrams, and data tables that must work together. This approach recognizes that when an engineer reads a maintenance manual, they need to see how the text instructions relate to the accompanying diagrams and reference the relevant specification tables.</p><p>Our automatic image extraction and indexing system works like a specialized photography department in our archival workshop. Every visual element is carefully catalogued, numbered, and prepared for analysis, ensuring that no diagram, chart, or illustration is lost in the digitization process. This systematic approach means that when a user later searches for information about a specific process, they’ll find not just the textual description but also the visual representations that make the concept clear.</p><p>The intelligent caching system operates like an institutional memory that learns from each processing session. Just as an experienced librarian remembers which books have been processed and can quickly direct researchers to the right resources, our caching system ensures that once a document has been analyzed and enhanced with AI insights, that valuable work is preserved and instantly available for future queries.</p><h4><strong>2. AI-Powered Content Analysis — The Expert Translation Service</strong></h4><p>Our AI-powered content analysis functions like having a team of world-class translators who don’t just convert languages, but translate complex visual and tabular information into clear, searchable narratives. Claude-3 Sonnet serves as our master translator, capable of looking at a technical diagram and explaining not just what it shows, but what it means, how it works, and why it matters.</p><p>When Sonnet analyzes an image, it’s like having an expert in the relevant field examine the visual content and provide a comprehensive explanation that captures both the obvious and subtle details. A flowchart becomes a step-by-step process explanation, a technical diagram transforms into a detailed component analysis, and a data visualization evolves into insights about trends and relationships. This translation process makes visual information as searchable and useful as traditional text.</p><p>The table processing capability works similarly to having a data analyst who can look at any spreadsheet or table and immediately understand its purpose, identify key patterns, and explain the relationships between different data points. Rather than leaving users to interpret raw tabular data, our system provides natural language explanations that highlight the most important insights and make complex data accessible to anyone.</p><h4><strong>3. Intelligent Query Routing — The Expert Reference Librarian System</strong></h4><p>Our intelligent query routing system operates like having the world’s most knowledgeable reference librarian who instantly knows whether your question is best answered from the library’s specialized collection or requires current information from external sources. This system represents a fundamental advancement over traditional approaches, creating a dynamic decision-making process that adapts to each user’s specific information needs.</p><p>The automatic query analysis functions like an expert librarian who can listen to your question and immediately understand not just what you’re asking, but what type of information you really need. When someone asks about “the latest developments in AI regulation,” the system recognizes this requires current information and routes to web search. When they ask about “machine learning fundamentals,” it understands this is best served by our curated knowledge base of technical documentation.</p><p>Our hybrid information retrieval strategy works like having access to both a specialized research library and a team of current affairs researchers. The primary vectorstore search acts as our specialized collection, where domain experts have carefully curated and organized the most valuable resources. When this collection doesn’t contain relevant information, our intelligent fallback system automatically connects to real-time web search, ensuring users always receive comprehensive answers regardless of whether the information exists in our local collection.</p><h4><strong>4. Scalable MCP Architecture — The Modular Expert Network</strong></h4><p>Our MCP architecture functions like creating a network of specialized expert consultants who can work independently yet collaborate seamlessly when needed. Rather than building a monolithic system where all capabilities are interdependent, we’ve created a modular ecosystem where each component excels in its specific domain while contributing to the overall intelligence of the system.</p><p>The modular tool-based design works like having a consulting firm where each expert can be engaged independently for their specific expertise, yet they all follow the same professional standards and communication protocols. This means we can enhance, update, or scale individual capabilities without disrupting the entire system, much like how a consulting firm can add new specialists or upgrade existing expertise without reorganizing the entire organization.</p><p>Our async processing approach functions like having a team of experts who can work on multiple projects simultaneously without blocking each other’s progress. When one specialist is analyzing a complex document, others can continue handling different queries, ensuring that system performance remains optimal even under heavy load. The comprehensive error handling works like having experienced project managers who can adapt to unexpected challenges while keeping projects on track, ensuring users always receive meaningful responses even when optimal processing isn’t possible.</p><h3><strong>Extension to Industrial Use Cases</strong></h3><p>Our advanced RAG system represents more than just a technological achievement; it’s a transformative solution that addresses real-world challenges across diverse industries. Like a master key that opens doors to previously inaccessible information, our multi-modal document processing capabilities unlock the hidden value in complex documents that have long frustrated organizations seeking to leverage their knowledge assets.</p><p><strong>Healthcare &amp; Medical Research — Advancing Patient Care Through Intelligent Document Analysis</strong></p><p>In the healthcare sector, our system functions like having a team of medical librarians and research analysts who never sleep, continuously processing and understanding the vast corpus of medical knowledge. Medical literature analysis becomes dramatically more powerful when our system can simultaneously understand research text, interpret complex medical diagrams, analyze statistical tables, and extract insights from medical imaging reports. Imagine a researcher investigating a rare disease who can instantly access not just textual descriptions but also visual representations of symptoms, treatment protocols shown in flowcharts, and statistical outcomes presented in complex tables.</p><p>Clinical documentation processing transforms how healthcare providers manage patient information. Our system can analyze patient records that combine textual notes with diagnostic images, lab result tables, and treatment timelines, creating comprehensive patient profiles that support better clinical decision-making. In drug discovery, pharmaceutical researchers can leverage our system to analyze research documents that integrate molecular diagrams, clinical trial data visualizations, and complex statistical analyses, accelerating the path from research to treatment.</p><h4><strong>Financial Services — Transforming Risk Assessment and Regulatory Compliance</strong></h4><p>The financial services industry operates in a world where visual data representation is as critical as textual analysis. Our system serves as an intelligent financial analyst who can simultaneously read annual reports, interpret performance charts, analyze risk matrices, and understand complex financial tables. When processing regulatory filings, the system doesn’t just extract text but understands the relationships between narrative explanations and supporting financial visualizations, creating comprehensive insights that support better investment decisions and risk assessment.</p><p>Compliance documentation becomes manageable when our system can process regulatory documents that combine procedural text with compliance flowcharts, requirement matrices, and organizational diagrams. Financial institutions can finally leverage their vast repositories of complex documents, transforming static compliance materials into dynamic, searchable knowledge bases that support real-time decision-making and regulatory reporting.</p><h4><strong>Manufacturing &amp; Engineering — Revolutionizing Technical Knowledge Management</strong></h4><p>Manufacturing and engineering organizations possess some of the most complex multi-modal documents in any industry. Our system functions like having a master engineer who can instantly understand technical manuals that combine detailed specifications, assembly diagrams, and procedural instructions. Quality control processes are enhanced when inspection reports that include measurement data, compliance tables, and visual documentation can be processed as integrated knowledge rather than separate information silos.</p><p>Product development accelerates when R&amp;D documents containing prototype images, test result visualizations, and design specifications can be analyzed holistically. Engineers can query complex technical knowledge bases using natural language and receive comprehensive answers that draw from textual descriptions, technical diagrams, and specification tables, dramatically reducing the time required to access critical technical information.</p><h4><strong>Legal &amp; Compliance — Streamlining Complex Legal Analysis</strong></h4><p>The legal profession has long struggled with documents that combine complex textual clauses with organizational charts, procedural flowcharts, and detailed requirement matrices. Our system serves as an intelligent legal research assistant who can analyze contracts that integrate textual terms with visual representations of organizational structures and process flows. Patent research becomes more efficient when applications containing technical diagrams, detailed specifications, and complex claims can be processed as unified documents rather than fragmented information sources.</p><h4><strong>Education &amp; Research — Enhancing Academic Knowledge Discovery</strong></h4><p>Academic institutions possess vast repositories of research materials that combine textual analysis with complex figures, data tables, and experimental visualizations. Our system functions like having a research librarian who can instantly understand and connect information across diverse academic materials. Research papers that integrate theoretical discussions with experimental diagrams and statistical analyses can be processed as comprehensive knowledge sources rather than fragmented information.</p><h4><strong>Government &amp; Public Sector — Improving Public Service Through Intelligent Document Processing</strong></h4><p>Government organizations manage some of the most complex and diverse document collections in any sector. Our system serves as an intelligent policy analyst who can process government documents that combine statistical data with organizational charts and procedural diagrams. Public records management becomes more efficient when documents containing forms, tables, and administrative diagrams can be processed as integrated information systems rather than separate data sources.</p><h3><strong>Conclusion</strong></h3><p>In Part 1 of this technical blog series, we have explored the fundamental challenges that traditional RAG systems face when dealing with real-world, multi-modal documents and presented our comprehensive solution architecture that addresses these limitations through innovative technology integration.</p><h4><strong>Key Insights from Part 1</strong></h4><p>1. <strong>Problem Identification</strong>: Traditional RAG systems suffer from “document blindness,” treating complex multi-modal documents as simple text streams and losing critical visual and structural information that often contains the most valuable insights.</p><p>2. <strong>Technology Integration</strong>: Our solution combines cutting-edge technologies including the Model Context Protocol (MCP), AWS Bedrock’s foundation models, unstructured.io’s advanced document processing, and intelligent query routing to create a truly comprehensive document understanding system.</p><p>3. <strong>Architectural Innovation</strong>: The adoption of MCP represents a paradigm shift from monolithic to modular AI system architecture, enabling scalability, maintainability, and independent component evolution.</p><p>4. <strong>Industrial Applicability</strong>: The solution addresses real-world challenges across diverse industries, from healthcare and finance to manufacturing and government, demonstrating broad practical value.</p><h4><strong>Looking Ahead to Part 2</strong></h4><p>In Part 2 of this series, we will dive deep into the technical implementation details, exploring the system design, code architecture, and detailed explanations of how each component works together to create this sophisticated multi-modal RAG system. We’ll examine the actual code implementations, design patterns, and technical decisions that bring this solution to life.</p><p>The journey from identifying problems to implementing solutions represents the essence of innovative engineering — understanding not just what needs to be built, but why it matters and how it can transform the way organizations interact with their knowledge assets.</p><h3><strong>References</strong></h3><p>1. <strong>Model Context Protocol (MCP)</strong>: <a href="https://modelcontextprotocol.io/">https://modelcontextprotocol.io/</a></p><p>2. <strong>AWS Bedrock Documentation</strong>: <a href="https://docs.aws.amazon.com/bedrock/">https://docs.aws.amazon.com/bedrock/</a></p><p>3. <strong>Anthropic Claude Models</strong>: <a href="https://www.anthropic.com/claude">https://www.anthropic.com/claude</a></p><p>4. <strong>unstructured.io Documentation</strong>: <a href="https://unstructured-io.github.io/unstructured/">https://unstructured-io.github.io/unstructured/</a></p><p>5. <strong>LangChain Framework</strong>: <a href="https://python.langchain.com/">https://python.langchain.com/</a></p><p>6. <strong>ChromaDB Vector Database</strong>: <a href="https://docs.trychroma.com/">https://docs.trychroma.com/</a></p><p>7. <strong>Streamlit Documentation</strong>: <a href="https://docs.streamlit.io/">https://docs.streamlit.io/</a></p><p>8. <strong>Tavily Search API</strong>: <a href="https://tavily.com/">https://tavily.com/</a></p><p>9. <strong>FastMCP Implementation</strong>: <a href="https://github.com/jlowin/fastmcp">https://github.com/jlowin/fastmcp</a></p><p>10. <strong>RAG Best Practices</strong>: <a href="https://arxiv.org/abs/2312.10997">https://arxiv.org/abs/2312.10997</a></p><p><em>*This is Part 1 of a comprehensive technical blog series on building advanced RAG systems with multi-modal document processing capabilities. Part 2 will focus on the detailed technical implementation, system design, and code architecture that brings this solution to life.*</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dffd06498d8a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[# Building an Enterprise-Grade Agentic RAG Chatbot with LangGraph and AWS Bedrock AgentCore]]></title>
            <link>https://medium.com/@abhishek.01.09/building-an-enterprise-grade-agentic-rag-chatbot-with-langgraph-and-aws-bedrock-agentcore-69789499f56e?source=rss-e3eda35f3bf9------2</link>
            <guid isPermaLink="false">https://medium.com/p/69789499f56e</guid>
            <category><![CDATA[langgraph]]></category>
            <category><![CDATA[bedrock]]></category>
            <category><![CDATA[observability]]></category>
            <category><![CDATA[amazon-bedrock-agentcore]]></category>
            <category><![CDATA[agentic-ai]]></category>
            <dc:creator><![CDATA[Abhishek Tiwary]]></dc:creator>
            <pubDate>Sun, 10 Aug 2025 16:18:43 GMT</pubDate>
            <atom:updated>2025-08-13T06:05:26.408Z</atom:updated>
            <content:encoded><![CDATA[<h3>Building an Enterprise-Grade Agentic RAG Chatbot with LangGraph and AWS Bedrock AgentCore</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4ObywUMy1IxTk03YOZEpew.png" /></figure><h3><strong>Introduction</strong></h3><p>In today’s rapidly evolving AI landscape, traditional chatbots fall short of enterprise requirements due to their inability to maintain context, validate information accuracy, and adapt to complex decision-making scenarios. The emergence of <strong>Agentic AI</strong> represents a paradigm shift from simple question-answering systems to intelligent agents capable of reasoning, planning, and executing complex workflows.</p><p>This comprehensive technical implementation showcases an enterprise-grade <strong>Retrieval-Augmented Generation (RAG) chatbot</strong> that transcends conventional limitations by integrating <strong>LangGraph’s agentic framework</strong> with <strong>AWS Bedrock AgentCore</strong>. Unlike traditional RAG systems that follow linear retrieval-generation patterns, our solution implements a sophisticated decision-making workflow that mirrors human cognitive processes.</p><h4><strong>The Challenge: Beyond Simple RAG</strong></h4><p>Traditional RAG systems suffer from several critical limitations:</p><blockquote>- <strong>Static Information Flow</strong>: Linear retrieval → generation without intelligent routing</blockquote><blockquote>- <strong>Context Amnesia</strong>: No memory of previous conversations or user preferences</blockquote><blockquote>- <strong>Quality Uncertainty</strong>: No validation mechanisms for generated responses</blockquote><blockquote>- <strong>Single Source Dependency</strong>: Reliance on either local knowledge or web search, not both</blockquote><blockquote>- <strong>Security Gaps</strong>: Lack of enterprise-grade authentication and authorization</blockquote><h4><strong><em>Solution: Agentic RAG Architecture</em></strong></h4><p>Our implementation addresses these challenges through:</p><blockquote>- <strong>Intelligent Query Routing</strong>: An AI-powered decision engine that analyzes incoming questions and dynamically routes them to the most appropriate data source — conversation memory, local knowledge base, or real-time web search. This routing is based on semantic analysis of the query content and historical interaction patterns.</blockquote><blockquote>- <strong>Multi-Stage Validation Pipeline</strong>: A comprehensive quality assurance system that validates responses through three critical checkpoints:</blockquote><blockquote>- <strong>Document Relevance Assessment</strong>: Ensures retrieved documents actually relate to the user’s question</blockquote><blockquote>- <strong>Hallucination Detection</strong>: Verifies that generated answers are grounded in provided context</blockquote><blockquote>- <strong>Answer Usefulness Evaluation</strong>: Confirms that responses actually address the user’s intent</blockquote><blockquote>- <strong>Persistent Conversational Memory</strong>: Integration with AWS Bedrock AgentCore provides enterprise-grade memory management that maintains conversation context across sessions, enabling personalized interactions and contextual follow-up questions.</blockquote><blockquote>- <strong>Enterprise Security Framework</strong>: Implementation of AWS Cognito for user authentication combined with fine-grained IAM policies ensures secure access control and compliance with enterprise security standards.</blockquote><blockquote>- <strong>Production-Ready Observability</strong>: Comprehensive tracing and monitoring using OpenTelemetry provides real-time insights into system performance, user interactions, and potential issues.</blockquote><h3><strong>Technology Stack Deep Dive</strong></h3><p><strong>Core Agentic Framework:</strong></p><blockquote>- <strong>LangGraph</strong>: Facebook’s cutting-edge framework for building stateful, multi-actor applications with LLMs. Unlike traditional chain-based approaches, LangGraph enables the creation of cyclical graphs where agents can revisit previous states, make decisions, and adapt their behavior based on intermediate results. This is crucial for implementing the complex decision-making logic required in our agentic RAG system.</blockquote><blockquote>- <strong>LangChain</strong>: Provides the foundational abstractions for LLM integration, document processing, and prompt management. Acts as the bridge between our workflow logic and the underlying language models, handling tokenization, embedding generation, and response parsing.</blockquote><blockquote>- <strong>AWS Bedrock</strong>: Amazon’s fully managed service providing access to foundation models. We leverage:</blockquote><blockquote>- <strong>Claude-3 Haiku</strong>: Anthropic’s fast, cost-effective model optimized for conversational AI with strong reasoning capabilities</blockquote><blockquote>- <strong>Titan Embeddings</strong>: Amazon’s proprietary embedding model optimized for semantic search and retrieval tasks</blockquote><h4><strong>Memory &amp; Observability Infrastructure:</strong></h4><blockquote>- <strong>Bedrock AgentCore</strong>: AWS’s managed service for agent memory and session management. Provides persistent storage for conversation history, user preferences, and contextual information across sessions. Unlike simple database storage, AgentCore is optimized for AI agent workflows with built-in indexing and retrieval capabilities.</blockquote><blockquote>- <strong>OpenTelemetry</strong>: Industry-standard observability framework providing distributed tracing, metrics collection, and logging. Essential for monitoring complex agentic workflows where understanding the decision path is crucial for debugging and optimization.</blockquote><blockquote>- <strong>ChromaDB</strong>: Open-source vector database optimized for AI applications. Provides efficient similarity search capabilities with support for metadata filtering and hybrid search combining vector and keyword matching.</blockquote><h4><strong>User Interface &amp; Security Layer:</strong></h4><blockquote>- <strong>Streamlit</strong>: Python-based framework for rapid development of data science and AI applications. Chosen for its simplicity in creating interactive interfaces while maintaining the flexibility to integrate complex backend workflows.</blockquote><blockquote>- <strong>AWS Cognito</strong>: Fully managed identity service providing user authentication, authorization, and user management. Supports enterprise features like multi-factor authentication, social identity providers, and compliance with security standards.</blockquote><blockquote>- <strong>IAM Policies</strong>: Fine-grained access control ensuring that users and services have only the minimum permissions required for their functions, following the principle of least privilege.</blockquote><p><strong>System Architecture &amp; Design Flow</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gapLNChsXp37JRUi0EEbIw.png" /></figure><p><strong>Information Flow Pattern:</strong></p><p><strong>1. Authentication Flow</strong>: User credentials → Cognito → JWT tokens → Session establishment</p><p><strong>2. Query Processing Flow:</strong> User question → Memory search → Document retrieval → Web search (if needed) → Response generation</p><p><strong>3. Quality Assurance Flow:</strong> Generated response → Hallucination check → Usefulness validation → Final output</p><p><strong>4. Memory Persistence Flow:</strong> Conversation pairs → AgentCore storage → Future context retrieval</p><p><strong>5. Observability Flow: </strong>All operations → OpenTelemetry spans → Distributed tracing → Performance monitoring</p><h3><strong>Core Implementation: Key Code Snippets</strong></h3><p><strong>1. LangGraph State Management</strong></p><p>The foundation of our agentic system lies in stateful workflow management. Unlike traditional function chaining, LangGraph maintains a persistent state that flows through each processing node, enabling complex decision-making and backtracking capabilities.</p><pre>class GraphState(TypedDict):<br>    &quot;&quot;&quot;Workflow state definition for type safety and clarity<br>    <br>    This TypedDict ensures type safety across the entire workflow while providing<br>    a clear contract for what data flows between nodes. Each field serves a specific<br>    purpose in the decision-making process:<br>    <br>    - question: The original user query, preserved throughout the workflow<br>    - generation: The current generated response, may be updated multiple times<br>    - web_search: Flag indicating whether web search is needed (&quot;Yes&quot;/&quot;No&quot;)<br>    - documents: Retrieved context, can be from memory, vector store, or web<br>    &quot;&quot;&quot;<br>    question: str      # Original user query - immutable reference point<br>    generation: str    # Current generated answer - evolves through workflow<br>    web_search: str    # Decision flag for routing logic<br>    documents: List[str]  # Context sources - dynamic based on routing decisions<br><br>class WorkflowManager:<br>    &quot;&quot;&quot;Central orchestrator for the agentic RAG workflow<br>    <br>    This class implements the Command Pattern, encapsulating all workflow logic<br>    and maintaining references to specialized components. The design follows<br>    the Single Responsibility Principle where each component handles one aspect<br>    of the RAG process.<br>    <br>    Key Design Decisions:<br>    - Dependency injection for all components enables testing and flexibility<br>    - Optional memory components allow graceful degradation<br>    - Session tracking enables user-specific personalization<br>    &quot;&quot;&quot;<br>    def __init__(self, retriever, rag_chain, retrieval_grader, <br>                 hallucination_grader, answer_grader, web_search_tool,<br>                 memory_client=None, memory_id=None, actor_id=None, session_id=None):<br>        # Core RAG components - required for basic functionality<br>        self.retriever = retriever                    # Vector database interface<br>        self.rag_chain = rag_chain                   # LLM generation pipeline<br>        self.retrieval_grader = retrieval_grader     # Document relevance assessor<br>        self.hallucination_grader = hallucination_grader  # Factual grounding validator<br>        self.answer_grader = answer_grader           # Response usefulness evaluator<br>        self.web_search_tool = web_search_tool       # External knowledge source<br>        <br>        # Memory components - optional for enhanced functionality<br>        self.memory_client = memory_client           # Bedrock AgentCore client<br>        self.memory_id = memory_id                   # Unique memory identifier<br>        self.actor_id = actor_id                     # User-specific identifier<br>        self.session_id = session_id                 # Session-specific identifier<br>        <br>        # The memory system enables:<br>        # 1. Cross-session conversation continuity<br>        # 2. User-specific personalization<br>        # 3. Context-aware follow-up questions<br>        # 4. Learning from user preferences over time</pre><p>The `<strong>GraphState</strong>` acts as a shared memory bus that carries information between processing nodes. This design enables:</p><ul><li><strong>State Persistence:</strong> Each node can access and modify the complete context</li><li><strong>Decision Tracking: </strong>The `web_search` flag enables conditional routing</li><li><strong>Context Evolution:</strong> The `documents` field adapts based on routing decisions</li><li><strong>Immutable Reference:</strong> The original `question` remains unchanged for consistency</li></ul><p>The `<strong>WorkflowManager</strong>` implements the Mediator Pattern, coordinating interactions between specialized components without tight coupling. This architecture enables:</p><ul><li><strong>Component Swapping:</strong> Easy replacement of individual components for testing or optimization</li><li><strong>Graceful Degradation:</strong> System continues functioning even if memory services are unavailable</li><li><strong>Session Management: </strong>User-specific tracking enables personalized experiences</li></ul><p><strong>2. Memory-Aware RAG Chain</strong></p><p>The RAG chain represents the cognitive core of our system, where retrieved context is transformed into coherent responses. The integration with Bedrock AgentCore memory elevates this from simple context-response generation to contextually-aware conversation.</p><pre>def create_rag_chain(llm, memory_client=None, memory_id=None, actor_id=None, session_id=None):<br>    &quot;&quot;&quot;Create RAG chain with memory integration<br>    <br>    This function implements the Factory Pattern to create a context-aware RAG chain.<br>    The key innovation is the conditional integration of memory capabilities,<br>    allowing the same codebase to work with or without persistent memory.<br>    <br>    Architecture Decision: Tool-Based Memory Access<br>    Instead of directly injecting memory into prompts, we use LangChain&#39;s tool<br>    system. This approach provides several advantages:<br>    1. The LLM can decide when to access memory based on query context<br>    2. Memory access is traced and logged for observability<br>    3. Error handling is encapsulated within the tool<br>    4. The system can gracefully handle memory service outages<br>    &quot;&quot;&quot;<br>    <br>    # Conditional memory integration - enables graceful degradation<br>    if memory_client and memory_id:<br>        @tool<br>        def get_conversation_history():<br>            &quot;&quot;&quot;Retrieve recent conversation history for context<br>            <br>            This tool implements the Repository Pattern for memory access,<br>            abstracting the complexity of Bedrock AgentCore API calls.<br>            <br>            Key Features:<br>            - Automatic error handling with fallback responses<br>            - Configurable result limits to control context size<br>            - Session-specific filtering for user privacy<br>            - Structured error messages for debugging<br>            &quot;&quot;&quot;<br>            try:<br>                # Query AgentCore with specific filters<br>                events = memory_client.list_events(<br>                    memory_id=memory_id,        # Specific memory instance<br>                    actor_id=actor_id,          # User-specific filtering<br>                    session_id=session_id,      # Session-specific context<br>                    max_results=5               # Limit context size for performance<br>                )<br>                <br>                # Transform events into conversational context<br>                # This step is crucial for maintaining conversation flow<br>                return events<br>            except Exception as e:<br>                # Graceful error handling - system continues without memory<br>                logger.warning(f&quot;Memory access failed: {str(e)}&quot;)<br>                return f&quot;Error retrieving history: {str(e)}&quot;<br>        <br>        # Bind the memory tool to the LLM - enables autonomous memory access<br>        llm_with_tools = llm.bind_tools([get_conversation_history])<br>    else:<br>        # Fallback mode - standard LLM without memory capabilities<br>        llm_with_tools = llm<br>    <br>    def traced_rag(inputs):<br>        &quot;&quot;&quot;Core RAG generation function with distributed tracing<br>        <br>        This function implements the Template Method Pattern, defining the<br>        standard flow for RAG generation while allowing customization through<br>        the memory tool system.<br>        <br>        Tracing Strategy:<br>        OpenTelemetry spans provide visibility into:<br>        - Generation latency and performance<br>        - Input/output characteristics<br>        - Memory access patterns<br>        - Error rates and failure modes<br>        &quot;&quot;&quot;<br>        with tracer.start_as_current_span(&quot;rag_generation&quot;) as span:<br>            # Extract and validate inputs<br>            question = inputs.get(&quot;question&quot;, &quot;&quot;)<br>            context = inputs.get(&quot;context&quot;, &quot;&quot;)<br>            <br>            # Add telemetry attributes for monitoring<br>            span.set_attribute(&quot;question.length&quot;, len(question))<br>            span.set_attribute(&quot;context.length&quot;, len(context))<br>            span.set_attribute(&quot;memory.enabled&quot;, memory_client is not None)<br>            <br>            # Construct conversation messages using the Chat Message format<br>            # This structure is optimized for conversational AI models<br>            messages = [<br>                SystemMessage(content=&quot;&quot;&quot;You are an AI research assistant specialized in <br>                providing accurate, contextual responses. Use the provided context to answer <br>                questions precisely. If you have access to conversation history tools, <br>                reference previous interactions when relevant. Always ground your responses <br>                in the provided context and indicate when information is uncertain.&quot;&quot;&quot;),<br>                <br>                HumanMessage(content=f&quot;Question: {question}\nContext: {context}&quot;)<br>            ]<br>            <br>            # Generate response using the tool-enabled LLM<br>            # The LLM can autonomously decide whether to access memory<br>            result = llm_with_tools.invoke(messages)<br>            <br>            # Add output telemetry<br>            span.set_attribute(&quot;generation.length&quot;, len(result.content))<br>            <br>            return result.content<br>    <br>    # Return a callable chain object that encapsulates the generation logic<br>    return TracedChain()</pre><p><strong>Internal Flow Breakdown:</strong></p><ul><li><strong>Memory Tool Creation:</strong> The `get_conversation_history` tool acts as a smart proxy to Bedrock AgentCore, handling authentication, filtering, and error recovery automatically.</li><li><strong>Conditional Enhancement:</strong> The system adapts its capabilities based on available services — full memory integration when available, graceful degradation when not.</li><li><strong>Autonomous Memory Access:</strong> The LLM decides when to access memory based on query context, enabling natural conversation flow without explicit memory triggers.</li><li><strong>Distributed Tracing:</strong> Every generation is wrapped in OpenTelemetry spans, providing complete visibility into system behavior and performance characteristics.</li><li><strong>Error Resilience:</strong> Multiple layers of error handling ensure the system continues functioning even when individual components fail.</li></ul><p><strong>3. Workflow Orchestration</strong></p><pre>def create_workflow(self) -&gt; Callable:<br>    &quot;&quot;&quot;Create and configure the workflow graph&quot;&quot;&quot;<br>    workflow = StateGraph(GraphState)<br>    <br>    # Add processing nodes<br>    workflow.add_node(&quot;search_memory&quot;, self.search_memory)<br>    workflow.add_node(&quot;grade_memory&quot;, self.grade_memory)<br>    workflow.add_node(&quot;retrieve&quot;, self.retrieve)<br>    workflow.add_node(&quot;grade_documents&quot;, self.grade_documents)<br>    workflow.add_node(&quot;websearch&quot;, self.web_search)<br>    workflow.add_node(&quot;generate&quot;, self.generate)<br>    <br>    # Set entry point<br>    workflow.set_entry_point(&quot;search_memory&quot;)<br>    <br>    # Define conditional routing<br>    workflow.add_conditional_edges(<br>        &quot;grade_memory&quot;,<br>        self.decide_after_memory,<br>        {<br>            &quot;generate&quot;: &quot;generate&quot;,<br>            &quot;retrieve&quot;: &quot;retrieve&quot;,<br>        },<br>    )<br>    <br>    workflow.add_conditional_edges(<br>        &quot;grade_documents&quot;,<br>        self.decide_to_generate,<br>        {<br>            &quot;websearch&quot;: &quot;websearch&quot;,<br>            &quot;generate&quot;: &quot;generate&quot;,<br>        },<br>    )<br>    <br>    return workflow.compile()</pre><p><strong>LangGraph Agentic AI Framework Integration with Bedrock AgentCore</strong></p><p>The integration between LangGraph and Bedrock AgentCore represents a powerful combination of workflow orchestration and memory management:</p><p><strong>Memory Integration Pattern</strong></p><pre>def initialize_memory(username=None):<br>    &quot;&quot;&quot;Initialize Bedrock AgentCore memory with user-specific sessions&quot;&quot;&quot;<br>    try:<br>        client = MemoryClient(region_name=&quot;us-east-1&quot;)<br>        memory_name = &quot;langgraph_rag&quot;<br>        <br>        memory = client.create_memory_and_wait(<br>            name=memory_name,<br>            description=&quot;LangGraph RAG Assistant Memory&quot;,<br>            strategies=[],<br>            event_expiry_days=7,<br>            max_wait=300,<br>            poll_interval=10<br>        )<br>        <br>        # Generate user-specific identifiers<br>        actor_id = f&quot;user-{username}&quot; if username else f&quot;user-{datetime.now().strftime(&#39;%Y%m%d%H%M%S&#39;)}&quot;<br>        session_id = f&quot;session-{username}-{datetime.now().strftime(&#39;%Y%m%d%H%M%S&#39;)}&quot;<br>        <br>        return client, memory[&#39;id&#39;], actor_id, session_id<br>    except Exception as e:<br>        logger.warning(f&quot;Failed to initialize memory: {str(e)}&quot;)<br>        return None, None, None, None</pre><p><strong>Conversation Persistence</strong></p><pre>def generate(self, state: StateDict) -&gt; StateDict:<br>    &quot;&quot;&quot;Generate answer with automatic memory persistence&quot;&quot;&quot;<br>    question = state[&quot;question&quot;]<br>    documents = state[&quot;documents&quot;]<br>    <br>    # Generate response<br>    generation = self.rag_chain.invoke({&quot;context&quot;: documents, &quot;question&quot;: question})<br>    <br>    # Save conversation to memory<br>    if self.memory_client and self.memory_id and generation.strip():<br>        try:<br>            conversation = [<br>                (question, &quot;USER&quot;),<br>                (generation, &quot;ASSISTANT&quot;)<br>            ]<br>            self.memory_client.create_event(<br>                memory_id=self.memory_id,<br>                actor_id=self.actor_id,<br>                session_id=self.session_id,<br>                messages=conversation<br>            )<br>            logger.info(&quot;Conversation saved to memory&quot;)<br>        except Exception as e:<br>            logger.warning(f&quot;Failed to save conversation: {str(e)}&quot;)<br>    <br>    return {&quot;documents&quot;: documents, &quot;question&quot;: question, &quot;generation&quot;: generation}</pre><p><strong>Importance of Bedrock AgentCore Memory and Observability</strong></p><p><strong>Memory Management Benefits</strong></p><ul><li><strong>Session Continuity:</strong> Maintains context across user sessions</li><li><strong>Personalization:</strong> User-specific conversation history</li><li><strong>Context Awareness: </strong>References previous interactions for better responses</li><li><strong>Scalability: </strong>Managed service handles storage and retrieval</li></ul><p><strong>Observability Implementation</strong></p><pre>from opentelemetry import trace<br>from utils.telemetry import set_session_context, get_session_context<br><br>def traced_rag(inputs):<br>    with tracer.start_as_current_span(&quot;rag_generation&quot;) as span:<br>        question = inputs.get(&quot;question&quot;, &quot;&quot;)<br>        span.set_attribute(&quot;question&quot;, question)<br>        <br>        # Add session context to span<br>        session_ctx = get_session_context()<br>        for key, value in session_ctx.items():<br>            if value:<br>                span.set_attribute(f&quot;session.{key}&quot;, value)<br>        <br>        # Process and trace<br>        result = llm_with_tools.invoke(messages)<br>        span.set_attribute(&quot;generation.length&quot;, len(result.content))<br>        return result.content</pre><p><strong>Telemetry Context Management</strong></p><pre>def set_session_context(session_id, user_id=None, actor_id=None, experiment_id=None):<br>    &quot;&quot;&quot;Set session context for OpenTelemetry tracing&quot;&quot;&quot;<br>    ctx = baggage.set_baggage(&quot;session.id&quot;, session_id)<br>    <br>    if user_id:<br>        ctx = baggage.set_baggage(&quot;user.id&quot;, user_id, context=ctx)<br>    if actor_id:<br>        ctx = baggage.set_baggage(&quot;actor.id&quot;, actor_id, context=ctx)<br>    <br>    return context.attach(ctx)</pre><p><strong>LangGraph Workflow Manager Orchestration</strong></p><p>The workflow manager orchestrates complex decision-making through a series of interconnected nodes:</p><p><strong>Decision Flow Logic</strong></p><pre>def decide_after_memory(self, state: StateDict) -&gt; str:<br>    &quot;&quot;&quot;Intelligent routing based on memory relevance&quot;&quot;&quot;<br>    web_search = state.get(&quot;web_search&quot;, &quot;Yes&quot;)<br>    <br>    if web_search == &quot;Yes&quot;:<br>        logger.info(&quot;Memory not relevant, proceeding to vector search&quot;)<br>        return &quot;retrieve&quot;<br>    else:<br>        logger.info(&quot;Memory is relevant, generating answer&quot;)<br>        return &quot;generate&quot;<br><br>def grade_generation_v_documents_and_question(self, state: StateDict) -&gt; str:<br>    &quot;&quot;&quot;Multi-stage answer validation&quot;&quot;&quot;<br>    question = state[&quot;question&quot;]<br>    generation = state[&quot;generation&quot;]<br>    <br>    # Check usefulness<br>    score = self.answer_grader.invoke({<br>        &quot;question&quot;: question, <br>        &quot;generation&quot;: generation<br>    })<br>    <br>    usefulness_grade = score.get(&#39;score&#39;, &#39;&#39;).lower()<br>    <br>    if usefulness_grade == &quot;yes&quot;:<br>        return &quot;useful&quot;<br>    else:<br>        return &quot;not useful&quot;</pre><p><strong>Quality Assurance Pipeline</strong></p><pre>def create_retrieval_grader(llm):<br>    &quot;&quot;&quot;Document relevance assessment&quot;&quot;&quot;<br>    prompt = PromptTemplate(<br>        template=&quot;&quot;&quot;You are a grader assessing relevance of a retrieved document <br>        to a user question. Give a binary score &#39;yes&#39; or &#39;no&#39; to indicate whether <br>        the document is relevant to the question.&quot;&quot;&quot;,<br>        input_variables=[&quot;question&quot;, &quot;document&quot;],<br>    )<br>    return prompt | llm | JsonOutputParser()<br><br>def create_hallucination_grader(llm):<br>    &quot;&quot;&quot;Factual grounding validation&quot;&quot;&quot;<br>    prompt = PromptTemplate(<br>        template=&quot;&quot;&quot;You are a grader assessing whether an answer is grounded in <br>        a set of facts. Give a binary &#39;yes&#39; or &#39;no&#39; score to indicate whether <br>        the answer is grounded in the provided facts.&quot;&quot;&quot;,<br>        input_variables=[&quot;generation&quot;, &quot;documents&quot;],<br>    )<br>    return prompt | llm | JsonOutputParser()</pre><p><strong>Security: Cognito Integration and IAM Policies</strong></p><p><strong>Authentication Handler</strong></p><pre>class AuthHandler:<br>    def __init__(self, credentials):<br>        self.cognito_client = boto3.client(<br>            &#39;cognito-idp&#39;,<br>            aws_access_key_id=credentials[&#39;aws_access_key_id&#39;],<br>            aws_secret_access_key=credentials[&#39;aws_secret_access_key&#39;],<br>            region_name=credentials[&#39;region_name&#39;]<br>        )<br>        self.user_pool_id = credentials[&#39;cognito&#39;][&#39;user_pool_id&#39;]<br>        self.client_id = credentials[&#39;cognito&#39;][&#39;client_id&#39;]<br><br>    def sign_in(self, username, password):<br>        try:<br>            auth_response = self.cognito_client.initiate_auth(<br>                ClientId=self.client_id,<br>                AuthFlow=&#39;USER_PASSWORD_AUTH&#39;,<br>                AuthParameters={<br>                    &#39;USERNAME&#39;: username,<br>                    &#39;PASSWORD&#39;: password<br>                }<br>            )<br>            <br>            auth_result = auth_response[&#39;AuthenticationResult&#39;]<br>            return {<br>                &#39;success&#39;: True,<br>                &#39;token&#39;: auth_result[&#39;IdToken&#39;],<br>                &#39;access_token&#39;: auth_result[&#39;AccessToken&#39;],<br>                &#39;refresh_token&#39;: auth_result[&#39;RefreshToken&#39;]<br>            }<br>        except Exception as e:<br>            return {&#39;success&#39;: False, &#39;message&#39;: str(e)}</pre><p><strong>IAM Policy for Bedrock Access</strong></p><pre>{<br>    &quot;Version&quot;: &quot;2012-10-17&quot;,<br>    &quot;Statement&quot;: [<br>        {<br>            &quot;Effect&quot;: &quot;Allow&quot;,<br>            &quot;Action&quot;: [<br>                &quot;bedrock:InvokeModel&quot;,<br>                &quot;bedrock:InvokeModelWithResponseStream&quot;<br>            ],<br>            &quot;Resource&quot;: [<br>                &quot;arn:aws:bedrock:*::foundation-model/anthropic.claude-3-haiku-20240307-v1:0&quot;,<br>                &quot;arn:aws:bedrock:*::foundation-model/amazon.titan-embed-text-v1&quot;<br>            ]<br>        },<br>        {<br>            &quot;Effect&quot;: &quot;Allow&quot;,<br>            &quot;Action&quot;: [<br>                &quot;bedrock-agent:CreateMemory&quot;,<br>                &quot;bedrock-agent:GetMemory&quot;,<br>                &quot;bedrock-agent:ListMemories&quot;,<br>                &quot;bedrock-agent:CreateEvent&quot;,<br>                &quot;bedrock-agent:ListEvents&quot;<br>            ],<br>            &quot;Resource&quot;: &quot;*&quot;<br>        }<br>    ]<br>}</pre><p><strong>Industrial Use Cases and Extensions</strong></p><p><strong>Real-World Applications Explained:</strong></p><p>This isn’t just a technical demo — it’s a foundation for solving real business problems. Here are four practical ways organizations can use this technology:</p><ol><li><strong>Customer Support Automation</strong></li></ol><p>What This Means for Business:</p><p>Imagine having a customer service representative who:</p><ul><li>Never sleeps (24/7 availability)</li><li>Remembers every customer interaction-</li><li>Knows when to escalate complex issues to humans</li><li>Provides consistent, accurate answers based on company knowledge</li><li>Automatically creates support tickets for follow-up</li></ul><p><strong>Benefits:</strong></p><ul><li>24/7 availability with intelligent escalation</li><li>Consistent responses based on company knowledge</li><li>Automatic ticket creation for complex issues</li><li>Integration with existing CRM systems</li></ul><p><strong>2. Technical Documentation Assistant</strong></p><p>What This Means for Business:</p><p>For software companies and IT departments, this creates an intelligent assistant that:</p><ul><li>Understands code snippets and technical questions</li><li>Provides API documentation and integration guidance</li><li>Offers troubleshooting help based on error messages</li><li>Suggests best practices and coding standards</li><li>Reduces the burden on senior developers for routine questions</li></ul><p>Use Cases:</p><ul><li>API documentation queries</li><li>Code troubleshooting assistance</li><li>Integration guidance</li><li>Best practices recommendations</li></ul><p><strong>3. Compliance and Regulatory Assistant</strong></p><p>What This Means for Business:</p><p>For regulated industries (finance, healthcare, legal), this provides:</p><ul><li>Automatic compliance checking for all responses</li><li>Audit trails for regulatory requirements</li><li>Risk assessment integration</li><li>Policy adherence validation</li><li>Consistent, compliant communication across the organization</li></ul><p>Features:</p><ul><li>Regulatory compliance validation</li><li>Audit trail maintenance</li><li>Risk assessment integration</li><li>Policy adherence checking</li></ul><p><strong>4. Multi-Language Enterprise Assistant</strong></p><p>What This Means for Business:</p><p>For global organizations, this enables:</p><ul><li>Seamless communication across language barriers</li><li>Consistent information delivery in multiple languages</li><li>Cultural context awareness</li><li>Global knowledge sharing</li><li>Reduced need for language-specific support teams</li></ul><p><strong>Performance Optimization and Scaling</strong></p><p>Performance Considerations:</p><p>The system is designed with enterprise-scale performance in mind:</p><ul><li>Efficient Chunking: 512-character chunks for optimal context</li><li>State Management: Structured data flow through workflow</li><li>Error Handling: Comprehensive exception management</li><li>Async Processing: Non-blocking operations where possible</li></ul><p>Scaling Strategies:</p><ul><li>Caching: Frequent queries and document retrievals can be cached</li><li>Load Balancing: Multiple workflow instances for high availability</li><li>Database Optimization: Vector database indexing and partitioning</li><li>Memory Management: Efficient cleanup and resource management</li></ul><p><strong>Monitoring and Observability</strong></p><p>Built-in Observability Features:</p><ul><li>OpenTelemetry Integration: Distributed tracing across all components</li><li>Structured Logging: Comprehensive error tracking and debugging</li><li>Performance Metrics: Response times, success rates, and resource usage</li><li>Health Checks: System component status monitoring</li><li>User Analytics: Conversation patterns and usage statistics</li></ul><p><strong>Conclusion</strong></p><p>This enterprise-grade RAG chatbot demonstrates the powerful synergy between LangGraph’s agentic framework and AWS Bedrock AgentCore. The solution addresses critical enterprise requirements while remaining accessible to both technical and non-technical stakeholders.</p><p><strong>Technical Excellence:</strong></p><ul><li><strong>Intelligent Routing:</strong> Like a smart librarian who knows exactly where to find information — whether in memory, local files, or the internet</li><li><strong>Quality Assurance:</strong> Multiple checkpoints ensure answers are accurate, relevant, and helpful — like having several editors review an article before publication</li><li><strong>Memory Management:</strong> Conversations are remembered across sessions, enabling natural, contextual interactions</li><li><strong>Observability:</strong> Complete visibility into system performance and user interactions for continuous improvement</li></ul><p><strong>Enterprise Readiness:</strong></p><ul><li><strong>Security:</strong> Bank-level security with AWS Cognito authentication and fine-grained access controls</li><li><strong>Scalability:</strong> Designed to handle thousands of concurrent users with efficient resource management</li><li><strong>Compliance:</strong> Built-in audit trails and regulatory compliance features for enterprise governance</li><li><strong>Multi-tenancy:</strong> Each user gets personalized experiences while maintaining data isolation</li></ul><p><strong>Industrial Applications:</strong></p><p>The framework’s flexibility enables diverse use cases:</p><ul><li><strong>Customer Support:</strong> 24/7 intelligent assistance with human escalation</li><li><strong>Technical Documentation:</strong> Code-aware assistance for developers</li><li><strong>Compliance Monitoring: </strong>Regulatory-compliant responses with audit trails</li></ul><p><strong>Future Enhancements:</strong></p><ul><li>Integration with enterprise knowledge graphs for deeper organizational intelligence</li><li>Advanced reasoning capabilities with multi-agent collaboration</li><li>Real-time learning from user feedback and interaction patterns</li><li>Integration with business intelligence systems for data-driven insights</li></ul><p><strong>Project Repository: </strong>To be added</p><p>This implementation showcases how modern AI frameworks can be combined with cloud-native services to create production-ready, enterprise-grade intelligent systems that deliver real business value while maintaining the highest standards of security, reliability, and observability.</p><p><strong>References and Documentation</strong></p><p><strong>Core Technologies</strong></p><ul><li>LangGraph Documentation: <a href="https://langchain-ai.github.io/langgraph/">https://langchain-ai.github.io/langgraph/</a></li><li>LangChain Documentation: <a href="https://python.langchain.com/docs/get_started/introduction">https://python.langchain.com/docs/get_started/introduction</a></li><li>AWS Bedrock Documentation: <a href="https://docs.aws.amazon.com/bedrock/">https://docs.aws.amazon.com/bedrock/</a></li><li>AWS Bedrock AgentCore Memory: <a href="https://docs.aws.amazon.com/bedrock/latest/userguide/agents-memory.html">https://docs.aws.amazon.com/bedrock/latest/userguide/agents-memory.html</a></li></ul><p><strong>Vector Database and Embeddings</strong></p><ul><li>ChromaDB Documentation: <a href="https://docs.trychroma.com/">https://docs.trychroma.com/</a></li><li>Amazon Titan Embeddings: <a href="https://docs.aws.amazon.com/bedrock/latest/userguide/titan-embedding-models.html">https://docs.aws.amazon.com/bedrock/latest/userguide/titan-embedding-models.html</a></li></ul><p><strong>Observability and Monitoring</strong></p><ul><li>OpenTelemetry Documentation: <a href="https://opentelemetry.io/docs/">https://opentelemetry.io/docs/</a></li><li>AWS Bedrock Observability: <a href="https://docs.aws.amazon.com/bedrock/latest/userguide/monitoring-overview.html">https://docs.aws.amazon.com/bedrock/latest/userguide/monitoring-overview.html</a></li></ul><p><strong>Security and Authentication</strong></p><ul><li>AWS Cognito Documentation: <a href="https://docs.aws.amazon.com/cognito/">https://docs.aws.amazon.com/cognito/</a></li><li>AWS IAM Best Practices: <a href="https://docs.aws.amazon.com/IAM/latest/UserGuide/best-practices.html">https://docs.aws.amazon.com/IAM/latest/UserGuide/best-practices.html</a></li></ul><p><strong>Additional Resources</strong></p><ul><li>Streamlit Documentation: <a href="https://docs.streamlit.io/">https://docs.streamlit.io/</a></li><li>Anthropic Claude Models: <a href="https://docs.anthropic.com/claude/docs">https://docs.anthropic.com/claude/docs</a></li><li>Tavily Search API: <a href="https://tavily.com/">https://tavily.com/</a></li></ul><p><strong>Research Papers and Articles</strong></p><ul><li>Retrieval-Augmented Generation: <a href="https://arxiv.org/abs/2005.11401">https://arxiv.org/abs/2005.11401</a></li><li>LangGraph: Multi-Agent Workflows: <a href="https://blog.langchain.dev/langgraph-multi-agent-workflows/">https://blog.langchain.dev/langgraph-multi-agent-workflows/</a></li><li>AWS Bedrock AgentCore: <a href="https://aws.amazon.com/blogs/machine-learning/build-generative-ai-agents-with-amazon-bedrock-agents/">https://aws.amazon.com/blogs/machine-learning/build-generative-ai-agents-with-amazon-bedrock-agents/</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=69789499f56e" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>