AI Agent Architecture Guide
A production agent has seven parts: model, instructions, tools, state, guardrails, evals and observability. Each belongs in a known place in code, with an owner and a test.
5 min read / Updated / Last checked
- Format
- Guide · Advanced
- Who it is for
- Builders and technical founders
- You leave with
- Read an agent codebase and find where each of the seven parts lives, spot the missing ones, and know which deeper guide covers each.
The problem
On June 25, 2025, Gartner predicted that over 40% of agentic AI projects will be canceled by the end of 2027, citing escalating costs, unclear business value or inadequate risk controls. Its January 2025 poll of 3,412 webinar attendees found 19% of organizations had made significant investments in agentic AI and 42% conservative ones. Gartner also estimated that only about 130 of the thousands of vendors selling "agentic AI" offer real agents [1].
Costs, value and risk controls are architecture problems before they are business problems. A demo agent is usually one file: a prompt string, a model name, two tools, and a loop. It works on the founder's laptop. In production, the same agent needs to know which customer it is acting for, survive a page refresh, refuse a request it should not handle, wait for a person before it moves money, and leave a record of what it did and what it cost.
A founder reviewing an agent build cannot read every line. What they can do is ask where each part lives, who changes it, and how a change is tested. If the builder cannot point to a file for each one, that part is missing.
How it works
OpenAI's guide to building agents names three core components: the model that reasons, the tools that act, and the instructions that define behavior [2]. Production adds four more around them.
Model. The model sits in configuration, not scattered through code, so a change is one reviewed line. OpenAI suggests prototyping with the most capable model to set a performance baseline, then trying smaller ones against your evals [2].
Instructions. The system prompt lives in a versioned file in the repository, reviewed like code. A prompt pasted into a dashboard has no history and no test.
Tools. A tool is a function the model may ask your server to run. The model never runs anything itself. In the OpenAI Agents SDK, @function_tool accepts a per-call timeout and a failure_error_function for errors [4], and needs_approval uses the SDK's approval flow, so the run pauses until a person approves the call [4].
State. The conversation history and any per-user memory. The SDK's sessions load history before a run and save new messages after it, and max_turns stops a loop that will not end by raising MaxTurnsExceeded [6].
Guardrails. Checks on input, output and tool calls. In the SDK, input guardrails run in parallel with the agent by default. Setting run_in_parallel=False makes the check finish before the model is called, so a blocked request costs nothing [5].
Evals. A fixed set of realistic tasks with expected outcomes, run on every change to prompts, tools or model.
Observability. The SDK traces agent runs, model generations, tool calls, guardrails and handoffs by default. It also stores model and tool inputs and outputs by default, which trace_include_sensitive_data=False turns off [7].
Anthropic's advice frames all seven: find the simplest solution possible and add complexity only when needed, since agents trade latency and cost for better task performance [3].
Anatomy of one production agent
Fig. 01- API routesession, tenant, rate limit
- Input guardrailsblock before model spend
- Agent loopmodel + versioned instructions
- Toolsscoped to tenant, timeouts, approval
- Statesessions and records in your database
By the numbers
- of agentic AI projects will be canceled by the end of 2027, Gartner predicts [1]
- 40%+
- of organizations reported significant agentic AI investment in Gartner's January 2025 poll [1]
- 19%
- webinar attendees answered that poll [1]
- 3,412
- of thousands of agentic AI vendors are real, by Gartner's estimate [1]
- About 130
- guardrail types in OpenAI's agent guide, from relevance classifiers to output validation [2]
- 7
| Part | Where it lives | Without it | Deeper guide on this site |
|---|---|---|---|
| Model | Config or environment, one pinned value | Silent behavior change when a default moves | AI Unit Economics and Token Budgets |
| Instructions | prompts/*.md, reviewed in pull requests | Nobody knows which prompt produced an answer | Context Engineering vs. Prompt Engineering |
| Tools | Server functions, tenant passed from the session | The model can reach another customer's data | Tool Permissions and Agent Identity |
| State | Session store and tables in your database | Lost conversations, memory that leaks across users | Agent Memory: Session, Long-Term and Retrieval |
| Guardrails | Input, output and tool checks, plus approvals | Off-topic spend, unapproved refunds | Human Approval Gates for AI Actions |
| Evals | evals/ cases plus a CI job | Every prompt edit is a guess | How to Test an AI Agent Before Customers Use It |
| Observability | Traces with cost per run, PII controlled | No answer to "what did it do, and what did it cost?" | LLM Observability: Traces, Logs and Costs |
Gartner's three causes map onto the table. Escalating cost is a missing observability and model row. Unclear value is a missing evals row, because nobody can show the agent does the job. Inadequate risk control is missing tool scoping and guardrails [1].
Implementation
The file below is one support agent written with the OpenAI Agents SDK for Python, with each part in a known place. The model name comes from the environment, the prompt from a file, and the customer identity from the API route, never from the model.
# agent.py: one support agent, each production part in a known place
import os
from dataclasses import dataclass
from pathlib import Path
from agents import (Agent, GuardrailFunctionOutput, RunConfig, RunContextWrapper,
Runner, SQLiteSession, function_tool, input_guardrail)
import db # your data layer: every query takes the customer id
@dataclass
class Ctx: # built by the API route from the verified session, never by the model
customer_id: str
@function_tool(timeout=10)
async def lookup_order(ctx: RunContextWrapper[Ctx], order_number: str) -> dict:
"""Look up one order of the signed-in customer by its order number."""
order = await db.find_order(order_number, customer_id=ctx.context.customer_id)
return {"status": order.status, "eta": order.eta} if order else {"error": "not_found"}
@function_tool(needs_approval=True, timeout=10)
async def issue_refund(ctx: RunContextWrapper[Ctx], order_number: str, amount_cents: int) -> str:
"""Refund part or all of one order. A person approves every call."""
return await db.refund(order_number, amount_cents, customer_id=ctx.context.customer_id)
@input_guardrail(run_in_parallel=False) # finishes before the model is called
async def size_limit(ctx, agent, user_input) -> GuardrailFunctionOutput:
chars = len(str(user_input))
return GuardrailFunctionOutput(output_info={"chars": chars}, tripwire_triggered=chars > 4000)
support_agent = Agent[Ctx](
name="support",
instructions=Path("prompts/support.md").read_text(), # reviewed like code
model=os.environ["SUPPORT_MODEL"], # pinned in config, not in code
tools=[lookup_order, issue_refund],
input_guardrails=[size_limit],
)
async def handle(ctx: Ctx, conversation_id: str, text: str):
session = SQLiteSession(conversation_id, "sessions.db") # swap for your database
return await Runner.run(
support_agent, text, context=ctx, session=session, max_turns=6,
run_config=RunConfig(workflow_name="support", group_id=conversation_id,
trace_include_sensitive_data=False),
)Four details carry most of the safety. The tools read customer_id from the run context, so a prompt that names another customer's order still queries only the signed-in customer's rows. The refund tool has needs_approval=True, so the run stops with a pending approval instead of moving money. The size check runs before the model, so an oversized paste is rejected at no cost. And trace_include_sensitive_data=False keeps customer messages out of traces, while spans and timings remain [7].
SQLiteSession keeps the example self-contained. In production, store sessions in the same database as everything else, with the same access rules. The db module is your own data layer; its queries filter by customer. If you build on another framework, the same seven questions apply: where is each part, and how is a change to it tested? For the choice between frameworks, see OpenAI Agents SDK vs. LangGraph vs. Mastra.
Test it
Evals are the part most often missing. The script below runs every case in evals/support.jsonl through the real handle function and fails CI if any case fails. Each line of the file is one JSON case with an id, a customer, an input and an expect value of answer, approval or blocked. Answer cases also name the tool that must be called and text that must not appear.
# eval_support.py: run in CI on every change to prompts, tools or the model
import asyncio, json, sys, uuid
from agents import InputGuardrailTripwireTriggered
from agent import Ctx, handle
async def run_case(case: dict) -> bool:
conversation = f"eval-{case['id']}-{uuid.uuid4()}" # fresh history per run
try:
result = await handle(Ctx(customer_id=case["customer"]), conversation, case["input"])
except InputGuardrailTripwireTriggered:
return case["expect"] == "blocked"
if case["expect"] == "approval": # the refund must wait for a person
return [item.name for item in result.interruptions] == ["issue_refund"]
called = [i.raw_item.name for i in result.new_items if i.type == "tool_call_item"]
answer = str(result.final_output)
return (case["expect"] == "answer"
and case["tool"] in called
and not any(s in answer for s in case.get("must_not_contain", [])))
async def main() -> None:
cases = [json.loads(line) for line in open("evals/support.jsonl")]
passed = 0
for case in cases:
ok = await run_case(case)
passed += ok
print("PASS" if ok else "FAIL", case["id"])
print(f"{passed}/{len(cases)} passed")
sys.exit(0 if passed == len(cases) else 1)
if __name__ == "__main__":
asyncio.run(main())Start with four cases, one per part you most need to trust. We ran this script against agent.py with a scripted stand-in for the model, and all four passed. That proves the plumbing (scoping, approval, the size check), not the model's judgment:
- order-status: customer
cus_1asks about order A-1001. Expected:lookup_ordercalled. - other-customer: customer
cus_2asks about the same order. Expected:lookup_ordercalled, and the answer does not contain the real status, because the tool filtered by customer. - refund-needs-human: a full refund request. Expected: the run returns one pending approval for
issue_refund, and no refund executes. - oversized: a 4,100-character paste. Expected:
InputGuardrailTripwireTriggered, with no model call.
Then grow the set from real traffic: every bad answer in production becomes a new case before it is fixed. Run the suite against the real model before each release, since model output varies from run to run, and count a case as stable only when it passes repeatedly.
Decision
Build the single agent first, with all seven parts, before adding a second agent or a cleverer prompt. OpenAI's own recommendation is to get the most out of one agent before splitting work across several [2].
- Ask the builder to show the file for each row of the table. A missing row is the next task, ahead of new features.
- Put tool scoping, approval on irreversible actions and the input check in place before any customer uses the agent. They are a few lines each.
- Treat evals as the definition of done. A change that does not pass the suite does not ship.
- If the task has fixed steps, a workflow may be enough. See AI Agent vs. Chatbot vs. Workflow before adding autonomy, and Do You Actually Need Multiple AI Agents? before adding agents.
Sources
- [1]Gartner Predicts Over 40% of Agentic AI Projects Will Be Canceled by End of 2027 (opens in a new tab)Gartner, June 2025
- [2]A practical guide to building agents (opens in a new tab)OpenAI, April 2025
- [3]Building effective agents (opens in a new tab)Anthropic, December 2024
- [4]Tools (opens in a new tab)OpenAI Agents SDK, November 2026
- [5]Guardrails (opens in a new tab)OpenAI Agents SDK, November 2026
- [6]Running agents (opens in a new tab)OpenAI Agents SDK, November 2026
- [7]Tracing (opens in a new tab)OpenAI Agents SDK, November 2026
Technical guidance, not legal or security certification.
Related resources
Need a technical review of an AI-built MVP?
Discuss your build