<?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"><channel><title><![CDATA[deepdev-ai - Engineering & Research]]></title><description><![CDATA[deepdev-ai - Engineering & Research]]></description><link>https://deepdev-ai.hashnode.dev</link><image><url>https://cdn.hashnode.com/uploads/logos/6b0b841d0e82463d822e0bce/357c0b38-6c3e-414a-b5f4-f13494fe95fc.png</url><title>deepdev-ai - Engineering &amp; Research</title><link>https://deepdev-ai.hashnode.dev</link></image><generator>RSS for Node</generator><lastBuildDate>Fri, 04 Dec 2026 21:17:42 GMT</lastBuildDate><atom:link href="https://deepdev-ai.hashnode.dev/rss.xml" rel="self" type="application/rss+xml"/><language><![CDATA[en]]></language><ttl>60</ttl><item><title><![CDATA[Agentic RAG in Production: Hybrid Search, Reranking, and Self-Corrective Retrieval]]></title><description><![CDATA[Build production-grade agentic RAG: hybrid BM25 + dense search with RRF, cross-encoder reranking, and CRAG-style self-correction.]]></description><link>https://deepdev-ai.hashnode.dev/agentic-rag-in-production-hybrid-search-reranking-and-self-corrective-retrieval-mx6yfklc</link><guid isPermaLink="true">https://deepdev-ai.hashnode.dev/agentic-rag-in-production-hybrid-search-reranking-and-self-corrective-retrieval-mx6yfklc</guid><category><![CDATA[RAG ]]></category><category><![CDATA[llm]]></category><category><![CDATA[AI Engineering]]></category><category><![CDATA[Python]]></category><category><![CDATA[claude]]></category><dc:creator><![CDATA[deepdev-ai]]></dc:creator><pubDate>Thu, 03 Dec 2026 02:47:37 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/6b0b841d0e82463d822e0bce/f4a1dde1-3dd3-4c42-93fc-832e32ed4fe0.jpg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Most RAG demos fail in production for the same reason: they treat retrieval as a single, trusted step. A user query goes in, the top-k chunks come out, and the model is expected to make sense of whatever arrives. When the chunks are wrong, the answer is confidently wrong.</p>
<p>An agentic RAG system treats retrieval as a decision loop instead. It retrieves broadly, ranks precisely, evaluates what it found, and corrects course when the evidence is weak. Here is the architecture I use, and what keeps it economical.</p>
<ol>
<li>Hybrid Retrieval and Cross-Encoder Reranking</li>
</ol>
<p>Dense embeddings capture semantic similarity but routinely miss exact identifiers: error codes, product SKUs, function names, regulatory clauses. BM25 has the opposite profile: it is excellent on rare tokens and blind to paraphrase. Running both and fusing the results covers each retriever's weakness.</p>
<p>The fusion method matters. Raw scores from BM25 and cosine similarity live on incompatible scales, so normalizing them is fragile. Reciprocal Rank Fusion (RRF) sidesteps the problem by using only rank positions:</p>
<p>RRF(d) = Σ 1 / (k + rank_i(d))</p>
<p>With the conventional k = 60, a document ranked highly by either retriever floats to the top, and one ranked well by both wins decisively. There are no weights to tune and no score calibration to maintain.</p>
<p>Fusion gives you a good candidate set, typically 50 to 100 chunks, but not a good ordering. For that, add a cross-encoder reranker. Unlike a bi-encoder, which embeds query and document independently, a cross-encoder reads them together and scores the pair with full attention. It is far more accurate and far too slow to run over a whole corpus, which is why it belongs after fusion: reduce 100 candidates to the best 5 to 8. This two-stage design (cheap recall, expensive precision) is the backbone of every serious retrieval stack.</p>
<ol start="2">
<li>Self-Corrective Retrieval Loops (CRAG)</li>
</ol>
<p>Even excellent retrieval returns bad context for some queries: ambiguous phrasing, vocabulary mismatch, or a question the corpus simply cannot answer. Corrective RAG (CRAG) adds an evaluation step between retrieval and generation:</p>
<p>Retrieve and rerank as above. A lightweight evaluator grades each chunk as relevant, ambiguous, or irrelevant. If enough relevant evidence exists, generate the answer from the surviving chunks only. If not, rewrite the query and retrieve again, or fall back to another source such as web search.</p>
<p>The evaluator should be fast and cheap, because it runs on every request. Claude Haiku is a natural fit: grading relevance against a rubric is a narrow task that does not need a frontier model. The query rewriter can be the same model. Given the original question and the reasons the chunks failed, it produces a reformulation that targets the gap, for example expanding an acronym or decomposing a compound question.</p>
<ol start="3">
<li>Filtering Retrieved Chunks with Claude and Pydantic</li>
</ol>
<p>The evaluator must return structured output that downstream code can trust. Forcing a tool call with a Pydantic-derived schema, then validating the result, gives you exactly that.</p>
<pre><code class="language-python">import anthropic
from typing import Literal
from pydantic import BaseModel, Field

client = anthropic.Anthropic()  # reads ANTHROPIC_API_KEY from the environment
GRADER_MODEL = "claude-haiku-5-5"


class ChunkGrade(BaseModel):
    """Relevance verdict for a single retrieved chunk."""
    chunk_id: int
    verdict: Literal["relevant", "ambiguous", "irrelevant"]
    reason: str = Field(max_length=200)


class GradedBatch(BaseModel):
    grades: list[ChunkGrade]


# The rubric is static, so it is a good candidate for prompt caching.
# Note: caching only activates above the model's minimum cacheable prompt length.
GRADER_SYSTEM = [{
    "type": "text",
    "text": (
        "You grade retrieved text chunks for a question-answering system. "
        "'relevant': directly helps answer the question. "
        "'ambiguous': related but incomplete or tangential. "
        "'irrelevant': off-topic or misleading. "
        "Judge each chunk independently and call submit_grades exactly once."
    ),
    "cache_control": {"type": "ephemeral"},
}]

# Derive the tool schema from the Pydantic model: one source of truth.
GRADE_TOOL = {
    "name": "submit_grades",
    "description": "Submit one relevance grade per chunk.",
    "input_schema": GradedBatch.model_json_schema(),
}


def filter_chunks(query: str, chunks: list[str]) -&gt; tuple[list[str], bool]:
    """Return (relevant_chunks, needs_retry)."""
    numbered = "\n\n".join(f"[{i}] {c}" for i, c in enumerate(chunks))

    response = client.messages.create(
        model=GRADER_MODEL,
        max_tokens=1024,
        system=GRADER_SYSTEM,
        tools=[GRADE_TOOL],
        tool_choice={"type": "tool", "name": "submit_grades"},  # force structured output
        messages=[{
            "role": "user",
            "content": f"Question: {query}\n\nChunks:\n{numbered}",
        }],
    )

    # Validate the model's output; raises if the schema is violated.
    tool_block = next(b for b in response.content if b.type == "tool_use")
    batch = GradedBatch.model_validate(tool_block.input)

    keep = {g.chunk_id for g in batch.grades if g.verdict == "relevant"}
    relevant = [c for i, c in enumerate(chunks) if i in keep]

    # Trigger a rewrite when no chunk is clearly relevant.
    return relevant, len(relevant) == 0


def rewrite_query(query: str, chunks: list[str]) -&gt; str:
    """Ask the grader model for a sharper reformulation after a failed retrieval."""
    response = client.messages.create(
        model=GRADER_MODEL,
        max_tokens=100,
        messages=[{
            "role": "user",
            "content": (
                "Retrieval failed for this question. Rewrite it as a single, "
                "self-contained search query using more specific terminology. "
                f"Return only the query.\n\nQuestion: {query}"
            ),
        }],
    )
    return response.content[0].text.strip()
</code></pre>
<p>The outer loop is then trivial: retrieve, call filter_chunks, and if needs_retry is true, call rewrite_query and go around again, up to a hard limit.</p>
<ol start="4">
<li>Latency and Cost Optimization in Production</li>
</ol>
<p>A self-corrective loop multiplies model calls, so discipline matters. Three levers do most of the work.</p>
<p>Tiered model routing. Use the smallest model that can do each job. Haiku handles grading and query rewriting; a larger model such as Sonnet is reserved for final synthesis, and only on queries that need it. Simple lookups can skip the loop entirely if the first retrieval scores well above a confidence threshold.</p>
<p>Prompt caching. The grader's rubric, tool schema, and any few-shot examples are identical on every call. Marking them with cache_control means repeated requests read them at a fraction of the normal input price and with lower latency. The same applies to a stable system prompt on the generation side. Keep cacheable content at the front of the prompt and variable content (the query and chunks) at the end.</p>
<p>Iteration limits. Cap the loop at two or three rewrites. Beyond that, returns diminish sharply and tail latency explodes. When the budget is exhausted, degrade gracefully: answer with the best available context and state the uncertainty, or tell the user the corpus does not contain the answer. An honest "I don't know" is better than a fourth retry.</p>
<p>Two further practices pay off: grade chunks in a single batched call, as above, rather than one call per chunk, and log every verdict and rewrite. That log is your evaluation dataset, and it shows exactly where your retrieval fails.</p>
<p>Closing</p>
<p>Agentic RAG is not about adding complexity for its own sake. It is about making retrieval accountable: every answer rests on evidence that was ranked, graded, and, when necessary, retrieved again. Built with tiered models, caching, and firm iteration limits, the loop adds modest cost and delivers a large gain in reliability.</p>
<p>If you are designing retrieval or agentic architectures for an enterprise environment and want an experienced second opinion, visit <a href="http://deepdev-ai.github.io">deepdev-ai.github.io</a> for consulting and AI architecture engagements.</p>
]]></content:encoded></item><item><title><![CDATA[Building Enterprise-Ready MCP Servers for Anthropic Claude: Architecture & Security]]></title><description><![CDATA[A practical engineering guide to designing secure, deterministic Model Context Protocol (MCP) servers in Python for enterprise Claude workflows.]]></description><link>https://deepdev-ai.hashnode.dev/building-enterprise-ready-mcp-servers-for-anthropic-claude-architecture-security</link><guid isPermaLink="true">https://deepdev-ai.hashnode.dev/building-enterprise-ready-mcp-servers-for-anthropic-claude-architecture-security</guid><category><![CDATA[claude]]></category><category><![CDATA[Model Context Protocol]]></category><category><![CDATA[Python]]></category><category><![CDATA[agentic AI]]></category><category><![CDATA[software architecture]]></category><dc:creator><![CDATA[deepdev-ai]]></dc:creator><pubDate>Tue, 01 Dec 2026 02:18:35 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/6b0b841d0e82463d822e0bce/43435bad-c859-4e4c-a994-15f82e40227d.jpg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>While the Model Context Protocol (MCP) has rapidly become the standard interface for connecting Anthropic Claude to internal tools, databases, and enterprise APIs, moving an MCP server from a local developer workstation to a production environment requires strict security and architectural boundaries. An MCP server is not merely a wrapper around an API—it is an execution boundary between a probabilistic reasoning model and your core business systems. Here is how to architect and harden production-grade MCP servers in Python.</p>
<ol>
<li>Design Intent-Based Tools, Not Raw CRUD Wrappers</li>
</ol>
<p>A common mistake when building MCP servers is exposing low-level database operations (such as execute_sql or generic http_request tools) directly to the model. This maximizes the blast radius of hallucinations and prompt injections. Instead, design narrow, intent-specific tools with strict input validation using Pydantic: • Principle of Least Privilege: Expose only read-only or tightly scoped domain actions (e.g., get_customer_invoice_status rather than query_billing_db). • Structured Schema Contracts: Enforce explicit types, regex patterns, and enum constraints on every parameter before execution reaches your backend.</p>
<pre><code class="language-python">from mcp.server.fastmcp import FastMCP
from pydantic import BaseModel, Field
import re

mcp = FastMCP("enterprise-billing-gateway")

class InvoiceRequest(BaseModel):
    invoice_id: str = Field(..., pattern=r"^INV-\d{6}$", description="Format: INV-123456")
    tenant_id: str = Field(..., min_length=4, max_length=32)

@mcp.tool()
async def get_invoice_status(req: InvoiceRequest) -&gt; dict:
    """Safely retrieve read-only invoice status for an authorized tenant."""
    # 1. Deterministic authorization check (never rely on LLM context alone)
    if not await verify_tenant_access(req.tenant_id, req.invoice_id):
        return {"error": "Access denied or invoice not found."}

    # 2. Fetch and sanitize response payload
    record = await fetch_invoice_from_erp(req.invoice_id)
    return {
        "invoice_id": record.id,
        "status": record.status,
        "amount_eur": record.amount,
        "due_date": str(record.due_date)
    }
</code></pre>
<ol start="2">
<li>Defend Against Indirect Prompt Injection in Tool Outputs</li>
</ol>
<p>When Claude invokes an MCP tool to read emails, support tickets, or external documents, untrusted text enters the model's context window. Malicious instructions embedded inside that data can attempt to hijack subsequent tool calls. • Output Sanitization &amp; Minimization: Strip HTML, hidden markdown, and unnecessary metadata before returning tool outputs to Claude. Return only the minimal fields required for the next reasoning step. • Separation of Read and Write Capabilities: Never allow an agent session that ingests untrusted external text to autonomously invoke state-mutating tools without a Human-in-the-Loop (HITL) confirmation gate.</p>
<ol start="3">
<li>Transport Security, Timeouts, and Observability</li>
</ol>
<p>Local MCP servers typically run over stdio, whereas enterprise deployments require remote, multi-tenant transports (such as Streamable HTTP / SSE) behind an API gateway. • Zero-Trust Identity Propagation: Pass short-lived OAuth2 / JWT tokens per session rather than static service-account keys, ensuring every MCP tool call inherits the exact RBAC permissions of the human user. • Strict Execution Timeouts &amp; Circuit Breakers: Bound every external API or database call inside your MCP server with strict timeouts so a slow downstream service never stalls an entire agentic workflow. • Structured Audit Logging: Log every tool invocation with correlation IDs, validated input parameters, execution latency, and user identity for compliance with frameworks like the EU AI Act.</p>
<p>Conclusion</p>
<p>The Model Context Protocol dramatically simplifies how enterprise AI systems interact with internal infrastructure, but reliability comes from deterministic engineering around the protocol. By enforcing strict Pydantic schemas, scoping tool granularity, and propagating user-level authorization, organizations can deploy Claude-powered workflows safely at scale.</p>
]]></content:encoded></item><item><title><![CDATA[Architecting Production-Grade Agentic Systems: Beyond the LLM Prototype]]></title><description><![CDATA[Move from experimental prompt demos to deterministic, governed, and scalable enterprise AI architectures with Anthropic Claude and MCP.]]></description><link>https://deepdev-ai.hashnode.dev/architecting-production-grade-agentic-systems-beyond-the-llm-prototype</link><guid isPermaLink="true">https://deepdev-ai.hashnode.dev/architecting-production-grade-agentic-systems-beyond-the-llm-prototype</guid><category><![CDATA[llm]]></category><category><![CDATA[claude]]></category><category><![CDATA[ClaudeCode]]></category><category><![CDATA[agentic AI]]></category><category><![CDATA[softwarearchitecture]]></category><category><![CDATA[#ArtificialIntelligence ]]></category><dc:creator><![CDATA[deepdev-ai]]></dc:creator><pubDate>Mon, 30 Nov 2026 00:08:05 GMT</pubDate><content:encoded><![CDATA[<p>Most enterprise Generative AI initiatives stall between a promising Jupyter notebook demo and production deployment. The reason is rarely model capability—it is architecture. Large Language Models (LLMs) are inherently probabilistic reasoning engines, whereas enterprise systems require deterministic execution, strict access control, predictable latency, and auditability. Bridging this gap is the core discipline of modern AI Engineering. Here is the four-pillar architectural framework I apply when designing production-grade Agentic AI and Claude-based solutions across European and APAC enterprise environments.</p>
<ol>
<li>Decouple Probabilistic Reasoning from Deterministic Execution</li>
</ol>
<p>A common anti-pattern in early LLM apps is allowing the model to generate raw SQL, shell commands, or unstructured API payloads directly against production infrastructure. Instead, treat the LLM strictly as a reasoning and routing layer, while delegating all side effects to deterministic, stateless backend services: • Model Context Protocol (MCP): Standardize how models like Anthropic Claude discover and invoke enterprise tools, internal databases, and documentation repositories through strongly typed schemas. • Explicit State Graphs: Replace open-ended, unpredictable loops with explicit state machines (such as LangGraph), where every state transition, retry policy, and fallback path is observable and bounded.</p>
<img src="https://cdn.hashnode.com/uploads/covers/6b0b841d0e82463d822e0bce/948eb8ff-1d96-49ec-a425-d7c724a918e7.svg" alt="" style="display:block;margin:0 auto" />

<ol start="2">
<li>Treat the LLM as an Untrusted Actor</li>
</ol>
<p>In zero-trust enterprise security, an autonomous agent operating on external data (emails, PDFs, web pages, user queries) is exposed to indirect prompt injection. • Input &amp; Output Guardrails: Deploy lightweight validation layers before and after inference to detect adversarial instructions, mask Personally Identifiable Information (PII), and enforce strict JSON output contracts. • Human-in-the-Loop (HITL) Gates: Any irreversible or high-impact tool execution (e.g., financial transactions, database mutations, external communications) must trigger a deterministic pause requiring explicit human approval.</p>
<ol start="3">
<li>Engineer Context, Not Just Prompts</li>
</ol>
<p>Prompt engineering alone cannot compensate for noisy or bloated context windows. As context grows, attention degrades and token costs scale nonlinearly. • Agentic RAG over Naive Vector Search: Combine hybrid retrieval (dense embeddings + BM25 lexical search), cross-encoder reranking, and query decomposition so the model receives only high-signal context. • Prompt Caching &amp; Model Routing: Route routine classification or extraction subtasks to fast, cost-efficient models while reserving frontier reasoning models for complex synthesis—leveraging prompt caching to cut latency and inference spend dramatically.</p>
<ol start="4">
<li>Continuous LLMOps &amp; Governance by Design</li>
</ol>
<p>Under frameworks such as the EU AI Act, enterprise AI systems must be traceable, reproducible, and evaluated against clear risk thresholds. • Versioned Artifacts: System prompts, tool schemas, and retrieval configurations must live under Git version control alongside application code. • Automated Evaluation Gates: Before shipping any prompt or model update, run automated regression suites measuring retrieval precision, faithfulness (hallucination rate), and end-to-end task completion against a curated golden dataset.</p>
<p>Conclusion</p>
<p>Generative AI delivers sustainable ROI only when treated with the same rigor as distributed systems engineering. By combining structured protocols like MCP, bounded agentic workflows, and automated evaluation, organizations can deploy autonomous systems that are both capable and safe. Looking to architect production-grade AI systems, custom Claude &amp; MCP integrations, or Agentic RAG pipelines? Explore my engineering services or reach out directly at <a href="http://deepdev-ai.github.io">deepdev-ai.github.io</a>.</p>
]]></content:encoded></item></channel></rss>