<?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 Usama Nawaz on Medium]]></title>
        <description><![CDATA[Stories by Usama Nawaz on Medium]]></description>
        <link>https://medium.com/@usamanawaz789?source=rss-3cd12dbc6d59------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*uvkc1T-2Miyl6trCFN_IVg.jpeg</url>
            <title>Stories by Usama Nawaz on Medium</title>
            <link>https://medium.com/@usamanawaz789?source=rss-3cd12dbc6d59------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 13:04:55 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@usamanawaz789/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 First Production LLM API Call: A 2026 Wrapper Pattern for Claude Opus 4.7]]></title>
            <link>https://medium.com/@usamanawaz789/your-first-production-llm-api-call-a-2026-wrapper-pattern-for-claude-opus-4-7-ec4fdecb8535?source=rss-3cd12dbc6d59------2</link>
            <guid isPermaLink="false">https://medium.com/p/ec4fdecb8535</guid>
            <category><![CDATA[ai-production]]></category>
            <category><![CDATA[ai-engineering]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[claude]]></category>
            <category><![CDATA[llm]]></category>
            <dc:creator><![CDATA[Usama Nawaz]]></dc:creator>
            <pubDate>Thu, 30 Apr 2026 08:04:58 GMT</pubDate>
            <atom:updated>2026-04-30T08:04:58.417Z</atom:updated>
            <content:encoded><![CDATA[<p>Last month I sat in on an incident review. A small AI feature that had shipped six weeks earlier was throwing 500s on roughly four percent of requests. The on-call engineer had no logs from the failing calls. No token counts. No correlation. No model id. Just stack traces from a one-liner inside a route handler that called the Anthropic SDK directly.</p><p>The fix took an afternoon. The cost of not having done it the first time, in support hours and customer trust, was about three weeks. This article is about the file that should have existed on day one.</p><h3>The Problem</h3><p>A production LLM call is not the same as a working LLM call. The SDK request looks identical. What differs is everything that surrounds it: how errors are mapped to your domain, how retries are policed, how the call is observable in logs and metrics, how token usage rolls into your cost dashboard, how a single user-facing operation can be traced through every component it touches.</p><p>In 2026, the gap matters more than it did even a year ago. Claude Opus 4.7 shipped on April 16 with API behaviour that breaks code written for Opus 4.6 (temperature, top_p, and top_k now return HTTP 400 if non-default; the new tokenizer produces up to 35% more tokens; thinking content is omitted by default). Anthropic’s SDK is on 0.97.0 as of April 23. OpenAI’s SDK is on 2.32.0. The version notes are real. The wrapper that abstracts your team away from those notes pays for itself the first time you migrate a model.</p><h3>Image prompt for this article</h3><p><strong>Medium featured image</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*A6zaKKjs-4iBz-jxyAW2DQ.png" /></figure><h3>The Solution</h3><p>One file in your codebase owns the boundary to every language-model API. Every call goes through it. Every caller sees a stable interface. The five responsibilities of that file are non-negotiable.</p><h3>1. Typed errors with stable names</h3><p>SDK exception classes change names across major versions. Application code that catches RateLimitError directly will need to be rewritten the next time Anthropic restructures its exception hierarchy. The wrapper catches every SDK exception and re-raises a small set of stable, domain-named errors: rate_limited, overloaded, timeout, connection_error, api_error_&lt;status&gt;. Upstream code branches on those.</p><p>One specific case to handle: HTTP 529 (overloaded_error) is a capacity signal from Anthropic’s platform, separate from a 429 rate limit on your account. The SDK surfaces it as APIStatusError. Treat it as a distinct condition; a 429 means slow down, a 529 means try a different model.</p><h3>2. Retries the SDK already does</h3><p>The Anthropic Python SDK retries 408, 409, 429, 5xx, and connection errors twice by default with exponential backoff and jitter. It honours the retry-after and retry-after-ms headers. The OpenAI SDK has equivalent behaviour. A second retry loop on top of the SDK is a thundering-herd generator. State max_retries explicitly so future readers can audit it. Then leave it.</p><h3>3. Five-field structured logging</h3><p>Every successful call emits one structured log line with five fields: correlation_id, model, input_tokens, output_tokens, latency_ms. Add stop_reason as a sixth and you can spot truncations. Add request_id as a seventh and Anthropic support can find your call. Do not log prompt or response bodies; user data ends up in places it should not.</p><h3>4. Token accounting at the call site</h3><p>message.usage carries the canonical token counts. Read it, return it on the typed response, and do not approximate. Opus 4.7’s new tokenizer makes any client-side estimate wrong; billing happens on the model’s count, not yours.</p><h3>5. Correlation that survives</h3><p>A twelve-character hex ID generated at the entry point, threaded through every layer that touches the call. When something fails, one grep tells the whole story.</p><h3>Code Walkthrough</h3><p>Here is the wrapper. It is the only place in the codebase that imports from `anthropic`. Every other call site goes through call_llm.</p><pre># llm_client.py<br># A production-grade wrapper around the Anthropic Messages API.<br># Verified against anthropic SDK 0.97.0 (released April 23, 2026)<br># and Claude Opus 4.7 / Sonnet 4.6 / Haiku 4.5.<br> <br>from __future__ import annotations<br> <br>import logging<br>import os<br>import time<br>import uuid<br>from dataclasses import dataclass<br>from typing import Any<br> <br>import anthropic<br>from anthropic import (<br>    Anthropic,<br>    APIConnectionError,<br>    APIStatusError,<br>    APITimeoutError,<br>    RateLimitError,<br>)<br> <br>logger = logging.getLogger(__name__)<br> <br> <br>@dataclass(frozen=True)<br>class LLMResponse:<br>    &quot;&quot;&quot;Typed response object returned to upstream callers.&quot;&quot;&quot;<br>    text: str<br>    model: str<br>    input_tokens: int<br>    output_tokens: int<br>    stop_reason: str | None<br>    request_id: str | None<br>    latency_ms: int<br>    correlation_id: str<br> <br> <br>class LLMClientError(Exception):<br>    &quot;&quot;&quot;Domain error wrapping any failure from the LLM call site.&quot;&quot;&quot;<br> <br> <br># Build the SDK client once at import time. The SDK is internally async-safe<br># and reuses an httpx connection pool, so a module-level instance is the<br># correct production shape. Key precedence is: explicit kwarg &gt; env var.<br>_CLIENT = Anthropic(<br>    # api_key omitted intentionally; SDK reads ANTHROPIC_API_KEY from env.<br>    # max_retries=2 is the SDK default; we keep it explicit for auditability.<br>    max_retries=2,<br>    # 60 seconds is enough for non-streaming completions up to ~4K tokens;<br>    # raise this only when generating long structured output.<br>    timeout=60.0,<br>)<br> <br> <br>def call_llm(<br>    prompt: str,<br>    *,<br>    system: str | None = None,<br>    model: str = &quot;claude-sonnet-4-6&quot;,<br>    max_tokens: int = 1024,<br>    correlation_id: str | None = None,<br>) -&gt; LLMResponse:<br>    &quot;&quot;&quot;Production entry point for a single-turn Messages call.<br> <br>    Returns a typed LLMResponse. Raises LLMClientError on any unrecoverable<br>    failure. Caller is expected to log the correlation_id.<br>    &quot;&quot;&quot;<br>    cid = correlation_id or uuid.uuid4().hex[:12]<br>    started = time.monotonic()<br> <br>    # Note on model choice: claude-opus-4-7 rejects temperature/top_p/top_k<br>    # if non-default, so we do NOT pass them by default. If you must control<br>    # sampling on Sonnet/Haiku, branch on model id and pass them only there.<br>    request: dict[str, Any] = {<br>        &quot;model&quot;: model,<br>        &quot;max_tokens&quot;: max_tokens,<br>        &quot;messages&quot;: [{&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: prompt}],<br>    }<br>    if system is not None:<br>        request[&quot;system&quot;] = system<br> <br>    try:<br>        # The SDK retries APIConnectionError, 408, 409, 429, and 5xx by<br>        # default with exponential backoff and jitter. We layer logging<br>        # around it; we do NOT add a second retry loop on top.<br>        message = _CLIENT.messages.create(**request)<br> <br>    except RateLimitError as e:<br>        # 429: request-rate or token-rate quota exceeded. The retry-after<br>        # header is the source of truth; the SDK already honours it on<br>        # the inner retries, so reaching here means we are out of budget.<br>        logger.warning(<br>            &quot;llm_rate_limited cid=%s model=%s status=%s&quot;,<br>            cid, model, e.status_code,<br>        )<br>        raise LLMClientError(&quot;rate_limited&quot;) from e<br> <br>    except APIStatusError as e:<br>        # 529 overloaded_error is a capacity signal, distinct from 429.<br>        # Surface it explicitly so upstream can fall back to another model.<br>        if e.status_code == 529:<br>            logger.warning(&quot;llm_overloaded cid=%s model=%s&quot;, cid, model)<br>            raise LLMClientError(&quot;overloaded&quot;) from e<br>        logger.error(<br>            &quot;llm_api_error cid=%s model=%s status=%s body=%s&quot;,<br>            cid, model, e.status_code, getattr(e, &quot;body&quot;, None),<br>        )<br>        raise LLMClientError(f&quot;api_error_{e.status_code}&quot;) from e<br> <br>    except APITimeoutError as e:<br>        logger.error(&quot;llm_timeout cid=%s model=%s&quot;, cid, model)<br>        raise LLMClientError(&quot;timeout&quot;) from e<br> <br>    except APIConnectionError as e:<br>        logger.error(&quot;llm_connection_error cid=%s model=%s&quot;, cid, model)<br>        raise LLMClientError(&quot;connection_error&quot;) from e<br> <br>    latency_ms = int((time.monotonic() - started) * 1000)<br> <br>    # The Messages API returns a list of content blocks. For a normal<br>    # text reply, the first block is type=&quot;text&quot;. We concatenate text<br>    # blocks defensively so that future model behaviour does not silently<br>    # drop content (for example, when summarized thinking blocks appear).<br>    text = &quot;&quot;.join(<br>        block.text for block in message.content if block.type == &quot;text&quot;<br>    )<br> <br>    response = LLMResponse(<br>        text=text,<br>        model=message.model,<br>        input_tokens=message.usage.input_tokens,<br>        output_tokens=message.usage.output_tokens,<br>        stop_reason=message.stop_reason,<br>        request_id=getattr(message, &quot;_request_id&quot;, None),<br>        latency_ms=latency_ms,<br>        correlation_id=cid,<br>    )<br> <br>    # Structured success log. Always include correlation_id, model,<br>    # token counts, latency, and stop_reason. These five fields are the<br>    # minimum viable observability surface for a production LLM call.<br>    logger.info(<br>        &quot;llm_call_ok cid=%s rid=%s model=%s input_tokens=%d output_tokens=%d &quot;<br>        &quot;latency_ms=%d stop_reason=%s&quot;,<br>        cid, response.request_id, response.model,<br>        response.input_tokens, response.output_tokens,<br>        response.latency_ms, response.stop_reason,<br>    )<br> <br>    # stop_reason=&quot;max_tokens&quot; means the model was cut off mid-thought.<br>    # Do not silently return truncated output; let the caller decide.<br>    if response.stop_reason == &quot;max_tokens&quot;:<br>        logger.warning(<br>            &quot;llm_truncated cid=%s model=%s output_tokens=%d max_tokens=%d&quot;,<br>            cid, model, response.output_tokens, max_tokens,<br>        )<br> <br>    return response<br> <br> <br>if __name__ == &quot;__main__&quot;:<br>    logging.basicConfig(<br>        level=logging.INFO,<br>        format=&quot;%(asctime)s %(levelname)s %(message)s&quot;,<br>    )<br>    out = call_llm(<br>        prompt=&quot;In one sentence, what is a production-grade LLM API call?&quot;,<br>        system=&quot;You are a precise senior engineer. Reply concisely.&quot;,<br>        model=&quot;claude-sonnet-4-6&quot;,<br>        max_tokens=200,<br>    )<br>    print(out.text)</pre><p>Three design choices in this file are worth calling out.</p><p>The SDK client is constructed once at import time. The httpx connection pool inside the SDK is reused across requests; per-call client construction would add TLS handshake overhead to every request. max_retries=2 and timeout=60.0 are stated explicitly even though they match the SDK defaults; future readers can audit the policy without reading SDK source.</p><p>Errors are caught in three tiers. RateLimitError (429) is a quota signal. APIStatusError covers everything else from the API, including 529. APITimeoutError and APIConnectionError are the network-side errors. Each maps to a stable domain code. The catch order matters: RateLimitError is a subclass of APIStatusError, so it must come first.</p><p>Text extraction concatenates only blocks where block.type == “text”. This is forward-compatible with Opus 4.7’s thinking-block behaviour (where summarized thinking blocks can appear before text blocks) and any future content-block types.</p><h3>Production Gotchas</h3><p>Here is the same call written naively. Every line is wrong; every wrongness is a class of incident.</p><pre># DO NOT SHIP THIS<br># Every line in this file is a future production incident.<br> <br>import anthropic<br> <br>client = anthropic.Anthropic(api_key=&quot;sk-ant-api03-XXXXXXXXXXXX&quot;)<br> <br>def ask(prompt):<br>    response = client.messages.create(<br>        model=&quot;claude-3-opus-20240229&quot;,        # Deprecated model id<br>        max_tokens=4096,<br>        temperature=0.7,                       # 400 error on Opus 4.7<br>        messages=[{&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: prompt}]<br>    )<br>    return response.content[0].text             # Crashes if the first<br>                                                # block is not text.<br> <br>print(ask(&quot;Hello&quot;))</pre><blockquote><strong>Naive vs production</strong></blockquote><blockquote>Hardcoded API key vs environment variable: a single secret leak undoes everything.</blockquote><blockquote>Deprecated model id vs config-driven id: a model deprecation should be a config bump, not a deploy.</blockquote><blockquote>Default sampling parameters vs no sampling parameters: temperature=0.7 returns 400 on Opus 4.7.</blockquote><blockquote>No error handling vs five typed domain errors: every failure mode is uncatchable in the naive case.</blockquote><blockquote>No logging vs five structured fields: incidents are uninvestigable in the naive case.</blockquote><blockquote>Index-based content access vs type-filtered concatenation: brittle to any future content-block type.</blockquote><h3>Summary</h3><p>The shape of your first production LLM call decides the shape of your production system. One file owns the boundary. That file accepts a prompt and a model, returns a typed response with token counts and correlation, raises stable domain errors, emits one structured log line per call, and works correctly across the Claude 4.x family. Every other section in this chapter (token economics, streaming, error handling, multi-provider abstraction, observability) builds on the shape established here.</p><p>Cost: forty extra minutes the first time. Savings: every incident week you do not have to spend reverse-engineering an unobservable call site.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ec4fdecb8535" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Claude Opus 4.7 vs GPT-5.4 vs Llama 4: 2026 AI Guide]]></title>
            <link>https://medium.com/@usamanawaz789/claude-opus-4-7-vs-gpt-5-4-vs-llama-4-2026-ai-guide-dd38cc326da2?source=rss-3cd12dbc6d59------2</link>
            <guid isPermaLink="false">https://medium.com/p/dd38cc326da2</guid>
            <category><![CDATA[langchain]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Usama Nawaz]]></dc:creator>
            <pubDate>Fri, 17 Apr 2026 08:01:06 GMT</pubDate>
            <atom:updated>2026-04-17T08:01:06.625Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GgbpT1B1KI2qNwR-RrSifQ.png" /></figure><p>It is April 17, 2026. Yesterday Anthropic released Claude Opus 4.7. Last month OpenAI shipped GPT-5.4. Three months ago Meta previewed Muse Spark as a closed-weights successor to the Llama line. If you wired an LLM into your product eighteen months ago and have not revisited the decision since, you are almost certainly paying too much for a model that no longer fits your workload.</p><p>This article is the field guide. I will walk through the four model families that actually matter for production AI engineering right now, map each to the workloads it serves well, and show you the single most important piece of code you will write on any new LLM project: a provider abstraction that lets you swap vendors without rewriting your application.</p><h3>The Problem: Model Selection Is an Architectural Decision</h3><p>Most teams treat model selection like shopping. Pick one, wire it in, revisit when the bill arrives. This framing is wrong and it shows up as pain six months later.</p><p>A model choice commits you to a tokenizer, a context window, a tool calling schema, a streaming protocol, a safety filter, a pricing curve, and a rate limit pool. Change any one of those and you are migrating, not reconfiguring. Worse, the optimal choice is workload-specific. A model that is cheap for short classification tasks can be ruinous for long-document summarization because its output pricing dominates. A model with a 1M token context window is wasted on 400-token customer support prompts. A model that tops the coding charts may underperform on creative writing.</p><p>You cannot pick one model that is optimal for all your production workloads. Your architecture needs to accommodate routing between multiple models from day one. That premise drives the rest of this article.</p><h3>The Solution: The Four Families That Matter in April 2026</h3><h3>1. Anthropic’s Claude Family</h3><p><strong>Claude Opus 4.7 </strong>(claude-opus-4–7): Released on April 16, 2026. $5 input / $25 output per million tokens. 1M token context at flat pricing. High-resolution vision up to 3.75 megapixels, roughly three times the resolution of Opus 4.6. Excels at long-horizon agentic work, complex coding (87.6 percent on SWE-bench Verified), and workflows where the model verifies its own outputs before returning.</p><p>Two production caveats. First, the new tokenizer can produce up to thirty-five percent more tokens for the same text versus Opus 4.6 — your bill may climb even though the rate card did not. Second, several Opus 4.6 sampling parameters and explicit thinking budgets have been removed. Migration is not a drop-in replacement. Replay a representative traffic sample and measure before cutting over.</p><p><strong>Claude Sonnet 4.6 </strong>(claude-sonnet-4–6): $3/$15 per MTok, 1M context. The recommended default for the majority of production workloads. Forty percent cheaper than Opus on both sides. Unless you have measured a real quality gap on your specific task, start here.</p><p><strong>Claude Haiku 4.5 </strong>(claude-haiku-4–5): $1/$5 per MTok, 200K context. Classification, routing, extraction, moderation, summarization. The high-volume workhorse.</p><h3>2. OpenAI’s GPT-5.4 Family</h3><p>OpenAI shipped GPT-5.4 in early March 2026 as the successor to GPT-5.3 Codex. Base pricing: $2.50 input / $15 output per million tokens, with GPT-5.4-pro at six times the rate for deep reasoning. GPT-5.4-mini ($0.25/$2) is the current price-performance sweet spot for lightweight production tasks. GPT-5.4-nano ($0.05/$0.40) is built for extraction and classification at scale.</p><p>Every GPT-5.4 model ships with cached input pricing at ten percent of the base rate automatically. Any repeated prompt prefix becomes dramatically cheaper after the first call. The Responses API has replaced the legacy Chat Completions API as the primary interface. Context windows top out at 1.05 million tokens on GPT-5.4, with prompts above 272K tokens triggering a 2x multiplier on input and 1.5x on output for the entire session.</p><p>Where GPT-5.4 shines: multimodal reasoning, cache-heavy workloads, and any pipeline that benefits from OpenAI’s aggressive automatic caching. Where it does not shine: long-horizon autonomous agent work where Claude Opus 4.7 measurably outperforms, and any workload with strict data residency requirements that OpenAI’s regional endpoints charge a ten percent premium for.</p><h3>3. Meta’s Llama 4 Family</h3><p>Llama 4 Maverick (17B active / 128 experts, ~400B total) and Llama 4 Scout (17B active / 16 experts, 10M context) are the open-weight options you reach for when data cannot leave your infrastructure. Scout fits on a single H100 with INT4 quantization. Maverick requires a full H100 host. Both are natively multimodal for text and image input.</p><p>Pricing is different because you run it yourself. Meta’s own estimate lands Maverick at roughly nineteen cents per million tokens on distributed inference, climbing to thirty to forty-nine cents on a single host. You pay in GPU complexity, quota, and operational burden rather than per-token fees.</p><p>One flag. In April 2026 Meta announced Muse Spark as a closed-weights successor from Meta Superintelligence Labs, and the open-weight future of Llama is no longer guaranteed. If you build on Llama 4 today, you build on a snapshot, not a roadmap.</p><h3>4. Cloud-Managed Claude (Bedrock, Vertex AI, Foundry)</h3><p>Claude Opus 4.7 shipped on AWS Bedrock on April 16, 2026 as anthropic.claude-opus-4–7-v1:0. Google Vertex AI publishes the same model as claude-opus-4–7@20260416. Microsoft Foundry lists it in the Azure AI Foundry catalog. Per-token cost matches direct Anthropic API access, though cloud providers may add enterprise margin.</p><p>Route here when your data must not leave a specific cloud perimeter, when your existing IAM story is too valuable to bypass, or when you need contractual enterprise SLAs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GrpGqhEFcRNv_zEWKsXCkg.png" /></figure><h3>Code Walkthrough: The Provider Abstraction</h3><p>Here is the piece of code that will save you the most pain over the next two years. Build this on day one, use it for every LLM call, and you buy flexibility the moment the landscape shifts.</p><pre># providers/base.py<br>from __future__ import annotations<br>import abc, logging, os, time<br>from dataclasses import dataclass, field<br>from typing import Any<br> <br>logger = logging.getLogger(__name__)<br> <br>@dataclass<br>class LLMResponse:<br>    &quot;&quot;&quot;Normalized response. Callers never touch raw SDK objects.&quot;&quot;&quot;<br>    text: str<br>    model: str<br>    provider: str<br>    input_tokens: int<br>    output_tokens: int<br>    latency_ms: int<br>    stop_reason: str<br>    metadata: dict[str, Any] = field(default_factory=dict)<br> <br>class LLMProvider(abc.ABC):<br>    name: str<br>    default_model: str<br> <br>    @abc.abstractmethod<br>    def complete(<br>        self, prompt: str, system: str | None = None,<br>        model: str | None = None, max_tokens: int = 1024,<br>        temperature: float = 0.2,<br>    ) -&gt; LLMResponse: ...<br> <br># providers/anthropic_provider.py<br>import anthropic<br>from anthropic import APIError, APIConnectionError, RateLimitError<br> <br>class ClaudeProvider(LLMProvider):<br>    name = &quot;anthropic&quot;<br>    default_model = &quot;claude-opus-4-7&quot;   # Released April 16, 2026<br> <br>    def __init__(self) -&gt; None:<br>        self._client = anthropic.Anthropic(<br>            api_key=os.environ[&quot;ANTHROPIC_API_KEY&quot;]<br>        )<br> <br>    def complete(self, prompt, system=None, model=None,<br>                 max_tokens=1024, temperature=0.2):<br>        start = time.perf_counter()<br>        try:<br>            kwargs = {<br>                &quot;model&quot;: model or self.default_model,<br>                &quot;max_tokens&quot;: max_tokens,<br>                &quot;temperature&quot;: temperature,<br>                &quot;messages&quot;: [{&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: prompt}],<br>            }<br>            if system is not None:<br>                kwargs[&quot;system&quot;] = system<br>            msg = self._client.messages.create(**kwargs)<br>        except RateLimitError:<br>            logger.warning(&quot;anthropic_rate_limited&quot;)<br>            raise   # caller decides: backoff, queue, or fall back<br>        except (APIConnectionError, APIError) as e:<br>            logger.error(&quot;anthropic_api_error&quot;, exc_info=True)<br>            raise<br> <br>        latency = int((time.perf_counter() - start) * 1000)<br>        text = &quot;&quot;.join(b.text for b in msg.content if b.type == &quot;text&quot;)<br> <br>        return LLMResponse(<br>            text=text, model=msg.model, provider=self.name,<br>            input_tokens=msg.usage.input_tokens,<br>            output_tokens=msg.usage.output_tokens,<br>            latency_ms=latency,<br>            stop_reason=msg.stop_reason or &quot;end_turn&quot;,<br>            metadata={&quot;id&quot;: msg.id},<br>        )</pre><p><strong>Read this with a production eye. </strong>Every design decision has a reason.</p><p>• <strong>The </strong>LLMResponse dataclass exists so your downstream code never touches vendor-specific objects. Swap Anthropic for OpenAI and nothing upstream changes.</p><p>• <strong>Token counts are first-class fields. </strong>Without them you cannot attribute cost to features, users, or requests.</p><p>• <strong>Latency is measured caller-side. </strong>Vendor clocks are not your clocks; round-trip time is what your users actually feel.</p><p>• <strong>Errors are typed. </strong>RateLimitError gets different treatment from APIConnectionError, which gets different treatment from generic API errors. The caller decides what to do with each.</p><p>• <strong>Rate limit exceptions are re-raised, not swallowed. </strong>The provider does not know whether you want to back off, queue, or fail over. The caller does.</p><h3>Production Gotchas</h3><pre>❌ NAIVE<br>What most teams write the first time:<br>import anthropic<br> <br># Hardcoded, checked into git.<br>client = anthropic.Anthropic(api_key=&quot;sk-ant-api03-abc123-LEAKED&quot;)<br> <br>def ask(prompt):<br>    r = client.messages.create(<br>        model=&quot;claude-3-opus&quot;,   # model ID no longer exists<br>        messages=[{&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: prompt}],<br>    )<br>    return r.content[0].text    # no error handling, no token count</pre><p>Every single line of that snippet will hurt you in production.</p><p>• <strong>Hardcoded API key. </strong>The moment the repo is shared, forked, or indexed by any secret-scanning tool, the key is compromised.</p><p>• <strong>Stale model identifier. </strong>claude-3-opus no longer exists. The call will fail and your users will see a 500.</p><p>• <strong>No timeout, no retry, no circuit breaker. </strong>A single rate limit event takes down the entire service.</p><p>• <strong>No token accounting. </strong>The first time you know your bill doubled is when the invoice arrives.</p><p>• <strong>No structured logging. </strong>When a response is wrong, you have no way to reproduce it.</p><pre>✅ PRODUCTION<br>What the provider abstraction gives you by default:<br>• API keys from environment only<br>• Current, valid model identifiers verified at call time<br>• Typed errors separated by class, propagated to callers<br>• Every call tagged with provider, model, tokens, latency<br>• Vendor-specific response objects never leaking past the boundary<br>• Response shape containing every field needed for cost attribution</pre><h3>Summary</h3><p>Model selection is an architectural decision, not a shopping decision. In April 2026 the four families that matter are Anthropic’s Claude 4.x for reasoning and agents, OpenAI’s GPT-5.4 for multimodal and cache-heavy workloads, Meta’s Llama 4 for self-hosted compliance, and the cloud-managed Claude offerings on Bedrock, Vertex AI, and Foundry for enterprise guarantees.</p><p>Default to Sonnet 4.6. Upgrade to Opus 4.7 only where you have measured a real quality gap. Drop to Haiku 4.5 for classification and high-volume routing. Build a provider abstraction on day one so you can swap vendors without rewriting your application. Measure quality on your own workload, never on someone else’s benchmark. These five rules will save you more pain than every framework choice you make combined.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dd38cc326da2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Build Your First RAG Pipeline in 5 Minutes: The AI Environment Smoke Test Every Developer Needs]]></title>
            <link>https://medium.com/@usamanawaz789/build-your-first-rag-pipeline-in-5-minutes-the-ai-environment-smoke-test-every-developer-needs-259a940b55e9?source=rss-3cd12dbc6d59------2</link>
            <guid isPermaLink="false">https://medium.com/p/259a940b55e9</guid>
            <category><![CDATA[rags]]></category>
            <category><![CDATA[claude]]></category>
            <category><![CDATA[chromadb]]></category>
            <category><![CDATA[langchain]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Usama Nawaz]]></dc:creator>
            <pubDate>Fri, 20 Mar 2026 06:01:00 GMT</pubDate>
            <atom:updated>2026-03-20T06:01:00.869Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*61g1KH-reUCA2it9tGeV6w.png" /></figure><p>Four hours. That is how long I spent debugging a retrieval pipeline before realizing the root cause was a missing environment variable. The code compiled. The imports resolved. But the API key for Claude was not loaded, and the error surfaced three layers deep as a generic HTTP exception that pointed nowhere useful. A 30 second end-to-end validation would have caught it before I wrote a single line of feature code.</p><p>If you are setting up an AI development environment for production work, this article shows you how to build a minimal RAG pipeline that validates every tool in your chain: package installation, API authentication, vector database indexing, embedding generation, retrieval, and LLM response generation. All in a single Python script that runs in under a minute.</p><h3>The Problem</h3><p>A modern AI development environment consists of at least six interdependent components. A Python environment manager (uv or Poetry) handles packages. Environment variables store API credentials. A vector database (ChromaDB, FAISS, or pgvector) stores embeddings. An orchestration layer (LangChain) wires the pipeline together. An embedding model converts text to vectors. And an LLM provider (Anthropic, OpenAI, or a self-hosted model) generates responses.</p><p>Each component has its own installation process, configuration requirements, and failure modes. Testing them individually tells you nothing about whether they work together. The failure point is almost always at the boundary between components: a serialization mismatch between the splitter and the vector store, an incompatible embedding dimension, or an environment variable that loads in your shell but not in your Python process.</p><h3>The Solution: A 5-Stage Smoke Test Pipeline</h3><p>The smoke test implements the five stages of a RAG pipeline in discrete functions, each with structured logging that reports what happened and what to check if something goes wrong.</p><p>Stage 1 (Ingestion) loads a sample document. Using inline text instead of a file eliminates one failure vector. Stage 2 (Chunking) splits the text using LangChain’s RecursiveCharacterTextSplitter with small chunk sizes for fast validation. Stage 3 (Embedding) and Stage 4 (Indexing) happen together in ChromaDB, which accepts raw text and handles both steps internally using its default embedding model. Stage 5 (Query) assembles a LangChain LCEL chain that pipes retrieved context and a question through a Claude-powered prompt.</p><p>The key design decisions all serve the same goal: minimize variables. In-memory ChromaDB eliminates server configuration. Default embeddings eliminate model configuration. Inline text eliminates file system dependencies. What remains is pure pipeline wiring, which is exactly what you want to test.</p><h3>Code Walkthrough</h3><p>The critical section is the chain assembly. Using LangChain v1.2’s LCEL syntax:</p><pre>retriever = vectorstore.as_retriever(search_kwargs={&quot;k&quot;: 3})<br> <br>llm = ChatAnthropic(<br>    model=&quot;claude-sonnet-4-20250514&quot;,<br>    max_tokens=1024,<br>    temperature=0.1,<br>)<br> <br>chain = (<br>    {&quot;context&quot;: retriever | format_docs, &quot;question&quot;: RunnablePassthrough()}<br>    | prompt<br>    | llm<br>)</pre><p>This pattern replaces the deprecated ConversationalRetrievalChain from LangChain 0.x. The pipe syntax is composable, testable, and the current standard in production LangChain applications. The dictionary on the first line maps retriever output to the context template variable and passes the raw question through unchanged.</p><p>Environment validation at the top of the script is equally important. Checking for the API key before running any pipeline logic follows the fail-fast principle: if a prerequisite is missing, report it immediately and exit, rather than letting the failure cascade through multiple stages before surfacing as an ambiguous error.</p><h3>Production Gotchas</h3><p>This smoke test deliberately ignores production concerns. In a real system, you would add retry logic with exponential backoff on every API call (Chapter 2). You would use a persistent vector store with proper health checks (Section 1.6 showed ChromaDB in Docker). You would track token usage and cost per query (Chapter 13). And you would evaluate answer quality with automated metrics rather than eyeballing the response (Chapter 12).</p><p>One non-obvious gotcha: ChromaDB’s default embedding model (all-MiniLM-L6-v2) generates 384-dimensional vectors. If you later switch to OpenAI’s text-embedding-3-small (1536 dimensions) or Cohere’s embed-v3 (1024 dimensions), you cannot mix them in the same collection. The embedding model is an architectural decision locked in at index creation time. Chapter 5 covers this in detail.</p><h3>Summary</h3><p>A smoke test validates that your AI environment’s components work together, not just individually. Structure the test as discrete functions mirroring your production pipeline architecture. Fail fast on missing prerequisites like API keys. Use the simplest possible configuration (in-memory vector store, inline documents, default embeddings) to isolate wiring issues from architectural decisions. When the test passes, you have confidence that your environment is ready for real feature development.</p><blockquote><strong>Version Note</strong></blockquote><blockquote>This example uses LangChain v1.2.12, langchain-anthropic v1.3.4, and ChromaDB v1.5.5.</blockquote><blockquote>Always check the official docs for the latest API.</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=259a940b55e9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Set Up FAISS, ChromaDB, and pgvector for Local AI Development in 2026]]></title>
            <link>https://medium.com/@usamanawaz789/how-to-set-up-faiss-chromadb-and-pgvector-for-local-ai-development-in-2026-131145ee7ade?source=rss-3cd12dbc6d59------2</link>
            <guid isPermaLink="false">https://medium.com/p/131145ee7ade</guid>
            <category><![CDATA[chromadb]]></category>
            <category><![CDATA[vector-database]]></category>
            <category><![CDATA[faiss]]></category>
            <category><![CDATA[ai-engineering]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Usama Nawaz]]></dc:creator>
            <pubDate>Wed, 18 Mar 2026 06:01:00 GMT</pubDate>
            <atom:updated>2026-03-18T06:01:00.683Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*phQtkgRVJ62JP7hLsYwoZg.png" /></figure><p>A developer on my team spent three days debugging a retrieval quality issue in our RAG pipeline. Every test query hit a cloud vector store. Every re index uploaded embeddings over the network. The total cost of that debugging session was over $400 in API charges. The actual bug was a chunking function that split paragraphs mid sentence. A local vector store would have caught it in an afternoon at zero cost.</p><h3>The Problem</h3><p>Most AI engineering tutorials skip local vector database setup entirely. They walk you through creating a Pinecone account, generating an API key, and querying a cloud endpoint. This works for a demo, but it creates real friction during development. Every iteration on your chunking strategy, embedding model, or retrieval parameters requires network round trips and accumulates cloud costs. Your CI/CD pipeline becomes dependent on external services, making tests slow and flaky.</p><p>Local vector databases solve all of these problems. They give you the same core functionality (store vectors, search by similarity) without network latency, API rate limits, or cloud bills. The three tools that cover the production spectrum are FAISS, ChromaDB, and pgvector.</p><h3>The Solution: Three Vector Stores for Different Needs</h3><h3>FAISS: Maximum Speed, Minimum Abstraction</h3><p>FAISS (v1.14.1) from Meta AI Research is the performance baseline for vector similarity search. It is a C++ library with Python bindings that operates entirely in memory. Install it with pip install faiss-cpu and you get access to multiple index types: exact search with IndexFlatL2, approximate search with IndexIVFFlat and IndexHNSWFlat, and quantized indexes for memory efficiency.</p><p>The key limitation is that FAISS is a search library, not a database. It does not store your original documents or metadata. You maintain a separate data structure that maps FAISS index positions to your source content. This is fine for batch pipelines where you rebuild the index on every run, but it requires discipline for long running applications where the index and metadata must stay synchronized.</p><h3>ChromaDB: The Complete Developer Experience</h3><p>ChromaDB (v1.5.5, released March 2026) is purpose built for AI application development. It combines vector storage, metadata management, and optional automatic embedding in a single package. The PersistentClient writes indexed data to disk, so your documents survive application restarts. The Client constructor creates a purely in memory instance for tests.</p><p>ChromaDB collections support metadata filtering with operators like $contains, $regex, and standard comparison operators. This lets you combine semantic search with structured queries: “Find documents similar to this query that belong to category X and were created after date Y.” This is not a toy feature. This is the exact query pattern that production RAG systems use daily.</p><p>For teams that want to mirror production architectures during development, ChromaDB also runs as a standalone server. Pull the Docker image (chromadb/chroma:1.5.5) and multiple services can share the same vector store, just as they would in a deployed environment.</p><h3>pgvector: Vector Search Meets PostgreSQL</h3><p>pgvector (v0.8.2, February 2026) adds a native VECTOR data type to PostgreSQL. If your application already uses Postgres for relational data, pgvector means you do not need a separate vector store at all. Embeddings, documents, metadata, and user data coexist in one database with one connection pool and one backup strategy.</p><p>Run it locally with Docker: docker pull pgvector/pgvector:pg18. Enable the extension with CREATE EXTENSION vector, create a table with a VECTOR(1536) column, and add an HNSW index for fast approximate search. Queries use standard PostgreSQL syntax with custom distance operators: ORDER BY embedding &lt;=&gt; query_vector for cosine distance.</p><h3>Code Walkthrough</h3><p>Here is FAISS at the API level. Notice how minimal it is: create an index, add vectors, search. No server, no config.</p><pre>import numpy as np<br>import faiss<br><br># Create 1000 random vectors with 1536 dimensions<br>dimension = 1536<br>vectors = np.random.random((1000, dimension)).astype(&quot;float32&quot;)<br><br># Build an exact search index<br>index = faiss.IndexFlatL2(dimension)<br>index.add(vectors)<br><br># Search for the 5 nearest neighbors<br>query = np.random.random((1, dimension)).astype(&quot;float32&quot;)<br>distances, indices = index.search(query, k=5)<br><br># Persist to disk<br>faiss.write_index(index, &quot;my_index.faiss&quot;)</pre><p>ChromaDB requires even less code and handles embedding, persistence, and metadata automatically:</p><pre>import chromadb<br><br># Persistent client — data survives restarts<br>client = chromadb.PersistentClient(path=&quot;./chroma_db&quot;)<br><br>collection = client.get_or_create_collection(<br>    name=&quot;dev_documents&quot;,<br>    metadata={&quot;hnsw:space&quot;: &quot;cosine&quot;} <br>)<br><br># Add documents — ChromaDB handles embedding<br>collection.add(<br>    documents=[&quot;FAISS is optimized for in-memory search&quot;,<br>               &quot;pgvector adds vectors to PostgreSQL&quot;],<br>    metadatas=[{&quot;category&quot;: &quot;search&quot;},<br>              {&quot;category&quot;: &quot;database&quot;}],<br>    ids=[&quot;doc1&quot;, &quot;doc2&quot;]<br>)<br><br># Query with metadata filtering<br>results = collection.query(<br>    query_texts=[&quot;Which tool works with PostgreSQL?&quot;],<br>    n_results=2,<br>    where={&quot;category&quot;: &quot;database&quot;}<br>)</pre><p>For pgvector, the setup is Docker plus SQL. Here is the schema and a hybrid query:</p><pre>-- Enable the extension<br>CREATE EXTENSION IF NOT EXISTS vector;<br><br>CREATE TABLE documents (<br>  id BIGSERIAL PRIMARY KEY,<br>  content TEXT NOT NULL,<br>  embedding VECTOR(1536),<br>  metadata JSONB,<br>  created_at TIMESTAMPTZ DEFAULT NOW()<br>);<br><br>-- HNSW index for fast approximate search<br>CREATE INDEX ON documents<br>  USING hnsw (embedding vector_cosine_ops)<br>  WITH (m = 16, ef_construction = 64);<br><br>-- Hybrid query: vector similarity + metadata filter<br>SELECT id, content,<br>       embedding &lt;=&gt; $1::vector AS distance<br>FROM documents<br>WHERE metadata-&gt;&gt;&#39;category&#39; = &#39;technical&#39;<br>  AND created_at &gt; &#39;2025-01-01&#39;<br>ORDER BY embedding &lt;=&gt; $1::vector<br>LIMIT 10;</pre><h3>Production Gotchas</h3><p><strong>FAISS index and metadata desynchronization. </strong>FAISS assigns sequential integer IDs to vectors. If you delete a document from your metadata store but not from the FAISS index (or vice versa), your search results will point to the wrong documents. The production pattern is to rebuild the index from your source of truth rather than attempting incremental deletes.</p><p><strong>ChromaDB default embedding model. </strong>ChromaDB uses a default embedding function when you add raw text without specifying one. This default may change between versions. For reproducible results, always specify your embedding function explicitly. In production, you should generate embeddings outside of ChromaDB using the same model you use for query embedding.</p><p><strong>pgvector HNSW tuning. </strong>The default HNSW parameters (m=16, ef_construction=64) work well for development but may not be optimal for your production dataset. Higher values improve recall at the cost of memory and index build time. Additionally, set ef_search at query time (via SET hnsw.ef_search = 100) to control the speed vs. recall tradeoff for queries.</p><h3>Other Local Capable Vector Databases</h3><p>FAISS, ChromaDB, and pgvector cover the three foundational patterns (library, embedded database, database extension), but several other production grade options also run locally. <strong>Weaviate</strong> (v1.36) is a Go based vector database with built in vectorizer modules and a GraphQL API. <strong>Qdrant</strong>, written in Rust, is optimized for fast filtered vector search with minimal memory overhead. <strong>Milvus</strong> (v2.6) separates compute and storage for billion scale workloads. All three run locally via Docker.</p><p>One notable absence: <strong>Pinecone</strong> is a cloud only managed service with no self hosted option. It is an excellent production vector store, but it does not serve the local development purpose this article addresses. Production vector store comparisons, including Pinecone, Weaviate, Qdrant, and Milvus, are covered in depth in Chapter 5 of this series.</p><h3>Summary</h3><p>Local vector databases are a non negotiable part of a productive AI development environment. FAISS gives you raw speed for batch workloads. ChromaDB gives you the fastest path to a working prototype with persistence and metadata. pgvector gives you vector search without adding infrastructure if you already use PostgreSQL. Set up at least one of these before you write your first RAG query, and keep your cloud vector store for production traffic only.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=131145ee7ade" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Configure Ruff, mypy, and Pre-commit for Production AI Python Projects]]></title>
            <link>https://medium.com/@usamanawaz789/how-to-configure-ruff-mypy-and-pre-commit-for-production-ai-python-projects-1b3fc56d3d4c?source=rss-3cd12dbc6d59------2</link>
            <guid isPermaLink="false">https://medium.com/p/1b3fc56d3d4c</guid>
            <category><![CDATA[mypy]]></category>
            <category><![CDATA[pre-commit]]></category>
            <category><![CDATA[document-processing]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[ruff]]></category>
            <dc:creator><![CDATA[Usama Nawaz]]></dc:creator>
            <pubDate>Fri, 13 Mar 2026 07:01:02 GMT</pubDate>
            <atom:updated>2026-03-13T07:01:02.413Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-3He94LzEZvUkiMjwgsqtw.png" /></figure><p>A production outage traced to a single untyped function. The function parsed LLM responses and returned <em>None </em>on schema mismatches. No type annotation. No linting. The caller assumed a <em>dict</em> return. It worked for three weeks because the LLM cooperated. Then it didn’t. Four hours to find, five minutes to fix. A type checker would have flagged it before the code ever shipped.</p><h3>The Problem</h3><p>AI codebases face a unique combination of challenges that make static analysis tools more valuable than in traditional web development. LLM responses are dynamically structured, even when you request JSON output. Vector store queries return complex nested objects. Async pipelines create subtle type mismatches when developers forget to await coroutines. Import statements proliferate as files integrate multiple AI frameworks, LLM providers, and utility libraries.</p><p>Without automated linting and type checking, these issues surface as runtime errors in production. Without automated formatting, they surface as noisy diffs and merge conflicts that slow down code reviews.</p><h3>The Solution: A Unified Toolchain</h3><p>The modern Python quality stack has consolidated around three tools. Ruff handles both linting and formatting, replacing five or more legacy tools with a single Rust powered binary. mypy provides static type checking that catches type mismatches before runtime. Pre-commit automates both tools to run on every git commit.</p><p>Ruff (v0.15 as of early 2026) implements over 800 lint rules and a Black compatible formatter. It runs 10 to 100 times faster than the tools it replaces. This speed is not just convenient. It changes developer behavior. When linting takes 30 seconds, developers run it only in CI. When it takes 0.4 seconds, they run it on every save. Instant feedback loops produce cleaner code.</p><p>mypy (v1.19) reads type annotations and catches errors without executing code. For AI projects, the highest value annotations are on functions that handle LLM responses, vector store results, and pipeline orchestration. Strict mode on these core modules catches the bugs that are most expensive to debug in production.</p><h3>Code Walkthrough</h3><p>The complete configuration lives in two files. First, your pyproject.toml defines both Ruff and mypy settings:</p><pre># pyproject.toml — Ruff configuration<br>[tool.ruff]<br>target-version = &quot;py312&quot;<br>line-length = 88<br><br>[tool.ruff.lint]<br>select = [&quot;E&quot;, &quot;W&quot;, &quot;F&quot;, &quot;I&quot;, &quot;B&quot;, &quot;UP&quot;, &quot;S&quot;, &quot;SIM&quot;, &quot;RUF&quot;]<br>ignore = [&quot;E501&quot;, &quot;S101&quot;]<br><br>[tool.ruff.lint.per-file-ignores]<br>&quot;tests/**/*.py&quot; = [&quot;S101&quot;, &quot;S106&quot;]<br>&quot;__init__.py&quot; = [&quot;F401&quot;]<br><br># mypy configuration — graduated strictness<br>[tool.mypy]<br>python_version = &quot;3.12&quot;<br>disallow_untyped_defs = true<br>warn_return_any = true<br><br>[[tool.mypy.overrides]]<br>module = [&quot;app.services.llm.*&quot;, &quot;app.models.*&quot;]<br>disallow_any_generics = true   # Strict on core modules<br><br>[[tool.mypy.overrides]]<br>module = [&quot;langchain_community.*&quot;, &quot;chromadb.*&quot;, &quot;crewai.*&quot;]<br>ignore_missing_imports = true  # AI libs without type stubs</pre><p>Second, your .pre-commit-config.yaml wires both tools into your git workflow:</p><pre># .pre-commit-config.yaml<br>repos:<br>  - repo: https://github.com/pre-commit/pre-commit-hooks<br>    rev: v6.0.0<br>    hooks:<br>      - id: trailing-whitespace<br>      - id: check-yaml<br>      - id: check-added-large-files<br>      args: [&quot; - maxkb=5000&quot;] # Block model artifacts<br>      - id: detect-private-key<br>  - repo: https://github.com/astral-sh/ruff-pre-commit<br>    rev: v0.15.3<br>    hooks:<br>      - id: ruff<br>      args: [&quot; - fix&quot;, &quot; - select&quot;, &quot;I&quot;]<br>      - id: ruff-format<br>  - repo: https://github.com/pre-commit/mirrors-mypy<br>    rev: v1.19.1<br>    hooks:<br>      - id: mypy<br>      additional_dependencies: [&quot;pydantic&gt;=2.0&quot;, &quot;types-requests&quot;]</pre><h3>Production Gotchas</h3><p>Several pitfalls specific to AI projects deserve attention when configuring these tools.</p><p>• <strong>Third party AI libraries without type stubs: </strong>Some AI and ML libraries do not ship type stubs. Configure mypy with per module overrides to ignore missing imports for these packages while maintaining strict checking on your own code.</p><p>• <strong>Mutable default arguments in pipeline functions: </strong>Enable Ruff’s B (bugbear) rule set. Functions with mutable defaults like def process(docs: list = []) are a common source of subtle bugs in document processing pipelines.</p><p>• <strong>Dynamic LLM response types: </strong>Use Pydantic v2 models as your return type annotations for LLM parsing functions. This gives both runtime validation and static type safety in a single pattern.</p><p>• <strong>Import sprawl across AI frameworks: </strong>Enable Ruff’s I (isort) rules to enforce deterministic import ordering. This eliminates merge conflicts from import reordering across team members.</p><h3>Summary</h3><p>Ruff, mypy, and pre-commit form the modern Python quality stack. Ruff replaces five legacy tools with one fast binary. mypy catches the type errors that AI codebases are uniquely prone to. Pre-commit makes both tools run automatically on every commit. Together, they create a quality layer that catches bugs before code review, lets reviewers focus on logic instead of style, and prevents the runtime type errors that plague dynamic AI systems. Configure them once, and they protect every commit your team makes.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1b3fc56d3d4c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Project Scaffolding Patterns for Production AI Services]]></title>
            <link>https://medium.com/@usamanawaz789/project-scaffolding-patterns-for-production-ai-services-47b51e37a153?source=rss-3cd12dbc6d59------2</link>
            <guid isPermaLink="false">https://medium.com/p/47b51e37a153</guid>
            <dc:creator><![CDATA[Usama Nawaz]]></dc:creator>
            <pubDate>Thu, 12 Mar 2026 06:01:00 GMT</pubDate>
            <atom:updated>2026-03-12T06:01:00.974Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nVnxNZcsyM1iU8fo6mZdaw.png" /></figure><h3>The Problem</h3><p>AI projects are structurally different from traditional web applications. They contain categories of code that standard Python templates never anticipated: prompt templates that evolve like code but behave like configuration, embedding pipelines that run offline while their outputs serve real time queries, agent definitions with their own tool registries and behavioral constraints, and evaluation datasets that live alongside but separate from unit tests.</p><p>Generic project scaffolding tools produce layouts optimized for CRUD applications. An AI project built on a generic template inevitably accumulates structural debt as prompts, chains, agent graphs, and retrieval logic get jammed into whichever directory seems least wrong at the time.</p><h3>The Solution: Three Archetypes</h3><p>Production AI projects follow one of three structural archetypes, each shaped by its primary workload.</p><p><strong>RAG applications </strong>demand a clean split between the ingestion path (batch document processing, embedding generation, vector store population) and the serving path (query handling, context retrieval, LLM generation). These two paths have different deployment schedules, different scaling profiles, and different failure modes. Structuring them as separate top-level modules within a shared repository enables independent deployment while preserving shared configuration and data models.</p><p><strong>Multi-agent systems </strong>organize around agent definitions, tool registries, and orchestration logic. Each agent gets its own module containing its prompt, tool bindings, and behavioral constraints. The orchestration layer that coordinates agents is a separate concern. Shared memory stores and inter-agent communication patterns have dedicated homes.</p><p><strong>API-backed AI services </strong>extend the familiar routers/services/models pattern with AI-specific layers: prompt management, LLM client abstraction, and evaluation modules. The architectural rule that matters most is keeping LangChain chains and agent graphs behind a service layer rather than inside endpoint handlers.</p><h3>Code Walkthrough: The Configuration Backbone</h3><p>Across all three archetypes, the configuration layer is where structural decisions become tangible. The following pattern uses Pydantic’s BaseSettings with composed sub-settings, SecretStr for API keys, and a cached factory function that ensures environment variables are read once at startup.</p><pre># src/config/settings.py<br>from functools import lru_cache<br>from pydantic_settings import BaseSettings<br>from pydantic import SecretStr, Field<br> <br>class LLMSettings(BaseSettings):<br>    anthropic_api_key: SecretStr = Field(...)<br>    default_model: str = &quot;claude-sonnet-4-6&quot;<br>    temperature: float = 0.2<br>    model_config = {&quot;env_prefix&quot;: &quot;LLM_&quot;}<br> <br>class AppSettings(BaseSettings):<br>    environment: str = &quot;development&quot;<br>    llm: LLMSettings = LLMSettings()<br>    model_config = {&quot;env_prefix&quot;: &quot;APP_&quot;}<br> <br>@lru_cache<br>def get_settings() -&gt; AppSettings:<br>    return AppSettings()</pre><p>Every service imports configuration through get_settings(). In tests, you clear the cache and set environment variables before each test. No monkeypatching, no global state mutation, no import-order dependencies.</p><h3>Production Gotchas</h3><p><strong>❌ Naive: </strong>All code in one main.py that grows to 2,000 lines. Prompts as string literals inside handler functions. Configuration via raw os.getenv() with no defaults or validation. Two developers cannot work on different features without merge conflicts.</p><p><strong>✅ Production: </strong>Modular layout with separate directories for config, services, prompts, routers, and evaluations. Typed configuration behind a single factory function. Prompts in dedicated template files. AI logic encapsulated in services that the API layer calls but does not contain.</p><p>The restructuring cost is always higher than starting organized. A clean layout on day one costs thirty minutes. Restructuring a six month old monolith costs two weeks.</p><h3>Summary</h3><p>AI projects need intentional folder structures that account for prompt management, ingestion and serving path separation, agent definitions, and evaluation datasets. Centralizing configuration behind Pydantic BaseSettings eliminates scattered environment reads. Keeping AI logic behind a service layer makes it testable and reusable. Adding an ARCHITECTURE.md file to the project root serves both AI coding tools and human developers.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=47b51e37a153" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Docker for AI Services: Multi-Stage Builds, Compose, and GPU Containers in Production]]></title>
            <link>https://medium.com/@usamanawaz789/docker-for-ai-services-multi-stage-builds-compose-and-gpu-containers-in-production-fa95098f7350?source=rss-3cd12dbc6d59------2</link>
            <guid isPermaLink="false">https://medium.com/p/fa95098f7350</guid>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[ai-engineering]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[devops]]></category>
            <dc:creator><![CDATA[Usama Nawaz]]></dc:creator>
            <pubDate>Wed, 11 Mar 2026 06:01:01 GMT</pubDate>
            <atom:updated>2026-03-11T06:01:01.042Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QOmOQDDVWYl8hqFWzCtBIA.png" /></figure><p>Last year I shipped an AI document processing service that worked flawlessly on three engineers’ laptops and failed catastrophically on its first cloud deployment. The service depended on Tesseract OCR, pdfplumber, and LangChain, and the Docker image was missing a single shared library that Tesseract needed at runtime. The error message was cryptic, the container restart loop was relentless, and the fix took four hours to diagnose. The root cause took ten seconds to fix: one line in the Dockerfile.</p><p>That failure taught me that Docker for AI services is a fundamentally different challenge than Docker for standard web applications. AI dependencies are heavier, more fragile, and more entangled with system libraries. This article covers the production Docker patterns I use on every AI project now.</p><h3>The Problem: AI Dependencies Are Not Normal Dependencies</h3><p>A typical Python web application depends on a web framework, a database driver, and maybe a handful of utility libraries. Total dependency weight: 50 to 100 MB. A typical AI application depends on LangChain (which pulls in dozens of transitive dependencies), a vector database client, an LLM SDK, potentially PyTorch or Transformers for local inference, and document processing libraries. Total dependency weight: 500 MB to 2 GB.</p><p>This difference changes every Docker decision you make. Image size matters more because you are pushing and pulling these images across networks during deployment. Build time matters more because a full pip install can take 5 to 10 minutes. And system-level dependencies matter more because packages like PyMuPDF, Tesseract, and pgvector have native C extensions that require specific libraries at both build time and runtime.</p><h3>The Solution: Multi-Stage Builds for AI Services</h3><p>The core pattern is a two-stage Dockerfile. The first stage (builder) includes compilers and development headers needed to build native extensions. It installs all Python dependencies into an isolated virtual environment. The second stage (runtime) starts from a clean slim image, copies only the pre-built virtual environment, and adds only the runtime system libraries. No compilers, no header files, no build artifacts.</p><h3>Production Dockerfile</h3><pre># Builder: compile native extensions here<br>FROM python:3.13-slim-trixie AS builder<br>WORKDIR /build<br>RUN apt-get update &amp;&amp; apt-get install -y - no-install-recommends \<br>build-essential gcc libpq-dev \<br>&amp;&amp; rm -rf /var/lib/apt/lists/*<br>COPY requirements.txt .<br>RUN python -m venv /opt/venv<br>ENV PATH=&quot;/opt/venv/bin:$PATH&quot;<br>RUN pip install - no-cache-dir -r requirements.txt<br># Runtime: clean image with only what runs<br>FROM python:3.13-slim-trixie AS runtime<br>RUN apt-get update &amp;&amp; apt-get install -y - no-install-recommends \<br>libpq5 curl &amp;&amp; rm -rf /var/lib/apt/lists/*<br>RUN useradd - create-home appuser<br>COPY - from=builder /opt/venv /opt/venv<br>ENV PATH=&quot;/opt/venv/bin:$PATH&quot; \<br>PYTHONDONTWRITEBYTECODE=1 \<br>PYTHONUNBUFFERED=1<br>WORKDIR /app<br>COPY . .<br>USER appuser<br>HEALTHCHECK - interval=30s - timeout=10s - retries=3 \<br>CMD curl -f http://localhost:8000/health || exit 1<br>EXPOSE 8000<br>CMD [&quot;uvicorn&quot;, &quot;app.main:app&quot;, &quot; - host&quot;, &quot;0.0.0.0&quot;, &quot; - port&quot;, &quot;8000&quot;]</pre><h3>Code Walkthrough</h3><p>The builder stage uses python:3.13-slim-trixie (Debian 13) as the base. Slim variants are preferred over Alpine for AI workloads because Alpine uses musl libc, which breaks prebuilt binary wheels for NumPy, SciPy, and most scientific computing packages. The apt-get install line adds only the compilers and headers needed for native extensions, then immediately cleans the package cache. Dependencies install into /opt/venv so they can be copied as a single directory.</p><p>The runtime stage starts fresh. It installs only runtime libraries (libpq5 for PostgreSQL connections, curl for health checks). A non-root user is created because running as root inside containers is a security anti-pattern. The virtual environment copies over from the builder, carrying all installed packages without any build tooling.</p><p>Three environment variables configure the Python runtime for production: PYTHONDONTWRITEBYTECODE prevents .pyc file creation (wasted disk I/O in ephemeral containers), PYTHONUNBUFFERED forces immediate log output (critical for container logging drivers), and the HEALTHCHECK gives orchestrators a reliable signal for readiness.</p><h3>Docker Compose for Local AI Stacks</h3><p>AI development environments typically need multiple services running together. A compose file that brings up your AI application alongside ChromaDB for vector search and Redis for LLM response caching gives you a production-like environment locally.</p><p>The critical detail is using depends_on with condition: service_healthy instead of plain depends_on. Without the health condition, Compose starts your service as soon as the dependency container’s process launches, not when the service inside that container is ready. For databases and vector stores that take several seconds to initialize, this causes intermittent startup crashes.</p><h3>Production Gotchas</h3><p>• <strong>Missing .dockerignore: </strong>AI project directories contain model weights, .git history, and vector database snapshots. Without .dockerignore, builds are slow and images may contain secrets.</p><p>• <strong>Layer order mistakes: </strong>Copying code before dependencies means every code change triggers a full pip install. Always copy the requirements file and install first.</p><p>• <strong>No health checks: </strong>Orchestrators cannot distinguish a running but unresponsive container from a healthy one without explicit HEALTHCHECK directives.</p><p>• <strong>Using Alpine for AI: </strong>musl libc breaks prebuilt wheels. You end up compiling from source, which adds 10 to 20 minutes to builds and makes images larger, not smaller.</p><h3>Summary</h3><p>Docker for AI services requires more deliberate architecture than standard web containers. Multi-stage builds keep images lean despite heavy scientific dependencies. Non-root users and health checks are production table stakes. Compose with health-aware dependency ordering prevents the intermittent startup failures that waste hours of debugging time. And a .dockerignore file is the single cheapest improvement you can make to both build speed and security.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fa95098f7350" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Production Secrets Management for AI Services: Pydantic Settings, .env Files, and Cloud Vaults]]></title>
            <link>https://medium.com/@usamanawaz789/production-secrets-management-for-ai-services-pydantic-settings-env-files-and-cloud-vaults-c535c231940b?source=rss-3cd12dbc6d59------2</link>
            <guid isPermaLink="false">https://medium.com/p/c535c231940b</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[cloud-security]]></category>
            <category><![CDATA[pydantic]]></category>
            <category><![CDATA[ai-engineering]]></category>
            <category><![CDATA[management-secrets]]></category>
            <dc:creator><![CDATA[Usama Nawaz]]></dc:creator>
            <pubDate>Tue, 10 Mar 2026 06:01:00 GMT</pubDate>
            <atom:updated>2026-03-10T06:01:00.577Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YXFq_zHfnoqH1dyo90neGw.png" /></figure><p>A developer on your team pushes a commit. Somewhere in a config file, an Anthropic API key sits in plain text. GitHub’s automated secret scanner catches it in minutes, revokes the token, and sends an alert. The lucky version of this story ends there. The unlucky version involves unauthorized token consumption, a forensic audit of every system that key could access, and an incident report explaining how it happened.</p><p>AI projects are especially vulnerable to this pattern because they depend on a higher density of API keys than typical web services. A production RAG pipeline might require keys for an LLM provider, an embedding service, a vector database, a relational database, and an object storage bucket. That is five secrets for one service, and every one of them is a potential exposure point.</p><h3>The Problem</h3><p>Hardcoded secrets are the most common security failure in AI codebases. But the problem extends beyond simple exposure. Without validation, a missing API key silently becomes None, producing confusing NoneType errors deep in a call stack during a user request. Without masking, a debug log statement dumps every credential to your log aggregation service. Without a consistent loading pattern, each service on the team invents its own configuration approach, making security audits a per-service effort.</p><h3>The Solution: Layered Secrets Management</h3><p>The production pattern is a three layer approach. At the foundation, the twelve factor app principle requires that every configurable value lives in environment variables. In the development layer, python-dotenv (v1.2.2) loads a local .env file into the environment. In the validation layer, Pydantic Settings (v2.13.1) wraps every environment variable in a typed, validated model with SecretStr masking for credentials.</p><p>In production, cloud secret managers (AWS Secrets Manager, GCP Secret Manager, OCI Vault) inject secrets as environment variables before the container starts. Pydantic reads from the environment regardless of the source, so your code works identically across local, staging, and production.</p><h3>Code Walkthrough</h3><p>The core implementation is a Settings class inheriting from BaseSettings. Each field declares its type, and Pydantic validates all values on instantiation. SecretStr fields mask credentials in logs and repr output. Field validators enforce business rules like temperature ranges. A singleton function ensures validation happens once at startup.</p><blockquote>Define your settings class with SettingsConfigDict(env_file=“.env”) to load from the .env file in development. Use SecretStr for every credential field. Add @field_validator decorators for domain specific constraints. Then expose a get_settings() function that creates the settings instance once and caches it for the application’s lifetime.</blockquote><p>When passing a SecretStr value to an API client, call .get_secret_value() to unwrap the actual string. This explicit call serves as a visual marker in code reviews that a secret is being accessed.</p><h3>Production Gotchas</h3><p><strong>Missing .gitignore entry: </strong>A .env file without a .gitignore entry will be committed to version control on the first git add command. Once in Git history, the secret persists even after the file is deleted. Add .env to .gitignore on day one of every project.</p><p><strong>Override behavior: </strong>By default, python-dotenv does not override existing environment variables. This is correct for production, where the cloud platform sets variables before the .env file is read. But it catches developers off guard when editing .env does not change behavior because the shell already exports the same variable. Restart the process after .env changes.</p><p><strong>Shared .env with production keys: </strong>If developers use production credentials locally, a single laptop compromise exposes the production environment. Use separate .env files per environment and restrict production secrets to the cloud secret manager exclusively.</p><p><strong>No pre-commit scanning: </strong>Even with .gitignore, secrets can end up in unexpected files like Jupyter notebooks, test fixtures, or configuration YAML. Use the detect-secrets pre-commit hook to scan all staged files for credential patterns before they reach the repository.</p><h3>Summary</h3><p>Secrets management for AI services is a layered discipline. Store configuration in the environment following the twelve factor principle. Load locally with python-dotenv. Validate and mask with Pydantic Settings and SecretStr. Deploy with cloud secret managers that inject variables before your container starts. Add pre-commit scanning with detect-secrets and schedule quarterly key rotation. Each layer reinforces the others, creating a security posture where no single failure exposes your credentials.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c535c231940b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Git Workflows for AI Projects: Branching, LFS, and Commit Strategies That Scale]]></title>
            <link>https://medium.com/@usamanawaz789/git-workflows-for-ai-projects-branching-lfs-and-commit-strategies-that-scale-34adf895642b?source=rss-3cd12dbc6d59------2</link>
            <guid isPermaLink="false">https://medium.com/p/34adf895642b</guid>
            <category><![CDATA[github]]></category>
            <category><![CDATA[git]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Usama Nawaz]]></dc:creator>
            <pubDate>Mon, 09 Mar 2026 06:01:00 GMT</pubDate>
            <atom:updated>2026-03-09T06:01:00.733Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tQYla7H802ee40FPKU24tA.png" /></figure><p>Last year, a team I worked with spent two full days tracking down a retrieval quality regression. The root cause turned out to be an accidental merge from an experiment branch that changed the chunking configuration from 512 tokens with 50 token overlap to 256 tokens with zero overlap. The commit message read: “misc updates.” There was no branch naming convention, no structured commit format, and no pre-commit guard to flag the change. Two days of engineering time, burned because version control was treated as an afterthought.</p><h3>The Problem</h3><p>AI repositories are not like traditional application repositories. They accumulate model weights measured in gigabytes, experiment configurations that drift across branches, notebook files that generate merge conflicts on every execution, and evaluation outputs that nobody remembers to clean up. Standard Git practices, designed for text files and small assets, collapse under these conditions. The result is repositories that take an hour to clone, branch lists that run to dozens of stale entries, and commit histories where nobody can trace when or why a critical configuration changed.</p><p>The fix is not complicated, but it does require deliberate planning from day one. Most teams discover this need only after the pain has already accumulated.</p><h3>The Solution: An AI-Aware Git Workflow</h3><h3>Experiment Branch Namespacing</h3><p>Use a modified trunk based approach where the main branch is always deployable, feature branches follow standard short lived patterns, and experiment branches get their own namespace. Name experiments descriptively: experiment/embedding-model-swap, experiment/chunking-512-overlap-50. Experiments never merge directly into main. When an experiment succeeds, extract the winning configuration into a clean feature branch with proper review and tests.</p><h3>Production .gitignore Patterns</h3><p>A production AI .gitignore needs categories that standard templates miss: model artifacts (*.pt, *.safetensors, *.onnx), data artifacts (data/raw/, *.parquet), embedding caches (*.faiss, chroma_db/), notebook checkpoints (.ipynb_checkpoints/), evaluation outputs (eval_results/, wandb/), and infrastructure state (*.tfstate, .terraform/). Set this up before the first commit. Retroactive cleanup is painful and permanent.</p><h3>Git LFS From Day One</h3><p>Git LFS v3.7.x replaces large binaries with pointer files while storing actual content on a separate server. Declare tracking patterns in .gitattributes before committing any large files. Common patterns for AI repos include *.pt, *.safetensors, *.onnx, and *.parquet. The critical mistake teams make is committing large files first and configuring LFS afterward. At that point, the file is baked into Git history, and fixing it requires history rewriting with git lfs migrate.</p><h3>AI-Specific Commit Conventions</h3><p>Extend conventional commits with AI specific type prefixes: prompt() for prompt template changes, model() for model configuration changes, eval() for evaluation updates, and data() for pipeline or dataset modifications. A commit that reads data(chunking): switch to semantic chunking with sentence boundaries is searchable, debuggable, and tells the full story at a glance.</p><h3>Production Gotchas</h3><p><strong>❌ Naive Approach</strong></p><p>No .gitignore for AI artifacts. No LFS. Flat branch naming. Generic commit messages. No pre-commit hooks. “We will clean it up later.”</p><p>Result: 12 GB repository, 45 minute clone times, untraceable configuration changes, committed API keys, and a deployment failure caused by an accidental experiment merge.</p><p><strong>✅ Production Approach</strong></p><p>Comprehensive .gitignore from day one. LFS tracking in .gitattributes before first large file commit. Experiment branch namespace. AI-specific commit prefixes. Pre-commit hooks with detect-secrets, nbstripout, and check-added-large-files.</p><p>Result: Fast clones, clean history, searchable commits, zero secret leaks, and experiment traceability that saves debugging hours every month.</p><h3>Summary</h3><p>Version control for AI projects is not optional infrastructure. It is the foundation that determines whether your team can trace changes, reproduce results, onboard new members quickly, and deploy with confidence. Set up .gitignore, LFS tracking, branch namespacing, commit conventions, and pre-commit hooks at the start of every AI project. The ten minutes of setup prevents weeks of accumulated pain.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=34adf895642b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Python Environment Management for Production AI Projects]]></title>
            <link>https://medium.com/@usamanawaz789/python-environment-management-for-production-ai-projects-8370803f50dd?source=rss-3cd12dbc6d59------2</link>
            <guid isPermaLink="false">https://medium.com/p/8370803f50dd</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Usama Nawaz]]></dc:creator>
            <pubDate>Sun, 08 Mar 2026 06:31:00 GMT</pubDate>
            <atom:updated>2026-03-08T06:31:00.547Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sOz5nF6NcmHFtzLCrqFcFw.png" /></figure><p>A production RAG pipeline returns different results on two machines running identical code. A model training job fails in CI despite passing locally. A deployment rolls back because a tokenizer library updated between the staging and production builds. Every one of these failures traces back to the same root cause: unmanaged Python environments.</p><h3>The Problem</h3><p>AI projects carry dependency profiles that are fundamentally different from typical web applications. They depend on compiled C extensions with system-level library requirements. They require specific Python versions certified by frameworks like PyTorch and TensorFlow. They use rapidly evolving libraries (LangChain, LlamaIndex, CrewAI) that push breaking changes across minor releases. And they often need GPU-specific package builds that differ from the default PyPI distributions.</p><p>A loose requirements.txt (the kind generated by pip freeze) captures a snapshot that decays immediately. Two builds from the same file, separated by a week, can produce environments with different transitive dependencies and different behavior. In AI work, “different behavior” can mean different model outputs, different retrieval results, or different evaluation scores, with no error message to alert you.</p><h3>The Solution</h3><p>Production-grade Python environment management for AI projects uses three layers working together.</p><p>Layer one: Python version management with pyenv. Install pyenv, then run pyenv install and pyenv local to set a project-specific Python version. This creates a .python-version file that belongs in version control. Every developer and CI runner that uses pyenv will automatically use the correct Python version for the project.</p><p>Layer two: virtual environment isolation. Use python -m venv .venv to create an isolated environment in your project directory. Activate it before installing anything. This ensures packages install into the project’s .venv directory and never leak into your system Python.</p><p>Layer three: dependency resolution with Poetry. Poetry replaces pip and requirements.txt with a proper resolver. Your pyproject.toml declares direct dependencies with flexible version ranges. The poetry lock command resolves the entire transitive dependency tree and writes exact versions into poetry.lock. Running poetry install anywhere reproduces the identical environment.</p><h3>Dependency Pinning for AI Stacks</h3><p>Not all dependencies should be pinned the same way. Use a tiered strategy. Pin core ML frameworks (PyTorch, TensorFlow, transformers) to exact versions, since even patch releases can change numerical outputs. Pin application frameworks (LangChain, FastAPI, LlamaIndex) to compatible release ranges with the tilde operator. Leave utility libraries at broader ranges with the caret operator. This balances stability where behavior sensitivity is highest with flexibility where updates carry low risk.</p><h3>Production Gotchas</h3><p>GPU dependencies are the most common silent failure. PyTorch’s default pip installation gives you a CPU-only build. The code runs, the tests pass, but production inference is 50x slower than it should be. The fix is to declare the CUDA-specific source repository in your pyproject.toml and validate GPU availability in CI.</p><p>Another gotcha: stale CI caches. When your CI provider caches the virtual environment between runs, it can accumulate packages from old dependency versions that should have been removed. Schedule periodic full rebuilds, or hash your poetry.lock file into the cache key so the cache invalidates whenever dependencies change.</p><p>Finally, treat dependency changes like code changes. Every modification to pyproject.toml or poetry.lock goes through pull request review. Run poetry check in CI to verify consistency. Rebuild environments from scratch periodically to catch drift that incremental installs hide.</p><h3>Summary</h3><p>Python environment management is not a one-time setup task. For AI projects with heavy native dependencies, compiled binaries, and rapidly evolving frameworks, it is ongoing infrastructure that directly affects reproducibility, debugging speed, and deployment reliability. Lock your Python version with pyenv, isolate with virtual environments, resolve dependencies with Poetry, pin strategically by risk tier, and validate GPU builds in CI. The time investment is small. The debugging time it saves is enormous.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8370803f50dd" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>