<?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 Vengadesa Boopathi on Medium]]></title>
        <description><![CDATA[Stories by Vengadesa Boopathi on Medium]]></description>
        <link>https://medium.com/@vengiboopathi?source=rss-d9be6945e434------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*kkBwCf_sJPz8LgC7mvRmXQ.jpeg</url>
            <title>Stories by Vengadesa Boopathi on Medium</title>
            <link>https://medium.com/@vengiboopathi?source=rss-d9be6945e434------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 10:22:50 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@vengiboopathi/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[Your AI Agent Didn’t Crash. It Just Quietly Got Worse.]]></title>
            <link>https://medium.com/@vengiboopathi/your-ai-agent-didnt-crash-it-just-quietly-got-worse-8cef6b698be1?source=rss-d9be6945e434------2</link>
            <guid isPermaLink="false">https://medium.com/p/8cef6b698be1</guid>
            <category><![CDATA[ai-agent-observability]]></category>
            <category><![CDATA[observability]]></category>
            <dc:creator><![CDATA[Vengadesa Boopathi]]></dc:creator>
            <pubDate>Thu, 05 Nov 2026 05:50:41 GMT</pubDate>
            <atom:updated>2026-11-05T05:50:41.719Z</atom:updated>
            <content:encoded><![CDATA[<p><em>A practical guide to observability for AI agents: what to capture, what to measure, and how to turn anomalies into alerts and tickets.</em></p><p>Picture a few weeks after your agent goes to production. Nothing is on fire. The dashboards are green, the error rate is flat, latency looks normal. And yet users keep saying the answers feel off.</p><p>That is the moment you learn that monitoring an agent is not the same as monitoring a service. A traditional service fails loudly. An agent fails politely: it returns a confident, well-formatted answer that happens to be wrong. This article covers why that happens and what to build so you can see it.</p><h3>Agent Observability</h3><blockquote>Observability is the ability to understand the internal state of a complex system by looking only at what it emits externally, which in practice means its telemetry.</blockquote><p>Monitoring and observability are related but different:</p><ul><li><strong>Monitoring</strong> tells you <em>that</em> something is wrong. It watches for conditions you defined in advance.</li><li><strong>Observability</strong> lets you ask <em>why</em>, including about failures you never anticipated.</li></ul><p>The classic telemetry signals are:</p><blockquote><strong>Metrics:</strong> numeric measurements over time, such as latency, request counts, token usage.</blockquote><blockquote><strong>Logs:</strong> timestamped records of discrete events.</blockquote><blockquote><strong>Traces:</strong> the end-to-end path of one request or workflow, broken into timed steps called spans.</blockquote><p>In practice the setup is a loop. Your system sends metrics, logs, and traces to an external platform. The platform evaluates rules for the anomalies you care about. When one fires, an alert goes out and a ticket is created so a human owns the problem.</p><p>For AI systems there is a fourth signal worth adding to that list: <strong><em>evaluation results</em></strong>, meaning scores that describe the <em>quality</em> of an output, not just whether it was produced. We will come back to that.</p><h3>The layers of AI observability</h3><ul><li><strong>LLM observability:</strong> prompts, completions, token usage, cost, latency, finish reasons, model versions.</li><li><strong>RAG observability:</strong> what was retrieved, relevance scores, which chunks ended up in the prompt, and whether the answer was grounded in them.</li><li><strong>Agent observability:</strong> the full chain of reasoning, tool calls, handoffs between agents, and state changes across a run.</li><li><strong>ML observability:</strong> data drift, feature quality, and model performance over time for traditional ML models.</li><li><strong>AI infrastructure observability:</strong> GPU utilization, queues, rate limits, vector database health, and the services underneath everything.</li></ul><p>Agent observability sits on top of the others and inherits all of their problems. A bad retrieval step or a rate-limited model call shows up as an agent failure, so you need visibility into every layer below.</p><h3>Traces, not just logs</h3><p>Here is the shift that matters most: <strong>logs capture events, traces capture causality.</strong></p><p>A log tells you a tool was called. A trace tells you <em>why</em>: this tool was called because of this LLM output, which was produced from this context, which was assembled from these pieces. When you debug an agent, causality is the whole game.</p><p>For each step in a run, a good trace captures five categories of data:</p><ol><li><strong>Context snapshot:</strong> What the LLM actually saw: system prompt, conversation history, retrieved documents, accumulated tool results. Storing this at full fidelity is expensive, so many teams store a hash plus the delta from the previous step, and keep full content only for sampled or failed runs.</li><li><strong>LLM invocation record:</strong> Model ID, temperature, prompt and completion token counts, latency, and the finish reason. The finish reason is often ignored, but a length finish on a step that was supposed to produce structured output quietly corrupts everything downstream.</li><li><strong>Tool call record:</strong> Tool name, input arguments, raw response, latency, HTTP status where relevant, and a schema validation result. That last field is the one most teams skip, and it is the one that catches the silent failures described above.</li><li><strong>Verification result:</strong> Did the step’s output pass the inline checks you defined, such as format checks, guardrails, or a groundedness test?</li><li><strong>State transition:</strong> What changed in the agent’s working state: the state machine move, or the updated scratchpad or memory.</li></ol><p>The principle: every step in the execution graph gets a span, and every span carries enough structured data to reconstruct what happened <em>without replaying the run</em>.</p><h3>OpenTelemetry:</h3><p>OpenTelemetry (OTel) is the vendor-neutral standard for generating and exporting telemetry. For agents, it is a good foundation for a few reasons:</p><ul><li>You instrument your code once and can send the data to any compatible backend, so you are not locked in to one vendor.</li><li>Spans nest naturally, which maps well onto an agent run containing LLM calls, tool calls, and sub-agents.</li><li>The OTel community has been developing semantic conventions for generative AI (attributes such as model name and token counts). These are still evolving, so check the current spec rather than hard-coding assumptions.</li></ul><p>You do not have to hand-write everything. Many agent frameworks emit OTel traces natively or through instrumentation libraries such as OpenInference or OpenLLMetry, and observability platforms like Langfuse can ingest OTel data. Check what your specific framework supports before building custom wrappers.</p><h3>Setting it up, step by step</h3><p>First, four words you will keep running into:</p><ul><li><strong>API and SDK:</strong> The API is what your code calls to create a span. The SDK is the engine behind it that collects, batches, and sends the data.</li><li><strong>Instrumentation:</strong> The code that creates spans. It is either automatic (a library does it for you) or manual (you write it).</li><li><strong>Exporter:</strong> The part that ships data out, usually over <strong>OTLP</strong>, OpenTelemetry’s standard wire format. By default, OTLP uses port 4318 for HTTP and 4317 for gRPC.</li><li><strong>Collector:</strong> A small standalone service that receives telemetry, cleans it up, and routes it to your backends. Optional, but strongly recommended.</li></ul><p>Here is the sample example in Python. Other languages follow the same shape:</p><pre>import time<br>import logging<br>from typing import Dict, Any<br><br># OpenTelemetry Tracing<br>from opentelemetry import trace<br>from opentelemetry.sdk.trace import TracerProvider<br>from opentelemetry.sdk.trace.export import BatchSpanProcessor<br>from opentelemetry.exporter.otlp.proto.grpc.trace_exporter import OTLPSpanExporter<br>from opentelemetry.sdk.resources import Resource<br><br># OpenTelemetry Metrics<br>from opentelemetry import metrics<br>from opentelemetry.sdk.metrics import MeterProvider<br>from opentelemetry.sdk.metrics.export import PeriodicExportingMetricReader<br>from opentelemetry.exporter.otlp.proto.grpc.metric_exporter import OTLPMetricExporter<br><br># OpenTelemetry Logging<br>from opentelemetry._logs import set_logger_provider<br>from opentelemetry.sdk._logs import LoggerProvider, LoggingHandler<br>from opentelemetry.sdk._logs.export import BatchLogRecordProcessor<br>from opentelemetry.exporter.otlp.proto.grpc._log_exporter import OTLPLogExporter<br><br># ==========================================<br># 1. SETUP OPENTELEMETRY INFRASTRUCTURE<br># ==========================================<br>OTLP_ENDPOINT = &quot;localhost:4317&quot;  # Replace with external collector/backend endpoint<br><br>resource = Resource.create({&quot;service.name&quot;: &quot;multi-agent-orchestrator&quot;, &quot;service.version&quot;: &quot;1.0.0&quot;})<br><br># Traces setup<br>trace_provider = TracerProvider(resource=resource)<br>trace_exporter = OTLPSpanExporter(endpoint=OTLP_ENDPOINT, insecure=True)<br>trace_provider.add_span_processor(BatchSpanProcessor(trace_exporter))<br>trace.set_tracer_provider(trace_provider)<br>tracer = trace.get_tracer(&quot;agent-orchestrator&quot;)<br><br># Metrics setup<br>metric_reader = PeriodicExportingMetricReader(<br>    OTLPMetricExporter(endpoint=OTLP_ENDPOINT, insecure=True),<br>    export_interval_millis=5000<br>)<br>meter_provider = MeterProvider(resource=resource, metric_readers=[metric_reader])<br>metrics.set_meter_provider(meter_provider)<br>meter = metrics.get_meter(&quot;agent-orchestrator&quot;)<br><br># Setup metrics instruments<br>agent_call_counter = meter.create_counter(<br>    name=&quot;agent_executions_total&quot;,<br>    description=&quot;Total count of agent invocations&quot;,<br>    unit=&quot;1&quot;<br>)<br>tool_latency_histogram = meter.create_histogram(<br>    name=&quot;tool_execution_duration_seconds&quot;,<br>    description=&quot;Duration of tool execution in seconds&quot;,<br>    unit=&quot;s&quot;<br>)<br><br># Logging setup (bridges Python logging -&gt; OpenTelemetry -&gt; OTLP)<br>logger_provider = LoggerProvider(resource=resource)<br>log_exporter = OTLPLogExporter(endpoint=OTLP_ENDPOINT, insecure=True)<br>logger_provider.add_log_record_processor(BatchLogRecordProcessor(log_exporter))<br>set_logger_provider(logger_provider)<br><br>handler = LoggingHandler(level=logging.INFO, logger_provider=logger_provider)<br>logger = logging.getLogger(&quot;agent_orchestration&quot;)<br>logger.setLevel(logging.INFO)<br>logger.addHandler(handler)<br><br><br># ==========================================<br># 2. DEFINE AGENTS &amp; THEIR TOOLS<br># ==========================================<br><br>class WeatherAgent:<br>    &quot;&quot;&quot;Agent 1: Specialized in retrieving atmospheric conditions.&quot;&quot;&quot;<br>    <br>    def execute_tool(self, location: str) -&gt; Dict[str, Any]:<br>        with tracer.start_as_current_span(&quot;weather_agent_tool:get_weather&quot;) as span:<br>            start_time = time.time()<br>            span.set_attribute(&quot;agent.name&quot;, &quot;WeatherAgent&quot;)<br>            span.set_attribute(&quot;tool.input.location&quot;, location)<br><br>            # Simulated weather fetching logic<br>            logger.info(&quot;Executing get_weather tool&quot;, extra={&quot;location&quot;: location})<br>            time.sleep(0.1)  # Simulate I/O network delay<br>            result = {&quot;location&quot;: location, &quot;condition&quot;: &quot;Rainy&quot;, &quot;temperature_c&quot;: 19}<br>            <br>            span.set_attribute(&quot;tool.output.condition&quot;, result[&quot;condition&quot;])<br>            duration = time.time() - start_time<br>            tool_latency_histogram.record(duration, {&quot;tool&quot;: &quot;get_weather&quot;, &quot;status&quot;: &quot;success&quot;})<br>            return result<br><br><br>class NotificationAgent:<br>    &quot;&quot;&quot;Agent 2: Specialized in alerting users via simulated external delivery.&quot;&quot;&quot;<br>    <br>    def execute_tool(self, message: str, recipient: str) -&gt; Dict[str, Any]:<br>        with tracer.start_as_current_span(&quot;notification_agent_tool:send_notification&quot;) as span:<br>            start_time = time.time()<br>            span.set_attribute(&quot;agent.name&quot;, &quot;NotificationAgent&quot;)<br>            span.set_attribute(&quot;tool.input.recipient&quot;, recipient)<br><br>            # Simulated notification delivery logic<br>            logger.info(&quot;Executing send_notification tool&quot;, extra={&quot;recipient&quot;: recipient})<br>            time.sleep(0.08)  # Simulate API network delay<br>            result = {&quot;status&quot;: &quot;delivered&quot;, &quot;recipient&quot;: recipient, &quot;message&quot;: message}<br>            <br>            span.set_attribute(&quot;tool.output.status&quot;, result[&quot;status&quot;])<br>            duration = time.time() - start_time<br>            tool_latency_histogram.record(duration, {&quot;tool&quot;: &quot;send_notification&quot;, &quot;status&quot;: &quot;success&quot;})<br>            return result<br><br><br># ==========================================<br># 3. ORCHESTRATION PIPELINE<br># ==========================================<br><br>class AgentOrchestrator:<br>    def __init__(self):<br>        self.weather_agent = WeatherAgent()<br>        self.notification_agent = NotificationAgent()<br><br>    def run_flow(self, target_city: str, recipient_contact: str):<br>        with tracer.start_as_current_span(&quot;orchestration_pipeline:weather_alert&quot;) as root_span:<br>            root_span.set_attribute(&quot;flow.type&quot;, &quot;weather_alert_trigger&quot;)<br>            logger.info(f&quot;Orchestration started for city: {target_city}&quot;)<br><br>            # Step 1: Delegate to Weather Agent<br>            agent_call_counter.add(1, {&quot;agent&quot;: &quot;WeatherAgent&quot;})<br>            weather_data = self.weather_agent.execute_tool(location=target_city)<br><br>            # Step 2: Orchestrator evaluation logic<br>            condition = weather_data.get(&quot;condition&quot;)<br>            alert_needed = condition in [&quot;Rainy&quot;, &quot;Stormy&quot;, &quot;Snowing&quot;]<br>            root_span.set_attribute(&quot;decision.alert_needed&quot;, alert_needed)<br><br>            # Step 3: Delegate to Notification Agent if alert criteria met<br>            if alert_needed:<br>                message = f&quot;Weather Alert: It is currently {condition} in {target_city}.&quot;<br>                agent_call_counter.add(1, {&quot;agent&quot;: &quot;NotificationAgent&quot;})<br>                notify_result = self.notification_agent.execute_tool(<br>                    message=message, <br>                    recipient=recipient_contact<br>                )<br>                logger.info(&quot;Notification successfully sent by orchestrator.&quot;, extra={&quot;result&quot;: notify_result})<br>            <br>            logger.info(&quot;Orchestration pipeline completed successfully.&quot;)<br>            return {&quot;weather&quot;: weather_data, &quot;alert_sent&quot;: alert_needed}<br><br><br># ==========================================<br># 4. EXECUTION RUNNER<br># ==========================================<br>if __name__ == &quot;__main__&quot;:<br>    orchestrator = AgentOrchestrator()<br>    print(&quot;Running multi-agent orchestrated task with OpenTelemetry instrumentation...&quot;)<br>    <br>    result = orchestrator.run_flow(target_city=&quot;Bengaluru&quot;, recipient_contact=&quot;user@example.com&quot;)<br>    print(&quot;Execution Result:&quot;, result)<br><br>    # Force flushes to ensure all traces, metrics, and logs leave memory before exit<br>    trace_provider.shutdown()<br>    meter_provider.shutdown()<br>    logger_provider.shutdown()<br>    print(&quot;Telemetry flushed to OTLP collector.&quot;)</pre><h3>A practical architecture</h3><p>Debugging and alerting are different jobs, so a sensible setup feeds telemetry to more than one place:</p><pre>Agent app (orchestrator, agents, tools)<br>        |  OpenTelemetry SDK: traces, metrics, logs<br>        v<br>   OTel Collector  (batching, filtering, redaction, routing)<br>     |          |            |<br>     v          v            v<br>  Traces     Metrics       Logs<br>Langfuse   Prometheus    Loki or similar<br>(and/or     |<br> Tempo,     v<br> Jaeger)   Grafana  --&gt;  Alertmanager  --&gt;  Slack / Teams / Email / On-call<br>                                                   |<br>                                                   v<br>                                            Ticketing (Jira, ServiceNow, ...)</pre><h3>Component breakdown</h3><ul><li><strong>OpenTelemetry:</strong> The instrumentation layer. Each agent run, LLM call, and tool call becomes a span; related spans group into a trace representing one workflow execution.</li><li><strong>OTel Collector:</strong> Central routing layer. It receives telemetry, batches, samples, filters, redacts, and forwards to backends. It acts as the gatekeeper to strip sensitive data before leaving your perimeter.</li><li><strong>Langfuse:</strong> AI-specific insight engine. Provides visual execution graphs, prompt/response inspection, token and cost analytics, evaluation scores, and end-to-end debugging. It is built for understanding why an agent made a decision, not for 3 a.m. paging.</li><li><strong>Prometheus, Grafana, and Alertmanager:</strong> Prometheus stores metrics, Grafana visualizes them, and Alertmanager routes notifications based on threshold rules (e.g., elevated latency, dropping pass rates).</li></ul><h3>The Collector: one config file that ties it together</h3><p>The Collector receives data from your application, cleans it, samples it, and fans it out. Its configuration consists of four sections: <strong>receivers</strong>, <strong>processors</strong>, <strong>exporters</strong>, and <strong>pipelines</strong>.</p><pre>receivers:<br>  otlp:<br>    protocols:<br>      http: { endpoint: 0.0.0.0:4318 }<br>      grpc: { endpoint: 0.0.0.0:4317 }<br>processors:<br>  memory_limiter:             # protects the Collector process itself<br>    check_interval: 1s<br>    limit_mib: 512<br>  attributes/redact:          # remove sensitive fields before egress<br>    actions:<br>      - { key: user.email, action: delete }<br>  tail_sampling:              # evaluate after the trace completes<br>    decision_wait: 30s<br>    policies:<br>      - { name: keep-errors, type: status_code, status_code: { status_codes: [ERROR] } }<br>      - { name: keep-slow,   type: latency,     latency: { threshold_ms: 30000 } }<br>      - { name: sample-rest, type: probabilistic, probabilistic: { sampling_percentage: 10 } }<br>  batch: {}<br>exporters:<br>  otlphttp/langfuse:          # traces for AI debugging<br>    endpoint: https://cloud.langfuse.com/api/public/otel<br>    headers:<br>      Authorization: &quot;Basic ${env:LANGFUSE_AUTH}&quot;<br>  otlp/tempo:                 # traces for general-purpose tracing (optional)<br>    endpoint: tempo:4317<br>    tls: { insecure: true }<br>  prometheus:                 # metrics exposed for Prometheus scraping<br>    endpoint: 0.0.0.0:8889<br>  otlphttp/loki:              # logs<br>    endpoint: http://loki:3100/otlp<br>service:<br>  pipelines:<br>    traces:<br>      receivers: [otlp]<br>      processors: [memory_limiter, attributes/redact, tail_sampling, batch]<br>      exporters: [otlphttp/langfuse, otlp/tempo]<br>    metrics:<br>      receivers: [otlp]<br>      processors: [memory_limiter, batch]<br>      exporters: [prometheus]<br>    logs:<br>      receivers: [otlp]<br>      processors: [memory_limiter, attributes/redact, batch]<br>      exporters: [otlphttp/loki]</pre><h3>Key considerations for this config</h3><ul><li><strong>Multiple trace destinations:</strong> Spans fan out to both Langfuse and Tempo simultaneously without changing application code.</li><li><strong>Tail sampling:</strong> Decisions are made after the trace completes, letting you preserve 100% of errors and slow runs while probabilistically sampling healthy runs. This requires the otelcol-contrib distribution.</li><li><strong>Central redaction:</strong> Sensitive attributes are deleted before hitting external networks.</li><li><strong>Target routing:</strong> Langfuse handles traces over HTTP; metrics route to Prometheus; logs route to Loki.</li></ul><p>To run locally with the contrib image:</p><pre>docker run -p 4317:4317 -p 4318:4318 -p 8889:8889 \<br>  -e LANGFUSE_AUTH=&quot;$(echo -n &#39;pk-lf-...:sk-lf-...&#39; | base64)&quot; \<br>  -v $(pwd)/otel-config.yaml:/etc/otelcol-contrib/config.yaml \<br>  otel/opentelemetry-collector-contrib</pre><h3>Architectural archetypes</h3><ol><li><strong>Open-source &amp; flexible:</strong> OpenTelemetry SDK + OTel Collector + Langfuse (traces/evals) + Prometheus/Grafana/Alertmanager (metrics/alerts).</li><li><strong>Framework-first:</strong> LangSmith for applications built heavily on LangChain/LangGraph, paired with OTel for underlying infrastructure.</li><li><strong>Enterprise APM:</strong> Direct OTel export into existing systems like Datadog or New Relic.</li><li><strong>Cloud-native:</strong> Managed cloud logging and monitoring solutions when regulatory policies mandate localized data handling.</li></ol><h3>Dashboards and SLOs: deciding what “healthy” means</h3><p>Data without a definition of “good” is just noise. Focus on four dedicated dashboard views:</p><ul><li><strong>Overview:</strong> Task completion rate, p95 and p99 latency, daily spend, and active alerts.</li><li><strong>Quality:</strong> Verification pass rates, eval scores (groundedness, relevance), and user feedback trends by task class.</li><li><strong>Tool health:</strong> Per-tool invocation counts, schema validation rates, latencies, and error rates.</li><li><strong>Cost &amp; capacity:</strong> Token consumption, API cost per task class, 429 rate limits, and prompt cache hit rates.</li></ul><h3>From anomaly to ticket</h3><p>Alerts should capture leading indicators of degradation. Below is a Prometheus alert rule checking for tool schema failures:</p><pre>groups:<br>  - name: agent-health<br>    rules:<br>      - alert: ToolSchemaFailureRateHigh<br>        expr: |<br>          sum by (tool) (rate(agent_tool_calls_total{schema_valid=&quot;false&quot;}[10m]))<br>            /<br>          sum by (tool) (rate(agent_tool_calls_total[10m])) &gt; 0.05<br>        for: 10m<br>        labels:<br>          severity: ticket<br>        annotations:<br>          summary: &quot;Tool {{ $labels.tool }}: more than 5% schema-invalid responses&quot;<br>          runbook: &quot;https://wiki.example.com/runbooks/tool-schema-failures&quot;</pre><h3>Alerting operational rules</h3><ul><li><strong>Link the alert directly to a trace view</strong> to expedite triage.</li><li><strong>Attach a concise runbook</strong> outlining verification and escalation steps.</li><li><strong>Alert on leading symptoms</strong> (schema validation failures, verification drops) before user degradation occurs.</li><li><strong>Use duration windows (</strong><strong>for: 10m)</strong> to prevent transient noise from creating spurious tickets.</li></ul><h3>Closing thought</h3><p>The uncomfortable truth about agents is that “it did not throw an error” means very little. A system can be fully up and still be wrong, and it will hand you bad data in a confident tone. Observability is how you stop trusting the green checkmark and start trusting evidence.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8cef6b698be1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Inside an AI Agent’s Mind: Where Context Comes From]]></title>
            <link>https://medium.com/@vengiboopathi/inside-an-ai-agents-mind-where-context-comes-from-92cac1ed8fca?source=rss-d9be6945e434------2</link>
            <guid isPermaLink="false">https://medium.com/p/92cac1ed8fca</guid>
            <dc:creator><![CDATA[Vengadesa Boopathi]]></dc:creator>
            <pubDate>Wed, 28 Oct 2026 11:55:08 GMT</pubDate>
            <atom:updated>2026-10-28T11:55:08.109Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Seven layers decide whether your agent is a clever demo or something you can actually deploy. Let’s walk through them, one floor at a time.</em></p><h3>The Brilliant Amnesiac Problem</h3><p>Picture an AI model as the smartest person you’ve ever met. It can work through graduate-level math, write solid code, and draft a sonnet before lunch.</p><p>It also has <strong>no idea who you are, what your company sells, or what happened five minutes ago.</strong></p><p>That’s the catch with every large language model. Whatever it needs to know has to be placed in front of it, in its <strong>context window</strong>, every single time. Getting the right information in, in the right shape, at the right moment, at a price you can afford: that’s <strong>context engineering</strong>.</p><p>Prompt engineering is about what you <em>ask</em>. Context engineering is about what the model <em>knows when you ask it</em>.</p><blockquote><em>The prompt tells the model what to do. The context tells it what to know.</em></blockquote><p>And here’s the part most people miss: when an agent disappoints, the model is rarely the problem. The information around it usually is.</p><h3>Think of it as onboarding a new hire</h3><p>Imagine your agent is a brilliant new employee on day one. Great brain, zero company knowledge. How would you set them up?</p><ul><li>Hand them the <strong>employee handbook</strong> → that’s your system prompt.</li><li>Point them to the <strong>company wiki</strong> → that’s retrieval (RAG).</li><li>Give them <strong>software and tools</strong> → that’s function calling and MCP.</li><li>Let them look at <strong>notes from yesterday’s meeting</strong> → that’s memory.</li><li>Teach them to <strong>keep their desk tidy</strong> → that’s compaction and subagents.</li><li>Decide <strong>what they’re allowed to see and do</strong> → that’s governance.</li></ul><p>Keep this picture in your head. We’ll keep coming back to it.</p><h3>1. Instruction Context: What the Agent Knows Before You Say Hello</h3><p>This is everything the agent is handed <em>before</em> your question arrives: the handbook, the how-to guides, the examples, the principles.</p><p>It’s also the same text sent on <strong>every turn</strong>, so it drives your baseline cost, and a mistake here gets repeated in every answer. Small layer, big leverage.</p><h3>System prompts</h3><p>A solid one usually covers a handful of things: the <strong>role</strong>, the <strong>rules</strong> (do and don’t), the <strong>output format</strong>, the <strong>scope</strong>, and <strong>when to use tools</strong>.</p><p>There’s a trap, though. Models pay the most attention to the start and end of their context and less to the middle. Researchers call it <strong>“lost in the middle”</strong> (Liu et al., 2023). So as a conversation grows, your system prompt gets a smaller slice of the model’s attention, and the agent slowly starts ignoring the rules. We call that <strong>prompt drift</strong>.</p><p>Three ways to fight it:</p><ol><li><strong>Re-inject</strong> the critical rules every few turns, or after a burst of tool calls.</li><li><strong>Check outputs</strong> with middleware that re-prompts when a rule is broken.</li><li><strong>Repeat the must-have rules</strong> at both the start and the end.</li></ol><h3>Skills: how-to knowledge you can version</h3><p>A skill is a <strong>reusable</strong>, <strong>structured set of instructions</strong> that teaches an agent how to perform a specific task., like “how to process a refund.” The common format is a SKILL.md file:</p><pre>---<br>name: customer-refund-processing<br>version: 2.1.0<br>description: Handles refund requests<br>tools_required: [order_lookup, payment_status, refund_initiate]<br>dependencies: [kyc-verification, fraud-check]<br>---<br># Refund Processing Procedure<br>1. Query payment_status for the order<br>2. If status == &quot;settled&quot;, continue; otherwise escalate to manual review<br>3. Run fraud-check, then refund_initiate</pre><p>Why a file and not a paragraph in your prompt? Because a paragraph can’t be versioned, tested, or rolled back. A file can. Procedures deserve the same care as code.</p><blockquote><strong>Prompt → agent-level behavior</strong></blockquote><blockquote><strong>Skill → task-level behavior</strong></blockquote><p>You can load skills three ways:</p><ul><li><strong>always-on</strong> (simple but pricey),</li><li><strong>trigger-matched</strong> (load when the intent fits),</li><li><strong>progressive</strong> (the agent sees only a name and short description first, around 50 tokens each, and fetches the full skill when it needs it). Progressive loading lets you keep hundreds of skills without paying for them all up front.</li></ul><h3>Few-shot examples</h3><p>Sometimes showing beats telling. A few input-output examples can teach tone, structure, and edge cases better than a paragraph of rules.</p><p>But examples ride along on every turn. Five examples at ~300 tokens each is 1,500 tokens. Over a 50-turn session, that’s <strong>75,000 tokens</strong> just for examples. So keep only the ones that teach something your instructions can’t, and put the most representative one last.</p><h3>Scratchpads and intent</h3><p>A <strong>structured scratchpad</strong> is a JSON area where the agent keeps its plan, current step, and observations. It carries state between turns and lets your code peek in and correct course.</p><p><strong>Intent</strong> goes one step further. Instructions say <em>what to do</em>. Intent says <em>how to decide when instructions clash or run out</em>:</p><pre>intent:<br>  primary_goal: &quot;Maximize task success for the user&quot;<br>  constraints:<br>    - priority: 1<br>      rule: &quot;Never fabricate data&quot;<br>    - priority: 2<br>      rule: &quot;Prefer concise responses&quot;<br>  trade_offs:<br>    - when: &quot;accuracy vs. speed&quot;<br>      resolution: &quot;accuracy for financial data, speed for operational queries&quot;</pre><p>Without it, an agent falls over the first time reality surprises it.</p><h3>The cost of the fixed prefix</h3><p>Here’s a back-of-the-envelope formula for input tokens in a session:</p><pre>Total input tokens ≈ T × P + (T × (T+1) / 2) × G</pre><p>T = turns, P = size of the fixed prefix, G = new tokens added per turn.</p><p>With 50 turns, a 5,000-token prefix, and 200 new tokens per turn, the prefix alone is about 250,000 tokens. That’s roughly <strong>half your bill</strong>, spent re-reading the same text.</p><p>The fix starts with ordering: put the <strong>most stable</strong> stuff first (system prompt, intent, tool schemas) and the <strong>most changeable</strong> last (examples, skills, scratchpad, chat). That way a change near the end only invalidates what comes after it, and your cache survives.</p><p><strong>Next up:</strong> The agent now knows who it is. But it knows nothing about <em>your</em> data. Enter retrieval.</p><h3>2. Retrieval Context: Giving the New Hire a Searchable Wiki</h3><p>Retrieval pulls knowledge from outside the model right when it’s needed. Unlike instructions, it changes with every question.</p><p><a href="https://medium.com/@vengiboopathi/retrieval-augmented-generation-a-complete-guide-from-foundations-to-production-53cc7cc91d90">Check this Article for more on RAG</a></p><h3>Vector RAG: search by meaning</h3><p>The classic recipe:</p><ol><li><strong>Chunk</strong> your documents (commonly 256 to 1,024 tokens each).</li><li><strong>Embed</strong> each chunk as a vector.</li><li><strong>Index</strong> the vectors for fast nearest-neighbor search.</li><li><strong>Search</strong> with the embedded question, then rerank and pack the best chunks into the prompt.</li></ol><p>It works beautifully, until it doesn’t. Common ways it breaks:</p><ul><li><strong>Semantic gap:</strong> you get chunks on the right <em>topic</em> that don’t contain the <em>answer</em>.</li><li><strong>Chunk boundaries:</strong> the answer is split across two chunks.</li><li><strong>Jargon:</strong> a general-purpose embedding model doesn’t understand your domain’s vocabulary.</li><li><strong>Top-k cutoff:</strong> the best chunk ranked just below the cutoff.</li><li><strong>Redundancy:</strong> five chunks say the same thing, and the budget is gone.</li></ul><p>Chunk size is a genuine trade-off. Small chunks are precise but fragment answers. Big chunks keep context but blur the meaning. Splitting at natural boundaries (sections, paragraphs) with a little overlap helps, though it never fully solves it.</p><p><strong>A neat trick: HyDE.</strong> Questions and answers don’t look alike. So instead of searching with the question, you have the model write a <em>hypothetical answer</em> first and search with that. Answer-shaped text tends to match answer-shaped documents better.</p><h3>Graph RAG: search by relationships</h3><p>Some questions aren’t about similar text. They’re about <em>connections</em>: “Who is the CEO of the company that acquired X?”</p><p>A knowledge graph stores entities and the relations between them, so the system can walk the path: X → acquired by → Company → CEO → Person. Vector search would need one chunk that happens to mention all of it.</p><p>Watch out for wrong entity matches, missing relations, and “context explosion” when you hop too far. Two or three hops is a common limit.</p><h3>Hybrid: the usual production answer</h3><p>In practice, teams combine <strong>vector search</strong> (meaning), <strong>keyword search like BM25</strong> (exact terms such as product codes), and sometimes <strong>graph search</strong> (relationships). A simple way to merge the results is <strong>Reciprocal Rank Fusion</strong>, which needs no score tuning. No single method wins every query type, and running two is cheap compared to a miss.</p><h3>Agentic retrieval: let the agent drive</h3><p>Instead of “retrieve once, then answer,” the agent decides whether to search, what to search for, and whether the results are enough. If they’re not, it rewrites the query and tries again.</p><p>It shines on multi-hop questions, ambiguous queries, and high-stakes domains. It’s overkill for simple lookups, and the extra round trips cost time and money.</p><h3>OKF: a portable format for company knowledge</h3><p>The <strong>Open Knowledge Format (OKF)</strong> is a Google Cloud specification, introduced in June 2026, for packaging organizational knowledge as a folder of Markdown files with YAML headers: one concept per file, linked together. Think table schemas, metric definitions, and runbooks.</p><p>A simplified example (check the spec for the exact fields):</p><pre>---<br>type: table<br>title: orders<br>description: Transaction records for all customer orders<br>sources: [warehouse schema export]<br>status: stable<br>stale_after: 2026-12-31<br>---<br># orders<br>...schema and notes in plain Markdown...</pre><p>The agent reads in steps: <strong>scan headers</strong> first (cheap), read the <strong>body</strong> only if the concept looks relevant, then follow <strong>links</strong> to related concepts. It’s the same “look at the index before committing tokens” idea you saw with skills.</p><p>One clarification: OKF is a <em>format</em>, not a search algorithm. You can still index it with vectors or walk it as a graph.</p><h3>Seven ways retrieval fails</h3><ul><li><strong>Recall:</strong> the right document never showed up → hybrid search, query rewriting</li><li><strong>Precision:</strong> junk got in → reranking, filters</li><li><strong>Ranking:</strong> the right doc was ranked too low → a cross-encoder reranker</li><li><strong>Chunking:</strong> the answer got split → overlap, parent-document retrieval</li><li><strong>Packing:</strong> good chunks were cut for space → token budgets</li><li><strong>Staleness:</strong> the document is outdated → freshness metadata</li><li><strong>Attribution:</strong> the model can’t cite its source → chunk-level provenance</li></ul><p>Here’s the part that surprises people: many “hallucinations” are actually <strong>retrieval failures.</strong> The right information never reached the model. So measure retrieval on its own (recall@k, MRR, NDCG), not just final answer quality.</p><h3>4. Tool Context: Giving the New Hire Real Software</h3><p>Retrieval tells the agent what’s <em>known</em>. Tools tell it what’s <em>true right now</em> and let it <em>do</em> things.</p><h3>How function calling works</h3><p>The model never runs anything itself. It writes a structured request (“call lookup_order with this ID&quot;), your code validates and runs it, and the result goes back into the conversation.</p><pre>{<br>  &quot;type&quot;: &quot;function&quot;,<br>  &quot;function&quot;: {<br>    &quot;name&quot;: &quot;lookup_order&quot;,<br>    &quot;description&quot;: &quot;Retrieves order status and metadata by order ID&quot;,<br>    &quot;parameters&quot;: {<br>      &quot;type&quot;: &quot;object&quot;,<br>      &quot;properties&quot;: {<br>        &quot;order_id&quot;: {&quot;type&quot;: &quot;string&quot;, &quot;description&quot;: &quot;UUID of the order&quot;}<br>      },<br>      &quot;required&quot;: [&quot;order_id&quot;],<br>      &quot;additionalProperties&quot;: false<br>    }<br>  }<br>}</pre><p>Treat the schema as a <strong>constraint</strong>, not documentation. Clear names and descriptions help the model pick the right tool. Enums keep arguments valid. additionalProperties: false stops it from inventing parameters. Strict mode forces the output to match the schema exactly.</p><h3>MCP: one plug for everything</h3><p>Before the <strong>Model Context Protocol (MCP)</strong>, connecting M apps to N data sources meant M×N custom integrations. With MCP, each side implements the protocol once, so you get M+N.</p><p><a href="https://medium.com/@vengiboopathi/model-context-protocol-0bab0bd7b8a3?sharedUserId=vengiboopathi">Check MCP Article</a></p><p>MCP servers offer three things. What matters is <strong>who’s in control</strong> of each:</p><ul><li><strong>Tools:</strong> the <em>model</em> decides when to call them (e.g., search_flights).</li><li><strong>Resources:</strong> the <em>application</em> decides what to attach (e.g., a file or schema).</li><li><strong>Prompts:</strong> the <em>user</em> triggers them (e.g., a slash command).</li></ul><h3>The “too many tools” problem</h3><p>Here’s something that catches teams off guard. If you connect many MCP servers and load every tool definition up front, the definitions alone can eat a big chunk of your window before the user says a word.</p><p>Anthropic’s engineering team (Adam Jones and Conor Kelly) put numbers on it in a November 2025 post. In <strong>one example workflow</strong>, moving data from Google Drive to Salesforce, token usage dropped from about <strong>150,000 to about 2,000</strong>, roughly 98.7%. That’s an impressive result, but it’s <em>one example</em>. An independent test with a single MCP server saw a 78.5% drop in input tokens, along with slightly higher latency. The benefit grows with the size of your tool catalog.</p><p>Two ideas make that possible:</p><p><strong>1. Progressive tool discovery.</strong> Give the model a small search_tools tool and load full definitions only for the tools it picks. A common rule of thumb is to switch this on once tool definitions take up a few percent of your window. Below that, loading everything is simpler and fine.</p><p><strong>2. Code execution with MCP.</strong> Instead of calling tools one at a time, the agent <em>writes code</em> that calls them inside a sandbox. Loops, filtering, and data crunching happen in code, and only the final result comes back to the model. Big datasets never touch your context, and sensitive data can stay out entirely. The price: you need a secure sandbox, and a model that writes reliable code.</p><h3>Slow tools: don’t make the user wait</h3><p>For tools that take a while, use <strong>async</strong> calls: the agent fires a webhook, keeps chatting, and the backend injects the result into the conversation when it’s ready, whether that’s 5 seconds or 5 minutes later.</p><h3>Keep tool results on a leash</h3><p>Tool results grow fast, and they go stale fast. They’re <strong>observations, not knowledge.</strong> Some habits that help:</p><ul><li><strong>Summarize and offload:</strong> save the full result to a file, return a short summary.</li><li><strong>Deduplicate:</strong> don’t inject the same thing twice.</li><li><strong>Expire old results:</strong> replace them with pointers after a few turns.</li><li><strong>Filter in code:</strong> return only the slice that matters.</li></ul><h3>5. Memory Context: What Did We Talk About Yesterday?</h3><p>The classic mistake: treating “memory” as a single vector database. Memory is really <strong>four different things</strong> with different speeds and rules.</p><h3>The four types</h3><ul><li><strong>Working memory:</strong> the live context window. Fastest, but gone when the session ends.</li><li><strong>Episodic memory:</strong> past sessions and events, with timestamps (“what happened last time?”). Being a bit stale is okay; it’s history.</li><li><strong>Semantic memory:</strong> distilled facts and preferences (“this user works in fintech”). <strong>Staleness is a bug,</strong> because it’s supposed to reflect what’s true <em>now</em>.</li><li><strong>Procedural memory:</strong> skills and playbooks (“how do I do this?”). Changes slowly and on purpose.</li></ul><p>Put them all in one vector store and you get stale facts returned with high confidence and timelines that don’t hold together.</p><p>One more thing: agents don’t have a persistent working memory. When it <em>feels</em> like an agent “remembers” across sessions, older memories are really being loaded back into the window at the start.</p><h3>Semantic memory is all about updates</h3><p>When a new fact arrives, the system must decide: replace the old one, keep both (with dates), or reject it. Skip that logic and your memory slowly fills with contradictions that nobody can sort out. Bugs can creep in at three points: when <strong>extracting</strong> (inventing a fact nobody said), <strong>updating</strong> (failing to replace an old fact), and <strong>answering</strong> (fetching the wrong one). Test each separately.</p><h3>Compression always loses something</h3><p>When the window fills, agents summarize older content. But summaries tend to lose the <em>concrete</em> stuff: file paths, version numbers, IDs, exact error messages. And if you summarize a summary, the damage compounds. The text still reads smoothly, so nobody notices what disappeared.</p><p>A 2026 Princeton paper called <strong>Slipstream</strong> attacks this directly. It runs the summarizer <em>in parallel</em> while the agent keeps working on the original context, then has a judge compare the two to check the summary kept what the agent actually needed. On coding and web-browsing benchmarks, it improved task accuracy by <strong>up to 8.8 percentage points</strong> and cut latency by <strong>up to 39.7%</strong>. (Those are best-case figures on specific benchmarks, and the biggest accuracy gain was on a small model.)</p><h3>Context folding: branch, then fold</h3><p>Instead of summarizing after the fact, the agent can <strong>branch</strong> into a sub-task, do the messy work in its own mini-context, and <strong>fold</strong> the result back as a short summary. It works a bit like a function call.</p><p>An ICML 2026 paper on <em>Context Folding</em> reports matching baseline performance with an active context up to <strong>10× smaller</strong>. A related project, <strong>AgentFold</strong> (ICLR 2026), kept a web agent’s context at roughly 7,000 tokens after 100 turns, around 92% smaller than a standard ReAct agent at the same point. A 30B-parameter model using it scored 36.2% on BrowseComp, ahead of DeepSeek-V3.1 (30.0%) and o4-mini (28.3%).</p><h3>ACE: a playbook that improves itself</h3><p><strong>ACE (Agentic Context Engineering)</strong> treats context as an evolving playbook with three roles:</p><ul><li><strong>Generator:</strong> does the task and leaves traces.</li><li><strong>Reflector:</strong> pulls lessons out of successes and failures.</li><li><strong>Curator:</strong> adds small, incremental updates to the playbook.</li></ul><p>The trick is making <strong>small additions instead of full rewrites</strong>, which avoids “context collapse” where details erode over time. The paper reports average gains of +10.6% on agent benchmarks and +8.6% on finance benchmarks, with no weight updates, and it can use natural execution feedback instead of labeled data. The gains are strongest on knowledge-rich, edge-case-heavy tasks and smaller on short, rule-like ones.</p><h3>Memory can be attacked</h3><p>Memory is also a security surface.</p><ul><li><strong>Poisoning:</strong> in the <strong>MINJA</strong> research, attackers with only ordinary user access got malicious records stored in an agent’s memory with 98.2% average success. Getting the agent to <em>act</em> on them worked about 76.8% of the time. (You’ll often see “&gt;95%” quoted, but that’s the injection rate, not the final attack rate.)</li><li><strong>Overwrites:</strong> a “write” tool that quietly replaces a whole file instead of adding to it can wipe memory.</li><li><strong>Stored isn’t the same as admitted:</strong> a memory can sit in your database and still be unfit to use right now, because it expired, came from an untrusted source, or doesn’t match the user’s current role. Check at read time.</li></ul><p>Practical defense: track where every memory came from, and enforce critical rules in code rather than hoping the model remembers them.</p><h3>⏸️ Pause and think</h3><p><em>A user tells your agent they moved from Pune to London. Three weeks later it still plans around Pune. Which memory tier misbehaved, and why?</em></p><p><strong>Answer:</strong> Semantic memory. The old fact was never superseded. It needs update and conflict-resolution logic at write time.</p><p><strong>Next up:</strong> Memory is about what lasts. Now, how do we manage the window <em>while</em> the agent is working?</p><h3>6. Execution Context: Keeping a Tidy Desk</h3><p>Agents get worse as their context fills up, often well before the advertised limit. This is called <strong>context rot</strong>, and it’s one reason some teams compact at a fixed, modest size (for example, around 30K tokens) instead of waiting for the window to fill.</p><p>Context grows in two different directions:</p><ul><li><strong>Deep:</strong> lots of turns piling up.</li><li><strong>Wide:</strong> one enormous tool result (say, an 80K-token file).</li></ul><p>They need different fixes. Summarizing aggressively won’t save you if a single giant result is the problem.</p><h3>Offloading (fixes “wide”)</h3><p>Write the big result to a file and leave a short pointer behind:</p><pre>Tool result offloaded (18,234 characters) at &#39;/path/tool_results/search-123.txt&#39;.<br>Preview: Fusion startups reported...</pre><p>The pointer keeps the location, the size, and a short preview. Nothing is lost; the agent can reopen the file anytime. Sensible rules: offload results above a size threshold, don’t offload the last few results the agent is still using, and offload repeated reads of the same file.</p><h3>Compaction (fixes “deep”)</h3><p>Replace older history with a summary, and keep recent turns word-for-word. Typical settings:</p><ul><li><strong>Trigger:</strong> when to compact (a percent of the window, or a fixed token count)</li><li><strong>Keep:</strong> how many recent messages stay untouched</li><li><strong>Target:</strong> how small to make it</li><li><strong>Model:</strong> a small, cheap one for summarizing</li></ul><p>Use a <strong>structured summary</strong> with fixed sections (say, Session Intent, Summary, Artifacts, Next Steps) and tell the summarizer to preserve every fact, path, error, and open task. Also handle “context length exceeded” as something recoverable: compact, then retry.</p><h3>Subagents: a separate desk for each job</h3><p>A subagent runs in its own context. It might read eight files and make fifteen tool calls, while your main agent only sees a short summary. That keeps the parent’s window clean.</p><p>A useful rule of thumb: <strong>fork workers, isolate verifiers.</strong></p><ul><li>A <em>worker</em> continuing an investigation benefits from inheriting the parent’s context (a <strong>forked</strong> subagent).</li><li>A <em>verifier</em> that must judge independently should start fresh (an <strong>isolated</strong> subagent).</li></ul><p>Support three timing modes: <strong>sync</strong> (wait for the answer), <strong>async</strong> (carry on, result arrives later), and <strong>scheduled</strong> (run later). And log the subagent’s full trajectory somewhere outside the parent, so you can audit a wrong answer.</p><h3>Hooks: where the rules live</h3><p>Hooks are interception points in the agent loop (before_model, after_model, wrap_tool_call, and so on). Offloading, compaction, and budgets are all easy to build as hooks, so you can reorder and test them independently. <strong>Order matters:</strong> compact <em>before</em> you inject new content, or your fresh injection may get summarized away.</p><h3>Hard limits</h3><p>Soft tools (offload, compact, fold) keep quality high. <strong>Hard budgets</strong> (token caps, per-tool call limits, loop caps) keep costs under control and make sure runs actually end. You want both.</p><h3>The pipeline, in order</h3><ol><li>Tool runs</li><li>Offload big results</li><li>Trim old tool inputs</li><li>Compact, only if still needed</li><li>Delegate to a subagent if the task is separable</li><li>Fold if the sub-task must stay in the parent</li><li>Check the token budget</li></ol><p>Golden rule: <strong>offload before you compact.</strong> Offloaded data can be recovered. Compacted data can’t.</p><h3>7. Governance and Economics: Who Decides, and Who Pays?</h3><p>Two final questions decide whether any of this survives contact with production:</p><ol><li><strong>Governance:</strong> <em>Should</em> this context be used, by this agent, right now?</li><li><strong>Economics:</strong> What does it <em>cost</em> to carry it?</li></ol><p>(This section also covers the Interaction layer from our map: who controls what enters the window.)</p><h3>Who’s in charge of what enters the context?</h3><p>Remember MCP’s three primitives? The control model matters. Tools belong to the model, resources to the app, prompts to the user. If you make <em>everything</em> a tool, you flatten that separation, and a harmless read-only lookup suddenly has an action surface with no approval step.</p><p>Also: <strong>enforce permissions outside the model.</strong> A rule written in a prompt is advice, not a guarantee. Use scoped tokens, tool-level Read/Write/Admin permissions, and role-based bundles of tools, all checked before a tool runs.</p><h3>Provenance: where did this come from?</h3><p>A highly relevant document can still be expired, unapproved, or superseded. Check admission <em>before</em> relevance ranking.</p><p>A July 2026 preprint called <strong>ContextNest</strong> tested this. In a 30-query “stale-version” experiment, governed selection passed 97% of queries, versus 90 to 93% for plain BM25, using roughly <strong>one third of the input tokens</strong>. A good sign, though it’s a small test by the tool’s own authors, so treat it as directional.</p><p>Google’s <strong>OKF v0.2</strong> (July 2026) builds this thinking into the knowledge format itself. Each concept can answer five questions straight from its header:</p><ul><li><strong>Provenance:</strong> what was this made from?</li><li><strong>Trust:</strong> how much should I trust it?</li><li><strong>Freshness:</strong> is it still true?</li><li><strong>Lifecycle:</strong> is it the current version?</li><li><strong>Attestation:</strong> was this number produced the approved way?</li></ul><p>Notably, Google chose to record <em>signals</em> rather than a single credibility score, leaving each consumer to apply its own rules. And the signals live in the header because most reads never get past it.</p><h3>Format changes the bill, not always the accuracy</h3><p>A study by Damon McMillan ran 9,649 experiments across 11 models and four formats (YAML, Markdown, JSON, TOON) on SQL-schema tasks. The headline: <strong>model quality mattered far more than format</strong> for accuracy.</p><p>Cost told a more interesting story. TOON, designed to be extra compact, used 138% <em>more</em> tokens than YAML at 500 tables and 740% more at 10,000 tables in the Claude-based scale tests. The authors call it a “grep tax”: the model was unfamiliar with the syntax and burned extra steps working around it. But TOON’s own benchmarks show about 40% fewer tokens on uniform tabular data. The lesson isn’t “never use compact formats.” It’s <strong>measure token cost with your own model and access pattern.</strong> Keep JSON where schema validation matters.</p><h3>Prefix caching: the engine under the hood</h3><p>Without caching, a 5,000-token prefix over 50 turns means 250,000 tokens of repeated work. With caching, the repeated part costs close to nothing. That’s why Section 2 told you to order content from most stable to least stable.</p><p>Agents make this harder, though, because they keep editing their own history. And the way the cache gets cleared matters too. Standard LRU eviction (drop the least recently used) tends to wipe out a few agents’ entire histories at once; when those agents return, they recompute everything. <strong>RR-Evict</strong> takes a small slice from each idle agent instead, round-robin. In tests on SGLang with Qwen3 models, it cut P99 time-to-first-token by up to <strong>75.4%</strong> and P99 uncached prompt tokens by up to <strong>65.7%</strong>, compared with LRU. It’s a preprint with specific test conditions, but the direction is clear: eviction policy is a real cost lever.</p><h3>Track cost like you mean it</h3><p>An invoice tells you the total, not <em>which workflow</em> caused it. Measure cost per <strong>reasoning step</strong>, per <strong>tenant</strong>, per <strong>agent or workflow</strong>, and per <strong>outcome</strong>. Cost per completed task beats cost per token. And instrument it from day one, because you can’t rebuild it later from a monthly bill.</p><h3>Two gates before anything enters the window</h3><pre>Proposed context<br>  → Gate 1 (governance): trusted source? current authorization? current version?<br>  → Gate 2 (economics): cacheable? within budget? attributable?<br>  → Enters the window</pre><h3>8. Putting It All Together</h3><p>A real agent isn’t seven separate tricks. It’s one pipeline:</p><pre>SESSION START<br>  Load stable prefix: system prompt, intent, tool index, skill index<br>  Load memory: user facts, relevant past sessions</pre><pre>EACH TURN<br>  User message or event arrives<br>  → Gate 1: governance check<br>  → Retrieve (query, search, rerank, pack)<br>  → Use tools (discover if needed, call, observe)<br>  → Gate 2: economic check<br>  → Manage the window (offload → truncate → compact → fold)<br>  → Model runs<br>  → Validate output, check budget</pre><pre>SESSION END<br>  Save episode, update facts, refine skills, attribute costs</pre><h3>Six rules that hold across every layer</h3><ol><li><strong>Order by how often things change</strong>, not by topic. Stable first, volatile last.</li><li><strong>Don’t destroy what you could keep.</strong> Offload before compacting.</li><li><strong>Nothing enters without provenance.</strong> Check at read time.</li><li><strong>Judge summaries by behavior</strong>, not by how nicely they read.</li><li><strong>Tool results are observations.</strong> They expire fast.</li><li><strong>Every cost needs an owner.</strong> If you can’t attribute it, you can’t tune it.</li></ol><h3>Mistakes that show up again and again</h3><ul><li>Compacting before offloading</li><li>Injecting content before compaction runs</li><li>One vector store for all memory</li><li>Access rules that live only in the prompt</li><li>Loading every tool schema up front</li><li>Ranking by relevance with no governance check</li><li>Reconstructing costs from invoices</li><li>Supporting only synchronous subagents</li></ul><h3>What to build first</h3><ol><li><strong>Instruction layer and control model.</strong> Get a stable, cacheable prefix.</li><li><strong>Caching and eviction.</strong> Before anything depends on prefix reuse.</li><li><strong>Retrieval and tools.</strong> Evaluate retrieval separately.</li><li><strong>Memory.</strong> Four tiers, each with its own write path.</li><li><strong>Execution management.</strong> Offload before compact, with budgets.</li><li><strong>Governance gates.</strong> Ship last, but <strong>design provenance into your data from day one.</strong> Backfilling it later is a migration, not a feature.</li></ol><p>And pick a posture early. What’s your agent’s main weakness? <strong>Doesn’t know things</strong> → retrieval-first. <strong>Can’t act</strong> → tool-first. <strong>Doesn’t remember</strong> → memory-first.</p><h3>🧾 Self-audit: score your own agent</h3><p>Grab a coffee and answer yes or no:</p><ul><li>Is my system prompt ordered from most to least stable?</li><li>Do I know how many tokens my fixed prefix costs per session?</li><li>Do I measure retrieval quality separately from final answers?</li><li>Are exact-match queries (codes, IDs) handled, not just semantic ones?</li><li>Do I have a plan for when tool catalogs grow?</li><li>Do my memory tiers have different update rules?</li><li>Do I offload big tool results <em>before</em> compacting?</li><li>Is there a hard token or loop budget?</li><li>Are permissions enforced in code, not just in the prompt?</li><li>Can I attribute cost per workflow and per outcome?</li></ul><p><strong>0 to 3 yes:</strong> start with the instruction layer and caching. <strong>4 to 7:</strong> you’re in the middle of the pack; tighten memory and execution. <strong>8 to 10:</strong> you’re doing real context engineering. Go write about it.</p><h3>The Big Idea</h3><p>Context is a <strong>designed environment</strong>, not a retrieved bag of chunks.</p><blockquote><em>The agent that controls its context controls its behavior. The system that controls the context architecture decides whether the agent is a demo or a deployment.</em></blockquote><p><strong>Your turn:</strong> which of the seven layers is the weakest link in the agents you’ve built? Tell me in the comments. I’m curious whether it’s memory or governance. (My bet is memory.)</p><h3>A Note on the Numbers</h3><p>Many results here come from 2025 and 2026 preprints and specific benchmarks. Treat them as directional evidence, not guarantees, and test on your own workload.</p><h3>Sources and Further Reading</h3><ul><li>Anthropic Engineering, <em>Code execution with MCP: Building more efficient agents</em> (Nov 2025): <a href="https://www.anthropic.com/engineering/code-execution-with-mcp">https://www.anthropic.com/engineering/code-execution-with-mcp</a></li><li>Sun et al., <em>Scaling Long-Horizon Agent via Context Folding</em> (ICML 2026): <a href="https://proceedings.mlr.press/v306/sun26x.html">https://proceedings.mlr.press/v306/sun26x.html</a></li><li>Ye et al., <em>AgentFold: Long-Horizon Web Agents with Proactive Context Management</em>: <a href="https://arxiv.org/abs/2510.24699">https://arxiv.org/abs/2510.24699</a></li><li>Zhang et al., <em>Agentic Context Engineering (ACE)</em>: <a href="https://arxiv.org/abs/2510.04618">https://arxiv.org/abs/2510.04618</a></li><li>Chen et al., <em>Slipstream: Trajectory-Grounded Compaction Validation for Long-Horizon Agents</em>: <a href="https://arxiv.org/abs/2605.08580">https://arxiv.org/abs/2605.08580</a></li><li>Dong et al., <em>A Practical Memory Injection Attack against LLM Agents (MINJA)</em>: <a href="https://arxiv.org/abs/2503.03704">https://arxiv.org/abs/2503.03704</a></li><li>Sulpovar et al., <em>ContextNest: Verifiable Context Governance for Autonomous AI Agent</em>: <a href="https://arxiv.org/pdf/2607.02116">https://arxiv.org/pdf/2607.02116</a></li><li>Google Cloud, <em>Open Knowledge Format v0.2 tackles agentic trust</em>: <a href="https://cloud.google.com/blog/products/data-analytics/okf-v0-2-adds-trust-signals">https://cloud.google.com/blog/products/data-analytics/okf-v0-2-adds-trust-signals</a></li><li>McMillan, <em>Structured Context Engineering for File-Native Agentic Systems</em> (summary by Simon Willison): <a href="https://simonwillison.net/2026/Feb/9/structured-context-engineering-for-file-native-agentic-systems/">https://simonwillison.net/2026/Feb/9/structured-context-engineering-for-file-native-agentic-systems/</a></li><li><em>RR-Evict: Fine-Grained Prefix Cache Eviction beyond LRU for Agentic LLM Serving</em>: <a href="https://arxiv.org/pdf/2609.32278">https://arxiv.org/pdf/2609.32278</a></li><li>Liu et al., <em>Lost in the Middle: How Language Models Use Long Contexts</em> (2023)</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=92cac1ed8fca" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[SQLAlchemy and SQLModel]]></title>
            <link>https://medium.com/@vengiboopathi/sqlalchemy-and-sqlmodel-84cdac3e01fd?source=rss-d9be6945e434------2</link>
            <guid isPermaLink="false">https://medium.com/p/84cdac3e01fd</guid>
            <dc:creator><![CDATA[Vengadesa Boopathi]]></dc:creator>
            <pubDate>Fri, 17 Apr 2026 06:13:52 GMT</pubDate>
            <atom:updated>2026-04-17T06:13:52.430Z</atom:updated>
            <content:encoded><![CDATA[<p>If you have been writing Python for a while and working with databases, you have probably heard of SQLAlchemy. And if you have been building APIs with FastAPI, you have likely run into SQLModel too. These two libraries are closely related, often confused, and absolutely worth understanding deeply.</p><p>This guide covers everything — from what these libraries actually are, to how they work under the hood, to building production-ready applications with them. No fluff, no skipping the important parts.</p><h3>Part 1: Understanding the Problem These Libraries Solve</h3><p>Before jumping into code, let us understand why these libraries even exist.</p><p>Back in the early days of Python web development, if you wanted to talk to a database, you had to use raw database drivers. Each database had its own driver with its own API. MySQL had MySQLdb, PostgreSQL had psycopg2, SQLite had the built-in sqlite3 module.</p><p>Here is what <strong>raw database execution </strong>looked like:</p><pre>#sql<br>import sqlite3<br>conn = sqlite3.connect(&quot;mydb.db&quot;)<br>cursor = conn.cursor()<br>cursor.execute(&quot;INSERT INTO users (name, email) VALUES (?, ?)&quot;, (&quot;Venki&quot;, &quot;venki@example.com&quot;))<br>conn.commit()<br>cursor.execute(&quot;SELECT * FROM users WHERE id = ?&quot;, (1,))<br>row = cursor.fetchone()<br>conn.close()<br><br>#postgresql<br>import psycopg2<br>conn = psycopg2.connect(host=&quot;localhost&quot;,database=&quot;mydb&quot;,user=&quot;postgres&quot;,password=&quot;password&quot;)<br>cursor = conn.cursor()<br>cursor.execute(&quot;INSERT INTO users (name, email) VALUES (%s, %s)&quot;,(&quot;Venki&quot;, &quot;venki@example.com&quot;))<br>conn.commit()<br>cursor.execute(&quot;SELECT * FROM users WHERE id = %s&quot;,(1,))<br>row = cursor.fetchone()<br>conn.close()</pre><p>This works fine for a small script. But as your application grows, problems start appearing fast:</p><ul><li>You are manually managing connections and cursors everywhere</li><li>If you switch from SQLite to PostgreSQL, you rewrite all your queries</li><li>No protection against SQL injection unless you are careful every single time</li><li>No way to represent database tables as Python objects</li><li>No connection pooling, so performance degrades under load</li></ul><p>SQLAlchemy was created in 2006 by Michael Bayer specifically to solve all of these problems at once. It became the gold standard for database access in Python and has stayed that way for nearly two decades.</p><h3>Part 2: What is SQLAlchemy</h3><p>SQLAlchemy is a Python SQL toolkit and Object Relational Mapper. That definition sounds dry, so let us break it down into what it actually gives you.</p><p><strong>A common interface for multiple databases.</strong> Write your code once and it works with PostgreSQL, MySQL, SQLite, Oracle, and MSSQL. You change one line — the connection string — and everything else stays the same.</p><p><strong>Two layers to choose from.</strong> SQLAlchemy gives you a Core layer for writing SQL in a Pythonic way while staying close to raw SQL, and an ORM layer for working with Python classes and objects instead of SQL. You can use either or mix both in the same project.</p><p><strong>Connection pooling out of the box.</strong> SQLAlchemy manages a pool of database connections so your app does not open and close a new connection for every single request. This is critical for any application with real traffic.</p><p><strong>Protection against SQL injection by default.</strong> SQLAlchemy uses parameterized queries under the hood so you are safe without having to think about it.</p><h3>Part 3: Installing SQLAlchemy</h3><pre>pip install sqlalchemy</pre><p>For specific databases you also need the driver:</p><pre># PostgreSQL<br>pip install psycopg2-binary<br># MySQL<br>pip install pymysql<br># Async PostgreSQL<br>pip install asyncpg</pre><p>SQLite needs no extra driver because it is built into Python.</p><h3>Part 4: The Connection String</h3><p>The connection string is how you tell SQLAlchemy which database to connect to. The format is:</p><pre>dialect+driver://username:password@host:port/database</pre><p>Real examples:</p><pre># SQLite (file based)<br>&quot;sqlite:///myapp.db&quot;<br># SQLite (in memory, great for testing)<br>&quot;sqlite:///:memory:&quot;<br># PostgreSQL<br>&quot;postgresql://venki:password@localhost:5432/mydb&quot;<br># PostgreSQL with asyncpg (async)<br>&quot;postgresql+asyncpg://venki:password@localhost:5432/mydb&quot;<br># MySQL<br>&quot;mysql+pymysql://venki:password@localhost:3306/mydb&quot;</pre><h3>Part 5: The Engine — Your Entry Point to Everything</h3><p>The engine is the starting point of any SQLAlchemy application. It holds the connection pool and knows how to talk to your specific database.</p><pre>from sqlalchemy import create_engine<br><br>engine = create_engine(&quot;sqlite:///myapp.db&quot;)</pre><p>The engine does not actually connect to the database when you create it. It connects lazily when you first need it.</p><p>You can configure the connection pool:</p><pre>engine = create_engine(<br>    &quot;postgresql://venki:password@localhost/mydb&quot;,<br>    pool_size=10,        # number of connections to keep open<br>    max_overflow=20,     # extra connections allowed beyond pool_size<br>    pool_timeout=30,     # seconds to wait before giving up<br>    pool_recycle=1800,   # recycle connections after 30 minutes<br>    echo=True            # log all SQL statements (great for debugging)<br>)</pre><h3>Part 6: SQLAlchemy Core — Writing SQL the Pythonic Way</h3><p>The Core layer lets you write SQL using Python constructs while staying close to actual SQL. This is useful when you need full control over your queries.</p><h3>Running Raw SQL with text()</h3><p>In SQLAlchemy 2.x, all raw SQL strings must be wrapped in text():</p><pre>from sqlalchemy import create_engine, text<br>engine = create_engine(&quot;sqlite:///myapp.db&quot;)<br><br>with engine.connect() as conn:<br>    result = conn.execute(text(&quot;SELECT * FROM users&quot;))<br>    for row in result:<br>        print(row)</pre><p>Always use named parameters with :param syntax, never f-strings:</p><pre># WRONG — SQL injection risk<br>name = &quot;Venki&quot;<br>conn.execute(text(f&quot;SELECT * FROM users WHERE name = &#39;{name}&#39;&quot;))<br><br># RIGHT - safe parameterized query<br>conn.execute(text(&quot;SELECT * FROM users WHERE name = :name&quot;), {&quot;name&quot;: name})</pre><h3>Creating Tables with Core</h3><pre>from sqlalchemy import create_engine, Table, Column, Integer, String, MetaData<br><br>engine = create_engine(&quot;sqlite:///myapp.db&quot;)<br>metadata = MetaData()<br>users = Table(<br>    &quot;users&quot;,<br>    metadata,<br>    Column(&quot;id&quot;, Integer, primary_key=True),<br>    Column(&quot;name&quot;, String(100), nullable=False),<br>    Column(&quot;email&quot;, String(200), unique=True),<br>)<br>metadata.create_all(engine)</pre><h3>Insert, Select, Update, Delete with Core</h3><pre>from sqlalchemy import insert, select, update, delete<br><br># Insert<br>with engine.connect() as conn:<br>    conn.execute(insert(users).values(name=&quot;Venki&quot;, email=&quot;venki@example.com&quot;))<br>    conn.commit()<br># Select<br>with engine.connect() as conn:<br>    result = conn.execute(select(users).where(users.c.name == &quot;Venki&quot;))<br>    for row in result:<br>        print(row)<br># Update<br>with engine.connect() as conn:<br>    conn.execute(update(users).where(users.c.id == 1).values(name=&quot;Venkatesh&quot;))<br>    conn.commit()<br># Delete<br>with engine.connect() as conn:<br>    conn.execute(delete(users).where(users.c.id == 1))<br>    conn.commit()</pre><h3>Part 7: The ORM Layer — Working With Python Classes</h3><p>The ORM (Object Relational Mapper) layer is where SQLAlchemy really shines. Instead of writing SQL, you define Python classes that map to database tables and SQLAlchemy handles the SQL for you.</p><h4>Defining Models</h4><p>In SQLAlchemy 2.x, the recommended way uses DeclarativeBase:</p><pre>from sqlalchemy import String, Integer<br>from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column<br><br>class Base(DeclarativeBase):<br>    pass<br>class User(Base):<br>    __tablename__ = &quot;users&quot;<br>    id: Mapped[int] = mapped_column(Integer, primary_key=True)<br>    name: Mapped[str] = mapped_column(String(100), nullable=False)<br>    email: Mapped[str] = mapped_column(String(200), unique=True)<br>    def __repr__(self):<br>        return f&quot;User(id={self.id}, name={self.name})&quot;</pre><p>The Mapped annotation is new in SQLAlchemy 2.x and gives you proper type checking. The old 1.x style still works but the new style is recommended for new projects.</p><h4>Creating Tables From Models</h4><pre>from sqlalchemy import create_engine<br><br>engine = create_engine(&quot;sqlite:///myapp.db&quot;, echo=True)<br>Base.metadata.create_all(engine)</pre><h4>Sessions — The Core of ORM Operations</h4><p>A session is the main way you interact with the database through the ORM. Think of it as a staging area. You add objects to it, and when you commit, they get written to the database.</p><pre>from sqlalchemy.orm import Session<br># Create<br>with Session(engine) as session:<br>    user = User(name=&quot;Venki&quot;, email=&quot;venki@example.com&quot;)<br>    session.add(user)<br>    session.commit()<br>    session.refresh(user)  # reload to get auto-generated id<br>    print(user.id)<br># Read<br>with Session(engine) as session:<br>    user = session.get(User, 1)  # get by primary key<br>    print(user.name)<br># Read with filter<br>from sqlalchemy import select<br>with Session(engine) as session:<br>    stmt = select(User).where(User.name == &quot;Venki&quot;)<br>    users = session.execute(stmt).scalars().all()<br># Update<br>with Session(engine) as session:<br>    user = session.get(User, 1)<br>    user.name = &quot;Venkatesh&quot;<br>    session.commit()<br># Delete<br>with Session(engine) as session:<br>    user = session.get(User, 1)<br>    session.delete(user)<br>    session.commit()</pre><h3>Part 8: Relationships Between Tables</h3><p>Real applications always have tables that relate to each other. SQLAlchemy handles this beautifully.</p><h3>One to Many</h3><p>One user has many posts. Each post belongs to one user.</p><pre>from sqlalchemy import ForeignKey<br>from sqlalchemy.orm import relationship<br><br>class User(Base):<br>    __tablename__ = &quot;users&quot;<br>    id: Mapped[int] = mapped_column(primary_key=True)<br>    name: Mapped[str] = mapped_column(String(100))<br>    posts: Mapped[list[&quot;Post&quot;]] = relationship(&quot;Post&quot;, back_populates=&quot;user&quot;)<br>class Post(Base):<br>    __tablename__ = &quot;posts&quot;<br>    id: Mapped[int] = mapped_column(primary_key=True)<br>    title: Mapped[str] = mapped_column(String(200))<br>    user_id: Mapped[int] = mapped_column(ForeignKey(&quot;users.id&quot;))<br>    user: Mapped[&quot;User&quot;] = relationship(&quot;User&quot;, back_populates=&quot;posts&quot;)</pre><p>Using the relationship:</p><pre>with Session(engine) as session:<br>    user = User(name=&quot;Venki&quot;)<br>    post1 = Post(title=&quot;SQLAlchemy Guide&quot;, user=user)<br>    post2 = Post(title=&quot;FastAPI Tutorial&quot;, user=user)</pre><pre>    session.add(user)<br>    session.commit()</pre><pre>    # Access posts through the relationship<br>    user = session.get(User, 1)<br>    for post in user.posts:<br>        print(post.title)</pre><h3>Many to Many</h3><p>Students can enroll in many courses. Courses can have many students.</p><pre>from sqlalchemy import Table<br>enrollment = Table(<br>    &quot;enrollment&quot;,<br>    Base.metadata,<br>    Column(&quot;student_id&quot;, ForeignKey(&quot;students.id&quot;), primary_key=True),<br>    Column(&quot;course_id&quot;, ForeignKey(&quot;courses.id&quot;), primary_key=True),<br>)<br>class Student(Base):<br>    __tablename__ = &quot;students&quot;<br>    id: Mapped[int] = mapped_column(primary_key=True)<br>    name: Mapped[str] = mapped_column(String(100))<br>    courses: Mapped[list[&quot;Course&quot;]] = relationship(&quot;Course&quot;, secondary=enrollment, back_populates=&quot;students&quot;)<br>class Course(Base):<br>    __tablename__ = &quot;courses&quot;<br>    id: Mapped[int] = mapped_column(primary_key=True)<br>    title: Mapped[str] = mapped_column(String(200))<br>    students: Mapped[list[&quot;Student&quot;]] = relationship(&quot;Student&quot;, secondary=enrollment, back_populates=&quot;courses&quot;)</pre><h3>Part 9: Lazy vs Eager Loading</h3><p>This is one of the most important performance topics in SQLAlchemy.</p><p><strong>Lazy loading</strong> (the default) means related objects are fetched only when you actually access them. This causes the N+1 problem — one query for the main objects, then one more query per object to fetch related data.</p><pre># This triggers N+1 queries<br>users = session.execute(select(User)).scalars().all()<br>for user in users:<br>    print(user.posts)  # a new query fires for EACH user</pre><p><strong>Eager loading</strong> fetches everything in one query using a JOIN.</p><pre>from sqlalchemy.orm import joinedload<br># One query fetches users AND their posts<br>users = session.execute(<br>    select(User).options(joinedload(User.posts))<br>).scalars().unique().all()<br>for user in users:<br>    print(user.posts)  # no extra queries</pre><p>Always use eager loading when you know you will access related data.</p><h3>Part 10: Transactions</h3><p>SQLAlchemy gives you full control over transactions.</p><pre>with Session(engine) as session:<br>    try:<br>        user = User(name=&quot;Venki&quot;, email=&quot;venki@example.com&quot;)<br>        session.add(user)<br><br>post = Post(title=&quot;First Post&quot;, user=user)<br>        session.add(post)<br>        session.commit()  # both saved together<br>    except Exception as e:<br>        session.rollback()  # neither saved if anything fails<br>        raise e</pre><p>The with statement automatically rolls back if an exception escapes.</p><h3>Part 11: Async SQLAlchemy</h3><p>Modern web frameworks like FastAPI are async. SQLAlchemy 2.0 added full async support.</p><pre>from sqlalchemy.ext.asyncio import create_async_engine, AsyncSession, async_sessionmaker<br>engine = create_async_engine(<br>    &quot;postgresql+asyncpg://venki:password@localhost/mydb&quot;,<br>    echo=True<br>)<br>AsyncSessionLocal = async_sessionmaker(engine, expire_on_commit=False)<br>async def get_user(user_id: int):<br>    async with AsyncSessionLocal() as session:<br>        user = await session.get(User, user_id)<br>        return user<br>async def create_user(name: str, email: str):<br>    async with AsyncSessionLocal() as session:<br>        user = User(name=name, email=email)<br>        session.add(user)<br>        await session.commit()<br>        await session.refresh(user)<br>        return user</pre><h3>Part 12: Database Migrations with Alembic</h3><p>SQLAlchemy creates tables but it does not handle schema changes. If you add a column to your model, SQLAlchemy will not automatically add it to your existing database. That is Alembic’s job.</p><p>Alembic is the official migration tool for SQLAlchemy.</p><pre>pip install alembic<br>alembic init migrations</pre><p>Configure alembic.ini with your database URL, then edit migrations/env.py to import your models.</p><p>Create a migration after changing your models:</p><pre>alembic revision --autogenerate -m &quot;add phone column to users&quot;</pre><p>Apply the migration:</p><pre>alembic upgrade head</pre><p>Roll back the last migration:</p><pre>alembic downgrade -1</pre><p>In production, always run alembic upgrade head as part of your deployment process.</p><h3>Part 13: Using Pandas With SQLAlchemy</h3><p>SQLAlchemy integrates nicely with Pandas for data analysis work.</p><pre>import pandas as pd<br>from sqlalchemy import create_engine, text</pre><pre>engine = create_engine(&quot;sqlite:///myapp.db&quot;)</pre><pre># Read query result into DataFrame<br>df = pd.read_sql(text(&quot;SELECT * FROM users&quot;), engine)</pre><pre># Write DataFrame to database<br>df.to_sql(&quot;new_table&quot;, engine, if_exists=&quot;replace&quot;, index=False)</pre><h3>Part 14: SQLAlchemy 1.x vs 2.x — What Changed</h3><p>If you are reading old tutorials, you will see code like this:</p><pre># Old 1.x style<br>session.query(User).filter(User.name == &quot;Venki&quot;).all()<br>session.query(User).filter_by(name=&quot;Venki&quot;).first()</pre><p>In 2.x the recommended style is:</p><pre># New 2.x style<br>session.execute(select(User).where(User.name == &quot;Venki&quot;)).scalars().all()<br>session.execute(select(User).where(User.name == &quot;Venki&quot;)).scalar_one_or_none()</pre><p>The old style still works in 2.x but will eventually be removed. Start new projects with the 2.x style.</p><h3>Part 15: What is SQLModel</h3><p>SQLModel is a library built on top of SQLAlchemy and Pydantic by Tiangolo, the creator of FastAPI. It was released in 2021 to solve a specific pain point that every FastAPI developer feels.</p><p>In FastAPI, you need two separate class definitions for the same data:</p><ol><li>A SQLAlchemy model for the database layer</li><li>A Pydantic model for request and response validation</li></ol><p>This means you write essentially the same fields twice and keep them in sync manually. With a simple User table you might have UserDB, UserCreate, UserRead, UserUpdate — four different classes all representing the same thing.</p><p>SQLModel merges Pydantic and SQLAlchemy into a single class definition.</p><h3>Part 16: Installing SQLModel</h3><pre>pip install sqlmodel</pre><p>SQLModel automatically installs compatible versions of SQLAlchemy and Pydantic.</p><h3>Part 17: Defining Models With SQLModel</h3><pre>from sqlmodel import SQLModel, Field<br>class User(SQLModel, table=True):<br>    id: int | None = Field(default=None, primary_key=True)<br>    name: str<br>    email: str</pre><p>The table=True argument tells SQLModel this class maps to a real database table. Without it, the class is just a Pydantic model for validation.</p><p>This one class does the work of both a SQLAlchemy model and a Pydantic model. You can use it for database operations and also use it to validate API request bodies.</p><h3>Part 18: Creating Tables and Session With SQLModel</h3><pre>from sqlmodel import create_engine, Session, SQLModel</pre><pre>engine = create_engine(&quot;sqlite:///myapp.db&quot;, echo=True)</pre><pre>SQLModel.metadata.create_all(engine)</pre><p>Session works the same as SQLAlchemy session:</p><pre>with Session(engine) as session:<br>    user = User(name=&quot;Venki&quot;, email=&quot;venki@example.com&quot;)<br>    session.add(user)<br>    session.commit()<br>    session.refresh(user)<br>    print(user.id)</pre><h3>Part 19: Multiple Models for the Same Table</h3><p>This is where SQLModel really shines. You can define multiple Pydantic-only models (without table=True) that share fields with your table model.</p><pre>from sqlmodel import SQLModel, Field</pre><pre># Base model with shared fields (not a table)<br>class UserBase(SQLModel):<br>    name: str<br>    email: str</pre><pre># Table model (actual database table)<br>class User(UserBase, table=True):<br>    id: int | None = Field(default=None, primary_key=True)<br>    hashed_password: str  # stored in DB but never returned to user</pre><pre># What the API accepts when creating a user<br>class UserCreate(UserBase):<br>    password: str  # plain password, only used during creation</pre><pre># What the API returns (no password at all)<br>class UserRead(UserBase):<br>    id: int</pre><pre># What the API accepts when updating a user<br>class UserUpdate(SQLModel):<br>    name: str | None = None<br>    email: str | None = None</pre><p>This pattern gives you clean separation between what goes in the database and what you expose through your API.</p><h3>Part 20: SQLModel With FastAPI — A Complete Example</h3><p>Here is a complete working FastAPI application with SQLModel:</p><pre>from fastapi import FastAPI, HTTPException, Depends<br>from sqlmodel import SQLModel, Field, Session, create_engine, select<br>from typing import Generator<br><br># Models<br>class UserBase(SQLModel):<br>    name: str<br>    email: str<br>class User(UserBase, table=True):<br>    id: int | None = Field(default=None, primary_key=True)<br>class UserCreate(UserBase):<br>    pass<br>class UserRead(UserBase):<br>    id: int<br># Database setup<br>DATABASE_URL = &quot;sqlite:///./myapp.db&quot;<br>engine = create_engine(DATABASE_URL, echo=True)<br>def create_db():<br>    SQLModel.metadata.create_all(engine)<br>def get_session() -&gt; Generator:<br>    with Session(engine) as session:<br>        yield session<br># App<br>app = FastAPI()<br>@app.on_event(&quot;startup&quot;)<br>def on_startup():<br>    create_db()<br>@app.post(&quot;/users/&quot;, response_model=UserRead)<br>def create_user(user: UserCreate, session: Session = Depends(get_session)):<br>    db_user = User.model_validate(user)<br>    session.add(db_user)<br>    session.commit()<br>    session.refresh(db_user)<br>    return db_user<br>@app.get(&quot;/users/{user_id}&quot;, response_model=UserRead)<br>def get_user(user_id: int, session: Session = Depends(get_session)):<br>    user = session.get(User, user_id)<br>    if not user:<br>        raise HTTPException(status_code=404, detail=&quot;User not found&quot;)<br>    return user<br>@app.get(&quot;/users/&quot;, response_model=list[UserRead])<br>def list_users(session: Session = Depends(get_session)):<br>    users = session.execute(select(User)).scalars().all()<br>    return users<br>@app.patch(&quot;/users/{user_id}&quot;, response_model=UserRead)<br>def update_user(user_id: int, user_data: dict, session: Session = Depends(get_session)):<br>    user = session.get(User, user_id)<br>    if not user:<br>        raise HTTPException(status_code=404, detail=&quot;User not found&quot;)<br>    for key, value in user_data.items():<br>        setattr(user, key, value)<br>    session.commit()<br>    session.refresh(user)<br>    return user<br>@app.delete(&quot;/users/{user_id}&quot;)<br>def delete_user(user_id: int, session: Session = Depends(get_session)):<br>    user = session.get(User, user_id)<br>    if not user:<br>        raise HTTPException(status_code=404, detail=&quot;User not found&quot;)<br>    session.delete(user)<br>    session.commit()<br>    return {&quot;message&quot;: &quot;User deleted&quot;}</pre><h3>Part 21: Relationships in SQLModel</h3><pre>from sqlmodel import SQLModel, Field, Relationship<br>from typing import Optional<br><br>class User(SQLModel, table=True):<br>    id: int | None = Field(default=None, primary_key=True)<br>    name: str<br>    posts: list[&quot;Post&quot;] = Relationship(back_populates=&quot;user&quot;)<br>class Post(SQLModel, table=True):<br>    id: int | None = Field(default=None, primary_key=True)<br>    title: str<br>    user_id: int | None = Field(default=None, foreign_key=&quot;user.id&quot;)<br>    user: User | None = Relationship(back_populates=&quot;posts&quot;)</pre><p>Note that SQLModel uses Relationship instead of SQLAlchemy&#39;s relationship.</p><h3>Part 22: Async With SQLModel</h3><p>SQLModel supports async the same way SQLAlchemy does:</p><pre>from sqlmodel.ext.asyncio.session import AsyncSession<br>from sqlalchemy.ext.asyncio import create_async_engine, async_sessionmaker<br><br>engine = create_async_engine(&quot;postgresql+asyncpg://venki:password@localhost/mydb&quot;)<br>AsyncSessionLocal = async_sessionmaker(engine, class_=AsyncSession)<br>async def get_user(user_id: int):<br>    async with AsyncSessionLocal() as session:<br>        user = await session.get(User, user_id)<br>        return user</pre><h3>Part 23: SQLAlchemy vs SQLModel — When to Use Which</h3><p><strong>Use SQLAlchemy when:</strong></p><ul><li>You are not using FastAPI</li><li>You need maximum control and flexibility over your database layer</li><li>You have complex queries with multiple joins and aggregations</li><li>You need battle tested stability that has been proven in production for 15+ years</li><li>You are working on an existing codebase that already uses SQLAlchemy</li></ul><p><strong>Use SQLModel when:</strong></p><ul><li>You are building a FastAPI application</li><li>You want to write less code and maintain fewer class definitions</li><li>Your team is comfortable with Pydantic and wants unified models</li><li>You are starting a new project and want the cleanest possible code structure</li></ul><p><strong>The important thing to understand:</strong> SQLModel is SQLAlchemy under the hood. Everything you know about SQLAlchemy — sessions, queries, relationships, migrations with Alembic — applies to SQLModel too. You are not choosing between them, you are choosing how much abstraction you want on top of SQLAlchemy.</p><h3>Part 24: Production Checklist</h3><p>Before shipping a SQLAlchemy or SQLModel application to production, make sure you have covered these:</p><p><strong>Connection pooling configured</strong> — set pool_size, max_overflow, and pool_recycle appropriate for your expected traffic.</p><p><strong>Environment variables for credentials</strong> — never hardcode database URLs. Use environment variables or a secrets manager.</p><pre>import os<br>DATABASE_URL = os.getenv(&quot;DATABASE_URL&quot;, &quot;sqlite:///./dev.db&quot;)</pre><p><strong>Alembic migrations set up</strong> — never use create_all() in production to manage schema. Use Alembic so you have a history of changes and can roll back safely.</p><p><strong>Connection error handling</strong> — wrap database operations in try/except and handle connection failures gracefully.</p><p><strong>Async for FastAPI</strong> — if you are using FastAPI, use the async versions of the engine and session to get the full performance benefit.</p><p><strong>Index your columns</strong> — add database indexes to columns you filter or sort by frequently.</p><pre>class User(Base):<br>    __tablename__ = &quot;users&quot;<br>    id: Mapped[int] = mapped_column(primary_key=True)<br>    email: Mapped[str] = mapped_column(String(200), index=True)  # indexed</pre><p><strong>Close sessions properly</strong> — always use context managers or dependency injection to ensure sessions are closed after each request.</p><h3>Wrapping Up</h3><p>SQLAlchemy is one of those libraries that pays dividends the more you invest in learning it. It has been the backbone of Python database access for nearly two decades for good reason. It is mature, flexible, and does not get in your way when you need to drop down to raw SQL.</p><p>SQLModel is the natural evolution for FastAPI developers who got tired of the boilerplate. It gives you the power of SQLAlchemy with significantly less ceremony.</p><p>The best way to learn either of them is to build something real. Start with SQLite since it needs zero setup, get your models working, then swap the connection string to PostgreSQL when you are ready for production. That single line change is one of the best demonstrations of why using an ORM layer is worth it.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=84cdac3e01fd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Python Concurrency Explained: async/await, asyncio, Threads, and Processes — A Complete Guide]]></title>
            <link>https://medium.com/@vengiboopathi/python-concurrency-explained-async-await-asyncio-threads-and-processes-a-complete-guide-4f84f83d8be9?source=rss-d9be6945e434------2</link>
            <guid isPermaLink="false">https://medium.com/p/4f84f83d8be9</guid>
            <dc:creator><![CDATA[Vengadesa Boopathi]]></dc:creator>
            <pubDate>Sun, 05 Apr 2026 06:49:58 GMT</pubDate>
            <atom:updated>2026-04-05T06:49:58.960Z</atom:updated>
            <content:encoded><![CDATA[<p>I’ve been working with Python backends for a while now, and if there’s one topic that consistently trips people up — it’s concurrency. The words get thrown around interchangeably: async, concurrent, parallel, threads, processes. They’re not the same thing, and the distinctions matter a lot when you’re building something real.</p><p>This article is my attempt to lay it all out clearly, from first principles to production patterns. By the end, you’ll know exactly what each tool does, when to use it, and why Python’s asyncio works the way it does.</p><h3>The Core Problem: Waiting Is Wasteful</h3><p>When your program makes a network request, reads from disk, or queries a database, the CPU just sits idle waiting for the result. The whole story of concurrency, async, and parallelism is about what to do with that idle time.</p><p>Before we get into any code, we need to clear up three axes of confusion that most people collapse into one.</p><h3>Three Axes You Must Separate</h3><h3>1. Concurrency vs Parallelism</h3><p>These are not the same thing.</p><p><strong>Concurrency</strong> means <em>dealing with</em> multiple things at once — structurally. Multiple tasks may be in progress, but they don’t necessarily run at the same physical instant.</p><p><strong>Parallelism</strong> means <em>running</em> multiple things at the same physical instant — on multiple CPU cores <strong>simultaneously.</strong></p><p>You can have concurrency without parallelism: one CPU core, multiple tasks interleaving. Python’s asyncio does exactly this. You can also have parallelism without meaningful concurrency in your code structure.</p><p>Rob Pike said it well: <em>“Concurrency is about structure. Parallelism is about execution.”</em></p><h3>2. Synchronous vs Asynchronous</h3><p><strong>Synchronous</strong>: you call a function, it blocks until it returns. Your code literally stops and waits.</p><p><strong>Asynchronous</strong>: you <em>start</em> an operation and instead of blocking, you get a handle back. You can do other work and collect the result later.</p><h3>3. I/O-bound vs CPU-bound</h3><p>This one determines which tool you should reach for.</p><ul><li><strong>I/O-bound work</strong>: waiting for network, disk, database. The CPU is idle most of the time. asyncio is the right tool.</li><li><strong>CPU-bound work</strong>: heavy computation — image processing, ML inference, numerical work. The CPU is fully occupied. You need threads or processes, not async.</li></ul><p>Get this wrong and you’ll use asyncio where it can&#39;t help you, or spin up expensive processes for work that a coroutine would handle fine.</p><h3>How We Got Here: A Brief History</h3><h3>Stage 1 — Blocking, Single-Threaded Code</h3><p>The original model. One task runs to completion, then the next starts. If task A is waiting for I/O, everything halts.</p><pre>result = requests.get(&quot;https://api.example.com/data&quot;)  # CPU idles here<br>data = result.json()</pre><p>Fine for simple scripts. Terrible for servers handling many clients.</p><h3>Stage 2 — Multi-threading (1990s–2000s)</h3><p>The OS-level solution: spawn a thread per task. The OS scheduler context-switches between them. Works for I/O-bound work, but Python has a complication — the <strong>GIL</strong>.</p><p>The Global Interpreter Lock (GIL) is a mutex in CPython that allows only one thread to execute Python bytecode at a time. So Python threads give you concurrency but not true parallelism for CPU-bound work. For I/O-bound work, the GIL is released during I/O syscalls, so threads do help there.</p><p>The other downsides: threads are expensive (each carries an ~8MB OS stack), context-switching has overhead, and shared mutable state introduces race conditions. Managing locks to prevent races introduces deadlock risk.</p><pre>import threading<br>import requests</pre><pre>def fetch(url):<br>    return requests.get(url).json()</pre><pre>threads = [threading.Thread(target=fetch, args=(url,)) for url in urls]<br>for t in threads: t.start()<br>for t in threads: t.join()</pre><h3>Stage 3 — Callbacks and Event Loops (2000s)</h3><p>Instead of threads, use a single thread with an event loop. Register callbacks for I/O operations. When I/O completes, the event loop calls your callback.</p><p>This works, but produces the infamous “callback hell”:</p><pre>// Node.js-style callback hell<br>fetchUser(id, function(user) {<br>    fetchPosts(user.id, function(posts) {<br>        fetchComments(posts[0].id, function(comments) {<br>            // ...buried three levels deep<br>        });<br>    });<br>});</pre><p>Python had Twisted (from ~2001) for this pattern, and later Tornado (2009). Powerful, but notoriously hard to read and maintain.</p><h3>Stage 4 — Generators as Coroutines (Python 3.4)</h3><p>Python 3.4 introduced asyncio using generators to simulate coroutines with @asyncio.coroutine and yield from. This solved callback hell structurally but was awkward in practice.</p><h3>Stage 5 — Native async/await (Python 3.5+)</h3><p>Python 3.5 gave us async def and await as first-class language syntax. The event loop is still single-threaded, but the code reads almost like synchronous code. This is what we use today.</p><h3>The Modern Python Async Model — Every Concept</h3><h3>Coroutine</h3><p>A coroutine is a function defined with async def. Calling it does <strong>not</strong> run it — it returns a coroutine object. It only runs when you await it or schedule it as a task.</p><pre>async def fetch_data(url):<br>    async with aiohttp.ClientSession() as session:<br>        response = await session.get(url)<br>        return await response.json()<br><br># This does NOT run the function:<br>coro = fetch_data(&quot;https://api.example.com&quot;)  # just a coroutine object<br># This runs it:<br>result = await fetch_data(&quot;https://api.example.com&quot;)</pre><p>A coroutine is a <strong>pausable function</strong>. When it hits an await, it suspends itself and returns control to the event loop. The event loop can run another coroutine. When the awaited operation completes, the event loop resumes this coroutine from exactly where it paused.</p><p>This is <strong>cooperative multitasking</strong> — unlike OS threads which are preemptive (the OS forcibly interrupts them), coroutines voluntarily yield control at await points.</p><h3>The Event Loop</h3><p>The event loop is the engine of asyncio. It runs a continuous cycle:</p><ol><li>Pick a ready coroutine or callback from its queue</li><li>Run it until it hits an await or completes</li><li>Register the awaited I/O operation with the OS (via select/epoll/kqueue)</li><li>Pick the next ready task</li><li>When I/O completes, mark the suspended coroutine as ready</li><li>Repeat</li></ol><pre>import asyncio<br><br>async def main():<br>    await some_coroutine()<br>asyncio.run(main())  # Creates loop, runs main(), closes loop</pre><p>asyncio.run() is the standard entry point. It creates a fresh event loop for the current thread and runs until the coroutine completes. In frameworks like FastAPI and uvicorn, the framework creates the event loop for you — you never call asyncio.run() inside an endpoint.</p><h3>await</h3><p>await does two things at once:</p><ol><li>Unpacks a coroutine or Future and waits for the result</li><li>Suspends the current coroutine and yields control to the event loop while waiting</li></ol><p>You can only await inside an async def function. You can await anything that implements __await__, including coroutines, asyncio.Task, asyncio.Future, and objects from async libraries like aiohttp or SQLAlchemy&#39;s async session.</p><pre>async def example():<br>    result = await some_io_operation()  # suspends here, loop runs other things<br>    return result</pre><h3>Task</h3><p>A Task wraps a coroutine and schedules it to run on the event loop immediately. The key difference from plain await:</p><pre>async def main():<br>    # Sequential — total time = t1 + t2<br>    result1 = await fetch(&quot;url1&quot;)<br>    result2 = await fetch(&quot;url2&quot;)<br><br>    # Concurrent - total time = max(t1, t2)<br>    task1 = asyncio.create_task(fetch(&quot;url1&quot;))<br>    task2 = asyncio.create_task(fetch(&quot;url2&quot;))<br>    result1 = await task1<br>    result2 = await task2</pre><p>asyncio.create_task() schedules the coroutine immediately. The task starts running as soon as the current coroutine yields to the event loop.</p><h3>asyncio.gather()</h3><p>gather() is the idiomatic way to run multiple coroutines or tasks concurrently and wait for all of them.</p><pre>async def main():<br>    results = await asyncio.gather(<br>        fetch(&quot;url1&quot;),<br>        fetch(&quot;url2&quot;),<br>        fetch(&quot;url3&quot;),<br>    )<br>    r1, r2, r3 = results  # order matches input, not completion order</pre><p>Key behaviors to know:</p><ul><li>All coroutines start together</li><li>Returns when <strong>all</strong> of them complete</li><li>Results are in the same order as the inputs, regardless of which finished first</li><li>By default, if one raises an exception, gather() cancels the others and re-raises. Pass return_exceptions=True to collect exceptions as values instead:</li></ul><pre>results = await asyncio.gather(<br>    fetch(&quot;url1&quot;),<br>    fetch(&quot;url2&quot;),<br>    return_exceptions=True<br>)<br>for r in results:<br>    if isinstance(r, Exception):<br>        print(f&quot;Failed: {r}&quot;)<br>    else:<br>        print(f&quot;Got: {r}&quot;)</pre><h3>asyncio.Semaphore</h3><p>A Semaphore limits how many coroutines can be in a critical section simultaneously. It works as a counter: acquiring decrements it, releasing increments it. When the counter hits zero, any coroutine trying to acquire blocks until another releases.</p><p>Why does this matter in practice? gather() with 1000 URLs fires 1000 concurrent requests instantly, which can overwhelm a server or exhaust your connection pool. A Semaphore throttles that concurrency to a safe level.</p><pre>sem = asyncio.Semaphore(10)  # max 10 concurrent at any time<br><br>async def fetch_with_limit(session, url):<br>    async with sem:  # blocks if 10 are already running<br>        response = await session.get(url)<br>        return await response.json()<br><br>async def main():<br>    async with aiohttp.ClientSession() as session:<br>        results = await asyncio.gather(<br>            *[fetch_with_limit(session, url) for url in large_list_of_urls]<br>        )</pre><p>The async with sem: pattern is idiomatic — it acquires on entry and releases on exit, even if an exception is raised.</p><h3>Other Synchronization Primitives</h3><p><strong>asyncio.Lock</strong> — a Semaphore(1). Only one coroutine can hold it at a time. Use it to protect shared mutable state.</p><p><strong>asyncio.Event</strong> — a signal. One coroutine sets it, others await it. Useful for one-to-many notifications.</p><p><strong>asyncio.Queue</strong> — a producer-consumer queue. Safe to use across coroutines in the same event loop.</p><h3>asyncio.wait() vs gather()</h3><p>asyncio.wait() is lower-level and more flexible:</p><pre>tasks = [asyncio.create_task(fetch(url)) for url in urls]<br><br># Wait for all:<br>done, pending = await asyncio.wait(tasks)<br># Return as soon as the first one completes:<br>done, pending = await asyncio.wait(tasks, return_when=asyncio.FIRST_COMPLETED)<br># With a timeout:<br>done, pending = await asyncio.wait(tasks, timeout=5.0)</pre><p>Use gather() when you want all results in order and don&#39;t need fine-grained control. Use wait() when you need to react to partial completion or enforce timeouts.</p><h3>asyncio.as_completed()</h3><p>Yields tasks as they finish, not in submission order. Perfect for processing results immediately as they arrive:</p><pre>for coro in asyncio.as_completed([fetch(u) for u in urls]):<br>    result = await coro  # gets the fastest result first<br>    process(result)</pre><h3>When asyncio Is Not Enough: Threads and Processes</h3><p>asyncio is single-threaded. It handles concurrency through cooperative yielding, which only works for I/O-bound work. If you call a synchronous blocking function directly inside an async def — like requests.get(), time.sleep(), or any heavy computation — the entire event loop freezes. Nothing else can run while it&#39;s blocked.</p><h3>asyncio.to_thread() — Bridging Async and Blocking Code</h3><p>The clean solution when you have a synchronous library with no async equivalent:</p><pre># Runs a blocking function in a thread without freezing the event loop<br>result = await asyncio.to_thread(blocking_function, arg1, arg2)</pre><p>Under the hood, this uses loop.run_in_executor() with the default ThreadPoolExecutor. In FastAPI, this is exactly how synchronous route handlers are handled — the framework wraps them in run_in_executor automatically.</p><pre># The long-form equivalent (useful when you need a custom executor):<br>from concurrent.futures import ThreadPoolExecutor<br><br>executor = ThreadPoolExecutor(max_workers=4)<br>loop = asyncio.get_event_loop()<br>result = await loop.run_in_executor(executor, blocking_function, arg1, arg2)</pre><h3>ProcessPoolExecutor — True Parallelism for CPU-bound Work</h3><p>For truly parallel execution that bypasses the GIL, use separate processes:</p><pre>from concurrent.futures import ProcessPoolExecutor<br><br>async def main():<br>    loop = asyncio.get_event_loop()<br>    with ProcessPoolExecutor() as executor:<br>        result = await loop.run_in_executor(executor, cpu_heavy_function, data)</pre><p>The trade-off: inter-process communication requires pickling data, there’s startup overhead per process, and there’s no shared memory. Use this only when you’ve profiled and confirmed the bottleneck is CPU computation.</p><h3>The Decision Matrix</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pAJFyXeF-2jXDYryyXHtMg.png" /></figure><h3>Common Pitfalls</h3><p><strong>1. Blocking the event loop.</strong> Calling requests.get(), time.sleep(), or any heavy computation inside async def freezes the entire loop. Use async equivalents (aiohttp, asyncio.sleep()) or asyncio.to_thread().</p><p><strong>2. Forgetting to </strong><strong>await.</strong> Writing result = fetch() creates a coroutine object but never runs it. You&#39;ll get a &quot;coroutine was never awaited&quot; warning and no result. Always await coroutine calls or wrap them in create_task().</p><p><strong>3. Sharing mutable state without locks.</strong> Even though asyncio is single-threaded, code can interleave between await points. If two coroutines both modify the same dict with an await in the middle of their logic, you can get inconsistent state. Use asyncio.Lock for critical sections.</p><p><strong>4. Using asyncio primitives across threads.</strong> asyncio.Lock, asyncio.Queue, and friends are NOT thread-safe. Don&#39;t use them across threads. Use loop.call_soon_threadsafe() to schedule work on the event loop from a thread.</p><p><strong>5. Misunderstanding coroutines vs tasks.</strong> gather(coro1(), coro2()) passes coroutine objects which gather wraps as tasks — that&#39;s fine. But coro = coro1() without create_task() means the coroutine won&#39;t start until it&#39;s explicitly awaited or passed somewhere. Use create_task() if you want it to start immediately.</p><h3>A Production Pattern</h3><p>Here’s a pattern I use regularly when scraping or hitting external APIs at scale in a FastAPI service:</p><pre>import asyncio<br>import aiohttp<br>from asyncio import Semaphore<br><br>sem = Semaphore(10)  # never more than 10 concurrent fetches<br>async def fetch_one(session: aiohttp.ClientSession, url: str) -&gt; dict:<br>    async with sem:<br>        async with session.get(url) as resp:<br>            return await resp.json()<br><br>async def fetch_all(urls: list[str]) -&gt; list[dict]:<br>    async with aiohttp.ClientSession() as session:<br>        tasks = [fetch_one(session, url) for url in urls]<br>        results = await asyncio.gather(*tasks, return_exceptions=True)<br>    return results</pre><p>The flow: gather() creates tasks for all URLs simultaneously. Each task tries to acquire the semaphore. Only 10 proceed at a time. As one finishes and releases the semaphore, the next waiting task gets in. All results are collected in input order.</p><p>This pattern gives you maximum concurrency within a safe upper bound, with clean error handling via return_exceptions=True.</p><h3>Wrapping Up</h3><p>The concurrency landscape in Python has layers, and each layer exists because the one before it wasn’t enough for some class of problem:</p><ul><li>Blocking code wasn’t enough → threads</li><li>Threads were too expensive and error-prone → event loops with callbacks</li><li>Callbacks were unreadable → generator-based coroutines</li><li>Generator coroutines were awkward → native async/await</li></ul><p>Understanding this evolution means you understand <em>why</em> the tools work the way they do, not just <em>how</em> to call them. That understanding is what lets you debug a frozen event loop, decide when to reach for a thread pool, and build systems that actually scale.</p><p>If you’re working with FastAPI, SQLAlchemy async, or any modern Python async stack, most of your daily work lives in async def, await, gather, and Semaphore. The thread and process tools are the escape hatches you&#39;ll be glad exist when you eventually need them.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4f84f83d8be9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[FastAPI]]></title>
            <link>https://medium.com/@vengiboopathi/fastapi-66b2d17293d5?source=rss-d9be6945e434------2</link>
            <guid isPermaLink="false">https://medium.com/p/66b2d17293d5</guid>
            <dc:creator><![CDATA[Vengadesa Boopathi]]></dc:creator>
            <pubDate>Sat, 28 Mar 2026 18:27:23 GMT</pubDate>
            <atom:updated>2026-03-28T18:27:23.987Z</atom:updated>
            <content:encoded><![CDATA[<p>FastAPI is not just another web framework. It is a fundamental rethink of what a Python API framework should feel like in 2026— one that makes the right thing the easy thing, gives you production-grade features out of the box, and does not ask you to write boilerplate that a machine can infer from code you already wrote.</p><p>This article goes deep. We cover the internals, the patterns, the gotchas, and end with an honest comparison against Flask, Django REST Framework, and other contenders.</p><h3>Why FastAPI Exists</h3><p>Flask came out in 2010. It was a breath of fresh air after Django — minimal, explicit, stay-out-of-your-way. But it was designed for a synchronous, pre-type-hints Python world. To get validation, serialization, and documentation out of Flask, you bolt on marshmallow, Flask-RESTful, apispec, Flask-Login — each with its own API, its own quirks, its own maintenance burden.</p><p>FastAPI was created by Sebastián Ramírez and first released in 2018. The core insight was: Python now has type hints (PEP 484, 3.5+) and Pydantic uses them to do runtime validation. If a framework is built from the ground up around type hints, it can eliminate entire categories of boilerplate automatically.</p><p>The result: you write Python functions with typed parameters. FastAPI infers the request schema, validates inputs, generates OpenAPI docs, and serializes responses — all from the same type annotations you’d write anyway for a good IDE experience.</p><h3>The Foundation: ASGI, Starlette, and Uvicorn</h3><p>Before writing a line of FastAPI code, understand the stack underneath it.</p><p><strong>WSGI vs ASGI</strong></p><p>Flask is a WSGI framework. WSGI (Web Server Gateway Interface, PEP 3333) is synchronous — one request, one thread, one response, done. This is fine for CPU-bound or DB-bound workloads where you’d use a thread pool anyway. But it cannot natively handle long-lived connections (WebSockets) or concurrent I/O without threads.</p><p>ASGI (Asynchronous Server Gateway Interface) is the async successor. Instead of a synchronous callable, an ASGI app is an async callable. This lets a single process handle thousands of concurrent connections using Python’s asyncio event loop — no threads required for I/O-bound work.</p><p>Difference between Synchronous and Asynchronous Programming:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/747/0*rVZ08l1swZKaq2Aa.png" /></figure><p><strong>Starlette</strong></p><p>FastAPI is built on top of Starlette, which is the actual ASGI framework. Starlette handles routing, middleware, WebSockets, background tasks, static files, and test client. FastAPI wraps Starlette and adds the type-hint-driven parameter injection, Pydantic validation, and OpenAPI generation on top.</p><p><strong>Uvicorn</strong></p><p>Uvicorn is the ASGI server — the thing that actually listens on a port, accepts TCP connections, and runs your ASGI app. It is to FastAPI what Gunicorn is to Flask. For production, you typically run Gunicorn as the process manager with Uvicorn workers.</p><pre>[Client] -&gt; [Nginx] -&gt; [Gunicorn] -&gt; [Uvicorn Worker] -&gt; [Starlette/FastAPI App]</pre><p>Install the full stack:</p><pre>pip install fastapi uvicorn[standard] gunicorn</pre><h3>Your First FastAPI App</h3><pre>from fastapi import FastAPI<br><br>app = FastAPI()<br><br>@app.get(&quot;/&quot;)<br>def root():<br>    return {&quot;message&quot;: &quot;Hello, World&quot;}</pre><p>Run it:</p><pre>uvicorn main:app --reload</pre><p>--reload watches for file changes and restarts automatically. Never use it in production.</p><p>Now open http://127.0.0.1:8000/docs. You get a fully interactive Swagger UI — for free, generated entirely from your code. Also available at /redoc for ReDoc UI and /openapi.json for the raw OpenAPI schema.</p><p>This is not a demo feature. The docs stay in sync with your code because they ARE generated from your code. There is no separate documentation to maintain.</p><h3>Path Parameters</h3><pre>from fastapi import FastAPI<br><br>app = FastAPI()<br>@app.get(&quot;/users/{user_id}&quot;)<br>def get_user(user_id: int):<br>    return {&quot;user_id&quot;: user_id}</pre><p>FastAPI reads the {user_id} in the path and maps it to the user_id parameter of the function. The int type annotation means FastAPI will:</p><ol><li>Extract user_id from the path</li><li>Attempt to convert it to int</li><li>If conversion fails, return a 422 Unprocessable Entity with a clear error message automatically</li></ol><pre>GET /users/5      -&gt; {&quot;user_id&quot;: 5}<br>GET /users/abc    -&gt; 422 {&quot;detail&quot;: [{&quot;loc&quot;: [&quot;path&quot;, &quot;user_id&quot;], &quot;msg&quot;: &quot;value is not a valid integer&quot;}]}</pre><p>No try/except, no manual validation. The type annotation is the validation.</p><p>Path parameter types supported out of the box: int, float, str, bool, UUID, datetime, date, Decimal, and any Pydantic type.</p><p>Ordering matters: If you have both /users/me and /users/{user_id}, define /users/me first. FastAPI matches routes in definition order.</p><pre>@app.get(&quot;/users/me&quot;)<br>def get_me():<br>    return {&quot;user&quot;: &quot;current user&quot;}<br><br>@app.get(&quot;/users/{user_id}&quot;)<br>def get_user(user_id: int):<br>    return {&quot;user_id&quot;: user_id}</pre><h3>Query Parameters</h3><p>Any function parameter that is not in the path pattern is treated as a query parameter:</p><pre>@app.get(&quot;/items&quot;)<br>def list_items(<br>    skip: int = 0,<br>    limit: int = 10,<br>    search: str | None = None,<br>    active: bool = True<br>):<br>    return {<br>        &quot;skip&quot;: skip,<br>        &quot;limit&quot;: limit,<br>        &quot;search&quot;: search,<br>        &quot;active&quot;: active<br>    }<br><br>GET /items?skip=20&amp;limit=5&amp;search=phone&amp;active=false</pre><p>FastAPI handles the string-to-type coercion for all of them. bool conversion is smart: &quot;false&quot;, &quot;0&quot;, &quot;no&quot;, &quot;off&quot; all become False. &quot;true&quot;, &quot;1&quot;, &quot;yes&quot;, &quot;on&quot; all become True.</p><p>str | None = None marks a parameter as optional. Without a default value, it is required.</p><h3>Pydantic Models: The Core of FastAPI</h3><p>Pydantic is the engine that makes FastAPI’s validation work. A Pydantic model is a class that inherits from BaseModel and uses type annotations to define its fields. At instantiation time, Pydantic validates and coerces the input.</p><pre>from pydantic import BaseModel, EmailStr, Field<br>from datetime import datetime<br><br>class UserCreate(BaseModel):<br>    name: str = Field(min_length=1, max_length=100)<br>    email: EmailStr<br>    age: int = Field(ge=0, le=150)<br>    bio: str | None = None<br>class UserResponse(BaseModel):<br>    id: int<br>    name: str<br>    email: str<br>    created_at: datetime<br>    class Config:<br>        from_attributes = True  # Enables ORM mode (read from SQLAlchemy models)</pre><p>Field() lets you add constraints: min_length, max_length, ge (greater than or equal), le (less than or equal), gt, lt, regex, description, example.</p><p>EmailStr requires pip install pydantic[email] and validates email format.</p><p>Using these in a route:</p><pre>@app.post(&quot;/users&quot;, response_model=UserResponse, status_code=201)<br>def create_user(user: UserCreate):<br>    # user is already validated -- if we&#39;re here, the data is clean<br>    new_user = save_to_db(user)<br>    return new_user</pre><p>response_model=UserResponse tells FastAPI: filter and serialize the return value through UserResponse. Fields not in UserResponse are stripped. This is your output validation — you never accidentally leak internal fields.</p><h3>Request Body, Path, and Query Together</h3><p>FastAPI figures out where each parameter comes from based on its type:</p><pre>from fastapi import FastAPI, Path, Query, Body<br>from pydantic import BaseModel<br><br>app = FastAPI()<br>class ItemUpdate(BaseModel):<br>    name: str<br>    price: float<br>@app.put(&quot;/shops/{shop_id}/items/{item_id}&quot;)<br>def update_item(<br>    shop_id: int = Path(ge=1),<br>    item_id: int = Path(ge=1),<br>    currency: str = Query(default=&quot;INR&quot;, max_length=3),<br>    item: ItemUpdate = Body(...)<br>):<br>    return {<br>        &quot;shop_id&quot;: shop_id,<br>        &quot;item_id&quot;: item_id,<br>        &quot;currency&quot;: currency,<br>        &quot;item&quot;: item<br>    }</pre><ul><li>shop_id and item_id come from the path</li><li>currency comes from the query string</li><li>item comes from the request body (JSON)</li></ul><p>Path(), Query(), Body() are not just for validation — they also enrich the generated OpenAPI docs with descriptions, examples, and constraints.</p><h3>Dependency Injection</h3><p>This is one of FastAPI’s most powerful and underused features. The Depends system lets you declare reusable logic that FastAPI resolves and injects before calling your route function.</p><h3>Common Pagination Pattern</h3><pre>from fastapi import Depends, Query<br><br>class PaginationParams:<br>    def __init__(<br>        self,<br>        page: int = Query(default=1, ge=1),<br>        per_page: int = Query(default=20, ge=1, le=100)<br>    ):<br>        self.page = page<br>        self.per_page = per_page<br>        self.offset = (page - 1) * per_page<br>@app.get(&quot;/products&quot;)<br>def list_products(pagination: PaginationParams = Depends()):<br>    return {<br>        &quot;page&quot;: pagination.page,<br>        &quot;per_page&quot;: pagination.per_page,<br>        &quot;offset&quot;: pagination.offset<br>    }<br>@app.get(&quot;/orders&quot;)<br>def list_orders(pagination: PaginationParams = Depends()):<br>    # Reuse the same pagination logic -- no copy-paste<br>    return {&quot;offset&quot;: pagination.offset}</pre><h3>Authentication Dependency</h3><pre>from fastapi import Depends, HTTPException, Security<br>from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials<br><br>security = HTTPBearer()<br>def get_current_user(<br>    credentials: HTTPAuthorizationCredentials = Security(security)<br>) -&gt; dict:<br>    token = credentials.credentials<br>    user = verify_jwt_token(token)  # your JWT verification logic<br>    if not user:<br>        raise HTTPException(status_code=401, detail=&quot;Invalid token&quot;)<br>    return user<br>@app.get(&quot;/profile&quot;)<br>def get_profile(current_user: dict = Depends(get_current_user)):<br>    return {&quot;user&quot;: current_user}<br>@app.delete(&quot;/profile&quot;)<br>def delete_profile(current_user: dict = Depends(get_current_user)):<br>    return {&quot;deleted&quot;: current_user[&quot;id&quot;]}</pre><p>Dependencies can depend on other dependencies. FastAPI builds a dependency graph, resolves it in the correct order, and caches results within the same request scope by default.</p><h3>Database Session Dependency</h3><pre>from sqlalchemy.orm import Session<br>from database import SessionLocal<br><br>def get_db():<br>    db = SessionLocal()<br>    try:<br>        yield db<br>    finally:<br>        db.close()<br>@app.get(&quot;/users/{user_id}&quot;)<br>def get_user(user_id: int, db: Session = Depends(get_db)):<br>    user = db.query(User).filter(User.id == user_id).first()<br>    if not user:<br>        raise HTTPException(status_code=404, detail=&quot;User not found&quot;)<br>    return user</pre><p>yield in a dependency turns it into a context manager. FastAPI runs the code before yield before the route, injects the yielded value, runs your route, then runs the code after yield for cleanup — even if an exception was raised.</p><h3>Async Routes: When and Why</h3><p>FastAPI supports both sync and async route functions. Understanding which to use matters.</p><pre># Sync -- runs in a thread pool executor<br>@app.get(&quot;/sync&quot;)<br>def sync_route():<br>    result = some_blocking_db_call()<br>    return result<br><br># Async -- runs on the event loop<br>@app.get(&quot;/async&quot;)<br>async def async_route():<br>    result = await some_async_db_call()<br>    return result</pre><p>When to use async: when your route does I/O — HTTP calls, database queries, file reads — using an async library (httpx, asyncpg, motor, aiofiles). The event loop can handle other requests while yours waits.</p><p>When to use sync: when your route does CPU-bound work, or when you’re using a synchronous library (like the standard requests library or synchronous SQLAlchemy). FastAPI runs sync routes in a thread pool automatically, so they don&#39;t block the event loop.</p><p>The mistake to avoid: never call blocking synchronous I/O inside an async route. This blocks the entire event loop.</p><pre>import httpx<br>import requests<br><br># WRONG -- blocks the event loop<br>@app.get(&quot;/wrong&quot;)<br>async def wrong():<br>    response = requests.get(&quot;https://api.example.com/data&quot;)  # blocks<br>    return response.json()<br># RIGHT -- async HTTP with httpx<br>@app.get(&quot;/right&quot;)<br>async def right():<br>    async with httpx.AsyncClient() as client:<br>        response = await client.get(&quot;https://api.example.com/data&quot;)<br>    return response.json()</pre><h3>Error Handling</h3><h3>HTTPException</h3><pre>from fastapi import HTTPException<br><br>@app.get(&quot;/users/{user_id}&quot;)<br>def get_user(user_id: int):<br>    user = db.get(user_id)<br>    if not user:<br>        raise HTTPException(<br>            status_code=404,<br>            detail={&quot;error&quot;: &quot;User not found&quot;, &quot;user_id&quot;: user_id}<br>        )<br>    return user</pre><p>detail can be a string or a dict — FastAPI serializes it as JSON automatically.</p><h3>Custom Exception Handlers</h3><pre>from fastapi import Request<br>from fastapi.responses import JSONResponse<br><br>class InsufficientFundsError(Exception):<br>    def __init__(self, balance: float, required: float):<br>        self.balance = balance<br>        self.required = required<br>@app.exception_handler(InsufficientFundsError)<br>async def insufficient_funds_handler(request: Request, exc: InsufficientFundsError):<br>    return JSONResponse(<br>        status_code=402,<br>        content={<br>            &quot;error&quot;: &quot;Insufficient Funds&quot;,<br>            &quot;balance&quot;: exc.balance,<br>            &quot;required&quot;: exc.required,<br>            &quot;shortfall&quot;: exc.required - exc.balance<br>        }<br>    )<br>@app.post(&quot;/purchase&quot;)<br>def make_purchase(amount: float):<br>    balance = get_user_balance()<br>    if balance &lt; amount:<br>        raise InsufficientFundsError(balance=balance, required=amount)<br>    return {&quot;status&quot;: &quot;success&quot;}</pre><h3>Override Default Validation Error Handler</h3><p>FastAPI returns a 422 with Pydantic’s error format by default. You can override it:</p><pre>from fastapi.exceptions import RequestValidationError<br><br>@app.exception_handler(RequestValidationError)<br>async def validation_exception_handler(request: Request, exc: RequestValidationError):<br>    errors = []<br>    for error in exc.errors():<br>        errors.append({<br>            &quot;field&quot;: &quot;.&quot;.join(str(loc) for loc in error[&quot;loc&quot;]),<br>            &quot;message&quot;: error[&quot;msg&quot;],<br>            &quot;type&quot;: error[&quot;type&quot;]<br>        })<br>    return JSONResponse(<br>        status_code=422,<br>        content={&quot;error&quot;: &quot;Validation Failed&quot;, &quot;details&quot;: errors}<br>    )</pre><h3>Middleware</h3><pre>import time<br>import uuid<br>from fastapi import Request<br><br>@app.middleware(&quot;http&quot;)<br>async def request_middleware(request: Request, call_next):<br>    request_id = str(uuid.uuid4())<br>    start_time = time.time()<br>    request.state.request_id = request_id<br>    response = await call_next(request)<br>    duration_ms = round((time.time() - start_time) * 1000, 2)<br>    response.headers[&quot;X-Request-ID&quot;] = request_id<br>    response.headers[&quot;X-Response-Time&quot;] = f&quot;{duration_ms}ms&quot;<br>    print(f&quot;{request.method} {request.url.path} -&gt; {response.status_code} ({duration_ms}ms)&quot;)<br>    return response</pre><p>For CORS:</p><pre>from fastapi.middleware.cors import CORSMiddleware<br><br>app.add_middleware(<br>    CORSMiddleware,<br>    allow_origins=[&quot;https://yourfrontend.com&quot;],<br>    allow_credentials=True,<br>    allow_methods=[&quot;GET&quot;, &quot;POST&quot;, &quot;PUT&quot;, &quot;DELETE&quot;, &quot;PATCH&quot;],<br>    allow_headers=[&quot;Authorization&quot;, &quot;Content-Type&quot;]<br>)</pre><p>For compression:</p><pre>from fastapi.middleware.gzip import GZipMiddleware<br><br>app.add_middleware(GZipMiddleware, minimum_size=1000)</pre><h3>Routers: Structuring a Real Application</h3><pre>project/<br>├── main.py<br>├── routers/<br>│   ├── __init__.py<br>│   ├── users.py<br>│   └── products.py<br>├── models/<br>│   ├── user.py<br>│   └── product.py<br>├── dependencies.py<br>└── database.py</pre><p>routers/users.py:</p><pre>from fastapi import APIRouter, Depends, HTTPException<br>from dependencies import get_db, get_current_user<br><br>router = APIRouter(<br>    prefix=&quot;/users&quot;,<br>    tags=[&quot;users&quot;],<br>    dependencies=[Depends(get_current_user)]<br>)<br>@router.get(&quot;/&quot;)<br>def list_users(db=Depends(get_db)):<br>    return db.query(User).all()<br>@router.get(&quot;/{user_id}&quot;)<br>def get_user(user_id: int, db=Depends(get_db)):<br>    user = db.query(User).filter(User.id == user_id).first()<br>    if not user:<br>        raise HTTPException(status_code=404, detail=&quot;Not found&quot;)<br>    return user<br>@router.post(&quot;/&quot;, status_code=201)<br>def create_user(data: UserCreate, db=Depends(get_db)):<br>    user = User(**data.dict())<br>    db.add(user)<br>    db.commit()<br>    db.refresh(user)<br>    return user</pre><p>main.py:</p><pre>from fastapi import FastAPI<br>from routers import users, products<br><br>app = FastAPI(<br>    title=&quot;My API&quot;,<br>    description=&quot;Production API built with FastAPI&quot;,<br>    version=&quot;1.0.0&quot;<br>)<br>app.include_router(users.router)<br>app.include_router(products.router)</pre><p>tags=[&quot;users&quot;] groups routes in the Swagger UI. prefix=&quot;/users&quot; means you don&#39;t repeat /users in every route definition.</p><h3>Lifespan Events: Startup and Shutdown</h3><p>FastAPI’s modern way to handle startup/shutdown logic (DB connections, loading ML models, etc.):</p><pre>from contextlib import asynccontextmanager<br>from fastapi import FastAPI<br><br>@asynccontextmanager<br>async def lifespan(app: FastAPI):<br>    # Runs before app starts accepting requests<br>    print(&quot;Starting up...&quot;)<br>    await database.connect()<br>    load_ml_model()<br>    yield  # App runs here<br>    # Runs when app is stopping<br>    print(&quot;Shutting down...&quot;)<br>    await database.disconnect()<br>app = FastAPI(lifespan=lifespan)</pre><p>This replaces the older @app.on_event(&quot;startup&quot;) decorator which is now deprecated.</p><h3>Background Tasks</h3><p>For work that should happen after the response is sent:</p><pre>from fastapi import BackgroundTasks<br><br>def send_welcome_email(email: str, name: str):<br>    # Runs after the response is already sent<br>    email_service.send(<br>        to=email,<br>        subject=&quot;Welcome!&quot;,<br>        body=f&quot;Hello {name}, welcome aboard.&quot;<br>    )<br>@app.post(&quot;/users&quot;, status_code=201)<br>def create_user(user: UserCreate, background_tasks: BackgroundTasks):<br>    new_user = db.create(user)<br>    background_tasks.add_task(send_welcome_email, user.email, user.name)<br>    return new_user  # Response sent immediately; email sends after</pre><p>For heavier background work (long-running jobs), use a proper task queue like Celery + Redis instead.</p><h3>WebSockets</h3><p>FastAPI supports WebSockets natively via Starlette:</p><pre>from fastapi import WebSocket, WebSocketDisconnect<br><br>class ConnectionManager:<br>    def __init__(self):<br>        self.active: list[WebSocket] = []<br>    async def connect(self, ws: WebSocket):<br>        await ws.accept()<br>        self.active.append(ws)<br>    def disconnect(self, ws: WebSocket):<br>        self.active.remove(ws)<br>    async def broadcast(self, message: str):<br>        for connection in self.active:<br>            await connection.send_text(message)<br>manager = ConnectionManager()<br>@app.websocket(&quot;/ws/{client_id}&quot;)<br>async def websocket_endpoint(ws: WebSocket, client_id: str):<br>    await manager.connect(ws)<br>    try:<br>        while True:<br>            data = await ws.receive_text()<br>            await manager.broadcast(f&quot;{client_id}: {data}&quot;)<br>    except WebSocketDisconnect:<br>        manager.disconnect(ws)<br>        await manager.broadcast(f&quot;{client_id} left&quot;)</pre><p>Real-time chat broadcast in under 30 lines. Flask cannot do this natively at all.</p><h3>Consuming External APIs from FastAPI</h3><p>Since FastAPI is async-native, use httpx instead of requests for outbound HTTP calls. requests is synchronous and blocks the event loop inside async routes.</p><pre>pip install httpx</pre><h3>Basic GET Request</h3><pre>import httpx<br>from fastapi import FastAPI, HTTPException<br><br>app = FastAPI()<br>@app.get(&quot;/weather/{city}&quot;)<br>async def get_weather(city: str):<br>    async with httpx.AsyncClient() as client:<br>        response = await client.get(<br>            &quot;https://api.openweathermap.org/data/2.5/weather&quot;,<br>            params={&quot;q&quot;: city, &quot;appid&quot;: &quot;your_api_key&quot;, &quot;units&quot;: &quot;metric&quot;},<br>            timeout=5.0<br>        )<br>    if response.status_code == 404:<br>        raise HTTPException(status_code=404, detail=f&quot;City not found&quot;)<br>    response.raise_for_status()<br>    return response.json()</pre><h3>Reusing a Client with Lifespan (Production Pattern)</h3><p>Opening a new AsyncClient on every request creates a new connection pool each time. The right pattern is one client at startup, reused across all requests.</p><pre>import httpx<br>from contextlib import asynccontextmanager<br>from fastapi import FastAPI, Depends<br><br>http_client: httpx.AsyncClient = None<br>@asynccontextmanager<br>async def lifespan(app: FastAPI):<br>    global http_client<br>    http_client = httpx.AsyncClient(<br>        timeout=httpx.Timeout(connect=3.0, read=10.0, write=5.0, pool=2.0),<br>        limits=httpx.Limits(max_connections=100, max_keepalive_connections=20)<br>    )<br>    yield<br>    await http_client.aclose()<br>app = FastAPI(lifespan=lifespan)<br>def get_http_client() -&gt; httpx.AsyncClient:<br>    return http_client<br>@app.get(&quot;/github/{username}&quot;)<br>async def get_github_user(<br>    username: str,<br>    client: httpx.AsyncClient = Depends(get_http_client)<br>):<br>    response = await client.get(<br>        f&quot;https://api.github.com/users/{username}&quot;,<br>        headers={&quot;Accept&quot;: &quot;application/vnd.github.v3+json&quot;}<br>    )<br>    if response.status_code == 404:<br>        raise HTTPException(status_code=404, detail=&quot;GitHub user not found&quot;)<br>    response.raise_for_status()<br>    return response.json()</pre><h3>Parallel API Calls with asyncio.gather</h3><p>One of the biggest wins of async: fire multiple API calls simultaneously and wait for all together. Sequential requests would take 300ms x 3 = 900ms. asyncio.gather runs them concurrently so total time is roughly the slowest single call, around 300ms.</p><pre>import asyncio<br>import httpx<br>from fastapi import FastAPI<br><br>app = FastAPI()<br>@app.get(&quot;/dashboard/{user_id}&quot;)<br>async def get_dashboard(user_id: int):<br>    async with httpx.AsyncClient(timeout=10.0) as client:<br>        profile_task = client.get(f&quot;https://api.example.com/users/{user_id}&quot;)<br>        orders_task = client.get(f&quot;https://api.example.com/orders?user={user_id}&quot;)<br>        notifs_task = client.get(f&quot;https://api.example.com/notifications/{user_id}&quot;)<br>        profile, orders, notifs = await asyncio.gather(<br>            profile_task, orders_task, notifs_task<br>        )<br>    return {<br>        &quot;profile&quot;: profile.json(),<br>        &quot;orders&quot;: orders.json(),<br>        &quot;notifications&quot;: notifs.json()<br>    }</pre><h3>Error Handling for Outbound Calls</h3><pre>import httpx<br>from fastapi import HTTPException<br><br>async def call_external_api(url: str, client: httpx.AsyncClient) -&gt; dict:<br>    try:<br>        response = await client.get(url, timeout=5.0)<br>        response.raise_for_status()<br>        return response.json()<br>    except httpx.TimeoutException:<br>        raise HTTPException(status_code=504, detail=&quot;External API timed out&quot;)<br>    except httpx.HTTPStatusError as e:<br>        raise HTTPException(<br>            status_code=e.response.status_code,<br>            detail=f&quot;External API error: {e.response.text}&quot;<br>        )<br>    except httpx.RequestError as e:<br>        raise HTTPException(status_code=502, detail=f&quot;Could not reach external API: {str(e)}&quot;)</pre><h3>POST with Headers and Auth to External APIs</h3><pre>@app.post(&quot;/send-notification&quot;)<br>async def send_notification(user_id: int, message: str):<br>    async with httpx.AsyncClient() as client:<br>        response = await client.post(<br>            &quot;https://api.notifications.com/send&quot;,<br>            json={&quot;user_id&quot;: user_id, &quot;message&quot;: message},<br>            headers={<br>                &quot;Authorization&quot;: &quot;Bearer your_token_here&quot;,<br>                &quot;Content-Type&quot;: &quot;application/json&quot;<br>            },<br>            timeout=5.0<br>        )<br>    response.raise_for_status()<br>    return {&quot;status&quot;: &quot;sent&quot;, &quot;response&quot;: response.json()}Testing FastAPI</pre><h4>TestClient</h4><p>FastAPI ships with a TestClient from Starlette (wraps httpx):</p><pre>from fastapi.testclient import TestClient<br>from main import app<br><br>client = TestClient(app)<br>def test_create_user():<br>    response = client.post(<br>        &quot;/users&quot;,<br>        json={&quot;name&quot;: &quot;Venki&quot;, &quot;email&quot;: &quot;v@example.com&quot;, &quot;age&quot;: 25}<br>    )<br>    assert response.status_code == 201<br>    data = response.json()<br>    assert data[&quot;name&quot;] == &quot;Venki&quot;<br>    assert &quot;id&quot; in data<br>def test_invalid_email():<br>    response = client.post(<br>        &quot;/users&quot;,<br>        json={&quot;name&quot;: &quot;Venki&quot;, &quot;email&quot;: &quot;not-an-email&quot;, &quot;age&quot;: 25}<br>    )<br>    assert response.status_code == 422<br>def test_user_not_found():<br>    response = client.get(&quot;/users/99999&quot;)<br>    assert response.status_code == 404</pre><p>For async tests with pytest-asyncio:</p><pre>import pytest<br>import httpx<br>from main import app<br><br>@pytest.mark.asyncio<br>async def test_async_endpoint():<br>    async with httpx.AsyncClient(app=app, base_url=&quot;http://test&quot;) as client:<br>        response = await client.get(&quot;/async-endpoint&quot;)<br>    assert response.status_code == 200</pre><h3>A Production-Ready FastAPI Template</h3><pre>import time<br>import uuid<br>import logging<br>from contextlib import asynccontextmanager<br>from fastapi import FastAPI, Request<br>from fastapi.middleware.cors import CORSMiddleware<br>from fastapi.exceptions import RequestValidationError<br>from fastapi.responses import JSONResponse<br>from fastapi.middleware.gzip import GZipMiddleware<br><br>LOG_FORMAT = &quot;%(asctime)s | %(levelname)s | %(name)s | %(message)s&quot;<br>logging.basicConfig(level=logging.INFO, format=LOG_FORMAT)<br>logger = logging.getLogger(__name__)<br><br>@asynccontextmanager<br>async def lifespan(app: FastAPI):<br>    logger.info(&quot;Starting up...&quot;)<br>    # await db.connect()<br>    yield<br>    logger.info(&quot;Shutting down...&quot;)<br>    # await db.disconnect()<br><br>app = FastAPI(<br>    title=&quot;My API&quot;,<br>    description=&quot;Production-ready FastAPI application&quot;,<br>    version=&quot;1.0.0&quot;,<br>    lifespan=lifespan,<br>    docs_url=&quot;/docs&quot;,<br>    redoc_url=&quot;/redoc&quot;<br>)<br>app.add_middleware(GZipMiddleware, minimum_size=1000)<br>app.add_middleware(<br>    CORSMiddleware,<br>    allow_origins=[&quot;*&quot;],<br>    allow_methods=[&quot;*&quot;],<br>    allow_headers=[&quot;*&quot;]<br>)<br><br>@app.middleware(&quot;http&quot;)<br>async def request_middleware(request: Request, call_next):<br>    request_id = str(uuid.uuid4())<br>    request.state.request_id = request_id<br>    start = time.time()<br>    response = await call_next(request)<br>    duration_ms = round((time.time() - start) * 1000, 2)<br>    response.headers[&quot;X-Request-ID&quot;] = request_id<br>    response.headers[&quot;X-Response-Time&quot;] = f&quot;{duration_ms}ms&quot;<br>    logger.info(<br>        f&quot;rid={request_id} method={request.method} &quot;<br>        f&quot;path={request.url.path} status={response.status_code} &quot;<br>        f&quot;duration_ms={duration_ms}&quot;<br>    )<br>    return response<br><br>@app.exception_handler(RequestValidationError)<br>async def validation_error_handler(request: Request, exc: RequestValidationError):<br>    errors = [<br>        {<br>            &quot;field&quot;: &quot;.&quot;.join(str(l) for l in e[&quot;loc&quot;]),<br>            &quot;message&quot;: e[&quot;msg&quot;],<br>            &quot;type&quot;: e[&quot;type&quot;]<br>        }<br>        for e in exc.errors()<br>    ]<br>    return JSONResponse(status_code=422, content={&quot;error&quot;: &quot;Validation Failed&quot;, &quot;details&quot;: errors})<br><br>@app.exception_handler(Exception)<br>async def unhandled_exception_handler(request: Request, exc: Exception):<br>    logger.exception(f&quot;Unhandled exception on {request.method} {request.url.path}&quot;)<br>    return JSONResponse(<br>        status_code=500,<br>        content={<br>            &quot;error&quot;: &quot;Internal Server Error&quot;,<br>            &quot;request_id&quot;: request.state.request_id<br>        }<br>    )<br><br>@app.get(&quot;/health&quot;, tags=[&quot;system&quot;])<br>def health_check():<br>    return {&quot;status&quot;: &quot;ok&quot;}<br><br># app.include_router(users.router)<br># app.include_router(products.router)</pre><p>Run in production:</p><pre>gunicorn main:app \<br>  --workers 4 \<br>  --worker-class uvicorn.workers.UvicornWorker \<br>  --bind 0.0.0.0:8000 \<br>  --timeout 60 \<br>  --access-logfile -</pre><h3>FastAPI vs Flask vs Django REST Framework vs Others</h3><h3>FastAPI vs Flask</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/943/1*xHhQQYLzLsmyIlzoT-24nA.png" /></figure><p>Flask’s advantage is its age. If you search for a Flask extension to do something, it probably exists. FastAPI’s ecosystem is younger but growing rapidly. If you’re starting a new project today with no legacy constraints, FastAPI is the better choice in almost every scenario.</p><h3>FastAPI vs Django REST Framework (DRF)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/839/1*pPfBX58iSaBSGXs4hmqo6A.png" /></figure><p>DRF is the right choice when you are building a Django application that needs REST endpoints — you already have the ORM, migrations, admin, and auth. Adding DRF is natural. FastAPI is the right choice when you want a pure API backend with no framework opinions on ORM or database.</p><h3>FastAPI vs Express (Node.js)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/681/1*siagPIlJaXhmYwtPv0R7zw.png" /></figure><p>Choosing between these is mostly a language preference call. If your team knows Python, FastAPI. If they know JavaScript/TypeScript, Express or Fastify.</p><h3>FastAPI vs Litestar</h3><p>Litestar is the closest competitor to FastAPI in the Python async world. Both are ASGI, both use Pydantic, both generate OpenAPI docs. Litestar has a more opinionated architecture with better built-in dependency injection patterns and a slightly steeper learning curve. FastAPI has a larger community and far more third-party tutorials. For most teams, FastAPI is the better-supported choice today.</p><h3>When NOT to Use FastAPI</h3><ul><li>You need Django admin, Django ORM, or Django’s full-stack features — use Django + DRF</li><li>You have an existing Flask codebase with years of extensions — migration cost may not be worth it</li><li>Your team is a Node.js shop — pick Fastify or Express</li><li>You’re building a simple internal tool with minimal endpoints — Flask’s simplicity may actually be an advantage</li><li>You need gRPC as your primary protocol — consider grpcio directly</li></ul><h3>The Bottom Line</h3><p>FastAPI earns its popularity. It is not hype. The combination of Pydantic validation, automatic OpenAPI docs, native async, and a clean dependency injection system produces APIs that are faster to write, harder to break, and easier to document than anything Python had before it.</p><p>The learning curve is real — you need to understand async/await, Pydantic models, and dependency injection to use it well. But once those click, going back to writing manual validation and maintaining separate API documentation feels like a step backward.</p><p>Start with the production template above. Add SQLAlchemy + alembic for your database. Add python-jose or PyJWT for JWT auth. Add pytest + httpx for tests. You will have a production-grade API stack in an afternoon.</p><p><em>This is part of a series on Python API development. The previous article covers APIs from first principles — TCP handshakes, HTTP internals, Flask deep dive, and common API design mistakes.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=66b2d17293d5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[APIs: The Invisible Infrastructure of Everything You Use]]></title>
            <link>https://medium.com/@vengiboopathi/apis-the-invisible-infrastructure-of-everything-you-use-3253b8330d8b?source=rss-d9be6945e434------2</link>
            <guid isPermaLink="false">https://medium.com/p/3253b8330d8b</guid>
            <dc:creator><![CDATA[Vengadesa Boopathi]]></dc:creator>
            <pubDate>Fri, 27 Mar 2026 10:43:59 GMT</pubDate>
            <atom:updated>2026-03-27T10:43:59.658Z</atom:updated>
            <content:encoded><![CDATA[<p>You’ve heard the word a thousand times. APIs. But most articles stop at the waiter analogy and call it a day. This one doesn’t. By the end of this article you’ll understand not just <em>what</em> an API is, but <em>why</em> it’s designed the way it is, what actually happens at the network level when a request is made, how a server handles thousands of concurrent connections, and how to build and host your own API from scratch using Python and Flask. We’ll also look at the mistakes developers make when building APIs and how to avoid them.</p><p>Let’s go deep.</p><h3>The Real Reason APIs Exist</h3><p>Before HTTP, before REST, before JSON — software systems still needed to talk to each other. Early solutions were nightmares: shared memory regions, custom binary protocols, raw TCP sockets with hand-rolled parsing. Every integration was a one-off engineering project.</p><p>APIs are the answer to a design question: <em>how do we let two systems communicate without either one needing to know the internal implementation details of the other?</em></p><p>This is the principle of <strong>encapsulation</strong> applied to networked systems. A good API is a <strong>contract</strong>. It says: “Send me a request in this shape, I’ll send back a response in that shape. What I do in between is none of your business.”</p><p>That contract is what makes software composable. Stripe doesn’t care if you built your frontend in React or Django. They expose an API and you call it. The internals are invisible. This is not a convenience — it’s a fundamental architectural principle that enables the entire modern software ecosystem.</p><h3>What HTTP Actually Is (And Why APIs Use It)</h3><p>Almost every API you’ll encounter is an HTTP API. To understand APIs deeply, you need to understand what HTTP is doing under the hood.</p><p>HTTP (HyperText Transfer Protocol) is a <strong>text-based, application-layer protocol</strong> built on top of TCP/IP. When your browser (or your Python script) makes an HTTP request, here’s what actually travels over the wire:</p><pre>GET /v1/forecast?city=London HTTP/1.1<br>Host: api.weather.com<br>Accept: application/json<br>Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...<br>Connection: keep-alive</pre><p>That’s it. Plain text. The server reads this, parses it, does some work, and sends back:</p><pre>HTTP/1.1 200 OK<br>Content-Type: application/json<br>Content-Length: 87<br>Date: Mon, 27 Mar 2026 12:00:00 GMT<br><br>{<br>  &quot;city&quot;: &quot;London&quot;,<br>  &quot;temperature&quot;: 14,<br>  &quot;unit&quot;: &quot;C&quot;,<br>  &quot;condition&quot;: &quot;Overcast&quot;<br>}</pre><p>Two blocks of text separated by a blank line. Everything above the blank line is <strong>headers</strong> (metadata about the request/response). Everything below is the <strong>body</strong> (the actual payload).</p><p>Understanding this is important because it demystifies the whole thing. There’s no magic. An API endpoint is just a server that listens on a port, reads these text messages, and writes back other text messages. Every framework — Flask, FastAPI, Express, Rails — is ultimately doing this, just with a lot of ergonomic scaffolding on top.</p><h3>The TCP Handshake: What Happens Before Your Request Even Sends</h3><p>Before any HTTP data flows, TCP (Transmission Control Protocol) has to establish a connection. This is the <strong>three-way handshake</strong>:</p><ol><li><strong>SYN</strong> — Your machine sends a SYN (synchronize) packet to the server’s IP and port. “I want to connect.”</li><li><strong>SYN-ACK</strong> — The server responds with SYN-ACK. “Okay, I acknowledge. I’m ready.”</li><li><strong>ACK</strong> — Your machine sends ACK. “Great. Connection established.”</li></ol><p>Only after this handshake does your HTTP request actually get sent. This is why latency matters. If the server is geographically far from you, even before your API call is processed, you’ve already spent time just shaking hands.</p><p>With HTTP/1.1, connections can be <strong>kept alive</strong> (reused for multiple requests). With HTTP/2, multiple requests can be <strong>multiplexed</strong> over a single connection simultaneously. This is why upgrading your server infrastructure isn’t just about CPU — network protocol choices have real performance implications.</p><h3>DNS: How api.weather.com Becomes an IP Address</h3><p>You don’t make requests to IP addresses directly in most cases. You use domain names. But underneath, networks only understand numbers.</p><p>When you call https://api.weather.com/v1/forecast, before the TCP handshake even begins, your operating system does a <strong>DNS lookup</strong>:</p><ol><li>Checks the local cache. Found? Use it.</li><li>Asks your router. Found? Use it.</li><li>Asks a recursive DNS resolver (usually your ISP’s or Google’s 8.8.8.8).</li><li>That resolver walks up the DNS hierarchy: root servers → .com TLD servers → weather.com authoritative nameserver.</li><li>Gets back: api.weather.com → 104.22.6.49</li></ol><p>Now your machine knows the actual IP to connect to. This entire process can happen in under 10 milliseconds when cached, or tens to hundreds of milliseconds on a cold lookup. This is why CDNs and DNS TTL tuning are real performance levers in production systems.</p><h3>REST: A Style, Not a Standard</h3><p>REST is not a protocol. It’s not a library. It’s not something you install. It’s an <strong>architectural style</strong> — a set of constraints described by Roy Fielding in his 2000 PhD dissertation.</p><p>The six constraints of REST:</p><ol><li><strong>Client-Server</strong> — Concerns are separated. The client handles the UI, the server handles data and logic. They communicate only through the interface.</li><li><strong>Stateless</strong> — Every request must contain all the information needed to process it. The server holds no session state between requests. This is why you send your auth token on every request instead of logging in once.</li><li><strong>Cacheable</strong> — Responses must declare whether they’re cacheable. This enables CDNs and browser caches to reduce server load.</li><li><strong>Uniform Interface</strong> — This is the big one. All resources are identified by URLs. Actions are expressed via HTTP methods. Responses describe how to modify the resource (HATEOAS, though rarely implemented in practice).</li><li><strong>Layered System</strong> — The client doesn’t know whether it’s talking directly to the server or to a load balancer, a cache, or a gateway. Each layer only knows about the layer immediately above and below.</li><li><strong>Code on Demand</strong> (optional) — Servers can send executable code to clients (like JavaScript). Most REST APIs don’t use this.</li></ol><p>When people say “RESTful API,” they usually mean: uses HTTP methods correctly, uses URLs as resource identifiers, returns JSON, and is stateless. The full Fielding definition is rarely implemented completely, especially HATEOAS.</p><p>The key practical takeaways:</p><ul><li>Use nouns in URLs, not verbs: /users/123 not /getUser?id=123</li><li>Use HTTP methods for the action: GET /users/123, DELETE /users/123, PATCH /users/123</li><li>Use status codes correctly (more on this shortly)</li><li>Keep it stateless — don’t store session data server-side between requests</li></ul><h3>HTTP Status Codes: Not Optional</h3><p>Bad APIs return 200 OK with {&quot;error&quot;: &quot;user not found&quot;} in the body. Don&#39;t be that API. Status codes exist precisely to communicate outcome at the protocol level, before the client even parses the body.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/768/1*iQ1Oud664ZxBOjyxWlC6cA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/825/1*sqrV4TS4Yv4eUN9wyr1Jeg.png" /></figure><p>The distinction between 401 and 403 confuses people: <strong>401 means “I don’t know who you are”</strong>, <strong>403 means “I know who you are, and you can’t do this.”</strong></p><h3>Flask: The Minimal Python Web Framework</h3><p>Flask is a micro web framework for Python. “Micro” doesn’t mean limited — it means Flask gives you the essentials and stays out of your way. It doesn’t dictate how you structure your project, which database to use, or how to handle authentication. That’s your call.</p><p>Flask’s core job: map incoming HTTP requests to Python functions and turn their return values into HTTP responses.</p><h3>Install Flask</h3><pre>pip install flask</pre><h3>Your First API Endpoint</h3><pre>from flask import Flask, jsonify, request<br><br>app = Flask(__name__)<br>@app.route(&#39;/hello&#39;, methods=[&#39;GET&#39;])<br>def hello():<br>    name = request.args.get(&#39;name&#39;, &#39;World&#39;)<br>    return jsonify({&quot;message&quot;: f&quot;Hello, {name}!&quot;})<br>if __name__ == &#39;__main__&#39;:<br>    app.run(debug=True)</pre><p>Run it:</p><pre>python app.py</pre><p>Test it:</p><pre>curl &quot;http://127.0.0.1:5000/hello?name=Venki&quot;<br># {&quot;message&quot;: &quot;Hello, Venki!&quot;}</pre><p>What just happened? @app.route(&#39;/hello&#39;, methods=[&#39;GET&#39;]) is a <strong>decorator</strong>. It registers the function hello as the handler for HTTP GET requests to the path /hello. When a request comes in, Flask&#39;s router matches the path, calls the function, and wraps the return value into an HTTP response.</p><h3>Flask: The Full CRUD Pattern</h3><p>Let’s build a complete in-memory user management API. This is the foundation of every REST API you’ll ever write.</p><pre>from flask import Flask, jsonify, request, abort<br><br>app = Flask(__name__)<br># In-memory &quot;database&quot; - a simple dict<br>users = {}<br>next_id = 1<br><br># GET /users - list all users<br>@app.route(&#39;/users&#39;, methods=[&#39;GET&#39;])<br>def list_users():<br>    return jsonify(list(users.values())), 200<br><br># GET /users/&lt;id&gt; - get a single user<br>@app.route(&#39;/users/&lt;int:user_id&gt;&#39;, methods=[&#39;GET&#39;])<br>def get_user(user_id):<br>    user = users.get(user_id)<br>    if user is None:<br>        abort(404)<br>    return jsonify(user), 200<br><br># POST /users - create a new user<br>@app.route(&#39;/users&#39;, methods=[&#39;POST&#39;])<br>def create_user():<br>    global next_id<br>    data = request.get_json()<br>    if not data or &#39;name&#39; not in data or &#39;email&#39; not in data:<br>        return jsonify({&quot;error&quot;: &quot;name and email are required&quot;}), 400<br>    user = {<br>        &quot;id&quot;: next_id,<br>        &quot;name&quot;: data[&#39;name&#39;],<br>        &quot;email&quot;: data[&#39;email&#39;]<br>    }<br>    users[next_id] = user<br>    next_id += 1<br>    return jsonify(user), 201<br><br># PUT /users/&lt;id&gt; - replace a user completely<br>@app.route(&#39;/users/&lt;int:user_id&gt;&#39;, methods=[&#39;PUT&#39;])<br>def update_user(user_id):<br>    if user_id not in users:<br>        abort(404)<br>    data = request.get_json()<br>    if not data or &#39;name&#39; not in data or &#39;email&#39; not in data:<br>        return jsonify({&quot;error&quot;: &quot;name and email are required&quot;}), 400<br>    users[user_id] = {&quot;id&quot;: user_id, &quot;name&quot;: data[&#39;name&#39;], &quot;email&quot;: data[&#39;email&#39;]}<br>    return jsonify(users[user_id]), 200<br><br># PATCH /users/&lt;id&gt; - update specific fields<br>@app.route(&#39;/users/&lt;int:user_id&gt;&#39;, methods=[&#39;PATCH&#39;])<br>def patch_user(user_id):<br>    if user_id not in users:<br>        abort(404)<br>    data = request.get_json()<br>    user = users[user_id]<br>    # Only update fields that were provided<br>    user[&#39;name&#39;] = data.get(&#39;name&#39;, user[&#39;name&#39;])<br>    user[&#39;email&#39;] = data.get(&#39;email&#39;, user[&#39;email&#39;])<br>    return jsonify(user), 200<br><br># DELETE /users/&lt;id&gt; - remove a user<br>@app.route(&#39;/users/&lt;int:user_id&gt;&#39;, methods=[&#39;DELETE&#39;])<br>def delete_user(user_id):<br>    if user_id not in users:<br>        abort(404)<br>    del users[user_id]<br>    return &#39;&#39;, 204<br><br>if __name__ == &#39;__main__&#39;:<br>    app.run(debug=True)</pre><p>Test with curl:</p><pre># Create<br>curl -X POST http://127.0.0.1:5000/users \<br>  -H &quot;Content-Type: application/json&quot; \<br>  -d &#39;{&quot;name&quot;: &quot;Venki&quot;, &quot;email&quot;: &quot;v@example.com&quot;}&#39;<br># Read<br>curl http://127.0.0.1:5000/users/1<br># Update<br>curl -X PATCH http://127.0.0.1:5000/users/1 \<br>  -H &quot;Content-Type: application/json&quot; \<br>  -d &#39;{&quot;name&quot;: &quot;Venkatesh&quot;}&#39;<br># Delete<br>curl -X DELETE http://127.0.0.1:5000/users/1</pre><h3>Flask: Request Object Deep Dive</h3><p>request is Flask&#39;s global object representing the current HTTP request. It&#39;s thread-safe via context locals — each request gets its own isolated instance.</p><pre>from flask import request<br><br>@app.route(&#39;/demo&#39;, methods=[&#39;POST&#39;])<br>def demo():<br>    # Query string: /demo?page=2&amp;limit=10<br>    page = request.args.get(&#39;page&#39;, 1, type=int)<br>    limit = request.args.get(&#39;limit&#39;, 10, type=int)<br>    # JSON body<br>    body = request.get_json()           # Returns dict or None<br>    body = request.get_json(silent=True) # Returns None instead of raising on bad JSON<br>    # Form data (application/x-www-form-urlencoded)<br>    username = request.form.get(&#39;username&#39;)<br>    # Raw body bytes<br>    raw = request.data<br>    # Headers<br>    auth_header = request.headers.get(&#39;Authorization&#39;)<br>    content_type = request.content_type<br>    # HTTP method<br>    method = request.method  # &#39;GET&#39;, &#39;POST&#39;, etc.<br>    # Full URL info<br>    full_url = request.url           # http://127.0.0.1:5000/demo?page=2<br>    base_url = request.base_url      # http://127.0.0.1:5000/demo<br>    host = request.host              # 127.0.0.1:5000<br>    path = request.path              # /demo<br>    # Client IP<br>    client_ip = request.remote_addr<br>    return jsonify({&quot;page&quot;: page, &quot;method&quot;: method})</pre><h3>Flask: Error Handling Done Right</h3><p>Flask lets you register global error handlers. Use them to return consistent error responses instead of letting exceptions bubble up as ugly 500 HTML pages.</p><pre>from flask import Flask, jsonify<br>from werkzeug.exceptions import HTTPException<br><br>app = Flask(__name__)<br><br>@app.errorhandler(400)<br>def bad_request(e):<br>    return jsonify({&quot;error&quot;: &quot;Bad Request&quot;, &quot;message&quot;: str(e.description)}), 400<br><br>@app.errorhandler(404)<br>def not_found(e):<br>    return jsonify({&quot;error&quot;: &quot;Not Found&quot;, &quot;message&quot;: str(e.description)}), 404<br><br>@app.errorhandler(405)<br>def method_not_allowed(e):<br>    return jsonify({&quot;error&quot;: &quot;Method Not Allowed&quot;}), 405<br><br>@app.errorhandler(500)<br>def internal_error(e):<br>    return jsonify({&quot;error&quot;: &quot;Internal Server Error&quot;}), 500<br><br># Catch-all for any other HTTP exception<br>@app.errorhandler(HTTPException)<br>def handle_http_exception(e):<br>    return jsonify({<br>        &quot;error&quot;: e.name,<br>        &quot;message&quot;: e.description,<br>        &quot;status_code&quot;: e.code<br>    }), e.code</pre><p>Now your API always returns JSON errors, never HTML. Your clients will thank you.</p><h3>Flask Blueprints: Structuring a Real Application</h3><p>When your API grows beyond a handful of routes, a single app.py becomes unmanageable. Flask&#39;s <strong>Blueprint</strong> system lets you split routes into separate modules.</p><pre>project/<br>├── app.py<br>├── routes/<br>│   ├── __init__.py<br>│   ├── users.py<br>│   └── products.py</pre><p>routes/users.py:</p><pre>from flask import Blueprint, jsonify<br><br>users_bp = Blueprint(&#39;users&#39;, __name__, url_prefix=&#39;/users&#39;)<br>@users_bp.route(&#39;/&#39;, methods=[&#39;GET&#39;])<br>def list_users():<br>    return jsonify({&quot;users&quot;: []})<br>@users_bp.route(&#39;/&lt;int:user_id&gt;&#39;, methods=[&#39;GET&#39;])<br>def get_user(user_id):<br>    return jsonify({&quot;id&quot;: user_id})</pre><p>app.py:</p><pre>from flask import Flask<br>from routes.users import users_bp<br>from routes.products import products_bp<br><br>app = Flask(__name__)<br>app.register_blueprint(users_bp)<br>app.register_blueprint(products_bp)<br>if __name__ == &#39;__main__&#39;:<br>    app.run(debug=True)</pre><p>Blueprints let you keep each resource’s routes, logic, and error handling together. This is how you scale a Flask project without descending into chaos.</p><h3>Authentication: Protecting Your Endpoints</h3><p>Any API exposed to the internet needs authentication. Here’s a simple API key implementation:</p><pre>from flask import Flask, jsonify, request<br>from functools import wraps<br><br>app = Flask(__name__)<br># In production, store these in a database, not a dict<br>VALID_API_KEYS = {<br>    &quot;key_abc123&quot;: &quot;user_1&quot;,<br>    &quot;key_xyz789&quot;: &quot;user_2&quot;,<br>}<br><br>def require_api_key(f):<br>    @wraps(f)<br>    def decorated(*args, **kwargs):<br>        api_key = request.headers.get(&#39;X-API-Key&#39;)<br>        if not api_key or api_key not in VALID_API_KEYS:<br>            return jsonify({&quot;error&quot;: &quot;Unauthorized&quot;}), 401<br>        # Attach user info to the request context<br>        request.current_user = VALID_API_KEYS[api_key]<br>        return f(*args, **kwargs)<br>    return decorated<br><br>@app.route(&#39;/protected&#39;, methods=[&#39;GET&#39;])<br>@require_api_key<br>def protected_route():<br>    return jsonify({<br>        &quot;message&quot;: f&quot;Hello, {request.current_user}!&quot;,<br>        &quot;data&quot;: &quot;This is private data.&quot;<br>    })</pre><p>Test it:</p><pre># No key — 401<br>curl http://127.0.0.1:5000/protected<br><br># Wrong key - 401<br>curl -H &quot;X-API-Key: wrong&quot; http://127.0.0.1:5000/protected<br># Valid key - 200<br>curl -H &quot;X-API-Key: key_abc123&quot; http://127.0.0.1:5000/protected</pre><h3>Rate Limiting: Protecting Your API From Abuse</h3><p>Without rate limiting, a single misbehaving client can overwhelm your server. The flask-limiter library handles this cleanly.</p><pre>pip install flask-limiter<br><br>from flask import Flask, jsonify<br>from flask_limiter import Limiter<br>from flask_limiter.util import get_remote_address<br><br>app = Flask(__name__)<br>limiter = Limiter(<br>    app=app,<br>    key_func=get_remote_address,  # Rate limit per client IP<br>    default_limits=[&quot;100 per hour&quot;, &quot;10 per minute&quot;]<br>)<br><br>@app.route(&#39;/public&#39;, methods=[&#39;GET&#39;])<br>def public_route():<br>    return jsonify({&quot;data&quot;: &quot;Anyone can call this, up to the default limits&quot;})<br><br>@app.route(&#39;/expensive&#39;, methods=[&#39;GET&#39;])<br>@limiter.limit(&quot;5 per minute&quot;)  # Stricter limit for resource-heavy endpoints<br>def expensive_route():<br>    # Imagine this calls an LLM or does heavy computation<br>    return jsonify({&quot;result&quot;: &quot;expensive computation&quot;})</pre><p>When a client exceeds the limit, they receive a 429 status code automatically.</p><h3>Consuming APIs with Python’s requests Library</h3><p>Building APIs is only half the picture. Here’s how to consume them properly.</p><h3>Basic Usage</h3><pre>import requests<br><br>response = requests.get(<br>    &#39;https://api.github.com/users/torvalds&#39;,<br>    headers={&#39;Accept&#39;: &#39;application/vnd.github.v3+json&#39;}<br>)<br>print(response.status_code)   # 200<br>print(response.headers)       # Response headers dict<br>data = response.json()        # Parsed JSON body<br>print(data[&#39;public_repos&#39;])   # Number of public repos</pre><h3>Handling Errors Properly</h3><pre>import requests<br>from requests.exceptions import RequestException, Timeout, ConnectionError<br><br>def fetch_user(user_id: int) -&gt; dict | None:<br>    try:<br>        response = requests.get(<br>            f&#39;https://api.example.com/users/{user_id}&#39;,<br>            headers={&#39;Authorization&#39;: &#39;Bearer your_token&#39;},<br>            timeout=5  # Always set a timeout<br>        )<br>        response.raise_for_status()  # Raises HTTPError for 4xx and 5xx<br>        return response.json()<br>    except Timeout:<br>        print(&quot;Request timed out&quot;)<br>        return None<br>    except ConnectionError:<br>        print(&quot;Could not connect to the server&quot;)<br>        return None<br>    except requests.HTTPError as e:<br>        print(f&quot;HTTP error: {e.response.status_code} - {e.response.text}&quot;)<br>        return None<br>    except RequestException as e:<br>        print(f&quot;Request failed: {e}&quot;)<br>        return None</pre><h3>Using a Session for Repeated Calls</h3><p>Every requests.get() call opens and closes a new TCP connection. If you&#39;re making many calls to the same API, use a <strong>Session</strong> to reuse the connection:</p><pre>import requests<br><br>session = requests.Session()<br>session.headers.update({<br>    &#39;Authorization&#39;: &#39;Bearer your_token&#39;,<br>    &#39;Accept&#39;: &#39;application/json&#39;<br>})<br># These reuse the same underlying TCP connection (keep-alive)<br>r1 = session.get(&#39;https://api.example.com/users/1&#39;)<br>r2 = session.get(&#39;https://api.example.com/users/2&#39;)<br>r3 = session.get(&#39;https://api.example.com/products/5&#39;)<br>session.close()</pre><p>This can reduce latency significantly when making dozens of API calls.</p><h3>Hosting Your API Locally — And What Actually Happens</h3><p>Flask’s built-in dev server (app.run()) is not production-grade. It handles one request at a time. It&#39;s purely for development. Here&#39;s what it does internally when you call it:</p><ol><li><strong>Creates a TCP socket</strong> — socket.socket(socket.AF_INET, socket.SOCK_STREAM)</li><li><strong>Binds to address</strong> — socket.bind((&#39;0.0.0.0&#39;, 5000)) 0.0.0.0 means &quot;all network interfaces&quot; — your localhost AND your LAN IP 127.0.0.1 would mean &quot;localhost only&quot;</li><li><strong>Starts listening</strong> — socket.listen(n) — OS queues incoming connections</li><li><strong>Accept loop</strong> — for each connection: conn, addr = socket.accept()</li><li><strong>Read the HTTP request</strong> from the socket</li><li><strong>Parse it</strong> — method, path, headers, body</li><li><strong>Route it</strong> — Flask matches path to your function</li><li><strong>Run your function</strong> — generates the response</li><li><strong>Write the response</strong> back to the socket</li><li><strong>Handle keep-alive or close</strong> the connection</li></ol><p>Flask’s dev server does all this synchronously, single-threaded. For production, you replace it with <strong>Gunicorn</strong> (for synchronous apps) or <strong>Uvicorn</strong> (for async apps), which run multiple workers.</p><h3>Running on Your Local Network</h3><pre>app.run(host=&#39;0.0.0.0&#39;, port=5000, debug=True)</pre><p>Find your machine’s local IP:</p><pre># Linux / macOS<br>ip addr show | grep &#39;inet &#39; | grep -v 127.0.0.1<br># Windows<br>ipconfig | findstr IPv4</pre><p>Let’s say it’s 192.168.1.100. Any device on your Wi-Fi can now hit:</p><pre>http://192.168.1.100:5000/users</pre><h3>Exposing to the Internet with ngrok</h3><pre>pip install ngrok<br>ngrok http 5000</pre><p>ngrok tunnels traffic from a public URL (https://abc123.ngrok.io) to your local port 5000. Useful for demos, webhooks, and testing.</p><h3>Common API Design Mistakes (And How to Avoid Them)</h3><p><strong>1. Using verbs in URLs</strong></p><pre># Wrong<br>GET /getUser?id=5<br>POST /createUser<br>DELETE /deleteUser?id=5</pre><pre># Right<br>GET /users/5<br>POST /users<br>DELETE /users/5</pre><p><strong>2. Not versioning your API</strong></p><p>If you ever need to make a breaking change, you’ll thank yourself for having /v1/ in your URLs from day one. Clients can stay on v1 while you build v2.</p><pre>GET /v1/users/5<br>GET /v2/users/5</pre><p><strong>3. Ignoring status codes</strong></p><p>Don’t return 200 OK with an error message in the body. Use the appropriate 4xx or 5xx code.</p><p><strong>4. No pagination on list endpoints</strong></p><pre># Bad — returns everything<br>@app.route(&#39;/users&#39;, methods=[&#39;GET&#39;])<br>def list_users():<br>    return jsonify(all_10_million_users)<br><br># Good - paginated<br>@app.route(&#39;/users&#39;, methods=[&#39;GET&#39;])<br>def list_users():<br>    page = request.args.get(&#39;page&#39;, 1, type=int)<br>    per_page = min(request.args.get(&#39;per_page&#39;, 20, type=int), 100)<br>    offset = (page - 1) * per_page<br>    paginated = list(users.values())[offset:offset + per_page]<br>    return jsonify({<br>        &quot;data&quot;: paginated,<br>        &quot;page&quot;: page,<br>        &quot;per_page&quot;: per_page,<br>        &quot;total&quot;: len(users)<br>    })</pre><p><strong>5. Not validating input</strong></p><p>Never trust client input. Always validate before processing:</p><pre>from flask import request, jsonify<br><br>@app.route(&#39;/users&#39;, methods=[&#39;POST&#39;])<br>def create_user():<br>    data = request.get_json(silent=True)<br>    if data is None:<br>        return jsonify({&quot;error&quot;: &quot;Request body must be valid JSON&quot;}), 400<br>    errors = {}<br>    if not data.get(&#39;name&#39;) or not isinstance(data[&#39;name&#39;], str):<br>        errors[&#39;name&#39;] = &quot;Required, must be a string&quot;<br>    if not data.get(&#39;email&#39;) or &#39;@&#39; not in str(data.get(&#39;email&#39;, &#39;&#39;)):<br>        errors[&#39;email&#39;] = &quot;Required, must be a valid email&quot;<br>    if errors:<br>        return jsonify({&quot;error&quot;: &quot;Validation failed&quot;, &quot;details&quot;: errors}), 422<br>    # Safe to proceed<br>    ...</pre><p><strong>6. Exposing internal details in error messages</strong></p><pre># Bad — exposes your database schema and internal paths<br>{&quot;error&quot;: &quot;psycopg2.errors.UniqueViolation: duplicate key value violates unique constraint \&quot;users_email_key\&quot; DETAIL: Key (email)=(v@example.com) already exists.&quot;}<br><br># Good<br>{&quot;error&quot;: &quot;Conflict&quot;, &quot;message&quot;: &quot;An account with this email already exists&quot;}</pre><h3>Where to Go From Here</h3><p>You now understand APIs at the level most developers never reach. The next steps:</p><p><strong>Deepen your Flask knowledge</strong>: Add SQLAlchemy for a real database, Flask-Migrate for schema migrations, and marshmallow or Pydantic for request/response serialization.</p><p><strong>Learn FastAPI</strong>: If you want async support, automatic OpenAPI docs, and Pydantic validation built in, FastAPI is the modern Python alternative. It builds on the same ASGI/WSGI concepts.</p><p><strong>Understand authentication properly</strong>: Study OAuth 2.0 and JWT (JSON Web Tokens). These are how real-world authentication flows work.</p><p><strong>Build something</strong>: The only way to really learn API design is to build one, use it, find its rough edges, and fix them. Start with a small project you actually care about.</p><p><strong>Read the HTTP spec</strong>: RFC 7230–7235. Not the whole thing, but skim it. Knowing what the protocol actually specifies versus what frameworks paper over gives you a durable mental model.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3253b8330d8b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Retrieval-Augmented Generation: A Complete Guide from Foundations to Production]]></title>
            <link>https://medium.com/@vengiboopathi/retrieval-augmented-generation-a-complete-guide-from-foundations-to-production-53cc7cc91d90?source=rss-d9be6945e434------2</link>
            <guid isPermaLink="false">https://medium.com/p/53cc7cc91d90</guid>
            <category><![CDATA[in-depth]]></category>
            <category><![CDATA[rags]]></category>
            <dc:creator><![CDATA[Vengadesa Boopathi]]></dc:creator>
            <pubDate>Tue, 24 Mar 2026 07:07:32 GMT</pubDate>
            <atom:updated>2026-03-24T07:07:32.871Z</atom:updated>
            <content:encoded><![CDATA[<h3>Load → Chunk → Embed → Index → Store → Retrieve → Rank → Augment → Generate → Evaluate</h3><p><em>Stack: LangChain + ChromaDB + Google Gemini</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*dbV7aeoP_NifcO7F.png" /><figcaption>Source Image :<a href="https://ashutoshtripathi.com/wp-content/uploads/2023/12/rag.png?w=2048">https://ashutoshtripathi.com/wp-content/uploads/2023/12/rag.png?w=2048</a></figcaption></figure><h3>Part 0: What is RAG and Why Should You Care?</h3><h3>The Core Idea</h3><p>Retrieval-Augmented Generation is an AI architecture/Technique that enhances LLMs by connecting them to external knowledge base at inference time. Instead of relying on knowledge baked into model weights during training, RAG allows the model to <em>look things up</em> before generating a response.</p><p>The term was introduced in a 2020 paper by Lewis et al. from Facebook AI Research — <em>“Retrieval-Augmented Generation for Knowledge-Intensive NLP Tasks”</em> (arXiv:2005.11401). The idea: combine a parametric memory (the LLM) with a non-parametric memory (a retrieval system backed by Wikipedia). In practice: <strong>RAG = Retrieve relevant documents + Augment the prompt + Generate a grounded answer.</strong></p><h3>The Problems RAG Actually Solves</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/757/1*rRJjStaKnosgf-pjhs1Tyw.png" /></figure><h3>The Full Pipeline</h3><p>A RAG system has two phases: <strong>Indexing</strong> (offline) and <strong>Retrieval &amp; Generation</strong> (online).</p><p><strong>Indexing phase:</strong></p><ol><li><strong>Load</strong> — Ingest raw data from PDFs, databases, websites, APIs</li><li><strong>Chunk</strong> — Split documents into smaller, semantically coherent pieces</li><li><strong>Embed</strong> — Convert each chunk into a numerical vector</li><li><strong>Index</strong> — Build an efficient search index over the vectors</li><li><strong>Store</strong> — Persist vectors, metadata, and text in a vector database</li></ol><p><strong>Retrieval &amp; Generation phase:</strong></p><p>6. User asks a question</p><p>7. Embed the query with the same model used at index time</p><p>8. Retrieve the top-k most similar chunks via similarity search</p><p>9. Optionally re-rank retrieved chunks</p><p>10. Augment — combine chunks with the user query into a structured prompt</p><p>11. Generate — send the augmented prompt to the LLM and return the answer</p><h3>RAG vs Fine-Tuning vs Prompt Engineering</h3><p>These three techniques are often confused because they overlap at the edges. They solve fundamentally different problems.</p><p><strong>Prompt engineering</strong> works by including all context directly in the prompt. No retrieval, no training. Works for small and static knowledge; breaks down when context gets large or changes frequently.</p><p><strong>Fine-tuning</strong> updates the model’s weights on new data. Best for teaching the model <em>how</em> to respond — tone, format, domain vocabulary — not <em>what</em> to say. It still hallucinates on facts it wasn’t explicitly trained on, and it’s expensive.</p><p><strong>RAG</strong> handles <em>what to say</em> — grounding responses in specific, current, and private data. Knowledge updates require only re-indexing documents, not retraining. In practice, the best production systems combine all three: fine-tune for tone and format, use RAG for dynamic knowledge, and craft careful prompts to control behavior.</p><h3>Types of RAG</h3><p><strong>Naive RAG:</strong> Index documents, retrieve top-k chunks, stuff them into a prompt. Simple and effective for basic use cases.</p><p><strong>Advanced RAG:</strong> Adds pre-retrieval optimizations (query rewriting, HyDE, multi-query expansion) and post-retrieval steps (re-ranking, contextual compression). Significantly improves quality without redesigning the architecture.</p><p><strong>Modular RAG:</strong> Each component is an independent module that can be swapped or tuned. LangChain and LlamaIndex both implement this philosophy.</p><p><strong>Agentic RAG:</strong> The LLM decides <em>when</em> to retrieve, <em>what</em> to retrieve, and whether to accept the results. Built with LangGraph or similar frameworks. Best for multi-hop reasoning across complex questions.</p><h3>Part 1: Load — Getting Data into the Pipeline</h3><h3>Why Loading Matters More Than You Think</h3><p>Loading is the entry point of the RAG pipeline. Without proper loading, the pipeline sees garbage: binary PDF bytes, raw HTML tags, unstructured database rows. The load step ensures only clean, structured text reaches the chunker. It also captures critical metadata — source file, page number, timestamp — that enables filtering and attribution downstream.</p><p>In LangChain, document loaders return a list of Document objects, each with page_content (the text) and metadata (source path, page number, etc.).</p><pre>from langchain_community.document_loaders import DirectoryLoader, PyPDFLoader<br><br>def file_loader():<br>    loader = DirectoryLoader(<br>        &#39;C:\\...\\knowledge-base&#39;,<br>        glob=&#39;**/*.pdf&#39;,<br>        loader_cls=PyPDFLoader,<br>        show_progress=True<br>    )<br>    return loader.load()</pre><h3>What You Can Load</h3><p>LangChain supports virtually every source type: PDFs (PyPDFLoader, PDFPlumberLoader), Word docs, HTML, Markdown, CSVs, JSON, emails, SQL databases, Confluence, Notion, GitHub, Slack, YouTube transcripts, and arbitrary web pages.</p><p>For production with mixed document types, the unstructured library is the most robust option. It handles scanned PDFs via OCR, preserves document structure, and returns elements like Title, NarrativeText, Table, and ListItem — which is valuable for structure-aware chunking.</p><pre>from langchain_community.document_loaders import UnstructuredFileLoader<br><br>loader = UnstructuredFileLoader(<br>    &#39;document.pdf&#39;,<br>    mode=&#39;elements&#39;,    # preserves document structure<br>    strategy=&#39;hi_res&#39;   # uses layout detection model<br>)<br>elements = loader.load()</pre><h3>Incremental Loading</h3><p>Re-indexing the entire knowledge base on every update is wasteful. Timestamp-based or hash-based change detection ensures you only process what’s new.</p><pre>import hashlib<br><br>def file_hash(path):<br>    with open(path, &#39;rb&#39;) as f:<br>        return hashlib.md5(f.read()).hexdigest()<br>def has_changed(path, hash_store):<br>    current_hash = file_hash(path)<br>    if current_hash != hash_store.get(path):<br>        hash_store[path] = current_hash<br>        return True<br>    return False</pre><h3>Metadata Enrichment and Data Cleaning</h3><p>Metadata is data <em>about</em> the data. It travels alongside every chunk through the entire pipeline and is essential for source attribution, metadata filtering, and debugging. Always enrich your documents with ingestion timestamps, document type, department tags, and unique IDs.</p><p>Raw text from PDFs and web pages also needs cleaning before it reaches the chunker — remove page headers, footers, page numbers, excessive whitespace, and null bytes. Poor input quality is one of the leading causes of poor RAG performance.</p><h3>Part 2: Chunk — Splitting Documents for Retrieval</h3><h3>The Core Problem</h3><p>Embedding a 50-page PDF as a single vector is meaningless. Most embedding models have input limits (512 tokens for BERT-based models, 8191 for OpenAI’s latest). Even if the limit weren’t there, a single vector for a 100-page document averages out all topics, making it useless for similarity search.</p><p>Each chunk should be a self-contained unit of meaning — enough context to answer a question, small enough to be retrieved precisely.</p><h3>Recursive Character Text Splitting (The Practical Default)</h3><p>This is the most popular general-purpose strategy. It tries a hierarchy of separators in order — paragraph breaks, then line breaks, then sentence endings, then spaces — falling back to finer splits only when necessary.</p><pre>from langchain_text_splitters import RecursiveCharacterTextSplitter<br><br>splitter = RecursiveCharacterTextSplitter(<br>    chunk_size=1000, #1000 characters<br>    chunk_overlap=200,<br>    separators=[&#39;\n\n&#39;, &#39;\n&#39;, &#39;. &#39;, &#39; &#39;, &#39;&#39;],<br>)<br>chunks = splitter.split_documents(documents)</pre><p>A 20% overlap (200 chars on 1000) is solid — it prevents answers from being split across chunk boundaries without bloating storage.</p><h3>Token-Based Splitting</h3><p>Character count and token count are not the same. For models with strict token limits, use TokenTextSplitter with the appropriate tokenizer.</p><pre>from langchain_text_splitters import TokenTextSplitter<br><br>splitter = TokenTextSplitter(<br>    chunk_size=512, #512 tokens == 512 * 4 chars = 2048 chars(approx)<br>    chunk_overlap=50,<br>    encoding_name=&#39;cl100k_base&#39;  # GPT-4 / text-embedding-3 tokenizer<br>)</pre><p>A rough rule of thumb: 1 token ≈ 4 characters in English. For Gemini, character-based splitting with chunk_size=2048 roughly maps to 512 tokens.</p><h3>Semantic Chunking</h3><p>Instead of structural heuristics, semantic chunking uses embedding similarity to find natural topic boundaries. It splits when meaning changes significantly between consecutive sentences.</p><pre>from langchain_experimental.text_splitter import SemanticChunker<br>from langchain_google_genai import GoogleGenerativeAIEmbeddings<br><br>embeddings = GoogleGenerativeAIEmbeddings(model=&#39;gemini-embedding-001&#39;)<br>splitter = SemanticChunker(<br>    embeddings,<br>    breakpoint_threshold_type=&#39;percentile&#39;,<br>    breakpoint_threshold_amount=95<br>)<br>chunks = splitter.split_documents(documents)</pre><p>Semantically coherent chunks produce better embeddings. The trade-off is speed — every sentence needs to be embedded during the chunking process.</p><h3>Hierarchical / Parent-Child Chunking</h3><p>This is one of the most powerful retrieval patterns: index small chunks for retrieval precision, but return larger parent chunks (with more context) to the LLM.</p><pre>from langchain.retrievers import ParentDocumentRetriever<br>from langchain_text_splitters import RecursiveCharacterTextSplitter<br>from langchain_community.storage import InMemoryStore<br><br>child_splitter = RecursiveCharacterTextSplitter(chunk_size=400)<br>parent_splitter = RecursiveCharacterTextSplitter(chunk_size=2000)<br>retriever = ParentDocumentRetriever(<br>    vectorstore=vectorstore,<br>    docstore=InMemoryStore(),<br>    child_splitter=child_splitter,<br>    parent_splitter=parent_splitter,<br>)<br>retriever.add_documents(documents)</pre><p>Child chunk vectors are stored in the vector database. At retrieval time, the system finds the right child chunk (precise match), then returns the full parent (rich context) to the LLM.</p><h3>Tuning Chunk Size</h3><p>There’s no universally optimal chunk size — it depends on your embedding model, your documents, and your query types. As a starting point:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/632/1*WQ_Sa4f-hNG8MvB09wZzfg.png" /></figure><p>To tune empirically: create 20–50 query-answer test pairs from your documents, run them across chunk sizes (500, 1000, 1500, 2000) with overlaps at 10% and 20%, and measure Hit Rate at k=3. Pick the config with the best Hit Rate.</p><h3>Part 3: Embed — Turning Text into Vectors</h3><h3>The Intuition</h3><p>Embedding converts text into a fixed-length numerical vector — the text’s semantic fingerprint. Imagine a high-dimensional map where documents about “machine learning” cluster together, documents about “cooking” cluster somewhere else, and documents about “finance” form their own group. When a user asks “how do I train a neural network?”, their query vector lands near the machine learning cluster, and similarity search retrieves the most relevant chunks from that region.</p><p>The key insight: <strong>similar meaning = close vectors</strong>, even when different words are used. “Car” and “automobile” will have very similar vectors in a well-trained model.</p><p>In code, this is where your embedding model comes in:</p><pre>from langchain_google_genai import GoogleGenerativeAIEmbeddings<br><br>def embedding_model():<br>    return GoogleGenerativeAIEmbeddings(<br>        model=&#39;gemini-embedding-001&#39;,<br>        google_api_key=os.getenv(&#39;GEMINI_API_KEY&#39;)<br>    )</pre><p>Always use the <strong>same</strong> embedding model for both indexing and querying. A vector from Model A is not comparable to a vector from Model B — they live in entirely different vector spaces.</p><h3>Dense Embeddings</h3><p>Dense embedding models are transformer-based networks trained via contrastive learning. Positive pairs (question + correct answer) are pulled together in vector space; negative pairs (question + irrelevant text) are pushed apart. The loss function used is typically InfoNCE or Multiple Negatives Ranking Loss.</p><p>The architecture: Input text → Tokenizer → Transformer encoder → Pooling (CLS token or mean pooling) → Dense vector.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5OISxTNQJCYH5lLRuvWKyg.png" /></figure><h3>Sparse Embeddings: TF-IDF and BM25</h3><p>Dense models are powerful for semantic matching, but they can miss exact keyword matches — product codes, names, acronyms. Sparse embeddings address this.</p><p><strong>TF-IDF</strong> assigns weights to terms based on two factors: how often a term appears <em>in this document</em> (Term Frequency), and how rare it is <em>across all documents</em> (Inverse Document Frequency). A term like “machine” appearing in 10 of 1,000 documents gets IDF = log(1000/10) = 4.6. The word “the” appearing in 950 documents gets IDF ≈ 0.05. <strong>The rare, meaningful term</strong> gets ~92x more weight — exactly right.</p><p><strong>BM25</strong> improves on TF-IDF with two critical innovations:</p><ul><li><strong>Saturation:</strong> Additional occurrences of a term beyond the first few contribute diminishing returns. A document mentioning “Python” 50 times isn’t 50× more relevant than one mentioning it 5 times.</li><li><strong>Length normalization:</strong> Long documents naturally contain more term occurrences. BM25 normalizes by document length to avoid unfairly favoring longer documents.</li></ul><pre>from langchain_community.retrievers import BM25Retriever<br>bm25_retriever = BM25Retriever.from_documents(chunks, k=5)<br>results = bm25_retriever.invoke(&#39;your query here&#39;)</pre><p>BM25 is the default ranking algorithm in Elasticsearch and Lucene. In RAG, it’s most valuable as part of a hybrid system.</p><h3>SPLADE and ColBERT</h3><p><strong>SPLADE</strong> (SParse Lexical AnD Expansion) is a neural method that produces learned sparse vectors. Unlike BM25, which only matches exact terms, SPLADE learns to <em>expand</em> — when encoding “car,” it also gives weight to “automobile,” “vehicle,” “sedan.” This combines the interpretability of sparse vectors with the semantic understanding of dense models.</p><p><strong>ColBERT</strong> takes a different approach entirely: instead of compressing a document into one vector, it stores a <em>matrix</em> of vectors — one per token. At retrieval time, for each query token, it finds the maximum similarity with any document token (MaxSim). This allows fine-grained alignment: “machine” in the query can find “learning” in the document even if they’re in different positions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Juo_eFrwvbg1D4yRFYOt7A.png" /></figure><h3>Fine-Tuning Embedding Models</h3><p>Pre-trained models are trained on general web text. For specialized domains — medical, legal, finance, code — fine-tuning on domain-specific data can significantly improve retrieval quality.</p><p>The common approach is to use <strong>MultipleNegativesRankingLoss</strong> with sentence-transformers: each query’s correct document is the positive, and all other documents in the batch are treated as negatives.</p><p>If you don’t have labeled query-document pairs (and you usually don’t), generate synthetic training data using your LLM — prompt it to generate 3–5 questions that each chunk would answer, then use those (question, chunk) pairs as your training data.</p><h3>Matryoshka Representation Learning (MRL)</h3><p>Named after Russian nesting dolls, MRL produces embeddings where the first <em>d</em> dimensions are already a valid, high-quality embedding for any <em>d</em> from 64 to the full size. OpenAI’s text-embedding-3 models use MRL — you can request 256-dim embeddings with only a modest accuracy loss compared to 1536 dims. This gives you a cost-accuracy dial that&#39;s genuinely useful in production.</p><h3>Part 4: Index — Making Search Fast at Scale</h3><h3>Why You Need an Index</h3><p>At 1 million chunks × 1024 dimensions × 4 bytes per float ≈ 4 GB of raw vectors. A linear scan at query time — comparing the query against every stored vector — would take seconds. A well-built index reduces this to milliseconds. Indexing is what makes vector search practical at scale.</p><h3>Indexing Algorithms</h3><p><strong>Flat Index (Exact Search):</strong> No indexing, brute-force comparison. 100% recall. Use only for datasets under ~100K vectors when exact recall is mandatory.</p><p><strong>IVF (Inverted File Index):</strong> Divides the vector space into clusters using K-means. At query time, only the vectors in the nearest nprobe clusters are searched. More clusters = faster search but potentially lower recall. nprobe is the key tuning parameter — increase it for higher recall at the cost of speed.</p><p><strong>HNSW (Hierarchical Navigable Small World):</strong> Graph-based index and the default in most modern vector databases (Chroma, Weaviate, Qdrant all use HNSW). Builds a multi-layer graph where each node connects to its nearest neighbors. Query traversal starts at the top (sparse) layer and drills down to the dense bottom layer.</p><p>Key HNSW parameters:</p><ul><li><strong>M:</strong> Connections per node. Higher = better recall, more memory. Typical: 16–64.</li><li><strong>ef_construction:</strong> Build quality. Higher = better graph, slower build.</li><li><strong>ef_search:</strong> Query beam width. Higher = better recall, slower query.</li></ul><p><strong>IVF-PQ:</strong> Combines IVF clustering with Product Quantization to compress vectors by 32–64×. Enables billion-scale search in RAM-constrained environments with ~5–15% recall loss.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/893/1*_zUuio6TWdG0AcqoGtlWbA.png" /></figure><p>ChromaDB — which powers the implementation in this guide — uses HNSW via hnswlib under the hood. You can configure HNSW parameters when creating a collection:</p><pre>import chromadb<br><br>client = chromadb.Client()<br>collection = client.create_collection(<br>    name=&#39;my_docs&#39;,<br>    metadata={<br>        &#39;hnsw:space&#39;: &#39;cosine&#39;,<br>        &#39;hnsw:construction_ef&#39;: 200,<br>        &#39;hnsw:search_ef&#39;: 128,<br>        &#39;hnsw:M&#39;: 32<br>    }<br>)</pre><h3>Part 5: Store — Vector Databases Explained</h3><h3>Relational vs Vector Databases</h3><p>A relational database stores data in rows and columns. Queries use exact match (WHERE id = 5) or range filters. The underlying structure is a B-tree optimized for equality lookups. A LIKE query finds only exact substrings — &quot;automobile&quot; does NOT match &quot;car.&quot;</p><p>A vector database stores embedding vectors and enables similarity search: “find the K vectors most similar to this query vector.” The underlying structure is an ANN index. The result is semantic matching: a query about “car purchase” finds documents about “automobile buying,” “vehicle acquisition,” and so on.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/690/1*WqcymNs1hiVx1I_Whl4dSA.png" /></figure><p><strong>pgvector</strong> gives you the best of both worlds — a PostgreSQL extension that adds vector similarity search while preserving full ACID compliance, SQL queries, JOINs, and transactions. This is increasingly the choice for teams that want to avoid managing a separate vector database.</p><h3>Choosing a Vector Database</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/719/1*K5WcFn-HLzRUgYwZbPcWWw.png" /></figure><h3>Advanced Storage Patterns</h3><p><strong>Metadata filtering</strong> can happen before or after vector search. Pre-filtering is faster when the filter is highly selective; post-filtering gives better recall when few vectors match the filter. Most vector databases support both modes.</p><p><strong>Embedding caching</strong> prevents redundant API calls during re-indexing runs:</p><pre>from langchain.storage import LocalFileStore<br>from langchain.embeddings import CacheBackedEmbeddings<br><br>underlying_embeddings = GoogleGenerativeAIEmbeddings(model=&#39;gemini-embedding-001&#39;)<br>fs = LocalFileStore(&#39;./embedding_cache&#39;)<br>cached_embedder = CacheBackedEmbeddings.from_bytes_store(<br>    underlying_embeddings,<br>    fs,<br>    namespace=underlying_embeddings.model<br>)</pre><p><strong>Multi-tenancy</strong> is handled by separate collections per tenant in ChromaDB, namespaces in Pinecone, or payload filters in Qdrant. Never mix tenant data in a single collection.</p><h3>Part 6: Retrieve — Finding the Right Chunks</h3><h3>Similarity Metrics</h3><p><strong>Cosine similarity</strong> measures the angle between vectors, ignoring magnitude. It’s magnitude-invariant: a long document and a short document covering the same topic get similar scores. This is why it’s the default for RAG.</p><p><strong>Dot product</strong> combines angle and magnitude — a longer, more detailed document covering a topic will score higher than a short snippet. Useful when document comprehensiveness matters.</p><p><strong>Euclidean distance</strong> measures the straight-line distance between points in vector space. Less common in RAG; cosine is preferred for text.</p><p>Set ChromaDB to use cosine similarity explicitly:</p><pre>collection = client.create_collection(<br>    name=&#39;my_docs&#39;,<br>    metadata={&#39;hnsw:space&#39;: &#39;cosine&#39;}<br>)</pre><h3>Hybrid Retrieval</h3><p>Dense retrieval catches semantic matches and synonyms but can miss exact rare terms. Sparse retrieval catches exact keyword matches but misses semantic meaning. <strong>Combining them almost always outperforms either alone.</strong></p><p>The standard method for combining ranked lists is <strong>Reciprocal Rank Fusion (RRF):</strong></p><pre>RRF_score(d) = SUM over each retriever: 1 / (k + rank(d))</pre><p>Where k=60 is a smoothing constant. Documents ranked highly by both retrievers get the highest combined scores.</p><p>In LangChain:</p><pre>from langchain.retrievers import EnsembleRetriever<br>from langchain_community.retrievers import BM25Retriever<br><br>dense_retriever = vector_store.as_retriever(search_kwargs={&#39;k&#39;: 10})<br>bm25_retriever = BM25Retriever.from_documents(chunks, k=10)<br>ensemble = EnsembleRetriever(<br>    retrievers=[dense_retriever, bm25_retriever],<br>    weights=[0.6, 0.4]<br>)</pre><h3>Query Transformation</h3><p>User queries are often ambiguous, too short, or poorly phrased for retrieval. Query transformation improves results without changing the index.</p><p><strong>Query rewriting</strong> uses the LLM to reformulate a vague query — “what about revenue?” becomes “What was the total annual revenue and growth rate in the most recent fiscal year?”</p><p><strong>HyDE (Hypothetical Document Embeddings)</strong> is one of the most impactful techniques. The insight: a question’s embedding is semantically different from its answer’s embedding. HyDE uses the LLM to generate a <em>hypothetical answer</em>, then embeds that instead of the query. The hypothetical answer’s vector is much closer to actual relevant documents in the vector space.</p><p><strong>Multi-Query Retrieval</strong> generates multiple rephrased versions of the query, retrieves for each, and deduplicates. More queries = broader coverage of the semantic space.</p><p><strong>MMR (Maximal Marginal Relevance)</strong> addresses retrieval redundancy — all top-k results saying the same thing. MMR balances relevance and diversity at each selection step, ensuring retrieved chunks cover different facets of the answer.</p><pre>retriever = vector_store.as_retriever(<br>    search_type=&#39;mmr&#39;,<br>    search_kwargs={<br>        &#39;k&#39;: 5,<br>        &#39;fetch_k&#39;: 20,<br>        &#39;lambda_mult&#39;: 0.5  # balance relevance vs diversity<br>    }<br>)</pre><h3>Contextual Compression and Self-Querying</h3><p><strong>Contextual compression</strong> uses the LLM to extract only the relevant portion of each retrieved chunk before passing to generation. Less noise in the context = better answers.</p><p><strong>Self-querying</strong> lets the LLM automatically generate both a semantic query and metadata filters from natural language. “Show me finance documents from 2024 about Q3 revenue” automatically becomes: semantic_search(&#39;Q3 revenue&#39;) + filter(department=&#39;finance&#39;, year=&#39;2024&#39;).</p><h3>Part 7: Ranking — Precision After Recall</h3><h3>Two-Stage Architecture</h3><p>Modern RAG systems separate recall from precision into two stages:</p><p><strong>Stage 1 (Recall):</strong> Fast ANN search or BM25. Retrieve a large candidate set — top-50 or top-100 chunks. Optimized for speed: you want to not miss any relevant documents. Uses bi-encoder models (embeddings computed independently).</p><p><strong>Stage 2 (Precision):</strong> A slower, more accurate model re-scores the candidates, reducing them to the final top-k passed to the LLM. Uses cross-encoder models (query and document processed <em>together</em> for fine-grained interaction scoring).</p><p>Cross-encoders are 10–100× slower than bi-encoders — but running them on 20–100 pre-filtered candidates is perfectly fast.</p><h3>Cross-Encoders</h3><p>A cross-encoder takes both query and document as a single concatenated input and outputs a relevance score. Unlike bi-encoders, cross-encoders can model fine-grained token-level interactions, which is why they’re significantly more accurate.</p><pre>from sentence_transformers import CrossEncoder<br><br>cross_encoder = CrossEncoder(&#39;cross-encoder/ms-marco-MiniLM-L-6-v2&#39;)<br>def rerank_with_cross_encoder(query, documents, top_k=5):<br>    pairs = [(query, doc.page_content) for doc in documents]<br>    scores = cross_encoder.predict(pairs)<br>    scored_docs = sorted(zip(scores, documents), key=lambda x: x[0], reverse=True)<br>    return [doc for score, doc in scored_docs[:top_k]]<br># Stage 1: retrieve 20 candidates<br>candidates = vector_store.as_retriever(search_kwargs={&#39;k&#39;: 20}).invoke(query)<br># Stage 2: re-rank, keep top 5<br>final_docs = rerank_with_cross_encoder(query, candidates, top_k=5)</pre><p>Top cross-encoder models: BAAI/bge-reranker-large (best open-source), mixedbread-ai/mxbai-rerank-large-v1, and Cohere&#39;s managed Rerank API.</p><h3>Ranking Evaluation Metrics</h3><p><strong>MRR (Mean Reciprocal Rank):</strong> Average of 1/rank of the first correct result. Rewards correct documents appearing higher in results.</p><p><strong>nDCG (Normalized Discounted Cumulative Gain):</strong> Accounts for graded relevance and position. A highly relevant result at rank 1 contributes more than the same result at rank 5.</p><p><strong>MAP (Mean Average Precision):</strong> Rewards systems that consistently retrieve relevant documents at the top across all queries.</p><h3>Part 8: Augment — Building the Prompt</h3><h3>Why Augmentation Is Underrated</h3><p>Retrieval quality determines <em>what information is available</em>. Augmentation quality determines <em>how well that information reaches the LLM</em>. A poorly constructed prompt can ruin excellent retrieval. A well-constructed one can compensate for mediocre retrieval.</p><p>The basic pattern (the “stuff” pattern) concatenates all retrieved chunks into a single {context} block:</p><pre>prompt = ChatPromptTemplate.from_template(&#39;&#39;&#39;<br>You are a helpful assistant. Use the context provided below to answer the question accurately.</pre><pre>If the answer is not found in the context, say &#39;I don&#39;t have enough information to answer that.&#39;</pre><pre>Context:<br>{context}</pre><pre>Question: {input}</pre><pre>Answer:&#39;&#39;&#39;)</pre><p>This is solid for most use cases. Here are the improvements that matter in production.</p><h3>Prompts That Actually Work</h3><p><strong>Citations prompt:</strong> Forces the model to cite sources for each fact, enabling traceability.</p><p><strong>Chain-of-thought prompt:</strong> Asks the model to reason step by step before giving a final answer. Particularly effective for complex or multi-part questions.</p><p><strong>Constrained system prompt:</strong> Be explicit — “Answer ONLY using information from the provided context. Do NOT use your general training knowledge to fill gaps.” The more explicit the constraint, the lower the hallucination rate.</p><h3>The Lost-in-the-Middle Problem</h3><p>Research shows LLMs are significantly better at using information at the beginning and end of the context, and significantly <em>worse</em> at using information in the middle. This is the “lost-in-the-middle” phenomenon.</p><p>The fix: reorder chunks so the most relevant appear first and last. Less relevant chunks go in the middle.</p><pre>from langchain.document_transformers import LongContextReorder<br><br>reorder = LongContextReorder()<br>reordered_docs = reorder.transform_documents(retrieved_docs)</pre><p>Also: using k=3 is often better than k=10 for this exact reason. Fewer, more relevant chunks lose less information to position bias.</p><h3>Part 9: Generate — From Chunks to Answers</h3><h3>LLM Selection for RAG</h3><p>The generation model has a bigger impact than people expect. Key considerations for RAG:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/702/1*RDwSm3pILZXvZ7_8XlmyEQ.png" /></figure><h3>Temperature Matters More in RAG Than You Think</h3><p>For factual RAG applications, use temperature=0.1 to 0.3. Higher temperature introduces creativity — which sounds good until your model starts embellishing retrieved facts with plausible-sounding inventions.</p><pre>factual_llm = ChatGoogleGenerativeAI(<br>    model=&#39;gemini-2.5-flash&#39;,<br>    temperature=0.1,<br>    max_output_tokens=1024<br>)</pre><h3>Multi-Turn Conversational RAG</h3><p>The basic pipeline is stateless — each query is independent. For a chat interface, you need conversation history so follow-up questions like “What about its revenue?” make sense in context.</p><p>LangChain’s create_history_aware_retriever reformulates each query as a standalone question (resolving references to previous messages) before retrieval. Combined with RunnableWithMessageHistory, this gives you full multi-turn conversation support with per-session state management.</p><h3>Hallucination Mitigation</h3><p>Even with RAG, LLMs can hallucinate by going beyond the provided context. Defense layers:</p><ol><li><strong>Explicit system prompt constraints</strong> — “Answer ONLY based on the provided context.”</li><li><strong>Low temperature</strong> — Reduces creative deviation from the source material.</li><li><strong>Post-generation verification</strong> — Prompt the LLM to verify each claim in its answer against the retrieved context.</li><li><strong>RAGAS faithfulness scoring</strong> — Automatically measure what fraction of the answer is supported by the context.</li></ol><h3>Part 10: Evaluate — You Can’t Improve What You Don’t Measure</h3><h3>Why Evaluation Is Non-Negotiable</h3><p>Without systematic evaluation, you’re flying blind. Change chunk_size from 1000 to 500 — did it help or hurt? Swap your embedding model — did retrieval improve? You need quantitative signals to guide every design decision.</p><h3>RAGAS: The Standard RAG Evaluation Framework</h3><p>RAGAS measures four core metrics using LLMs as judges:</p><p><strong>Answer Faithfulness:</strong> Does the generated answer contain only information from the retrieved context? Decompose the answer into atomic claims; check how many are supported by the context. Score: 0–1 (1 = perfectly faithful).</p><p><strong>Answer Relevancy:</strong> Does the answer actually address what was asked? Generate N question variations from the answer; measure how similar they are to the original question.</p><p><strong>Context Precision:</strong> Are the retrieved chunks actually relevant? Fraction of retrieved chunks that are useful for answering the question.</p><p><strong>Context Recall:</strong> Was all necessary information retrieved? Fraction of facts needed for the ground-truth answer that appear in the retrieved chunks.</p><pre>from ragas import evaluate<br>from ragas.metrics import faithfulness, answer_relevancy, context_precision, context_recall<br>from datasets import Dataset<br><br>eval_data = {<br>    &#39;question&#39;: [&#39;What is the refund policy?&#39;, &#39;What are the payment methods?&#39;],<br>    &#39;answer&#39;: [generated_answers[0], generated_answers[1]],<br>    &#39;contexts&#39;: [retrieved_docs_per_query[0], retrieved_docs_per_query[1]],<br>    &#39;ground_truth&#39;: [&#39;Refunds are processed within 7-10 business days.&#39;,<br>                     &#39;We accept Visa, MasterCard, and UPI.&#39;]<br>}<br>dataset = Dataset.from_dict(eval_data)<br>results = evaluate(<br>    dataset=dataset,<br>    metrics=[faithfulness, answer_relevancy, context_precision, context_recall],<br>)<br>print(results)<br># {&#39;faithfulness&#39;: 0.89, &#39;answer_relevancy&#39;: 0.92, &#39;context_precision&#39;: 0.85, &#39;context_recall&#39;: 0.78}</pre><h3>Building a Golden Dataset</h3><p>A golden dataset is your north star — a set of (question, ground_truth_answer) pairs that represents the queries your system will face. Have domain experts create 50–100 pairs manually, or use your LLM to generate synthetic data: for each chunk, prompt the LLM to generate 2–3 questions the chunk would answer, then use those pairs as training and evaluation data.</p><h3>Observability with LangSmith</h3><p>Three lines of code, and every LangChain call is automatically traced — inputs, retrieved docs, prompts, LLM outputs, latency, token counts, and errors:</p><pre>import os<br>os.environ[&#39;LANGCHAIN_TRACING_V2&#39;] = &#39;true&#39;<br>os.environ[&#39;LANGCHAIN_API_KEY&#39;] = &#39;your-langsmith-api-key&#39;<br>os.environ[&#39;LANGCHAIN_PROJECT&#39;] = &#39;rag-production&#39;</pre><h3>Part 11: Advanced RAG Patterns</h3><h3>Self-RAG</h3><p>Self-RAG trains the LLM to dynamically decide when to retrieve and how to evaluate retrieved content. It introduces special tokens — [Retrieve], [IsREL] (is relevant), [IsSUP] (is supported), [IsUSE] (is useful) — that the model learns to generate as part of its output. In practice, you can approximate this behavior using LangGraph tool-calling without a specially fine-tuned model.</p><h3>CRAG (Corrective RAG)</h3><p>CRAG addresses a key weakness: what if retrieved documents are irrelevant or incorrect? After retrieval, CRAG evaluates the relevance of each retrieved document. If all documents are irrelevant, it triggers a web search for better sources. If some are irrelevant, it uses only the relevant ones and supplements with web search. Knowledge refinement strips irrelevant content before passing to the LLM.</p><h3>GraphRAG (Microsoft)</h3><p>GraphRAG uses knowledge graphs to represent relationships between entities extracted from documents. Standard RAG retrieves isolated chunks; GraphRAG traverses entity relationships. The process: extract entities and relationships from all documents → build a knowledge graph → detect communities of related entities → generate community summaries → retrieve relevant communities plus raw chunks.</p><p>Best for questions that require connecting information across many documents: “How does X relate to Y in the context of Z?”</p><h3>Agentic RAG</h3><p>In Agentic RAG, the LLM is given a retrieval tool and decides autonomously when and what to retrieve. This enables multi-hop reasoning: retrieve, reason, retrieve again based on new sub-questions.</p><pre>from langchain.tools.retriever import create_retriever_tool<br>from langchain.agents import create_tool_calling_agent, AgentExecutor<br><br>retriever_tool = create_retriever_tool(<br>    retriever=vector_store.as_retriever(search_kwargs={&#39;k&#39;: 5}),<br>    name=&#39;search_knowledge_base&#39;,<br>    description=&#39;Search the company knowledge base for any factual questions.&#39;<br>)<br>agent = create_tool_calling_agent(llm=llm, tools=[retriever_tool], prompt=agent_prompt)<br>agent_executor = AgentExecutor(agent=agent, tools=[retriever_tool], verbose=True)</pre><h3>RAG Fusion</h3><p>RAG Fusion generates multiple search queries from a single user query, retrieves documents for each, and uses RRF to combine the results. Dramatically improves recall by exploring different phrasings of the same information need. A typical implementation generates 4 query variations, retrieves 5 documents per query, then fuses the 20 candidates using RRF.</p><h3>Adaptive RAG</h3><p>Adaptive RAG routes queries to different retrieval strategies based on complexity. Simple factual queries go directly to the vector store. Complex multi-hop questions trigger agentic retrieval. Out-of-scope questions are answered from the LLM’s parametric knowledge directly. The router is an LLM call that classifies the query as simple, complex, or no_retrieval_needed.</p><h3>Part 12: Production RAG</h3><h3>Architecture</h3><p>A production RAG system adds layers beyond the basic pipeline:</p><pre>API Gateway / Load Balancer<br>        ↓<br>RAG Application Servers (FastAPI — horizontal scaling)<br>        ↓<br>  ┌─────────┐   ┌─────────────┐   ┌─────────┐<br>  │ Vector  │   │ Cache       │   │ LLM API │<br>  │ DB      │   │ (Redis)     │   │ (Gemini)│<br>  └─────────┘   └─────────────┘   └─────────┘<br>        ↓<br>Indexing Pipeline (Airflow/Prefect scheduler)<br>        ↓<br>Data Sources (S3 / SharePoint / Database)<br>        ↓<br>Observability (LangSmith / Prometheus + Grafana)</pre><h3>Latency Optimization</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*A_oRyDAsDU78gQPmIejxhg.png" /></figure><h3>Security</h3><ul><li><strong>API Authentication:</strong> JWT or API keys on FastAPI endpoints</li><li><strong>Data Isolation:</strong> Separate vector store namespaces per user/tenant</li><li><strong>PII Redaction:</strong> Scrub personal data before indexing using presidio or spaCy NER</li><li><strong>Prompt Injection Prevention:</strong> Sanitize user inputs; never directly concatenate user input into system prompts</li><li><strong>Rate Limiting:</strong> Per-user limits to prevent abuse</li></ul><h3>Common Failure Modes</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iZWIRCnCtl7gC7RlErsJTA.png" /></figure><h3>CI/CD for RAG Pipelines</h3><p>Treat your RAG pipeline like software. Minimum checks before deploying a change:</p><ul><li>Faithfulness ≥ 0.85</li><li>Answer Relevancy ≥ 0.80</li><li>Context Recall ≥ 0.75</li><li>P95 latency ≤ 3 seconds</li></ul><p>Run RAGAS evaluation on your golden dataset in CI/CD on every pull request. If metrics drop more than 5%, block the merge and alert the team. On merge to main, trigger a re-indexing job to keep the knowledge base current.</p><h3>Putting It All Together</h3><p>Here’s a production-ready pipeline that combines the key improvements from this guide:</p><pre>def build_production_rag(knowledge_base_path=&#39;./knowledge-base&#39;):<br>    # 1. LOAD with error handling<br>    loader = DirectoryLoader(<br>        knowledge_base_path, glob=&#39;**/*.pdf&#39;,<br>        loader_cls=PyPDFLoader, show_progress=True<br>    )<br>    documents = loader.load()<br>    # 2. CHUNK<br>    splitter = RecursiveCharacterTextSplitter(chunk_size=1000, chunk_overlap=200)<br>    chunks = splitter.split_documents(documents)<br>    # 3. EMBED with caching<br>    underlying_embeddings = GoogleGenerativeAIEmbeddings(<br>        model=&#39;gemini-embedding-001&#39;,<br>        google_api_key=os.getenv(&#39;GEMINI_API_KEY&#39;)<br>    )<br>    cached_embeddings = CacheBackedEmbeddings.from_bytes_store(<br>        underlying_embeddings, LocalFileStore(&#39;./embedding_cache&#39;),<br>        namespace=&#39;gemini-embedding-001&#39;<br>    )<br>    # 4. STORE in ChromaDB<br>    vector_store = Chroma(<br>        client=chromadb.PersistentClient(path=&#39;./chroma_db&#39;),<br>        collection_name=&#39;documents&#39;,<br>        embedding_function=cached_embeddings,<br>    )<br>    vector_store.add_documents(chunks)<br>    # 5. HYBRID RETRIEVAL: Dense + BM25 with MMR<br>    dense_retriever = vector_store.as_retriever(<br>        search_type=&#39;mmr&#39;,<br>        search_kwargs={&#39;k&#39;: 10, &#39;fetch_k&#39;: 20, &#39;lambda_mult&#39;: 0.5}<br>    )<br>    bm25_retriever = BM25Retriever.from_documents(chunks, k=10)<br>    ensemble_retriever = EnsembleRetriever(<br>        retrievers=[dense_retriever, bm25_retriever],<br>        weights=[0.6, 0.4]<br>    )<br>    # 6. PROMPT<br>    prompt = ChatPromptTemplate.from_template(&#39;&#39;&#39;<br>You are a precise assistant. Answer ONLY from the context.<br>If not in context, say: I don&#39;t have that information.<br>Context: {context}<br>Question: {input}<br>Answer:&#39;&#39;&#39;)<br>    # 7. GENERATE with low temperature for factual accuracy<br>    llm = ChatGoogleGenerativeAI(<br>        model=&#39;gemini-2.5-flash&#39;,<br>        temperature=0.1,<br>        google_api_key=os.getenv(&#39;GEMINI_API_KEY&#39;)<br>    )<br>    document_chain = create_stuff_documents_chain(llm, prompt)<br>    return create_retrieval_chain(ensemble_retriever, document_chain)</pre><h3>Final Thoughts</h3><p>RAG is deceptively simple to prototype and genuinely difficult to do well. The basic pipeline — load, chunk, embed, retrieve, generate — takes an afternoon to implement. Building a system that reliably answers real user questions, stays faithful to its sources, handles edge cases gracefully, and degrades predictably under load — that’s engineering.</p><p>The pipeline you’ve seen in this guide isn’t a tutorial toy. With appropriate index sizing, query tuning, re-ranking, and evaluation, the same architecture runs at production scale. Every component is a dial you can turn. The key is knowing what each dial does and measuring the effect when you turn it.</p><p>Start with the naive implementation. Measure everything. Then improve exactly what the metrics tell you to improve.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=53cc7cc91d90" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Google ADK]]></title>
            <link>https://medium.com/@vengiboopathi/google-adk-8a56f57da9ca?source=rss-d9be6945e434------2</link>
            <guid isPermaLink="false">https://medium.com/p/8a56f57da9ca</guid>
            <category><![CDATA[agentic-ai]]></category>
            <category><![CDATA[google-adk]]></category>
            <dc:creator><![CDATA[Vengadesa Boopathi]]></dc:creator>
            <pubDate>Mon, 16 Mar 2026 06:18:26 GMT</pubDate>
            <atom:updated>2026-03-16T06:18:26.820Z</atom:updated>
            <content:encoded><![CDATA[<blockquote><strong>1. What is Google ADK?</strong></blockquote><blockquote><strong>Google ADK (Agent Development Kit)</strong> is an <strong>open-source, framework f</strong>or <strong>building, testing, and deploying AI agents.</strong></blockquote><ul><li>It provides a comprehensive set of <strong>libraries, tools, and conventions</strong> to create intelligent agents that can reason, use external tools, collaborate with other agents, and execute complex, multi-step tasks.</li><li>Model-agnostic: Works with Gemini, Anthropic, Meta, Mistral, and hundreds of other models via LiteLLM and Vertex AI Model Garden.</li><li>Supports both single and multi-agent systems: From simple chatbots to teams of specialized agents.</li></ul><p>Announced at Google Cloud Next ’25 in April 2025, with stable Python v1.0.0 release in May 2025. It powers Google’s own Agentspace product.</p><h4><strong>2. Why Do We Need Google ADK?</strong></h4><ul><li>Before ADK, developers often cobbled together solutions using general-purpose frameworks like <strong>LangChain</strong>, or built custom orchestration loops. Google ADK aims to standardize and simplify this process, providing a unified, production-ready toolkit.</li></ul><h4>3. How Google ADK Works: Architecture &amp; Workflow</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/958/0*bsS6LL2W2Tqs8NnS.png" /></figure><p><strong>WorkFlow of a Single Agent:</strong></p><pre>1. User Query: User sends a message to the agent via the Runner.<br>2. Session Initialization: Runner loads or creates a Session <br>(with history and state).<br>3. LLM Call: Runner sends the conversation (system prompt + history) <br>to the agent&#39;s LLM.<br>4. Action Decision: The LLM may respond with:<br>  - A final answer (text).<br>  - A request to call a tool (function call).<br>  - A request to delegate to a sub‑agent.<br>5. Tool Execution: If a tool is requested, Runner executes the <br>  corresponding function, passing arguments and ToolContext.<br>6. Loop: The result of the tool call is appended to the conversation; <br>  Runner goes back to step 3.<br>7. Final Answer: When the LLM provides a final answer, Runner returns <br>  it and updates the Session.</pre><p><strong>Multi-Agent WorkFlow</strong></p><pre>- Root Agent receives the user query.<br>- Based on its instructions, it may decide a sub‑agent is better suited.<br>- Root Agent calls the sub‑agent (via the Runner) with a specific request.<br>- Sub‑agent runs its own loop (LLM + tools) and returns a result.<br>- Root Agent incorporates the result and continues its loop, possibly <br>    calling other sub‑agents.<br>- Orchestrators like SequentialAgent automate this: they run each agent <br>    in order, automatically passing outputs.</pre><h4>3. Core Concepts</h4><h4><strong>3.1 Agent :</strong></h4><p>An autonomous entity that uses an LLM to decide which actions to take to achieve a goal. Defined by a name, instruction (system prompt), model, tools, and optional sub‑agents.</p><pre>weather_agent = Agent(<br>name=&quot;weather&quot;,<br>model=&quot;gemini-2.5-flash&quot;,<br>instruction=&quot;You provide weather info. Use the get_weather tool.&quot;,<br>tools=[get_weather] # assume get_weather exists<br>)</pre><h4>3.2. Tools and Integrations</h4><p><strong>Tool</strong> : A function or capability an agent can invoke. Can be pre‑built (e.g., google_search), custom (any Python function decorated with @tool), or connected via MCP.</p><p><strong>Creating Custom Tools</strong></p><pre>from google.adk.tools import tool<br>@tool<br>def get_weather(city: str) -&gt; str:<br>&quot;&quot;&quot;Get the current weather for a city.<br>Args:<br>city: The name of the city (e.g., &quot;New York&quot;).<br>Returns:<br>A string describing the weather.<br>&quot;&quot;&quot;<br># In reality, call a weather API<br>return f&quot;The weather in {city} is sunny, 22°C.&quot;</pre><ul><li>Python function decorated with @tool , The docstring becomes the tool description seen by the LLM.</li><li>Type hints are used for argument validation.</li></ul><p><strong>Pre‑built Tools</strong></p><pre>- google_search: Performs a live Google Search.<br>- code_interpreter: Executes Python code in a secure sandbox.<br>- arxiv: Searches arXiv for academic papers.<br>- calculator: Evaluates mathematical expressions.<br>- webpage_fetcher: Fetches and reads content from a URL.<br><br>Example:<br>from google.adk.tools.weather import WeatherTool<br><br># Create the prebuilt weather tool<br>weather_tool = WeatherTool()<br><br># Create an agent and attach the tool<br>agent = Agent(<br>    name=&quot;weather_agent&quot;,<br>    instruction=&quot;You are a helpful assistant that provides current weather information.&quot;,<br>    tools=[weather_tool],<br>)</pre><p><strong>MCP (Model Context Protocol) Tools</strong></p><p>Connect to any MCP server to give your agent live data.</p><pre>from google.adk.tools.mcp import MCPTool<br>mcp_tool = MCPTool(server_url=&quot;http://localhost:8000&quot;)<br>agent = Agent(…, tools=[mcp_tool])</pre><h4>3.3. Runner</h4><p>The Runner is the execution engine. Think of it as the conductor that takes your agent and a user query, and runs the agent loop until a final answer is produced.</p><p><strong>What the Runner Does</strong></p><ul><li>Takes a <strong>user query + session ID</strong></li><li><strong>Loads or creates a session</strong> to keep conversation context</li><li>Calls the agent’s <strong>LLM</strong> with system prompt, history, and state</li><li>Handles the LLM response:</li></ul><p><em>Returns a </em><strong><em>final answer</em></strong><em>, or</em></p><p><em>Executes a </em><strong><em>tool call</em></strong><em> and adds the result to context, or</em></p><p><em>Delegates to a </em><strong><em>sub‑agent</em></strong><em> and feeds the result back</em></p><ul><li>Repeats until a <strong>final answer</strong> is produced</li><li><strong>Updates the session</strong> and returns the result (optionally streaming events)</li></ul><p><strong>Runner in Code</strong></p><pre>from google.adk.runners import Runner<br>from google.adk.sessions import InMemorySessionService<br><br># Create a session service (stores sessions)<br>session_service = InMemorySessionService()<br># Create a runner with your agent and the session service<br>runner = Runner(<br>agent=my_agent,<br>session_service=session_service<br>)<br># Run a query<br>result = runner.run(<br>query=&quot;What&#39;s the weather in Paris?&quot;,<br>session_id=&quot;user-123&quot;<br>)<br>print(result.content)</pre><p>The Runner is stateless — it doesn’t store any data itself. All state is kept in the Session.</p><h4>3.4. Session</h4><p>The Session is the memory of a conversation. It holds everything that an agent needs to remember across multiple turns and between different agents in the same conversation.</p><p><strong>A Session object has three main parts:</strong></p><ul><li>id — A unique identifier for the session</li><li>history — A list of messages exchanged so far.</li><li>state — A Python dictionary (JSON‑serializable)</li></ul><p><strong>Why Session is Important</strong></p><ul><li>Continuity: Without a session, each turn would be isolated. The agent wouldn’t remember what was said earlier.</li><li>Sharing data between agents:</li><li>Persistence: Sessions can be saved to a database (e.g., Firestore) and reloaded later, allowing conversations to resume even after the server restarts.</li></ul><p><strong>Session in Code</strong></p><pre>from google.adk.sessions import Session<br># Creating a session manually<br>session = Session(<br>id=&quot;user-123&quot;,<br>user_id=&quot;user-123&quot;, # optional, for linking to a user<br>state={&quot;notes&quot;: []}, # initial state<br>history=[] # empty history<br>)<br># Accessing session data<br>print(session.state[&quot;notes&quot;])<br>session.state[&quot;last_query&quot;] = &quot;weather in Paris&quot;<br></pre><p><strong>Session Services</strong></p><p>You don’t usually create Session objects directly. Instead, you use a Session Service that manages sessions for you.</p><ul><li><strong>InMemorySessionService</strong> — Stores sessions in memory (good for testing, but lost when the program ends).</li><li><strong>FirestoreSessionService </strong>— Stores sessions in Google Cloud Firestore (persistent across restarts, suitable for production).</li></ul><p><strong>Accessing Session State in Tools</strong></p><p>Tools receive a ToolContext object that includes the session state.</p><pre>from google.adk.tools import tool, ToolContext<br>@tool<br>def save_note(content: str, context: ToolContext) -&gt; str:<br>&quot;&quot;&quot;Save a note in the session.&quot;&quot;&quot;<br>notes = context.state.get(&quot;notes&quot;, [])<br>notes.append(content)<br>context.state[&quot;notes&quot;] = notes<br>return &quot;Note saved.&quot;</pre><h4>3.5 Orchestration</h4><p>Orchestration is about controlling the flow of multiple agents. While a single agent can handle many tasks, sometimes you need a team of agents working together — each with its own expertise. Orchestration defines how they interact.</p><p><strong>Why Orchestration?</strong></p><ul><li><strong>Divide and conquer: </strong>Break a complex task into smaller, specialised sub‑tasks.</li><li><strong>Parallel processing: </strong>Run independent tasks simultaneously to speed up response.</li><li><strong>Pipeline: </strong>Process data through a sequence of agents (like an assembly line).</li></ul><p><strong>Orchestration Agents in ADK</strong></p><p><strong>a) SequentialAgent</strong></p><p>Runs a list of agents one after another. The output of the first becomes the input to the second, and so on.</p><pre>from google.adk.agents import SequentialAgent<br>pipeline = SequentialAgent(<br>name=&quot;pipeline&quot;,<br>agents=[planner_agent, executor_agent, summarizer_agent]<br>)<br># When you run pipeline, it will:<br># 1. Run planner_agent with the original query.<br># 2. Pass the output to executor_agent.<br># 3. Pass that output to summarizer_agent.<br># 4. Return the final output.</pre><p><strong>b) ParallelAgent</strong></p><p>Runs multiple agents concurrently and then combines their results.</p><pre>from google.adk.agents import ParallelAgent<br>parallel = ParallelAgent(<br>name=&quot;parallel_searches&quot;,<br>agents=[flight_agent, hotel_agent, car_rental_agent],<br>combiner=lambda outputs: &quot;\n\n&quot;.join(outputs) # how to merge results<br>)</pre><p>All three agents run at the same time. When all finish, their outputs are passed to the combiner function, which returns the final answer.</p><p><strong>c) LoopAgent</strong></p><p>Repeats a sub‑agent until a condition is met.</p><pre>from google.adk.agents import LoopAgent<br>refinement_loop = LoopAgent(<br>name=&quot;refiner&quot;,<br>agent=generator_agent,<br>max_iterations=5,<br>stop_condition=lambda output: &quot;FINAL&quot; in output<br>)</pre><p>The generator runs repeatedly; each time its output is fed back as input. The loop stops when the output contains the word “FINAL” or after 5 iterations.</p><p><strong>d) Hierarchical Delegation (Implicit Orchestration)</strong></p><p>Even without explicit orchestrators, a parent agent with sub_agents can delegate tasks. The parent’s LLM decides when to call a sub‑agent based on the sub‑agent’s description. This is a form of dynamic orchestration.</p><pre>math_agent = Agent(<br>name=&quot;math_expert&quot;,<br>instruction=&quot;Solve math problems.&quot;,<br>description=&quot;Useful for mathematical tasks.&quot;<br>)<br>root_agent = Agent(<br>name=&quot;root&quot;,<br>instruction=&quot;Delegate math tasks to math_expert.&quot;,<br>sub_agents=[math_agent]<br>)</pre><p>When you run root_agent, if the LLM determines the task is mathematical, it will output a special delegate action, and the Runner will invoke math_agent automatically.</p><p><strong>How Orchestration Relates to Runner and Session</strong></p><ul><li>The Runner executes every agent, whether it’s a simple agent or an orchestrator.</li><li>The Session is shared among all agents involved. So state written by one agent is visible to others.</li><li>Orchestrators themselves are just agents — they have instructions, and they use the Runner to invoke their sub‑agents.</li></ul><p>For example, when you run a SequentialAgent, its own run method (called by the Runner) will create a new Runner instance for each sub‑agent, passing the same session, so the sub‑agents see the accumulated context.</p><h4>4. Evaluation and Debugging</h4><p>Evaluation</p><p>1. Create test cases in YAML/JSON:</p><pre>- input: &quot;What is 2+2?&quot;<br>expected_output: &quot;4&quot;<br>- input: &quot;Search for AI news&quot;<br>expected_tool_calls:<br>- tool_name: google_search<br>arguments:<br>query: &quot;AI news&quot;<br>expected_output_contains: &quot;artificial intelligence&quot;</pre><p>2. Run evaluation:</p><pre>adk eval - agent my_agent.py - tests tests/test_cases.yaml</pre><p>3. Use in code:</p><pre>from google.adk.evaluation import Evaluator<br>evaluator = Evaluator(agent=my_agent, test_cases=test_cases)<br>results = evaluator.run()<br>print(results.summary())</pre><p><strong>Debugging</strong></p><ul><li>adk run my_agent.py: Interactive terminal session with detailed logs.</li><li>adk web my_agent.py: Launches a web UI at <a href="http://localhost:8000/">http://localhost:8000</a> for step‑by‑step debugging.</li></ul><h4>5. Deployment Options</h4><p><strong>Local / Embedded</strong></p><p>Embed the Runner in any Python application (e.g., Flask API).</p><pre>from flask import Flask, request<br>from google.adk.runners import Runner<br>from my_agent import root_agent<br>app = Flask(__name__)<br>runner = Runner(agent=root_agent)<br>@app.route(&quot;/chat&quot;, methods=[&quot;POST&quot;])<br>def chat():<br>data = request.json<br>result = runner.run(data[&quot;query&quot;], session_id=data[&quot;session_id&quot;])<br>return {&quot;response&quot;: result.content}</pre><p><strong>Containerized Deployment</strong></p><p>1. Create a Dockerfile:</p><pre>FROM python:3.10-slim<br>WORKDIR /app<br>COPY requirements.txt .<br>RUN pip install -r requirements.txt<br>COPY . .<br>CMD [&quot;python&quot;, &quot;app.py&quot;]</pre><p>2. Build and run the container, then deploy to any container platform (Cloud Run, Kubernetes, etc.).</p><p><strong>Vertex AI Agent Engine (Managed)</strong></p><p>Google Cloud’s fully managed service for agents. Provides auto‑scaling, monitoring, and security.</p><p>To deploy:</p><p>1. Package your agent with a main.py containing a create_agent() function:</p><pre># main.py<br>from google.adk.agents import Agent<br>def create_agent():<br>return Agent(name=&quot;my_agent&quot;, …)</pre><p>2. Use the gcloud CLI:</p><pre>gcloud alpha vertex ai agent-engine create \<br> - display-name=&quot;my-agent&quot; \<br> - agent-engine-config-file=config.yaml</pre><h4>6. Comparison with Other Frameworks</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eYqaSs0cPlvyfA4j3NXwSg.png" /></figure><p><strong>Key Differentiators of ADK:</strong></p><ul><li>Enterprise readiness: Built‑in evaluation, seamless Google Cloud deployment, enterprise connectors.</li><li>A2A support: Future‑proofing for multi‑framework agent ecosystems.</li></ul><h4><strong>7. Agent2Agent (A2A) Protocol</strong></h4><ul><li>Open standard for inter‑agent communication.</li><li>ADK agents can collaborate with agents from other frameworks (e.g., LangChain, AutoGen) if they implement A2A.</li></ul><pre>from google.adk.a2a import A2AClient<br>client = A2AClient(agent_url=&quot;http://other-agent:8000/a2a&quot;)<br>response = client.send_message(&quot;Hello&quot;, session_id=&quot;cross&quot;)</pre><h4>8. Libraries and Conventions Explained</h4><p><strong>Libraries (Modules)</strong></p><pre>Module What It Provides<br>google.adk.agents Base classes for agents: Agent, LlmAgent, SequentialAgent, ParallelAgent, LoopAgent.<br>google.adk.tools @tool decorator, pre‑built tools, ToolContext, MCP integration.<br>google.adk.runners Runner class for executing agents.<br>google.adk.sessions Session, InMemorySessionService, FirestoreSessionService, base classes.<br>google.adk.orchestration Higher‑level orchestration helpers (the orchestrator agents).<br>google.adk.evaluation Evaluator class and supporting functions.<br>google.adk.integrations Connectors for LiteLLM, Vertex AI, MCP.<br>google.adk.code_executor Sandboxed environment for code_interpreter.<br>google.adk.artifacts Support for handling files (e.g., images, PDFs) generated by agents.<br>google.adk.a2a Client and server support for the Agent2Agent protocol.</pre><p><strong>Conventions (Best Practices)</strong></p><ul><li>Agent definition: Each agent has name, instruction (system prompt), model, optional tools, optional sub_agents. Sub‑agents include a description for delegation decisions.</li><li>Tool documentation: Write clear docstrings with parameter descriptions; use type hints.</li><li>State management: Use session state to share data; tools should write results to state; orchestrators may pass outputs explicitly.</li></ul><h4>9. Starting a Project with Google ADK</h4><p><strong>Installation</strong></p><pre>python -m venv adk-env<br>source adk-env/bin/activate # Windows: adk-env\Scripts\activate<br>pip install google-adk</pre><p><strong>Project Structure (No Automatic Scaffolding) :</strong></p><pre>my-adk-project/<br>├── .venv/<br>├── agents/<br>│ ├── __init__.py<br>│ ├── customer_support.py<br>│ └── research_assistant.py<br>├── tools/<br>│ ├── __init__.py<br>│ ├── weather.py<br>│ └── database.py<br>├── tests/<br>│ ├── test_cases.yaml<br>├── config/<br>├── main.py<br>├── requirements.txt<br>└── README.md</pre><p>Complete Example Combining Components</p><pre># my_project/main.py<br>from google.adk.agents import Agent, SequentialAgent<br>from google.adk.tools import google_search, tool<br>from google.adk.runners import Runner<br>from google.adk.sessions import InMemorySessionService<br><br># 1. Custom tool<br>@tool<br>def get_time(city: str) -&gt; str:<br>&quot;&quot;&quot;Get the current time in a city.&quot;&quot;&quot;<br># In reality, call a time API<br>return f&quot;The current time in {city} is 12:00 PM.&quot;<br><br># 2. Sub‑agents<br>weather_agent = Agent(<br>name=&quot;weather&quot;,<br>model=&quot;gemini-2.5-flash&quot;,<br>instruction=&quot;You provide weather info. Use the get_weather tool.&quot;,<br>tools=[get_weather] # assume get_weather exists<br>)<br>time_agent = Agent(<br>name=&quot;time&quot;,<br>model=&quot;gemini-2.5-flash&quot;,<br>instruction=&quot;You provide time info. Use the get_time tool.&quot;,<br>tools=[get_time]<br>)<br># 3. Root agent with sub‑agents<br>root = Agent(<br>name=&quot;root&quot;,<br>model=&quot;gemini-2.5-flash&quot;,<br>instruction=&quot;Delegate weather questions to weather, time questions to time.&quot;,<br>sub_agents=[weather_agent, time_agent]<br>)<br># 4. Runner and session<br>session_service = InMemorySessionService()<br>runner = Runner(agent=root, session_service=session_service)<br># 5. Run<br>result = runner.run(&quot;What&#39;s the weather in Paris?&quot;, session_id=&quot;test&quot;)<br>print(result.content)</pre><p><strong>10. CLI Commands</strong></p><ul><li>adk run &lt;file&gt; — Interactive terminal.</li><li>adk web &lt;file&gt; — Web debugger.</li><li>adk eval — agent &lt;file&gt; — tests &lt;file&gt; — Run evaluation.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8a56f57da9ca" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[MODEL CONTEXT PROTOCOL]]></title>
            <link>https://medium.com/@vengiboopathi/model-context-protocol-0bab0bd7b8a3?source=rss-d9be6945e434------2</link>
            <guid isPermaLink="false">https://medium.com/p/0bab0bd7b8a3</guid>
            <dc:creator><![CDATA[Vengadesa Boopathi]]></dc:creator>
            <pubDate>Thu, 05 Mar 2026 05:25:15 GMT</pubDate>
            <atom:updated>2026-03-05T05:25:15.328Z</atom:updated>
            <content:encoded><![CDATA[<h4><strong>1. Why APIs Matter?</strong></h4><ul><li>API (Application Programming Interface): a set of rules that lets one piece of software talk to another.</li><li>Analogy: a waiter in a restaurant — you (the client) order, the waiter takes it to the kitchen (server), and brings back your food.</li><li>Without an API: you’d have to scrape websites or write custom code for every integration — fragile and time‑consuming.</li><li>With an API: you get a stable, documented interface (e.g., REST) that returns clean data (usually JSON).</li></ul><p>Example: GET <a href="https://api.weather.com/?city=London">https://api.weather.com?city=London</a> → {“temp”:22}.</p><p>Read more about Api in this article: <a href="https://medium.com/@vengiboopathi/application-programming-interface-4dfda97e7428">https://medium.com/@vengiboopathi/application-programming-interface-4dfda97e7428</a></p><h4><strong>2. The Problem Before MCP (How AI Agents Used Tools)</strong></h4><p>Before MCP, integrating tools with AI agents was messy and non‑standard:</p><p><strong>2.1 Hardcoded Integrations</strong></p><ul><li>Developer manually wrote if/elif blocks for each tool inside the agent code.</li><li>LLM was told about tools via a <strong>plain‑text system prompt.</strong></li><li>Adding a new tool meant editing code and prompt.</li></ul><p><strong>2.2 Plugin Architectures (e.g., LangChain)</strong></p><ul><li>Tools registered via decorators or config files; framework collected them.</li><li>Framework generated prompt and parsed LLM output.</li><li>Still framework‑specific; tools couldn’t be shared across different agent frameworks.</li></ul><p><strong>2.3 LLM‑Native Function Calling (OpenAI, etc.)</strong></p><ul><li>Developer provided a list of function definitions (name, description, parameters) to the LLM API.</li><li>LLM could return a structured function_call object.</li><li>Execution still required custom code to call actual functions; definitions were static.</li></ul><p>Common issues: no dynamic discovery, no standard way to package/share tools, each integration required custom glue code.</p><h4><strong>3. What is MCP?</strong></h4><p>MCP (Model Context Protocol) is an open protocol that standardizes how AI applications (clients) discover and use tools, data, and resources from external servers.</p><ul><li>Purpose: Make tool‑augmented AI interoperable, scalable, and plug‑and‑play.</li><li>Analogy: Like USB‑C for AI agents — any agent (client) can plug into any tool server that speaks MCP.</li><li>Not a general‑purpose API: Designed <strong>specifically for AI agents (LLM‑based applications) to interact with tools.</strong></li></ul><h4>4. MCP Components</h4><p>Component Description Example</p><p><strong>Client:</strong> The AI application (e.g., chatbot, agent framework) that wants to use tools. It connects to one or more servers. Claude Desktop, custom Python agent</p><p><strong>Server: </strong>A program that wraps one or more tools (functions) and exposes them via the MCP protocol. Weather server, calculator server</p><p><strong>Protocol: </strong>The set of rules for communication — uses <strong>JSON‑RPC 2.0 over transports like stdio (local) or HTTP/SSE (remote).</strong> Messages like tools/list, tools/call</p><h4><strong>5. How MCP Works — Step by Step</strong></h4><p><strong>5.1 Tool Discovery</strong></p><ul><li>Client sends a tools/list request to the server.</li><li>Server responds with a list of tools, each containing:</li></ul><pre>name — unique identifier<br>description - what the tool does (for the LLM)<br>inputSchema - JSON Schema describing expected arguments</pre><p>Example request:</p><pre>json<br>{&quot;jsonrpc&quot;:&quot;2.0&quot;, &quot;id&quot;:1, &quot;method&quot;:&quot;tools/list&quot;}</pre><p>Example response:</p><pre>json<br>{<br>&quot;jsonrpc&quot;:&quot;2.0&quot;, &quot;id&quot;:1,<br>&quot;result&quot;: {<br>&quot;tools&quot;: [<br>{<br>&quot;name&quot;: &quot;get_weather&quot;,<br>&quot;description&quot;: &quot;Get current weather for a city&quot;,<br>&quot;inputSchema&quot;: {<br>&quot;type&quot;: &quot;object&quot;,<br>&quot;properties&quot;: {&quot;city&quot;: {&quot;type&quot;: &quot;string&quot;}},<br>&quot;required&quot;: [&quot;city&quot;]<br>}}]}}</pre><p><strong>5.2 Informing the LLM</strong></p><ul><li>Client takes these tool descriptions and injects them into the LLM’s prompt (or uses native function‑calling APIs).</li><li>The LLM now knows what tools exist and how to call them.</li></ul><p><strong>5.3 LLM Decides to Call a Tool</strong></p><ul><li>The LLM outputs a structured response indicating which tool to use and with what arguments.</li><li>This could be a native function_call (OpenAI) or a custom JSON format.</li></ul><p>Example (OpenAI style):</p><pre>json{<br>&quot;function_call&quot;: {<br>&quot;name&quot;: &quot;get_weather&quot;,<br>&quot;arguments&quot;: &quot;{\&quot;city\&quot;: \&quot;London\&quot;}&quot;<br>}<br>}</pre><p><strong>5.4 Client(Agent) Translates and Sends tools/call</strong></p><ul><li>Client parses the LLM’s response, extracts the tool name and arguments.</li><li>Sends a tools/call request to the appropriate MCP server.</li></ul><pre>json<br>{<br>&quot;jsonrpc&quot;:&quot;2.0&quot;, &quot;id&quot;:2,<br>&quot;method&quot;:&quot;tools/call&quot;,<br>&quot;params&quot;: {<br>&quot;name&quot;: &quot;get_weather&quot;,<br>&quot;arguments&quot;: {&quot;city&quot;: &quot;London&quot;}<br>}<br>}</pre><p><strong>5.5 Server Executes the Tool</strong></p><ul><li>Server receives the request, looks up the function mapped to the tool name.</li><li>Calls that function with the provided arguments (e.g., queries a real weather API).</li><li>The function returns a result (e.g., “The temperature is 22°C”).</li></ul><p><strong>5.6 Server Returns the Result</strong></p><ul><li>Server wraps the result in a CallToolResult response (with content, possibly multiple types).</li></ul><pre>json<br>{<br>&quot;jsonrpc&quot;:&quot;2.0&quot;, &quot;id&quot;:2,<br>&quot;result&quot;: {<br>&quot;content&quot;: [<br>{&quot;type&quot;: &quot;text&quot;, &quot;text&quot;: &quot;The temperature in London is 22°C.&quot;}<br>]}}</pre><p><strong>5.7 Client Feeds Result Back to LLM</strong></p><ul><li>Client receives the result and sends it back to the LLM (e.g., as a function response).</li><li>LLM uses this information to generate the final answer to the user.</li></ul><h4><strong>6. Example MCP Server in Python (Using Official SDK)</strong></h4><pre>python<br>from mcp.server import Server, stdio_server<br>from mcp.types import TextContent, Tool, CallToolResult<br>app = Server(&quot;weather-server&quot;)<br># Actual tool implementation<br>def get_weather(city: str) -&gt; str:<br># Replace with real API call<br>return f&quot;The temperature in {city} is 22°C.&quot;<br># Register tool discovery<br>@app.list_tools()<br>async def list_tools():<br>return [<br>Tool(<br>name=&quot;get_weather&quot;,<br>description=&quot;Get current weather for a city&quot;,<br>inputSchema={<br>&quot;type&quot;: &quot;object&quot;,<br>&quot;properties&quot;: {&quot;city&quot;: {&quot;type&quot;: &quot;string&quot;}},<br>&quot;required&quot;: [&quot;city&quot;]<br>}<br>)<br>]<br># Register tool execution<br>@app.call_tool()<br>async def call_tool(name: str, arguments: dict) -&gt; CallToolResult:<br>if name == &quot;get_weather&quot;:<br>city = arguments[&quot;city&quot;]<br>result_text = get_weather(city)<br>return CallToolResult(<br>content=[TextContent(type=&quot;text&quot;, text=result_text)]<br>)<br>raise ValueError(f&quot;Unknown tool: {name}&quot;)<br>if __name__ == &quot;__main__&quot;:<br>stdio_server.run(app)</pre><ul><li>This server runs over stdio (standard input/output). A client can launch it as a subprocess and communicate via stdin/stdout.</li></ul><h4><strong>7. How the Server Maps Tool Names to Functions</strong></h4><p>Inside the server, you maintain a mapping (e.g., a dictionary) between tool names and the actual Python functions.</p><pre>python<br>TOOL_FUNCTIONS = {<br>&quot;get_weather&quot;: get_weather,<br>&quot;calculator&quot;: lambda a,b: a+b,<br># …<br>}<br>@app.call_tool()<br>async def call_tool(name: str, arguments: dict):<br>if name in TOOL_FUNCTIONS:<br>result = TOOL_FUNCTIONS[name](**arguments)<br>return CallToolResult(…)<br>…</pre><ul><li>The call_tool handler receives the name and arguments, looks up the function, calls it, and returns the result wrapped in the MCP response format.</li></ul><h4><strong>8. Transport Options</strong></h4><p>Transport Description Typical Use</p><p><strong>stdio:</strong> Server runs as subprocess; client writes to its stdin, reads from stdout. Local tools, lightweight, easy to spawn.</p><p><strong>HTTP + SSE</strong> : Server runs as HTTP server; client sends requests via HTTP, receives streaming responses via Server‑Sent Events. Remote services, web‑based agents.</p><p>The protocol messages (JSON‑RPC) are the same; only the transport layer changes.</p><h4><strong>9. Benefits of MCP</strong></h4><ul><li>Dynamic Discovery: Client can ask “what tools do you have?” at runtime — no hardcoding.</li><li>Standardized Invocation: Every tool is called the same way (tools/call with arguments).</li><li>Language Agnostic: Servers can be written in any language (Python, JS, Rust, etc.) as long as they speak JSON‑RPC over a supported transport.</li><li>Interoperability: Any MCP‑compatible client can use any MCP server without modification.</li></ul><h3>FastMCP</h3><h4>1. What is FastMCP?</h4><p>FastMCP is a high‑level <strong>Python framework</strong> built on top of the official MCP (Model Context Protocol) SDK. It is designed to simplify and accelerate the development of MCP servers by providing a <strong>declarative, decorator‑based API.</strong> With FastMCP, you can focus on writing your tool logic without worrying about the underlying JSON‑RPC message handling, request routing, or schema generation.</p><h4>2. Why FastMCP? The Problem It Solves</h4><p>The base MCP Server class (from the official SDK) requires you to manually implement:</p><ul><li>list_tools() — to return tool definitions.</li><li>call_tool() — to route incoming calls to the correct function.</li><li>JSON‑RPC request parsing and response formatting.</li><li>Argument validation and error handling.</li><li>Transport setup (stdio or SSE).</li></ul><p>This is repetitive and error‑prone, especially for servers with many tools. FastMCP automates all of that:</p><ul><li>Automatic tool discovery — just decorate a function with @mcp.tool().</li><li>Automatic schema generation — from Python type hints and docstrings.</li><li>Automatic request routing — based on the tool name.</li><li>Built‑in validation — arguments are checked against the schema.</li><li>Easy transport configuration — mcp.run(transport=”stdio”) or “sse”.</li></ul><h4>3. Core Concepts</h4><p><strong>3.1 The FastMCP Class</strong></p><p>The central object. You create one instance per server:</p><pre>python<br>from fastmcp import FastMCP<br>mcp = FastMCP(&quot;My Server Name&quot;)</pre><p><strong>3.2 Tools</strong></p><p>A tool is a Python function that can be called by an AI agent. Decorate it with <strong>@mcp.tool():</strong></p><pre>python<br>@mcp.tool()<br>def add(a: int, b: int) -&gt; int:<br>&quot;&quot;&quot;Add two numbers together.&quot;&quot;&quot;<br>return a + b</pre><ul><li>The function name becomes the tool name (add).</li><li>The docstring becomes the tool description (sent to the LLM).</li><li>Type hints are used to generate the JSON Schema for input validation.</li><li>The return value is automatically converted to a TextContent result (or you can return richer structures).</li></ul><p><strong>3.3 Resources</strong></p><p>A resource exposes static or dynamically generated data (like files, database records) to the client. Use <strong>@mcp.resource():</strong></p><pre>python<br>@mcp.resource(&quot;config://app&quot;)<br>def get_config() -&gt; str:<br>&quot;&quot;&quot;Return the application configuration.&quot;&quot;&quot;<br>return &quot;debug=True\nport=8080&quot;</pre><p>Resources are identified by a URI scheme (here config://). The client can fetch them.</p><p><strong>3.4 Prompts</strong></p><p>A prompt is a reusable template that the client can request to insert into the LLM’s context. <strong>Use @mcp.prompt():</strong></p><pre>python<br>@mcp.prompt()<br>def analyze_sentiment(text: str) -&gt; str:<br>&quot;&quot;&quot;Create a prompt for sentiment analysis.&quot;&quot;&quot;<br>return f&quot;Analyze the sentiment of the following text: {text}&quot;</pre><p>Prompts can be parameterised and are returned as plain text or a list of messages.</p><h4><strong>4. How FastMCP Works Under the Hood</strong></h4><p>When you decorate a function with @mcp.tool(), FastMCP:</p><p><strong>1. Inspects the function </strong>— name, docstring, parameters, type hints, return annotation.</p><p><strong>2. Builds a JSON Schema</strong> from the parameters (using the pydantic library internally).</p><p>3. Registers the tool in an <strong>internal registry,</strong> storing the schema and a reference to the function.</p><p>4. When the server receives a tools/list request, it iterates the registry and <strong>returns the list of tool definitions.</strong></p><p>5. When a tools/call request arrives, it:</p><ul><li>Looks up the function by name.</li><li>Validates the arguments against the schema.</li><li>Calls the function with the arguments.</li><li>Converts the return value into an MCP CallToolResult (by default wrapping it in TextContent).</li><li>Handles any exceptions and returns an error response.</li></ul><p>All of this happens without any boilerplate from you.</p><h4>5. Example: A Complete FastMCP Server</h4><pre>python<br>from fastmcp import FastMCP<br># Create the server<br>mcp = FastMCP(&quot;Demo Server&quot;)<br># - Tools -<br>@mcp.tool()<br>def greet(name: str) -&gt; str:<br>&quot;&quot;&quot;Greet a person by name.&quot;&quot;&quot;<br>return f&quot;Hello, {name}!&quot;<br>@mcp.tool()<br>def add(a: float, b: float) -&gt; float:<br>&quot;&quot;&quot;Add two numbers.&quot;&quot;&quot;<br>return a + b<br># - Resource -<br>@mcp.resource(&quot;info://version&quot;)<br>def get_version() -&gt; str:<br>&quot;&quot;&quot;Return the server version.&quot;&quot;&quot;<br>return &quot;1.0.0&quot;<br># - Prompt -<br>@mcp.prompt()<br>def haiku(topic: str) -&gt; str:<br>&quot;&quot;&quot;Create a haiku prompt.&quot;&quot;&quot;<br>return f&quot;Write a haiku about {topic}.&quot;<br># Run the server (stdio by default)<br>if __name__ == &quot;__main__&quot;:<br>mcp.run()</pre><p>Save this as server.py. You can then connect any MCP client (like Claude Desktop) to it.</p><h4>6. Running FastMCP Servers</h4><p>FastMCP supports two transports:</p><p><strong>6.1 stdio (Standard Input/Output)</strong></p><p>The server runs as a subprocess. This is the default and is ideal for local tools.</p><pre>python<br>mcp.run() # or mcp.run(transport=&quot;stdio&quot;)</pre><p>The client (e.g., Claude Desktop) launches your script and communicates via stdin/stdout.</p><p><strong>6.2 SSE (Server‑Sent Events) over HTTP</strong></p><p>The server runs as an HTTP server, and the client connects via HTTP. Useful for remote or containerised servers.</p><pre>python<br>mcp.run(transport=&quot;sse&quot;, host=&quot;0.0.0.0&quot;, port=8000)</pre><p>Then clients can connect to <a href="http://your-host:8000/sse.">http://your-host:8000/sse.</a></p><h4>7. Advanced Features</h4><p><strong>7.1 Context Injection</strong></p><p>If your tool needs access to the request context (e.g., to get client information, or to use logging), you can add a parameter of type fastmcp.Context. FastMCP will automatically inject the context.</p><pre>python<br>from fastmcp import FastMCP, Context<br>mcp = FastMCP(&quot;Context Demo&quot;)<br>@mcp.tool()<br>def long_task(ctx: Context, duration: int) -&gt; str:<br>&quot;&quot;&quot;Simulate a long task with progress reporting.&quot;&quot;&quot;<br>for i in range(duration):<br>ctx.report_progress(i, duration) # sends progress notifications<br>time.sleep(1)<br>return &quot;Done&quot;</pre><p>The context object provides methods for logging, progress reporting, and accessing request metadata.</p><p><strong>7.2 Custom Result Types</strong></p><p>By default, FastMCP wraps return values in TextContent. You can return an mcp.types.CallToolResult directly for full control, or return other content types like ImageContent or EmbeddedResource.</p><pre>python<br>from mcp.types import ImageContent<br>@mcp.tool()<br>def plot() -&gt; list[ImageContent]:<br># generate an image…<br>return [ImageContent(type=&quot;image&quot;, data=base64_data, mimeType=&quot;image/png&quot;)]</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*X5XHwI6K-XzxGtBPsEYgpg.png" /></figure><h4>9. Integration with MCP Clients</h4><p>Any client that speaks the MCP protocol can connect to a FastMCP server. Popular examples:</p><ul><li>Claude Desktop — you can configure it to launch your FastMCP server as a subprocess.</li><li>Custom Python agents — using the mcp client SDK.</li><li>VS Code extensions — that support MCP.</li></ul><p>Claude Desktop, for instance, allows you to add an MCP server by specifying the command to run your script (e.g., python my_server.py). It will then automatically discover your tools and make them available to Claude.</p><h4>10. Benefits of Using FastMCP</h4><ul><li>Speed of development — go from idea to working tool in minutes.</li><li>Readability — your code clearly shows what tools exist and what they do.</li><li>Maintainability — adding or changing a tool is a one‑line change.</li><li>Type safety — type hints reduce bugs and improve IDE support.</li><li>Ecosystem compatibility — works with all MCP clients.</li><li>Extensibility — easy to add resources, prompts, and custom behaviour when needed.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0bab0bd7b8a3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Application Programming Interface]]></title>
            <link>https://medium.com/@vengiboopathi/application-programming-interface-4dfda97e7428?source=rss-d9be6945e434------2</link>
            <guid isPermaLink="false">https://medium.com/p/4dfda97e7428</guid>
            <dc:creator><![CDATA[Vengadesa Boopathi]]></dc:creator>
            <pubDate>Thu, 05 Mar 2026 05:23:40 GMT</pubDate>
            <atom:updated>2026-03-05T05:23:40.075Z</atom:updated>
            <content:encoded><![CDATA[<h4><strong>What is an API?</strong></h4><p>API stands for Application Programming Interface.</p><p>It’s a set of rules that allows one piece of software to talk to another. Think of it as a waiter in a restaurant:</p><ul><li>You (the client) tell the waiter what you want.</li><li>The waiter takes your order to the kitchen (the server).</li><li>The kitchen prepares your food and gives it to the waiter.</li><li>The waiter brings it back to you.</li></ul><p>The waiter abstracts the complexity of the kitchen — you don’t need to know how the food is cooked, you just place your order and receive the result.</p><p>In software, an API defines the methods and data formats that applications can use to request services from each other.</p><h4><strong>Why Do We Need APIs?</strong></h4><p>Without APIs, every integration would be custom‑coded and fragile.</p><p>Example: Imagine you want to display the current weather in your app.</p><p><strong>Without an API (The Messy Way)</strong></p><p>You decide to scrape the weather website:</p><blockquote>1. Write code to download the HTML page (e.g., weather.com/city).</blockquote><blockquote>2. Use regular expressions or an HTML parser to locate the temperature element (&lt;span class=”temp”&gt;72°F&lt;/span&gt;).</blockquote><blockquote>3. Extract the value.</blockquote><blockquote>4. Repeat for other cities, handling different page structures.</blockquote><blockquote>5. If the website redesigns its HTML, your code breaks.</blockquote><blockquote>6. You might get blocked for scraping, need to handle cookies, and deal with rate limiting.</blockquote><blockquote>7. To add another weather source, you start from scratch with new scraping logic.</blockquote><p>Result: Time‑consuming, brittle, and hard to maintain.</p><p><strong>With an API (The Clean Way)</strong></p><p>The weather service provides an official API:</p><ul><li>They document a single endpoint: <a href="https://api.weather.com/v1/current">https://api.weather.com/v1/current</a></li><li>You send a request: GET <a href="https://api.weather.com/v1/current?city=London&amp;apikey=123">https://api.weather.com/v1/current?city=London&amp;apikey=123</a></li><li>The server responds with clean JSON:</li></ul><pre>json<br>{<br>&quot;city&quot;: &quot;London&quot;,<br>&quot;temp&quot;: 72,<br>&quot;unit&quot;: &quot;F&quot;<br>}</pre><ul><li>Your app parses the JSON and displays the temperature.</li><li>If they change something internally, the API remains backward‑compatible.</li><li>To switch providers, you just call a different API (similar pattern).</li></ul><p>Result: Simple, reliable, and reusable.</p><h4>Key Concepts of APIs</h4><p><strong>1. Client and Server</strong></p><ul><li>Client: The application that <strong>requests</strong> data or services (e.g., your mobile app, a web frontend, a script).</li><li>Server: The application that <strong>provides</strong> the data or service (e.g., a weather database, a payment processor).</li></ul><p><strong>2. HTTP Methods (Verbs)</strong></p><p>APIs often use HTTP to communicate. Common methods:</p><pre>GET — Retrieve data (e.g., get weather).<br>POST - Send new data (e.g., create a user).<br>PUT - Update existing data.<br>DELETE - Remove data.</pre><p><strong>3. Endpoint</strong></p><p>A specific URL where the API can be accessed.</p><p>Example: <a href="https://api.weather.com/v1/current">https://api.weather.com/v1/current</a></p><ul><li>https:// — protocol</li><li>api.weather.com — domain</li><li>/v1/current — path (often includes version and resource)</li></ul><p><strong>4. Request Parameters</strong></p><p>Data sent with the request. Can be:</p><ul><li>Query parameters (in the URL): ?city=London&amp;units=metric</li><li>Headers (metadata like authentication): Authorization: Bearer token</li><li>Body (for POST/PUT, usually JSON)</li></ul><p><strong>5. Response</strong></p><p>The data the server sends back. Usually in JSON (or XML).</p><p>Example:</p><pre>json<br>{<br>&quot;city&quot;: &quot;London&quot;,<br>&quot;temp&quot;: 22,<br>&quot;unit&quot;: &quot;C&quot;<br>}</pre><p><strong>6. REST</strong></p><p>REST (Representational State Transfer) is a popular architectural style for APIs. RESTful APIs:</p><ul><li>Use standard HTTP methods.</li><li>Are stateless (each request contains all needed info).</li><li>Return data in JSON or XML.</li><li>Organize resources around URLs (e.g., /users, /users/123).</li></ul><p><strong>Example: Using a Weather API in Python :</strong></p><p>Let’s use a fake weather API to illustrate. We’ll use the requests library.</p><pre>python<br>import requests<br># API endpoint<br>url = &quot;https://api.weather.com/v1/current&quot;<br># Parameters<br>params = {<br>&quot;city&quot;: &quot;London&quot;,<br>&quot;units&quot;: &quot;metric&quot;,<br>&quot;apikey&quot;: &quot;your_api_key_here&quot;<br>}<br># Send GET request<br>response = requests.get(url, params=params)<br># Check if successful (status code 200)<br>if response.status_code == 200:<br>data = response.json() # Parse JSON<br>print(f&quot;Temperature in {data[&#39;city&#39;]}: {data[&#39;temp&#39;]}°{data[&#39;unit&#39;]}&quot;)<br>else:<br>print(&quot;Error:&quot;, response.status_code)</pre><p><strong>Explanation:</strong></p><ul><li>We build the URL with query parameters.</li><li>requests.get() sends the request and waits for the response.</li><li>The server returns JSON, which we convert to a Python dictionary.</li><li>We extract and display the data.</li></ul><p><strong>Why Are APIs So Useful?</strong></p><ul><li><strong>Abstraction:</strong> You don’t need to know the server’s internal implementation.</li><li><strong>Standardization: </strong>All clients interact with the same well‑defined interface.</li><li><strong>Reusability: </strong>The same API can serve many different clients (web, mobile, desktop).</li><li><strong>Security: </strong>The server can control access (via API keys, OAuth) without exposing internals.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4dfda97e7428" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>