AI engineering · Field guide
Agentic AI, from first principles
What makes an AI system an agent, the main agent architectures, how LangGraph models them as graphs, how to evaluate them, and how retrieval-augmented generation (RAG) gives them knowledge they were never trained on. Every concept comes with a diagram or a small example.
Practice and scoring
Test yourself as you read. Each section you mark as read earns XP, each quiz question you answer correctly earns XP, and a realm is cleared when you have read all of its sections and answered all of its questions correctly. Each realm ends with a boss question worth the most XP. Progress is saved in this browser only.
| Action | XP |
|---|---|
| Mark a section as read (once per section) | +10 |
| First correct answer to a quiz question | +20 |
| First wrong attempt at a question | +4 |
| Answer today's daily question | +25, plus +15 if correct |
| Clear a realm (all its sections and questions) | +50 |
| Defeat a realm boss | +150 |
Every 100 XP raises your level and changes your title. A streak counts consecutive days on which you answer the daily question.
1. Foundations
A large language model (LLM) takes text in and produces text out. On its own it cannot look up a fact, read your database, or change anything outside the conversation. Three ideas turn it into something more:
- Context window. Everything the model can see in one call: instructions, conversation history, tool results and retrieved documents. Anything not in the window does not exist for the model in that call.
- Tool calling. The model can emit a structured request such as
search_orders(customer_id="42"). Your code runs the function and returns the result as a new message. The model never executes anything itself. - A loop. Your code calls the model again with the new result, repeating until the model returns a final answer instead of a tool request.
An agent is an LLM running in such a loop, where the model decides what to do next. A chatbot answers once. A workflow follows steps you wrote in advance. An agent chooses its own steps while it runs. Most production systems sit between these two, and the rest of this guide shows how to choose the right point on that spectrum.
2. Workflows vs agents
Anthropic's guide Building effective agents draws a useful line. A workflow is a system where LLMs and tools follow predefined code paths. An agent is a system where the LLM dynamically directs its own process and tool use. Workflows are more predictable and cheaper to test. Agents suit open-ended problems where you cannot list the steps in advance.
The common workflow building blocks:
| Pattern | What it does | Use it when |
|---|---|---|
| Prompt chaining | Output of one LLM call feeds the next, with optional checks in between | The task splits cleanly into fixed stages, such as outline, then draft, then translate |
| Routing | A classifier sends each input to a specialised prompt or model | Inputs fall into distinct categories, such as billing, technical or sales questions |
| Parallelization | Independent subtasks run at once, or the same task runs several times and results are combined | Subtasks are independent and you want speed, or you want several opinions for confidence |
| Orchestrator-workers | A central LLM breaks the task into pieces at runtime and delegates them to workers | You cannot predict the subtasks in advance, such as editing many files for one change |
| Evaluator-optimizer | One LLM generates, another critiques, and the loop repeats until the critique passes | Clear quality criteria exist and iteration measurably improves the result |
3. Agent types
These names come up constantly. They describe how the loop is organised, not which vendor provides it.
ReAct (reason and act)
The model alternates between a short reasoning step and a tool call, observing each result before deciding the next move. It is the default pattern for tool-using agents and the loop shown in Section 1.
Plan-and-execute
A planner writes the full list of steps first. An executor carries them out, and the plan is revised only when a step fails. This suits long tasks where you want a visible plan before any side effects happen.
Reflection (self-critique)
After producing an answer, the agent reviews its own output against criteria and revises it. The gain depends heavily on whether the critic can actually detect errors. Without a concrete check, reflection tends to rephrase rather than fix.
Router
A single step chooses which specialist handles the request. Simple, cheap and easy to test, and often the right first step before anything more complex.
Supervisor (multi-agent)
One agent receives the request, delegates to specialist agents, and decides when the work is complete. See Section 6.
Hierarchical teams
Supervisors manage other supervisors. Useful when a task has distinct sub-domains, each with its own tools and sub-steps, but it multiplies cost and latency quickly.
Handoff (swarm)
There is no central boss. The active agent transfers control directly to another agent by calling a handoff tool, and the conversation continues with the new agent's instructions and tools.
| Type | Control | Strength | Main risk |
|---|---|---|---|
| ReAct | Model, step by step | Flexible, simple to build | Wanders or loops without a stop rule |
| Plan-and-execute | Upfront plan | Predictable, reviewable | Plan goes stale when reality differs |
| Reflection | Self-review pass | Catches some errors | Costs double, and may not find real errors |
| Router | One classification | Cheap, testable | Misrouted inputs fail silently |
| Supervisor | Central agent | Clear ownership | Supervisor becomes a bottleneck |
| Handoff | Agents pass control | Natural for conversational flows | Hard to trace where state went |
4. Tools and memory
Designing tools
The model chooses tools by reading their names and descriptions, so those descriptions are part of the prompt. Good tools are:
- Narrow.
get_order_status(order_id)beatsrun_sql(query). Narrow tools are safer and easier to evaluate. - Typed. Use a schema for every argument, with enums where values are fixed.
- Informative on failure. Return "order 4411 not found, check the ID format" rather than a stack trace. The model can recover from the first; it cannot from the second.
- Least privileged. Read-only by default. Anything that spends money, sends messages or deletes data needs a confirmation step, often a human-in-the-loop interrupt (Section 5).
Kinds of memory
| Memory | Where it lives | Example |
|---|---|---|
| Working | The context window for this run | The current conversation and tool results |
| Short-term thread | A checkpointed state keyed by thread ID | Resuming a support chat tomorrow |
| Long-term | An external store, often searched by embedding | Remembering a user's stated preferences across many sessions |
| Procedural | Instructions and examples in the prompt or code | The rules for how to write a refund reply |
5. LangGraph
LangGraph is a library from the LangChain team for building agents as explicit graphs. Instead of a hidden loop, you define a shared state, nodes that are functions which read and update that state, and edges that decide which node runs next. The control flow is visible in code, can be drawn as a diagram, and can be paused, saved and resumed.
The four core ideas
- State. A typed record, usually a
TypedDictor Pydantic model, that every node sees. Nodes return only the fields they change. - Reducers. Rules for merging updates into state.
Annotated[list, add_messages]appends new messages rather than overwriting the list. - Nodes. Ordinary Python functions. A node might call an LLM, run a tool, query a database or do plain logic.
- Edges. Fixed edges always go to the same next node. Conditional edges call a routing function that returns the name of the next node, or
END.
A minimal tool-calling agent
from typing import Annotated, TypedDict
from langgraph.graph import StateGraph, START, END
from langgraph.graph.message import add_messages
from langgraph.prebuilt import ToolNode
from langgraph.checkpoint.memory import MemorySaver
class State(TypedDict):
messages: Annotated[list, add_messages] # reducer: append, do not overwrite
tools = [search_orders, refund_order] # plain functions decorated with @tool
llm_with_tools = llm.bind_tools(tools)
def call_model(state: State):
response = llm_with_tools.invoke(state["messages"])
return {"messages": [response]} # only the field we changed
def route(state: State):
last = state["messages"][-1]
return "tools" if last.tool_calls else END
builder = StateGraph(State)
builder.add_node("agent", call_model)
builder.add_node("tools", ToolNode(tools)) # runs requested tools, returns results
builder.add_edge(START, "agent")
builder.add_conditional_edges("agent", route, ["tools", END])
builder.add_edge("tools", "agent") # always return to the model after tools
app = builder.compile(checkpointer=MemorySaver())
config = {"configurable": {"thread_id": "customer-42"}}
result = app.invoke({"messages": [("user", "Where is order 4411?")]}, config)
Note the thread_id. With a checkpointer, every call for the same thread continues from the saved state, which is how a chat keeps its history between requests.
Features that matter in practice
- Checkpointers. Save state after every step. In-memory saving is fine for tests; a database-backed checkpointer is needed for production, so a crash or deploy does not lose a conversation.
- Human-in-the-loop. Interrupt before a sensitive node, show the proposed action to a person, then resume with their decision. Typical for refunds, deletions and outbound messages.
- Streaming. Stream tokens, node updates or both, so a UI can show progress instead of a long wait.
- Subgraphs. A compiled graph can be a node in another graph. Use this to package a research sub-agent with its own state.
- Send (map-reduce). Dispatch the same node over a dynamic list of inputs in parallel, such as one worker per document, then reduce the results. This is orchestrator-workers from Section 2 expressed in code.
- Time travel. Load an earlier checkpoint, change the state, and rerun from there. Invaluable for debugging why an agent chose a path.
6. Multi-agent systems
Split one agent into several when specialisation helps: different prompts, different tools, different permissions, or simply a context window that would otherwise fill with irrelevant detail. Splitting for its own sake usually adds cost, latency and coordination bugs.
Common failure modes
- Agents talking past each other. Two agents redo the same work, or each assumes the other did a step. Fix with a single shared state and explicit ownership of each field.
- Endless delegation. The supervisor keeps routing back and forth. Fix with a step budget and a stop condition in the graph, not only in the prompt.
- Context drift. Each hand-off loses details. Pass structured state, not a paraphrase.
- Cost blow-up. Each agent multiplies the tokens. Measure cost per task in evals before adding a fourth specialist.
7. Evals
An eval is a repeatable test of an LLM system's behaviour. Without one, every prompt change is a guess: it may fix the example you looked at and break three others. Evals turn "it seems better" into a number you can compare.
What to measure
| Dimension | Example check | How to score |
|---|---|---|
| Correctness | The refund amount matches the order record | Exact match or code-based assertion |
| Tool use | Called search_orders before refund_order | Compare the actual tool trajectory with the expected one |
| Groundedness | Every claim is supported by the retrieved text | LLM judge with the source, or a human |
| Style and policy | No promises of delivery dates; polite tone | Rubric scored by an LLM judge, spot-checked by humans |
| Cost and latency | Tokens and seconds per task | Logged from traces, compared with a budget |
| Safety | Refuses a request outside policy | Pass/fail on adversarial cases |
Ways to grade
- Deterministic code. Regular expressions, JSON schema checks, unit tests on the output. Cheap, fast and reliable, so use them wherever they can express the requirement.
- Reference-based. Compare with a known good answer, using exact match, token overlap or semantic similarity.
- LLM-as-judge. A model scores an output against a rubric. Useful for open-ended quality. Validate it: check its agreement with human labels, watch for bias toward longer answers, and pin the judge model and prompt so scores stay comparable.
- Human review. The ground truth, but slow. Use it to calibrate the automated graders, not to score every run.
Building a dataset that tells you something
- Start from real traffic. Sample production inputs, especially ones that failed or confused users. Invented examples skew easy.
- Cover categories deliberately. Common cases, edge cases, adversarial inputs and cases where the right answer is "I don't know".
- Keep expected outputs at the right level. Often "must cite order 4411 and must not promise a date" is better than one exact sentence.
- Separate dev and holdout sets. Tune prompts on one set and check the final version on another, or you will overfit the examples you can see.
- Test agents on trajectories. For agents, check the sequence of tool calls and the final state, not only the final text. A correct answer reached by an unsafe path is still a failure.
Metrics for classic ML and retrieval
Retrieval has its own metrics, covered in the RAG section below: recall at k, precision at k, mean reciprocal rank and normalised discounted cumulative gain (nDCG). These measure the retriever in isolation, which is essential because a generator cannot fix documents it never received.
8. RAG (retrieval-augmented generation)
An LLM knows only what it learned in training, which ends at a fixed date, and it has no access to your private data. RAG adds a retrieval step: find the most relevant passages for the question, place them in the prompt, and ask the model to answer from them. The model gets fresh, specific knowledge without retraining, and you can show the source of each claim.
Stage by stage
1. Chunking
Documents are split into pieces small enough to retrieve precisely but large enough to make sense alone. Common strategies:
- Fixed size with overlap. Simple and a good baseline. Overlap keeps sentences that straddle a boundary retrievable.
- Structure-aware. Split on headings, sections or code blocks, and keep the heading path as metadata.
- Semantic. Split where the topic shifts, detected with embedding similarity between sentences. More expensive, sometimes better.
Attach metadata to every chunk: source, section, date, access permissions. Metadata filters are often the cheapest accuracy gain, for example "only documents from product version 3".
2. Embedding and indexing
An embedding model maps text to a vector so that similar meanings produce nearby vectors. A vector database stores these and finds nearest neighbours quickly. Keep the embedding model and version fixed; changing either means re-embedding everything.
3. Retrieval
- Dense (semantic) search finds passages that mean the same thing, even with different words.
- Sparse (keyword) search, typically BM25, finds exact terms such as error codes, product names and identifiers, which embeddings can blur.
- Hybrid search runs both and merges the ranked lists, often with reciprocal rank fusion. This is the sensible default for real corpora.
- Query rewriting lets the model turn a vague follow-up into a standalone search query, using the conversation so far.
4. Reranking
Retrieval is tuned for recall, so it returns many candidates. A cross-encoder reranker reads the question and each candidate together and scores them more accurately. Retrieve around 50 candidates cheaply, rerank, then keep the top 5 or so for the prompt.
5. Generation with grounding
The prompt should instruct the model to answer only from the supplied context, to say when the answer is not there, and to cite chunk IDs. Number the chunks so the citations can be checked and linked back to the source.
def answer(question: str) -> dict:
q_vec = embed(question) # same model as ingestion
candidates = hybrid_search(question, q_vec, k=50, filters={"product": "v3"})
top = rerank(question, candidates)[:5] # cross-encoder scores
context = "\n\n".join(f"[{i+1}] ({c.source}) {c.text}" for i, c in enumerate(top))
prompt = (
"Answer using only the numbered sources. Cite them like [1]. "
"If the sources do not contain the answer, say so.\n\n"
f"Sources:\n{context}\n\nQuestion: {question}"
)
return {"answer": llm(prompt), "sources": [c.source for c in top]}
Evaluating RAG
Split the evaluation in two, because the failures are different:
| Layer | Question it answers | Typical metrics |
|---|---|---|
| Retrieval | Did the right chunks come back? | Recall at k, precision at k, MRR, nDCG, using labelled relevant documents |
| Context | Is the retrieved text relevant and free of noise? | Context precision, context relevance (judge-scored) |
| Faithfulness | Does the answer stick to the context? | Claim-level support check against the retrieved text |
| Answer quality | Does the answer actually address the question? | Answer relevance, correctness against reference answers |
A common mistake is to tune the prompt while the real problem is retrieval. If recall at k is low, no generator will fix the answer. Measure retrieval first.
Common failure modes
- Chunks too small lose the context that makes them meaningful. Chunks too large dilute the signal and waste the context window.
- Stale index. Documents changed but embeddings did not. Track document versions and re-ingest on change.
- Missing answers. The information is split across chunks. Try parent-document retrieval, where small chunks are matched and the larger section is passed to the model.
- Hallucinated citations. The model cites [4] when only three sources exist. Validate citation IDs in code.
- Prompt injection in documents. Retrieved text can contain instructions. Treat it as data, keep system instructions separate, and limit what tools the answering step can use.
Beyond basic RAG
- Agentic RAG. The agent decides whether to retrieve, what query to send, and whether the results were enough, possibly retrieving again. In LangGraph this is a retrieval tool inside the agent loop from Section 5.
- Multi-hop retrieval. Answering one question needs facts from several documents in sequence. Each step's result shapes the next query.
- GraphRAG. Build a knowledge graph of entities and relations from the corpus, then retrieve connected subgraphs. Helpful for "what themes run across these reports" questions that keyword and vector search handle poorly.
- Long context instead of RAG. A large context window can hold a small corpus whole. It is simpler, but costs more per request, and quality can drop when relevant text is buried in the middle. Measure before choosing.
9. Putting it together
A practical sequence for a new agentic feature:
- Define the task and failure cost. What must never go wrong? That decides how much autonomy and how many human checks you need.
- Write 30 to 50 eval cases from real or realistic inputs before building anything complicated.
- Start with a single call. Add retrieval if the answer depends on private or changing data. Measure retrieval recall separately.
- Add a workflow (routing, chaining or parallel calls) where the steps are known.
- Add an agent loop only for the steps that genuinely need the model to choose its path. Put a step budget and a stop condition in the graph.
- Add checkpoints and interrupts before any action with real-world effects.
- Gate releases on evals and log traces in production so new failures become new test cases.
| Question | Start with |
|---|---|
| Answer depends on private or recent documents | RAG with hybrid retrieval and citations |
| Steps are known in advance | A workflow: chaining, routing or parallel calls |
| Steps depend on what the model finds | A ReAct-style agent with narrow tools |
| Subtasks need different tools or permissions | Supervisor or handoff, with a shared state |
| Model needs a consistent style or format | Better prompts and examples first, fine-tuning later if evals show the gap |
10. The 21 agentic design patterns
The book Agentic Design Patterns: A Hands-On Guide to Building Intelligent Systems (Springer) organises agent engineering into 21 reusable patterns, one per chapter. The table below summarises each one in our own words. Use it as a map: when a design problem looks familiar, the matching pattern tells you which trade-offs to check first.
The book uses a "canvas" metaphor for the infrastructure an agent runs on, and it builds the patterns in roughly this order: first how work is structured, then how agents act on the world, and finally how they are governed and improved.
| # | Pattern | Core idea | Reach for it when |
|---|---|---|---|
| 1 | Prompt chaining | Split a task into steps; each step's output feeds the next. Also called the pipeline pattern. | The task has clear stages and each stage needs focused attention |
| 2 | Routing | Classify the input and send it down the right path, using rules, embeddings or an LLM. | Inputs fall into categories that need different handling |
| 3 | Parallelization | Run independent calls or tools at the same time and merge the results. | Subtasks don't depend on each other, or you wait on slow external calls |
| 4 | Reflection | The agent critiques its own output and revises it. A producer-critic split often works best. | Quality, accuracy or instruction-following matters more than speed |
| 5 | Tool use | The model emits structured function calls; your code runs them and returns the results. | The agent needs live data or must take real actions |
| 6 | Planning | Break a goal into steps that lead from the current state to the target state. | The goal is open-ended and the path must be worked out first |
| 7 | Multi-agent collaboration | Specialist agents hand off work, run in parallel, debate, or report to a coordinator. | One problem needs several kinds of expertise or stages |
| 8 | Memory management | Short-term memory is the current context. Long-term memory lives in external storage and is found by search. | The agent must keep context within a session or across many sessions |
| 9 | Learning and adaptation | The agent changes its behaviour or knowledge from experience. Sub-agents and an overseer keep self-improvement on track. | Performance should improve over time without manual tuning |
| 10 | Model Context Protocol (MCP) | An open, client-server standard that lets any LLM connect to tools, data and prompts in a consistent way. | You want one integration that works across many models and tools |
| 11 | Goal setting and monitoring | Define the goal state and success criteria, then track progress against them. | The agent must know whether it has actually succeeded |
| 12 | Exception handling and recovery | Detect errors, then retry, fall back, degrade gracefully, log, or escalate. | Tools fail, outputs are malformed, or dependencies time out |
| 13 | Human-in-the-loop | Bring people in for oversight, intervention, feedback and escalation. | Mistakes are costly, or the decision needs human judgement |
| 14 | Knowledge retrieval (RAG) | Retrieve relevant snippets and add them to the prompt. GraphRAG adds relationships between entities. | Answers depend on current, private or specialised knowledge |
| 15 | Inter-agent communication (A2A) | An open, HTTP-based standard for agents built with different frameworks to discover and work with each other. Each agent publishes an AgentCard describing its capabilities. | Agents from different teams or vendors must cooperate |
| 16 | Resource-aware optimization | Manage compute, time and money. Choose between accurate but costly models and fast cheap ones, and route simple queries to smaller models. | Budgets, latency or cost limits shape what the agent may do |
| 17 | Reasoning techniques | Make reasoning explicit and spend more inference-time compute on hard problems. ReAct is the core loop. | Problems need multi-step logic, and users must trust the plan |
| 18 | Guardrails and safety | Layer protections: input validation, output filtering, prompt constraints, tool restrictions, moderation APIs and human oversight. | The agent can affect users, data or systems in ways that need limits |
| 19 | Evaluation and monitoring | Measure accuracy, latency, token use and compliance in live systems. Use A/B tests and watch for drift and anomalies. | The system is running in production and its quality must be kept up |
| 20 | Prioritization | Rank tasks by urgency, importance and dependencies, and re-rank as conditions change. | Many tasks compete for limited time or resources |
| 21 | Exploration and discovery | Proactively look for new information, generate hypotheses and test new approaches. | The domain is open-ended and static knowledge is not enough |
How the patterns combine
Most real systems use several patterns together. A research assistant, for example, might plan its steps, route each question to the right tool, retrieve sources for each claim, reflect on the draft, check guardrails before publishing, and log evaluation metrics for every run. Choosing patterns is less about picking one and more about deciding which failure modes you must cover.
The book describes four levels, which is a useful way to decide how much agency a feature needs:
- Level 0: an LLM alone, answering from training data with no tools, memory or live information.
- Level 1: the LLM uses external tools such as search, databases or APIs to gather current information.
- Level 2: the agent plans across several steps and manages its own context carefully, using techniques such as context engineering and prompt engineering.
- Level 3: a team of specialised agents collaborates on a complex workflow, similar to a human organisation with different departments.
Where the book sees agents heading
The closing chapter lists five hypotheses. In brief: agents may become generalists that manage long-running goals; they may become proactive and personalised; they may act in the physical world through robotics; they may take part in economic activity as autonomous actors; and future multi-agent systems may reorganise their own structure to meet a declared goal. The book presents these as possibilities, not predictions, and each one raises the same questions about reliability, evaluation and oversight that the patterns above are meant to address.
11. Appendices: frameworks, prompting and real-world agents
The appendices extend the main chapters beyond design patterns:
- Advanced prompting. Techniques for structuring requests, supplying context, specifying output formats and showing examples, and why poorly designed prompts give ambiguous or wrong outputs.
- Agents that use computers and the physical world. How agents operate graphical interfaces and interact with real environments, and what that changes for automation.
- Framework overview. LangChain and its Expression Language (LCEL) for linear, acyclic pipelines; LangGraph for stateful graphs with loops, covered in Section 5; CrewAI for orchestrating roles and tasks across multiple agents; and Google's Agent Development Kit for building, evaluating and deploying agents.
- Enterprise agent platforms. How a platform can provide unified search across an organisation's documents, email and databases, and host specialised agents that automate processes.
- Agents on the command line. Coding agents that understand natural language, keep context about a whole codebase, and run multi-step tasks from the terminal.
- Inside reasoning engines. How the LLM at the core of an agent makes decisions and plans, and why understanding those mechanisms matters for building reliable systems.
- Coding agents. "Vibe coding" as a fast way to move from an idea to a working prototype, and the discipline needed to review and harden what it produces.
12. Glossary
| Term | Meaning |
|---|---|
| Agent | An LLM in a loop that chooses its own next action, usually with tools |
| Chunk | A piece of a document stored and retrieved as one unit in RAG |
| Checkpointer | Component that saves graph state so a run can resume or be inspected |
| Conditional edge | A graph edge chosen at runtime by a routing function |
| Embedding | A vector that represents the meaning of a piece of text |
| Eval | A repeatable test that scores an LLM system's behaviour |
| Golden dataset | A curated set of inputs with expected results or criteria, used for evals |
| Grounding | Basing an answer on supplied sources and citing them |
| Hallucination | A fluent output that is not supported by the context or facts |
| Human-in-the-loop | A pause where a person approves, edits or rejects an agent's next action |
| LLM-as-judge | Using a model to score another model's output against a rubric |
| Node | A step in a LangGraph graph: a function that reads and updates state |
| Reducer | A rule for merging a node's update into the existing state |
| Reranker | A model that re-scores retrieved candidates more accurately |
| Trace | A recorded log of an agent run: prompts, tool calls, results and timings |
| Vector index | A data structure for fast nearest-neighbour search over embeddings |
Further reading
- Anthropic, Building effective agents: the workflow and agent distinction used in Section 2.
- LangGraph documentation: state, persistence, interrupts and multi-agent patterns.
- Information retrieval texts on BM25, reciprocal rank fusion and nDCG for the retrieval metrics in Section 8.
- Agentic Design Patterns: A Hands-On Guide to Building Intelligent Systems (Springer): the source of the 21 patterns in Section 10 and the appendices in Section 11.
0 Comments