Simple definition#
Most AI applications converge on the same architecture, but no team should build it all on day one. This article grows it one component at a time, each added only when a concrete need appears: context, guardrails, routing, caching, actions — and the observability that makes all of it operable.
The enterprise AI stack shows the destination as layers. This is the journey.
Step 0 — The simplest architecture#
The application sends the user’s query to a model API and returns the response. No context, no guardrails, no optimisation.
flowchart LR
U["User"] --> APP["Application"] --> M["Model API<br/>hosted or self-hosted"] --> APP --> U
It is the right place to start: it tells you what the model can do unaided and gives a baseline for every later step.
Step 1 — Enhance the context#
Give the model the information it lacks: retrieval over documents, tools that query databases, APIs and the web, and conversation memory. This is usually the largest quality jump. See RAG fundamentals and tool calling.
Context construction is to foundation models what feature engineering was to classic ML.
Step 2 — Put in guardrails#
Guardrails protect users and the business. They sit on both sides of the model.
flowchart LR
U["User"] --> IG["Input guardrails<br/>PII masking, injection checks,<br/>topic and policy filters"]
IG --> CTX["Context<br/>retrieval, tools"]
CTX --> M["Model"]
M --> OG["Output guardrails<br/>format, grounding, toxicity,<br/>PII, policy"]
OG -->|"pass"| U
OG -->|"fail"| F["Retry, fallback,<br/>or human"]
Input guardrails#
| Risk | Guardrail |
|---|---|
| Leaking private data to an external model | Detect and mask PII, secrets and confidential terms before the call; reverse the mapping on the response |
| Prompt attacks | Detect injection and jailbreak attempts — see AI security |
| Out-of-scope requests | Topic classifiers; block or redirect |
Output guardrails#
| Failure | Check |
|---|---|
| Quality | Malformed format, ungrounded claims, irrelevant answers |
| Security | Toxicity, leaked PII, unsafe code or commands, brand risk |
Define a policy per failure mode: retry (with the same or a different model), fall back to a safe answer, or hand off to a human. Retries add latency; run them in parallel where cost allows.
The trade-off#
Guardrails add latency and false positives. Streaming responses complicate output checks, because the user sees tokens before the full answer can be checked. Decide per use case: stream and check incrementally, or buffer and check fully.
Step 3 — Add a model router and gateway#
Router#
A router sends each request to the best handler, usually via an intent classifier:
- Route easy requests to a small, cheap model and hard ones to a large model.
- Route out-of-scope requests to a canned response, and sensitive ones to a human.
- Route by task type to specialised pipelines (billing, technical support, password reset).
- Detect ambiguous requests and ask for clarification.
Routers must be fast and cheap — typically small classifiers or small models. See model routing and cascades.
Gateway#
A model gateway is the single, unified interface to every model provider and self-hosted model. It centralises access control and keys, cost tracking and budgets, rate limiting, fallbacks when a provider fails, logging, and sometimes caching and guardrails. Changing a model becomes a configuration change. See AI gateway.
Step 4 — Reduce latency and cost with caching#
| Cache | Key | Hit when | Watch out for |
|---|---|---|---|
| Prompt (KV) cache | Repeated prompt prefix | Same system prompt, tools, documents | Handled by the model provider or serving engine — see prompt caching |
| Exact cache | Hash of the full request | Identical query (FAQ, product lookups, embeddings) | Personalised or time-sensitive answers; eviction policy (LRU, LFU) |
| Semantic cache | Embedding of the query | A similar query was answered before | A wrong hit returns a wrong answer; tune the similarity threshold carefully and measure hit precision |
Step 5 — Add agent patterns and write actions#
Now the system can do more than answer: loop over retrieval, call several tools, reflect on its output, and take write actions — send an email, place an order, update a record.
Write actions are where risk jumps. Add permissions and approvals, budgets and stop conditions and an audit trail before giving the system the ability to change the world. See agentic workflow patterns.
The full picture#
flowchart TB
U["User"] --> IG["Input guardrails"]
IG --> R["Router / intent classifier"]
R --> CA{"Cache hit?"}
CA -->|"yes"| OG
CA -->|"no"| CTX["Context construction<br/>retrieval · tools · memory"]
CTX --> GW["Model gateway"]
GW --> M1["Small model"]
GW --> M2["Large model"]
M1 --> AG["Agent logic<br/>reflection · write actions"]
M2 --> AG
AG --> OG["Output guardrails"]
OG --> U
subgraph OBS["Monitoring and observability"]
MET["Metrics"]
LOG["Logs and traces"]
FB["User feedback"]
end
IG -.-> OBS
CTX -.-> OBS
GW -.-> OBS
OG -.-> OBS
Monitoring and observability#
Monitoring tells you that something is wrong; observability lets you find out why from the outside, without shipping new code. Design for observability from the start.
Three numbers frame incident handling: MTTD (time to detect), MTTR (time to resolve) and CFR (change failure rate — the share of changes that cause failures).
Metrics#
| Category | Examples |
|---|---|
| Format failures | Invalid JSON rate, schema violations |
| Quality | Judge-scored grounding, relevance, hallucination flags (sampled) |
| Safety | Guardrail trigger rates, toxicity, PII detections |
| User signals | Thumbs up/down, regenerations, early stops, conversation length — see user feedback |
| Component metrics | Retrieval context precision, tool error rates, cache hit rate |
| Latency | TTFT, TPOT, total latency, by percentile |
| Cost | Tokens and spend per request, per user, per feature |
Slice every metric by user segment, release, model and prompt version.
Logs and traces#
Log everything you need to reconstruct a request: configuration (model, prompt version, sampling parameters), the full prompt and context, tool calls and results, intermediate outputs and the final response, with user feedback attached. Traces link these steps for one request so you can see where it went wrong. Apply data-retention and PII rules to logs — they contain user data.
Drift detection#
Behaviour changes even when your code does not:
| Drift source | Example |
|---|---|
| System prompt changes | A teammate edits the template; a variable renders differently |
| User behaviour changes | Users learn to write shorter queries, or new user groups arrive |
| Underlying model changes | A provider updates the model behind the same API name |
Pin model versions where possible, version prompts, and run your evaluation suite on a schedule against production samples.
AI pipeline orchestration#
An orchestrator defines the components (models, retrievers, tools, guardrails, caches) and chains them: pre-process, retrieve, build the prompt, generate, check, post-process. Frameworks such as LangChain, LlamaIndex, Haystack and Spring AI do this; for agents see the framework landscape.
Choose by: integration and extensibility (does it support your models, stores and tools?), support for complex pipelines (branching, parallelism, retries, human steps), and ease of use, performance and scalability. Start without a framework if the pipeline is simple — you will understand it better, and can adopt one when the complexity is real.
Common mistakes#
Review questions#
In what order would you add components to an AI application? Typically: enhance context (retrieval, tools), add input and output guardrails, add a router and gateway, add caching for latency and cost, then agent patterns and write actions — with monitoring and observability throughout. Adapt the order to measured needs.
What is the difference between a router and a gateway? A router decides where a request should go (which model or pipeline) based on intent or difficulty. A gateway is the unified access layer to models that handles authentication, cost, rate limits, fallbacks and logging.
What are the risks of semantic caching? Serving an answer to a query that is similar but not equivalent, returning a wrong answer with confidence, and leaking one user’s answer to another if keys are not scoped.
What would you monitor in an LLM application? Format failures, quality (sampled judges), safety triggers, user feedback signals, component metrics (retrieval, tools, cache), latency percentiles and cost — sliced by segment and version — plus traces that reconstruct each request.
What causes drift when your code has not changed? Prompt template edits, changing user behaviour and silent updates to the underlying model behind an API.
Summary#
- Start with one call; add context, guardrails, router and gateway, caches and actions as measured needs appear.
- Guardrails need a policy per failure mode and cost latency.
- Routers pick the path; gateways unify access, cost control and fallback.
- Exact and semantic caches cut cost — scope them, and measure semantic hit precision.
- Monitoring, traces and drift detection make the system operable; orchestrators chain it together.
References#
- Chip Huyen, AI Engineering, O’Reilly, 2025 — chapter 10.
- Chip Huyen, Building A Generative AI Platform, 2024.
- Google, DORA metrics.