Architecture Patterns in Practice
AI Patterns for Reliable Output: Structured Output, RAG, Context Engineering, Evals
October 17, 2026 · 30 min read
Software Architecture, Design Patterns, AI, LLM, C#, Python
This post is part of Architecture Patterns in Practice, a series that turns the patterns in my 2026 architecture map into small programs you can run. This one starts the AI section of the map, with the four patterns under "getting reliable output".
A model call is the least predictable function in your codebase. The same input can give different output, the output is text unless you insist otherwise, and the model only knows what was in its training data plus whatever you put in the prompt. These four patterns are how you put a box around that:
| Pattern | The problem it solves | Old idea underneath |
|---|---|---|
| Structured output | Free text is hard to use in code | A typed contract at the boundary |
| Retrieval-augmented generation (RAG) | The model doesn't know your data | Cache-aside for knowledge |
| Context engineering | The context window is finite and noisy | Managing a scarce resource |
| Evals | You can't tell if a change made it better | Regression tests |
All four examples use one feature: a support assistant for a small habit-tracking app. It triages tickets, answers questions from help articles, and keeps a conversation going.
About the model calls. Every model call below is a stand-in: a deterministic function that returns canned or rule-based output. That's so every sample runs offline with no API key, and so the output you see is exactly what you'll get. The patterns are the code around the model, and that code is real. Where it helps, I show what the real SDK call looks like in a separate, clearly labelled block that isn't run. C# runs as .NET 10 file-based apps (dotnet run file.cs), Python as 3.12 with only the standard library, and every output block is pasted from a real run.
Structured output
If your code is going to act on a model's answer (route a ticket, fill a form, call a function), you want an object, not a paragraph. Structured output means you give the model a schema and treat the reply as data that must match it.
There are two layers to this, and you need both:
- Constrain the generation. Most hosted APIs now accept a JSON schema and use constrained decoding, so the reply is guaranteed to parse and match the schema's shape.
- Validate at the boundary anyway. A schema guarantees shape, not truth. It can't tell you the order ID exists, or that "priority 1" fits the ticket. And plenty of setups have no constrained decoding at all: local models, older endpoints, some OpenAI-compatible servers. In those cases the reply can be anything, as I found when building a small agent for local models.
So the pattern in your code is: parse, validate, and on failure, retry once with the errors fed back, then fall back to something safe. Here's that loop with a stand-in model whose first reply is wrong in three ways:
import json
from dataclasses import dataclass
CATEGORIES = {"billing", "bug", "account", "other"}
@dataclass(frozen=True)
class Triage:
category: str
priority: int # 1 = urgent, 3 = whenever
summary: str
order_id: str | None
def parse_triage(text: str) -> tuple[Triage | None, list[str]]:
"""The contract at the boundary. Returns the object, or every reason it isn't one."""
try:
data = json.loads(text)
except json.JSONDecodeError as e:
return None, [f"not JSON: {e.msg}"]
errors = []
if data.get("category") not in CATEGORIES:
errors.append(f"category must be one of {sorted(CATEGORIES)}, got {data.get('category')!r}")
if not isinstance(data.get("priority"), int) or not 1 <= data["priority"] <= 3:
errors.append(f"priority must be an integer 1-3, got {data.get('priority')!r}")
if not isinstance(data.get("summary"), str) or not 0 < len(data["summary"]) <= 80:
errors.append("summary must be a string of 1-80 characters")
if "order_id" not in data:
errors.append("order_id is required (use null if there isn't one)")
if errors:
return None, errors
return Triage(data["category"], data["priority"], data["summary"], data["order_id"]), []
# Stand-in for a model call: deterministic, offline. First reply is the kind of thing
# a model returns without constrained decoding; the second follows the error feedback.
REPLIES = iter([
'{"category": "Billing", "priority": "high", "summary": "Customer was charged twice"}',
'{"category": "billing", "priority": 1, "summary": "Charged twice for annual plan", "order_id": "A-1042"}',
])
def fake_model(prompt: str) -> str:
return next(REPLIES)
def triage(ticket: str, max_attempts: int = 2) -> Triage:
prompt = f"Triage this ticket. Reply with JSON only.\n\n{ticket}"
for attempt in range(1, max_attempts + 1):
result, errors = parse_triage(fake_model(prompt))
if result:
print(f"attempt {attempt}: ok")
return result
print(f"attempt {attempt}: rejected", *errors, sep="\n ")
prompt += "\n\nYour last reply was rejected:\n- " + "\n- ".join(errors) + "\nReply with corrected JSON only."
# Out of attempts: degrade to something safe instead of guessing.
return Triage("other", 2, "Needs a human: model output failed validation", None)
print(triage("I was charged twice for my annual plan, order A-1042. Please fix today!"))
attempt 1: rejected
category must be one of ['account', 'billing', 'bug', 'other'], got 'Billing'
priority must be an integer 1-3, got 'high'
order_id is required (use null if there isn't one)
attempt 2: ok
Triage(category='billing', priority=1, summary='Charged twice for annual plan', order_id='A-1042')
Things worth copying:
- Collect every error, not just the first. The retry prompt lists all three problems, so the model can fix them in one go.
- Cap the retries. One retry fixes most format slips. If the second attempt fails too, the input is probably the problem, and more attempts just cost money.
- Fall back to something safe. "Needs a human" is a valid triage result. A guessed category isn't.
In C#, System.Text.Json with a JsonDocument lets you inspect each field and collect errors, instead of letting deserialization throw on the first bad one:
using System.Text.Json;
var replies = new Queue<string>([
"""{"category": "Billing", "priority": "high", "summary": "Customer was charged twice"}""",
"""{"category": "billing", "priority": 1, "summary": "Charged twice for annual plan", "order_id": "A-1042"}""",
]);
string FakeModel(string prompt) => replies.Dequeue(); // stand-in: offline and deterministic
Console.WriteLine(Triage("I was charged twice for my annual plan, order A-1042. Please fix today!"));
TicketTriage Triage(string ticket, int maxAttempts = 2)
{
var prompt = $"Triage this ticket. Reply with JSON only.\n\n{ticket}";
for (var attempt = 1; attempt <= maxAttempts; attempt++)
{
var (result, errors) = TicketTriage.Parse(FakeModel(prompt));
if (result is not null) { Console.WriteLine($"attempt {attempt}: ok"); return result; }
Console.WriteLine($"attempt {attempt}: rejected\n " + string.Join("\n ", errors));
prompt += "\n\nYour last reply was rejected:\n- " + string.Join("\n- ", errors) + "\nReply with corrected JSON only.";
}
return new("other", 2, "Needs a human: model output failed validation", null);
}
record TicketTriage(string Category, int Priority, string Summary, string? OrderId)
{
static readonly string[] Categories = ["account", "billing", "bug", "other"];
public static (TicketTriage?, List<string>) Parse(string text)
{
JsonElement root;
try { root = JsonDocument.Parse(text).RootElement; }
catch (JsonException e) { return (null, [$"not JSON: {e.Message}"]); }
var errors = new List<string>();
string? Str(string name) =>
root.TryGetProperty(name, out var v) && v.ValueKind == JsonValueKind.String ? v.GetString() : null;
var category = Str("category");
if (category is null || !Categories.Contains(category))
errors.Add($"category must be one of [{string.Join(", ", Categories)}], got '{category}'");
var priority = root.TryGetProperty("priority", out var p) && p.ValueKind == JsonValueKind.Number
&& p.TryGetInt32(out var n) && n is >= 1 and <= 3 ? n : 0;
if (priority == 0)
errors.Add($"priority must be an integer 1-3, got {(root.TryGetProperty("priority", out var raw) ? raw.GetRawText() : "nothing")}");
var summary = Str("summary");
if (summary is null || summary.Length is 0 or > 80) errors.Add("summary must be a string of 1-80 characters");
if (!root.TryGetProperty("order_id", out _)) errors.Add("order_id is required (use null if there isn't one)");
return errors.Count > 0 ? (null, errors) : (new(category!, priority, summary!, Str("order_id")), errors);
}
}
attempt 1: rejected
category must be one of [account, billing, bug, other], got 'Billing'
priority must be an integer 1-3, got "high"
order_id is required (use null if there isn't one)
attempt 2: ok
TicketTriage { Category = billing, Priority = 1, Summary = Charged twice for annual plan, OrderId = A-1042 }
What the real call looks like (not run). With the Anthropic Python SDK, you pass the schema in output_config.format, and the reply's text block is JSON that matches it:
# Not run in this post: needs the anthropic package and an API key.
import json
import anthropic
client = anthropic.Anthropic()
response = client.messages.create(
model="claude-sonnet-5-5",
max_tokens=4096,
messages=[{"role": "user", "content": "Triage this ticket: I was charged twice for order A-1042."}],
output_config={
"format": {
"type": "json_schema",
"schema": {
"type": "object",
"properties": {
"category": {"type": "string", "enum": ["billing", "bug", "account", "other"]},
"priority": {"type": "integer", "enum": [1, 2, 3]},
"summary": {"type": "string"},
"order_id": {"type": ["string", "null"]},
},
"required": ["category", "priority", "summary", "order_id"],
"additionalProperties": False,
},
}
},
)
text = next(b.text for b in response.content if b.type == "text")
triage, errors = parse_triage(text) # still validate: the schema can't check business rules
An older trick was to define a tool with the schema as its input and force the model to call it. The newest Claude models, including Sonnet 5.5, reject a forced tool_choice, so use structured outputs for "just give me JSON", and strict: true on a tool definition when you want a real tool call whose arguments match the schema. OpenAI's API and many OpenAI-compatible servers have their own JSON-schema option; check your provider's docs for the exact shape.
When not to use it. If the output is for a person to read (an answer, a summary, an email draft), forcing it into JSON makes it worse and buys you nothing. Use structured output where code consumes the result. And keep schemas small: a schema with forty optional fields gets you forty chances for a plausible but wrong value. As I noted in the Jev issue of The Decode, a typed answer can't invent text, but it can still be wrong.
Retrieval-augmented generation (RAG)
The model doesn't know your help center, your product's settings screens, or last week's pricing change. RAG fixes that at request time: find the few documents most relevant to the question, put them in the prompt, and tell the model to answer from them.
The pipeline has three parts:
- Index (offline): split documents into chunks and turn each into a vector with an embedding model.
- Retrieve (per request): embed the question and find the closest chunks.
- Generate: build a prompt with those chunks as sources, and ask for an answer that cites them.
For an offline example, the "embedding" here is a bag of words compared with cosine similarity. Real embedding models capture meaning, not just shared words, but the pipeline around them is identical:
import math
import re
from collections import Counter
DOCS = {
"refunds": "Refunds for annual plans are available within 14 days of purchase from Settings, Billing.",
"double-charge": "If you were charged twice, the second charge is a pending authorization and drops off in 3 to 5 days.",
"export": "Export your data as CSV from Settings, Data, Export. Exports include all habits and check-ins.",
"sync": "Sync needs iCloud to be signed in. If sync stalls, sign out of iCloud and back in.",
"widgets": "Add a widget from the home screen by long pressing and tapping the plus button.",
}
STOP = {"a", "an", "the", "is", "are", "to", "of", "and", "or", "from", "in", "my", "i", "you", "if", "for", "be", "do", "how", "can", "was", "were", "as", "by"}
def embed(text: str) -> Counter:
"""A stand-in embedding: bag of words. Real systems use an embedding model; the pipeline is the same."""
return Counter(w for w in re.findall(r"[a-z0-9]+", text.lower()) if w not in STOP)
def cosine(a: Counter, b: Counter) -> float:
dot = sum(a[k] * b[k] for k in a)
norm = math.sqrt(sum(v * v for v in a.values())) * math.sqrt(sum(v * v for v in b.values()))
return dot / norm if norm else 0.0
INDEX = {doc_id: embed(text) for doc_id, text in DOCS.items()} # built once, offline
def retrieve(question: str, k: int = 2, min_score: float = 0.2) -> list[tuple[str, float]]:
q = embed(question)
scored = sorted(((doc_id, cosine(q, vec)) for doc_id, vec in INDEX.items()), key=lambda s: -s[1])
return [(doc_id, round(score, 2)) for doc_id, score in scored[:k] if score >= min_score]
def build_prompt(question: str, hits: list[tuple[str, float]]) -> str:
sources = "\n".join(f'<source id="{doc_id}">{DOCS[doc_id]}</source>' for doc_id, _ in hits)
return (f"Answer using only the sources below. Cite the source id. "
f"If the sources don't answer it, say you don't know.\n\n{sources}\n\nQuestion: {question}")
def answer(question: str) -> str:
hits = retrieve(question)
print(f"Q: {question}\n retrieved: {hits}")
if not hits:
return " -> no source passed the threshold; hand off instead of letting the model guess"
prompt = build_prompt(question, hits)
return f" -> prompt is {len(prompt)} chars, sources: {[d for d, _ in hits]}"
print(answer("I got charged twice for the annual plan, can I get a refund?"))
print(answer("How do I export my habits to CSV?"))
print(answer("Does the app support Apple Watch?"))
print()
print(build_prompt("How do I export my habits to CSV?", retrieve("How do I export my habits to CSV?")))
Q: I got charged twice for the annual plan, can I get a refund?
retrieved: [('double-charge', 0.23)]
-> prompt is 319 chars, sources: ['double-charge']
Q: How do I export my habits to CSV?
retrieved: [('export', 0.56)]
-> prompt is 278 chars, sources: ['export']
Q: Does the app support Apple Watch?
retrieved: []
-> no source passed the threshold; hand off instead of letting the model guess
Answer using only the sources below. Cite the source id. If the sources don't answer it, say you don't know.
<source id="export">Export your data as CSV from Settings, Data, Export. Exports include all habits and check-ins.</source>
Question: How do I export my habits to CSV?
The output shows the three things I'd want any RAG feature to get right:
- A score threshold. The Apple Watch question matched nothing, so the code hands off without calling the model at all. Without a threshold, retrieval always returns something, and the model will try to answer from an unrelated article.
- Sources with IDs. Each chunk is tagged, and the prompt asks for citations. That lets the UI link to the article, and lets you check an answer against its source.
- A visible failure. The first question asked about a double charge and a refund. The refund article scored 0.12, under the threshold, because to a bag of words "refund" and "refunds" are different words. A real embedding model would likely catch it. But the general lesson stands: retrieval is where most RAG answers go wrong, before the model sees anything. Anthropic's contextual retrieval post covers the usual fixes, including combining embeddings with keyword search (BM25) so exact terms like error codes still match.
The C# version builds the same index:
using System.Text.RegularExpressions;
var docs = new Dictionary<string, string>
{
["refunds"] = "Refunds for annual plans are available within 14 days of purchase from Settings, Billing.",
["double-charge"] = "If you were charged twice, the second charge is a pending authorization and drops off in 3 to 5 days.",
["export"] = "Export your data as CSV from Settings, Data, Export. Exports include all habits and check-ins.",
["sync"] = "Sync needs iCloud to be signed in. If sync stalls, sign out of iCloud and back in.",
["widgets"] = "Add a widget from the home screen by long pressing and tapping the plus button.",
};
var index = new BagOfWordsIndex(docs);
foreach (var q in new[] { "I got charged twice for the annual plan, can I get a refund?",
"How do I export my habits to CSV?",
"Does the app support Apple Watch?" })
{
var hits = index.Retrieve(q);
Console.WriteLine($"Q: {q}\n retrieved: [{string.Join(", ", hits.Select(h => $"{h.Id} {h.Score:F2}"))}]");
Console.WriteLine(hits.Count == 0
? " -> nothing passed the threshold; hand off instead of guessing"
: $" -> prompt is {BuildPrompt(q, hits).Length} chars");
}
string BuildPrompt(string question, List<(string Id, double Score)> hits) =>
"Answer using only the sources below. Cite the source id. If the sources don't answer it, say you don't know.\n\n"
+ string.Join("\n", hits.Select(h => $"<source id=\"{h.Id}\">{docs[h.Id]}</source>"))
+ $"\n\nQuestion: {question}";
// Stand-in for an embedding model + vector store: bag of words and cosine similarity.
sealed partial class BagOfWordsIndex(Dictionary<string, string> docs)
{
static readonly HashSet<string> Stop = ["a", "an", "the", "is", "are", "to", "of", "and", "or", "from", "in", "my", "i", "you", "if", "for", "be", "do", "how", "can", "was", "were", "as", "by"];
readonly Dictionary<string, Dictionary<string, int>> _vectors = docs.ToDictionary(d => d.Key, d => Embed(d.Value));
public List<(string Id, double Score)> Retrieve(string question, int k = 2, double minScore = 0.2)
{
var q = Embed(question);
return _vectors.Select(v => (Id: v.Key, Score: Cosine(q, v.Value)))
.OrderByDescending(s => s.Score).Take(k).Where(s => s.Score >= minScore).ToList();
}
static Dictionary<string, int> Embed(string text) =>
Words().Matches(text.ToLowerInvariant()).Select(m => m.Value).Where(w => !Stop.Contains(w))
.GroupBy(w => w).ToDictionary(g => g.Key, g => g.Count());
static double Cosine(Dictionary<string, int> a, Dictionary<string, int> b)
{
double dot = a.Sum(kv => kv.Value * (b.TryGetValue(kv.Key, out var n) ? n : 0));
double norm = Math.Sqrt(a.Values.Sum(v => v * v)) * Math.Sqrt(b.Values.Sum(v => v * v));
return norm == 0 ? 0 : dot / norm;
}
[GeneratedRegex("[a-z0-9]+")] private static partial Regex Words();
}
Q: I got charged twice for the annual plan, can I get a refund?
retrieved: [double-charge 0.23]
-> prompt is 319 chars
Q: How do I export my habits to CSV?
retrieved: [export 0.56]
-> prompt is 278 chars
Q: Does the app support Apple Watch?
retrieved: []
-> nothing passed the threshold; hand off instead of guessing
In production, the dictionary becomes a vector store (pgvector, Azure AI Search, SQLite with a vector extension, or an on-device index), and the bag of words becomes an embedding model. The Abstract Factory section of my creational patterns post covers one trap there: vectors from one embedding model only make sense in an index built for that model.
When not to use it. If all your reference material fits comfortably in the context window, just include it. A 20-page help center doesn't need a vector database, and prompt caching makes sending the same large prefix cheap. RAG earns its complexity when the corpus is large, changes often, or has per-user permissions (each user should only retrieve what they're allowed to see). It's also the wrong tool for teaching the model a behavior or format; that's what instructions and examples are for.
Context engineering
The context window looks huge now, but everything in it competes for the model's attention, and every token costs money and latency. Anthropic's engineering team describes context engineering as curating the smallest set of high-signal tokens that gets the job done. In code, that means something decides what goes in, in what order, and what gets dropped, instead of concatenating everything you have.
A context builder is the pattern. Each part has a priority, a few parts are pinned, and the builder spends a token budget on the most important parts first:
from dataclasses import dataclass
def tokens(text: str) -> int:
return max(1, len(text) // 4) # rough estimate; use the provider's token counter for real numbers
@dataclass
class Part:
name: str
text: str
priority: int # lower = more important
pinned: bool = False # never dropped
TOOLS = {
"lookup_order": "lookup_order(order_id): order status and charges",
"issue_refund": "issue_refund(order_id, reason): refund an order",
"reset_sync": "reset_sync(user_id): clear the sync token",
"export_data": "export_data(user_id): email a CSV export",
"update_email": "update_email(user_id, email): change login email",
"close_account": "close_account(user_id): close the account",
}
TOOLS_FOR = {"billing": ["lookup_order", "issue_refund"], "bug": ["reset_sync"], "account": ["update_email", "export_data"]}
def summarize(turns: list[str]) -> str:
# Stand-in for a cheap model call that compacts old turns.
return f"Earlier ({len(turns)} turns, summarized): user asked about sync, then a widget; both resolved."
def build_context(category: str, sources: list[str], history: list[str], user_msg: str, budget: int):
keep_recent = 2
parts = [
Part("instructions", "You are the support assistant for a habit tracker. Be brief. Never promise refunds "
"outside policy. Use tools for facts about orders.", 0, pinned=True),
Part("tools", "\n".join(TOOLS[t] for t in TOOLS_FOR.get(category, [])), 1), # only what this task needs
*[Part(f"source {i + 1}", s, 2) for i, s in enumerate(sources)],
Part("history summary", summarize(history[:-keep_recent]), 4) if len(history) > keep_recent else None,
*[Part(f"turn -{len(history[-keep_recent:]) - i}", t, 3) for i, t in enumerate(history[-keep_recent:])],
Part("user", user_msg, 0, pinned=True),
]
parts = [p for p in parts if p and p.text]
used, kept, dropped = 0, set(), []
for p in sorted(parts, key=lambda p: (not p.pinned, p.priority)): # spend the budget on what matters most
if p.pinned or used + tokens(p.text) <= budget:
used += tokens(p.text)
kept.add(p.name)
else:
dropped.append(p.name)
ordered = [p for p in parts if p.name in kept] # but keep the original, stable order
return ordered, used, dropped
history = ["How do I fix sync?", "Sign out of iCloud and back in.", "Thanks. How do I add a widget?",
"Long press the home screen and tap plus.", "One more thing about billing.", "Sure, what is it?"]
sources = ["If you were charged twice, the second charge is a pending authorization and drops off in 3 to 5 days.",
"Refunds for annual plans are available within 14 days of purchase from Settings, Billing."]
for budget in (200, 110):
parts, used, dropped = build_context("billing", sources, history, "I was charged twice for order A-1042.", budget)
print(f"budget {budget}: used {used}, sent {[p.name for p in parts]}")
print(f" dropped {dropped}; tools offered: {len(TOOLS_FOR['billing'])} of {len(TOOLS)}")
budget 200: used 144, sent ['instructions', 'tools', 'source 1', 'source 2', 'history summary', 'turn -2', 'turn -1', 'user']
dropped []; tools offered: 2 of 6
budget 110: used 102, sent ['instructions', 'tools', 'source 1', 'turn -2', 'turn -1', 'user']
dropped ['source 2', 'history summary']; tools offered: 2 of 6
The decisions in that builder are the pattern:
- Pinned parts never drop. The instructions and the user's message always go in. Everything else earns its place.
- Only relevant tools. A billing ticket gets 2 of the 6 tool definitions. Fewer tools means fewer wrong tool choices, and the descriptions you don't send are tokens you don't pay for.
- Old history gets compacted, recent history stays verbatim. Four old turns become one summary line (a stand-in here; in practice a cheap model call), and the last two turns stay exact because they're what the user is reacting to.
- Budget by priority, send in a stable order. The builder picks parts by importance but sends them in a fixed order: instructions, tools, sources, history, user. A stable prefix matters for prompt caching, which only reuses an identical prefix.
- Drops are reported. At a budget of 110, the second source and the summary didn't fit. Logging what was dropped is how you debug "why didn't it know that?" later.
The C# version:
var tools = new Dictionary<string, string>
{
["lookup_order"] = "lookup_order(order_id): order status and charges",
["issue_refund"] = "issue_refund(order_id, reason): refund an order",
["reset_sync"] = "reset_sync(user_id): clear the sync token",
["export_data"] = "export_data(user_id): email a CSV export",
["update_email"] = "update_email(user_id, email): change login email",
["close_account"] = "close_account(user_id): close the account",
};
var toolsFor = new Dictionary<string, string[]>
{
["billing"] = ["lookup_order", "issue_refund"], ["bug"] = ["reset_sync"], ["account"] = ["update_email", "export_data"],
};
string[] history = ["How do I fix sync?", "Sign out of iCloud and back in.", "Thanks. How do I add a widget?",
"Long press the home screen and tap plus.", "One more thing about billing.", "Sure, what is it?"];
string[] sources = ["If you were charged twice, the second charge is a pending authorization and drops off in 3 to 5 days.",
"Refunds for annual plans are available within 14 days of purchase from Settings, Billing."];
foreach (var budget in new[] { 200, 110 })
{
var (sent, used, dropped) = Build("billing", "I was charged twice for order A-1042.", budget);
Console.WriteLine($"budget {budget}: used {used}, sent [{string.Join(", ", sent.Select(p => p.Name))}]");
Console.WriteLine($" dropped [{string.Join(", ", dropped)}]");
}
(List<Part> Sent, int Used, List<string> Dropped) Build(string category, string userMsg, int budget)
{
const int keepRecent = 2;
var parts = new List<Part>
{
new("instructions", "You are the support assistant for a habit tracker. Be brief. Never promise refunds " +
"outside policy. Use tools for facts about orders.", 0, Pinned: true),
new("tools", string.Join("\n", toolsFor.GetValueOrDefault(category, []).Select(t => tools[t])), 1),
};
parts.AddRange(sources.Select((s, i) => new Part($"source {i + 1}", s, 2)));
if (history.Length > keepRecent)
parts.Add(new("history summary", Summarize(history[..^keepRecent]), 4));
parts.AddRange(history[^keepRecent..].Select((t, i) => new Part($"turn -{keepRecent - i}", t, 3)));
parts.Add(new("user", userMsg, 0, Pinned: true));
var used = 0;
var kept = new HashSet<string>();
var dropped = new List<string>();
foreach (var p in parts.Where(p => p.Text.Length > 0).OrderBy(p => !p.Pinned).ThenBy(p => p.Priority))
{
if (p.Pinned || used + p.Tokens <= budget) { used += p.Tokens; kept.Add(p.Name); }
else dropped.Add(p.Name);
}
return (parts.Where(p => kept.Contains(p.Name)).ToList(), used, dropped); // original, stable order
}
// Stand-in for a cheap model call that compacts old turns.
static string Summarize(string[] turns) =>
$"Earlier ({turns.Length} turns, summarized): user asked about sync, then a widget; both resolved.";
record Part(string Name, string Text, int Priority, bool Pinned = false)
{
public int Tokens => Math.Max(1, Text.Length / 4); // rough; use the provider's token counter for real numbers
}
budget 200: used 144, sent [instructions, tools, source 1, source 2, history summary, turn -2, turn -1, user]
dropped []
budget 110: used 102, sent [instructions, tools, source 1, turn -2, turn -1, user]
dropped [source 2, history summary]
The token count here is a rough four-characters-per-token estimate. For real numbers, use your provider's token counting endpoint or tokenizer; estimates drift, especially for code and non-English text.
When not to use it. For a single-shot call with a short prompt, a context builder is overkill: write the prompt. It starts to matter with long conversations, many tools, retrieved documents, or agents that accumulate tool results over many steps. That last case gets its own treatment in the next post, on workflows and agents.
Evals
You changed the prompt. Is it better? Without evals, the honest answer is "it looked better on the three examples I tried". Evals are automated test sets for model output: a list of real inputs, the answer a careful person would accept, and graders that score each output. Run them on every prompt or model change, like a regression suite.
Here are two versions of the triage feature. v2 is a real-looking improvement: it fixes a priority bug and redacts email addresses. The eval runs both:
import re
# A small eval set: real-looking inputs with the answer a careful human would give.
CASES = [
{"id": "double-charge", "ticket": "Charged twice for my annual plan!", "category": "billing", "max_priority": 1},
{"id": "refund-late", "ticket": "Can I get a refund? Bought it 2 months ago.", "category": "billing", "max_priority": 3},
{"id": "sync-stuck", "ticket": "Sync has been stuck since the update.", "category": "bug", "max_priority": 2},
{"id": "crash", "ticket": "App crashes when I open widgets.", "category": "bug", "max_priority": 1},
{"id": "email-change", "ticket": "Change my login email to sam@example.com", "category": "account", "max_priority": 3},
{"id": "feature", "ticket": "Please add an Apple Watch app.", "category": "other", "max_priority": 3},
]
EMAIL = re.compile(r"\b\S+@\S+\.\w+\b")
# Two versions of the feature under test. In real life these are two prompts (or models)
# called through the same code; here they're deterministic stand-ins.
def triage_v1(ticket: str) -> dict:
t = ticket.lower()
category = ("billing" if "charged" in t or "refund" in t else
"bug" if "sync" in t or "crash" in t else
"account" if "email" in t else "other")
priority = 1 if "!" in t or "crash" in t else 3
return {"category": category, "priority": priority, "summary": ticket[:60]}
def triage_v2(ticket: str) -> dict:
out = triage_v1(ticket)
if "stuck" in ticket.lower():
out["priority"] = 2
if "widget" in ticket.lower(): # "widget tickets are usually how-to questions"
out["category"] = "other"
out["summary"] = EMAIL.sub("[email]", ticket)[:60]
return out
def grade(case: dict, out: dict) -> list[str]:
"""Code-based graders: cheap, fast, deterministic. Each returns a reason on failure."""
failures = []
if out["category"] != case["category"]:
failures.append(f"category {out['category']} != {case['category']}")
if out["priority"] > case["max_priority"]:
failures.append(f"priority {out['priority']} too low (needs <= {case['max_priority']})")
if EMAIL.search(out["summary"]):
failures.append("summary leaks an email address")
return failures
def run(name: str, fn) -> set[str]:
passed = set()
for case in CASES:
failures = grade(case, fn(case["ticket"]))
if not failures:
passed.add(case["id"])
else:
print(f" {name} FAIL {case['id']}: {'; '.join(failures)}")
print(f"{name}: {len(passed)}/{len(CASES)} passed")
return passed
baseline = run("v1", triage_v1)
candidate = run("v2", triage_v2)
regressions = sorted(baseline - candidate)
print("fixed:", sorted(candidate - baseline), "| regressed:", regressions)
print("ship v2?", "no, it regressed " + ", ".join(regressions) if regressions else "yes")
v1 FAIL sync-stuck: priority 3 too low (needs <= 2)
v1 FAIL email-change: summary leaks an email address
v1: 4/6 passed
v2 FAIL crash: category other != bug
v2: 5/6 passed
fixed: ['email-change', 'sync-stuck'] | regressed: ['crash']
ship v2? no, it regressed crash
v2 scores higher overall, 5 of 6 against 4 of 6. If you only looked at the average, you'd ship it. But it regressed the crash case: a well-meant rule that widget tickets are how-to questions turned "the app crashes when I open widgets" into "other", priority unchanged. Comparing per case, not just per score, is what catches it.
What makes this useful rather than ceremonial:
- Real inputs. Cases should come from real tickets and real failures, with personal details removed. Anthropic's guide to agent evals suggests that 20 to 50 tasks drawn from real failures is a good start, so don't wait for a big dataset.
- Code-based graders first. Exact category, a priority bound, a regex for leaked emails. They're fast, free and deterministic. Add model-based graders ("is this answer faithful to the source?") only for qualities code can't check, and spot-check those graders against human judgment.
- Grade with tolerance where it's honest.
max_priorityaccepts "more urgent than needed" but not "less". Write the check that matches what you'd actually accept. - Gate on regressions. "No previously passing case may fail" is a stricter and more useful rule than "the average went up".
The C# version runs the same comparison:
using System.Text.RegularExpressions;
EvalCase[] cases =
[
new("double-charge", "Charged twice for my annual plan!", "billing", 1),
new("refund-late", "Can I get a refund? Bought it 2 months ago.", "billing", 3),
new("sync-stuck", "Sync has been stuck since the update.", "bug", 2),
new("crash", "App crashes when I open widgets.", "bug", 1),
new("email-change", "Change my login email to sam@example.com", "account", 3),
new("feature", "Please add an Apple Watch app.", "other", 3),
];
var email = new Regex(@"\b\S+@\S+\.\w+\b");
// Deterministic stand-ins for two prompt versions behind the same call site.
Output TriageV1(string ticket)
{
var t = ticket.ToLowerInvariant();
var category = t.Contains("charged") || t.Contains("refund") ? "billing"
: t.Contains("sync") || t.Contains("crash") ? "bug"
: t.Contains("email") ? "account" : "other";
var priority = t.Contains('!') || t.Contains("crash") ? 1 : 3;
return new(category, priority, ticket[..Math.Min(60, ticket.Length)]);
}
Output TriageV2(string ticket)
{
var o = TriageV1(ticket);
var t = ticket.ToLowerInvariant();
if (t.Contains("stuck")) o = o with { Priority = 2 };
if (t.Contains("widget")) o = o with { Category = "other" }; // "widget tickets are usually how-to questions"
var redacted = email.Replace(ticket, "[email]");
return o with { Summary = redacted[..Math.Min(60, redacted.Length)] };
}
List<string> Grade(EvalCase c, Output o)
{
var failures = new List<string>();
if (o.Category != c.Category) failures.Add($"category {o.Category} != {c.Category}");
if (o.Priority > c.MaxPriority) failures.Add($"priority {o.Priority} too low (needs <= {c.MaxPriority})");
if (email.IsMatch(o.Summary)) failures.Add("summary leaks an email address");
return failures;
}
HashSet<string> Run(string name, Func<string, Output> triage)
{
var passed = new HashSet<string>();
foreach (var c in cases)
{
var failures = Grade(c, triage(c.Ticket));
if (failures.Count == 0) passed.Add(c.Id);
else Console.WriteLine($" {name} FAIL {c.Id}: {string.Join("; ", failures)}");
}
Console.WriteLine($"{name}: {passed.Count}/{cases.Length} passed");
return passed;
}
var baseline = Run("v1", TriageV1);
var candidate = Run("v2", TriageV2);
var regressed = baseline.Except(candidate).Order().ToList();
Console.WriteLine($"fixed: [{string.Join(", ", candidate.Except(baseline).Order())}] | regressed: [{string.Join(", ", regressed)}]");
Console.WriteLine(regressed.Count > 0 ? $"ship v2? no, it regressed {string.Join(", ", regressed)}" : "ship v2? yes");
record EvalCase(string Id, string Ticket, string Category, int MaxPriority);
record Output(string Category, int Priority, string Summary);
v1 FAIL sync-stuck: priority 3 too low (needs <= 2)
v1 FAIL email-change: summary leaks an email address
v1: 4/6 passed
v2 FAIL crash: category other != bug
v2: 5/6 passed
fixed: [email-change, sync-stuck] | regressed: [crash]
ship v2? no, it regressed crash
With a real model, run each case a few times, because the same input can produce different outputs. Then track the pass rate per case, and treat a case that passes only sometimes as a finding in its own right.
When not to use it. For a throwaway prototype, evals are premature; you don't know what "good" means yet. But the first time you change a prompt in a feature real people use, you want at least a small set. The trap to avoid is the opposite one: a large eval set that nobody looks at, scored by a grader nobody checked. Six real cases you read are worth more than a thousand synthetic ones you don't.
How the four fit together
In a real feature they form one pipeline. Context engineering decides what goes in, and RAG is one of the things it puts there. Structured output defines what comes back. Evals tell you whether a change to any of the other three helped. If you only adopt one, I'd pick evals, because they're what make the other three safe to change.
Check yourself: questions and answers
1. The API supports JSON schemas with constrained decoding. Why validate the output yourself?
Because the schema only guarantees shape. It can't check business rules (does order A-1042 exist, is this customer allowed a refund), and the same code may later run against a model or endpoint without constrained decoding. Validation at the boundary is cheap and catches both.
2. A structured output call fails validation twice. What should the code do?
Stop retrying and fall back to a safe result, like routing the ticket to a person. Two failures usually mean the input is unusual, not that a third try will work. Log the input and both replies; they're good eval cases.
3. Your RAG feature confidently answers questions your docs don't cover. Where do you look first?
At retrieval, not the model. Check whether there's a relevance threshold, because without one the top match is always returned even when it's unrelated. Then make the prompt say to answer only from the sources and to say so when they don't cover the question, and add those questions to your evals.
4. Why not just put the entire conversation history and every tool into the context?
Cost, latency and accuracy. Every token is paid for on every call, irrelevant tools make wrong tool choices more likely, and long noisy contexts make it harder for the model to use what matters. Keep recent turns verbatim, compact older ones, and send only the tools this task needs.
5. Your new prompt raises the eval pass rate from 80% to 85%. Is it safe to ship?
Not yet. Check which cases changed. If any previously passing case now fails, that's a regression, and the average hides it. Also check how many runs each case had: with a non-deterministic model, a 5-point change on a small set can be noise.
6. When would you skip RAG entirely?
When the reference material fits in the context window. Include it directly and use prompt caching to keep it cheap. RAG adds an index, an embedding model and a new failure mode (bad retrieval), so it should earn its place with a large, changing or permissioned corpus.
Further reading
- Anthropic docs, Structured outputs
- OpenAI docs, Structured model outputs
- Anthropic, Introducing Contextual Retrieval (embeddings plus BM25, and why retrieval fails)
- Anthropic, Effective context engineering for AI agents
- Anthropic, Demystifying evals for AI agents
- Hamel Husain, Your AI Product Needs Evals
- My creational patterns post, which builds model requests and embedders with stand-in calls like the ones here
- My MCP guide, for when your app's actions become tools a model can call
Thoughts on this?
Tell me on X: @bobbyencoded · Share this post on X
Want more like this? Subscribe to The Decode, a weekly email on the AI and developer news worth your time.