AI Foundations0% complete
0%

Chapter 23 of 2525 chapters remaining

Saved on this device. Mark a chapter complete after reading.

MODULE 5 · LESSON 23 · 13 MIN

Designing AI-First Architectures

By Siten Sanghvi · Published · Updated

An AI-first architecture treats the model as one component that generates text, and keeps the controls that must be dependable in ordinary application code around it: who may ask, what the model sees, what is accepted back, and what is recorded. Which supporting components you add (a router, a queue, retrieval) depends on your requirements; a diagram of every component is a menu, not a template.

"AI-first" is not a standard term; here it means designed around how AI components behave. The advice comes from cloud architecture and security guidance, two papers, and earlier lessons (vendor documents read 2026-11-11). The diagram is one worked pattern, not a standard.

What a model component changes

Property of a model call What it asks of the design Lesson
Output varies for the same input Grade against your own test cases (exact match only where the answer is one fixed string); version prompts and models BT-L09, BT-L19
Slow and variable Timeouts, streaming, background work for long tasks BT-L17
Billed per token Budgets, quotas and spend caps; history is resent BT-L16
Fails by being wrong, not only by erroring Check outputs and record what happened BT-L20
Can be steered by text it reads Authorize in code; give the model little power BT-L18

AWS's Generative AI Lens lists the first row as a reliability challenge, suggesting testing, versioning and monitoring.

The reference flow: six steps, three supports

In the diagram on this page, solid arrows run through six steps; dashed arrows connect three supports.

Part What the application does Detail
01 Request An authorized API checks identity, permissions and input limits. Send all data requests through an API that enforces authorization (Azure). OWASP calls checking in the system that owns the data "complete mediation": do not ask the model whether an action is allowed. BT-L14
02 Context Builds the request: instructions, history, evidence, within a token budget. BT-L12
03 Route Picks a model by capability, latency, cost or fallback. Optional. below
04 Generate Calls the model, pinned to a version, with a bounded request (output cap, timeout). Pinning does not replace checks. BT-L17
05 Verify Treats the output as untrusted input (OWASP): checks format and evidence. Actions with side effects wait for approval. BT-L18
06 Respond Returns a result or hands off to a person.
Retrieval Supplies evidence to Context from sources filtered by the user's permissions. BT-L13
Work queue Runs long or bursty jobs in the background, with retries and deadlines. below
Telemetry Records requests for evaluation, cost and rollback. It shows what happened; it does not stop an action. BT-L20

The drawing simplifies two things. It draws no failure paths, such as a failed check; you must design them (see Verify). Dashed telemetry connections span the whole flow. It shows one pass: a tool call (a request from the model, such as an order lookup, that your code validates, authorizes as the user and runs; BT-L14) fits between Generate and Verify, and agents repeat the flow until a final answer. Queue workers run the same flow.

Add components when a requirement asks for them

Anthropic's agent guide advises the simplest solution possible, adding complexity only when it demonstrably improves outcomes. This table is the lesson's own judgment for three invented scenarios, not a standard:

Component Support chat (live, retailer) Document pipeline (nightly invoices) Internal agent (IT tickets, tools)
Authorized API Required: customers see only their own orders Required: who uploads what Required: acts as the employee
Context Required: policy text, trimmed history Required: extraction schema Required: tools, ticket history
Retrieval Required: policy pages (order lookup is a tool call) Optional: supplier records Optional: knowledge base
Route Optional: one model first Optional: easy versus hard document types Optional: per step
Verify Required: cites policy, no refund promises Required: schema and totals checks Required: approval before side effects
Respond or hand off Required: human handoff Required: review list Required: ask the user
Work queue Not on the chat path Likely: slow, bursty jobs, or a provider batch API Optional: long runs
Telemetry Required Required Required

EXHIBIT 23 / ARCHITECTURE

Explore the mechanism

Trace the whole request.

An AI feature is more than one model call.

Trace the whole request.01AuthenticateStep 102Assemble contextStep 203Route modelStep 304Generate replyStep 405Verify outputStep 506Observe resultStep 6

Trace step 1: Authenticate

A model proposes; application code authorizes. Context stores and async queues are optional architectural choices, not universal requirements.

Inspect the example data and reasoning
Trace the whole request. — current illustrative state
ElementWhat to notice
1Authenticate
2Assemble context
3Route model
4Generate reply
5Verify output
6Observe result

Reference pattern, not a mandatory stack. Optional stores and queues depend on actual workload and ownership.

Read the mechanism without interacting
Entry
Authenticate and enforce application permissions at the request boundary.
Context
Assemble evidence and instructions before selecting the model route.
Execution
Use bounded tool execution or queues when needed, then verify and observe the result.

Trace a question through entry, context and model. Compare a task that also needs a queued, authorized action.

Try explaining it: Which component authorizes an action, and which one merely proposes it?

What each addition buys and costs

Routing (step 03). In FrugalGPT, a cascade (try a cheap model first, escalate when a scorer is not confident) matched the best single model on each of three datasets, GPT-4 on two and GPT-3 on the third, at 59% to 98% lower cost (March 2023 prices), but needed labelled examples resembling the live questions. RouteLLM routers cut cost by over 2 times in some benchmark settings, yet on MMLU, routers trained only on its preference data did no better than random until about 1,500 in-domain labelled examples were added.

The costs: Anthropic says routing suits inputs you can classify accurately. OpenAI's agent guide suggests prototyping with the most capable model, then testing smaller ones. Azure says model routers add variability and testing work, and not to use one with fine-tuned models that have narrow SLOs (targets, BT-L17) or where deterministic behavior is critical. A gateway in front of providers adds latency and a single point of failure (Azure).

Work queue. Azure's asynchronous request-reply pattern replies at once with HTTP 202 (Accepted) and a status address the client polls. Queue-based load leveling lets a service work at its own pace, but suits poorly a caller needing a low-latency synchronous reply, so a live chat stays synchronous and streamed. Queues usually deliver at least once, so workers must be idempotent (running twice has the effect of once), or a retried job could email twice. Failed items need a dead-letter list, a holding area for jobs that keep failing. Work that can wait may fit a provider batch API (BT-L16).

Retrieval. It grounds answers in your documents (BT-L13), but OWASP warns that weak access control can leak data between users and tenants. Pass the user's identity into retrieval so it returns only what that user may see (Azure).

Verify. OWASP's excessive-agency advice adds human approval for high-impact actions. AWS's prompt-flow practice says to define a fallback action; for a failed check, options are a bounded retry, a safe default message or a handoff.

Telemetry and the audit record. BT-L20 covers what to log. Full event sourcing (storing every change as an immutable event) is not required: Azure's event sourcing page calls it complex, says traditional data management suffices for most systems, and notes that an immutable store conflicts with deletion duties unless personal data stays outside it or is encrypted per person. This lesson recommends an append-only record per request of its ID, prompt and model versions, retrieved document IDs, validation result and outcome, with content stored separately under access limits.

Reliability around the flow

  • Version prompts and models like code. AWS's prompt catalog practice releases a prompt only after it passes test thresholds, allows rollback, and keeps results per model version.
  • Degrade deliberately. Google's SRE book suggests serving lower-quality results under overload, and warns that a code path you never use often fails when needed, so exercise it. Google Cloud names circuit breakers (stop calling a failing service for a while; BT-L17) and fallbacks such as simpler models or cached data. Choose per scenario: a contact form for chat, hold and retry for the pipeline.
  • Cap cost. OWASP's unbounded consumption entry names "denial of wallet" (a bug or attacker running up pay-per-use charges) and advises rate limits, quotas and timeouts (BT-L16).
  • Test changes on real traffic. In a shadow test, a copy of live requests goes to the candidate and only the current version's answers return (SageMaker frames it around latency and errors). Grade its outputs (BT-L19); the copies add calls (our inference) and are logged data. A canary release gives the candidate to a small share of users; Google Cloud's guidance recommends canaries with rollback on quality alerts.
  • Plan the off switch. NIST's voluntary AI RMF lists mechanisms to deactivate a system performing outside its intended use; BT-L22 covers who owns it.

Try it: write a one-page decision record

An architecture decision record (ADR) documents one significant decision. Nygard's template has title, status, context, decision and consequences; Microsoft's guidance adds options considered and your confidence. AWS says accepted records are not edited: a changed decision gets a new record, and only the old one's status changes, to Superseded; its reasoning stays.

Scenario (invented). A retailer's help page gets about 20,000 chats a month: 70% about shipping and returns policy, 30% about the customer's own order. Policies change monthly, order data is private, the assistant may not issue refunds, one engineer builds it, and there is no eval set. Use BT-L16's example prices: a five-turn chat costs $0.0285 on a large model and $0.001425 on a small one (list prices checked 2026-11-09). Decision to record: do we route policy questions to a cheaper model at launch? Write your record first (title, status, context, options, decision, consequences, what would change it), then compare.

Reference answer.

  • ADR 1: Launch with one model; defer routing. Status: accepted, confidence medium.
  • Context: the figures above; no tests yet.
  • Options: (A) one capable model for all chats; (B) route policy questions to a small model now; (C) a small model for everything.
  • Decision: A. The model name lives in configuration; each request records model ID and tokens; a first eval set of, say, 50 real customer questions with personal data removed comes first (BT-L19; 50 is an illustration, as no source sets a minimum).
  • Consequences: simpler to test; costs more per chat than may be needed; changing models later means a configuration change and an eval re-run. C is rejected: nothing yet shows a small model handles order questions or avoids refund promises.
  • Arithmetic (illustrative, equal cost per chat). 20,000 chats cost $570.00 large-only, $28.50 small-only. Routing 70% to the small model: 6,000 × $0.0285 + 14,000 × $0.001425 = $171.00 + $19.95 = $190.95. The most it can save is $379.05 a month, only if the small model passes your tests, before router errors and engineering time.
  • What would change this: write ADR 2 if the eval set shows the small model passes policy questions within a margin agreed beforehand, if the saving grows past the router's build and upkeep cost, or if prices or models change.

Self-check. Does yours name a rejected option and why, say what to measure, and name a result, not a date, for what would change it?

The takeaway

In applications built on a hosted model, treat the model as one fallible component. Keep authorization, context assembly, output checks and records in your own code. Add routing, queues, retrieval and heavier audit stores only when a stated requirement and your own tests justify their costs, and write the decision down. These are vendor-design patterns and course judgment, not a required stack.

Up next

The AI Ecosystem: Anthropic, OpenAI, Google, Meta — Who Does What and Why: next, the providers and cloud platforms you would connect to. Then Capstone: Design a Complete AI System from Scratch has you write decision records like this one inside a full design document for a different, fictional scenario.

Six stages from an authorized API request to a response. Retrieval supports context, a queue supports background work, and protected telemetry spans the whole request.

Keep the system responsibilities visible

The model generates an output. The application controls data access, tool permissions, validation, escalation, and operating limits.

Download the architecture diagram ↓

VISUAL FIELDNOTES / 23

Keep the big picture.

A one-page visual companion. Save it, print it, or explain it to someone else.

An AI feature is more than one model call. Reference pattern, not a mandatory stack. Optional stores and queues depend on actual workload and ownership.View the full-size sheet ↗

Trace the whole request.

An AI feature is more than one model call.

One US Letter page · Vector artwork · Fits A4 when printed to fit

Read the key points as text
Entry
Authenticate and enforce application permissions at the request boundary.
Context
Assemble evidence and instructions before selecting the model route.
Execution
Use bounded tool execution or queues when needed, then verify and observe the result.

Remember: Authenticate and enforce application permissions at the request boundary.

Try it: Trace a question through entry, context and model. Compare a task that also needs a queued, authorized action.

Recall: Which component authorizes an action, and which one merely proposes it?

OPTIONAL CHECK

Check your understanding.

The optional check requires JavaScript. You can continue reading the lesson.

YOUR LEARNING

Keep your place.

Your progress is saved on this device.