<?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 Wael SAIDENI on Medium]]></title>
        <description><![CDATA[Stories by Wael SAIDENI on Medium]]></description>
        <link>https://medium.com/@wael-saideni?source=rss-f849de33d418------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*V42ZXshvfFBEGJdP-EzHJw.jpeg</url>
            <title>Stories by Wael SAIDENI on Medium</title>
            <link>https://medium.com/@wael-saideni?source=rss-f849de33d418------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 10:31:26 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@wael-saideni/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[AgentOps in Practice on AWS: What Everyone Skips Until Their Agent Breaks in Prod]]></title>
            <link>https://medium.com/@wael-saideni/agentops-in-practice-on-aws-what-everyone-skips-until-their-agent-breaks-in-prod-d2ef61c5545a?source=rss-f849de33d418------2</link>
            <guid isPermaLink="false">https://medium.com/p/d2ef61c5545a</guid>
            <category><![CDATA[agentic-ai]]></category>
            <category><![CDATA[agentops]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[amazon-bedrock-agentcore]]></category>
            <category><![CDATA[ai-architecture]]></category>
            <dc:creator><![CDATA[Wael SAIDENI]]></dc:creator>
            <pubDate>Wed, 02 Sep 2026 09:01:17 GMT</pubDate>
            <atom:updated>2026-09-02T09:01:17.104Z</atom:updated>
            <content:encoded><![CDATA[<h4>Building Enterprise-Grade Autonomous Systems That Are Observable, Governable, and Continuously Improving</h4><p><strong>Table of Contents</strong></p><ul><li>The Operations Gap</li><li>8 Design Principles</li><li>The 4 Pillars of AgentOps</li><li>Team Structure and Responsibilities</li><li>Implementation Roadmap</li><li>Conclusion</li></ul><h3>The Operations Gap</h3><p>Over the past eighteen months, building AI agents has become trivial. Modern frameworks: LangGraph, CrewAI, AutoGen, Amazon Bedrock AgentCore, let teams assemble multi-agent workflows in hours. Deploying those same agents into production remains anything but trivial.</p><p>Traditional software exhibits predictable behavior: structured input flows through deterministic business logic to produce consistent output. Teams know exactly what should happen and can test for it comprehensively.</p><p>The execution path is different every time. This non-determinism creates entirely new operational questions:</p><ul><li><em>Why did the agent select this tool instead of that one?</em></li><li><em>Which memory configuration caused this hallucination?</em></li><li><em>Why did yesterday’s execution cost half as much as today’s?</em></li><li><em>Which prompt version generated this problematic response?</em></li><li><em>Can we safely roll back a single agent without disrupting dependent workflows?</em></li></ul><p>These questions expose the gaps in traditional DevOps and MLOps practices. Those disciplines optimize infrastructure reliability and ML model performance. Neither addresses the autonomous decision-making, statefulness, and probabilistic behavior that defines agentic systems.</p><p><strong>AgentOps</strong> emerges as the operational discipline specifically designed for autonomous AI systems. It extends DevOps and MLOps by providing architectural patterns, governance frameworks, and observability practices that treat agents as first-class production concerns, not experimental features or API endpoints.</p><p>The architecture below illustrates how these concerns come together in practice. It maps the four foundational pillars of AgentOps, Governance &amp; Security, Build &amp; Operations, Evaluation, and Observability, onto a concrete AWS implementation, showing how isolated agents, versioned artifacts, structured memory, continuous evaluation, and feedback loops form a cohesive operational platform.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7r9pAoXV80RSmCRLfCf60w.png" /><figcaption><strong>AgentOps Reference Architecture for Enterprise Agentic Systems</strong></figcaption></figure><p>The diagram below illustrates the end-to-end AgentOps architecture that underpins the rest of this article. At its core, it shows how agents are deployed as isolated microservices: each with its own runtime, memory, evaluation suite, and telemetry, while being governed by a shared platform layer. The four foundational pillars (Governance &amp; Security, Build &amp; Operations, Evaluation, and Observability) form a continuous feedback loop: production telemetry feeds back into governance decisions, evaluation refinements, and build optimizations. Key additions to a traditional cloud architecture include structured memory (short-term, long-term user, organizational, and operational), reasoning traces for explainability, continuous evaluation at four levels (component, conversation, session, system), cost engineering as a first-class metric, and policy-based governance via Cedar and Bedrock Guardrails that remains invisible to developers. The subsequent sections explore each layer of this architecture in depth.</p><h3>8 Design Principles for Production Agentic Systems</h3><h3>Design Principle 1: Everything Becomes a Deployable Artifact</h3><p>The most dangerous mistake organizations make is treating prompts as configuration files, modifiable through web interfaces without versioning, testing, or deployment approval.</p><p>In reality, nearly every component of a production agent system changes independently and should be versioned:</p><ul><li><strong>Prompts</strong> (system instructions, few-shot examples)</li><li><strong>Agent orchestration graphs</strong> (agentic workflows, decision trees)</li><li><strong>Tool registries</strong> (available tools, capabilities)</li><li><strong>MCP server configurations</strong> (Model Context Protocol definitions)</li><li><strong>Memory schemas</strong> (extraction strategies, TTLs, namespaces)</li><li><strong>Evaluation datasets</strong> (ground truth test cases)</li><li><strong>Guardrails policies</strong> (safety rules, compliance controls)</li><li><strong>Model routing rules</strong> (which model for which request type)</li><li><strong>Runtime infrastructure</strong> (container images, dependencies)</li></ul><p>Think of a production agent as a software package with dependencies, versioning, and release management, not as a configuration layer on top of infrastructure.</p><p><strong>Example artifact structure:</strong></p><p>customer-support-agent/<br>├── v2.3.1/<br>│ ├── prompts/<br>│ │ ├── system.md (v12)<br>│ │ └── few_shot_examples.json (v8)<br>│ ├── tools_registry.yaml (v5)<br>│ ├── memory_config.yaml (v3)<br>│ ├── evaluation_dataset.json (v7)<br>│ ├── guardrails_policies.yaml (v4)<br>│ ├── Dockerfile (hash-based versioning)<br>│ └── deployment.manifest</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Etba0SNRX3VY65DmiGCqEA.png" /><figcaption><strong>Artifact Versioning &amp; Release Pipeline</strong></figcaption></figure><p><strong>Why this matters:</strong> When a customer reports an issue six months after deployment, you can reproduce the exact system configuration that generated that response (prompts, tools, memory state, guardrails, etc) enabling forensic analysis and preventing regressions.</p><h3>Design Principle 2: Separate Platform Teams from Agent Teams</h3><p>A common anti-pattern places all code (infrastructure, shared frameworks, agents, prompts, evaluation logic) in a single monolithic repository. This creates dependency hell: a platform engineer’s infrastructure change risks breaking an agent team’s workflow; a guardrails update requires coordinating across the entire organization.</p><p>Instead, separate concerns:</p><p><strong>Platform Team Owns:</strong></p><ul><li>Core infrastructure (VPCs, security groups, account structure)</li><li>Shared services (API Gateway, observability, identity management)</li><li>Bedrock configuration (model access, guardrails, memory resources)</li><li>MCP server runtime (shared tool ecosystem)</li><li>CI/CD framework (deployment pipelines, approval workflows)</li><li>Guardrails policies (organization-wide safety controls)</li></ul><p><strong>Agent/Application Teams Own:</strong></p><ul><li>Agent implementations (reasoning logic, orchestration)</li><li>Prompts and instruction sets</li><li>Application-specific memory configurations</li><li>Tool orchestration (which tools call which other tools)</li><li>Evaluation frameworks and test datasets</li><li>Agent-specific guardrails overrides (within platform guardrails)</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ayX--rQf_KISlHgHz14QZQ.png" /><figcaption><strong>Team Boundary &amp; Ownership Map</strong></figcaption></figure><p>This separation enables platform teams to evolve shared capabilities on their own schedule while agent teams iterate rapidly without impacting each other.</p><h3>Design Principle 3: Treat Each Agent Like an Independent Microservice</h3><p>Rather than consolidating multiple agents into a single runtime:</p><p><strong>Anti-pattern:</strong></p><pre>Single AgentCore Runtime<br>├── Agent A (Customer Support)<br>├── Agent B (Claims Processing)<br>├── Agent C (Fraud Detection)<br>└── Agent D (Document Classification)</pre><p><strong>Preferred pattern:</strong></p><pre>Runtime A (Customer Support Agent)<br>   └─ Independent deployment, scaling, memory, permissions<br><br>Runtime B (Claims Processing Agent)<br>   └─ Independent deployment, scaling, memory, permissions<br><br>Runtime C (Fraud Detection Agent)<br>   └─ Independent deployment, scaling, memory, permissions<br><br>Runtime D (Document Classification Agent)<br>   └─ Independent deployment, scaling, memory, permissions</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*faOVVIkoKLRTcM4nDJEUSA.png" /><figcaption><strong>Microservice Isolation Model</strong></figcaption></figure><p>Each agent should own:</p><ul><li>Its own <strong>deployment pipeline</strong> (independent CI/CD)</li><li>Its own <strong>runtime</strong> (separate AgentCore Runtime instance or container)</li><li>Its own <strong>evaluation pipeline</strong> (testing harness)</li><li>Its own <strong>telemetry and tracing</strong> (dedicated observability)</li><li>Its own <strong>memory resources</strong> (isolated data)</li><li>Its own <strong>IAM roles and permissions</strong> (least privilege)</li></ul><p>This isolation dramatically simplifies:</p><ul><li><strong>Debugging:</strong> Issues in Agent A don’t mask problems in Agent B</li><li><strong>Scaling:</strong> A spike in customer support requests doesn’t starve fraud detection</li><li><strong>Rollback:</strong> Promoting a new version of Agent B doesn’t touch Agents A, C, or D</li><li><strong>Cost allocation:</strong> Each team sees true operational costs</li><li><strong>Security:</strong> Compromised tool access in one agent doesn’t cascade to others</li></ul><h3>Design Principle 4: Memory Is Infrastructure, Not a Vector Database</h3><p>Teams often treat memory as a thin wrapper around a vector database, storing and retrieving embeddings. Enterprise systems should think structurally about what agents remember and why.</p><p>There are <strong>four distinct memory categories</strong>, each with different requirements:</p><p><strong>1. Short-Term Memory</strong></p><ul><li>Content: Current conversation context, immediate reasoning state</li><li>Lifetime: Session-scoped (usually minutes to hours)</li><li>Retention: Auto-expire after session</li><li>Encryption: Standard (application-level)</li><li>Owner: Runtime manages automatically</li></ul><p><strong>2. Long-Term User Memory</strong></p><ul><li>Content: Individual user preferences, interaction patterns, account-specific context</li><li>Lifetime: Persistent (days, months)</li><li>Retention: User-scoped (delete on user account closure)</li><li>Encryption: Per-user encryption keys if handling sensitive preferences</li><li>Owner: User/agent pair</li></ul><p><strong>3. Organizational Memory</strong></p><ul><li>Content: Shared knowledge, policies, documentation, procedures</li><li>Lifetime: Persistent (applies across users)</li><li>Retention: Governed by policy (e.g., 2-year regulatory hold)</li><li>Encryption: Organizational-level encryption</li><li>Owner: Knowledge management team</li></ul><p><strong>4. Operational Memory</strong></p><ul><li>Content: Agent execution history, failures, past decisions, tool outputs</li><li>Lifetime: Audit-scoped (regulatory retention)</li><li>Retention: depending on regulations</li><li>Encryption: Sensitive audit data encryption</li><li>Owner: Operations/compliance team</li></ul><p>Each category should have:</p><ul><li>Independent <strong>retention policies</strong> (TTLs)</li><li>Separate <strong>encryption strategies</strong> (key management)</li><li>Distinct <strong>access controls</strong> (who can read/write)</li><li>Clear <strong>ownership</strong> (who maintains it)</li><li>Dedicated <strong>infrastructure</strong> (not commingled)</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Jyepk4QwXuBsErMVl3Nu4Q.png" /><figcaption><strong>Memory Taxonomy Matrix</strong></figcaption></figure><p>Using AWS services like <strong>Amazon Bedrock AgentCore Memory</strong> with strategies, namespaces, and IAM policies gives you this structural separation without building custom systems.</p><h3>Design Principle 5: Observability Starts with Reasoning Traces</h3><p>Traditional logging captures <em>what happened</em>: “Tool X called, returned value Y, agent produced response Z.”</p><p>Agent observability must explain <em>why it happened</em>: “The agent reasoned that task required tool X (not Y) because the user question mentioned [context], the previous memory indicated [pattern], and the available tools were [options].”</p><p>A complete execution trace should capture:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*I_l-bhEs3wtVYoN7RhUoZQ.png" /><figcaption><strong>Reasoning Trace Chain</strong></figcaption></figure><p>Modern observability platforms should correlate across:</p><ul><li><strong>Prompt versions</strong> (which instruction set was active?)</li><li><strong>Tool invocations</strong> (which tool, with which parameters, what latency?)</li><li><strong>Token usage</strong> (input/output tokens, cost implications)</li><li><strong>Latency</strong> (end-to-end, per step, per LLM call)</li><li><strong>Retrieved documents</strong> (which knowledge base chunks influenced the decision?)</li><li><strong>Reasoning steps</strong> (the agent’s internal monologue)</li><li><strong>Memory operations</strong> (what was retrieved, what was stored?)</li><li><strong>Business metrics</strong> (did the customer get what they needed?)</li></ul><p><strong>OpenTelemetry</strong> is your foundation here. It provides a vendor-neutral tracing model that connects:</p><ul><li>LLM framework instrumentation (LangGraph, CrewAI spans)</li><li>Bedrock AgentCore service metrics (Memory operations, Gateway routing)</li><li>Infrastructure metrics (container CPU, network)</li><li>Application metrics (business logic)</li></ul><p>All within a single, causally-linked trace ID.</p><h3>Design Principle 6: Evaluation Is Continuous, Not a Release Gate</h3><p>Traditional software testing validates deterministic behavior: “Given input X, the system must always produce output Y.”</p><p>Agent evaluation measures probabilistic quality at multiple levels:</p><p><strong>1. Component Evaluation</strong></p><ul><li><em>Retrieval system:</em> Does the RAG pipeline retrieve relevant documents?</li><li><em>Tool execution:</em> Does the tool produce expected output?</li><li><em>Memory extraction:</em> Are important facts captured for future reference?</li></ul><p><strong>2. Agent Evaluation</strong></p><ul><li><em>Tool selection accuracy:</em> Did the agent choose the right tool?</li><li><em>Parameter extraction:</em> Did the agent parse user intent correctly?</li><li><em>Reasoning coherence:</em> Is the reasoning chain logical?</li></ul><p><strong>3. Workflow Evaluation</strong></p><ul><li><em>Multi-step task success:</em> Did the complete workflow accomplish the user’s goal?</li><li><em>Handoff accuracy:</em> In multi-agent systems, did requests route correctly?</li></ul><p><strong>4. Production Evaluation</strong></p><ul><li><em>User satisfaction:</em> Are users happier with agent responses?</li><li><em>Quality drift:</em> Has performance degraded since deployment?</li><li><em>Cost efficiency:</em> Did actual costs match projections?</li><li><em>Latency:</em> Are response times acceptable?</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vB_A5J7rxJhbDt_HdHeGzQ.png" /><figcaption><strong>Evaluation Levels Pyramid</strong></figcaption></figure><p>Evaluation runs in <strong>two modes</strong>:</p><p><strong>On-Demand Evaluation</strong> (Development → Pre-Prod)</p><ul><li>Trigger: Manual during development, automated before release</li><li>Coverage: Targeted spans, traces, sessions</li><li>Purpose: Rapid iteration, quality gates</li><li>Tools: LLM-as-Judge, human review queues</li></ul><p><strong>Online Evaluation</strong> (Production)</p><ul><li>Trigger: Continuous sampling of live traffic</li><li>Coverage: Configurable sampling rate (1% to 100%)</li><li>Purpose: Drift detection, quality monitoring</li><li>Tools: CloudWatch dashboards, anomaly detection</li></ul><p>Production evaluation is critical because user behavior evolves: prompts that performed well during development often degrade as data changes, new tools appear, or models receive updates.</p><h3>Design Principle 7: Governance Should Be Invisible to Developers</h3><p>Developers should never need to think about security. Instead, governance should be embedded into the platform, enforced automatically, transparently.</p><p>Examples of platform-embedded governance:</p><ul><li><strong>Centralized identity:</strong> All agents authenticate via AgentCore Identity for example; developers don’t manage credentials</li><li><strong>Policy-based authorization:</strong> Tool access governed by Cedar policies; developers write tools, platform enforces access</li><li><strong>Tool allowlists:</strong> Platform restricts which tools agents can invoke; developers can’t accidentally call unapproved external APIs</li><li><strong>Prompt scanning:</strong> Incoming user prompts scanned for jailbreak attempts before reaching the agent</li><li><strong>PII detection:</strong> Model responses checked for personal identifiable information; flagged if found</li><li><strong>Model routing:</strong> Sensitive requests routed to higher-capability (restricted-access) models; handled automatically</li><li><strong>Approval workflows:</strong> Changes to guardrails, memory schemas, tool access require approval; baked into CI/CD</li><li><strong>Human-in-the-loop escalation:</strong> Uncertain decisions automatically escalated to humans; no developer code needed</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dz5Lk28kgkO3AuXC7tQLHw.png" /><figcaption><strong>Governance as Platform Layer</strong></figcaption></figure><p>AWS services and features that enable this include <strong>IAM</strong> (centralized identity), <strong>Bedrock Guardrails</strong> (safety policies), <strong>AgentCore Identity and Policy</strong> (agent-level access control), and <strong>Verified Permissions</strong> (Cedar policy evaluation).</p><p>The key principle: Security decisions are made once by security teams, expressed as policies, and enforced uniformly by the platform, not reimplemented by each agent team.</p><h3>Design Principle 8: Cost Becomes an Engineering Metric</h3><p>Traditional systems optimize CPU utilization and memory efficiency. Agentic systems optimize:</p><ul><li><strong>Token usage</strong> (LLM calls are expensive; fewer tokens = lower cost)</li><li><strong>Model selection</strong> (for example: Nova vs. Claude vs. local model; right tool for task)</li><li><strong>Tool latency</strong> (faster tool execution = fewer retries)</li><li><strong>Retrieval efficiency</strong> (fewer vector DB calls = lower cost)</li><li><strong>Context window management</strong> (shorter prompts = lower token cost)</li><li><strong>Cache hit ratio</strong> (prompt caching reduces redundant tokens)</li></ul><p>A single poorly-written prompt can double inference costs. A suboptimal retrieval strategy might make queries 10x more expensive than necessary.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iF1zP31MTMvFAev0a2K89w.png" /><figcaption><strong>Cost Engineering Breakdown</strong></figcaption></figure><p>Engineering teams need dashboards showing:</p><ul><li><strong>Cost per session</strong> (total inference + tool costs)</li><li><strong>Cost per workflow</strong> (multi-step tasks cost breakdown)</li><li><strong>Cost per customer</strong> (which customers drive costs?)</li><li><strong>Cost per tool</strong> (external API costs, vector DB costs)</li><li><strong>Token distribution</strong> (which prompts consume most tokens?)</li><li><strong>Expensive execution paths</strong> (identify cost anomalies)</li></ul><p>Cost optimization becomes an ongoing engineering discipline alongside performance optimization — not a finance exercise after the fact.</p><h3>The Four Pillars of AgentOps</h3><p>Production agentic systems rest on four foundational pillars. They are <strong>not sequential,</strong> they develop concurrently throughout the system lifecycle.</p><h3>Pillar 1: Governance &amp; Security</h3><p>Agents operate on behalf of users but not every user should trigger every tool. A user with limited permissions triggers an agent — that agent must inherit those restrictions. When Agent A calls Agent B, authorization becomes ambiguous: what can Agent B do on behalf of the original user?</p><p><strong>Governance challenges that don’t exist in traditional software:</strong></p><ul><li><em>Agent-to-agent authentication:</em> When an agent delegates to another, how do permissions propagate?</li><li><em>Tool access isolation:</em> Which tools can which agents invoke with which parameters?</li><li><em>Memory access boundaries:</em> Which agents can read/write which memory namespaces?</li><li><em>Cross-account authorization:</em> In multi-account deployments, how do agents authenticate across boundaries?</li></ul><h3>Governance Implementation Actions</h3><p><strong>1. Multi-Account Architecture (Foundation)</strong></p><ul><li>Create separate AWS accounts for: Shared Services (central ECR, Secrets Manager, observability), Development, Pre-Production, Production</li><li>Use Service Control Policies (SCPs) to enforce org-wide guardrails (never allow root access, require MFA, enforce encryption)</li><li>Tag every resource with: Owner, Cost Center, Use Case ID, Environment</li><li>Delegate account management to teams via AWS Organizations</li></ul><p><strong>AWS Actions:</strong></p><pre>1. Create AWS Organization structure<br>2. Implement SCPs at organization root<br>3. Create cross-account roles for deployment pipelines<br>4. Enable AWS CloudTrail in all accounts</pre><p><strong>2. Identity and Access Control</strong></p><ul><li>Implement <strong>AgentCore Identity</strong> for agent-to-agent authentication</li><li>Use <strong>IAM roles</strong> for agent runtime permissions (least privilege)</li><li>Implement <strong>Cedar policies</strong> (AWS Verified Permissions) for deterministic, auditable access decisions</li><li>Enable <strong>CloudTrail logging</strong> for comprehensive audit trails</li></ul><p><strong>AWS Actions:</strong></p><pre>1. Create IAM roles per agent with minimum required permissions<br>2. Configure AgentCore Identity for cross-agent authentication<br>3. Define Cedar policies for tool access (e.g., &quot;agent X can only call tool Y with parameter Z &lt; $1000&quot;)<br>4. Set up CloudTrail log aggregation in shared services account</pre><p><strong>3. Model and Data Governance</strong></p><ul><li>Control which models agents can access using <strong>SCPs and IAM policies</strong></li><li>Implement <strong>Bedrock Guardrails</strong> to scan prompts and responses</li><li>Use <strong>Bedrock Guardrails</strong> to enforce PII redaction, toxicity filters, topic controls</li><li>Centralize model access via a <strong>generative AI gateway</strong> (LiteLLM, Bedrock)</li></ul><p><strong>AWS Actions:</strong></p><pre>1. Create IAM policies limiting model access by agent<br>2. Define Bedrock Guardrails policies (PII, toxicity, custom rules)<br>3. Deploy generative AI gateway with rate limiting and cost controls<br>4. Configure guardrails in pipeline as code (version controlled)</pre><p><strong>4. Memory and Tool Governance</strong></p><ul><li>Organize memory using <strong>AgentCore Memory namespaces</strong> (per-user, per-organization, per-agent)</li><li>Control memory access via <strong>IAM policies</strong> (which agents can read/write which namespaces)</li><li>Gate tool access through <strong>AgentCore Gateway</strong> with policy evaluation</li><li>Implement deterministic policies using <strong>Cedar</strong> for authorization (e.g., “can only approve claims &lt; $5M”)</li></ul><p><strong>AWS Actions:</strong></p><pre>1. Define memory namespace hierarchy (actor-level, session-level, organizational-level)<br>2. Create IAM policies for memory namespace access<br>3. Register tools in AgentCore Gateway with authentication methods<br>4. Write Cedar policies for tool parameter validation</pre><h3>Pillar 2: Build &amp; Operations</h3><p>Agents depend on infrastructure, tools, prompts, memory configurations, and models that change independently. Without operational discipline, a tool update from another team breaks your agent; a memory misconfiguration inadvertently exposes user context.</p><p><strong>Build &amp; Operations treats every component as a versioned, deployable artifact with its own repository, CI/CD, and ownership:</strong></p><pre>Infrastructure Repository<br>├── Account setup, networking, IAM roles<br>├── AgentCore Runtime configuration<br>├── Memory, Gateway, Identity setup<br>└── Shared MCP servers<br><br>Agent Repository<br>├── Agent orchestration logic<br>├── Prompt templates<br>├── Memory extraction strategies<br>├── Evaluation frameworks<br>└── Agent-specific guardrails<br><br>Tool Repository<br>├── Custom tool implementations<br>├── Tool MCP manifests<br>├── Tool-specific tests<br>└── Tool CI/CD pipeline<br><br>Application Repository<br>├── Business logic using agents<br>├── UI/API endpoints<br>├── Application-specific telemetry<br>└── Application CI/CD pipeline</pre><h3>Build &amp; Operations Implementation Actions</h3><p><strong>1. Repository Structure and Separation</strong></p><ul><li>Create <strong>separate repositories</strong> for infrastructure, agents, tools, and applications</li><li>Each repository has <strong>independent versioning</strong> (semantic versioning: major.minor.patch)</li><li>Each repository has <strong>independent CI/CD pipelines</strong> (deploy independently)</li><li>Shared modules (guardrails, evaluation frameworks) in <strong>separate shared repository</strong></li></ul><p><strong>AWS Actions:</strong></p><pre>1. Create AWS CodeCommit repositories (or link GitHub)<br>2. Set up branch protection rules (require PR reviews before merge)<br>3. Configure repository tags for release management<br>4. Set up cross-account deployment roles in each repository</pre><p><strong>2. CI/CD Pipelines for Agents</strong></p><p>Agent deployment pipeline structure:</p><pre>Developer commits → Trigger CI Pipeline<br>  ├─ Run tests (unit, integration, security)<br>  ├─ Build container image<br>  ├─ Push to ECR in shared services account<br>  ├─ Deploy IaC templates to pre-prod account<br>  ├─ Run evaluation pipeline<br>  │   ├─ On-demand evaluation (vs. ground truth)<br>  │   ├─ Regression tests<br>  │   ├─ Performance tests<br>  │   └─ Security tests<br>  ├─ Manual approval from domain expert<br>  └─ Deploy to production (rolling, canary, or blue-green)</pre><p><strong>AWS Actions:</strong></p><pre>1. Create AWS CodePipeline for agent deployment<br>2. Add AWS CodeBuild steps for testing and containerization<br>3. Configure manual approval steps before production<br>4. Set up automatic rollback on evaluation failures<br>5. Create separate pipeline for Pre-Prod (gates evaluation)</pre><p><strong>3. Agent Lifecycle Management</strong></p><p>Each agent has a defined lifecycle with versioning and deployment tracking:</p><pre>Development<br>  └─ Agent written, tested locally in dev account<br><br>Containerization<br>  └─ Agent code built into container image<br>  └─ Image tagged with git SHA and semantic version<br>  └─ Pushed to ECR (shared services account)<br><br>Pre-Production Deployment<br>  └─ IaC provisions AgentCore Runtime, Memory, Gateway access in pre-prod account<br>  └─ Container deployed to AgentCore Runtime<br>  └─ Agent automatically registered in AWS Agent Registry with metadata<br>  └─ Evaluation pipeline runs (must pass to proceed)<br><br>Production Deployment<br>  └─ IaC provisions identical resources in prod account<br>  └─ Container deployed to AgentCore Runtime<br>  └─ Endpoint alias (PROD) points to new version<br>  └─ Monitoring alerts configured, dashboards set up<br><br>Monitoring &amp; Iteration<br>  └─ Production telemetry flows to observability platform<br>  └─ Quality alerts trigger human review or rollback<br>  └─ Feedback feeds into next development cycle</pre><p><strong>AWS Actions:</strong></p><pre>1. Define agent versioning strategy (semantic versioning)<br>2. Configure ECR image scanning (security vulnerabilities)<br>3. Create IaC templates (CloudFormation/Terraform) for AgentCore Runtime<br>4. Implement endpoint aliases in AgentCore for instant rollback<br>5. Set up agent metadata registration in AWS Agent Registry<br>6. Create CloudWatch alarms for quality degradation</pre><p><strong>4. Tool Lifecycle and Governance</strong></p><p>Tools are separately versioned and deployed:</p><pre>Tool Development<br>  └─ Tool code in tool repository with unit tests<br><br>Tool Registration<br>  └─ Create tool manifest (name, auth method, prefix, compliance metadata)<br>  └─ Manifest reviewed by platform team, legal, compliance<br><br>Tool Deployment<br>  └─ CI/CD validates manifest<br>  └─ Registers tool target in AgentCore Gateway<br>  └─ Tool available to approved agents<br>  └─ Audit trail captured in CloudTrail<br><br>Tool Updates<br>  └─ New version deployed to gateway<br>  └─ Backward compatibility maintained<br>  └─ Agents continue working (no code changes needed)</pre><p><strong>AWS Actions:</strong></p><pre>1. Create tool repository with manifest schema<br>2. Add CI/CD validation for tool manifests<br>3. Implement tool registration via CreateGatewayTarget API<br>4. Set up gateway authentication (OAuth, mTLS, API keys)<br>5. Track tool changes in CloudTrail</pre><p><strong>5. Memory Configuration as Infrastructure</strong></p><p>Memory is versioned and deployed like other infrastructure:</p><pre>Memory Design<br>  └─ Define extraction strategies<br>  └─ Define namespace structure<br>  └─ Define TTLs and retention<br>  └─ Define encryption keys<br><br>Memory Deployment<br>  └─ IaC provisions AgentCore Memory resources<br>  └─ Extraction strategies deployed<br>  └─ Namespaces created<br>  └─ IAM policies configured<br><br>Memory Testing<br>  └─ Unit tests for extraction quality<br>  └─ Integration tests for namespace isolation<br>  └─ Performance tests for retrieval latency<br>  └─ Security tests for access control<br><br>Memory Promotion<br>  └─ Changes promoted through dev → pre-prod → prod<br>  └─ Rollback available instantly via endpoint aliases</pre><p><strong>AWS Actions:</strong></p><pre>1. Create IaC templates for AgentCore Memory<br>2. Version memory extraction strategies<br>3. Define namespace hierarchies in code<br>4. Implement memory testing harness<br>5. Set up memory metrics in CloudWatch (ops, latency, errors)</pre><h3>Pillar 3: Evaluation</h3><p>Agents fail in ways that are not immediately obvious. A wrong tool selection, a missed context, an outdated model — these failures can silently degrade quality. Structured evaluation at multiple levels catches issues before they reach production.</p><p>Evaluation happens at <strong>four distinct levels</strong>:</p><h3>Level 1: Component Evaluation (Span-Level)</h3><p>Evaluate individual components in isolation:</p><p><strong>Tool Evaluation:</strong></p><ul><li><em>Deterministic tools (APIs):</em> Unit tests verify expected behavior, latency metrics</li><li><em>LLM-backed tools (RAG):</em> Evaluate retrieval quality, answer correctness, hallucination rate</li><li><em>Data retrieval:</em> Evaluate document relevance, chunk quality, freshness</li></ul><p><strong>Example metrics:</strong></p><pre>Retrieval Quality: Are the top-3 documents relevant to the query?<br>  - Metric: MRR@3 (Mean Reciprocal Rank), NDCG@5<br>  - Threshold: MRR@3 &gt; 0.7<br><br>Answer Correctness: Does the RAG tool produce factually accurate answers?<br>  - Evaluator: LLM-as-Judge using reference answers<br>  - Threshold: Correctness &gt; 0.85<br><br>Tool Latency: Does the tool respond within SLA?<br>  - Threshold: P99 latency &lt; 2 seconds</pre><p><strong>AWS Actions:</strong></p><pre>1. Create evaluation datasets (100-500 examples per tool)<br>2. Implement LLM-as-Judge prompts using Bedrock Evaluations<br>3. Set up Amazon Augmented AI (A2I) for human review of uncertain cases<br>4. Configure automated testing in CodeBuild<br>5. Track metrics in CloudWatch</pre><h3>Level 2: Conversation Turn Evaluation (Trace-Level)</h3><p>Evaluate individual responses in a multi-turn conversation:</p><p><strong>Example metrics:</strong></p><pre>Correctness: Is the information factually accurate?<br>  - Evaluator: LLM-as-Judge<br>  - Threshold: Correctness &gt; 0.90<br><br>Helpfulness: How useful is this response?<br>  - Evaluator: LLM-as-Judge<br>  - Threshold: Helpfulness &gt; 0.80<br><br>Faithfulness: Is it grounded in provided context (no hallucination)?<br>  - Evaluator: LLM-as-Judge<br>  - Threshold: Faithfulness &gt; 0.92<br><br>Tool Selection Accuracy: Did the agent choose the right tool?<br>  - Evaluator: Human + LLM-as-Judge<br>  - Threshold: Tool selection accuracy &gt; 0.95</pre><p><strong>AWS Actions:</strong></p><pre>1. Create evaluation datasets with reference answers<br>2. Implement trace-level evaluation in pre-prod pipeline<br>3. Configure LLM-as-Judge evaluators<br>4. Set up human review workflow in Amazon A2I<br>5. Create CloudWatch dashboards for per-turn metrics</pre><h3>Level 3: Session Outcome Evaluation</h3><p>Evaluate whether the agent achieved the user’s goal across a full conversation:</p><p><strong>Example metrics:</strong></p><pre>Task Completion Rate: Did the agent complete the requested task?<br>  - Metric: % of conversations where task was completed<br>  - Threshold: &gt; 0.90<br><br>Goal Accuracy: Did the agent interpret the goal correctly?<br>  - Evaluator: LLM-as-Judge or human<br>  - Threshold: &gt; 0.95<br><br>Conversation Efficiency: How many turns to completion?<br>  - Metric: Median turns to task completion<br>  - Threshold: &lt; 5 turns<br><br>Memory Consistency: Was memory used correctly across turns?<br>  - Metric: % of sessions with consistent memory usage<br>  - Threshold: &gt; 0.98</pre><p><strong>AWS Actions:</strong></p><pre>1. Define session-level success criteria<br>2. Create evaluation workflows for session-level metrics<br>3. Implement human review for borderline cases<br>4. Set up session-level dashboards<br>5. Configure automated rollback on session success rate drop</pre><h3>Level 4: System-Level Metrics (Production)</h3><p>Evaluate operational performance and business impact:</p><p><strong>Example metrics:</strong></p><pre>End-to-End Latency: Total time from user input to response<br>  - Threshold: P99 &lt; 3 seconds<br><br>Time-to-First-Token: How quickly does response start?<br>  - Threshold: &lt; 500ms<br><br>Throughput: How many requests per second?<br>  - Threshold: &gt; 100 RPS<br><br>Tool Error Rate: How often do tool calls fail?<br>  - Threshold: &lt; 0.5%<br><br>Cost Per Task: How much does each completed task cost?<br>  - Threshold: &lt; $0.10<br><br>User Satisfaction: Do users actually prefer agent responses?<br>  - Evaluator: Thumbs up/down, NPS surveys<br>  - Threshold: &gt; 4.0 / 5.0 stars</pre><p><strong>AWS Actions:</strong></p><pre>1. Set up CloudWatch dashboards for system metrics<br>2. Configure alarms for SLA violations<br>3. Implement automatic alerting to on-call team<br>4. Create dashboards for business teams (task completion, user satisfaction)<br>5. Set up automated canary deployments for gradual rollout</pre><h3>Pillar 4: Observability and Monitoring</h3><p>Observability is where the AgentOps cycle completes. Production telemetry feeds back into:</p><ul><li>Governance decisions (has this tool been used as intended?)</li><li>Evaluation refinements (which scenarios are we missing?)</li><li>Build decisions (should we change this tool, prompt, or model?)</li></ul><p>You need visibility across <strong>four distinct telemetry layers</strong>:</p><h3>Layer 1: Agent &amp; Framework Telemetry</h3><p>Captures what your agent decided and did:</p><pre>Agent Decision Trace<br>  ├─ User query input<br>  ├─ Reasoning steps (agent&#39;s reasoning chain)<br>  ├─ Tool selection (which tool, why)<br>  ├─ Tool parameters (what values passed)<br>  ├─ Tool response (what the tool returned)<br>  ├─ Memory operations (what was retrieved/stored)<br>  └─ Final response (what agent returned to user)</pre><p><strong>Metrics to capture:</strong></p><ul><li>Tool invocation sequence</li><li>Reasoning steps and confidence scores</li><li>Tool response latency</li><li>Memory read/write operations</li><li>Number of retries or fallbacks</li><li>LLM invocations (model, tokens, latency)</li></ul><p><strong>AWS Actions:</strong></p><pre>1. Enable OpenTelemetry instrumentation in agent framework<br>   (Strands SDK includes built-in OTEL support)<br>2. Configure OTEL exporters to send to AWS Distro for OpenTelemetry Collector<br>3. Set sampling strategy (100% for development, 10% for production)<br>4. Configure trace context propagation for multi-agent calls</pre><h3>Layer 2: Service Telemetry</h3><p>Captures what happens inside Bedrock AgentCore services (invisible to framework):</p><pre>AgentCore Memory Operations<br>  ├─ Memory read latency<br>  ├─ Extraction success/failure<br>  ├─ Namespace isolation enforcement<br>  └─ Record access patterns<br><br>AgentCore Gateway Operations<br>  ├─ Tool routing decisions<br>  ├─ Authentication latency<br>  ├─ Authorization policy evaluation<br>  └─ Rate limiting enforcement<br><br>AgentCore Identity Operations<br>  ├─ Cross-agent authentication<br>  ├─ Token validation<br>  ├─ Permission propagation<br>  └─ Audit trail logging</pre><p><strong>AWS Actions:</strong></p><pre>1. Enable CloudWatch Logs for AgentCore Memory (operational metrics)<br>2. Configure CloudWatch metrics for Gateway operations<br>3. Set up Identity audit logging via CloudTrail<br>4. Create CloudWatch dashboards for service health<br>5. Aggregate service logs into central observability account</pre><h3>Layer 3: Infrastructure Telemetry</h3><p>Captures what’s happening on the host:</p><pre>Container Metrics<br>  ├─ CPU utilization<br>  ├─ Memory usage<br>  ├─ Network I/O<br>  └─ Disk I/O<br><br>Runtime Metrics<br>  ├─ Container start time<br>  ├─ Replica count / scaling events<br>  └─ Health checks</pre><p><strong>AWS Actions:</strong></p><pre>1. Enable CloudWatch Container Insights for ECS/Fargate<br>2. Configure EC2 agent if running on EC2<br>3. Set up alarms for resource utilization<br>4. Correlate infrastructure metrics with application traces</pre><h3>Layer 4: Application Telemetry</h3><p>Captures business-level metrics:</p><pre>Business Metrics<br>  ├─ Task completion rate<br>  ├─ User satisfaction scores<br>  ├─ Cost per task<br>  ├─ Revenue impact<br>  └─ Customer retention<br><br>Responsible AI Metrics<br>  ├─ Toxicity scores<br>  ├─ Bias detection<br>  ├─ Hallucination rates<br>  ├─ PII leakage<br>  └─ Refusal rates</pre><p><strong>AWS Actions:</strong></p><pre>1. Instrument application code with custom metrics<br>2. Send custom metrics to CloudWatch<br>3. Create application-specific dashboards<br>4. Set up business logic alerts (task completion drop, cost spike)</pre><p><strong>Key Dashboards:</strong></p><p><strong>Agent Performance Dashboard:</strong></p><ul><li>Tool success rate, tool latency, tool selection accuracy</li><li>Memory hit rate, memory latency</li><li>Reasoning coherence score, hallucination rate</li><li>Cost per request, cost trends</li></ul><p><strong>System Health Dashboard:</strong></p><ul><li>Request latency (P50, P95, P99)</li><li>Error rates (tool failures, memory failures, auth failures)</li><li>Throughput (requests/sec)</li><li>Resource utilization (CPU, memory, disk)</li></ul><p><strong>Business Impact Dashboard:</strong></p><ul><li>Task completion rate, user satisfaction</li><li>Revenue per task, cost per task</li><li>Customer retention, repeat usage</li><li>A/B test results</li></ul><h3>Team Structure and Responsibilities</h3><p>Production agentic AI systems require multiple specialized roles, each with distinct responsibilities. Organizations often underestimate the breadth of skills needed.</p><h3>Core Team Profiles Overview</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/680/1*sBonYfI1Q6QK5o8OjnvMSA.png" /></figure><h3>Cross-Functional Collaboration Matrix (RACI)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/730/1*Vn1m7-fcl3AXcPfhdGZGYg.png" /></figure><p><strong>Legend:</strong> A = Accountable (owns it) | R = Responsible (does it) | C = Consulted (input) | I = Informed (kept in loop)</p><h3>Implementation Roadmap</h3><p>Organizations typically follow this sequencing when implementing AgentOps:</p><h3>Phase 1: Foundation</h3><p><strong>Goal:</strong> Build secure, isolated infrastructure with governance</p><ul><li>Establish multi-account AWS architecture (dev, pre-prod, prod)</li><li>Implement SCPs for organization-wide guardrails</li><li>Deploy IAM policy framework</li><li>Set up CloudTrail logging</li><li>Configure Bedrock Guardrails (basic: PII, toxicity)</li><li>Deploy AgentCore runtime infrastructure</li><li>Create seed code repositories (infrastructure, agents, tools, applications)</li><li>Set up Agent Registry</li></ul><p><strong>Team:</strong> Platform Engineer + Security Engineer <strong>Deliverable:</strong> Runnable infrastructure that enforces governance</p><h3>Phase 2: Build &amp; Deployment</h3><p><strong>Goal:</strong> Implement CI/CD and artifact versioning</p><ul><li>Create CI/CD pipeline for agents (CodePipeline)</li><li>Implement container building and ECR management</li><li>Add IaC provisioning to deployment pipeline</li><li>Implement pre-prod environment and promotion workflow</li><li>Set up secrets management</li><li>Create tool registry and gateway configuration</li><li>Implement memory resource provisioning</li></ul><p><strong>Team:</strong> Platform Engineer + MLOps Engineer + AI Engineer <strong>Deliverable:</strong> Agents deployable through CI/CD with reproducible versions</p><h3>Phase 3: Evaluation Framework</h3><p><strong>Goal:</strong> Implement quality gates and evaluation</p><ul><li>Create evaluation datasets (100–500 examples per use case)</li><li>Implement LLM-as-Judge evaluation</li><li>Add on-demand evaluation to pre-prod pipeline</li><li>Integrate evaluation results into deployment gates</li><li>Set up evaluation result storage (S3)</li><li>Create evaluation dashboards</li></ul><p><strong>Team:</strong> ML/Evaluation Engineer + AI Engineer + Data Engineer <strong>Deliverable:</strong> Automated quality gates preventing poor-quality deployments</p><h3>Phase 4: Observability</h3><p><strong>Goal:</strong> Implement monitoring and alerting</p><ul><li>Deploy ADOT Collector</li><li>Configure OpenTelemetry in agents</li><li>Set up CloudWatch Log Groups with semantic conventions</li><li>Create agent performance dashboards</li><li>Implement cost tracking and alerts</li><li>Set up quality drift detection</li><li>Create runbooks and escalation procedures</li></ul><p><strong>Team:</strong> MLOps Engineer + Platform Engineer <strong>Deliverable:</strong> Real-time visibility into agent behavior and cost</p><h3>Phase 5: Production Readiness</h3><p><strong>Goal:</strong> Implement online evaluation and governance enforcement</p><ul><li>Implement online evaluation (production sampling)</li><li>Set up automated alerting for quality degradation</li><li>Implement automated rollback triggers</li><li>Add policy-based tool access (Cedar policies)</li><li>Configure AgentCore Identity for cross-agent auth</li><li>Implement human-in-the-loop escalation</li><li>Conduct security review and pen testing</li></ul><p><strong>Team:</strong> All teams <strong>Deliverable:</strong> Production-ready platform with continuous governance</p><h3>Phase 6: Optimization &amp; Scale</h3><p><strong>Goal:</strong> Continuous improvement and operational maturity</p><ul><li>Implement advanced cost optimization</li><li>Add multi-agent orchestration</li><li>Implement A/B testing framework</li><li>Build advanced observability dashboards</li><li>Create agent reuse and discovery mechanisms</li><li>Implement advanced memory strategies</li><li>Scale to multiple use cases</li></ul><p><strong>Team:</strong> All teams <strong>Deliverable:</strong> Scalable platform supporting dozens of agents</p><h3>Conclusion</h3><p>Building production-grade agentic AI is fundamentally different from deploying traditional software or even fine-tuning language models.</p><p>Agents make autonomous decisions. They invoke external tools. They maintain state across conversations. They evolve based on new data and prompts. Traditional DevOps practices were never designed for this complexity.</p><p><strong>AgentOps</strong> provides the architectural framework, governance patterns, and operational practices needed to scale from experimental agents to production systems that enterprise customers can trust.</p><p>The eight design principles provide the foundation:</p><ol><li><strong>Version everything</strong> (prompts, tools, memory, models)</li><li><strong>Separate concerns</strong> (platform team vs. agent teams)</li><li><strong>Isolate responsibility</strong> (each agent owns its runtime, evaluation, memory)</li><li><strong>Treat memory as infrastructure</strong> (not just a database)</li><li><strong>Instrument reasoning</strong> (not just what happened, but why)</li><li><strong>Evaluate continuously</strong> (component, conversation, session, system levels)</li><li><strong>Embed governance</strong> (security by platform, not convention)</li><li><strong>Optimize cost</strong> (token usage, model selection, context efficiency)</li></ol><p>The four pillars: Governance &amp; Security, Build &amp; Operations, Evaluation, and Observability, provide concrete implementation guidance.</p><p>The team structure ensures that specialized roles collaborate throughout the development lifecycle, each contributing their expertise.</p><p><strong>The path forward:</strong></p><p>Start with <strong>Foundation</strong> (multi-account architecture, governance). Progress to <strong>Build &amp; Deployment</strong> (CI/CD, artifact versioning). Add <strong>Evaluation</strong> (quality gates). Implement <strong>Observability</strong> (monitoring, alerting). Achieve <strong>Production Readiness</strong> (online evaluation, automated governance). Scale to <strong>Optimization</strong> (cost, multi-agent workflows, organizational learning).</p><p>Organizations that embrace these principles will successfully transition from building a handful of experimental agents to operating hundreds of production-grade AI systems that are observable, governable, testable, reproducible, and continuously improving.</p><p>The investment in AgentOps infrastructure pays dividends as you scale. The first agent takes weeks to build. The tenth agent takes days because shared infrastructure is in place, guardrails are consistent, evaluation is automatic, and observability is built-in.</p><p>The future of AI adoption in the enterprise depends on our ability to build, deploy, and operate agentic systems at scale. AgentOps provides the framework. It’s up to your teams to implement it.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d2ef61c5545a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Don’t Trust Your Guardrails — Test, Trace and Tune Them: An AWS-Native Framework for Bedrock Safety…]]></title>
            <link>https://medium.com/@wael-saideni/dont-trust-your-guardrails-test-trace-and-tune-them-an-aws-native-framework-for-bedrock-safety-37a38d2a14e0?source=rss-f849de33d418------2</link>
            <guid isPermaLink="false">https://medium.com/p/37a38d2a14e0</guid>
            <category><![CDATA[ai-security-governance]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[generative-ai-security]]></category>
            <category><![CDATA[amazon-bedrock]]></category>
            <category><![CDATA[generative-ai-use-cases]]></category>
            <dc:creator><![CDATA[Wael SAIDENI]]></dc:creator>
            <pubDate>Fri, 06 Mar 2026 16:29:27 GMT</pubDate>
            <atom:updated>2026-04-17T08:08:11.747Z</atom:updated>
            <content:encoded><![CDATA[<h3>Don’t Trust Your Guardrails — Test, Trace and Tune Them: An AWS-Native Framework for Bedrock Safety Validation</h3><h3>How we built an open, deployable toolkit to help teams evaluate, red-team, and optimise Bedrock Guardrails on Knowledge Bases — with full observability baked in.</h3><p><em>If your organisation is adopting Amazon Bedrock and you’re configuring Guardrails to protect your GenAI/AgenticAI applications, you’ve probably asked yourself: “How do I know if my guardrails are actually working? Are they too aggressive? Too permissive? What’s getting through?”</em></p><p><em>This article walks through a CDK-deployable framework we built to answer exactly those questions.</em></p><h3>The Problem: Guardrails Are Only as Good as Your Testing</h3><p>Amazon Bedrock Guardrails offer powerful content filtering — topic blocking, PII masking, content policy enforcement, and more. But configuring them is an iterative process. You set thresholds, define denied topics, add sensitive information filters… and then what?</p><p>Most teams hit the same wall:</p><ol><li><strong>No structured way to test</strong> — Engineers run ad-hoc queries in the AWS console, copy-paste results into spreadsheets, and hope they remember what they changed.</li><li><strong>No visibility into guardrail decisions </strong>— A query was blocked, but <em>why</em>? Which filter triggered? What was the confidence score? Was it a false positive?</li><li><strong>No historical tracking</strong> — You tweak a threshold, but you have no baseline to compare against. Did the change reduce false positives or just open a hole?</li><li><strong>No monitoring </strong>— In production, you have no idea if your guardrails are suddenly blocking 50% of legitimate queries or letting everything through.</li></ol><p>We needed a framework that would let any team — security engineers, ML engineers, product owners — sit down, run structured tests against their guardrails, see <em>exactly</em> what happened at the trace level, and track outcomes over time.</p><p>So we built one.</p><h3>What We Built: The Architecture at a Glance</h3><p>The framework deploys as a single AWS CDK stack. One cdk deploy command gives you the entire infrastructure:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eYsr-qYDWT4qDexP6PFL4Q.png" /><figcaption><strong>Amazon Bedrock Guardrails Tester Application — POC Architecture</strong></figcaption></figure><p>The stack provisions six core components:</p><ul><li><strong>A VPC with a public subnet</strong> (single AZ, no NAT — optimised for cost in dev/test)</li><li>A <strong>DynamoDB table</strong> for persisting every query and its guardrail outcome</li><li>A <strong>Lambda function</strong> that orchestrates Bedrock calls, records history, and publishes metrics</li><li>An <strong>API Gateway</strong> (REST, with CORS and throttling) as the Lambda’s front door</li><li>An <strong>EC2 instance</strong> running a Streamlit web app, with the app code pulled from an S3 asset</li><li>A <strong>CloudWatch dashboard</strong> with custom metrics and pre-configured alarms</li></ul><p>Let me break down the three most important layers and why each one matters.</p><h3>Layer 1: The Interactive Testing Interface (Streamlit)</h3><p>The front door to the framework is a Streamlit web application running on an EC2 instance. It’s deliberately simple — anyone on the team can use it without reading documentation.</p><h3>What You Can Do</h3><p>Configure your test parameters in the sidebar: Model ID, temperature, Knowledge Base ID, retrieval count, and Guardrail ID.</p><p>Choose your test mode with two checkboxes:</p><ul><li>☑️ Use Knowledge Base (RAG queries vs. direct model queries)</li><li>☑️ Use Guardrails (apply guardrails or bypass them)</li></ul><p>Submit queries and inspect results in detail. This is where the framework goes beyond a simple chat interface. For every query, you see:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ygFx23MpWTrDVxN7ju-Q7A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KBEiWriPyjiaFb9NH8MGcA.png" /><figcaption><strong>Bedrock Guardrails Tester — Allowed Query Example</strong></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9gYoNp4vP9BuzEiREazOKw.png" /><figcaption><strong>Bedrock Guardrails Tester — Blocked Query Example</strong></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*b5jg0wDu_mMTIlrJnXEECw.png" /><figcaption><strong>Bedrock Guardrails Tester — Content Masking Example</strong></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*u0JZ0NAu5ICi4uTxYrnyXg.png" /><figcaption><strong>Bedrock Guardrails Tester — Content Masking Example</strong></figcaption></figure><h3>The Guardrail Trace Parser: The Hard Part</h3><p>One of the trickiest parts of working with Bedrock Guardrails is parsing the trace data. The trace structure varies depending on the query mode (direct invoke vs. Knowledge Base), the guardrail version, and which filters triggered. The response nesting can be different every time.</p><p>We solved this with a brute-force recursive parser that searches the <em>entire</em> response for guardrail action entries, regardless of where they’re nested:</p><pre>def _recursive_find_actions(obj, max_depth=15):<br>    &quot;&quot;&quot;<br>    Recursively find ALL occurrences of &#39;action&#39; keys anywhere<br>    in the response, along with their context (match, type, name,<br>    score, threshold).<br>    &quot;&quot;&quot;<br>    found = []<br>    if max_depth &lt;= 0:<br>        return found<br>    if isinstance(obj, dict):<br>        if &quot;action&quot; in obj:<br>            found.append({<br>                &quot;action&quot;: str(obj[&quot;action&quot;]),<br>                &quot;match&quot;: str(obj.get(&quot;match&quot;, &quot;&quot;)),<br>                &quot;type&quot;: str(obj.get(&quot;type&quot;, &quot;&quot;)),<br>                &quot;name&quot;: str(obj.get(&quot;name&quot;, &quot;&quot;)),<br>                &quot;score&quot;: obj.get(&quot;score&quot;, None),<br>                &quot;threshold&quot;: obj.get(&quot;threshold&quot;, None),<br>            })<br>        for value in obj.values():<br>            found.extend(_recursive_find_actions(value, max_depth - 1))<br>    elif isinstance(obj, list):<br>        for item in obj:<br>            found.extend(_recursive_find_actions(item, max_depth - 1))<br>    return found</pre><p>The classification logic is then straightforward:</p><pre># BLOCKED = at least one action entry has action == &quot;BLOCKED&quot;<br># MASKED  = no BLOCKED entries, but at least one action == &quot;ANONYMIZED&quot;<br># NONE    = everything passed cleanly<br><br>if guardrail_info[&quot;blocked_items&quot;]:<br>    guardrail_info[&quot;action&quot;] = &quot;BLOCKED&quot;<br>elif guardrail_info[&quot;anonymized_items&quot;]:<br>    guardrail_info[&quot;action&quot;] = &quot;MASKED&quot;<br>else:<br>    guardrail_info[&quot;action&quot;] = &quot;NONE&quot;</pre><p>This approach is resilient to API changes and works consistently across all Bedrock query patterns. We also check the actionReason field as a secondary signal — if the guardrail trace structure ever changes, the fallback still catches blocked queries.</p><h3>Session-Level Analytics</h3><p>As you run multiple queries in a session, the app builds up in-memory analytics — total queries, allowed/blocked/masked counts, average response time, a bar chart of guardrail outcome breakdown, and a line chart of response time over successive queries.</p><p>The history view renders each past query with its full context:</p><pre># Each history entry captures the complete picture<br>st.session_state.chat_history.append({<br>    &quot;timestamp&quot;: datetime.now().strftime(&quot;%Y-%m-%d %H:%M:%S&quot;),<br>    &quot;query&quot;: query,<br>    &quot;use_kb&quot;: use_kb,<br>    &quot;use_guardrail&quot;: use_guardrail,<br>    &quot;response&quot;: response_text,<br>    &quot;duration&quot;: duration,<br>    &quot;blocked&quot;: guardrail_info.get(&quot;blocked&quot;, False),<br>    &quot;guardrail_action&quot;: guardrail_info.get(&quot;action&quot;, &quot;NONE&quot;),<br>    &quot;action_reason&quot;: guardrail_info.get(&quot;action_reason&quot;, &quot;&quot;),<br>    &quot;has_anonymization&quot;: guardrail_info.get(&quot;has_anonymization&quot;, False),<br>    &quot;input_tokens&quot;: usage.get(&quot;inputTokens&quot;, &quot;N/A&quot;),<br>    &quot;output_tokens&quot;: usage.get(&quot;outputTokens&quot;, &quot;N/A&quot;),<br>    &quot;stop_reason&quot;: model_resp.get(&quot;stopReason&quot;, &quot;N/A&quot;),<br>})</pre><p>This is invaluable during a red-teaming session — you can see at a glance how your guardrails are performing across a battery of test prompts, and drill into any individual query to understand exactly what happened.</p><h3>Deployment: S3 Asset, Not Inline Code</h3><p>A key architectural decision: the Streamlit app code lives in a separate app_code/ directory that gets packaged as an S3 asset by CDK. During EC2 bootstrap, the user data script downloads and unzips it from S3.</p><p>Why does this matter?</p><ol><li>Separation of concerns — The CDK stack defines infrastructure; the app code is independently versioned and maintained.</li><li>Easier iteration — Update the Streamlit app without modifying the CDK stack. Just redeploy.</li><li>Cleaner diffs — No more 200-line inline strings in your infrastructure code.</li></ol><h3>Layer 2: The Persistence Layer (DynamoDB)</h3><p>Every query processed by the Lambda function is recorded in a DynamoDB table. This is the framework’s memory.</p><h3>Table Design</h3><p>The table uses a UUID partition key and ISO 8601 timestamp sort key, with TTL support for automatic cleanup of old records:</p><pre>Table: bedrock-guardrails-query-history<br>├── Partition Key: query_id (UUID)<br>├── Sort Key: timestamp (ISO 8601)<br>├── TTL: ttl attribute (automatic expiry)<br>│<br>├── GSI: guardrail-action-index<br>│   ├── Partition: guardrail_action (BLOCKED / MASKED / NONE)<br>│   └── Sort: timestamp<br>│<br>└── GSI: date-index<br>    ├── Partition: query_date (YYYY-MM-DD)<br>    └── Sort: timestamp</pre><h3>Why Two GSIs?</h3><p>The Global Secondary Indexes are designed around the two most common analysis patterns:</p><p>1. “Show me all blocked queries” → guardrail-action-index</p><pre>aws dynamodb query \<br>  --table-name bedrock-guardrails-query-history \<br>  --index-name guardrail-action-index \<br>  --key-condition-expression &quot;guardrail_action = :action&quot; \<br>  --expression-attribute-values &#39;{&quot;:action&quot;: {&quot;S&quot;: &quot;BLOCKED&quot;}}&#39;</pre><p>This is your go-to query when reviewing false positives. Pull all blocked queries, inspect them, and decide if your guardrail thresholds need adjustment.</p><p>2. “What happened yesterday?” → date-index</p><pre>aws dynamodb query \<br>  --table-name bedrock-guardrails-query-history \<br>  --index-name date-index \<br>  --key-condition-expression &quot;query_date = :d&quot; \<br>  --expression-attribute-values &#39;{&quot;:d&quot;: {&quot;S&quot;: &quot;2026-02-25&quot;}}&#39;</pre><p>This powers time-series analysis. Compare guardrail performance before and after a configuration change.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TAsNwRF9LoNy5ZNefxJUMQ.png" /><figcaption><strong>Bedrock Guardrails Tester — DynamoDB table content</strong></figcaption></figure><h3>The Key Insight: DynamoDB Is Not CloudWatch</h3><p>This is a point worth emphasising because it’s a common architectural question: why store query history in DynamoDB when you’re also pushing metrics to CloudWatch?</p><p>They serve fundamentally different purposes:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*efpvwjkthaJUSdEYGmv-0Q.png" /></figure><p>DynamoDB gives you the “what” and “why.” CloudWatch gives you the “how much” and “when.”</p><p>The Lambda function writes to both on every request. There is no pipeline from DynamoDB to CloudWatch — they are independent sinks fed by the same source:</p><pre>              Lambda Function<br>             (on each request)<br>            /                  \<br>           ↓                    ↓<br>     DynamoDB               CloudWatch<br>  (detailed record)       (numeric metrics)</pre><h3>Layer 3: The Observability Layer (CloudWatch)</h3><p>This is where the framework shifts from a testing tool to a monitoring platform.</p><h3>Custom Metrics</h3><p>The Lambda function publishes custom metrics to a dedicated CloudWatch namespace. The namespace is configurable via environment variable, making it easy to run multiple environments side by side:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nSRgIBIlLAsF8fKoS59HlA.png" /></figure><h3>The Dashboard</h3><p>The CDK stack deploys a pre-built CloudWatch dashboard with four rows of widgets:</p><p><strong>Row 1 — Volume &amp; Outcomes:</strong> Total query count over time, guardrail outcome breakdown (Blocked in red, Masked in orange, Allowed in green), and single-value widgets showing 24-hour blocked and masked counts.</p><p><strong>Row 2 — Performance &amp; Usage:</strong> Response latency (average and p99), token consumption (input vs. output), and query mode split (Knowledge Base vs. Direct).</p><p><strong>Row 3 — Lambda Health: </strong>Invocations and errors, average and maximum duration. These use Lambda’s built-in metrics — no custom instrumentation needed.</p><p><strong>Row 4 — Error Tracking:</strong> Query error trend line and a CloudWatch Logs Insights widget that surfaces the 20 most recent Lambda errors with a query like:</p><pre>fields @timestamp, @message<br>| filter @message like /ERROR/<br>| sort @timestamp desc<br>| limit 20</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*c26ZdEyADZTDe5p1Hie5LQ.png" /><figcaption><strong>Bedrock Guardrails Tester — CloudWatch monitoring dashboard</strong></figcaption></figure><h3>Alarms</h3><p>Two alarms are deployed out of the box:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cplEAZkGYO6cMTYLP3cSpw.png" /></figure><p>In a production setup, you’d wire these to an SNS topic for Slack/PagerDuty notifications.</p><h3>Under the Hood: How the Lambda Ties It All Together</h3><p>The Lambda function is the central hub of the framework. On every request, it performs three operations:</p><p><strong>1. Call Bedrock</strong> — Either a direct model invocation or a Knowledge Base retrieval, with optional guardrail application.</p><p><strong>2. Write to DynamoDB</strong> — A detailed record with the query text, guardrail outcome, timestamps, and a TTL value for automatic expiry.</p><p><strong>3. Push to CloudWatch</strong> — Lightweight numeric metrics that power the dashboard and alarms.</p><p>The Lambda receives its configuration through environment variables, keeping it decoupled from the CDK stack:</p><pre># Environment variables injected by CDK<br>TABLE_NAME = os.environ.get(&#39;DYNAMODB_TABLE_NAME&#39;)<br>CW_NAMESPACE = os.environ.get(&#39;CLOUDWATCH_NAMESPACE&#39;, &#39;BedrockGuardrails&#39;)<br>KB_ID = os.environ.get(&#39;KB_ID&#39;)<br>GUARDRAIL_ID = os.environ.get(&#39;GUARDRAIL_ID&#39;)<br>MODEL_ID = os.environ.get(&#39;MODEL_ID&#39;)</pre><p>The IAM permissions follow the principle of least privilege, with separate policy statements for:</p><ul><li>Foundation model invocation (including cross-region inference profiles)</li><li>Knowledge Base retrieval</li><li>Guardrail application</li><li>DynamoDB read/write (scoped to the specific table)</li><li>CloudWatch metric publishing</li><li>Model discovery (list/get operations)</li></ul><h3>The Workflow: How Teams Actually Use This</h3><h3>Scenario 1: Initial Guardrail Configuration</h3><p>You’ve just created a new Guardrail in Bedrock. You’ve set up topic filters, content policies, and PII detection. Now you need to validate it.</p><ol><li>Deploy the framework with your Guardrail ID in the configuration</li><li>Open the Streamlit app and enable both Knowledge Base and Guardrails</li><li>Run your test suite — legitimate queries, edge cases, adversarial prompts</li><li>Inspect every blocked query — Was it a true positive? Check the guardrail trace for the exact filter, match text, and confidence score</li><li>Adjust thresholds in the Bedrock console</li><li>Re-run the same queries — Compare results using the session history</li></ol><h3>Scenario 2: Red Teaming</h3><p>Your security team wants to probe the guardrails for weaknesses.</p><ol><li>Run adversarial prompts — Prompt injections, jailbreak attempts, requests for denied topics</li><li>Check the guardrail trace — Did the guardrail catch the attempt? Which filter triggered?</li><li>Query DynamoDB for all BLOCKED entries to see what was caught</li><li>Query DynamoDB for all NONE entries to see what <em>wasn&#39;t</em> caught — these are your gaps</li><li>Monitor the CloudWatch dashboard in real-time during the red team session</li></ol><h3>Scenario 3: Ongoing Monitoring</h3><p>The guardrails are in production. You need to know if something changes.</p><ol><li>Watch the dashboard — Is the block rate stable? Is latency creeping up?</li><li>Respond to alarms — A sudden spike in blocks could mean an attack; a sudden drop could mean a misconfiguration</li><li>Query DynamoDB by date — Compare this week’s guardrail outcomes to last week’s</li></ol><h3>Deploying It Yourself</h3><p>The entire framework deploys with four commands:</p><pre># 1. Setup<br>python3 -m venv .venv &amp;&amp; source .venv/bin/activate<br>pip install -r requirements.txt<br><br># 2. Bootstrap (first time only)<br>cdk bootstrap aws://YOUR_ACCOUNT/YOUR_REGION<br><br># 3. Deploy<br>cdk deploy<br><br># 4. Open the app — use the StreamlitURL from the stack outputs</pre><p><strong>Prerequisites</strong>: An existing Bedrock Knowledge Base, a configured Guardrail, and model access in your region. The framework tests your guardrails — it doesn’t create them.</p><p><strong>Cleanup</strong>: cdk destroy removes everything — the EC2 instance, VPC, Lambda, API Gateway, DynamoDB table, CloudWatch dashboard and alarms, and the S3 asset bucket. Your Bedrock Knowledge Base and Guardrails are untouched.</p><p>Check the repository for more details: <a href="https://github.com/WaelDataReply/cdk_bedrock_guardrails_testing_app">WaelDataReply/cdk_bedrock_guardrails_testing_app</a></p><h3>Project Structure</h3><pre>CDK-Bedrock-Guardrails-Testing-App/<br>├── app.py                          # CDK entry point<br>├── cdk.json                        # Configuration (KB ID, Guardrail ID, Model ID)<br>├── requirements.txt                # CDK dependencies<br>├── stacks/<br>│   └── bedrock_guardrails_stack.py # Infrastructure definition<br>├── lambda/<br>│   └── lambda_function.py          # API backend<br>└── app_code/<br>    └── streamlit_app.py            # Testing UI</pre><h3>Design Decisions Worth Highlighting</h3><h3>1. Lambda as the Central Hub</h3><p>The Lambda function is the single point that connects everything. It receives queries from the Streamlit app via API Gateway, calls Bedrock, writes results to DynamoDB, and pushes metrics to CloudWatch. This keeps the architecture simple — one function, three sinks.</p><h3>2. Pay-Per-Request DynamoDB</h3><p>We chose on-demand billing for DynamoDB because testing workloads are bursty. You might run 500 queries during a red-team session and then nothing for a week. Provisioned capacity would be wasteful.</p><h3>3. TTL on DynamoDB</h3><p>The ttl attribute lets you automatically expire old records. Set it to 30 days for testing environments, or remove it entirely if you need permanent audit trails.</p><h3>4. Resilient Trace Parsing</h3><p>Rather than hardcoding the path to guardrail trace data (which varies by API version and query mode), the recursive parser searches the entire response tree. This means the framework doesn’t break when AWS updates the Bedrock API response format.</p><h3>5. No Authentication (By Design)</h3><p>This is a development/testing framework. The security group allows all inbound traffic, CORS is open, and there’s no auth on the API. This is intentional for rapid iteration during testing. For production use, you’d add:</p><ul><li>Cognito or API key authentication</li><li>Restricted security groups</li><li>HTTPS with ACM certificates</li><li>VPN or bastion host access</li></ul><h3>6. Single AZ, No NAT</h3><p>Cost optimisation for a dev tool. The EC2 instance sits in a public subnet with a public IP. No NAT gateway means ~$30/month saved. For production, add multi-AZ, a load balancer, and private subnets.</p><h3>What’s Next</h3><p>This framework gives you the foundation. Here are natural extensions:</p><ul><li>SNS integration on CloudWatch alarms for Slack/PagerDuty notifications</li><li>A “test suite” mode in Streamlit that runs a predefined set of prompts and generates a report</li><li>A/B comparison — run the same query against two different guardrail configurations side by side</li><li>Export to CSV/PDF — generate compliance reports from DynamoDB history</li><li>Cognito auth — lock down the Streamlit app for multi-user teams</li><li>CI/CD integration — run guardrail regression tests as part of your deployment pipeline</li></ul><h3>Closing Thoughts</h3><p>Guardrails are not a “set and forget” feature. They require the same iterative tuning as any other part of your ML system — and that means you need tooling for testing, visibility, and monitoring.</p><p>What we’ve built here is deliberately opinionated about the workflow (test → inspect → adjust → monitor) but flexible about the specifics (your models, your Knowledge Bases, your guardrail policies). Deploy it, run your first red-team session, and you’ll immediately see things about your guardrails that the AWS console alone can’t show you.</p><p>The full trace parsing, the DynamoDB history with queryable indexes, and the CloudWatch dashboard with pre-configured alarms — these aren’t nice-to-haves. They’re the difference between <em>hoping</em> your guardrails work and <em>knowing</em> they do.</p><p><em>Have questions, want to extend the framework or see a live demo? Reach out at </em><a href="/service/mailto:w.saideni@reply.com"><em>w.saideni@reply.com</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=37a38d2a14e0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building Production-Ready MCP Workflows with Amazon Bedrock AgentCore Gateway]]></title>
            <link>https://medium.com/@wael-saideni/building-production-ready-mcp-workflows-with-amazon-bedrock-agentcore-gateway-d8386db65df3?source=rss-f849de33d418------2</link>
            <guid isPermaLink="false">https://medium.com/p/d8386db65df3</guid>
            <category><![CDATA[oauth2]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[amazon-bedrock-agentcore]]></category>
            <category><![CDATA[mcp-protocol]]></category>
            <category><![CDATA[agentic-ai]]></category>
            <dc:creator><![CDATA[Wael SAIDENI]]></dc:creator>
            <pubDate>Tue, 29 Jul 2025 07:27:34 GMT</pubDate>
            <atom:updated>2025-07-29T07:27:34.220Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZEjXDtw89eKT7zgmT06qEQ.png" /></figure><h3>Introduction</h3><p>The landscape of artificial intelligence is rapidly evolving toward more sophisticated agentic systems that can autonomously interact with external tools and data sources. However, as organizations attempt to scale these AI agents in production environments, they encounter significant challenges around security, standardization, and maintainability of integrations. The Model Context Protocol (MCP), introduced by Anthropic in November 2024, represents a breakthrough in addressing these challenges by providing a standardized framework for AI-to-external-system communication. Yet, implementing MCP at enterprise scale brings its own complexities — from multi-tenant security requirements to compliance with evolving authorization specifications. In this comprehensive blog, we’ll explore the intersection of MCP standardization and enterprise-grade agentic AI implementations by answering four critical questions:</p><blockquote><strong>What is MCP?</strong></blockquote><blockquote><strong>What are the challenges faced by companies to adopt MCP in their Agentic AI workflows?</strong></blockquote><blockquote><strong>What is Amazon Bedrock AgentCore Gateway and why is it important for MCP adoption in production-ready Agentic AI projects?</strong></blockquote><blockquote><strong>How to use Bedrock AgentCore Gateway to build a secure and scalable MCP-based workflow aligned with the MCP authorization and authentication specification?</strong></blockquote><p>Whether you’re an AI engineer looking to scale your agent deployments or an enterprise architect evaluating MCP adoption strategies, this guide will provide you with the insights and practical knowledge needed to successfully implement secure, scalable agentic AI workflows that meet both technical and business requirements.</p><h3>Understanding the Model Context Protocol (MCP)</h3><p>Model Context Protocol (MCP) is an emerging open-source standard designed to address key challenges in generative and agentic AI applications. Published by Anthropic in November 2024, MCP tackles the complex issues that arise when AI systems need to access multiple external data sources or tools via APIs at scale.</p><h3>The Problems MCP Solves</h3><p>MCP aims to resolve several critical challenges in AI system integration:</p><ul><li><strong>Maintenance Complexity</strong>: Traditional approaches require maintaining multiple custom integrations, each with its own implementation patterns and maintenance overhead. This creates a significant burden as the number of external systems grows.</li><li><strong>Flexibility Limitations</strong>: Rigid integration patterns make it difficult to adapt to changing requirements or add new data sources, limiting the agility of AI applications.</li><li><strong>Scalability Issues</strong>: Without standardization, scaling AI applications to work with numerous external systems becomes increasingly complex and resource-intensive.</li><li><strong>Data Centralization and Duplication Risks</strong>: Many current approaches require centralizing or duplicating sensitive data, creating security vulnerabilities and compliance challenges.<br>The protocol provides a standardized framework for structuring communication between AI and external environments, avoiding rigid snapshots or heavy integration processes.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/484/1*gqBCo5Xz9UHfThGxgq2ODw.png" /><figcaption><em>Figure 1: Illustration of LLM access to external tools before and after MCP implementation</em></figcaption></figure><h3>Key Features of MCP</h3><ul><li><strong>Standardized Interactions</strong>: MCP enables AI agents and models to interact with external tools and data sources in a uniform manner, reducing the complexity of managing multiple integration patterns.</li><li><strong>Structured and Secure Communications</strong>: The protocol facilitates well-defined and protected data exchanges, ensuring that sensitive information remains secure throughout the interaction process.</li><li><strong>Enhanced Capabilities</strong>: By providing a consistent interface, MCP improves the action and reasoning capabilities of AI systems, allowing them to more effectively leverage external resources.</li><li><strong>Safe Boundaries</strong>: MCP maintains clear and secure boundaries between AI systems and third-party resources, protecting both the AI application and external systems from potential security threats.</li></ul><p>By providing this standardized approach, MCP allows for more efficient, flexible, and secure integration of AI systems with external resources, addressing many of the scalability and maintenance challenges faced in complex AI deployments.</p><h3>Enterprise Challenges in MCP Adoption</h3><p>While creating MCP servers might appear straightforward in tutorials and basic demonstrations, the reality of implementing MCP in enterprise environments presents significantly more complex challenges. Most available examples showcase basic MCP servers using stdio transport, which are perfect for learning but inadequate for production enterprise infrastructure requirements.</p><h3>Security and Multi-Tenancy Requirements</h3><p>When deploying shared MCP services accessible to various applications within an organization, security becomes absolutely mandatory rather than optional. Enterprise data flowing through these servers is often highly sensitive and requires rigorous protection against unauthorized access. Organizations need MCP services that are:</p><ul><li><strong>Remotely accessible</strong>: Unlike stdio-based examples, enterprise MCP servers must be accessible across network boundaries</li><li><strong>Multi-tenant</strong>: Supporting multiple users, applications, and organizational units with proper isolation</li><li><strong>Highly governed and versioned</strong>: Following enterprise change management and version control processes</li><li><strong>Tightly secured</strong>: Implementing comprehensive security controls including authentication, authorization, and audit logging</li></ul><h3>Service Registration and Discovery Challenges</h3><p>Enterprises require systematic approaches to manage their MCP ecosystem effectively. This includes establishing robust processes for:</p><ul><li><strong>Service Cataloging</strong>: Creating comprehensive catalogs of approved MCP services that can be discovered and used by authorized applications and users.</li><li><strong>Registration Workflows</strong>: Implementing governance processes for registering new MCP services, including security reviews, compliance checks, and approval workflows.</li><li><strong>Discovery Mechanisms</strong>: Developing enterprise-grade discovery systems, similar to DNS or service meshes, that allow applications to locate and connect to appropriate MCP services.</li><li><strong>Security Protection</strong>: Protecting against MCP tool poisoning attacks, where malicious actors might attempt to register harmful or deceptive MCP services that could compromise AI agent behavior.</li></ul><h3>Authorization Specification Compliance</h3><p>The MCP Authorization specification presents several implementation challenges, particularly around compliance with OAuth 2.1/OAuth 2.0 and related standards. The recent <a href="https://modelcontextprotocol.io/specification/draft">MCP 2025‑06‑18 specification</a> includes both mandatory and recommended components:</p><p><strong>Required Components (MUST implement):</strong></p><ul><li><em>OAuth 2.1 with PKCE (Proof Key for Code Exchange) support</em></li><li><em>RFC 8414 (OAuth 2.0 Authorization Server Metadata)</em></li><li><em>RFC 9728 (OAuth 2.0 Protected Resource Metadata)</em></li></ul><p><strong>Recommended Components (SHOULD implement):</strong></p><ul><li><em>RFC 7591 (OAuth 2.0 Dynamic Client Registration Protocol)</em></li><li><em>RFC 8707 (Resource Indicators for OAuth 2.0)</em></li></ul><p>However, many enterprise identity providers don’t fully support these standards, creating significant implementation gaps:</p><ul><li><strong>Dynamic Client Registration (DCR) Challenges</strong>: The MCP specification expects anonymous Dynamic Client Registration, but enterprises typically avoid anonymous client registration due to security concerns. This creates a tension between security best practices and MCP compliance requirements.</li><li><strong>Resource Indicators Support</strong>: RFC 8707 is critical for proper token scoping and audience control, but most identity providers don’t implement this standard. This creates challenges for proper token delegation and audience control in multi-resource environments.</li></ul><p>These compliance gaps force organizations to choose between adhering to their security best practices and achieving full MCP specification compliance, often requiring custom implementations or workarounds that add complexity and potential security risks.</p><h3>Introducing Amazon Bedrock AgentCore Gateway</h3><p>Amazon Bedrock AgentCore Gateway is AWS’s solution to the enterprise MCP adoption challenge. It allows customers to transform their existing APIs and Lambda functions into fully managed MCP servers without worrying about infrastructure, hosting, or the complex implementation details of MCP compliance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*u34OuV0iBmb6bMl7ZjxdaQ.png" /><figcaption><em>Figure 2: Main components of Bedrock AgentCore Gateway including Gateway, Target, MCP Mechanism, Inbound Auth, and Outbound Auth</em></figcaption></figure><h3>Core Architecture and Features</h3><p><strong>Simplified Integration</strong>: Organizations can leverage their existing OpenAPI specifications or Lambda functions as interfaces to their tools, eliminating the need to rebuild integrations from scratch.</p><p><strong>Unified MCP Interface</strong>: The Gateway provides a standardized MCP interface for all connected tools, facilitating seamless integration with AI models and agents while maintaining consistency across different backend systems.</p><p><strong>Dual Authentication Model</strong>:</p><ul><li><strong>Inbound Authentication</strong>: Validates and authorizes users and applications attempting to access gateway resources</li><li><strong>Outbound Authentication</strong>: Enables the gateway to securely connect to backend resources on behalf of authenticated users, maintaining security throughout the entire request flow</li></ul><p><strong>Comprehensive Authentication Support</strong>: The Gateway supports multiple authentication methods including IAM credentials and OAuth-based authentication flows, providing flexibility for different enterprise security requirements.</p><p><strong>Streamable HTTP Transport</strong>: Full compatibility with MCP protocol’s streamable HTTP transport enables real-time communications, supporting interactive and responsive AI agent experiences.</p><h3>Strategic Importance for Enterprise MCP Adoption</h3><p>Bedrock AgentCore Gateway addresses the fundamental challenges that prevent organizations from successfully implementing MCP at scale:</p><ul><li><strong>Managed Infrastructure</strong>: By providing MCP as a managed service, organizations can focus on their core AI applications rather than the complexities of MCP server implementation, maintenance, and scaling.</li><li><strong>Enterprise Security</strong>: The Gateway implements enterprise-grade security controls, multi-tenancy, and compliance features that meet organizational requirements without requiring custom development.</li><li><strong>Standards Compliance</strong>: Built-in compliance with MCP authorization specifications reduces the implementation burden and ensures compatibility with the evolving MCP ecosystem.</li><li><strong>Operational Excellence</strong>: AWS’s managed service approach provides the reliability, monitoring, and support that enterprises require for production AI deployments.</li></ul><p>This solution enables organizations to accelerate their agentic AI initiatives by removing the technical and operational barriers that typically slow enterprise MCP adoption.</p><h3>Building Secure and Scalable MCP Workflows</h3><p>To demonstrate the practical implementation of Bedrock AgentCore Gateway, we’ll explore a comprehensive example using NASA’s Mars Weather API. This tutorial illustrates how to build a secure, production-ready AI agent that can access external APIs through the MCP protocol.</p><h3>Architecture Overview</h3><p>Our demonstration architecture illustrates a complete solution for creating an AI agent capable of interacting with external APIs using the Model Context Protocol. The architecture ensures security, scalability, and compliance with MCP specifications.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_Py40WydkLrMSai17DE63Q.png" /><figcaption>Figure 3: Demo AWS Architecture built upon Amazon Bedrock AgentCore</figcaption></figure><h3>System Components</h3><p><strong>User Infrastructure and Application:</strong></p><ul><li><strong>User Interface</strong>: Sends requests and receives responses from the AI agent</li><li><strong>EC2 Instance</strong>: Hosts the MCP client application running our Strands-based AI agent</li><li><strong>MCP Client-Strands Agent</strong>: An agent implementation using AWS Strands framework (v1.0.1), though the solution is framework-agnostic</li></ul><p><strong>AI Processing Layer:</strong></p><ul><li><strong>Amazon Bedrock with Claude Sonnet 3.5</strong>: Provides the language model capabilities that power our intelligent agent</li></ul><p><strong>MCP Infrastructure:</strong></p><ul><li><strong>AgentCore Gateway</strong>: Transforms OpenAPI specifications into MCP-compliant tools</li><li><strong>AgentCore Identity</strong>: Manages comprehensive authentication and authorization</li></ul><p><strong>Identity and Security Management:</strong></p><ul><li><strong>Amazon Cognito</strong>: Handles end-user authentication and token management</li><li><strong>OAuth 2.0 Protocols</strong>: Implements secure authentication at multiple architectural layers</li></ul><p><strong>External Integration:</strong></p><ul><li><strong>Weather API</strong>: External REST API providing Mars weather data</li><li><strong>Tool Integration</strong>: MCP tool created from the API specifications</li></ul><h3>Operational Flow</h3><h4>User Request Flow</h4><ol><li>The user sends a query to the application</li><li>The EC2 application hosting the Strands agent receives the request</li><li>The agent determines it needs to use an external tool</li></ol><h4>Interaction with the Language Model</h4><ol><li>The agent invokes the Claude Sonnet 3.5 model via Bedrock</li><li>The model generates a response or determines that a tool needs to be used</li></ol><h4>Tool Usage via AgentCore Gateway</h4><ol><li>The agent communicates with AgentCore Gateway via streamable HTTP</li><li>The agent can list available tools or invoke a specific tool</li><li>Inbound authentication uses JWT OAuth tokens</li><li>AgentCore Gateway translates the MCP request into a REST API call</li></ol><h3>Authentication and Security</h3><ol><li>Inbound Authentication: JWT OAuth token to secure communications between the agent and Gateway</li><li>Outbound Authentication: API Key (or OAuth token) for calls to the weather API</li><li>AgentCore Identity: Manages tool authentication via OAuth 2.0 Egress (RFC 9728)</li><li>Amazon Cognito: Provides user authentication via OAuth 2.0 Ingress/OAuth2 1-PKCE (RFC 7591)</li></ol><h3>Implementation Demonstration</h3><p>Let’s walk through the four key implementation steps for our Mars Weather agent demo. This implementation demonstrates how to transform NASA’s OpenAPI specifications into MCP tools that our Strands agent can use.</p><h3>Prerequisites and Setup</h3><p><strong>System Requirements:</strong></p><ul><li>Python 3.11+</li><li>AWS account with access to Amazon Cognito, Bedrock, AgentCore, and EC2</li><li>Weather API key (available at <a href="https://api.nasa.gov/">https://api.nasa.gov/</a>)</li></ul><p><strong>Initialize UV:</strong></p><pre>uv init</pre><p>Packages Installation:</p><pre>uv add &quot;boto3&gt;=1.39.10&quot; &quot;botocore&gt;=1.39.10&quot; &quot;mcp[cli]&gt;=1.12.0&quot; &quot;requests&gt;=2.32.4&quot; &quot;strands-agents&gt;=1.0.1&quot;</pre><p><strong>Repository setup: </strong>Clone my <a href="https://github.com/WaelDataReply/AmazonAgentCore_GW_demo">GitHub</a> repo</p><p><strong>Environment Configuration:</strong><br>Create a .env file with required environment variables and ensure AWS credentials are properly configured.</p><p><strong>AWS Configuration: </strong>Ensure your AWS credentials are properly configured to access the required AWS services (Cognito, Bedrock, AgentCore, EC2, IAM).</p><p><strong>Additional Configuration:</strong></p><ul><li>Make sure your AWS user/role has appropriate permissions to work with all required AWS services.</li><li>Ensure your Bedrock access includes the Claude Sonnet 3.5 model.</li></ul><h3>Step 1: Amazon Cognito and Inbound Authentication</h3><p>The first step establishes our authentication infrastructure using Amazon Cognito to secure access to our AgentCore Gateway. This involves creating a Cognito User Pool, configuring OAuth 2.1 with PKCE support, and setting up the necessary resource servers and scopes.</p><p>Here’s how your AWS Console should look after running the script:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*C17gh-VrFJWAyJPdBJg9AA.png" /></figure><h3>Step 2: Creating the AgentCore Gateway Endpoint</h3><p>Next, we create our AgentCore Gateway endpoint that serves as the central MCP server hub. This gateway will bridge communications between our agent and external APIs, providing the standardized MCP interface while handling authentication and protocol translation.</p><p>Here’s how your AWS Console should look after running the script:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*b7JTmbQgjyqI1vCmJrOWIg.png" /></figure><h3>Step 3: Configuring the NASA API Target</h3><p>We configure our gateway by creating a target that points to Mars’s Weather API. This involves:</p><ul><li>Setting up API key credential providers for secure external API access</li><li>Uploading OpenAPI JSON specifications to Amazon S3</li><li>Creating gateway targets with appropriate outbound authentication configurations</li></ul><p>Here’s how your AWS Console should look after running the script:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Engh8kjrwZb0EQtvS5rHvg.png" /></figure><h3>Step 4: Implementing the Strands Client</h3><p>Finally, we create our Strands agent client that uses the AgentCore Gateway to access Mars weather data. The agent can now seamlessly interact with the NASA API through the standardized MCP interface, maintaining security and providing a consistent development experience.<br>Each step can be executed using uv run &lt;step-file.py&gt;, providing a clear and reproducible implementation path.</p><p>Here’s how your terminal should look after running the script:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CErHYZs0LfTa_6OvJzhvEg.png" /></figure><h3>Compliance of Bedrock AgentCore Gateway Architecture with MCP Authentication and Authorization Specifications (June 18th, 2025)</h3><h3>Mandatory Requirements (MUST)</h3><h4>OAuth 2.1 / PKCE (for public OAuth clients)</h4><p>AgentCore Gateway fully implements PKCE (Proof Key for Code Exchange) support in accordance with OAuth 2.1 specifications. This feature is integrated into the Inbound Authentication mechanism, allowing public clients to establish secure connections without exposing client secrets. For example, AgentCore Gateway utilizes Amazon Cognito as an identity provider, which fully supports OAuth 2.1 with PKCE.</p><h4>RFC 8414 — OAuth 2.0 Authorization Server Metadata</h4><p>AgentCore Gateway exposes a metadata endpoint compliant with RFC 8414, enabling automatic discovery of the authorization server’s capabilities. This includes authorization endpoints, token generation methods, and supported signature capabilities. This is demonstrated through the use of a Cognito discovery URL (cognito_discovery_url) which is RFC 8414 compliant. This URL is used in the configuration of the custom JWT authenticator.</p><h4>RFC 9728 — OAuth 2.0 Protected Resource Metadata</h4><p>AgentCore Gateway implements RFC 9728 by exposing the necessary metadata for clients to discover how to access protected resources. This allows clients to understand the authorization requirements for each resource. The integration with Cognito and the configuration of the resource server with specific scopes (gateway:read, gateway:write) demonstrate compliance with this RFC.</p><h3>Recommended Requirements (SHOULD)</h3><h4>RFC 7591 — OAuth 2.0 Dynamic Client Registration Protocol</h4><p>AgentCore Gateway offers partial support for dynamic client registration. Although the implementation is not fully compliant with RFC 7591, the service allows programmatic registration of clients via AWS APIs, which addresses the primary intention of this requirement.</p><blockquote>Note on partial support<em>: The current implementation does not provide a publicly accessible HTTP endpoint (/register) that accepts POST requests with JSON bodies containing client metadata and returns standardized JSON responses with registered client information. Instead, Cognito is used rather than a standardized HTTP endpoint.</em></blockquote><h4>RFC 8707 — Resource Indicators for OAuth 2.0</h4><p>AgentCore Gateway implements resource indicators in accordance with RFC 8707, allowing clients to specify target resources during authorization requests. This feature is particularly important in the Gateway architecture, where different targets (Lambda, API) may require different access levels. This is evidenced by the use of resource indicators in the scope string:</p><pre>scopeString = f&quot;{RESOURCE_SERVER_ID}/gateway:read {RESOURCE_SERVER_ID}/gateway:write&quot;</pre><p>This syntax complies with RFC 8707, where scopes are prefixed by the resource server identifier.</p><h3>Cost Structure and Pricing</h3><p>Bedrock AgentCore Gateway follows a pay-as-you-go pricing model, charging only for actual usage without upfront costs or minimum commitments. This approach makes it accessible for organizations of all sizes while scaling cost-effectively with usage.</p><h4>AgentCore Gateway Pricing</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-4zzArR_yjOpsMLnIA0Hng.png" /></figure><h4>AgentCore Identity Pricing</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TTkTiv4CGvOwrl4kQCtNFA.png" /></figure><h3>Conclusion and perspectives</h3><p>The journey toward production-ready agentic AI requires more than just powerful language models — it demands robust, secure, and scalable infrastructure that can bridge the gap between AI capabilities and enterprise requirements. Amazon Bedrock AgentCore Gateway represents a significant step forward in this evolution, transforming the theoretical promise of MCP into practical, enterprise-grade reality. Through our exploration of MCP fundamentals, enterprise adoption challenges, and practical implementation, several key insights emerge:</p><ul><li><strong>Standardization drives scale</strong>: The Model Context Protocol provides the standardization necessary for scalable AI agent deployments, but enterprise implementation requires sophisticated infrastructure and security considerations that go far beyond basic tutorials and demonstrations.</li><li><strong>Security cannot be an afterthought</strong>: Enterprise MCP adoption demands comprehensive security architectures with multi-layered authentication, proper authorization controls, and compliance with evolving specifications. AgentCore Gateway’s dual authentication model and OAuth 2.0 compliance demonstrate how these requirements can be met without compromising functionality.</li><li><strong>Managed services accelerate innovation</strong>: By abstracting the complexities of MCP server implementation, authentication protocols, and infrastructure management, AgentCore Gateway allows organizations to focus on what matters most — building intelligent applications that deliver business value.</li><li><strong>Production readiness requires more than code</strong>: The gap between demonstration code and production systems is significant. Features like multi-tenancy, service discovery, governance workflows, and enterprise-grade security are essential for successful MCP adoption at scale.</li></ul><p>With Amazon Bedrock AgentCore still in <strong>preview</strong>, several additional development opportunities exist:</p><ol><li>Leveraging <strong>AgentCore Runtime</strong> to host agents built on AWS Strands instead of using VMs (on EC2 or locally), enabling the entire agentic workflow to run on Bedrock AgentCore</li><li>Implementing <strong>GenAI observability</strong> on CloudWatch to monitor agent usage once AgentCore Runtime is established</li><li>Adding <strong>additional targets</strong> or MCP servers to the same AgentCore Gateway to test its routing capabilities</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d8386db65df3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[️ Understanding MCP Security Threats and Mitigations: A Layered Approach]]></title>
            <link>https://medium.com/@wael-saideni/%EF%B8%8F-understanding-mcp-security-threats-and-mitigations-a-layered-approach-078e8e6b54f5?source=rss-f849de33d418------2</link>
            <guid isPermaLink="false">https://medium.com/p/078e8e6b54f5</guid>
            <category><![CDATA[model-context-protocol]]></category>
            <category><![CDATA[security]]></category>
            <category><![CDATA[owasp]]></category>
            <category><![CDATA[generative-ai-use-cases]]></category>
            <category><![CDATA[anthropic-claude]]></category>
            <dc:creator><![CDATA[Wael SAIDENI]]></dc:creator>
            <pubDate>Tue, 22 Apr 2025 09:27:40 GMT</pubDate>
            <atom:updated>2025-04-22T09:27:40.971Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GyygSzut45cuDI86USs4kA.png" /><figcaption>© Amazon Nova Canvas 1.0</figcaption></figure><p>As artificial intelligence systems evolve beyond static model queries into real-time, tool-using agents, <strong>securing the infrastructure that powers them has never been more urgent</strong>. One of the most promising — but complex — advancements in this space is the <a href="https://modelcontextprotocol.io/introduction"><strong>Model Context Protocol (MCP)</strong></a>, introduced by Anthropic.</p><p>While MCP unlocks powerful integrations between foundation models, tools, and external data, it also introduces <strong>a novel attack surface</strong> with implications for data privacy, compliance, and platform integrity.</p><p>This blog post presents a <strong>comprehensive breakdown of MCP security threats and mitigations</strong>, drawing inspiration from the academic research paper:</p><blockquote><a href="https://arxiv.org/abs/2504.08623"><strong><em>Enterprise-Grade Security for the Model Context Protocol (MCP): Frameworks and Mitigation Strategies</em></strong></a></blockquote><p>This paper systematically explores the MCP architecture and translates theoretical vulnerabilities into <strong>real-world defense strategies</strong>. Building on this work, we use the <strong>MAESTRO (Multi-Agent Environment, Security, Threat, Risk, and Outcome) framework, an agentic AI threat modeling framework,</strong> to map out MCP’s risks across its entire stack — and propose mitigation strategies tailored for <strong>enterprise-grade security</strong>.</p><h3>📄 About the reference: Inspiration from a Foundational Research Paper</h3><blockquote>“The Model Context Protocol (MCP), introduced by Anthropic, provides a standardized framework for artificial intelligence (AI) systems to interact with external data sources and tools in real-time. While MCP offers significant advantages for AI integration and capability extension, it introduces novel security challenges that demand rigorous analysis and mitigation…”</blockquote><p>The paper serves as a blueprint for security-focused AI architecture, offering actionable insights into:</p><ul><li>Tool poisoning and Command-and-Control compromise</li><li>Identity and access control failures</li><li>Data leakage and model exploitation</li></ul><p>The primary contribution lies in turning <strong>abstract threats into concrete defense patterns</strong>, which we’ve synthesized below into a readable, structured format for technical teams and security architects.</p><h3>Why MCP Security Matters</h3><p>MCP enables AI agents to dynamically interact with tools, external APIs, and data in ways that feel like “thinking.” This capability comes with risk. An insecure MCP deployment could result in:</p><ul><li>Exfiltration of sensitive enterprise data</li><li>Execution of malicious tool commands</li><li>Compromised identity flows or C2 infrastructure</li></ul><p>Traditional web and cloud security models don’t fully address the <strong>behavioral and structural nuances of agentic AI systems</strong>. That’s why new frameworks like <strong>MAESTRO</strong> are so critical.</p><h3>🧱 MAESTRO: A Framework for AI System Threat Modeling</h3><p>The MAESTRO model introduces a <strong>seven-layered perspective</strong> to identify vulnerabilities in AI systems. When applied to MCP, it helps dissect risk across:</p><ul><li><strong>L1 — Foundation Models</strong></li><li><strong>L2 — Data Operations</strong></li><li><strong>L3 — Agent Frameworks</strong></li><li><strong>L4 — Deployment Infrastructure</strong></li><li><strong>L5 — Evaluation &amp; Observability</strong></li><li><strong>L6 — Security &amp; Compliance</strong></li><li><strong>L7 — Agent Ecosystem</strong></li></ul><p>This structure ensures full-spectrum visibility — crucial for designing secure, resilient MCP deployments.</p><h3>A Deep Dive: MCP Threats &amp; Mitigations by Component</h3><p>Here’s a full breakdown of <strong>MCP threat categories</strong>, mapped to the MAESTRO layers, and enriched with <strong>technical mitigation strategies</strong> drawn from the research paper and enterprise best practices.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Y-aWyUKiyOZebYpfb_Bo3w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*V_3IFpmSzf8qQZEIWzfA8Q.png" /><figcaption>Comprehensive MCP security threats and mitigations categorized by MCP component</figcaption></figure><h3>🔐 Defense-in-Depth Is the Only Way Forward</h3><p>Whether you’re building autonomous agents or enterprise AI workflows, <strong>MCP isn’t just a protocol — it’s an ecosystem</strong>. Every layer — from model inputs to server configurations — needs protection.</p><p>Here’s what that looks like in action:</p><ul><li>✅ Prompt sanitization (L1)</li><li>✅ DLP and output filtering (L2)</li><li>✅ Sandboxed tools and agent logic validation (L3)</li><li>✅ Config hardening and file integrity monitoring (L4)</li><li>✅ Auditable logs and anomaly detection (L5)</li><li>✅ MFA and scoped access (L6)</li><li>✅ Trusted registry enforcement and TLS validation (L7)</li></ul><h3>In a Nutshell</h3><p>Securing MCP is not a luxury — it’s a baseline requirement for responsible AI integration. Inspired by the detailed threat modeling in <em>Enterprise-Grade Security for the Model Context Protocol (MCP)</em>, this blog post has aimed to translate critical insights into actionable strategies for security teams and AI developers.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=078e8e6b54f5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Revolutionizing Multimodal Data Processing with Amazon Bedrock Data Automation]]></title>
            <link>https://medium.com/@wael-saideni/revolutionizing-multimodal-data-processing-with-amazon-bedrock-data-automation-ca9ff3c9a779?source=rss-f849de33d418------2</link>
            <guid isPermaLink="false">https://medium.com/p/ca9ff3c9a779</guid>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[bedrock]]></category>
            <category><![CDATA[multimodality]]></category>
            <category><![CDATA[generative-ai-use-cases]]></category>
            <dc:creator><![CDATA[Wael SAIDENI]]></dc:creator>
            <pubDate>Mon, 10 Mar 2025 12:28:07 GMT</pubDate>
            <atom:updated>2025-03-10T12:28:07.359Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UPrhiRU9-N5QQ8sXS5KcuA.png" /></figure><p>In today’s data-driven landscape, organizations grapple with vast amounts of unstructured content — documents, images, audio, and videos. Extracting meaningful insights from this multimodal data is often challenging, requiring intricate workflows and significant resources. Enter Amazon Bedrock Data Automation (BDA), a groundbreaking feature designed to streamline and enhance data processing capabilities.</p><h3>Understanding Amazon Bedrock Data Automation</h3><p>Amazon Bedrock Data Automation is a fully managed service that automates the extraction, transformation, and generation of insights from unstructured multimodal content. By leveraging advanced foundation models, BDA provides a unified API-driven experience, enabling developers to process documents, images, audio, and videos through a single interface. This consolidation eliminates the need to manage multiple AI models and services, thereby reducing complexity and accelerating development timelines.</p><h4><a href="https://aws.amazon.com/bedrock/bda/?nc1=h_ls">Amazon Bedrock Data Automation</a></h4><h3>Key Features and Benefits</h3><h3>1. Intelligent Document Processing (IDP)</h3><p>BDA automates complex document processing tasks such as classification, extraction, normalization, and validation. This capability transforms unstructured documents into structured, business-specific data outputs, facilitating seamless integration with existing workflows.</p><p><em>Example:</em> A financial institution can utilize BDA to process loan applications, automatically extracting relevant information and populating internal systems, thereby reducing manual data entry and associated errors.</p><h3>2. Media Analysis</h3><p>Beyond documents, BDA extends its capabilities to media content, including images, audio, and videos. It can generate summaries, detect objects, transcribe audio, and analyze visual and audible content for toxicity. This functionality is crucial for organizations aiming to monitor brand presence, ensure content compliance, or derive insights from multimedia assets.</p><p><em>Example:</em> A media company can leverage BDA to analyze video footage, automatically identifying key scenes, detecting logos, and generating metadata to enhance content discovery and user engagement.</p><h3>3. Customizable Blueprints</h3><p>BDA offers customizable blueprints, allowing developers to define specific output requirements using natural language or a schema editor. These blueprints specify fields to extract, data formats, and any necessary transformations, granting full control over the output and ensuring compatibility with downstream applications.</p><p><em>Example:</em> An insurance company can create a blueprint to extract policy numbers, claim amounts, and customer details from claim forms, standardizing the data for seamless integration into their claims processing system.</p><h3>Integration with AWS Services</h3><p>BDA seamlessly integrates with other AWS services, enhancing its functionality and ease of use. For instance, developers can utilize AWS Lambda and Amazon EventBridge to create event-driven workflows that trigger BDA processing upon data ingestion. Additionally, integration with Amazon Bedrock Knowledge Bases facilitates retrieval-augmented generation (RAG), enabling more relevant and context-aware responses in AI applications.</p><h3>Getting Started with BDA Using boto3</h3><p>For Python developers, AWS provides the Boto3 SDK to interact with BDA programmatically. Here’s a simplified example of how to set up a BDA project and process a document:</p><pre>#!/usr/bin/env python3<br>&quot;&quot;&quot;<br>AWS Bedrock Data Automation processing script for document analysis.<br>This script processes documents using AWS Bedrock Data Automation and extracts specific fields.<br>&quot;&quot;&quot;<br>import json<br>import sys<br>import time<br>from typing import Dict, Any, List, Optional<br>import argparse<br><br>import boto3<br>from botocore.client import BaseClient<br><br><br>class BedrockDataAutomation:<br>    &quot;&quot;&quot;<br>    A class to handle AWS Bedrock Data Automation for document analysis.<br>    &quot;&quot;&quot;<br>    # Configuration constants<br>    VERBOSE_LOGGING = True<br>    AWS_REGION = &#39;&lt;REGION&gt;&#39;<br>    STORAGE_BUCKET = &#39;&lt;BUCKET&gt;&#39;<br>    DOCUMENT_INPUT_DIR = &#39;Input&#39;<br>    DOCUMENT_OUTPUT_DIR = &#39;Output&#39;<br>    <br>    AUTOMATION_PROJECT_ID = &#39;&lt;PROJECT_ID&gt;&#39;<br>    BLUEPRINT = &#39;&lt;BLUEPRINT&gt;&#39;<br>    <br>    # Document fields to extract and display<br>    TARGET_FIELDS = [<br>        &#39;NAME_DETAILS/FIRST_NAME&#39;,<br>        &#39;NAME_DETAILS/MIDDLE_NAME&#39;,<br>        &#39;NAME_DETAILS/LAST_NAME&#39;,<br>        &#39;DATE_OF_BIRTH&#39;,<br>        &#39;DATE_OF_ISSUE&#39;,<br>        &#39;EXPIRATION_DATE&#39;<br>    ]<br><br>    def __init__(self):<br>        &quot;&quot;&quot;Initialize AWS clients and other parameters.&quot;&quot;&quot;<br>        self.bedrock_client = boto3.client(&#39;bedrock-data-automation-runtime&#39;, region_name=self.AWS_REGION)<br>        self.storage_client = boto3.client(&#39;s3&#39;, region_name=self.AWS_REGION)<br>        self.identity_client = boto3.client(&#39;sts&#39;)<br>        self.account_id = self._retrieve_aws_account_id()<br><br>    def _retrieve_aws_account_id(self) -&gt; str:<br>        &quot;&quot;&quot;<br>        Get the current AWS account ID.<br>        <br>        Returns:<br>            str: The AWS account ID<br>        &quot;&quot;&quot;<br>        return self.identity_client.get_caller_identity().get(&#39;Account&#39;)<br><br>    def debug_log(self, data: Any) -&gt; None:<br>        &quot;&quot;&quot;<br>        Log detailed information when verbose logging is enabled.<br>        <br>        Args:<br>            data: The data to log (dictionary or other object)<br>        &quot;&quot;&quot;<br>        if not self.VERBOSE_LOGGING:<br>            return<br>            <br>        if isinstance(data, dict):<br>            formatted_text = json.dumps(data, indent=4)<br>        else:<br>            formatted_text = str(data)<br>        print(formatted_text)<br><br>    def fetch_json_from_s3(self, s3_uri: str) -&gt; Dict[str, Any]:<br>        &quot;&quot;&quot;<br>        Download and parse a JSON object from S3.<br>        <br>        Args:<br>            s3_uri: The S3 URI of the JSON object<br>            <br>        Returns:<br>            dict: The parsed JSON content<br>        &quot;&quot;&quot;<br>        uri_parts = s3_uri.split(&#39;/&#39;)<br>        bucket_name = uri_parts[2]<br>        object_key = &#39;/&#39;.join(uri_parts[3:])<br>        <br>        response = self.storage_client.get_object(Bucket=bucket_name, Key=object_key)<br>        content = response[&#39;Body&#39;].read()<br>        return json.loads(content)<br><br>    def start_automation_job(self, input_uri: str, output_uri: str) -&gt; Dict[str, Any]:<br>        &quot;&quot;&quot;<br>        Start an asynchronous Bedrock Data Automation job.<br>        <br>        Args:<br>            input_uri: S3 URI for the input file<br>            output_uri: S3 URI for the output directory<br>            <br>        Returns:<br>            dict: Response from the API call<br>        &quot;&quot;&quot;<br>        automation_arn = f&quot;arn:aws:bedrock:{self.AWS_REGION}:{self.account_id}:data-automation-project/{self.AUTOMATION_PROJECT_ID}&quot;<br>        <br>        request_params = {<br>            &#39;inputConfiguration&#39;: {<br>                &#39;s3Uri&#39;: input_uri<br>            },<br>            &#39;outputConfiguration&#39;: {<br>                &#39;s3Uri&#39;: output_uri<br>            },<br>            &#39;dataAutomationConfiguration&#39;: {<br>                &#39;dataAutomationProjectArn&#39;: automation_arn<br>            },<br>            &#39;dataAutomationProfileArn&#39;: f&quot;arn:aws:bedrock:{self.AWS_REGION}:{self.account_id}:data-automation-profile/us.data-automation-v1&quot;<br>        }<br><br>        response = self.bedrock_client.invoke_data_automation_async(**request_params)<br>        self.debug_log(response)<br>        return response<br><br>    def monitor_automation_job(self, invocation_arn: str, poll_interval: int = 1) -&gt; Dict[str, Any]:<br>        &quot;&quot;&quot;<br>        Poll and wait for a data automation job to complete.<br>        <br>        Args:<br>            invocation_arn: The ARN of the job invocation<br>            poll_interval: How often to check the status (in seconds)<br>            <br>        Returns:<br>            dict: The final job status response<br>        &quot;&quot;&quot;<br>        while True:<br>            status_response = self.bedrock_client.get_data_automation_status(<br>                invocationArn=invocation_arn<br>            )<br>            current_status = status_response[&#39;status&#39;]<br>            <br>            if current_status not in [&#39;Created&#39;, &#39;InProgress&#39;]:<br>                print(f&quot; {current_status}&quot;)<br>                return status_response<br>                <br>            print(&quot;.&quot;, end=&#39;&#39;, flush=True)<br>            time.sleep(poll_interval)<br><br>    def display_document_analysis(self, result: Dict[str, Any]) -&gt; None:<br>        &quot;&quot;&quot;<br>        Display the document analysis results.<br>        <br>        Args:<br>            result: The document analysis data<br>        &quot;&quot;&quot;<br>        print(f&quot;Number of pages: {result[&#39;metadata&#39;][&#39;number_of_pages&#39;]}&quot;)<br>        <br>        for page in result[&#39;pages&#39;]:<br>            print(f&quot;- Page {page[&#39;page_index&#39;]}&quot;)<br>            <br>            if &#39;text&#39; in page[&#39;representation&#39;]:<br>                print(f&quot;{page[&#39;representation&#39;][&#39;text&#39;]}&quot;)<br>                <br>            if &#39;markdown&#39; in page[&#39;representation&#39;]:<br>                print(f&quot;{page[&#39;representation&#39;][&#39;markdown&#39;]}&quot;)<br><br>    def display_video_analysis(self, result: Dict[str, Any]) -&gt; None:<br>        &quot;&quot;&quot;<br>        Display the video analysis results.<br>        <br>        Args:<br>            result: The video analysis data<br>        &quot;&quot;&quot;<br>        print(f&quot;Duration: {result[&#39;metadata&#39;][&#39;duration_millis&#39;]} ms&quot;)<br>        print(f&quot;Summary: {result[&#39;video&#39;][&#39;summary&#39;]}&quot;)<br>        <br>        stats = result[&#39;statistics&#39;]<br>        print(&quot;Statistics:&quot;)<br>        print(f&quot;- Speaker count: {stats[&#39;speaker_count&#39;]}&quot;)<br>        print(f&quot;- Scene count: {stats[&#39;scene_count&#39;]}&quot;)<br>        print(f&quot;- Shot count: {stats[&#39;shot_count&#39;]}&quot;)<br>        <br>        for scene in result[&#39;scenes&#39;]:<br>            print(f&quot;Scene {scene[&#39;scene_index&#39;]} {scene[&#39;start_timecode_smpte&#39;]}-{scene[&#39;end_timecode_smpte&#39;]} ({scene[&#39;duration_millis&#39;]} ms)&quot;)<br>            <br>            if &#39;summary&#39; in scene:<br>                print(f&quot;- Scene summary: {scene[&#39;summary&#39;]}&quot;)<br><br>    def display_field_value(self, field_path: str, custom_result: Dict[str, Any]) -&gt; None:<br>        &quot;&quot;&quot;<br>        Display a specific field value and its confidence.<br>        <br>        Args:<br>            field_path: Path to the field, possibly containing a group path<br>            custom_result: The custom extraction result<br>        &quot;&quot;&quot;<br>        inference = custom_result[&#39;inference_result&#39;]<br>        confidence_data = custom_result[&#39;explainability_info&#39;][0]<br>        <br>        if &#39;/&#39; in field_path:<br>            # Handle fields within groups<br>            group_name, field_name = field_path.split(&#39;/&#39;)<br>            inference = inference[group_name]<br>            confidence_data = confidence_data[group_name]<br>        else:<br>            field_name = field_path<br>            <br>        field_value = inference[field_name]<br>        confidence_score = confidence_data[field_name][&#39;confidence&#39;]<br>        <br>        display_value = field_value if field_value else &#39;&lt;EMPTY&gt;&#39;<br>        print(f&#39;{field_name}: {display_value}  Confidence: {confidence_score}&#39;)<br><br>    def display_extracted_fields(self, custom_result: Dict[str, Any]) -&gt; None:<br>        &quot;&quot;&quot;<br>        Display the custom extraction results.<br>        <br>        Args:<br>            custom_result: The custom field extraction data<br>        &quot;&quot;&quot;<br>        matched_blueprint = custom_result[&#39;matched_blueprint&#39;][&#39;name&#39;]<br>        self.debug_log(custom_result)<br>        <br>        print(&#39;\n- Custom output&#39;)<br>        print(f&quot;Matched blueprint: {matched_blueprint}  Confidence: {custom_result[&#39;matched_blueprint&#39;][&#39;confidence&#39;]}&quot;)<br>        print(f&quot;Document class: {custom_result[&#39;document_class&#39;][&#39;type&#39;]}&quot;)<br>        <br>        if matched_blueprint == self.BLUEPRINT:<br>            print(&#39;\n- Fields&#39;)<br>            for field_path in self.TARGET_FIELDS:<br>                self.display_field_value(field_path, custom_result)<br><br>    def display_job_results(self, metadata_uri: str) -&gt; None:<br>        &quot;&quot;&quot;<br>        Display the complete results from a data automation job.<br>        <br>        Args:<br>            metadata_uri: S3 URI of the job metadata file<br>        &quot;&quot;&quot;<br>        job_data = self.fetch_json_from_s3(metadata_uri)<br>        self.debug_log(job_data)<br><br>        for segment in job_data[&#39;output_metadata&#39;]:<br>            asset_id = segment[&#39;asset_id&#39;]<br>            print(f&#39;\nAsset ID: {asset_id}&#39;)<br><br>            for segment_data in segment[&#39;segment_metadata&#39;]:<br>                # Process standard output<br>                standard_output_path = segment_data[&#39;standard_output_path&#39;]<br>                standard_result = self.fetch_json_from_s3(standard_output_path)<br>                self.debug_log(standard_result)<br>                <br>                print(&#39;\n- Standard output&#39;)<br>                content_type = standard_result[&#39;metadata&#39;][&#39;semantic_modality&#39;]<br>                print(f&quot;Semantic modality: {content_type}&quot;)<br>                <br>                if content_type == &#39;DOCUMENT&#39;:<br>                    self.display_document_analysis(standard_result)<br>                elif content_type == &#39;VIDEO&#39;:<br>                    self.display_video_analysis(standard_result)<br>                    <br>                # Process custom output if available<br>                if &#39;custom_output_status&#39; in segment_data and segment_data[&#39;custom_output_status&#39;] == &#39;MATCH&#39;:<br>                    custom_output_path = segment_data[&#39;custom_output_path&#39;]<br>                    custom_result = self.fetch_json_from_s3(custom_output_path)<br>                    self.display_extracted_fields(custom_result)<br><br>    def process_document(self, document_filename: str) -&gt; None:<br>        &quot;&quot;&quot;<br>        Process a document with Bedrock Data Automation.<br>        <br>        Args:<br>            document_filename: The name of the document file to process<br>        &quot;&quot;&quot;<br>        input_uri = f&quot;s3://{self.STORAGE_BUCKET}/{self.DOCUMENT_INPUT_DIR}/{document_filename}&quot;<br>        output_uri = f&quot;s3://{self.STORAGE_BUCKET}/{self.DOCUMENT_OUTPUT_DIR}&quot;<br><br>        print(f&quot;Invoking Bedrock Data Automation for &#39;{document_filename}&#39;&quot;, end=&#39;&#39;, flush=True)<br><br>        # Launch and monitor job<br>        job_response = self.start_automation_job(input_uri, output_uri)<br>        job_status = self.monitor_automation_job(job_response[&#39;invocationArn&#39;])<br><br>        # Process results if successful<br>        if job_status[&#39;status&#39;] == &#39;Success&#39;:<br>            result_metadata_uri = job_status[&#39;outputConfiguration&#39;][&#39;s3Uri&#39;]<br>            self.display_job_results(result_metadata_uri)<br>        else:<br>            print(f&quot;Job failed with status: {job_status[&#39;status&#39;]}&quot;)<br>            if &#39;error&#39; in job_status:<br>                print(f&quot;Error: {job_status[&#39;error&#39;]}&quot;)<br><br><br>def parse_arguments() -&gt; argparse.Namespace:<br>    &quot;&quot;&quot;<br>    Parse command line arguments.<br>    <br>    Returns:<br>        argparse.Namespace: The parsed arguments<br>    &quot;&quot;&quot;<br>    parser = argparse.ArgumentParser(<br>        description=&#39;Process documents with AWS Bedrock Data Automation&#39;<br>    )<br>    <br>    parser.add_argument(<br>        &#39;filename&#39;, <br>        help=&#39;The filename of the document to process&#39;<br>    )<br>    <br>    parser.add_argument(<br>        &#39;-v&#39;, &#39;--verbose&#39;, <br>        action=&#39;store_true&#39;, <br>        help=&#39;Enable verbose logging&#39;<br>    )<br>    <br>    return parser.parse_args()<br><br><br>def main() -&gt; None:<br>    &quot;&quot;&quot;<br>    Main function to process documents with Bedrock Data Automation.<br>    &quot;&quot;&quot;<br>    args = parse_arguments()<br>    <br>    # Initialize the data automation processor<br>    processor = BedrockDataAutomation()<br>    <br>    # Set verbose logging if specified<br>    if args.verbose:<br>        processor.VERBOSE_LOGGING = True<br>    <br>    # Process the specified document<br>    processor.process_document(args.filename)<br><br><br>if __name__ == &quot;__main__&quot;:<br>    main()</pre><p>This script has been tested using a French driving license document uploaded to the S3 bucket.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/450/1*BKFjHl1wPD6AckDgx2R6zw.jpeg" /><figcaption>The test document</figcaption></figure><p>Since I had already created a custom blueprint, we had two main output folders: one for custom output and another for standard output.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kqfXoBwLnoZai3XzmJsGJA.png" /><figcaption>The custom blueprint created</figcaption></figure><p>The custom output file containing the specified custom fields:</p><pre>{<br>    &quot;matched_blueprint&quot;: {<br>        &quot;arn&quot;: &quot;arn:aws:bedrock:us-east-1:555043101106:blueprint/0c87fce86dcc&quot;,<br>        &quot;name&quot;: &quot;FR-Driver-License-blueprint&quot;,<br>        &quot;confidence&quot;: 1<br>    },<br>    &quot;document_class&quot;: {<br>        &quot;type&quot;: &quot;default&quot;<br>    },<br>    &quot;split_document&quot;: {<br>        &quot;page_indices&quot;: [<br>            0<br>        ]<br>    },<br>    &quot;inference_result&quot;: {<br>        &quot;dateofbirth&quot;: &quot;14.07.1981&quot;,<br>        &quot;expirydate&quot;: &quot;31.12.2018&quot;,<br>        &quot;licensenumber&quot;: &quot;13AA00002&quot;,<br>        &quot;firstname&quot;: &quot;Paul&quot;,<br>        &quot;address&quot;: {<br>            &quot;city&quot;: &quot;Utopia&quot;,<br>            &quot;street&quot;: &quot;99999&quot;<br>        },<br>        &quot;signature&quot;: true,<br>        &quot;categories&quot;: [<br>            &quot;AM/A/A1/B1/B/BE/DE/D&quot;<br>        ],<br>        &quot;placeofbirth&quot;: &quot;Utopia city&quot;,<br>        &quot;issuedate&quot;: &quot;01.01.2013&quot;,<br>        &quot;lastname&quot;: &quot;MARTIN&quot;<br>    },<br>    &quot;explainability_info&quot;: [<br>        {<br>            &quot;dateofbirth&quot;: {<br>                &quot;success&quot;: true,<br>                &quot;confidence&quot;: 0.7265625,<br>                &quot;geometry&quot;: [<br>                    {<br>                        &quot;boundingBox&quot;: {<br>                            &quot;top&quot;: 0.32887621840048364,<br>                            &quot;left&quot;: 0.33074578667953614,<br>                            &quot;width&quot;: 0.12745223938639222,<br>                            &quot;height&quot;: 0.04162778970125186<br>                        },<br>                        &quot;vertices&quot;: [<br>                            {<br>                                &quot;x&quot;: 0.33074659205577106,<br>                                &quot;y&quot;: 0.32887621840048364<br>                            },<br>                            {<br>                                &quot;x&quot;: 0.45819802606592835,<br>                                &quot;y&quot;: 0.3288771954499967<br>                            },<br>                            {<br>                                &quot;x&quot;: 0.45819716535422306,<br>                                &quot;y&quot;: 0.3705040081017355<br>                            },<br>                            {<br>                                &quot;x&quot;: 0.33074578667953614,<br>                                &quot;y&quot;: 0.3705030671169912<br>                            }<br>                        ],<br>                        &quot;page&quot;: 1<br>                    }<br>                ],<br>                &quot;type&quot;: &quot;string&quot;,<br>                &quot;value&quot;: &quot;14.07.1981&quot;<br>            },<br>            &quot;expirydate&quot;: {<br>                &quot;success&quot;: true,<br>                &quot;confidence&quot;: 0.7734375,<br>                &quot;geometry&quot;: [<br>                    {<br>                        &quot;boundingBox&quot;: {<br>                            &quot;top&quot;: 0.4733457099553516,<br>                            &quot;left&quot;: 0.3300053563233053,<br>                            &quot;width&quot;: 0.5694970752196041,<br>                            &quot;height&quot;: 0.2355607003590428<br>                        },<br>                        &quot;vertices&quot;: [<br>                            {<br>                                &quot;x&quot;: 0.33000991197927354,<br>                                &quot;y&quot;: 0.4733457099553516<br>                            },<br>                            {<br>                                &quot;x&quot;: 0.8995024315429094,<br>                                &quot;y&quot;: 0.47334951644209283<br>                            },<br>                            {<br>                                &quot;x&quot;: 0.8994964767177936,<br>                                &quot;y&quot;: 0.7089064103143944<br>                            },<br>                            {<br>                                &quot;x&quot;: 0.3300053563233053,<br>                                &quot;y&quot;: 0.708903515731148<br>                            }<br>                        ],<br>                        &quot;page&quot;: 1<br>                    }<br>                ],<br>                &quot;type&quot;: &quot;string&quot;,<br>                &quot;value&quot;: &quot;31.12.2018&quot;<br>            },<br>            &quot;licensenumber&quot;: {<br>                &quot;success&quot;: true,<br>                &quot;confidence&quot;: 0.703125,<br>                &quot;geometry&quot;: [<br>                    {<br>                        &quot;boundingBox&quot;: {<br>                            &quot;top&quot;: 0.5448440168274151,<br>                            &quot;left&quot;: 0.05733383025755758,<br>                            &quot;width&quot;: 0.8861995040807235,<br>                            &quot;height&quot;: 0.3369341441621888<br>                        },<br>                        &quot;vertices&quot;: [<br>                            {<br>                                &quot;x&quot;: 0.05733938822345927,<br>                                &quot;y&quot;: 0.5448440168274151<br>                            },<br>                            {<br>                                &quot;x&quot;: 0.943533334338281,<br>                                &quot;y&quot;: 0.5448495094260564<br>                            },<br>                            {<br>                                &quot;x&quot;: 0.9435246621169595,<br>                                &quot;y&quot;: 0.8817781609896039<br>                            },<br>                            {<br>                                &quot;x&quot;: 0.05733383025755758,<br>                                &quot;y&quot;: 0.881774698087482<br>                            }<br>                        ],<br>                        &quot;page&quot;: 1<br>                    }<br>                ],<br>                &quot;type&quot;: &quot;string&quot;,<br>                &quot;value&quot;: &quot;13AA00002&quot;<br>            },<br>            &quot;firstname&quot;: {<br>                &quot;success&quot;: true,<br>                &quot;confidence&quot;: 0.7265625,<br>                &quot;geometry&quot;: [<br>                    {<br>                        &quot;boundingBox&quot;: {<br>                            &quot;top&quot;: 0.24758131721507393,<br>                            &quot;left&quot;: 0.329524191923781,<br>                            &quot;width&quot;: 0.08537626354141581,<br>                            &quot;height&quot;: 0.042851917077433854<br>                        },<br>                        &quot;vertices&quot;: [<br>                            {<br>                                &quot;x&quot;: 0.32952502044227616,<br>                                &quot;y&quot;: 0.24758131721507393<br>                            },<br>                            {<br>                                &quot;x&quot;: 0.4149004554651968,<br>                                &quot;y&quot;: 0.2475820188875337<br>                            },<br>                            {<br>                                &quot;x&quot;: 0.4148995887890684,<br>                                &quot;y&quot;: 0.2904332342925078<br>                            },<br>                            {<br>                                &quot;x&quot;: 0.329524191923781,<br>                                &quot;y&quot;: 0.29043255748923436<br>                            }<br>                        ],<br>                        &quot;page&quot;: 1<br>                    }<br>                ],<br>                &quot;type&quot;: &quot;string&quot;,<br>                &quot;value&quot;: &quot;Paul&quot;<br>            },<br>            &quot;address&quot;: {<br>                &quot;city&quot;: {<br>                    &quot;success&quot;: true,<br>                    &quot;confidence&quot;: 0.7734375,<br>                    &quot;geometry&quot;: [<br>                        {<br>                            &quot;boundingBox&quot;: {<br>                                &quot;top&quot;: 0.41017276576176254,<br>                                &quot;left&quot;: 0.5829556852217668,<br>                                &quot;width&quot;: 0.06164699997867318,<br>                                &quot;height&quot;: 0.039178500046124054<br>                            },<br>                            &quot;vertices&quot;: [<br>                                {<br>                                    &quot;x&quot;: 0.5829565462826143,<br>                                    &quot;y&quot;: 0.41017276576176254<br>                                },<br>                                {<br>                                    &quot;x&quot;: 0.64460268520044,<br>                                    &quot;y&quot;: 0.4101732042777953<br>                                },<br>                                {<br>                                    &quot;x&quot;: 0.6446017989492443,<br>                                    &quot;y&quot;: 0.4493512658078866<br>                                },<br>                                {<br>                                    &quot;x&quot;: 0.5829556852217668,<br>                                    &quot;y&quot;: 0.44935084370962813<br>                                }<br>                            ],<br>                            &quot;page&quot;: 1<br>                        }<br>                    ],<br>                    &quot;type&quot;: &quot;string&quot;,<br>                    &quot;value&quot;: &quot;Utopia&quot;<br>                },<br>                &quot;street&quot;: {<br>                    &quot;success&quot;: true,<br>                    &quot;confidence&quot;: 0.30078125,<br>                    &quot;geometry&quot;: [<br>                        {<br>                            &quot;boundingBox&quot;: {<br>                                &quot;top&quot;: 0.4084580443523725,<br>                                &quot;left&quot;: 0.4875509863124885,<br>                                &quot;width&quot;: 0.0914915552610489,<br>                                &quot;height&quot;: 0.03599551443461074<br>                            },<br>                            &quot;vertices&quot;: [<br>                                {<br>                                    &quot;x&quot;: 0.4875517415945916,<br>                                    &quot;y&quot;: 0.4084580443523725<br>                                },<br>                                {<br>                                    &quot;x&quot;: 0.5790425415735374,<br>                                    &quot;y&quot;: 0.408458696232579<br>                                },<br>                                {<br>                                    &quot;x&quot;: 0.5790417519432673,<br>                                    &quot;y&quot;: 0.4444535587869832<br>                                },<br>                                {<br>                                    &quot;x&quot;: 0.4875509863124885,<br>                                    &quot;y&quot;: 0.4444529292931238<br>                                }<br>                            ],<br>                            &quot;page&quot;: 1<br>                        }<br>                    ],<br>                    &quot;type&quot;: &quot;string&quot;,<br>                    &quot;value&quot;: &quot;99999&quot;<br>                }<br>            },<br>            &quot;signature&quot;: {<br>                &quot;success&quot;: true,<br>                &quot;confidence&quot;: 0.921875,<br>                &quot;geometry&quot;: [<br>                    {<br>                        &quot;boundingBox&quot;: {<br>                            &quot;top&quot;: 0.6300563605198929,<br>                            &quot;left&quot;: 0.05733383025755758,<br>                            &quot;width&quot;: 0.886197310809689,<br>                            &quot;height&quot;: 0.25172180046971104<br>                        },<br>                        &quot;vertices&quot;: [<br>                            {<br>                                &quot;x&quot;: 0.05733798257141572,<br>                                &quot;y&quot;: 0.6300563605198929<br>                            },<br>                            {<br>                                &quot;x&quot;: 0.9435311410672466,<br>                                &quot;y&quot;: 0.6300613397914284<br>                            },<br>                            {<br>                                &quot;x&quot;: 0.9435246621169595,<br>                                &quot;y&quot;: 0.8817781609896039<br>                            },<br>                            {<br>                                &quot;x&quot;: 0.05733383025755758,<br>                                &quot;y&quot;: 0.881774698087482<br>                            }<br>                        ],<br>                        &quot;page&quot;: 1<br>                    }<br>                ],<br>                &quot;type&quot;: &quot;boolean&quot;,<br>                &quot;value&quot;: true<br>            },<br>            &quot;categories&quot;: [<br>                {<br>                    &quot;confidence&quot;: 0.73046875,<br>                    &quot;geometry&quot;: [<br>                        {<br>                            &quot;boundingBox&quot;: {<br>                                &quot;top&quot;: 0.7049845370737874,<br>                                &quot;left&quot;: 0.09773023500677216,<br>                                &quot;width&quot;: 0.21857604310227538,<br>                                &quot;height&quot;: 0.04750432613285471<br>                            },<br>                            &quot;vertices&quot;: [<br>                                {<br>                                    &quot;x&quot;: 0.09773103862898942,<br>                                    &quot;y&quot;: 0.7049845370737874<br>                                },<br>                                {<br>                                    &quot;x&quot;: 0.31630627810904755,<br>                                    &quot;y&quot;: 0.7049856538590139<br>                                },<br>                                {<br>                                    &quot;x&quot;: 0.31630536619092725,<br>                                    &quot;y&quot;: 0.7524888632066421<br>                                },<br>                                {<br>                                    &quot;x&quot;: 0.09773023500677216,<br>                                    &quot;y&quot;: 0.7524878170022897<br>                                }<br>                            ],<br>                            &quot;page&quot;: 1<br>                        }<br>                    ],<br>                    &quot;type&quot;: &quot;string&quot;,<br>                    &quot;value&quot;: &quot;AM/A/A1/B1/B/BE/DE/D&quot;<br>                }<br>            ],<br>            &quot;placeofbirth&quot;: {<br>                &quot;success&quot;: true,<br>                &quot;confidence&quot;: 0.8203125,<br>                &quot;geometry&quot;: [<br>                    {<br>                        &quot;boundingBox&quot;: {<br>                            &quot;top&quot;: 0.32593890416673454,<br>                            &quot;left&quot;: 0.4677360246100543,<br>                            &quot;width&quot;: 0.17686856603290885,<br>                            &quot;height&quot;: 0.12341236164115205<br>                        },<br>                        &quot;vertices&quot;: [<br>                            {<br>                                &quot;x&quot;: 0.4677385886454456,<br>                                &quot;y&quot;: 0.32593890416673454<br>                            },<br>                            {<br>                                &quot;x&quot;: 0.6446045906429632,<br>                                &quot;y&quot;: 0.3259402635636996<br>                            },<br>                            {<br>                                &quot;x&quot;: 0.6446017989492443,<br>                                &quot;y&quot;: 0.4493512658078866<br>                            },<br>                            {<br>                                &quot;x&quot;: 0.4677360246100543,<br>                                &quot;y&quot;: 0.44935005478693507<br>                            }<br>                        ],<br>                        &quot;page&quot;: 1<br>                    }<br>                ],<br>                &quot;type&quot;: &quot;string&quot;,<br>                &quot;value&quot;: &quot;Utopia city&quot;<br>            },<br>            &quot;issuedate&quot;: {<br>                &quot;success&quot;: true,<br>                &quot;confidence&quot;: 0.75390625,<br>                &quot;geometry&quot;: [<br>                    {<br>                        &quot;boundingBox&quot;: {<br>                            &quot;top&quot;: 0.40062127462825564,<br>                            &quot;left&quot;: 0.32805348619885244,<br>                            &quot;width&quot;: 0.12794140367791462,<br>                            &quot;height&quot;: 0.04162766937800638<br>                        },<br>                        &quot;vertices&quot;: [<br>                            {<br>                                &quot;x&quot;: 0.32805429040557044,<br>                                &quot;y&quot;: 0.40062127462825564<br>                            },<br>                            {<br>                                &quot;x&quot;: 0.45599488987676706,<br>                                &quot;y&quot;: 0.40062219303120566<br>                            },<br>                            {<br>                                &quot;x&quot;: 0.4559940301222379,<br>                                &quot;y&quot;: 0.442248944006262<br>                            },<br>                            {<br>                                &quot;x&quot;: 0.32805348619885244,<br>                                &quot;y&quot;: 0.44224806180641807<br>                            }<br>                        ],<br>                        &quot;page&quot;: 1<br>                    }<br>                ],<br>                &quot;type&quot;: &quot;string&quot;,<br>                &quot;value&quot;: &quot;01.01.2013&quot;<br>            },<br>            &quot;lastname&quot;: {<br>                &quot;success&quot;: true,<br>                &quot;confidence&quot;: 0.87109375,<br>                &quot;geometry&quot;: [<br>                    {<br>                        &quot;boundingBox&quot;: {<br>                            &quot;top&quot;: 0.16212358868302798,<br>                            &quot;left&quot;: 0.32977041877827856,<br>                            &quot;width&quot;: 0.14800134745864363,<br>                            &quot;height&quot;: 0.04566851531107169<br>                        },<br>                        &quot;vertices&quot;: [<br>                            {<br>                                &quot;x&quot;: 0.32977130186034226,<br>                                &quot;y&quot;: 0.16212358868302798<br>                            },<br>                            {<br>                                &quot;x&quot;: 0.4777717662369222,<br>                                &quot;y&quot;: 0.16212489102532773<br>                            },<br>                            {<br>                                &quot;x&quot;: 0.4777708126607935,<br>                                &quot;y&quot;: 0.20779210399409967<br>                            },<br>                            {<br>                                &quot;x&quot;: 0.32977041877827856,<br>                                &quot;y&quot;: 0.2077908475963125<br>                            }<br>                        ],<br>                        &quot;page&quot;: 1<br>                    }<br>                ],<br>                &quot;type&quot;: &quot;string&quot;,<br>                &quot;value&quot;: &quot;MARTIN&quot;<br>            }<br>        }<br>    ]<br>}</pre><p>the standard output file:</p><pre>{<br>    &quot;metadata&quot;: {<br>        &quot;asset_id&quot;: &quot;0&quot;,<br>        &quot;logical_subdocument_id&quot;: &quot;0&quot;,<br>        &quot;semantic_modality&quot;: &quot;DOCUMENT&quot;,<br>        &quot;s3_bucket&quot;: &quot;drf-bda-genai-application-us-east-1-dev&quot;,<br>        &quot;s3_key&quot;: &quot;BDA/Input/permis.jpg&quot;,<br>        &quot;number_of_pages&quot;: 1,<br>        &quot;start_page_index&quot;: 0,<br>        &quot;end_page_index&quot;: 0<br>    },<br>    &quot;document&quot;: {<br>        &quot;statistics&quot;: {<br>            &quot;element_count&quot;: 7,<br>            &quot;table_count&quot;: 0,<br>            &quot;figure_count&quot;: 2<br>        }<br>    },<br>    &quot;pages&quot;: [<br>        {<br>            &quot;id&quot;: &quot;6fd9fb4c-bec3-4b32-bb2a-8468be11743c&quot;,<br>            &quot;page_index&quot;: 0,<br>            &quot;representation&quot;: {<br>                &quot;markdown&quot;: &quot;**PERMIS DE CONDUIRE R\u00c9PUBLIQUE FRAN\u00c7AISE**\n\n![IMAGE](./27338375-1d07-4325-a8cb-a36a8ed6fb50.png)\n\nF\n\n- 1. \&quot;MARTIN\n- 2. ^Paul\n- 3. 14.07.1981 (Utopia city)\n- 4a 01.01.2013 4c.99999 Utopia\n- 4b 31.12.2018\n- 5. 13AA00002\n- 7. Signature\n\n![IMAGE](./1085b036-1ddb-486e-a009-b2b86cc837c9.png)\n\n31/12/2018\n\n9. AM/A/A1/B1/B/BE/DE/D\n\n**D1FRA13AA000026181231MARTIN&lt;&lt;9**&quot;<br>            },<br>            &quot;statistics&quot;: {<br>                &quot;element_count&quot;: 7,<br>                &quot;table_count&quot;: 0,<br>                &quot;figure_count&quot;: 2<br>            },<br>            &quot;asset_metadata&quot;: {<br>                &quot;rectified_image_width_pixels&quot;: 449,<br>                &quot;rectified_image_height_pixels&quot;: 284,<br>                &quot;corners&quot;: [<br>                    [<br>                        0.0002576206127802531,<br>                        0.00026438306821020027<br>                    ],<br>                    [<br>                        1.0000262451171875,<br>                        0.00027428057632948225<br>                    ],<br>                    [<br>                        0.9999999321831597,<br>                        0.9996973941200658<br>                    ],<br>                    [<br>                        0.0002417294184366862,<br>                        0.9996941817434211<br>                    ]<br>                ]<br>            }<br>        }<br>    ],<br>    &quot;elements&quot;: [<br>        {<br>            &quot;type&quot;: &quot;TEXT&quot;,<br>            &quot;id&quot;: &quot;18cb91de-4789-470b-97af-bbaf8b913681&quot;,<br>            &quot;reading_order&quot;: 0,<br>            &quot;page_indices&quot;: [<br>                0<br>            ],<br>            &quot;representation&quot;: {<br>                &quot;markdown&quot;: &quot;**PERMIS DE CONDUIRE R\u00c9PUBLIQUE FRAN\u00c7AISE**&quot;<br>            },<br>            &quot;sub_type&quot;: &quot;PARAGRAPH&quot;<br>        },<br>        {<br>            &quot;type&quot;: &quot;FIGURE&quot;,<br>            &quot;id&quot;: &quot;27338375-1d07-4325-a8cb-a36a8ed6fb50&quot;,<br>            &quot;reading_order&quot;: 1,<br>            &quot;page_indices&quot;: [<br>                0<br>            ],<br>            &quot;representation&quot;: {<br>                &quot;markdown&quot;: &quot;![IMAGE](./27338375-1d07-4325-a8cb-a36a8ed6fb50.png)\n\nF&quot;<br>            },<br>            &quot;sub_type&quot;: &quot;IMAGE&quot;,<br>            &quot;title&quot;: &quot;&quot;<br>        },<br>        {<br>            &quot;type&quot;: &quot;TEXT&quot;,<br>            &quot;id&quot;: &quot;27e1fd77-e725-483f-95a2-f1e8911bf121&quot;,<br>            &quot;reading_order&quot;: 2,<br>            &quot;page_indices&quot;: [<br>                0<br>            ],<br>            &quot;representation&quot;: {<br>                &quot;markdown&quot;: &quot;- 1. \&quot;MARTIN\n- 2. ^Paul\n- 3. 14.07.1981 (Utopia city)\n- 4a 01.01.2013 4c.99999 Utopia\n- 4b 31.12.2018\n- 5. 13AA00002\n- 7. Signature&quot;<br>            },<br>            &quot;sub_type&quot;: &quot;LIST&quot;<br>        },<br>        {<br>            &quot;type&quot;: &quot;FIGURE&quot;,<br>            &quot;id&quot;: &quot;1085b036-1ddb-486e-a009-b2b86cc837c9&quot;,<br>            &quot;reading_order&quot;: 3,<br>            &quot;page_indices&quot;: [<br>                0<br>            ],<br>            &quot;representation&quot;: {<br>                &quot;markdown&quot;: &quot;![IMAGE](./1085b036-1ddb-486e-a009-b2b86cc837c9.png)&quot;<br>            },<br>            &quot;sub_type&quot;: &quot;IMAGE&quot;,<br>            &quot;title&quot;: &quot;&quot;<br>        },<br>        {<br>            &quot;type&quot;: &quot;TEXT&quot;,<br>            &quot;id&quot;: &quot;26860370-b21a-417a-94aa-3511fcc00795&quot;,<br>            &quot;reading_order&quot;: 4,<br>            &quot;page_indices&quot;: [<br>                0<br>            ],<br>            &quot;representation&quot;: {<br>                &quot;markdown&quot;: &quot;31/12/2018&quot;<br>            },<br>            &quot;sub_type&quot;: &quot;PARAGRAPH&quot;<br>        },<br>        {<br>            &quot;type&quot;: &quot;TEXT&quot;,<br>            &quot;id&quot;: &quot;a8a8691e-cf8b-4827-8ece-666fb991f35b&quot;,<br>            &quot;reading_order&quot;: 5,<br>            &quot;page_indices&quot;: [<br>                0<br>            ],<br>            &quot;representation&quot;: {<br>                &quot;markdown&quot;: &quot;9. AM/A/A1/B1/B/BE/DE/D&quot;<br>            },<br>            &quot;sub_type&quot;: &quot;PARAGRAPH&quot;<br>        },<br>        {<br>            &quot;type&quot;: &quot;TEXT&quot;,<br>            &quot;id&quot;: &quot;0750c78d-fbd2-4e4d-8e77-1374db4e238e&quot;,<br>            &quot;reading_order&quot;: 6,<br>            &quot;page_indices&quot;: [<br>                0<br>            ],<br>            &quot;representation&quot;: {<br>                &quot;markdown&quot;: &quot;**D1FRA13AA000026181231MARTIN&lt;&lt;9**&quot;<br>            },<br>            &quot;sub_type&quot;: &quot;PARAGRAPH&quot;<br>        }<br>    ]<br>}</pre><p>This script initializes a Bedrock client, creates a data automation project with specified input and output configurations, and starts a processing job using a custom blueprint. Developers can monitor the job status and retrieve results from the specified S3 bucket.</p><h3>Conclusion</h3><p>Amazon Bedrock Data Automation significantly enhances the automation of multimodal data analysis by streamlining the extraction and transformation of insights across various content types. This capability reduces the complexity of managing multiple foundation models, allowing developers to focus on building AI-driven solutions rather than fine-tuning and orchestrating models manually. Moreover, by integrating with AI agents, this feature enables more advanced and large-scale projects, such as autonomous document processing pipelines, intelligent content moderation, and automated media analysis. Organizations can leverage these AI-powered workflows to improve operational efficiency, enhance decision-making, and scale their AI-driven initiatives with minimal manual intervention.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ca9ff3c9a779" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering Hybrid Reasoning with Claude 3.7 Sonnet on Amazon Bedrock]]></title>
            <link>https://medium.com/@wael-saideni/mastering-hybrid-reasoning-with-claude-3-7-sonnet-on-amazon-bedrock-ede2ee610977?source=rss-f849de33d418------2</link>
            <guid isPermaLink="false">https://medium.com/p/ede2ee610977</guid>
            <category><![CDATA[generative-ai-use-cases]]></category>
            <category><![CDATA[bedrock]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[reasoning]]></category>
            <dc:creator><![CDATA[Wael SAIDENI]]></dc:creator>
            <pubDate>Mon, 03 Mar 2025 07:53:03 GMT</pubDate>
            <atom:updated>2025-03-03T07:53:03.110Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rLdHrIAn0JTrpshF_xrGJg.png" /></figure><h3>Introduction</h3><p>Artificial intelligence has taken a giant leap forward with the release of <strong>Anthropic’s Claude 3.7 Sonnet</strong> on <strong>Amazon Bedrock</strong>. This model introduces <strong>hybrid reasoning</strong>, a game-changing feature that enables step-by-step logical thinking before producing a response. With <strong>Extended Thinking Mode</strong>, adjustable reasoning budgets, and enhanced coding abilities, Claude 3.7 Sonnet is revolutionizing AI-powered decision-making.</p><p>In this blog, we’ll explore how you can leverage this cutting-edge model using a Python script from <a href="https://github.com/WaelDataReply/Bedrock_reasoning_mode">my GitHub</a> repository. By the end, you’ll understand how to use <strong>Claude 3.7 Sonnet’s reasoning capabilities</strong> for complex problem-solving.</p><h3>Why Reasoning Matters in AI</h3><p>Traditional language models are great at generating responses, but they often lack structured thought processes. <strong>Claude 3.7 Sonnet bridges this gap with hybrid reasoning</strong>, making it ideal for:</p><ul><li><strong>Complex decision-making</strong> (e.g., strategy planning, legal analysis, scientific research)</li><li><strong>Multi-step problem-solving</strong> (e.g., chess puzzles, logic games, math proofs)</li><li><strong>Enhanced code generation</strong> (e.g., debugging, refactoring, explaining code logic)</li></ul><p>With <strong>hybrid reasoning</strong>, Claude can dynamically switch between quick responses and <strong>step-by-step analytical thinking</strong>, giving users <strong>greater transparency into its decision-making</strong>.</p><h3>Key Features of Claude 3.7 Sonnet</h3><p>🔹 <strong>Hybrid Reasoning</strong> — A single model that can toggle between standard responses and detailed reasoning<br>🔹 <strong>Extended Thinking Mode</strong> — Analyzes problems in detail with transparent step-by-step thinking<br>🔹 <strong>Adjustable Reasoning Budget</strong> — Control how many tokens are allocated to the thinking process<br>🔹 <strong>Massive Output Capacity</strong> — Up to 15x longer output than predecessor models (up to 128K tokens)<br>🔹 <strong>Enhanced Coding Capabilities</strong> — Industry-leading performance on coding benchmarks</p><h3>Getting Started with Claude 3.7 Sonnet on Amazon Bedrock</h3><p>To test <strong>Claude 3.7 Sonnet’s reasoning capabilities</strong>, we’ll use a <strong>Python script</strong> that interacts with Amazon Bedrock’s API. This script allows you to:</p><p>✅ Configure <strong>AWS credentials</strong> for Bedrock access<br>✅ Set <strong>reasoning budgets</strong> to control thinking depth<br>✅ Invoke <strong>Claude’s reasoning mode</strong> on a real-world problem<br>✅ Analyze step-by-step responses to evaluate reasoning quality</p><h3>Step 1: Install Required Dependencies</h3><p>Ensure you have Python 3.8+ and <strong>boto3</strong> installed:</p><pre>pip install boto3</pre><h3>Step 2: Configure AWS Credentials</h3><p>Before running the script, configure your AWS profile with access to <strong>Amazon Bedrock</strong>:</p><pre>aws configure --profile &lt;your_profile_name&gt;</pre><h3>Step 3: Run the Claude 3.7 Sonnet Reasoning Script</h3><p>Below is a Python script that demonstrates how to interact with Claude 3.7 Sonnet on Amazon Bedrock. This script initializes a Bedrock client, configures logging, and submits a reasoning prompt to the model.</p><pre>#!/usr/bin/env python3<br>&quot;&quot;&quot;<br><br>This script demonstrates how to leverage Anthropic Claude 3.7 Sonnet&#39;s reasoning<br>capabilities through Amazon Bedrock using an object-oriented approach. It showcases:<br><br>- A dedicated BedrockReasoningClient class for interacting with the API<br>- Proper AWS client configuration using environment variables<br>- Modern Python error handling with context managers<br>- Type hints for better code documentation<br>- Structured logging<br>- A more complex and interesting reasoning challenge<br><br>Requirements:<br>- boto3 1.37.0+<br>- Python 3.9+<br>- Configured AWS credentials<br>&quot;&quot;&quot;<br><br>import json<br>import logging<br>from typing import Dict, List, Optional, Tuple, Any, Union<br><br>import boto3<br>from botocore.exceptions import ClientError<br><br><br>def configure_logging() -&gt; None:<br>    &quot;&quot;&quot;Set up structured logging configuration.&quot;&quot;&quot;<br>    logging.basicConfig(<br>        level=logging.INFO,<br>        format=&quot;%(asctime)s - %(name)s - %(levelname)s - %(message)s&quot;,<br>    )<br><br><br>class BedrockReasoningClient:<br>    &quot;&quot;&quot;<br>    Client for interacting with Claude&#39;s reasoning capabilities via Amazon Bedrock.<br>    <br>    This class encapsulates the logic for setting up a connection to Amazon Bedrock<br>    and invoking Claude 3.7 Sonnet with reasoning capabilities enabled.<br>    &quot;&quot;&quot;<br>    <br>    def __init__(<br>        self, <br>        region_name: str = &quot;us-east-1&quot;, <br>        profile_name: Optional[str] = &quot;data_reply&quot;,<br>        default_model_id: str = &quot;us.anthropic.claude-3-7-sonnet-20250219-v1:0&quot;<br>    ):<br>        &quot;&quot;&quot;<br>        Initialize the BedrockReasoningClient.<br>        <br>        Args:<br>            region_name: AWS region for the Bedrock client<br>            default_model_id: Default Claude model ID to use<br>        &quot;&quot;&quot;<br>        self.logger = logging.getLogger(self.__class__.__name__)<br>        self.region_name = region_name<br>        self.profile_name = profile_name<br>        self.default_model_id = default_model_id<br>        self.client = self._create_client()<br>    <br>    def _create_client(self) -&gt; Any:<br>        &quot;&quot;&quot;<br>        Create and return a configured Amazon Bedrock runtime client.<br>        <br>        Returns:<br>            Configured Bedrock runtime client<br>        <br>        Raises:<br>            Exception: If client creation fails<br>        &quot;&quot;&quot;<br>        try:<br>            # Using default credentials from environment or AWS config<br>            session = boto3.Session(profile_name=self.profile_name)<br>            return session.client(&quot;bedrock-runtime&quot;, region_name=self.region_name)<br>        except Exception as e:<br>            self.logger.error(f&quot;Failed to create Bedrock client: {e}&quot;)<br>            raise<br>    <br>    def invoke_reasoning(<br>        self,<br>        prompt: str,<br>        reasoning_budget: int = 2000,<br>        model_id: Optional[str] = None,<br>        temperature: float = 1,<br>    ) -&gt; Tuple[Optional[str], Optional[str]]:<br>        &quot;&quot;&quot;<br>        Invoke Claude with reasoning capability enabled.<br>        <br>        Args:<br>            prompt: User prompt to send to Claude<br>            reasoning_budget: Token budget for the reasoning step<br>            model_id: Bedrock model ID to override default<br>            temperature: Sampling temperature (0.0 to 1.0)<br>            <br>        Returns:<br>            Tuple containing (reasoning_text, response_text)<br>            <br>        Raises:<br>            ClientError: If the Bedrock API returns an error<br>            KeyError: If the response has an unexpected structure<br>            Exception: For any other unexpected errors<br>        &quot;&quot;&quot;<br>        model_id = model_id or self.default_model_id<br>        <br>        conversation = [<br>            {<br>                &quot;role&quot;: &quot;user&quot;,<br>                &quot;content&quot;: [{&quot;text&quot;: prompt}],<br>            }<br>        ]<br><br>        reasoning_config = {<br>            &quot;thinking&quot;: {<br>                &quot;type&quot;: &quot;enabled&quot;,<br>                &quot;budget_tokens&quot;: reasoning_budget<br>            }<br>        }<br>        <br>        # Additional model parameters<br>        inference_config = {<br>            &quot;temperature&quot;: temperature,<br>        }<br><br>        try:<br>            self.logger.info(f&quot;Invoking model {model_id} with reasoning enabled&quot;)<br>            response = self.client.converse(<br>                modelId=model_id,<br>                messages=conversation,<br>                inferenceConfig=inference_config,<br>                additionalModelRequestFields=reasoning_config<br>            )<br><br>            content_blocks = response[&quot;output&quot;][&quot;message&quot;][&quot;content&quot;]<br><br>            reasoning_text = None<br>            response_text = None<br><br>            for block in content_blocks:<br>                if &quot;reasoningContent&quot; in block:<br>                    reasoning_text = block[&quot;reasoningContent&quot;][&quot;reasoningText&quot;][&quot;text&quot;]<br>                if &quot;text&quot; in block:<br>                    response_text = block[&quot;text&quot;]<br><br>            return reasoning_text, response_text<br><br>        except ClientError as e:<br>            self.logger.error(f&quot;Bedrock API error: {e}&quot;)<br>            raise<br>        except KeyError as e:<br>            self.logger.error(f&quot;Unexpected response structure: {e}&quot;)<br>            raise<br>        except Exception as e:<br>            self.logger.error(f&quot;Unknown error during model invocation: {e}&quot;)<br>            raise<br>    <br>    def get_model_info(self, model_id: Optional[str] = None) -&gt; Dict[str, Any]:<br>        &quot;&quot;&quot;<br>        Get information about the currently configured model.<br>        <br>        Args:<br>            model_id: Optional model ID to check, uses default if None<br>            <br>        Returns:<br>            Dictionary with model information<br>        &quot;&quot;&quot;<br>        model_id = model_id or self.default_model_id<br>        return {<br>            &quot;model_id&quot;: model_id,<br>            &quot;region&quot;: self.region_name,<br>            &quot;provider&quot;: &quot;Anthropic&quot; if &quot;anthropic&quot; in model_id.lower() else &quot;Unknown&quot;,<br>            &quot;version&quot;: model_id.split(&quot;-&quot;)[-1] if &quot;-&quot; in model_id else &quot;Unknown&quot;<br>        }<br><br><br>def main() -&gt; None:<br>    &quot;&quot;&quot;Execute the Claude reasoning demonstration.&quot;&quot;&quot;<br>    configure_logging()<br>    logger = logging.getLogger(&quot;claude_reasoning_demo&quot;)<br>    <br>    try:<br>        # Complex chess puzzle that benefits from reasoning<br>        chess_puzzle_prompt = &quot;&quot;&quot;<br>        You&#39;re given a chess position with the following pieces:<br>        - White King on e1<br>        - White Rook on h1<br>        - White Pawns on a2, b2, c2, d2, f2, g2, h2<br>        - Black King on e8<br>        - Black Queen on d8<br>        - Black Rooks on a8 and f8<br>        - Black Bishops on c8 and g7<br>        - Black Knights on b8 and g8<br>        - Black Pawns on a7, b7, c7, d7, e7, f7, h7<br>        <br>        White has just moved pawn from e2 to e4. Find the best move for Black and explain your reasoning step by step.<br>        &quot;&quot;&quot;<br>        <br>        logger.info(&quot;Initializing BedrockReasoningClient&quot;)<br>        client = BedrockReasoningClient()<br>        <br>        # Print info about the model we&#39;re using<br>        model_info = client.get_model_info()<br>        logger.info(f&quot;Using model: {model_info[&#39;model_id&#39;]} in {model_info[&#39;region&#39;]}&quot;)<br>        <br>        # Invoke the model with our chess puzzle<br>        reasoning, response = client.invoke_reasoning(<br>            prompt=chess_puzzle_prompt,<br>            reasoning_budget=3000,  # Increased budget for the complex chess problem<br>        )<br>        <br>        if reasoning and response:<br>            print(&quot;\n===== CLAUDE&#39;S REASONING PROCESS =====&quot;)<br>            print(reasoning)<br>            print(&quot;\n===== CLAUDE&#39;S FINAL RESPONSE =====&quot;)<br>            print(response)<br>        else:<br>            logger.warning(&quot;Received incomplete response from Claude&quot;)<br>            <br>    except Exception as e:<br>        logger.error(f&quot;Failed to run demonstration: {e}&quot;)<br><br><br>if __name__ == &quot;__main__&quot;:<br>    main()</pre><p>Use the following command to execute the Python script from my GitHub repo:</p><pre>python bedrock_reasoning_class.py</pre><p><a href="https://github.com/WaelDataReply/Bedrock_reasoning_mode">https://github.com/WaelDataReply/Bedrock_reasoning_mode</a></p><h3>Step 4: Understanding the Output</h3><p>The script submits a <strong>complex chess puzzle</strong> to Claude 3.7 Sonnet, prompting it to reason through the best possible move for Black. Expect an output like this:</p><pre>===== CLAUDE&#39;S REASONING PROCESS =====<br>1. Evaluating White&#39;s last move (e2-e4)<br>2. Analyzing possible Black responses<br>3. Identifying key threats and opportunities<br>4. Selecting the best strategic move</pre><pre>===== CLAUDE&#39;S FINAL RESPONSE =====<br>Best move: c7-c5 (Sicilian Defense)<br>Explanation: This move immediately contests the center, countering White’s control.</pre><p>This breakdown <strong>shows Claude’s step-by-step thinking</strong>, demonstrating how it arrives at an answer — a crucial feature for high-stakes decision-making.</p><h3>Fine-Tuning Claude’s Reasoning</h3><h3>1. Adjusting the Reasoning Budget</h3><p>You can control the <strong>depth of reasoning</strong> by modifying the reasoning_budget parameter in the script:</p><pre>response = client.invoke_reasoning(prompt=chess_puzzle_prompt, reasoning_budget=3000)</pre><p>A <strong>higher budget</strong> allows for more detailed analysis, while a <strong>lower budget</strong> keeps responses concise.</p><h3>2. Comparing Standard vs. Extended Thinking Mode</h3><p>Try running <strong>two different calls</strong>:</p><pre>response_standard = client.invoke_reasoning(prompt, reasoning_budget=500)<br>response_extended = client.invoke_reasoning(prompt, reasoning_budget=5000)</pre><p>This will help you compare <strong>quick answers vs. deep-dive reasoning</strong>.</p><h3>The Future of AI-Powered Reasoning</h3><p>Claude 3.7 Sonnet isn’t just an upgrade — it’s a <strong>paradigm shift</strong> in AI reasoning. With <strong>Amazon Bedrock</strong>, businesses and developers can seamlessly integrate <strong>hybrid reasoning</strong> into their applications, unlocking AI-powered insights for research, strategy, coding, and beyond.</p><p>🚀 <strong>Ready to experience Claude 3.7 Sonnet’s reasoning in action?</strong> Clone the script from <a href="https://github.com/WaelDataReply/Bedrock_reasoning_mode">my GitHub</a> repo and start experimenting today!</p><h3>Have thoughts or questions?</h3><p>Drop a comment below or connect with me on <a href="https://www.linkedin.com/in/wael-saideni-753678152/">LinkedIn</a>. Let’s discuss the future of AI reasoning! 🚀</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ede2ee610977" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding the difference between context caching or prompt caching and semantic caching: A step…]]></title>
            <link>https://medium.com/@wael-saideni/understanding-the-difference-between-context-caching-and-semantic-caching-a-step-toward-optimizing-1a2b44d25c12?source=rss-f849de33d418------2</link>
            <guid isPermaLink="false">https://medium.com/p/1a2b44d25c12</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[caching]]></category>
            <category><![CDATA[optmization]]></category>
            <category><![CDATA[generative-ai-use-cases]]></category>
            <dc:creator><![CDATA[Wael SAIDENI]]></dc:creator>
            <pubDate>Fri, 13 Sep 2024 10:05:19 GMT</pubDate>
            <atom:updated>2024-09-16T08:26:33.151Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>Understanding the difference between context caching or prompt caching and semantic caching: A step toward optimizing RAG-based projects</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/907/1*kpSAj8Dl3Vbhxp-Gz-loOA.png" /><figcaption>This image has been generated using black-forest-labs/FLUX.1-dev on HuggingFace</figcaption></figure><p>As generative AI models and large language models (LLMs) become integral to a variety of applications, optimizing their efficiency is crucial to improving performance and reducing costs. Two caching techniques — <strong>context caching</strong> and <strong>semantic caching</strong> — stand out in this regard. While both methods aim to minimize redundant processing and reduce computational load, they operate on different principles and excel in distinct scenarios. This blog post explores the differences between these two caching strategies and highlights their respective advantages in optimizing LLM workflows.</p><p><strong>What Is Context Caching?</strong></p><p><strong>Context caching</strong> (also known as <strong>prompt caching</strong>) focuses on optimizing the processing of large context windows within generative models. Context windows refer to the amount of data or information a model can handle at one time. Models like Claude, Gemini or other LLMs need to process vast amounts of information, which can be computationally expensive and time-consuming.</p><p><strong>Context caching</strong> is designed to reuse previously computed tokens across multiple requests, eliminating the need to recompute the entire input context each time a new request is made. This approach is especially useful when working with large and complex datasets, such as extensive documents, video files, or detailed system prompts. For example, if a user is working with an in-context learning approach, caching previously computed context can significantly reduce processing time and computational overhead.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/962/1*NiNxcOslRMS6qfEP6m7ucA.png" /><figcaption>Overview of Prompt/context caching approach</figcaption></figure><p><strong>Benefits of Context Caching:</strong></p><ol><li><strong>Cost Savings</strong>: Since the computed tokens are stored in memory, the system avoids recomputing the same tokens for subsequent requests. Users pay only for the initial computation and a small fee for storing the cached tokens, reducing overall costs.</li><li><strong>Reduced Response Time</strong>: In some cases, context caching can improve response times, as seen with Google’s and Anthropic’s solutions. However, the degree of improvement depends on the use case, especially when handling very large contexts.</li></ol><p><strong>How Context/Prompt Caching Works:</strong></p><p>Here’s an example of how to implement Prompt Caching using Anthropic models:</p><pre>import anthropic<br><br>client = anthropic.Anthropic()<br><br>response = client.beta.prompt_caching.messages.create(<br>    model=&quot; claude-3-haiku-20240307&quot;,<br>    max_tokens=1024,<br>    system=[<br>      {<br>        &quot;type&quot;: &quot;text&quot;, <br>        &quot;text&quot;: &quot;You are an AI assistant tasked with analyzing literary works. Your goal is to provide insightful commentary on themes, characters, and writing style.\n&quot;,<br>      },<br>      {<br>        &quot;type&quot;: &quot;text&quot;, <br>        &quot;text&quot;: &quot;&lt;the entire contents of &#39;My book&#39;&gt;&quot;,<br>        &quot;cache_control&quot;: {&quot;type&quot;: &quot;ephemeral&quot;}<br>      }<br>    ],<br>    messages=[{&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: &quot;Analyze the major themes in &#39;My book&#39;.&quot;}],<br>)<br>print(response)</pre><p>For more details: <a href="https://docs.anthropic.com/en/docs/build-with-claude/prompt-caching">Anthropic-Prompt-Caching</a></p><p>You can also explore <a href="https://ai.google.dev/gemini-api/docs/caching?lang=python">Gemini-Context-Caching</a>, as they are the first to integrate this approach into their models.</p><p><strong>Limitations of Context Caching:</strong></p><p>While context caching can enhance efficiency, it doesn’t always offer the dramatic response time reductions seen with other retrieval-based approaches like <strong>retrieval-augmented generation (RAG)</strong>. However, it shines in scenarios where the model needs to maintain and reuse a large context, which makes it suitable for tasks like document summarization, in-context learning, or working with large system prompts.</p><p><strong>What Is Semantic Caching?</strong></p><p><strong>Semantic caching</strong> is a more advanced form of caching that stores the <strong>meaning</strong> of a query or request rather than just its physical characteristics (i.e., raw data). In this approach, the cache stores previous queries and their results based on the semantic content, allowing the system to recognize when two queries are essentially the same, even if the input differs slightly.</p><p>For instance, two users might request slightly different queries that ask for the same information. Traditional caching would store and serve these requests separately, increasing server load. In contrast, <strong>semantic caching</strong> allows the system to match the meaning of the queries and return the same result for both, improving efficiency. This approach is particularly beneficial for complex queries that span multiple data sources or require results that involve deeper layers of logic and understanding.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/801/1*G7F14ScLohs5WpqmQAp3cQ.png" /><figcaption>Overview of semantic caching approach</figcaption></figure><p><strong>Benefits of Semantic Caching:</strong></p><ol><li><strong>Lower Server Load</strong>: Semantic caching can significantly reduce the number of queries a server needs to process. By identifying requests with the same meaning and serving cached results, the system can avoid redundant computations.</li><li><strong>Cost Reduction</strong>: By caching responses, such as LLM outputs, semantic caching can lower API call expenses and reduce the need for continuous processing of similar queries.</li><li><strong>Improved Scalability</strong>: This caching strategy is especially useful for applications that require complex query handling and can improve scalability by minimizing the number of calls and reducing response times.</li></ol><p><strong>How Semantic Caching Works:</strong></p><p>Semantic caching tailors its cache based on the intent behind the query rather than the specific input. As a result, it can return the same response even if the underlying data has changed, as long as the meaning of the query remains the same. This offers significant flexibility and efficiency for systems that need to process a large volume of semantically similar queries.</p><p>Here’s an example of how to implement Semantic cache using:</p><ul><li><strong>Amazon Bedrock</strong> for LLM and embedding generation.</li><li><strong>OpenSearch</strong> for caching and querying the cached responses using FAISS-based k-NN search.</li><li><strong>boto3</strong> and <strong>opensearch-py</strong> libraries to interact with AWS and OpenSearch.</li></ul><pre>import json<br>import boto3<br>import datetime<br>from opensearchpy import OpenSearch<br>from typing import List, Dict, Optional<br><br># Initialize Amazon Bedrock client and OpenSearch client<br>bedrock_client = boto3.client(&#39;bedrock&#39;)<br>opensearch_client = OpenSearch(hosts=[{&#39;host&#39;: &#39;your-opensearch-endpoint&#39;, &#39;port&#39;: 443}], use_ssl=True)<br><br>OPENSEARCH_INDEX = &#39;semantic_cache&#39;<br>SIMILARITY_THRESHOLD = 0.7<br><br># Function to retrieve embeddings for a query using Amazon Bedrock<br>def get_embedding(text: str) -&gt; List[float]:<br>    body = json.dumps({&quot;inputText&quot;: text})<br>    response = bedrock_client.invoke_model(<br>        body=body,<br>        modelId=&quot;embedding-model-id&quot;, #&#39;cohere.embed-multilingual-v3&#39; <br>        accept=&quot;application/json&quot;,<br>        contentType=&quot;application/json&quot;<br>    )<br>    response_body = json.loads(response.get(&quot;body&quot;).read())<br>    return response_body.get(&quot;embedding&quot;)<br><br># Create OpenSearch index for storing cached responses and embeddings<br>def create_index() -&gt; None:<br>    index_mapping = {<br>        &quot;settings&quot;: {<br>            &quot;index&quot;: {&quot;knn&quot;: True, &quot;knn.algo_param.ef_search&quot;: 512}<br>        },<br>        &quot;mappings&quot;: {<br>            &quot;properties&quot;: {<br>                &quot;query_vectors&quot;: {<br>                    &quot;type&quot;: &quot;knn_vector&quot;,<br>                    &quot;dimension&quot;: 1024,  # Adjust based on your embedding model&#39;s dimension<br>                    &quot;method&quot;: {<br>                        &quot;engine&quot;: &quot;faiss&quot;,<br>                        &quot;space_type&quot;: &quot;l2&quot;,<br>                        &quot;name&quot;: &quot;hnsw&quot;,<br>                        &quot;parameters&quot;: {&quot;ef_construction&quot;: 512, &quot;m&quot;: 16}<br>                    }<br>                },<br>                &quot;query&quot;: {&quot;type&quot;: &quot;text&quot;},<br>                &quot;response&quot;: {&quot;type&quot;: &quot;text&quot;},<br>                &quot;create_date&quot;: {&quot;type&quot;: &quot;date&quot;},<br>                &quot;ttl&quot;: {&quot;type&quot;: &quot;integer&quot;}<br>            }<br>        }<br>    }<br><br>    if not opensearch_client.indices.exists(index=OPENSEARCH_INDEX):<br>        opensearch_client.indices.create(index=OPENSEARCH_INDEX, body=index_mapping)<br><br># Save query, embeddings, and response to OpenSearch<br>def save_response(query: str, response: str) -&gt; None:<br>    if not opensearch_client.indices.exists(index=OPENSEARCH_INDEX):<br>        create_index()<br><br>    vectors = get_embedding(query)<br>    index_body = {<br>        &quot;query&quot;: query,<br>        &quot;query_vectors&quot;: vectors,<br>        &quot;response&quot;: response,<br>        &quot;create_date&quot;: datetime.datetime.now().isoformat(),<br>        &quot;ttl&quot;: 3600  # 1 hour TTL for cache<br>    }<br><br>    opensearch_client.index(index=OPENSEARCH_INDEX, body=index_body, refresh=True)<br><br># Perform k-NN search in OpenSearch to find similar queries in the cache<br>def get_knn_results(query_embeddings: List[float]) -&gt; Optional[Dict]:<br>    query = {<br>        &quot;size&quot;: 1,<br>        &quot;query&quot;: {&quot;knn&quot;: {&quot;query_vectors&quot;: {&quot;vector&quot;: query_embeddings, &quot;k&quot;: 3}}},<br>        &quot;_source&quot;: [&quot;query&quot;, &quot;response&quot;, &quot;create_date&quot;, &quot;ttl&quot;]<br>    }<br><br>    response = opensearch_client.search(body=query, index=OPENSEARCH_INDEX)<br><br>    hits = response[&#39;hits&#39;][&#39;hits&#39;]<br>    if hits and hits[0][&#39;_score&#39;] &gt; SIMILARITY_THRESHOLD:<br>        return hits[0][&#39;_source&#39;]<br><br>    return None<br><br># Query the cache for a similar question<br>def query_cache(query: str) -&gt; Optional[str]:<br>    if opensearch_client.indices.exists(index=OPENSEARCH_INDEX):<br>        query_embeddings = get_embedding(query)<br>        cached_result = get_knn_results(query_embeddings)<br>        if cached_result:<br>            return cached_result[&#39;response&#39;]<br>    return None<br><br># Function to generate a response using Bedrock LLM<br>def generate_llm_response(query: str) -&gt; str:<br>    body = json.dumps({&quot;inputText&quot;: query})<br>    response = bedrock_client.invoke_model(<br>        body=body,<br>        modelId=&quot;llm-model-id&quot;, #anthropic.claude-3-haiku-20240307-v1:0<br>        accept=&quot;application/json&quot;,<br>        contentType=&quot;application/json&quot;<br>    )<br>    response_body = json.loads(response.get(&quot;body&quot;).read())<br>    return response_body.get(&quot;outputText&quot;)<br><br># Main function to get a response (from cache or LLM)<br>def get_response(query: str) -&gt; str:<br>    cached_response = query_cache(query)<br>    if cached_response:<br>        print(&quot;Cache hit!&quot;)<br>        return cached_response<br>    else:<br>        print(&quot;Cache miss! Generating new response using Amazon Bedrock.&quot;)<br>        new_response = generate_llm_response(query)<br>        save_response(query, new_response)<br>        return new_response<br><br># Example usage<br>query_1 = &quot;What is Semantic Cache?&quot;<br>response_1 = get_response(query_1)<br>print(f&quot;Response: {response_1}&quot;)<br><br>query_2 = &quot;Tell me about Semantic Cache.&quot;<br>response_2 = get_response(query_2)<br>print(f&quot;Response: {response_2}&quot;)</pre><p><strong>Key Differences Between Context Caching and Semantic Caching</strong></p><p>While both caching mechanisms serve to reduce computational overhead, their approaches and use cases differ significantly.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/910/1*-yAQsGQaxKLMiIWhj4TzyQ.png" /></figure><p><strong>Which Caching Approach Is Right for You?</strong></p><p><strong>Context caching</strong> is an excellent choice when you’re dealing with large, complex contexts that need to be processed repeatedly — especially when working with extensive documents or tasks requiring a long history of context. If your model needs access to a vast amount of information for every request, such as in long document summarization or video analysis, context caching will help reduce both time and cost.</p><p>On the other hand, <strong>semantic caching</strong> is more beneficial for systems where queries can be grouped or categorized by their meaning. If your application involves frequent requests with similar underlying semantics, such as a customer support system querying a knowledge base, semantic caching will drastically improve efficiency by avoiding redundant processing.</p><p>In some advanced applications, I think that a <strong>double cached approach</strong> can be employed by combining <strong>context caching</strong> and <strong>semantic caching</strong> to maximize efficiency and performance.</p><p>This hybrid approach significantly reduces latency and computational costs. For example, when an LLM handles a lengthy document, context caching avoids recomputing the entire document with every query. Simultaneously, semantic caching ensures that similar queries about the document retrieve results from the cache rather than triggering redundant model calls. By leveraging both methods, organizations can achieve a highly optimized system capable of handling complex, large-scale generative tasks while maintaining fast response times and minimizing computational overhead.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/672/1*luGzU28A8TNV71TqjXqhxA.png" /><figcaption>Overview of double cached RAG — when combining context caching and semantic caching</figcaption></figure><p>The challenge now is to implement this hybrid approach in a real-world project to fully assess its potential benefits and identify any limitations.</p><p><strong>In a nutshell</strong></p><p>As LLMs continue to advance, caching strategies like <strong>context caching, semantic caching and double caching </strong>play a pivotal role in optimizing performance, reducing server load, and cutting down costs. While context caching is most useful in scenarios where large datasets need to be reused across multiple requests, semantic caching shines when dealing with queries that have similar meanings but come in different forms. Understanding the differences between these two approaches allows developers and businesses to choose the most effective strategy to meet their specific needs, ensuring smoother, faster, and more cost-effective AI-driven processes.</p><p>Ultimately, the right caching strategy will depend on the nature of your application and the type of queries or data it processes. As the field of GenAI continues to evolve, combining both caching approaches with other techniques like RAG may offer even more powerful solutions for optimizing large-scale generative models. Maybe a double cached RAG</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1a2b44d25c12" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ Generative AI: 11 opportunities and real-world challenges]]></title>
            <link>https://medium.com/@wael-saideni/generative-ai-11-opportunities-and-real-world-challenges-467bb3464054?source=rss-f849de33d418------2</link>
            <guid isPermaLink="false">https://medium.com/p/467bb3464054</guid>
            <category><![CDATA[generative-ai-consulting]]></category>
            <category><![CDATA[tech-innovation]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[ai-challenge]]></category>
            <dc:creator><![CDATA[Wael SAIDENI]]></dc:creator>
            <pubDate>Mon, 10 Jun 2024 16:01:45 GMT</pubDate>
            <atom:updated>2024-09-09T15:32:32.890Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*EbBYDa_F2WGTIh0mPd8I4Q.gif" /></figure><p>Generative AI is transforming numerous industries, yet it brings a unique set of challenges that must be addressed to fully realize its potential. Here are some real-world challenges we are tackling alongside our partners and customers at <a href="https://www.reply.com/data-reply/fr/">Data Reply FR</a>:</p><p>✅ <strong>Building Centralized Generative AI Platforms:</strong> Developing a unified platform that caters to diverse use cases is a monumental task. Moving from proof of concept (PoC) to production involves ensuring scalability, reliability, and adaptability. Each use case demands unique considerations, making it essential to build a flexible and robust central platform. This requires thorough planning, robust architecture, and continuous integration and deployment pipelines to manage the diverse demands of different industries effectively.</p><p>✅ <strong>LLMOps — Offline and Online Evaluation</strong>: Evaluating large language models (LLMs) requires a dual approach. Offline testing helps refine models before deployment, ensuring they meet performance and accuracy standards. Once deployed, online monitoring is crucial to maintain continuous performance, catch issues in real-time, and adapt to evolving requirements. Effective LLMOps involves setting up comprehensive testing frameworks, monitoring tools, and feedback loops to ensure models are not only accurate but also resilient and adaptive to new data and changing contexts.</p><p>✅ <strong>Red Teaming for Vulnerability Detection</strong>: Identifying and mitigating vulnerabilities in LLMs is crucial for secure AI systems. Red teaming, or simulating attacks to uncover weaknesses, ensures that our AI models are robust and secure, capable of withstanding malicious attempts and maintaining integrity. This proactive approach involves not only technical assessments but also ethical considerations to anticipate and prevent misuse, ensuring AI systems are safe and trustworthy.</p><p>✅ <strong>Foundation Models on Edge</strong>: Deploying small foundation models on edge devices, such as CPUs, enhances real-time processing and reduces latency. This approach is vital for applications that require immediate responses, such as autonomous vehicles, healthcare monitoring systems, and smart devices. By bringing AI capabilities closer to the data source, edge deployments reduce the reliance on cloud connectivity, improve privacy, and enable faster decision-making.</p><p>✅ <strong>Multimodality for AGI</strong>: Using a single model to process various data types (text, image, audio) brings us closer to Artificial General Intelligence (AGI). Multimodal models significantly enhance the flexibility and capabilities of AI systems, allowing them to understand and generate diverse forms of data seamlessly. This integration paves the way for more natural and intuitive human-computer interactions, enabling AI to perform complex tasks that require understanding and synthesizing information from multiple modalities.</p><p>✅ <strong>Code Generation for Developer Productivity</strong>: Generative AI can transform software development by automating code generation, boosting productivity, and reducing errors. This empowers developers to focus on more complex tasks, accelerating the development cycle and enhancing the quality of software. By leveraging AI to handle repetitive and mundane coding tasks, developers can devote more time to innovation, problem-solving, and optimizing user experiences, leading to more robust and innovative software solutions.</p><p>✅ <strong>FinOps — Optimizing AI Infrastructure Costs</strong>: Managing the costs of generative AI infrastructure on cloud platforms is vital. FinOps practices help optimize expenditures, ensuring a balance between performance and budget. This involves strategic planning and continuous monitoring to keep costs under control without compromising on capabilities. Implementing cost-saving measures, such as optimizing resource usage, leveraging spot instances, and right-sizing infrastructure, can significantly reduce operational expenses while maintaining high performance.</p><p>✅ <strong>Calculating ROI for Generative AI Solutions</strong>: Measuring the return on investment (ROI) for AI solutions involves assessing their impact on efficiency, innovation, and revenue. A robust ROI framework justifies AI investments and guides strategic decisions, highlighting the tangible benefits of generative AI initiatives. By quantifying the value delivered through improved processes, reduced operational costs, enhanced customer experiences, and new revenue streams, businesses can make informed decisions about their AI investments.</p><p>✅ <strong>Open Source vs Closed Source</strong>: The debate between open and closed-source generative AI continues. Open-source fosters innovation and collaboration, allowing the community to contribute and improve models. Conversely, closed-source offers more control and proprietary advantages, enabling companies to maintain a competitive edge. Each approach has its merits, and the choice often depends on factors such as security requirements, competitive strategy, and the need for customization.</p><p>✅ <strong>Legislation for Generative AI</strong>: As AI systems become more integrated into society, robust legislation is essential to address ethical concerns, privacy issues, and ensure fair use. Policymakers must create frameworks that protect individuals and promote responsible AI development and deployment. This involves balancing innovation with regulation, ensuring that AI technologies are developed and used in ways that are ethical, transparent, and beneficial to society as a whole.</p><p>✅ <strong>Generative AI vs Traditional ML</strong>: Is generative AI sufficient to replace traditional machine learning models for tasks like classification and detection? While generative AI offers advanced capabilities, traditional ML remains valuable for specific, well-defined tasks. Both approaches have their merits, and their combination can lead to more robust solutions. By leveraging the strengths of both generative AI and traditional ML, we can develop comprehensive systems that address a wide range of challenges and applications.</p><p>The generative AI field is evolving rapidly, and other challenges are likely to emerge along the way.</p><p>Generative AI presents incredible opportunities, but navigating these challenges requires a strategic approach and continuous innovation.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=467bb3464054" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Load Testing of Amazon SageMaker Inference Endpoints: Ensuring Reliability and Performance in…]]></title>
            <link>https://medium.com/@wael-saideni/load-testing-of-amazon-sagemaker-inference-endpoints-ensuring-reliability-and-performance-in-fd2cf601e20e?source=rss-f849de33d418------2</link>
            <guid isPermaLink="false">https://medium.com/p/fd2cf601e20e</guid>
            <category><![CDATA[llama-3]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[amazon-sagemaker]]></category>
            <category><![CDATA[mistral]]></category>
            <category><![CDATA[load-testing]]></category>
            <dc:creator><![CDATA[Wael SAIDENI]]></dc:creator>
            <pubDate>Tue, 14 May 2024 07:10:23 GMT</pubDate>
            <atom:updated>2024-05-14T07:10:23.183Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>Load Testing of Amazon SageMaker Inference Endpoints: Ensuring Reliability and Performance in production</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1014/1*BYGnIatBYNcuPe80e0rAbA.png" /></figure><p>Amazon SageMaker makes it simple for data scientists and developers to create, train, and deploy machine learning (ML) models without the complexities of managing infrastructure. A core feature is the ability to deploy trained models as real-time inference endpoints, allowing you to deliver predictions and other ML-based insights quickly and interactively. However, launching a real-time endpoint is just the beginning; load testing is crucial to ensure that your endpoint can handle real-world workloads while maintaining acceptable latency and performance.</p><p>In this blog post, we’ll explore the importance of load testing Amazon SageMaker inference endpoints and provide a guide on how to implement load tests to ensure optimal performance.</p><p><strong>What is load testing and why is it important?</strong></p><p>Load testing is the process of simulating a realistic workload on an application, service, or endpoint to measure its performance under different conditions. The primary goals of load testing are to:</p><p><strong><em>· Evaluate Resilience and Efficiency:</em></strong> Determine how the endpoint performs under varying loads and identify any potential bottlenecks.</p><p><strong><em>· Simulate Realistic Workloads:</em></strong> Ensure the endpoint can handle the expected volume of requests in production scenarios.</p><p><strong><em>· Uncover Performance Issues:</em></strong><em> </em>Detect slowdowns, errors, or other issues that could affect the user experience.</p><p><strong><em>· Guide Optimization Efforts:</em></strong> Provide insights for improving scalability and reliability.</p><p>For Amazon SageMaker inference endpoints, load testing is essential to ensure that your deployed models can meet the demands of your users and applications. It helps to mitigate the risk of downtime or service degradation, ultimately contributing to a better user experience and more reliable ML services.</p><p><strong>Setting up your solution architecture</strong></p><p>In our solution, we’ve set up an Amazon SageMaker endpoint that works seamlessly with AWS Lambda. We use Amazon API Gateway to handle requests and responses between the frontend client and the SageMaker endpoint. This architecture allows for efficient communication and flexibility in handling requests, making it ideal for scenarios where you need real-time predictions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZUfhdzCj2qhJUP4ydXuFGQ.png" /><figcaption>A basic AWS architecture for deploying an open-source Large Language Model (LLM) on Amazon SageMaker</figcaption></figure><p>To load test this setup, we need to simulate multiple concurrent requests to the endpoint, monitor the performance metrics, and evaluate the results to identify areas for improvement.</p><p><strong>Load testing script</strong></p><p>While load testing can be executed using various tools like Locust, an open-source framework mentioned in this AWS blog post: <a href="https://aws.amazon.com/blogs/machine-learning/best-practices-for-load-testing-amazon-sagemaker-real-time-inference-endpoints/">Best practices for load testing Amazon SageMaker real-time inference endpoints</a>, simpler methods can also provide insights into the performance of SageMaker instances swiftly. In this code, we’ll assess the model’s performance on SageMaker G5 instances by conducting a simple load test. This involves sending multiple concurrent requests to the model and measuring its response time and throughput.</p><pre>#Main code<br>import sys<br>import time<br>import concurrent.futures<br>from tqdm import tqdm<br>import json<br> <br>sys.path.append(&quot;utils&quot;)<br>from get_metrics import get_metrics_from_cloudwatch<br> <br># Generation arguments<br>parameters = {<br>    &quot;do_sample&quot;: True,<br>    &quot;top_p&quot;: 0.6,<br>    &quot;temperature&quot;: 0.9,<br>    &quot;max_new_tokens&quot;: 250,<br>    &quot;return_full_text&quot;: False,<br>}<br> <br># The function to perform a single request<br>def make_request(payload):<br>    try:<br>        llm.predict(<br>            data={<br>                &quot;inputs&quot;: tokenizer.apply_chat_template(<br>                    [<br>                        {<br>                            &quot;role&quot;: &quot;user&quot;,<br>                            &quot;content&quot;: payload<br>                        }<br>                    ],<br>                    tokenize=False,<br>                    add_generation_prompt=True,<br>                ),<br>                &quot;parameters&quot;: parameters,<br>            }<br>        )<br>        return 200<br>    except Exception as e:<br>        print(e)<br>        return 500<br>    <br># Main function to run the load test<br>def run_load_test(total_requests, concurrent_users):<br>    with concurrent.futures.ThreadPoolExecutor(max_workers=concurrent_users) as executor:<br>        # Prepare a list of the same inputs to hit multiple times<br>        tasks = [&quot;Write a long story about llamas and why should protect them.&quot;] * total_requests<br>        start_time = time.time()<br>        <br>        # run the requests<br>        results = list(tqdm(executor.map(make_request, tasks), total=total_requests, desc=&quot;Running load test&quot;))<br>        end_time = time.time()<br>        <br>        print(f&quot;Total time for {total_requests} requests with {concurrent_users} concurrent users: {end_time - start_time:.2f} seconds&quot;)<br>        print(f&quot;Successful rate: {results.count(200) / total_requests * 100:.2f}%&quot;)<br>        # Get the metrics<br>        metrics = get_metrics_from_cloudwatch(<br>            endpoint_name=llm.endpoint_name,<br>            st=int(start_time),<br>            et=int(end_time),<br>            cu=concurrent_users,<br>            total_requests=total_requests,<br>            boto3_session=sess.boto_session<br>        )<br>        # store results<br>        with open(&quot;results.json&quot;, &quot;w&quot;) as f:<br>            json.dump(metrics, f)<br>        # print results<br>        # print(f&quot;Llama 3 8B results on `g5.2xlarge`:&quot;)<br>        print(f&quot;Mistral 7B Instruct results on `g5.48xlarge`:&quot;)<br>        print(f&quot;Throughput: {metrics[&#39;Thorughput (tokens/second)&#39;]:,.2f} tokens/s&quot;)<br>        print(f&quot;Latency p(50): {metrics[&#39;Latency (ms/token) p(50)&#39;]:,.2f} ms/token&quot;)<br>        return metrics<br><br># Run the load test<br>concurrent_users = 5<br>number_of_requests = 100<br>res = run_load_test(number_of_requests, concurrent_users)</pre><pre># get_metrics code<br>import time<br>import re<br><br>import pandas as pd<br><br><br>def convert_string_to_float_ms(input_string):<br>    if input_string[-2:] == &quot;µs&quot;:<br>        return float(input_string[:-2]) / 1000<br>    elif input_string[-2:] == &quot;ms&quot;:<br>        return float(input_string[:-2])<br>    elif input_string[-1:] == &quot;s&quot;:<br>        return float(input_string[:-1]) * 1000<br><br><br>def extract_metrics(input_string):<br>    kpi_pattern = r&#39;#\d+\[3m(\w+)#\d+\[0m#\d+\[2m=#\d+\[0m&quot;([^&quot;]+)&quot;&#39;<br>    kpis = re.findall(kpi_pattern, input_string)<br>    kpi_dict = dict(kpis)<br><br>    try:<br>        parsed_kpis = {<br>            &quot;total_time_ms&quot;: convert_string_to_float_ms(kpi_dict[&quot;total_time&quot;]),<br>            &quot;inference_time_ms&quot;: convert_string_to_float_ms(kpi_dict[&quot;inference_time&quot;]),<br>            &quot;time_per_token_ms&quot;: convert_string_to_float_ms(kpi_dict[&quot;time_per_token&quot;]),<br>            &quot;queue_time_ms&quot;: convert_string_to_float_ms(kpi_dict[&quot;queue_time&quot;]),<br>        }<br>    except:<br>        print(input_string)<br>        raise<br>    return parsed_kpis<br><br><br>def get_metrics_from_cloudwatch(<br>    endpoint_name=None,<br>    st=None,<br>    et=None,<br>    cu=None,<br>    boto3_session=None,<br>    total_requests=None,<br>    generated_tokens=250,<br>):<br>    print(&quot;Waiting for logs to be available ...&quot;)<br>    time.sleep(120)<br>    log_end_time = time.time()<br>    client = boto3_session.client(&quot;logs&quot;)<br><br>    loggroup = f&quot;/aws/sagemaker/Endpoints/{endpoint_name}&quot;<br><br>    start_query_response = client.start_query(<br>        logGroupName=loggroup,<br>        startTime=st,<br>        endTime=int(log_end_time),<br>        queryString=&quot;fields @message | sort @timestamp desc&quot;,<br>        limit=10000,<br>    )<br>    query_id = start_query_response[&quot;queryId&quot;]<br><br>    response = None<br><br>    while response == None or response[&quot;status&quot;] == &quot;Running&quot;:<br>        print(&quot;Waiting for query to complete ...&quot;)<br>        time.sleep(1)<br>        response = client.get_query_results(queryId=query_id)<br>    metrics = []<br>    for record in response[&quot;results&quot;]:<br>        if &quot;3mtotal_time&quot; in record[0][&quot;value&quot;]:<br>            metrics.append(extract_metrics(record[0][&quot;value&quot;]))<br><br>    if len(metrics) == 0:<br>        raise Exception(&quot;No metrics found&quot;)<br><br>    df = pd.DataFrame.from_records(metrics)<br><br>    throughput_gen_per_s = total_requests / (et - st) * generated_tokens<br><br>    # calculate the average inference time<br>    inference_time = {<br>        &quot;Number of requests&quot;: len(df),<br>        &quot;Concurrent Requests&quot;: int(cu),<br>        &quot;Thorughput (tokens/second)&quot;: throughput_gen_per_s,<br>        &quot;Latency (ms/token) min&quot;: df[&quot;time_per_token_ms&quot;].min(),<br>        &quot;Latency (ms/token) p(50)&quot;: df[&quot;time_per_token_ms&quot;].median(),<br>        &quot;Latency (ms/token) p(90)&quot;: df[&quot;time_per_token_ms&quot;].quantile(0.9),<br>        &quot;Latency Request ms min&quot;: df[&quot;total_time_ms&quot;].min(),<br>        &quot;Latency Request ms p(50)&quot;: df[&quot;total_time_ms&quot;].median(),<br>        &quot;Latency Request ms p(90)&quot;: df[&quot;total_time_ms&quot;].quantile(0.9),<br>        &quot;Latency Infernece ms min&quot;: df[&quot;inference_time_ms&quot;].min(),<br>        &quot;Latency Infernece ms p(50)&quot;: df[&quot;inference_time_ms&quot;].median(),<br>        &quot;Latency Infernece ms p(90)&quot;: df[&quot;inference_time_ms&quot;].quantile(0.9),<br>        &quot;Queue time ms min&quot;: df[&quot;queue_time_ms&quot;].min(),<br>        &quot;Queue time ms p(50)&quot;: df[&quot;queue_time_ms&quot;].median(),<br>        &quot;Queue time ms p(90)&quot;: df[&quot;queue_time_ms&quot;].quantile(0.9),<br>    }<br>    return inference_time</pre><p>For further information regarding the code and the benchmark results, please refer to the GitHub repository at the following link: <a href="https://github.com/WaelDataReply/Load_testing_SageMaker_endpoints/tree/main">Load Testing SageMaker Endpoints Repository</a>.</p><p><strong>Bechmark results</strong></p><p>The benchmark results compare the performance of two LLMs, Llama3–8B and Mistral-7B-Instruct, across three different instance types: g5.2xlarge, g5.4xlarge, and g5.48xlarge. The performance is measured in terms of throughput (tokens per second) and latency at different percentiles (minimum, p(50), p(90)). To conduct this benchmark, we employed a simple test setup featuring 5 concurrent users, 100 requests, and 250 token generations across the different scenarios. While this setup offers valuable insights, further comprehensive testing is recommended for a complete benchmark analysis.</p><p>Let’s summarize the key insights from this benchmark:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MAof7g7rB6oeoFoG4LskgQ.png" /><figcaption>Performance comparison of LLama3–8B and Mistral 7B Instruct across different instance types</figcaption></figure><p><strong>Throughput</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/571/1*j-3mVF_Ug4FiEFRM-Y2oIA.png" /></figure><p><strong><em>Llama3–8B:</em></strong></p><ul><li>Achieved the highest throughput on the g5.48xlarge instance with 149.7 tokens/second.</li><li>The g5.2xlarge and g5.4xlarge instances had slightly lower throughput, with 140.4 and 139.7 tokens/second, respectively.</li></ul><p><strong><em>Mistral-7B-Instruct:</em></strong></p><ul><li>Showed consistent throughput across the three instances, with values ranging from 138.9 to 140.4 tokens/second.</li><li>The g5.4xlarge had the highest throughput with 140.4 tokens/second, followed closely by the other two instances.</li></ul><p>Overall, Llama3–8B demonstrated higher throughput on the largest instance (g5.48xlarge), while Mistral-7B-Instruct had consistent throughput across all three instances.</p><p><strong>Latency</strong></p><p>Latency measures how quickly the model processes each token, with lower values indicating better performance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/595/1*F94ygkBOoR8kPbUnmCGPcA.png" /></figure><p><strong><em>Llama3–8B:</em></strong></p><ul><li>Minimum latency was lowest on the g5.4xlarge (35.93 ms/token) and highest on the g5.2xlarge (36.15 ms/token).</li><li>At the 50th percentile, latencies were similar across instances, ranging from 38.05 to 38.24 ms/token.</li><li>The 90th percentile latency was highest on the g5.48xlarge (38.28 ms/token), while the other two instances were slightly lower.</li></ul><p><strong><em>Mistral-7B-Instruct:</em></strong></p><ul><li>The g5.48xlarge had the lowest minimum latency (35.33 ms/token), while the g5.2xlarge had the highest (35.44 ms/token).</li><li>At the 50th percentile, latencies were also consistent, with the g5.4xlarge having the lowest value (35.38 ms/token).</li><li>The 90th percentile latency followed a similar pattern, with the g5.48xlarge and g5.4xlarge having the lowest values.</li></ul><p>For latency, Mistral-7B-Instruct showed lower values compared to Llama3–8B across most instances, indicating quicker token processing times. The lower latency values for Mistral-7B-Instruct suggest it might be more efficient in terms of token processing.</p><p><strong>In a nutshell</strong></p><ul><li>Throughput: Llama3–8B achieved higher throughput, particularly on the largest instance (g5.48xlarge). Mistral-7B-Instruct had more consistent throughput across all instances.</li><li>Latency: Mistral-7B-Instruct generally had lower latency, indicating faster token processing times.</li></ul><p>These results indicate that if throughput is the primary concern, Llama3–8B on g5.48xlarge might be preferable. If latency is more critical, Mistral-7B-Instruct, especially on g5.4xlarge or g5.48xlarge, could be the better choice.</p><p><strong>Conclusion</strong></p><p>In conclusion, Amazon SageMaker simplifies ML model deployment, but ensuring optimal performance requires load testing. This post highlighted the importance of load testing SageMaker inference endpoints to evaluate resilience, simulate realistic workloads, and uncover performance issues. Our solution architecture seamlessly integrated SageMaker with AWS Lambda and API Gateway for efficient communication. Benchmark results compared LLM performance across instances, aiding in informed model and instance selection. Ultimately, conducting load tests on SageMaker endpoints is crucial for delivering reliable ML services.</p><p>If you have any questions about load testing or Amazon SageMaker, feel free to leave a comment or reach out to via email at <strong><em>w.saideni@reply.com</em></strong>. We’re committed to assisting you in optimizing the performance of your ML endpoints, ensuring they deliver their utmost potential.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/652/1*v9mqRrST5Lnm_NFhxhqzKQ.jpeg" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fd2cf601e20e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[LLMs-based systems evaluation: A tremendous pillar of LLMOps]]></title>
            <link>https://medium.com/@wael-saideni/llms-based-systems-evaluation-a-tremendous-pillar-of-llmops-a51a7ce6c0c0?source=rss-f849de33d418------2</link>
            <guid isPermaLink="false">https://medium.com/p/a51a7ce6c0c0</guid>
            <category><![CDATA[generative-ai]]></category>
            <category><![CDATA[llmops]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[llm-evaluation]]></category>
            <dc:creator><![CDATA[Wael SAIDENI]]></dc:creator>
            <pubDate>Thu, 28 Mar 2024 10:14:47 GMT</pubDate>
            <atom:updated>2024-03-28T10:14:47.078Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-WolLiP_tUxw-n-9_U-xHw.png" /><figcaption><strong>© Image generated by Titan Image Generator G1 on Amazon Bedrock</strong></figcaption></figure><p>LLMOps refers to the strategic management of constructing and implementing Large Language Models (LLMs) for production use. It streamlines the workflow for developers of generative AI by leveraging automation. Key tasks in developing an LLM application, including experimenting with various models, testing diverse prompts, and assessing models based on different metrics, can be automated by adhering to LLMOps best practices.</p><p>A fundamental aspect of LLMOps lies in the rigorous evaluation of models. This pillar encompasses the systematic assessment of various metrics to gauge the performance, reliability, and suitability of large language models (LLMs) for their intended applications. Model evaluation in LLMOps involves not only quantitative measures such as accuracy and efficiency but also qualitative aspects like coherence, fluency, and semantic understanding. Additionally, it entails the comparison of different LLMs under diverse conditions to identify the most effective solutions for specific tasks or domains. By prioritizing model evaluation within LLMOps frameworks, developers can make informed decisions and continuously refine LLMs to meet evolving requirements and standards.</p><p>In this blog post, I will delve into the strategy of evaluating LLMs-based systems, explore the main metrics and framewoks used for the evaluation, and present the evaluation workflow employed in assessing their performance.</p><h3><strong>LLMs evaluation is not LLMs-based systems evaluation?</strong></h3><p>Before diving deeper into LLMs systems evaluation, it’s important to understand the difference between evaluating just the LLM itself and evaluating a whole system that uses the LLM.</p><p>Today’s LLMs can do a lot of different things like chatbot conversations, finding names in text (Named Entity Recognition), making summaries, answering questions, analyzing feelings in text (sentiment analysis), translating languages, and more. We usually test these models on standard tests like <a href="https://gluebenchmark.com/"><strong>GLUE</strong></a> <strong>(General Language Understanding Evaluation), SuperGLUE, </strong><a href="https://rowanzellers.com/hellaswag/"><strong>HellaSwag</strong></a><strong>, </strong><a href="https://arxiv.org/abs/2004.04696"><strong>BLEURT</strong></a><strong> (BLEU-based Evaluation of Language Understanding in Real Text), </strong><a href="https://github.com/sylinrl/TruthfulQA"><strong>TruthfulQA</strong></a><strong>, </strong><a href="https://arxiv.org/abs/1808.07036"><strong>QuAC</strong></a><strong> (Question Answering in Context) and </strong><a href="https://github.com/hendrycks/test"><strong>MMLU</strong></a><strong> (Multi-Modal Language Understanding)</strong> using specific measures.</p><p>But even though these LLMs are really good at many tasks, they might not work perfectly for our particular needs right away. Sometimes we need to adjust or “fine-tune” the LLM using our own data to make it better for our specific use. Evaluating a fine-tuned model or a system that uses LLMs usually means comparing how well it works with a real dataset, if we have one.</p><p>This is important because now it’s not just about the LLM itself performing well, but also about making sure the whole system gives the right results. To do this, we have to use the right instructions for the LLM, set up good ways to get the data, think about how the model is built (especially if we’re fine-tuning it), and more. However, choosing the right parts and doing a thorough evaluation of the whole system can be quite tricky.</p><h3><strong>Evaluation strategies for Language Model (LM) systems: Offline and Online</strong></h3><p>Because many features of Language Model (LM) systems are new and uncertain, it’s important to be careful when releasing them to protect privacy and meet social responsibility standards. When developing features, offline evaluation helps, but it doesn’t fully show how changes affect user experience in a live setting. So, a combination of online and offline evaluations can ensure the robustness of the solution, enhance the quality of LLMs outputs and upgrade the development and deployment lifecycle.</p><p>This approach guarantees that the model remains reliable and efficient by conducting controlled and automated tests.</p><h4><strong>Offline evaluation</strong></h4><p>Offline evaluation carefully examines Language Models (LLMs) using specific datasets. It checks if the features meet performance criteria before they are put into production.</p><p>This method relies on two primary techniques: the first involves using a dataset created by humans for evaluation, while the second involves employing an LLM as a judge.</p><p><strong>Tools to evaluate LLMs based systems using datasets created by humans</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1VeRm3hgWAsuCS68iA6bTQ.png" /><figcaption><strong>Some known evaluation frameworks for LLMs based applications</strong></figcaption></figure><p>Tools for evaluating LLMs based on datasets created by humans are provided by a variety of startups and cloud service providers like AWS. Some of the tools in this category include:</p><p><strong>1. Amazon SageMaker Clarify</strong>: This tool within Amazon SageMaker is specifically designed to detect biases and explain model predictions, enhancing transparency and fairness in LLM applications.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/921/1*dhbJS2MZ1sd82fA3lUBDzQ.png" /><figcaption><strong>AWS architecture for an evaluation process using SageMaker Clarify</strong></figcaption></figure><p>Amazon SageMaker Clarify enables to evaluate LLMs on various metrics such as accuracy, robustness, toxicity, stereotyping and factual knowledge for automated, and style, coherence, relevance for human-based evaluation, and evaluation methods by providing a framework to evaluate LLMs and LLM-based services such as Amazon Bedrock. SageMaker Clarify provides evaluation results in various formats to support diverse roles within the LLM workflow.</p><p>When high-risk alerts are detected while evaluating the LLM, Ops teams can work on a Reinforcement Learning approach using Amazon SageMaker GroundTruth and prepare a fine-tuning dataset.</p><p>Finally, evaluation results &amp; reports provide business stakeholders with comparative benchmarks between different models and versions.</p><p><strong>2. Amazon Bedrock Model Evaluation Feature</strong>: Offering an evaluation framework, this feature from Amazon provides capabilities to rigorously assess LLM performance across different metrics, ensuring reliability and robustness in deployment.</p><p>Model Evaluation within Amazon Bedrock empowers you to assess, compare, and choose the optimal foundation model tailored to your specific use case.</p><p>To evaluate your large model on Amazon Bedrock, you have the option to select either:</p><p><em>⛔</em> <strong>Automatic evaluation</strong>: an evaluation based on predefined metrics (using built-in datasets or by bringing your own evaluation dataset):</p><ul><li>Accuracy</li><li>Robustness</li><li>Toxicity</li></ul><p>⛔ <strong>Human evaluation</strong>: an evaluation based on custom metrics:</p><ul><li>Friendliness</li><li>Relevance</li><li>Style</li><li>Alignment to brand voice</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BihWoQekeI_w4td_YzWjXA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Q2oOBKIrE9LFhLzDWYaqOg.png" /><figcaption><strong>Bedrock Model Evaluation in practice: Automatic evaluation for Q&amp;A tasks | LLM = Claude 2</strong></figcaption></figure><p>🔗For more information about Amazon bedrock: <a href="https://aws.amazon.com/bedrock/">https://aws.amazon.com/bedrock/</a></p><p><strong>Tools to evaluate LLMs based systems using the technique of LLM as a Judge</strong></p><p>Tools designed to evaluate LLMs through the approach of LLM as a Judge, when an LLM is evaluating an LLM, are offered by a range of startups such as Giskard:</p><p>· <strong>Giskard</strong>: Designed specifically for assessing LLMs, Giskard boasts a suite of functionalities crafted to meticulously analyze model outputs for biases, inaccuracies, and other potential vulnerabilities. It stands as a transformative force in the realm of LLM vulnerability detection, leveraging an open-source library and employing the innovative “LLM as a Judge” approach.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*T-09ReF0fSNUmuId3Iuwvg.jpeg" /><figcaption><strong>Giskard in practice: Automatic evaluation for RAG tasks | LLM = Claude 2 | Vulnerability detected: Hallucination and Misinformation</strong></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rswYJVweh5-40jsUgdLszw.jpeg" /><figcaption><strong>Giskard in practice: Automatic evaluation for RAG tasks | LLM = Claude 2 | Vulnerability detected: Harmfulness</strong></figcaption></figure><p>This pioneering quality assurance tool revolutionizes the landscape by empowering users to identify a spectrum of critical issues inherent in large models, including hallucinations, misinformation, harmful outputs, stereotypes, disclosures, and prompt injections. These capabilities offer a comprehensive safeguard against unintended consequences and ethical pitfalls.</p><p>In a field where even the most sophisticated models can harbor vulnerabilities that evade traditional testing methods, Giskard emerges as a vital solution. Its mission is clear: to proactively address vulnerabilities, automate the scanning process, and facilitate the safe deployment of LLMs into production environments. With Giskard, stakeholders can confidently navigate the complexities of deploying large language models while upholding ethical standards and mitigating risks.</p><p>In this notebook, I evaluated <a href="https://www.linkedin.com/feed/hashtag/?keywords=claude&amp;highlightedUpdateUrns=urn%3Ali%3Aactivity%3A7128681939888152576">Claude</a> V2, one of AWS <a href="https://www.linkedin.com/feed/hashtag/?keywords=bedrock&amp;highlightedUpdateUrns=urn%3Ali%3Aactivity%3A7128681939888152576">Bedrock</a>’s most advanced models, using <a href="https://www.linkedin.com/feed/hashtag/?keywords=gpt&amp;highlightedUpdateUrns=urn%3Ali%3Aactivity%3A7128681939888152576">GPT</a>-4 and <a href="https://www.linkedin.com/company/giskard-ai/">Giskard</a> open-source library, and it costs less than $5.</p><p><a href="https://github.com/WaelDataReply/LLM_As_A_Judge">GitHub - WaelDataReply/LLM_As_A_Judge: This repository contains the notebook to detect vulnerabilities of Claude-V2 on AWS Bedrock using GPT4 and Giskard open-source library.</a></p><p>For more information about how to use Giskard in practice: <a href="https://docs.giskard.ai/en/latest/getting_started/quickstart/quickstart_llm.html">https://docs.giskard.ai/en/latest/getting_started/quickstart/quickstart_llm.html</a></p><p>It’s worth noting that several alternative frameworks exist for evaluating GenAI applications, including <a href="https://docs.ragas.io/en/stable/">Ragas</a>, <a href="https://github.com/stanford-futuredata/ARES">ARES</a>, <a href="https://docs.smith.langchain.com/">LangSmith</a>, <a href="https://github.com/confident-ai/deepeval">DeepEval</a>, etc.</p><p><strong>Offline evaluation metrics of LLM systems</strong></p><p>When examining the evaluation metrics of Language Model systems, it’s vital to customize the criteria according to the application scenarios. This ensures a detailed and context-specific evaluation. Various applications require unique performance measures that match their individual objectives and needs.</p><p>In this section, I will outline the main metrics to assess in each scenario:</p><p>🕵🏼‍♂️ Summarization</p><p>🕵🏼‍♂️ Q&amp;A</p><p>🕵🏼‍♂️ NER</p><p>🕵🏼‍♂️ Text-to-SQL</p><p>🕵🏼‍♂️ RAG</p><p>🔎 <strong>Summarization</strong></p><p><strong>1. Overlap-based metrics</strong></p><ul><li><a href="https://huggingface.co/spaces/evaluate-metric/bleu"><strong>BLEU</strong></a>: BLEU score is a precision-based measure, and it ranges from 0 to 1. The closer the value is to 1, the better the prediction.</li><li><a href="https://huggingface.co/spaces/evaluate-metric/rouge"><strong>ROUGE</strong></a>: Recall-Oriented Understudy for Gisting Evaluation is a set of metrics and accompanying software package used for evaluating automatic summarization and machine translation software in natural language processing.</li><li><a href="https://github.com/google-research/google-research/tree/master/rouge"><strong>ROUGE-N</strong></a>: Measures the overlap of n-grams (contiguous sequences of n words) between the candidate text and the reference text. It computes precision, recall, and F1 score based on the n-gram overlap.</li><li><a href="https://github.com/google-research/google-research/tree/master/rouge"><strong>ROUGE-L</strong></a>: Measures the longest common subsequence (LCS) between the candidate text and the reference text. It computes the precision, recall, and F1 score based on the length of the LCS.</li><li><a href="https://huggingface.co/spaces/evaluate-metric/meteor"><strong>METEOR</strong></a>: An automatic metric for machine translation evaluation that is based on a generalized concept of unigram matching between the machine-produced translation and human-produced reference translations.</li></ul><p><strong>2. Semantic similarity-based metrics</strong></p><ul><li><a href="https://huggingface.co/spaces/evaluate-metric/bertscore"><strong>BERTScore</strong></a>: It leverages the pre-trained contextual embeddings from BERT and matches words in candidate and reference sentences by cosine similarity.</li><li><a href="https://paperswithcode.com/paper/moverscore-text-generation-evaluating-with"><strong>MoverScore</strong></a>: Text Generation Evaluating with Contextualized Embeddings and Earth Mover Distance.</li></ul><p><strong>3. Specialized in summarization</strong></p><ul><li><a href="https://github.com/danieldeutsch/SUPERT"><strong>SUPERT</strong></a>: Unsupervised Multi-Document Summarization Evaluation &amp; Generation.</li><li><a href="https://paperswithcode.com/method/blanc"><strong>BLANC</strong></a>: A reference-less metric of summary quality that measures the difference in masked language modeling performance with and without access to the summary.</li><li><a href="https://github.com/salesforce/factCC"><strong>FactCC</strong></a>: Evaluating the Factual Consistency of Abstractive Text Summarization</li></ul><p>🔎 <strong>Q&amp;A</strong></p><ul><li><a href="https://github.com/danieldeutsch/sacrerouge/blob/master/doc/metrics/qaeval.md"><strong>QAEval</strong></a><strong>: </strong>A question-answering based metric for estimating the content quality of a summary.</li><li><a href="https://github.com/salesforce/QAFactEval"><strong>QAFactEval</strong></a><strong>: </strong>QA-Based Factual Consistency Evaluation</li><li><a href="https://github.com/ThomasScialom/QuestEval"><strong>QuestEval</strong></a><strong>: </strong>An NLG metric to assess whether two different inputs contain the same information. It can deal with multimodal and multilingual inputs.</li></ul><p>🔎 <strong>Named Entity Recognition (NER)</strong></p><p><strong>1. </strong><a href="https://docs.aws.amazon.com/comprehend/latest/dg/cer-metrics.html"><strong>Classification metrics</strong></a><strong>: </strong>Classification metrics (precision, recall, accuracy, F1 score, etc.) at entity level or model level.</p><p><strong>2. </strong><a href="https://github.com/neulab/InterpretEval"><strong>InterpretEval</strong></a><strong>: </strong>The main idea is to divide the data into buckets of entities based on attributes such as entity length, label consistency, entity density, sentence length, etc., and then evaluate the model on each of these buckets separately.</p><p>🔎 <strong>Text-to-SQL</strong></p><p><strong>1. Exact-set-match accuracy (EM): </strong>EM evaluates each clause in a prediction against its corresponding ground truth SQL query. However, a limitation is that there exist numerous diverse ways to articulate SQL queries that serve the same purpose.</p><p><strong>2. Execution Accuracy (EX): </strong>EX evaluates the correctness of generated answers based on the execution results.</p><p><strong>3. VES (Valid Efficiency Score): </strong>A metric to measure the efficiency along with the usual execution correctness of a provided SQL query.</p><p>🔎 <strong>Retrieval Augmented Generation (RAG)</strong></p><p>The retrieval-augmented generation technique is a methodology employed in natural language processing (NLP) and generative AI that combines elements of both retrieval-based and generation-based approaches. In this technique, a model first retrieves relevant information from a predefined database or knowledge base based on the input query or context. Then, it generates a response or output using the retrieved information along with additional generated content.</p><p>It represents one of the most common projects in GenAI, which is why we pay close attention to the main vulnerabilities of these systems.</p><p>The main evaluation metrics for retrieval system encompass:</p><p><strong>1. Hallucinations and Security Risks</strong>: LLMs may produce unforeseen and detrimental outputs, such as racist remarks or insults, posing significant security risks.</p><p><strong>2. Irrelevant Content</strong>: LLMs might generate content unrelated to the intended topic, like discussing art instead of insurance in a GenAI solution tailored for insurance companies.</p><p><strong>3. Accuracy Verification</strong>: Ensuring the accuracy of LLM responses poses a challenge, as they may not consistently align with the provided information.</p><p><strong>4. Lack of Common Sense</strong>: Despite sounding plausible, LLM-generated responses can be factually incorrect or nonsensical, reflecting a deficiency in common sense reasoning.</p><p><strong>5. Bias and Fairness</strong>: LLMs may inadvertently perpetuate or amplify biases present in their training data, potentially leading to biased content generation.</p><p><strong>6. Validation Errors</strong>: Responses from LLMs may fail to adhere to specified format requirements, introducing errors in data processing and interpretation.</p><p><strong>7. Data Leakage</strong>: There’s a risk of LLMs unintentionally memorizing and regurgitating sensitive or private information from their training data, raising concerns about privacy and confidentiality.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*d6twkBp7m1mQE4pps1Rf4g.png" /></figure><p><strong>Offline evaluation process of LLMs-based systems</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OhKHqfaLxKZpK3WWVfYDVw.png" /><figcaption><strong>Evaluation process of LLMs-based systems</strong></figcaption></figure><p><strong>Evaluating an LLM involves several key steps:</strong></p><p><strong>1. Scan Phase</strong>: This initial step involves thoroughly examining the LLM to identify any vulnerabilities. These vulnerabilities could include harmful biases, hallucination (generating incorrect or nonsensical information), or susceptibility to prompt injection (altering the model’s behavior through input manipulation).</p><p><strong>2. Quantification</strong>: Once vulnerabilities are identified, the next step is to quantify their impact. This involves measuring the extent to which these vulnerabilities affect the performance and reliability of the model. Techniques such as perturbation analysis and unit testing are commonly used to assess the impact of vulnerabilities.</p><p><strong>3. Evaluation</strong>: After quantifying the vulnerabilities, a comprehensive performance report is generated. This report provides insights into the overall effectiveness and reliability of the LLM, highlighting areas that need improvement or correction.</p><p><strong>Offline post-Evaluation Actions</strong>:</p><p>✅ If the Model is Approved (Go): If the evaluation indicates that the model meets the required standards for production use, it can be deployed into production. However, continuous monitoring using CI/CD (Continuous Integration/Continuous Deployment) techniques is essential to ensure ongoing performance and reliability.</p><p>❌ If the Model is Not Approved (No Go): If the evaluation reveals significant vulnerabilities or shortcomings that render the model unsuitable for production, several options are available:</p><ul><li><strong>Model Correction</strong>: This involves fine-tuning the existing model to address identified vulnerabilities. Techniques such as model fine-tuning, prompt engineering (modifying input prompts to guide the model’s responses), or adjusting model parameters can help rectify issues and improve performance.</li><li><strong>Model Replacement</strong>: If the vulnerabilities are severe or cannot be adequately addressed through correction, replacing the LLM with another model may be necessary. This could involve selecting a different LLM architecture or exploring models developed by different research groups or organizations.</li></ul><p>By following these steps and taking appropriate actions based on the evaluation results, organizations can ensure the reliability, effectiveness, and ethical soundness of their language models in various applications and contexts.</p><h3><strong>Online evaluation</strong></h3><p>After the model passes offline evaluation and is deployed into production, online evaluation takes place in real-world settings. It uses actual user data to evaluate how well the model performs and how satisfied users are, gathering feedback directly and indirectly.</p><p>In this section, I provide a list of online metrics that have to be measured when the LLM is deployed in production with reference from <a href="https://klu.ai/glossary/llm-evaluation">https://klu.ai/glossary/llm-evaluation</a></p><p>🔎 <strong>User engagement &amp; utility metrics</strong></p><ul><li><strong>Submitted</strong>: Number of users who submit prompts</li><li><strong>Responded</strong>: LLM app generates responses without errors</li><li><strong>Clicks</strong>: User clicks the reference documentation from LLM response if any</li></ul><p>🔎 <strong>User interaction</strong></p><ul><li><strong>User acceptance rate</strong>: Frequency of user acceptance, which varies by context</li><li><strong>LLM conversation</strong>: Average number of LLM conversations per user</li><li><strong>Active days</strong>: Active days using LLM features per user</li><li><strong>Interaction timing</strong>: Average time between prompts and responses, and time spent on each</li></ul><p>🔎<strong> Quality of response</strong></p><ul><li><strong>Prompt and response length</strong>: Average lengths of prompts and responses</li><li><strong>Edit distance metrics</strong>: The average edit distance measurement between user prompts and among LLM responses and retained content serves as an indicator of prompt refinement and content customization</li></ul><p>🔎 <strong>User feedback and retention</strong></p><ul><li><strong>User feedback</strong>: Number of responses with Thumbs Up/Down feedback</li><li><strong>Periodic Active User</strong>: Number of users who visited the LLM app feature in certain period</li><li><strong>User return rate</strong>: Percentage of users who used this feature in the previous week/month continue to use this feature this week/month</li></ul><p>🔎 <strong>Performance metrics</strong></p><ul><li><strong>Requests per second (Concurrency)</strong>: Number of requests processed by the LLM per second</li><li><strong>Tokens per second</strong>: Counts the tokens rendered per second during LLM response streaming</li><li><strong>Time to first token render</strong>: Time to first token render from submission of the user prompt, measured at multiple percentiles</li><li><strong>Error rate</strong>: Error rate for different types of errors such as 401 error, 429 error.</li><li><strong>Reliability</strong>: The percentage of successful requests compared to total requests, including those with errors or failures</li><li><strong>Latency</strong>: The average duration of processing time between the submission of a request query and the receipt of a response</li></ul><p>🔎 <strong>Cost metrics</strong></p><ul><li><strong>GPU/CPU utilization</strong>: Utilization in terms of total number of tokens</li><li><strong>LLM calls cost</strong>: Example cost Bedrock API calls</li><li><strong>Infrastructure cost</strong>: Costs from storage, networking, computing resources, etc.</li><li><strong>Operations cost</strong>: Costs from maintenance, support, monitoring, logging, security measures, etc.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aVm_-OFcOeMe8thriWw-pg.png" /><figcaption><strong>[Summary] The LLMs-based systems evaluation tree</strong></figcaption></figure><p><strong>Conclusion</strong></p><p>In this blog, I discussed a fundamental aspect of the LLMOps paradigm: evaluating LLM-based systems. I started by distinguishing between LLMs and LLMs-based systems evaluation to highlight the main differences. I then explored both offline and online evaluation strategies, focusing on main evaluation tools and metrics.</p><p>These evaluation approaches stand as a crucial pillar within any LLMOps project, ensuring the robustness and efficacy of the deployed applications.</p><p>It’s important to acknowledge the dynamic nature of generative AI technology, with new metrics and frameworks continually emerging beyond those outlined here. Staying informed about these advancements is vital for maintaining relevance and efficacy in LLM system evaluation.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a51a7ce6c0c0" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>