Skip to content
← All cheat sheets

Cheat sheet · Area 03

AI Agents

Workflows vs agents

A workflow is a fixed sequence of steps your code controls, with LLM calls filling in specific blanks; an agent lets the model decide the steps itself in a loop; most products should start with a workflow and only use an agent where the path really can't be planned in advance.

  • Workflow: code decides the path (classify → route → extract → draft). Predictable, testable, cheap.
  • Agent: the model decides the next step each turn, using tools, until done. Flexible, slower, costlier, less predictable.
  • Use an agent when the steps can't be known in advance and errors are recoverable.
  • Flow engineering: design the steps, checks and retries around the model instead of hoping one prompt does it all.
  • Common workflow patterns: chain, router, parallel, evaluator-optimizer.

Tool calling

Tool calling is how agents act, and doing it well means designing clear tools, running several calls from one turn and returning all their results together, sending errors back to the model instead of crashing, and checking every argument and permission in your own code.

  • Tool = name + description (when to use it) + JSON Schema (arguments). Descriptions matter most.
  • One model turn can request several tools: run them (in parallel if safe) and return ALL results in ONE message.
  • Errors become tool results with is_error so the model can recover; don't crash the loop.
  • Strict schemas (strict: true / additionalProperties false) guarantee well-formed arguments; you still check values and permissions.
  • Fewer, well-named tools beat many overlapping ones. Return short, structured results.

The agent loop and the ReAct pattern

Every agent runs the same loop (the model looks at the situation, decides on an action, the action runs, the result is added to the context, repeat until done), and ReAct is the classic recipe for it, interleaving reasoning ("Thought"), tool use ("Action") and results ("Observation").

  • Agent loop: think → act (tool call) → observe (tool result) → repeat until a stop condition.
  • The model is stateless; the loop's memory is the growing message list you send back each turn.
  • ReAct = Reason + Act: alternate Thought / Action / Observation, then Final Answer.
  • Modern APIs do ReAct natively: tool_use blocks are the Actions, tool results the Observations.
  • Always: step limit, budget, and a clear 'done' signal.

Planning and reflection

Planning means the agent writes down the steps before acting and keeps the plan updated, and reflection means it checks its own work (or has it checked) and revises, both of which make long, multi-step tasks far more reliable.

  • Planning: break the goal into steps up front (a to-do list), execute, and update the plan as you learn.
  • Plan-and-execute: a strong model plans; cheaper models or tools execute each step.
  • Reflection: draft → critique against criteria → revise; stop when it passes or the budget ends.
  • The best critics are external: tests, validators, rules, or a separate judge, not just 'are you sure?'.
  • Keep the plan in the context (or a file) so long tasks don't lose track.

Short-term and long-term memory

Short-term memory is what an agent keeps in its context window during one conversation or task, and long-term memory is information saved outside the model (facts, preferences, past results) and looked up again in later sessions.

  • Models are stateless. 'Memory' = what your app puts back into the context.
  • Short-term: the current conversation and tool results, trimmed or summarised to fit a budget.
  • Long-term: facts and preferences stored in a database or vector store, retrieved when relevant.
  • Types of long-term memory: facts about the user (semantic), past events (episodic), learned how-tos (procedural).
  • Decide what to store, let users see and delete it, and never store secrets or sensitive data without consent.

Context engineering and compaction

Context engineering is deciding exactly what goes into the model's context window at each step (instructions, tools, retrieved knowledge, memory, history, tool results) within a budget, and context compaction is shrinking a long history into a summary so long-running agents keep working without running out of room.

  • Context engineering: the right information, in the right format, at the right time, within a token budget.
  • Sources: system prompt, tool definitions, retrieved docs, memory, recent history, tool results, plan.
  • Prioritise, trim, and put stable parts first (for prompt caching) and volatile parts last.
  • Compaction: replace old turns with a faithful summary; keep recent turns, the goal and key decisions verbatim.
  • Also: clear old tool results, offload big artefacts to files, use sub-agents for noisy reading.

MCP: servers and clients

The Model Context Protocol (MCP) is an open standard for connecting AI apps to tools and data, so a tool written once as an MCP server can be used by any MCP client (Claude, ChatGPT, IDEs, your own agents) instead of building a custom integration for every app.

  • MCP = a standard plug between AI apps (hosts/clients) and capabilities (servers). Like USB-C for AI tools.
  • Server features: tools (actions), resources (data to read), prompts (reusable templates).
  • Client features: elicitation (the server asks the user for input). Spec version as of Nov 2026: 2026-07-28.
  • Transports: stdio (local process) and Streamable HTTP (remote, with OAuth-based auth).
  • Python SDK 2.x: from mcp.server import MCPServer; @server.tool(); client: from mcp import Client.
  • Only connect servers you trust; tool descriptions are untrusted input (see MCP server trust).

Agent skills

An agent skill is a folder with a SKILL.md file (a name, a description and instructions, plus optional scripts and reference files) that an agent loads only when a task needs it, so agents can carry many specialised abilities without filling their context.

  • Skill = folder with SKILL.md (frontmatter: name, description) + optional scripts/, references/, assets/.
  • Progressive disclosure: only name + description load at start; full instructions when relevant; files only when needed.
  • Write the description as 'what it does + when to use it' — that's how the agent picks skills.
  • Skills package procedures and know-how; MCP connects tools and data. They work together.
  • Agent Skills is an open format (agentskills.io), originally from Anthropic, supported by many agents.

Harness engineering: everything around the model

An agent is a model plus a harness, the system around it (instructions, tools, context management, permissions, hooks, verification and memory), and harness engineering is designing that system so the agent works reliably; in 2026 it became the main place teams invest after prompt and context engineering.

  • Agent = model + harness. Same model, better harness → much better agent.
  • Harness parts: instructions (AGENTS.md / CLAUDE.md), tools and skills, context management, permissions and sandbox, hooks, verification, memory/state, observability.
  • Prompt engineering → context engineering → harness engineering → loop engineering: each wraps the last.
  • Instruction files: short, specific, repo-level rules the agent reads every session.
  • Hooks: code that runs at fixed points (before a tool call, after an edit, before 'done') to enforce rules mechanically.
  • Rule of thumb: if a rule matters, enforce it with code (hooks, tests, CI), not only with words.

Multi-agent handoffs and orchestrator-worker

Multi-agent systems split work between several agents, either by handing a conversation from one specialist to another (handoffs) or by having an orchestrator break a job into parts that worker sub-agents do in parallel, each with its own focused context.

  • Handoff: agent A passes the whole conversation to specialist B, which takes over (triage → billing).
  • Orchestrator-worker: a lead agent splits the job, workers (sub-agents) do parts in parallel, the lead combines results.
  • Subagents get their own clean context and return a short result: great for noisy research and reading.
  • Costs: more tokens (often several times a single agent), more coordination, harder debugging.
  • Use multiple agents only when parallelism, separation or specialisation clearly pays off.

LangGraph, state and checkpoints

LangGraph builds agents and workflows as graphs of steps (nodes) connected by edges, with a shared state object that every step reads and updates, and checkpoints that save that state after each step so runs can pause, resume, recover from crashes and be inspected.

  • Graph = nodes (functions/LLM calls/tools) + edges (what runs next). Conditional edges choose the next node.
  • State: a typed dict every node reads and returns updates to.
  • Checkpointer (e.g. InMemorySaver, Postgres) saves state after each step under a thread_id.
  • Checkpoints enable: resume after a crash, human-in-the-loop pauses, memory per conversation, time travel/debugging.
  • pip install langgraph (1.x as of Nov 2026). Good for complex, long-running, stateful agents.

The OpenAI Agents SDK and other frameworks

The OpenAI Agents SDK is a small Python library with a few building blocks (agents with instructions and tools, a runner that executes the loop, handoffs, guardrails, sessions and tracing), and it sits among other frameworks like the Claude Agent SDK, LangGraph, CrewAI, AutoGen and LlamaIndex, each with a different focus.

  • pip install openai-agents (0.24 as of Nov 2026). Agent(name, instructions, tools, handoffs, guardrails) + Runner.run(...).
  • @function_tool turns a Python function (type hints + docstring) into a tool.
  • handoffs=[other_agent] lets the model transfer control; guardrails validate input/output in parallel.
  • Sessions keep conversation memory; tracing is built in; max_turns caps the loop.
  • Others: Claude Agent SDK (Claude Code's harness as a library), LangGraph (graphs + checkpoints), CrewAI (role-based crews), AutoGen (conversational multi-agent), LlamaIndex (data/RAG agents).

Human in the loop

Human in the loop means the agent pauses at important moments (before a risky action, when it's unsure, or to get missing information) so a person can approve, edit or reject, and the agent resumes from exactly where it stopped.

  • Pause points: before irreversible or expensive actions, on low confidence, on policy-sensitive topics, when information is missing.
  • Human options: approve, edit (change the arguments or draft), reject (with a reason), or answer a question.
  • Needs durable state: the agent may wait minutes or days (checkpoints, LangGraph interrupt + Command(resume=...)).
  • Show the human exactly what will happen: the action, its arguments, and why.
  • Measure approval rates; automate what's always approved, keep humans where they add value.

Stop conditions, errors and cost control

Agents need clear rules for when to stop (task done, step or token budget used, time up, stuck in a loop), sensible handling of tool and model errors (retry, back off, report), and cost controls so a confused agent can't run up a large bill.

  • Stop when: final answer / finish tool, max steps, max tokens or cost, max time, repeated actions, unrecoverable error.
  • Errors: tool errors go back to the model; transient failures retry with exponential backoff; give up gracefully with a clear message.
  • Cost control: per-task budgets, cheaper models for sub-steps, caching, concise tool results, alerts.
  • Loop detection: same tool + same arguments several times in a row means stuck.
  • Always return something useful when stopping early: progress so far + what's missing.

Loop engineering: agents that run on repeat

Loop engineering is designing the automated loops around agents (what triggers a run, how each result is checked, when the loop stops, what it may cost, and where humans review) so agents do useful work repeatedly without someone prompting them step by step.

  • Loop engineering: stop typing prompts one at a time; design systems that find work, run agents, verify results and repeat.
  • Building blocks: trigger (schedule, event), task source, harnessed agent, machine-checkable verifier, stop condition, budget, human gate, state.
  • Maker-checker: one agent makes, an independent checker (tests, linters, evals, another agent) verifies; loop until pass or budget.
  • Triggers: cron schedules, CI events (failed build, new issue), webhooks, queues.
  • Long-running autonomous agents need progress files, checkpoints, budgets and frequent verification.
  • Every loop must end: machine-checkable done, attempt cap, cost cap.

The A2A protocol

A2A (Agent2Agent) is an open protocol that lets independent agents, built by different teams on different frameworks, discover each other through an Agent Card, send each other tasks, and get results back, without exposing their internal prompts, tools or memory.

  • A2A = agent-to-agent. MCP = agent-to-tools. Use both.
  • Agent Card at /.well-known/agent-card.json: name, description, skills, endpoint, capabilities, auth.
  • Client agent sends a Message (made of Parts) → server agent works on a Task → returns Artifacts.
  • Task states: SUBMITTED, WORKING, INPUT_REQUIRED, AUTH_REQUIRED, COMPLETED, FAILED, CANCELED, REJECTED.
  • Bindings: JSON-RPC, gRPC, HTTP+JSON. Streaming and push notifications for long tasks. v1.0 spec, Linux Foundation (as of Nov 2026).

Coding agents and computer-use agents

Coding agents read, edit and run code in a repository using file, search and shell tools, verifying their work with tests, while computer-use and browser agents operate graphical interfaces by looking at screenshots and clicking and typing like a person.

  • Coding agent tools: read/search files, edit files, run shell commands and tests, use git.
  • Its loop: understand → plan → edit → run tests → read failures → fix → repeat → open a PR.
  • Computer use: screenshot → model decides click/type/scroll → harness performs it → new screenshot.
  • Browser agents: the same, often with page structure (DOM/accessibility tree) as well as pixels.
  • Always sandbox: a container or VM, limited network, no production credentials, human review.
  • Vibe coding = accepting AI code without really reading it; agentic engineering = directing agents with specs, tests and review.

Capstone: build an agent without a framework

You build a complete agent in one file (three tools, the agent loop, stop conditions, error handling and a real Claude model, plus an offline scripted mode for tests), so you understand exactly what every agent framework does under the hood.

  • An agent = model + tools + loop + stop conditions. About 100 lines without a framework.
  • Append the model's whole turn, then ALL tool results in ONE user message.
  • A finish tool gives a clean 'done' signal; step and token limits guarantee the loop ends.
  • Tool errors return is_error results; the model recovers.
  • Put the model behind a tiny interface so tests can swap in a scripted model.