<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0"><channel><title><![CDATA[Kevyn Franco]]></title><description><![CDATA[Kevyn Franco]]></description><link>https://kevynfranco.hashnode.dev</link><generator>RSS for Node</generator><lastBuildDate>Sat, 28 Nov 2026 00:33:27 GMT</lastBuildDate><atom:link href="https://kevynfranco.hashnode.dev/rss.xml" rel="self" type="application/rss+xml"/><language><![CDATA[en]]></language><ttl>60</ttl><item><title><![CDATA[From Notebook to Production: Hardening LLM Features in FastAPI]]></title><description><![CDATA[A field checklist for evals, guardrails, observability, fallbacks, and cost controls]]></description><link>https://kevynfranco.hashnode.dev/from-notebook-to-production-hardening-llm-features-in-fastapi</link><guid isPermaLink="true">https://kevynfranco.hashnode.dev/from-notebook-to-production-hardening-llm-features-in-fastapi</guid><category><![CDATA[Python]]></category><category><![CDATA[FastAPI]]></category><category><![CDATA[AI]]></category><category><![CDATA[llm]]></category><category><![CDATA[fast api]]></category><category><![CDATA[AI]]></category><category><![CDATA[LLM's ]]></category><dc:creator><![CDATA[Kevyn Franco]]></dc:creator><pubDate>Tue, 24 Nov 2026 06:31:51 GMT</pubDate><content:encoded><![CDATA[<p>A notebook proves that an LLM feature <em>can</em> work. Production asks a different question: does it keep working when the prompt changes? When the model goes down? When a user pastes 40,000 characters into the chat box? Someone will ask at 2 a.m. why the answers changed. You will want a good answer.</p>
<p>I run a FastAPI shop for production AI systems. This is the checklist I apply before an LLM feature goes live. It assumes Python, an OpenAI-compatible API or similar, and a team that will still own the feature after the launch dust settles. The original write-up lives on <a href="http://DEV.to">DEV.to</a>; this version walks the build order I follow in the field.</p>
<h2>1. Evals come first, before any other hardening</h2>
<p>If you only change one habit this quarter, make it this one. Everything else on the list protects the system; evals protect the behavior your users care about.</p>
<p>"Feels better" is not a measurement, and prompt changes are silent quality killers. Before any prompt or model change ships:</p>
<ul>
<li>Build a golden dataset from real traffic: 50 to 200 real inputs with the outputs you accept, labeled by hand. Quality beats size at this scale.</li>
<li>Score with code. Extraction and classification respond well to exact match or JSON-schema validation. Open-ended text needs a model-graded rubric, but keep the rubric narrow and the pass threshold explicit.</li>
<li>Run evals in CI on every prompt or model change, and block the merge when the score drops. Most "we tweaked the prompt and quality silently degraded" incidents die here.</li>
<li>Track scores over time. A JSON file committed next to the code, or a table in your observability tool, is enough.</li>
</ul>
<h2>2. Constrain the model's output</h2>
<p>Free-form text from a model is a liability inside a typed backend. Constrain it hard:</p>
<ul>
<li>Force structured output. Use JSON mode or function calling and validate with a Pydantic model. If validation fails, retry once with the error included, then fail loudly.</li>
<li>Validate inputs before the call. Length limits, allowlists, basic PII detection. A 40,000-character paste belongs in object storage, outside your context window.</li>
<li>Treat retrieved and user content as untrusted. Anything from a user or a web page can try to override your instructions. Keep system instructions and retrieved data clearly separated, and never let retrieved text decide which tools the model may call.</li>
<li>Set hard output limits. <code>max_tokens</code> caps runaway generations and gives you a predictable worst-case cost per call.</li>
</ul>
<h2>3. Build observability for the 2 a.m. incident</h2>
<p>When a user reports "the AI gave a weird answer yesterday," you need four answers fast. What went out, what came back, which model and prompt version produced it, and what it cost.</p>
<ul>
<li>Trace the full request. OpenTelemetry-based tools (OpenLLMetry, Langfuse, LangSmith) record prompts, completions, token counts, and latency per span. Wire the trace ID into your logs so support can jump from a ticket to the exact call.</li>
<li>Log model, prompt version, and parameters. "We deployed a new prompt at 14:00" should take one query. Version prompts like code and log the version with every call.</li>
<li>Watch the tail. P95 and P99 latency decide whether users bounce, and model latency varies a lot. Alert on the percentiles, since averages hide the slow calls that drive churn.</li>
<li>Alert on error patterns: rising validation-failure rate, fallback activations, sudden token spikes. These surface problems before your users do.</li>
</ul>
<h2>4. Decide degraded behavior before the outage</h2>
<p>The model will be slow, rate-limited, or down. Make the behavior decision before the incident.</p>
<ul>
<li>Timeouts on every call. In FastAPI, use a client-level timeout or wrap the call with <code>asyncio.wait_for</code>. The default "wait forever" is a bug at production load.</li>
<li>Retry with backoff on transient errors only: 429s and 5xx get exponential backoff plus jitter. Do not retry 400s.</li>
<li>Circuit breaker for sustained failures. After N consecutive failures, stop calling the model for a cooldown period and take the degraded path. Without a breaker, your outage becomes the provider's outage, amplified.</li>
<li>Model fallback. Route to a second provider or a smaller model when the primary fails. The fallback answer can be simpler; slow but working beats fast but down.</li>
<li>A non-LLM escape hatch. For some features, a rules-based or cached response is an acceptable degraded mode. Write down what degraded means for your feature before launch.</li>
</ul>
<h2>5. Cost controls that survive contact with users</h2>
<p>Costs are predictable until users arrive. Then someone pastes a book into your chat box.</p>
<ul>
<li>Track cost per request and per feature from day one. Token usage is in every response; multiply by your rates and log it. A daily number in a dashboard beats a monthly invoice surprise.</li>
<li>Budget per request in code. Derive <code>max_tokens</code> from the response budget you can afford, and reject or truncate inputs over a token threshold.</li>
<li>Route by difficulty. Classification and extraction often work with a small, cheap model. Reserve the expensive model for the steps that need it. This is the biggest cost lever in most systems.</li>
<li>Trim context aggressively. Retrieval should return the minimum text that answers the question. Every token you send is a token you pay for.</li>
<li>Cache identical requests. Embeddings especially: identical text in, identical vector out. A cache cuts cost and latency with no quality trade-off.</li>
</ul>
<h2>6. Wire it so adoption stays cheap</h2>
<p>A few FastAPI-specific notes that make the checklist easy to live with:</p>
<ul>
<li>Create the model client in a lifespan handler and store it in app state. Do not create a client per request; connection pooling matters when every request waits on an external API.</li>
<li>Inject the client and config through FastAPI dependencies, so tests and evals can swap a fake model without monkey-patching half the codebase.</li>
<li>Use background tasks or a queue for anything that does not need the model result to answer. A user-facing request should wait only for what it returns.</li>
<li>If you stream, stream end-to-end with <code>StreamingResponse</code>, and record token counts from the provider's usage payload when the stream ends.</li>
</ul>
<h2>7. The boring parts that save you</h2>
<ul>
<li>Keys live in a secret manager or environment variables, never in the repo. Rotate on a schedule and on every offboarding. Table stakes, and still the most common real incident.</li>
<li>Keep your model version in config. When the provider deprecates a model, you change one config line after running evals against the successor. No scattered string literals to hunt.</li>
<li>Write the runbook before launch: how to switch models, how to disable the feature flag, who gets paged, and what the fallback behavior is. One page is enough.</li>
<li>Feature-flag the whole path. Turning the LLM feature off in one click, without deploying, is the cheapest insurance on this list.</li>
</ul>
<h2>What "ready" means</h2>
<p>Ready is a higher bar than "the demo worked." A feature is ready when a prompt change that hurts quality fails CI. When every call carries a trace and a cost. When a provider outage triggers a fallback and your on-call sleeps through it. That bar is reachable in a sprint or two if you build in this order: evals first, then guardrails, then observability, then the rest.</p>
<p>This checklist comes out of shipping Python and AI systems for production teams. I take a small number of consulting engagements, mostly FastAPI backends and production AI architecture for teams in the US and Canada. Details: <a href="https://www.kevynfranco.com/consulting">https://www.kevynfranco.com/consulting</a>. If you run an agency or outsourcing firm that needs extra senior Python or AI delivery capacity, there is a white-label partner path at <a href="https://www.kevynfranco.com/partners">https://www.kevynfranco.com/partners</a>.</p>
]]></content:encoded></item></channel></rss>