08F.1 Agent Frameworks and SDKs
Lesson 08A.2 built the agent loop by hand: call the model, run the tools it asks for, append the results, repeat until the model answers or a budget runs out. That loop is twenty lines of orchestration wrapped around thousands of lines of provider API detail — and it works. So why does a small industry of agent frameworks exist, and when is adopting one better than continuing to own the loop yourself? This lesson answers that question honestly: what frameworks actually give you, what they quietly take away, a verified survey of every major framework as of November 2026, the same support agent implemented four different ways, and the cross-cutting concerns — portability, testing, tracing, durability, approvals, guardrails, churn and dependency risk — that decide whether a framework helps or hurts a production system. It also gives you a five-way comparison table of the frameworks you are most likely to choose between (OpenAI Agents SDK, Claude Agent SDK, LangGraph, Pydantic AI, LlamaIndex Workflows), a "raw tool loop first" selection method with a decision list, and a pointer to the low-code awareness lesson (n8n and Dify) that covers the platforms you will meet but not choose from this table.
What you'll learn
- Why agent frameworks exist, what they genuinely buy you (loop management, state, sessions, tracing, guardrails, handoffs, retries, provider abstraction), and what they cost (abstraction leaks, lock-in, churn, debugging difficulty, dependency risk)
- A framework-neutral checklist for evaluating any agent framework before you adopt it
- A verified survey of the field as of November 2026: OpenAI Agents SDK, Claude Agent SDK, Google ADK, LangGraph and LangChain, Pydantic AI, Microsoft Agent Framework, CrewAI, LlamaIndex, smolagents, Semantic Kernel, Haystack, DSPy, the TypeScript ecosystem, and the no-framework option — with current versions, licences and API shapes
- The same agent — the running example's support assistant — implemented four ways: your own loop, OpenAI Agents SDK, Pydantic AI and LangGraph, with a side-by-side comparison of lines, concepts, control, tracing and testing
- Cross-framework concerns: keeping tools and prompts portable, testing framework-built agents, tracing, durable execution and checkpointing, human-in-the-loop primitives, guardrails, streaming, structured output, upgrades and migration, and the security of framework dependencies
- Low-code workflow builders and hosted agent platforms: what exists per provider, and when a platform is the right answer instead of code
- A side-by-side comparison of five frameworks (OpenAI Agents SDK, Claude Agent SDK, LangGraph, Pydantic AI, LlamaIndex Workflows) across state, tools and MCP, tracing, human-in-the-loop and multi-agent style, plus selection criteria that start from "raw tool loop first" (2.4 to 2.6)
What you don't need
- A working agent loop. Lesson 08A.2 built one; this lesson assumes you have seen
call_model, aToolRegistryand aScriptedModel. - Deep knowledge of any framework. Every framework here is introduced from its core primitives.
- API keys. The framework samples are labelled illustrative and written against official documentation. The one runnable sample in this lesson is pure Python over in-memory fake data, exactly like the tools from 08A.6.
Setup
No installs are required to read this lesson. If you want to try the samples, they need Python 3.11+ and, for the framework parts, the provider SDKs from earlier module lessons plus the framework packages. Install each framework by package name only when you reach its section (for example uv add openai-agents). The versions the samples were written and checked against are listed in the table in 2.2 ("as of November 2026"). Several of these frameworks are 0.x or recently moved major versions, so a plain install may give you a newer release than the sample; each entry's "Watch out" line says what to expect and the project's changelog is the authority.
uv init agent-frameworks --bare --python 3.13 && cd agent-frameworks # first time only
uv add openai anthropic pydantic python-dotenv
# or: pip install openai anthropic pydantic python-dotenvThe .env file is the same one used across Modules 03 and 08A. OpenAI and Anthropic are the two primary providers:
# .env (never commit this file)
OPENAI_API_KEY=...
ANTHROPIC_API_KEY=...Other providers (optional)
Only the Google ADK sketch in 3.3 needs the Google SDK and a Gemini key. If you want to try it, also run uv add google-genai (or pip install google-genai) and add GEMINI_API_KEY=... to .env. An OpenRouter key (OPENROUTER_API_KEY=...) is only needed if you route calls through OpenRouter's gateway, as the OpenRouter sample in 08A.2 does. One data-governance note on OpenRouter: it is a third-party gateway that sits between you and the model provider, so your prompts and outputs pass through one more company. Before sending customer or regulated data through it, read its current data-handling and provider-routing policies and check them against your organisation's rules.
What you must be able to do after this lesson#
- Explain what an agent framework buys you and what it costs
- Apply a framework-neutral checklist to evaluate any agent framework
- Place the main frameworks in a taxonomy and name one strength of each
- Compare the same support agent written four ways
- Decide between a raw loop, a framework and a low-code platform for a given project
Why this matters for an AI engineer#
| You'll hear... | You'll understand it after... |
|---|---|
| "Should we use LangGraph or just write the loop?" | Part 1 and the decision table |
| "The framework handles retries and tracing for us." | 1.1 What a framework actually does |
| "We got locked into a framework and now we can't switch models." | 1.2 What it costs you and 5.1 Portability |
| "Pydantic AI is just 2.66 — is it stable enough?" | 3.5 Pydantic AI and the maturity column |
| "AutoGen is dead?" | 3.6 Microsoft Agent Framework |
| "The Agents SDK needs an OpenAI key — can it call Claude?" | 3.1 OpenAI Agents SDK (provider adapters) |
| "Claude Agent SDK sounds like the Messages API — is it?" | 3.2 Claude Agent SDK |
"What is ADK 2.0's Workflow?" |
3.3 Google ADK |
| "Do we need a graph for a simple support bot?" | 4.6 Side-by-side and 7.1 |
| "How do we test an agent built on a framework?" | 5.2 Testing |
| "Where do agent traces go?" | 5.3 Tracing and observability |
| "The agent paused for approval — how does resume work?" | 5.5 Human-in-the-loop primitives |
| "Can a managed agent platform replace our backend?" | Part 6 |
| "n8n or Dify — is that an agent framework?" | 6.2 Workflow builders and low-code platforms |
Part 1: Why frameworks exist#
1.1 What a framework actually does for you#
Strip away the marketing and an agent framework is a packaged version of decisions you would otherwise make yourself, repeatedly, per project:
| Thing a framework gives you | What it replaces in your own code |
|---|---|
| The loop | Your while loop over call_model → tool dispatch → append results (08A.2) |
| Tool registration | Your ToolRegistry: schema generation, validation, timeout and error wrapping (08A.6) |
| Conversation state | Your message list, provider-native item handling, session persistence across process restarts |
| Handoffs / sub-agents | Your own orchestration for "which agent handles this" (08A.10, 08D.3) |
| Guardrails | Your input/output validation hooks around the loop |
| Human-in-the-loop | Your pause/serialize/resume machinery (08A.10) |
| Tracing | Your trace_id logging and span emission (03.10) |
| Retries and fallbacks | Your retry policy from 03.8 applied to tool calls and model calls inside the loop |
| Provider abstraction | Your own provider-agnostic layer (03.11) — sometimes |
| Durable execution | Your checkpointing, resumption and crash recovery (08A.14) |
Notice the pattern: every row is something you already know how to build. The framework's pitch is that it builds them once, correctly, and maintained by a team whose job is agent edge cases — the dropped tool_call_id, the pause_turn you forgot to handle, the retry that double-charges a refund.
1.2 What it costs you#
| Cost | How it bites |
|---|---|
| Abstraction leaks | The framework's model of "a tool call" or "a turn" never exactly matches every provider's. When the mismatch matters — a pause_turn mid-handoff, a reasoning item the framework drops — you're debugging through the abstraction |
| Lock-in | Agents, tools, sessions and traces are expressed in the framework's types. Leaving means rewriting orchestration, not just swapping an import |
| Churn | These libraries move fast: OpenAI's Agents SDK is at 0.x, Pydantic AI ships breaking-change migrations between majors, LangGraph restructures APIs between minors. Prompts tuned on one version can behave differently on the next |
| Debugging difficulty | "What did we actually send to the model?" now has an extra layer between your code and the wire. The framework may retry, reorder, compact or transform things you didn't ask it to |
| Hidden behaviour | Auto-retries at two layers (framework and SDK) double your retry count and your bill; implicit context compaction changes what the model sees without telling you |
| Dependency risk | An agent framework pulls a dependency tree: LangChain's ecosystem, Pydantic AI's extras, CrewAI's chromadb stack. More packages = more supply-chain surface and more version conflicts (03.11, 13.9) |
| The lowest-common-denominator problem | A framework spanning five providers can only expose what all five share. Provider-specific power features live behind escape hatches you have to find |
1.3 A framework-neutral checklist#
Before adopting any framework — this one, or one released next month — answer these questions. They work for every entry in the survey:
- What does it own? Loop only? State? Tools? Guardrails? Tracing? Deployment? Write down exactly which layers it replaces and which stay yours.
- What does it hide? Can you see the exact messages sent to the provider on every turn? Can you disable auto-retries, auto-compaction and auto-summarisation? If not, you have a black box inside your black box.
- How do you test it? Is there a fake/scripted model so unit tests need no API key? (Pydantic AI's
TestModel, your ownScriptedModel, provider SDK mocks — each framework answers this differently; 5.2 covers the patterns.) - What happens on failure? Where do exceptions from tools, model errors, truncation and refusals surface? Does the framework retry things you didn't want retried (a refund is not idempotent)?
- What's the escape hatch? Can you call the provider SDK directly for the 10% of calls that need provider-specific features? Does it expose raw request/response objects?
- What's the state model? Where does conversation history live — in your process, in the framework's session store, on the provider's servers? Who is the source of truth, and what happens when the process dies mid-run?
- What's the upgrade story? How often does it release? What's the deprecation policy? Is there a migration guide, and does the old version keep working while you migrate?
- What's the dependency cost? Count the transitive packages (
uv pip compiletrick from 03.11). Who maintains it — a company, a foundation, or one person? - Does it match your providers? First-class support for the providers you actually use, or "works via LiteLLM"?
- Does it match your team? Will a new hire debug this in a week? Is the mental model (loop, graph, crew, code-agent) one your team already thinks in?
1.4 Where frameworks sit in the stack#
flowchart TD
app["Your application code<br/>(tools, prompts, business rules)"] --> choice{"Who owns the agent loop?"}
choice -->|"You"| own["Your own loop<br/>(08A.2 canonical loop + ToolRegistry)"]
choice -->|"A library"| fw["Agent framework<br/>(this lesson's survey)"]
choice -->|"A service"| hosted["Hosted agent platform<br/>(Part 6)"]
own --> sdk["Provider SDKs<br/>(openai, anthropic, google-genai)"]
fw --> sdk
fw -->|"some frameworks wrap SDKs,<br/>some speak HTTP directly"| http["Provider HTTP APIs"]
hosted --> prov["Provider-hosted runtime<br/>(Managed Agents, Agent Engine...)"]
sdk --> prov
http --> provThe important observation: these options compose, not compete. A team can run its own loop for one product and a framework for another; a framework can sit on top of the provider SDKs and expose its own hosted deployment; your tools — plain Python functions with JSON schemas — are the one layer that survives every choice. That's why Part 5 treats portability as the first concern, not an afterthought.
Part 2: A taxonomy of the field#
"Agent framework" covers at least five different products wearing the same label. Confusing them is the first mistake buyers make.
2.1 Five kinds of "framework"#
| Kind | What it is | Mental model | Examples (verified below) |
|---|---|---|---|
| Agent-loop frameworks | A library that runs the model→tools→repeat loop for you, with sessions, guardrails and tracing | "Give me an agent, I'll run it" | OpenAI Agents SDK, Pydantic AI, Claude Agent SDK, smolagents, Google ADK (agent mode) |
| Graph / orchestration frameworks | You define nodes and edges explicitly; the framework executes the graph, persists state, and lets the model decide within nodes | "Draw the flow, the model fills the steps" | LangGraph, Google ADK workflows, Microsoft Agent Framework workflows, LlamaIndex Workflows, DSPy (loosely) |
| Crew / role frameworks | You define named agents with roles and let them delegate to each other | "A team of specialists" | CrewAI, AutoGen (archived → MAF), some ADK multi-agent patterns |
| Coding-agent harnesses | A batteries-included agent for software work: file/shell tools, repo context, planning, its own CLI | "A junior engineer that runs commands" | Claude Agent SDK, OpenAI Agents SDK sandbox agents, smolagents CodeAgent, Pydantic AI Harness, coding CLIs (08A.15) |
| Hosted agent platforms | The loop runs on someone else's infrastructure; you configure agents, tools and environments through an API or console | "Rent the runtime" | Anthropic Managed Agents, OpenAI ChatKit/Workspace Agents, Google Agent Engine, CrewAI AMP, LlamaIndex LlamaAgents, low-code builders (Part 6) |
Two consequences follow. First, the "which framework" question is really "which layer do I want to own" — the loop, the graph, the team, or nothing at all. Second, several products span kinds: Google ADK does agents and graph workflows and hosted deployment; LangGraph does graphs and has a hosted platform (LangSmith Deployment); Microsoft Agent Framework does workflows, crews and Foundry hosting.
2.2 The landscape as of November 2026#
Every entry verified against its repository or package index on 5 November 2026. Versions move weekly — treat the version column as "current at time of writing" and the rest as the durable facts. A spot re-check of the PyPI pages on 8 November 2026 already showed newer releases of three of them: claude-agent-sdk 0.2.179, google-adk 2.14.0 and agent-framework 1.25.0 (the others matched, except dspy, which is listed at 3.5.0, released on 10 November 2026, the version 04.9 uses). The LangGraph and LangChain rows are the exception: they were re-checked on 18 November 2026 and show the versions current at time of writing, 18 November 2026 (langgraph 1.2.22, langchain 1.5.0). The other rows and the samples below stay on the versions whose docs and changelogs were read. A plain install gives you whatever is newest on the day you run it, so before you adopt a framework, check its current release against the table, read the changelog for anything between the two, and move forward deliberately.
| Framework | Package (version) | Licence | Language | Providers | Kind | Maturity signal |
|---|---|---|---|---|---|---|
| OpenAI Agents SDK | openai-agents 0.24.0 |
MIT | Python (+JS/TS sibling) | OpenAI native; 100+ via any-llm/LiteLLM adapters | Agent-loop | Very active; 0.x = API still moving; successor to Swarm |
| Claude Agent SDK | claude-agent-sdk 0.2.178 |
MIT | Python (+TS) | Claude only (drives Claude Code) | Coding-agent harness | "Alpha" classifier; bundled CLI; Anthropic-backed |
| Google ADK | google-adk 2.13.0 |
Apache-2.0 | Python, TS, Go, Java, Kotlin | Gemini native; Claude, OpenAI, Ollama, LiteLLM, vLLM | Agent-loop + graph + hosted | Google-backed; 2.0 rewrote around graph workflows; ~bi-weekly releases |
| LangGraph | langgraph 1.2.22 |
MIT | Python (+JS) | Any LangChain chat model | Graph orchestration | LangChain Inc; production-stable; checkpointer ecosystem |
| LangChain | langchain 1.5.0 |
MIT | Python (+JS) | Many via integrations | Component library + create_agent |
The incumbent; "agent engineering platform" positioning |
| Pydantic AI | pydantic-ai 2.66.0 |
MIT | Python | Dozens via model strings; OpenAI/Anthropic/Google/Gemini first-class | Agent-loop (+harness, evals, graph add-ons) | Pydantic team; fast-moving 2.x; type-first design |
| Microsoft Agent Framework | agent-framework 1.24.0 |
MIT | Python, .NET, Go | Azure/OpenAI first; provider-agnostic | Graph + crews + hosted | Microsoft's production successor to AutoGen and Semantic Kernel |
| CrewAI | crewai 1.15.35 |
MIT | Python | Many via LiteLLM | Crew/role + Flows | VC-backed company; AMP Suite commercial tier |
| LlamaIndex | llama-index 0.14.25 |
MIT | Python | Many | Agent-loop + Workflows | Company focus shifted to LlamaParse; OSS still maintained |
| smolagents | smolagents 1.26.0 |
Apache-2.0 | Python | HF Inference, LiteLLM, OpenAI, transformers, Ollama | Code-agent | Hugging Face; small, focused, sandbox-first |
| Semantic Kernel | semantic-kernel 1.47.0 |
MIT | Python, .NET, Java | Azure/OpenAI first | Plugin/orchestration | README redirects new work to Microsoft Agent Framework; still shipping 1.x |
| Haystack | haystack-ai 3.4.1 |
Apache-2.0 | Python | Many via integrations | Pipeline + agent components | deepset; strongest in RAG pipelines |
| DSPy | dspy 3.5.0 |
MIT | Python | Any LM via dspy.LM | Not an agent loop — LM program compiler | Stanford NLP; optimizes prompts/weights, doesn't run agents |
| Vercel AI SDK | ai 7.0.163 (npm) |
Apache-2.0 | TypeScript | Many | Agent-loop (TS) | Vercel; the TS ecosystem's default |
| Mastra | @mastra/core 1.82.0 (npm) |
(see repo) | TypeScript | Many | Agent-loop + workflows (TS) | TS-native; growing fast |
| Strands Agents | strands-agents 1.64.0 |
Apache-2.0 | Python (+TS) | Bedrock, Anthropic, OpenAI, Google, Ollama and more | Agent-loop (+ swarm/graph/workflow, agents-as-tools) | Developed by AWS (strandsagents.com); OpenTelemetry built in; deploys to Amazon Bedrock AgentCore, Lambda, Fargate, containers |
| AG2 | ag2 1.3.0 |
Apache-2.0 | Python | Many | Agent-loop + multi-agent network | Community-maintained rename of the original AutoGen line (v1.0 is not a drop-in upgrade from the autogen.* "Classic" code, which lives in its own repository) |
| AutoGen | autogen 0.14.1 |
Apache-2.0 | Python, .NET | Microsoft-first | Crew/role | Archived — do not start new projects |
2.3 Recommendation by scenario#
This is the honest shortlist before you read any code. It's deliberately conservative: pick the option that removes the most your complexity, not the one with the most features.
| Your situation | Start with | Why |
|---|---|---|
| One provider, want the shortest path to a working agent with approvals, sessions and tracing | That provider's own SDK/framework (OpenAI Agents SDK, Claude Agent SDK, Google ADK) | Fewest moving parts; the framework is the provider's reference implementation |
| Multi-provider product, typed codebase, small team | Pydantic AI | Model strings make provider a config choice; types carry through tools and outputs; TestModel makes tests trivial |
| Complex, long-running, stateful workflows where you need explicit control | LangGraph | The graph is the program; checkpointing, interrupts and time-travel are first-class |
| You already own a good loop (08A.2) and it works | Nothing — keep it, add tracing | A working loop plus your own logging beats a migration you don't need |
| Coding agents specifically | Claude Agent SDK, OpenAI Agents SDK sandbox agents, or the coding CLIs (08A.15) | These are harnesses tuned for repo work, not general agent loops |
| Multi-agent crews with named roles | CrewAI or Microsoft Agent Framework | Their primitives match the mental model; expect more abstraction distance from the model |
| Regulated/enterprise Microsoft shop | Microsoft Agent Framework | Foundry hosting, .NET parity, A2A/MCP interop, enterprise support story |
| You want prompts compiled and optimized rather than hand-written | DSPy | Different problem: it optimizes LM programs, doesn't replace your loop |
| No-code / business users building automations | n8n, Dify, Flowise (Part 6) | Visual builders trade flexibility for speed; know what you're giving up |
2.4 Five frameworks side by side (verified 2 December 2026)#
The survey in Part 3 covers many frameworks. In practice a small team choosing today ends up comparing five. This table puts them in the same rows so the differences are visible. Every cell was checked on 2 December 2026 against the project's official docs or repository (OpenAI Agents SDK docs and repo, Claude Agent SDK docs on code.claude.com, LangGraph docs and repo, Pydantic AI docs, LlamaIndex Workflows docs and the run-llama/workflows-py repo, and PyPI for licences and current versions). Where an official page did not state a fact, the cell says "unverified as of 2026-12-02" instead of guessing. The lessons on the OpenAI Agents SDK (08F.2) and the Claude Agent SDK (08F.3) go much deeper on those two; the LangGraph lessons are 08F.10, 08F.11, 08F.12, 08F.13 and 08F.14.
| OpenAI Agents SDK | Claude Agent SDK | LangGraph | Pydantic AI | LlamaIndex Workflows | |
|---|---|---|---|---|---|
| What it is | A lightweight agent framework: agents with instructions, tools, guardrails and handoffs, plus sessions and tracing | Claude Code's agent loop, built-in tools, permissions and hooks, packaged as a library you embed | A low-level orchestration framework and runtime for long-running, stateful agents, defined as graphs of state, nodes and edges | A Python SDK for agents with typed inputs and outputs and validated tools | An event-driven, async, step-based way to control the flow of an AI application: steps receive and emit events |
| Who maintains it | OpenAI | Anthropic | LangChain Inc | The Pydantic team | The run-llama organisation (the LlamaIndex company) |
| Language | Python (3.10+); a separate JS/TS version exists | Python and TypeScript | Python; LangGraph.js is the JS library | Python (3.11+) | Python (the repo is Python-first; other languages unverified as of 2026-12-02) |
| Licence | MIT | PyPI metadata says MIT, but the docs say use is governed by Anthropic's Commercial Terms (read both) | MIT | MIT | MIT |
| Model support | OpenAI Responses and Chat Completions APIs, plus 100+ other models through adapters; OpenAI models get the deepest support | Claude models. The overview page does not list other providers (unverified as of 2026-12-02) | Any model; it does not require LangChain, though the docs often use LangChain integrations | Many providers (OpenAI, Anthropic, Google, Bedrock, Groq, Mistral, Ollama and others), chosen by a model string | Through LlamaIndex's model integrations (not stated on the Workflows page, unverified as of 2026-12-02) |
| State and memory model | Sessions that keep working context; docs list SQLAlchemy, SQLite and encrypted session options | Sessions that keep context across exchanges and can be resumed or forked; Claude Code's skills, commands and memory files load from .claude/ |
Checkpointed graph state (durable execution), short-term thread state and long-term memory across sessions | You pass message history or keep your own store; durable execution through Temporal, DBOS or Prefect integrations | ctx.store holds shared per-run state; the repo says runs can be saved and resumed from a file or database |
| Tool and MCP support | Function tools, hosted tools and MCP tools side by side | Built-in file, shell and web tools; MCP servers; custom tools as in-process MCP servers (see 3.2) | Whatever tools your nodes call; LangChain tools and MCP adapters are common (details in 08F.8) | Decorated Python functions validated before they run; MCP is a core capability | Tools appear in the ReAct and function-calling agent examples; MCP appears in the docs navigation but its details are unverified as of 2026-12-02 |
| Tracing and observability | Built in and on by default, exported to OpenAI's traces dashboard; can be disabled; unavailable for organisations on Zero Data Retention; 30+ third-party processors are listed | Message stream and hooks give you the events; a dedicated tracing feature is not described on the overview page (unverified as of 2026-12-02) | LangSmith traces and evaluates; you can also instrument with OpenTelemetry yourself | OpenTelemetry traces; Pydantic Logfire is the recommended backend, any OTel backend works | The docs have an observability section, content unverified as of 2026-12-02 |
| Human-in-the-loop | Built in: interruptions and a resume state (see 4.3) | Permission modes and a can_use_tool callback decide what runs without asking |
interrupt() pauses the graph, you inspect or edit state, then resume |
Built-in approval for chosen tool calls | Supported (the llama-agents-server package is named for it); the mechanism is unverified as of 2026-12-02 |
| Multi-agent style | Handoffs between agents and agents-as-tools | Subagents spawned for focused subtasks | Explicit graphs and subgraphs (see 08F.13) | Sub-agents through the Pydantic AI Harness; Pydantic Graph for typed control flow | You wire steps and events yourself; multi-agent helpers are unverified as of 2026-12-02 |
| Best for | A team on OpenAI wanting a small, well-supported SDK with built-in tracing, sessions and handoffs | Agents that work with files and commands: coding, document and data-wrangling agents that benefit from Claude Code's harness | Complex, long-running, stateful flows that need durability, pause and resume and explicit control | Typed, multi-provider codebases with strong testing habits | Event-driven pipelines, especially when the rest of your stack already uses LlamaIndex |
| Watch out for | 0.x versioning: the API can still move; tracing defaults to OpenAI's backend | Alpha status on PyPI; it brings a coding agent's defaults (file and shell tools, permission system) even if you want a plain support bot | More concepts to learn (state, reducers, checkpointers); overkill for a two-tool bot | A fast-moving 2.x line with a migration guide; the capability layer is younger than the core Agent |
Smaller agent ecosystem around it; several rows above are unverified, so read the docs before committing |
Current versions on PyPI on 2 December 2026, for orientation (the samples in Part 3 and Part 4 were written against older ones, as stated there): openai-agents 0.26.2, claude-agent-sdk 0.2.189, langgraph 1.2.25, pydantic-ai 2.77.0, llama-index 0.14.26 and llama-index-workflows 2.26.1. Check the changelog before you rely on a specific API.
2.5 Selection criteria: the raw tool loop first#
Start from this rule: the raw tool loop from 08A.2 is the default. A framework has to earn its place. The loop is about twenty lines. If it works, you own every byte on the wire, and testing it with a ScriptedModel costs nothing. Add a framework only when you can name the specific job it does for you. Use these criteria, in this order:
- Does the raw loop plus tracing already do the job? If yes, stop. Add logging and budgets (08A.2) and keep going.
- Which job do you actually need help with? Pick the framework by the job, not by popularity: durable pause and resume (LangGraph), a typed codebase across providers (Pydantic AI), the provider's built-in tracing, sessions and handoffs (OpenAI Agents SDK), a file-and-shell agent harness (Claude Agent SDK), or event-driven steps around a LlamaIndex stack (LlamaIndex Workflows).
- Model reach. Does it support the providers you will actually run, as first-class? "Works through an adapter" is a weaker promise.
- State and failure. Where does state live, and what happens when the process dies mid-run? Prefer state you can export and inspect.
- Testability. Can you run the agent in a unit test with no key, and replay a trajectory? Check this before you adopt, not after.
- Observability and data path. Where do traces go by default? Is that acceptable for your data (the OpenAI SDK's default trace export is the example to remember)? Can you export to OpenTelemetry?
- Licence and terms. Read them. All five list MIT on PyPI, but the Claude Agent SDK documentation says its use is governed by Anthropic's Commercial Terms, so read both.
- Churn and exit cost. Version, release rate, migration guides. Keep tools and prompts as plain functions and text so the exit is an adapter rewrite (5.1).
- Team fit. Will a new hire be able to debug it in a week?
2.6 A decision list in text#
Walk down the list and stop at the first line that is true for you.
- You have a working loop and no unmet need? Keep the raw loop. Add tracing and tests.
- Your agent must pause for days, survive restarts and resume exactly, or you want an explicit graph? LangGraph (08F.10 to 08F.14).
- The agent mainly works with files, shell commands and documents, and you use Claude? Claude Agent SDK.
- You are on OpenAI, want sessions, handoffs, guardrails and tracing in one small package? OpenAI Agents SDK.
- You want typed tools and outputs, several providers and easy fake-model tests? Pydantic AI.
- Your application is already built around LlamaIndex (retrieval, parsing) and you want event-driven control flow? LlamaIndex Workflows.
- The people building it are not engineers, or it is an internal automation with low risk? Look at a low-code platform (next subsection), with the checks listed there.
- None of the above fits? Go back to line 1. Most "none of the above" cases are a raw loop with a good tool registry.
flowchart TD
a{"Does your raw loop<br/>already do the job?"} -->|"yes"| keep["Keep it, add tracing and tests"]
a -->|"no"| b{"Need durable pause/resume<br/>or an explicit graph?"}
b -->|"yes"| lg["LangGraph"]
b -->|"no"| c{"File and shell work<br/>on Claude?"}
c -->|"yes"| ca["Claude Agent SDK"]
c -->|"no"| d{"Which stack<br/>do you live in?"}
d -->|"OpenAI"| oa["OpenAI Agents SDK"]
d -->|"multi-provider, typed"| pa["Pydantic AI"]
d -->|"LlamaIndex"| li["LlamaIndex Workflows"]This decision list covers the five frameworks in the table. The wider survey in Part 3 and the older decision table add Google ADK, Microsoft Agent Framework, CrewAI, Haystack and DSPy for the cases where one of those is the better fit.
2.7 A note on low-code platforms#
n8n and Dify are not in the table because they are a different kind of thing: visual platforms rather than libraries, and often chosen by non-engineers. The lesson on low-code agent platforms (08F.16, "Low-Code Agent Platforms: n8n and Dify (awareness)") covers what they are, when they fit, their limits for an AI engineer (testing, versioning, evals, governance, licensing) and how to evaluate a finished flow as a black box. Part 6 of this lesson has the short version.
Part 3: The survey, framework by framework#
Reference
Each entry below gives the verified facts (version, licence, API shape) and a compact, realistic code sketch. The sketches are illustrative: they're written against the official documentation as of November 2026 but haven't been run against live APIs. Where an API is in flux, I say so.
3.1 OpenAI Agents SDK#
- Package:
openai-agents0.24.0, MIT, Python ≥3.10 (PyPI, docs) - What it is: OpenAI's lightweight agent framework — "a production-ready upgrade of Swarm" with a deliberately small primitive set:
Agent,Runner, tools, guardrails, handoffs, sessions, tracing. It uses the Responses API by default for OpenAI models but is provider-agnostic through any-llm/LiteLLM adapters (its docs claim 100+ LLMs). - Key API:
Agent(name=, instructions=, tools=, model=);Runner.run_sync(agent, input)→result.final_output;@function_tool(alias@tool) for Python functions with automatic schema generation and Pydantic validation;needs_approval=Trueor a callable on tools for human-in-the-loop;@input_guardrail/@output_guardraildecorators returningGuardrailFunctionOutput(tripwire_triggered=...); handoffs for agent→agent transfer andAgent.as_tool()for manager-style delegation; sessions viaagents.memory(SQLiteSession,OpenAIConversationsSession,OpenAIResponsesCompactionSession) andagents.extensions.memory(SQLAlchemy, async SQLite, Redis, MongoDB, Dapr, encrypted); built-in tracing to the OpenAI tracing UI. - Beyond the basics:
SandboxAgent(agents with isolated workspace/filesystem/shell capabilities),RealtimeAgentandVoicePipelinefor voice, hosted tools (web search, file search, code interpreter, hosted tool search, programmatic tool calling), MCP server tool calling, and an experimental Codex tool. - Watch out: 0.x versioning means the API can still move; tracing is OpenAI-flavoured (export paths to other backends exist but are less documented); the "provider-agnostic" claim is real but second-class — OpenAI models get the deepest feature support.
# illustrative — needs the openai-agents package
from agents import Agent, Runner, function_tool
@function_tool
def lookup_order(order_id: str) -> str:
"""Look up an order by its ID. Returns status, items and total."""
... # your implementation
@function_tool(needs_approval=True)
def issue_refund(order_id: str, amount_cents: int, reason: str) -> str:
"""Issue a refund. ALWAYS requires human approval before running."""
...
agent = Agent(
name="Support agent",
instructions="You are a support agent. Look up orders before promising anything.",
tools=[lookup_order, issue_refund],
)
result = Runner.run_sync(agent, "Where is order A-1042?")
print(result.final_output)3.2 Anthropic Claude Agent SDK#
- Package:
claude-agent-sdk0.2.178, MIT, classifier "Development Status :: 3 - Alpha", Python ≥3.10 (PyPI, docs). The olderclaude-code-sdkpackage is superseded. - What it is — and isn't: despite the name, this is not a wrapper around the Messages API. It's a Python SDK that drives the Claude Code CLI (bundled with the package) as an agent harness: Claude gets Claude Code's built-in toolset (Read, Write, Edit, Bash, and others), its permission system, its subagents and its skills. You configure it with
ClaudeAgentOptionsand consume its message stream. - Key API:
query(prompt=..., options=...)returns an async iterator of messages (one-shot);ClaudeSDKClientfor bidirectional conversations withinterrupt()support;ClaudeAgentOptionswithsystem_prompt,allowed_tools,disallowed_tools,permission_mode("default","acceptEdits","plan","dontAsk","bypassPermissions","auto"— a model classifier reviews actions such as shell commands and network requests),max_turns,can_use_tool(a permission callback that replaces the interactive prompt),mcp_servers,agents(programmatic subagents),skills,setting_sources,model,add_dirs, andhooks(HookMatcheron events likePreToolUse). Custom tools are Python functions via@tool(name, description, input_schema)packaged withcreate_sdk_mcp_server(...)as an in-process MCP server — no subprocess. - Messages:
AssistantMessage,UserMessage,SystemMessage,ResultMessage; the result'ssubtypeis one of"success","error_during_execution","error_max_turns","error_max_budget_usd","error_max_structured_output_retries";model_usagegives per-model token accounting across the whole agent tree. - Watch out: it's Anthropic-only and it's really "Claude Code as a library" — the agent's worldview is a coding assistant with file/shell tools, so using it for a pure support bot means fighting its defaults. Alpha status means the API is still settling (the docs themselves warn behaviours may be refined between releases). Because it spawns the CLI, it inherits Claude Code's operational model: filesystem access, permission modes, session directories.
# illustrative — needs the claude-agent-sdk package
import anyio
from claude_agent_sdk import query, ClaudeAgentOptions, ClaudeSDKClient, tool, create_sdk_mcp_server
@tool("lookup_order", "Look up an order by ID", {"order_id": str})
async def lookup_order(args):
return {"content": [{"type": "text", "text": f"Order {args['order_id']}: shipped"}]}
server = create_sdk_mcp_server(name="support-tools", tools=[lookup_order])
options = ClaudeAgentOptions(
system_prompt="You are a support agent. Use the tools for order facts.",
mcp_servers={"support": server},
allowed_tools=["mcp__support__lookup_order"], # auto-approve; unlisted tools still need permission_mode/can_use_tool
permission_mode="default",
max_turns=10,
)
async def main():
async for message in query(prompt="Where is order A-1042?", options=options):
print(message) # AssistantMessage / UserMessage / SystemMessage / ResultMessage
anyio.run(main)3.3 Google Agent Development Kit (ADK)#
- Package:
google-adk2.13.0 (released 2026-10-22), Apache-2.0, Python ≥3.11 (PyPI, docs, changelog). ADK 2.0 also ships TypeScript, Go, Java and Kotlin SDKs. - What it is: Google's open-source, code-first framework for building, evaluating and deploying agents. It's simultaneously an agent-loop framework (
Agent+Runner), a graph-workflow engine (Workflow, new in 2.0), an evaluation toolkit (adk eval), and a deployment path (Cloud Run, GKE, Vertex AI Agent Engine). - Key API:
Agent(model='gemini-flash-latest', name=, description=, instruction=, tools=[...])— tools are plain Python functions, OpenAPI specs, MCP tools,google_search, or code executors.Runner(agent=, app_name=, session_service=...)drivesrunner.run_async(user_id=, session_id=, new_message=types.Content(...))which yields an async stream ofEvents (each withauthorandcontent.parts: text,function_call,function_response). Sessions are explicit:session_service.create_session(app_name, user_id, session_id, state={...}); backends areInMemorySessionServicefor dev,DatabaseSessionServiceandVertexAiSessionServicefor production, andMongoDbSessionService— which lives atgoogle.adk.integrations.mongodb, notgoogle.adk.sessions; it's experimental (FeatureName.MONGODB_SESSION_SERVICE) and needs thegoogle-adk[mongodb]extra. - Beyond the basics: graph
Workflows with deterministic edges (the ADK 2.0 headline), template workflows (sequential, loop, parallel), agent routing, "managed agents" and "ambient agents" runtime concepts, Agent Config (YAML-defined agents without code), callbacks/plugins, context compression, memory service, skills, A2A protocol support, live/voice agents, and built-in evaluation with criteria and simulated users. - Watch out: it's the broadest framework here — breadth means a bigger surface to learn and more places for version churn (2.13.0 alone promoted 12 experimental features to stable and changed the default OpenTelemetry schema). Gemini is the first-class model; other providers work but with less depth. Deployment ergonomics favour Google Cloud.
# illustrative — needs the google-adk package
import asyncio
from google.adk import Agent, Runner
from google.adk.sessions import InMemorySessionService
from google.genai import types
def lookup_order(order_id: str) -> dict:
"""Look up an order by its ID."""
return {"status": "success", "order_id": order_id, "state": "shipped"}
root_agent = Agent(
model="gemini-3.8-flash",
name="support_agent",
description="Support agent for order questions",
instruction="You are a support agent. Use lookup_order for order facts.",
tools=[lookup_order],
)
async def main():
session_service = InMemorySessionService()
session = await session_service.create_session(app_name="support", user_id="u-1")
runner = Runner(agent=root_agent, app_name="support", session_service=session_service)
async for event in runner.run_async(
user_id="u-1", session_id=session.id,
new_message=types.Content(role="user", parts=[types.Part(text="Where is order A-1042?")]),
):
if event.content:
for part in event.content.parts:
if part.text:
print(part.text)
asyncio.run(main())3.4 LangGraph and LangChain#
- Packages:
langgraph1.2.22,langchain1.5.0,langchain-core1.8.2, all MIT (current at time of writing, 18 November 2026).langchainandlangchain-coreneed Python 3.11+;langgraphitself needs 3.10+ (PyPI, docs). - What they are: two different products from LangChain Inc that are often conflated. LangChain is the component library: chat-model integrations (
init_chat_model("provider:model")), tools (@tool+bind_tools), retrievers, and a high-levelcreate_agent. LangGraph is the orchestration framework: you define a state graph — nodes are functions, edges are transitions, state is a typed dict with reducers — and LangGraph executes it with checkpointing, streaming, interrupts and (via LangSmith Deployment) durable hosting. LangChain agents are built on LangGraph. - Key API (Graph):
StateGraph(StateSchema)where state is aTypedDict(useAnnotated[list, operator.add]for append-style fields);add_node(name, fn),add_edge(START, node),add_conditional_edges(node, router_fn, [targets]),compile(checkpointer=...),invoke(state)/ainvoke. For the agent loop specifically, the canonical pattern is anllm_callnode (model with bound tools) → conditional edge →tool_node(LangGraph shipsToolNodeandtools_conditioninlanggraph.prebuilt) → back tollm_call.interrupt()pauses for human input;Command(resume=...)continues. Checkpointers (MemorySaver,SqliteSaver, Postgres) persist state across runs. - Key API (Functional): LangGraph 1.x added a functional API — define the agent as a single function with
@entrypoint/@taskdecorators — for people who want the durability without drawing the graph. - Watch out: LangGraph is the most code-heavy option here — you write the nodes, so you also own the bugs in them. The flip side is total control: nothing happens between your code and the model that you didn't write. LangChain's breadth (hundreds of integrations) is also its weight: dependency trees are large and the "which import do I use" question has several defensible answers. LangSmith tracing is the natural pairing but is a separate product/account.
- Go deeper: lessons 08F.4 to 08F.17 are the in-depth LangChain and LangGraph lessons; for migrating old code and for the dependency-hygiene rules for this stack, read 08F.15, Part 3 and 08F.15, Part 5.
# illustrative — needs the langgraph and langchain packages
from langgraph.graph import StateGraph, START, END
from langgraph.prebuilt import ToolNode, tools_condition
from langgraph.checkpoint.memory import MemorySaver
from langchain.chat_models import init_chat_model
from langchain.tools import tool
from typing_extensions import TypedDict, Annotated
import operator
@tool
def lookup_order(order_id: str) -> str:
"""Look up an order by its ID."""
return f"Order {order_id}: shipped"
model = init_chat_model("openai:gpt-6-luna").bind_tools([lookup_order])
class AgentState(TypedDict):
messages: Annotated[list, operator.add]
def call_model(state: AgentState):
return {"messages": [model.invoke(state["messages"])]}
builder = StateGraph(AgentState)
builder.add_node("agent", call_model)
builder.add_node("tools", ToolNode([lookup_order]))
builder.add_edge(START, "agent")
builder.add_conditional_edges("agent", tools_condition)
builder.add_edge("tools", "agent")
agent = builder.compile(checkpointer=MemorySaver())
result = agent.invoke({"messages": [("user", "Where is order A-1042?")]},
config={"configurable": {"thread_id": "chat-1"}})3.5 Pydantic AI#
- Package:
pydantic-ai/pydantic-ai-slim2.66.0, MIT, Python ≥3.11 (PyPI, docs). - What it is: the type-first agent framework from the Pydantic team. One
Agentclass covers the loop; everything else — tools, output types, dependencies, model choice — is expressed in Python types. Model selection is a string:Agent('openai:gpt-6.1-sol'),Agent('anthropic:claude-fable-5-2'),Agent('google-gla:gemini-3.8-flash')-style strings (check the models docs for the current provider prefixes). - Key API:
Agent(model, instructions=, deps_type=, output_type=, capabilities=[...]); tools via@agent.tool(receivesRunContextwith your dependencies) or@agent.tool_plain(plain function); runs viaagent.run/run_sync/run_stream/run_stream_events/iter;result.outputis the validated output type. Capabilities are reusable bundles — caching, web search, guardrails, memory, sub-agents, planning, compaction, persistence — that snap onto an agent. - The ecosystem:
pydantic-ai-harness( batteries-included capabilities likeCoder), Pydantic Evals (dataset and online evaluation of outputs and tool-call trajectories), Pydantic Graph (typed control flow when one agent loop isn't enough), Pydantic Logfire (OpenTelemetry-based observability the SDK instruments natively), the Pydantic AI Gateway (one key, many models, budget controls),TemporalDurabilityfor durable execution on Temporal, and Monty for sandboxed model-written code. - Testing: built for it —
TestModelcalls every tool then returns schema-valid dummy output,FunctionModellets you script responses,agent.override(...)swaps model/deps/toolsets inside app code, andALLOW_MODEL_REQUESTS=Falsemakes accidental live calls fail loudly. - Watch out: 2.x is a fast-moving major line with a documented V1→V2 migration map — read the upgrade guide before pinning. The capability/harness layer is powerful but young; the core
Agent+tool+output_typeloop is the stable heart. Model-string prefixes are Pydantic AI's own convention, not the providers'.
# illustrative — needs the pydantic-ai package
from pydantic_ai import Agent, RunContext
support_agent = Agent(
"openai:gpt-6-luna",
instructions="You are a support agent. Look up orders before promising anything.",
output_type=str,
)
@support_agent.tool_plain
async def lookup_order(order_id: str) -> str:
"""Look up an order by its ID. Returns status, items and total."""
... # your implementation
result = support_agent.run_sync("Where is order A-1042?")
print(result.output)3.6 Microsoft Agent Framework (and the AutoGen and Semantic Kernel story)#
- Package:
agent-framework1.24.0 (+agent-framework-core,agent-framework-foundry), MIT, Python/.NET/Go (PyPI, repo, docs). - The story you need to know: Microsoft consolidated its three agent stacks into one. AutoGen is archived (its README carries a do-not-use banner); Semantic Kernel still ships (
semantic-kernel1.47.0, withsemantic_kernel.agents.ChatCompletionAgent) but its README redirects new work to MAF; Microsoft Agent Framework is the "enterprise-ready successor" — version 1.0 APIs, long-term support commitment. - What it is: a multi-language framework for production agents and multi-agent workflows: sequential/concurrent/handoff/group collaboration patterns, checkpointing, streaming, human-in-the-loop, time-travel, middleware pipelines, OpenTelemetry, declarative YAML agents, agent skills, A2A and MCP interop, and "Foundry hosted agents" deployment to Microsoft Foundry with ~2 lines of code.
- Watch out: it's the enterprise-weight option — the breadth (workflows, middleware, hosting, declarative agents) means a steeper start than Pydantic AI or the provider SDKs, and its centre of gravity is the Microsoft ecosystem (Foundry, Azure OpenAI, Copilot SDK) even though it supports other providers.
3.7 CrewAI#
CrewAI is the popular framework for crews of role-based agents (plus Flows for deterministic control); use it for role-separated or demo-style multi-agent work, not for a single-agent bot. See the comparison table (row: CrewAI) and the full entry in Part 8.
3.8 LlamaIndex#
- Package:
llama-index/llama-index-core0.14.25, MIT (PyPI, repo). - What it is — and the honest caveat: LlamaIndex built its name on RAG (Module 07 territory) and its agent features —
Workflowsfor orchestration andAgent/AgentWorkflowfor agent loops — remain in the OSS framework. But the company's stated focus has shifted to LlamaParse, its commercial document-parsing platform; the README says the OSS framework "is still available as an open toolkit" while "our primary focus has shifted towards LlamaParse". Hosted offerings: LlamaAgents (deployed document agents) and Agent Builder. - Watch out: fine for RAG-centric agent work inside the LlamaIndex ecosystem; think twice for a greenfield general agent where framework momentum matters — check commit activity and issue response times before committing.
3.9 smolagents#
smolagents is Hugging Face's small agent library whose CodeAgent writes its actions as Python code; take the sandbox seriously. See the comparison table (row: smolagents) and the full entry in Part 8.
3.10 Haystack#
Haystack is deepset's pipeline-first framework for production RAG, with an Agent component for tool loops; look at it when retrieval is central. See the comparison table (row: Haystack) and the full entry in Part 8.
3.11 DSPy#
DSPy is not an agent framework: it is a programming model whose optimizers compile prompts and demonstrations against a metric. See the comparison table (row: DSPy) and the full entry in Part 8.
3.12 The TypeScript side (mention only)#
If your stack is TypeScript, the two frameworks that matter are Vercel AI SDK (ai 7.0.163 on npm — generateText/streamText with tool loops and stopWhen conditions, the default for Next.js AI features) and Mastra (@mastra/core 1.82.0 — a fuller agent/workflow framework with memory, workflows and evals). Both are real, actively developed and worth a look if Python isn't your language; they don't change the trade-offs in this lesson, which are language-independent. OpenAI's Agents SDK and LangGraph also ship TypeScript versions.
3.13 The no-framework option#
Worth stating plainly because it's a legitimate choice, not a fallback: your own loop plus the thin provider-agnostic client from 03.11, the ToolRegistry from 08A.6, and the canonical loop from 08A.2. You own every line, every retry decision and every byte on the wire. The cost is that sessions, tracing, HITL resume, guardrails and durable execution are your code — which is exactly what Parts 4–6 of this lesson help you build or buy deliberately.
3.14 Survey-only frameworks at a glance#
Four of the frameworks above (CrewAI, smolagents, Haystack and DSPy) get no code sketch in the rest of this lesson, because the running example does not use them. Mastra, Agno and AutoGPT-style projects are in the survey too, but until now only in passing. This table puts all seven side by side so you can see which, if any, deserves a longer look. The full entries for the first four are in Part 8 (reference depth). Facts are as of 2 December 2026, checked against each project's repository, docs or package index; the versions of the first four are the November 2026 versions used elsewhere in this lesson.
| Framework | Language | What it is for | Maintainer | Maturity | When to look at it |
|---|---|---|---|---|---|
| CrewAI (full entry) | Python | Crews of role-based agents (role, goal, backstory), plus Flows for deterministic, event-driven orchestration |
CrewAI Inc (a venture-backed company; commercial AMP Suite for tracing and governance) | crewai 1.15.x, MIT. Very popular; 1.x |
You want role-separated agents, or a quick multi-agent demo. Skip it for a single-agent bot |
| smolagents (full entry) | Python | A small agent library whose CodeAgent writes its actions as Python code instead of JSON tool calls |
Hugging Face | smolagents 1.26.0, Apache-2.0. 1.x, small and focused |
Data-analysis and tool-composition tasks, if you can run generated code in a sandbox |
| Haystack (full entry) | Python | Pipelines of components (retrievers, rankers, routers, generators) for production RAG, plus an Agent component for tool loops |
deepset | haystack-ai 3.4.1, Apache-2.0. Long-established |
Retrieval is central to the product (pairs with Module 07) |
| DSPy (full entry) | Python | Not an agent loop. A programming model for LM pipelines whose prompts and demonstrations are compiled by optimizers against a metric | Stanford NLP | dspy 3.5.0, MIT. Widely used in research and prompt optimisation |
The prompts are the product and you have a metric to optimise (classification, extraction, multi-hop QA) |
| Mastra | TypeScript | A TypeScript framework for AI agents and apps: an Agent class with tools, memory, observability, a local Studio UI, and workflows that fix the order of steps |
Mastra (a company; the mastra-ai GitHub organisation, Y Combinator W25 badge on the repo) |
@mastra/core 1.86.0 on npm; about 30k GitHub stars. Apache-2.0, except code under ee/ directories, which needs a Mastra Enterprise License for production use |
Your stack is TypeScript and you want more than the Vercel AI SDK's tool loop (see 3.12) |
| Agno | Python | An SDK for agents, teams and workflows, plus AgentOS, a FastAPI-based runtime that serves them as an API and MCP server, with a control plane and Postgres storage for memory and traces | Agno (the agno-agi GitHub organisation; PyPI contact "Agno Team") |
agno 3.2.1 (latest GitHub release, 17 November). Apache-2.0, PyPI "Production/Stable", about 43k GitHub stars |
You want agents served as a durable service with memory and a management UI built in, and you accept an opinionated platform |
| AutoGPT-style projects | Python (the repo is tagged Python; the language of each part is unverified as of 2026-12-02) | The original "give it a goal and let it loop" autonomous agent (AutoGPT Classic), and today's AutoGPT Platform, a hosted or self-hosted builder for agents and workflows | Significant Gravitas (the Significant-Gravitas GitHub organisation) |
Platform v0.12.1 (latest GitHub release, 26 November). Very high star count (about 188k) but a 0.x platform. The autogpt_platform/ folder is under Polyform Shield 1.0.0 (no reselling as a competing hosted service); the rest of the repo is MIT |
For history and for how open-ended autonomous loops fail (see 08A.3). It is not a default choice for a production agent |
Part 4: The same agent, four ways#
Time to make the abstract concrete. We'll take one agent — the running example's support assistant — and implement it four ways: your own loop, OpenAI Agents SDK, Pydantic AI and LangGraph. (Claude Agent SDK and Google ADK were covered in Part 3; their versions of this agent look like their Part 3 sketches wrapped around the same tools file, and 4.6 says why they didn't make the deep cut.)
4.1 The agent and its tools#
The agent's job: answer support questions for the fictional company. It can look up orders, search the docs (the Module 07 docs_qa retriever concept, faked here), create tickets, run reports — and issue refunds only after human approval. Every tool is a plain Python function over in-memory fake data, exactly per 08A.6. This file is shared verbatim by all four implementations.
# support_tools.py — the running example's tools, framework-agnostic on purpose.
# Every implementation in this lesson wraps THESE functions; nothing here knows
# which framework is calling it.
from __future__ import annotations
ORDERS = {
"A-1042": {"status": "shipped", "total_cents": 12_990, "items": ["desk lamp", "USB-C cable"]},
"B-2077": {"status": "processing", "total_cents": 4_500, "items": ["noise-cancelling headphones"]},
"C-3390": {"status": "delivered", "total_cents": 8_750, "items": ["espresso machine"]},
}
TICKETS: dict[str, dict] = {}
DOCS = [
{"title": "Refund policy", "text": "Refunds are issued within 14 days of delivery for unused items."},
{"title": "Shipping times", "text": "Standard shipping takes 3-5 business days; express takes 1-2."},
{"title": "Warranty", "text": "All electronics carry a 2-year limited warranty."},
]
_next_ticket = 1000
def lookup_order(order_id: str) -> dict:
"""Look up an order by ID. Returns status, items and total in cents."""
order = ORDERS.get(order_id.strip().upper())
if order is None:
return {"error": f"no order found with id {order_id!r}; check the order number on the confirmation email"}
return {"order_id": order_id.strip().upper(), **order}
def search_docs(query: str) -> list[dict]:
"""Search the support documentation. Returns matching title/text pairs."""
terms = {t for t in query.lower().split() if len(t) > 3}
return [d for d in DOCS if terms & set(d["text"].lower().split())]
def create_ticket(subject: str, body: str, priority: str = "normal") -> dict:
"""Create a support ticket. priority is 'low', 'normal' or 'high'."""
global _next_ticket
if priority not in {"low", "normal", "high"}:
return {"error": f"priority must be low, normal or high, got {priority!r}"}
_next_ticket += 1
ticket = {"id": f"T-{_next_ticket}", "subject": subject, "body": body, "priority": priority}
TICKETS[ticket["id"]] = ticket
return ticket
def issue_refund(order_id: str, amount_cents: int, reason: str) -> dict:
"""Issue a refund against an order. DESTRUCTIVE: moves money; always needs approval."""
order = ORDERS.get(order_id.strip().upper())
if order is None:
return {"error": f"no order found with id {order_id!r}"}
if amount_cents <= 0 or amount_cents > order["total_cents"]:
return {"error": f"amount must be between 1 and {order['total_cents']} cents"}
return {"refunded_cents": amount_cents, "order_id": order_id.strip().upper(), "reason": reason}
def run_report(report: str, period: str) -> dict:
"""Run a canned ops report. report is 'tickets_summary' or 'orders_by_status'."""
if report == "tickets_summary":
return {"report": report, "period": period, "open_tickets": len(TICKETS)}
if report == "orders_by_status":
counts: dict[str, int] = {}
for o in ORDERS.values():
counts[o["status"]] = counts.get(o["status"], 0) + 1
return {"report": report, "period": period, "orders_by_status": counts}
return {"error": f"unknown report {report!r}; try 'tickets_summary' or 'orders_by_status'"}Run it once to see the shapes the model will see:
python3 -c "
from support_tools import lookup_order, search_docs, create_ticket, issue_refund
print(lookup_order('a-1042'))
print(search_docs('how long does shipping take'))
print(create_ticket('Late delivery', 'Order arrived late', 'high'))
print(issue_refund('A-1042', 5000, 'goodwill'))
"{'order_id': 'A-1042', 'status': 'shipped', 'total_cents': 12990, 'items': ['desk lamp', 'USB-C cable']}
[{'title': 'Shipping times', 'text': 'Standard shipping takes 3-5 business days; express takes 1-2.'}]
{'id': 'T-1001', 'subject': 'Late delivery', 'body': 'Order arrived late', 'priority': 'high'}
{'refunded_cents': 5000, 'order_id': 'A-1042', 'reason': 'goodwill'}4.2 Way one: your own loop#
08A.2 built this: a call_model function you inject, a ToolRegistry that validates arguments and wraps exceptions as error results, budgets (max steps, max tokens, max cost, wall-clock), stop conditions, and a ScriptedModel that replays canned tool calls so the whole thing is unit-testable with no API key. The support agent is just call_model + five registry.register(...) calls + the system prompt.
The honest summary: ~40 lines of your code own the loop; everything else the providers' APIs demand — streaming edge cases, retry policy, reasoning-item preservation, tool-call bookkeeping, resumable state — is still yours to build and maintain. Approval for issue_refund is a policy check in your dispatch layer — refuse until a human says yes, then re-run.
4.3 Way two: OpenAI Agents SDK#
# illustrative — needs openai-agents; assumes support_tools.py beside this file
from agents import Agent, Runner, function_tool
from support_tools import lookup_order, search_docs, create_ticket, issue_refund, run_report
SUPPORT_INSTRUCTIONS = """You are the support agent for Acme. Rules:
- Always look up the order before discussing its status or issuing anything.
- Refunds are destructive: the issue_refund tool pauses for human approval — use it only
when the customer explicitly asks for money back and the order is eligible.
- Search the docs before answering policy questions.
- If you can't resolve it, create a ticket and tell the customer the ticket ID."""
@function_tool
def lookup_order_tool(order_id: str) -> dict:
"""Look up an order by ID. Returns status, items and total."""
return lookup_order(order_id)
@function_tool
def search_docs_tool(query: str) -> list[dict]:
"""Search support documentation. Returns matching doc snippets."""
return search_docs(query)
@function_tool
def create_ticket_tool(subject: str, body: str, priority: str = "normal") -> dict:
"""Create a support ticket. priority: low, normal or high."""
return create_ticket(subject, body, priority)
@function_tool(needs_approval=True) # pauses the run; a human approves before it executes
def issue_refund_tool(order_id: str, amount_cents: int, reason: str) -> dict:
"""Issue a refund. ALWAYS requires human approval."""
return issue_refund(order_id, amount_cents, reason)
@function_tool
def run_report_tool(report: str, period: str) -> dict:
"""Run an ops report: 'tickets_summary' or 'orders_by_status'."""
return run_report(report, period)
agent = Agent(
name="Support agent",
instructions=SUPPORT_INSTRUCTIONS,
tools=[lookup_order_tool, search_docs_tool, create_ticket_tool,
issue_refund_tool, run_report_tool],
# model="gpt-6-luna", # optional; omit to use the SDK's configured default model — set it explicitly in production
)
result = Runner.run_sync(agent, "My order A-1042 arrived damaged. What's the status?")
print(result.final_output)
# If issue_refund_tool was called, the run pauses instead of finishing:
if result.interruptions:
# result.interruptions lists the pending approvals; after a human decides,
# resume the serialized RunState (see the HITL docs — approval state is
# designed to survive process restarts for long-running approvals).
passWhat the framework now owns for you: the loop, schema generation from type hints and docstrings, tool-call dispatch, conversation state across the run's turns, the approval pause/resume machinery, input/output guardrails (add @input_guardrail/@output_guardrail decorators that return GuardrailFunctionOutput(tripwire_triggered=...)), tracing to OpenAI's tracing UI, and sessions for history across runs — agents.memory provides SQLiteSession and the OpenAI conversation/compaction sessions, while agents.extensions.memory adds the SQLAlchemy, async-SQLite, Redis, MongoDB, Dapr and encrypted stores.
4.4 Way three: Pydantic AI#
# illustrative — needs pydantic-ai; assumes support_tools.py beside this file
from pydantic_ai import Agent, DeferredToolRequests, DeferredToolResults
from support_tools import lookup_order, search_docs, create_ticket, issue_refund, run_report
support_agent = Agent(
"openai:gpt-6-luna", # "provider:model" — swap to anthropic:/google-gla: etc.
instructions="""You are the support agent for Acme. Always look up the order
before discussing its status. Refunds need human approval, which the framework
enforces — call issue_refund only on an explicit request. Search docs before
policy answers. Create a ticket if unresolved.""",
# A run may now END with a DeferredToolRequests (pending approvals) instead of text.
output_type=[str, DeferredToolRequests],
# capabilities=[Caching()], # e.g. prompt caching — see the capabilities docs
)
@support_agent.tool_plain
async def lookup_order_tool(order_id: str) -> dict:
"""Look up an order by ID. Returns status, items and total."""
return lookup_order(order_id)
@support_agent.tool_plain
async def search_docs_tool(query: str) -> list[dict]:
"""Search support documentation."""
return search_docs(query)
@support_agent.tool_plain
async def create_ticket_tool(subject: str, body: str, priority: str = "normal") -> dict:
"""Create a support ticket. priority: low, normal or high."""
return create_ticket(subject, body, priority)
@support_agent.tool_plain(requires_approval=True) # the run pauses before this body executes
async def issue_refund_tool(order_id: str, amount_cents: int, reason: str) -> dict:
"""Issue a refund. Destructive — only after explicit customer request."""
return issue_refund(order_id, amount_cents, reason)
@support_agent.tool_plain
async def run_report_tool(report: str, period: str) -> dict:
"""Run an ops report: 'tickets_summary' or 'orders_by_status'."""
return run_report(report, period)
result = support_agent.run_sync("Please refund 5000 cents on order A-1042, it arrived damaged.")
if isinstance(result.output, DeferredToolRequests):
# A human reviews result.output.approvals: each entry carries tool_name, args, tool_call_id.
decisions = DeferredToolResults()
for call in result.output.approvals:
decisions.approvals[call.tool_call_id] = True # or ToolDenied("reason") / ToolApproved(override_args=...)
result = support_agent.run_sync(
"Continue",
message_history=result.all_messages(),
deferred_tool_results=decisions,
)
print(result.output)What changed versus the Agents SDK version: the tools are async Python functions whose signatures are the schema — no wrapper decorators generating JSON Schema behind your back, and RunContext/deps_type give you typed dependency injection when tools need a database handle or user context. Approval is deferred tool requests: mark the tool requires_approval=True, add DeferredToolRequests to the agent's output_type, and when the model calls the tool the run ends with that object instead of text; you collect decisions into DeferredToolResults (a boolean, ToolApproved with override_args to edit the arguments, or ToolDenied with a message the model reads) and start a new run with the original message_history. To pause across processes, persist the run's conversation rather than only the messages (see the deferred-tools docs, which also warn that approval is not an authorization boundary if a client can submit history — enforce permissions inside the tool). The shape was read from the deferred-tools docs on 8 November 2026; the API has moved across 2.x minors, so check the page for the version you installed. Testing is the standout: TestModel runs the whole agent, calls every tool and returns schema-valid output — no API key, deterministic, CI-friendly.
4.5 Way four: LangGraph#
# illustrative — needs langgraph and langchain; assumes support_tools.py beside this file
from typing_extensions import TypedDict, Annotated
import operator
from langgraph.graph import StateGraph, START, END
from langgraph.prebuilt import ToolNode, tools_condition
from langgraph.checkpoint.memory import MemorySaver
from langgraph.types import interrupt, Command
from langchain.chat_models import init_chat_model
from langchain.tools import tool
from support_tools import lookup_order, search_docs, create_ticket, issue_refund, run_report
@tool
def lookup_order_tool(order_id: str) -> dict:
"""Look up an order by ID."""
return lookup_order(order_id)
@tool
def search_docs_tool(query: str) -> list[dict]:
"""Search support documentation."""
return search_docs(query)
@tool
def create_ticket_tool(subject: str, body: str, priority: str = "normal") -> dict:
"""Create a support ticket."""
return create_ticket(subject, body, priority)
@tool
def issue_refund_tool(order_id: str, amount_cents: int, reason: str) -> str:
"""Issue a refund. PAUSES for human approval before executing."""
decision = interrupt({ # graph pauses here; state is checkpointed
"approval_needed": "issue_refund",
"order_id": order_id, "amount_cents": amount_cents, "reason": reason,
})
if not decision.get("approved"):
return "Refund rejected by the reviewer."
return str(issue_refund(order_id, amount_cents, reason))
@tool
def run_report_tool(report: str, period: str) -> dict:
"""Run an ops report."""
return run_report(report, period)
tools = [lookup_order_tool, search_docs_tool, create_ticket_tool,
issue_refund_tool, run_report_tool]
model = init_chat_model("openai:gpt-6-luna").bind_tools(tools)
class AgentState(TypedDict):
messages: Annotated[list, operator.add] # reducer: new messages append, never replace
def call_model(state: AgentState):
return {"messages": [model.invoke(state["messages"])]}
builder = StateGraph(AgentState)
builder.add_node("agent", call_model)
builder.add_node("tools", ToolNode(tools))
builder.add_edge(START, "agent")
builder.add_conditional_edges("agent", tools_condition) # "tools" or END
builder.add_edge("tools", "agent")
checkpointer = MemorySaver() # swap for SqliteSaver/Postgres for durability
agent = builder.compile(checkpointer=checkpointer)
# Turn 1: the refund request pauses inside issue_refund_tool at interrupt()
config = {"configurable": {"thread_id": "support-chat-1"}}
result = agent.invoke({"messages": [("user", "Refund order A-1042 please")]}, config)
# A human reviews result["__interrupt__"], then resumes the SAME thread:
agent.invoke(Command(resume={"approved": True}), config)What changed: you drew the loop. The agent node calls the model, tools_condition routes to ToolNode when the model emits tool calls, and the edge back to agent is the loop — there is no hidden "agent runner", every transition is a line you wrote. That buys you interrupt()/Command(resume=...) for approvals with checkpointed state (swap MemorySaver for SqliteSaver/Postgres and the pause survives restarts), explicit state you can inspect and branch on, and total control over what happens between turns. It costs you the most code and the most conceptual surface — which is the point of the comparison.
4.6 Side-by-side comparison#
| Own loop (08A.2) | OpenAI Agents SDK | Pydantic AI | LangGraph | |
|---|---|---|---|---|
| Core object | call_model + ToolRegistry |
Agent + Runner |
Agent |
StateGraph you compile |
| Who owns the loop | You | The SDK | The library | You (it's a graph) |
| Tool definition | Register functions + JSON schema | @function_tool, schema from signature |
@agent.tool_plain, signature is the schema |
@tool from LangChain + ToolNode |
| Approval | Your dispatch policy | needs_approval → interruptions → resume RunState |
requires_approval=True → DeferredToolRequests → resume with DeferredToolResults |
interrupt() + Command(resume=...) |
| State across runs | Your store | Sessions (agents.memory/extensions.memory) |
Message history / your store | Checkpointer (MemorySaver→Postgres) |
| Tracing | Your trace_id logging |
Built-in → OpenAI tracing UI | Logfire (OTel) / your hooks | LangSmith or your own |
| Testing | ScriptedModel replays tool calls |
SDK test utilities | TestModel/FunctionModel/override |
Fake model or scripted nodes |
| Provider reach | Whatever call_model wraps |
OpenAI native; 100+ via adapters | Dozens via model strings | Any LangChain chat model |
| Lines of orchestration you own | All of it | ~10 (Agent + tools + run) | ~10 (Agent + tools + run) | ~30 (nodes, edges, state, checkpointer) |
| Best when | You need total control or already built it | OpenAI shop wanting the reference impl | Typed, multi-provider, test-heavy | Complex stateful flows, durability, explicit control |
The pattern to notice: the frameworks don't disagree about the loop — they disagree about how much of it you see. Agents SDK and Pydantic AI hide the loop behind run; LangGraph makes the loop be the program; your own loop is the same idea with no packaging. Pick the amount of visibility your team can debug.
Why these four, and not Claude Agent SDK or Google ADK? Both can run this agent — their Part 3 sketches show the shape — but neither would have added a new point on the axis this comparison is built around: how much of the loop you see. The Claude Agent SDK hides the loop behind query() exactly like the Agents SDK does, and its distinguishing features point the other way: it's a coding-agent harness whose agent arrives with Claude Code's file/shell tools and a coding assistant's worldview, so a provider-neutral support bot mostly demonstrates how to fight its defaults (3.2's "Watch out"). Google ADK's agent mode likewise hides the loop behind Runner.run_async; its genuinely different machinery — graph Workflows, explicit session services, the adk eval harness — sits on a different axis (workflow structure and evaluation rather than loop visibility) and is surveyed in 3.3. The four implementations above span the meaningful design space for this agent: a hidden loop with minimal ceremony, a hidden loop with types and dependency injection, an explicit graph, and no packaging. Claude Agent SDK would have been the right choice for a coding agent — that's 08A.15's territory — and ADK workflows would have been right for a multi-step pipeline; for this support bot they would have been a fifth column that mostly remixed the first.
Part 5: Cross-framework concerns#
Deep-dive
Whatever you choose, these concerns apply identically — they're the parts frameworks can't decide for you.
5.1 Portability: keep tools and prompts framework-agnostic#
The single most valuable habit: define tools once, as plain functions plus JSON schemas, and write a thin adapter per framework. Every framework in the survey ultimately needs the same three things from a tool — a name, a description, a JSON Schema for arguments, and a callable. Your support_tools.py already is that; the adapters are 5–15 lines each:
# toolspec.py — the framework-neutral tool contract (pure Python, stdlib only)
from __future__ import annotations
from dataclasses import dataclass
import inspect, json, typing
@dataclass(frozen=True)
class ToolSpec:
name: str
description: str
fn: object # callable
parameters: dict # JSON Schema object
def schema_from_signature(fn) -> dict:
"""Minimal JSON Schema from a function signature (stdlib only)."""
sig = inspect.signature(fn)
hints = typing.get_type_hints(fn) # resolves 'int' etc. even under `from __future__ import annotations`
props, required = {}, []
for pname, p in sig.parameters.items():
if pname in {"self", "ctx"}:
continue
py = hints.get(pname, str)
jtype = {int: "integer", float: "number", bool: "boolean", dict: "object",
list: "array", str: "string"}.get(py, "string")
props[pname] = {"type": jtype, "description": ""}
if p.default is inspect.Parameter.empty:
required.append(pname)
return {"type": "object", "properties": props, "required": required,
"additionalProperties": False}
def register(fn) -> ToolSpec:
return ToolSpec(fn.__name__, (fn.__doc__ or "").strip(), fn, schema_from_signature(fn))
# Usage — the same ToolSpec feeds any framework's adapter:
# OpenAI Agents SDK: @function_tool wrapping spec.fn (or ToolSpec -> FunctionTool)
# Pydantic AI: @agent.tool_plain spec.fn
# LangGraph: langchain @tool spec.fn -> ToolNode
# Claude Agent SDK: @tool(spec.name, spec.description, typedict_or_jsonschema)
# Google ADK: tools=[spec.fn] (plain function)
# Your own loop: registry.register(spec.fn, spec.parameters)Run it:
python3 -c "
from toolspec import register
from support_tools import lookup_order, issue_refund
import json
for f in (lookup_order, issue_refund):
s = register(f)
print(s.name, '->', json.dumps(s.parameters))
"lookup_order -> {"type": "object", "properties": {"order_id": {"type": "string", "description": ""}}, "required": ["order_id"], "additionalProperties": false}
issue_refund -> {"type": "object", "properties": {"order_id": {"type": "string", "description": ""}, "amount_cents": {"type": "integer", "description": ""}, "reason": {"type": "string", "description": ""}}, "required": ["order_id", "amount_cents", "reason"], "additionalProperties": false}Keep prompts framework-agnostic the same way: store the system prompt and tool descriptions as versioned text (04.10), inject them into whatever the framework's instructions=/system_prompt= parameter accepts. A prompt tuned inside one framework's implicit scaffolding may not port — test it on the new one.
5.2 Testing agents built on frameworks#
The golden rule from 03.10 applies harder here: never let a unit test call a real model. Each framework gives you a different fake:
| Framework | The fake | How |
|---|---|---|
| Your own loop | ScriptedModel (08A.2) |
Replays canned call_model responses — tool calls, then final answer |
| OpenAI Agents SDK | Its testing utilities + RunConfig(tracing_disabled=...) |
Script the model or use the SDK's test helpers; disable tracing in tests |
| Pydantic AI | TestModel, FunctionModel, agent.override(...) |
TestModel calls every tool and returns schema-valid dummy output; ALLOW_MODEL_REQUESTS=False blocks accidents |
| LangGraph | Fake chat model or scripted nodes | Swap init_chat_model for a stub returning canned AIMessages; nodes are plain functions — test them directly |
| Claude Agent SDK | query() over a fake transport |
The SDK accepts a custom transport — point it at a stub CLI process |
| Google ADK | InMemorySessionService + fake model |
Swap the model= string for a test model; adk eval for trajectory evals |
Two patterns worth stealing regardless of framework: (1) test tools as pure functions first (they're just Python — support_tools.py needs no framework), then test the orchestration with a scripted model; (2) keep one "golden trajectory" test — a fixed input, a fixed sequence of model responses, asserting the exact tool calls and final output — because it catches the class of bugs frameworks introduce silently (reordered messages, dropped IDs, changed defaults).
5.3 Tracing and observability#
Every framework assumes you'll want to see inside the loop; they differ on where traces go:
| Framework | Built-in tracing | Export / backend |
|---|---|---|
| OpenAI Agents SDK | Yes — traces every run, span per turn/tool/handoff | OpenAI tracing UI; processor interface for custom exporters |
| Pydantic AI | Via Logfire instrumentation (OpenTelemetry) | Logfire, or any OTel backend (Phoenix, Langfuse, Datadog...) |
| LangGraph | Via LangSmith | LangSmith (hosted), or OpenTelemetry/Langfuse via callbacks |
| Google ADK | OpenTelemetry GenAI semantic conventions (v2 default since 2.13) | Any OTel collector → Jaeger/Tempo/Honeycomb/etc. |
| Claude Agent SDK | Session/message stream you consume yourself | Your logging; model_usage for per-model tokens |
| Your own loop | Whatever you build (03.10) | Your choice |
The engineering point: pick the trace backend first, then make sure the framework can emit to it. OpenTelemetry GenAI semantic conventions are becoming the lingua franca — ADK defaults to them, Pydantic AI's Logfire is built on them, and the major hosted tracers (Langfuse, Phoenix, LangSmith, Braintrust, Arize) all ingest OTel. Whichever framework you pick, verify it can emit OTel or has a processor/plugin hook before you need the trace in an incident. Deep coverage of tracing platforms is Module 11A.
5.4 Durable execution and checkpointing#
"Durable" means the run survives process death, deployment, and long waits for humans. The options, roughly in order of increasing power:
| Mechanism | Who provides it | Survives restart? | Best for |
|---|---|---|---|
| Framework session store | Agents SDK SQLiteSession/Redis/Mongo; ADK session services; LangGraph MemorySaver→SqliteSaver |
File/DB-backed ones, yes | Conversation continuity across runs |
| Checkpointer inside the graph | LangGraph checkpointers; Pydantic AI persistence capability | Yes — state is external | Resumable multi-step flows, HITL pauses |
| Durable-execution engine | Temporal (Pydantic AI TemporalDurability), Restate, DBOS, Hatchet, Inngest |
Yes — the engine owns the run | Long-running agents, sagas, retries at step level |
| Hosted agent platform | Anthropic Managed Agents sessions; OpenAI Conversations API | Yes — server-side state | When you want zero ops |
The lesson for engineers: durability is a spectrum, and "the framework has sessions" is not the same as "the run is durable." A session that stores messages lets you continue a conversation; a checkpointer that snapshots graph state lets you resume mid-run; a Temporal workflow lets the run survive your server being redeployed. Match the mechanism to the failure you're actually afraid of — and remember every durable layer adds a state schema you now own and must migrate (08A.14).
5.5 Human-in-the-loop primitives#
Approval is where frameworks differ most in feel even when they agree on mechanism:
| Framework | Mechanism | Resume API | Approval state lives |
|---|---|---|---|
| OpenAI Agents SDK | needs_approval on tool → run pauses with interruptions |
Resume serialized RunState |
Run state (serializable; designed for long-running approvals) |
| Pydantic AI | requires_approval=True → DeferredToolRequests |
New run with deferred_tool_results |
Your result object / store |
| LangGraph | interrupt() inside a node/tool |
Command(resume=...) on same thread_id |
Checkpointer (external state) |
| Claude Agent SDK | can_use_tool callback / permission_mode / hooks (PreToolUse can deny) |
Same session continues | Claude Code session |
| Google ADK | Tool confirmation flow (HITL), callbacks | Resume the run/event loop | Session state |
| Your own loop | Policy check in dispatch | Re-call call_model with decision appended |
Your store |
The pattern underneath is identical everywhere: pause → serialize enough state to resume → record the human's decision → continue. What differs is how much machinery the framework gives you for free versus how much you wire yourself. For destructive tools (refunds, deletes, sends), prefer the framework whose approval state is external and auditable — LangGraph's checkpointer or a Managed Agents session beats an in-process flag every time.
5.6 Guardrails features#
Input/output guardrails — validation that runs around the model call — exist in most frameworks but with different shapes:
- OpenAI Agents SDK:
@input_guardrail/@output_guardraildecorators; run in parallel with the agent,tripwire_triggeredfails fast. - Pydantic AI: guardrails as capabilities/hooks; output types validate structure;
output_retriesfor self-correction. - LangGraph: no built-in guardrail abstraction — you write them as nodes (which is flexibility or tedium depending on taste).
- Claude Agent SDK:
can_use_toolpermission callback +PreToolUsehooks can deny/modify tool calls deterministically. - Google ADK: callbacks/plugins wrap every model and tool call; "guardrails" docs cover input/output checks.
- CrewAI/others: vary widely — check before assuming.
5.7 Streaming and structured output#
- Streaming: every framework streams, but the event granularity differs — Agents SDK gives run-item events, Pydantic AI gives
AgentStreamEvents (part start/delta/end), LangGraph streams node-level updates, ADK streamsEvents, Claude Agent SDK streams messages. If your UI needs token-level prose and structured tool-call visibility, check which events each emits before committing. - Structured output: frameworks lean on the provider mechanisms from 03.4 — Pydantic AI's
output_typeis the cleanest expression (a Pydantic model in, validated object out, retries built in); Agents SDK has output-type support; LangGraph/LangChain use the provider's JSON mode or tool-call tricks; ADK relies on Gemini's structured output. Whatever the framework, your own validation still runs — the framework's "typed output" is a convenience, not a guarantee (03.4).
5.8 Upgrades, churn and migration#
Agent frameworks are young enough that the API you coded against will change. Practical rules:
- Pin exact versions and commit the lockfile (03.11, 13.9).
openai-agentsis 0.x; Pydantic AI ships V1→V2 migration maps; LangGraph restructures between minors. - Read the changelog before upgrading, not after. Frameworks mark breaking changes; agent behaviour can change without any API change (a new default model, a changed system-prompt template, different retry counts).
- Keep prompts and tools outside the framework (5.1) so a migration is an adapter rewrite, not a rewrite.
- Re-run your agent evals on every framework upgrade. A "patch" release can change tool-call ordering or context assembly enough to alter outputs — treat framework upgrades like model upgrades: eval before deploy.
- For the LangChain and LangGraph stack, go deeper: lessons 08F.4 to 08F.17 teach it in depth (08F.15, Part 3 is the migration playbook and Part 5 the dependency hygiene).
- Have a migration path before you need it. The AutoGen→MAF and Semantic Kernel→MAF consolidations prove frameworks get archived; know what your exit looks like while it's cheap.
5.9 Dependency security#
An agent framework is a large dependency tree — LangChain pulls integrations, CrewAI pulls chromadb and celery, ADK pulls fastapi/google-cloud, Pydantic AI's full extras pull dozens of model clients. The 03.11 dependency-hygiene checklist applies verbatim: exact pins, committed lockfile, hash-checked installs, reviewed upgrades, suspicion of new transitive deps, least-privilege keys, and awareness that the framework runs your tools with your credentials — a compromised or over-privileged framework is a compromised agent. Prefer frameworks whose dependency footprint you can audit (uv pip compile the install and read the list) and whose licence and maintenance you can verify.
Part 6: Low-code builders and hosted agent platforms#
Reference
Everything so far assumed you run the agent. There's a third option: someone else runs it. This part is deliberately awareness-level — enough to know what exists and when it's the right answer, with pointers to verify current state before committing.
6.1 Hosted agent platforms per provider#
| Provider | What exists (as of November 2026) | Status |
|---|---|---|
| OpenAI | Assistants API — shut down 26 August 2026 (deprecations). AgentKit (launched Oct 2025) bundled Agent Builder (visual workflow canvas), the Connector Registry, ChatKit (embeddable chat UI) and expanded Evals capabilities (datasets, trace grading, prompt optimization). OpenAI is winding down Agent Builder and Evals (announced 3 June 2026) — existing evals became read-only on 31 October 2026 and both products shut down on 30 November 2026 (deprecations page, opened 11 November 2026); ChatKit remains; OpenAI's recommended path is the Agents SDK or ChatGPT Workspace Agents. Conversations API for server-side state. | In flux — the hosted-agent story is deliberately narrowing to SDK + ChatKit |
| Anthropic | Claude Managed Agents (beta, managed-agents-2026-04-01 header): hosted agent harness with Agents, Environments (Anthropic cloud sandbox or self-hosted), Sessions and Events (docs). Stateful sessions resume after pauses; not ZDR/HIPAA eligible; MCP tunnels and "dreaming" in research preview. |
Beta, enabled by default on API accounts |
Gemini Enterprise Agent Platform (formerly Vertex AI, renamed April 2026) with Vertex AI Agent Engine for deploying ADK agents; Deep Research agent product; ADK's adk deploy targets Cloud Run/GKE/Agent Engine; Interactions API background mode for long-running agents (03.9). |
Production platform | |
| OpenRouter | Model gateway only — no hosted agent runtime. Data-governance note: prompts and outputs pass through a third party before reaching the model provider, so review its data-handling and routing policies before sending customer data. | n/a |
| AWS | Amazon Bedrock AgentCore — modular services you can use together or alone: Runtime (serverless, session-isolated hosting for agents built in any framework — LangGraph, CrewAI, Google ADK, OpenAI Agents SDK, Strands — over MCP and A2A), a managed agent-loop Harness, Memory, Gateway (turns APIs and Lambda functions into MCP tools), Identity, Code Interpreter, Browser, Observability (OpenTelemetry), Evaluations, Policy and a Registry (docs, opened 2026-11-08; service list changes quickly). | Production platform; consumption-priced |
| Microsoft | Foundry hosted agents — MAF agents deploy to Microsoft Foundry infrastructure with ~2 lines of code (agent-framework repo). | Production |
The pattern: hosted platforms are strongest where the provider also owns the model — Anthropic's Managed Agents runs Claude in Anthropic's sandbox; Google's Agent Engine runs ADK agents on Google Cloud; OpenAI's hosted story deliberately kept shrinking toward "SDK + ChatKit" rather than a managed runtime. That tells you something: the providers believe the loop is your code to own, and they're happy to host the runtime.
6.2 Workflow builders and low-code platforms#
For non-engineers — or engineers who want a visual canvas for deterministic flows — the established names:
- n8n — fair-code workflow automation platform, self-hostable or cloud; huge integration library; LLM nodes call models as workflow steps (not autonomous agents in the 08A.2 sense).
- Dify — open-source LLM application platform: visual prompt/workflow builder, RAG pipelines, agent nodes, plugins marketplace; self-host or Dify Cloud.
- Flowise — drag-and-drop builder for LangChain-style chains and agents; open source, self-host or cloud.
These trade flexibility for speed: you get a UI, versioning and hosting, but the agent's "reasoning" is whatever the canvas lets you express — usually less than code. Right answer for business teams prototyping automations and for deterministic workflows with an LLM step; wrong answer when you need the control, testing and evals of Parts 4–5.
6.3 Vertical agent platforms#
Thinner but real: CrewAI AMP Suite (tracing/governance for crews, commercial), LlamaIndex LlamaParse/LlamaAgents (document-agent platform — note the company's pivot away from the OSS framework), Haystack Enterprise Platform (managed Haystack pipelines), LangSmith Deployment (host LangGraph agents), and the coding-agent CLIs covered in 08A.15.
6.4 When a platform is the right answer#
Choose hosted/low-code when: the workflow is deterministic and visual review matters more than flexibility; the team isn't Python-fluent; compliance wants a managed runtime with an audit trail; or you need the provider's sandbox (Managed Agents' cloud environment, Agent Engine's scaling) more than you need loop control. Choose code — own loop or framework — when: the agent's behaviour is the product, you need evals and regression tests, tool logic is non-trivial, or you'll outgrow the canvas within a quarter. Most production systems end up hybrid: code for the agent core, a platform for deployment and observability.
Consumer agentic products are the other end of the spectrum — the largest deployed population of agent users, and mostly closed harnesses you can't instrument or eval. Two classes (as of November 2026 — names and availability change fast, verify current state): assistant agents inside chat products, such as ChatGPT's agent mode — which absorbed OpenAI's earlier Operator research preview — and ChatGPT Workspace Agents for business teams; and agentic browsers that drive a real browser with the user's logged-in session, such as Perplexity Comet, Claude in Chrome, Gemini's auto-browse in Chrome and Microsoft's Copilot browsing in Edge (OpenAI tried a standalone agentic browser, Atlas, before folding the capability back into ChatGPT in 2026). These products validate demand and set user expectations for what "an agent" should do — but they are someone else's loop, policy layer and trace. Your production agents need all three under your control, which is what this module builds.
Part 7: Choosing#
7.1 The decision table#
| If you need... | Pick | Because |
|---|---|---|
| Fastest path, one provider, want approvals+tracing+sessions free | That provider's framework (Agents SDK / Claude Agent SDK / ADK) | Reference implementation, least glue |
| Multi-provider, typed codebase, strong testing story | Pydantic AI | Model strings, types end-to-end, TestModel |
| Explicit state, durability, complex flows, total control | LangGraph | The graph is the program; checkpointing/interrupts first-class |
| Enterprise Microsoft shop, .NET parity, Foundry hosting | Microsoft Agent Framework | Consolidated successor; A2A/MCP; support story |
| Role-based multi-agent crews | CrewAI or MAF workflows | Primitives match the mental model |
| RAG-centric agents on Haystack pipelines | Haystack | Pipeline-first design, lifecycle hooks |
| Coding agents | Claude Agent SDK / sandbox agents / coding CLIs (08A.15) | Harness tuned for repo work |
| Optimizing prompts at scale, not running agents | DSPy | Different problem: LM program compiler |
| Non-engineers / visual flows | n8n, Dify, Flowise | Canvas > code for them |
| Zero ops, managed runtime | Anthropic Managed Agents, Agent Engine, Foundry hosted | Someone else runs the loop |
| You already own a working loop | Nothing new | Add tracing; migrate only if a need appears |
flowchart TD
start{"What does the agent need?"} --> q1{"One provider<br/>and its ecosystem?"}
q1 -->|"yes"| prov["Provider's own framework<br/>(Agents SDK / Claude Agent SDK / ADK)"]
q1 -->|"no, multi-provider"| q2{"Typed codebase<br/>and easy testing?"}
q2 -->|"yes"| pai["Pydantic AI"]
q2 -->|"no"| q3{"Complex stateful flows,<br/>durability, explicit control?"}
q3 -->|"yes"| lg["LangGraph"]
q3 -->|"no"| own["Your own loop + thin client<br/>(03.11 + 08A.2)"]
start --> q4{"Non-engineers or<br/>visual flows?"}
q4 -->|"yes"| low["n8n / Dify / Flowise"]
q4 -->|"no"| q5{"Want zero ops,<br/>managed runtime?"}
q5 -->|"yes"| host["Managed Agents / Agent Engine /<br/>Foundry hosted agents"]7.2 Failure gallery#
| Failure | What it looks like | Prevention |
|---|---|---|
| Framework magic hiding bugs | Tool calls reordered, messages compacted, retries doubled — outputs change and you can't see why | Disable auto-features you didn't ask for; log the exact request/response per turn (03.10); keep tools framework-agnostic |
| Version churn breaking prompts | Framework upgrade changes default model, system-prompt template or tool ordering; agent quality silently degrades | Pin versions; read changelogs; re-run agent evals on every upgrade (5.8) |
| Double retries | Framework retries a failed call and the SDK retries it again → 4 attempts, double cost, duplicate side effects | Set SDK max_retries=0 when the framework owns retries (the 03.11 lesson shows the trap) |
| State lost between runs | Deploy restarts; the "session" was in-memory; the agent forgets the conversation or the pending approval | Externalise state (checkpointer/session store you control); know which layer owns truth (5.4) |
| Lock-in discovered too late | Migration means rewriting orchestration, not imports | Keep tools+prompts portable (5.1); know the exit before you need it |
| Dependency surprise | uv add crewai pulls 100+ packages; conflict with your existing SDK versions; new transitive dep with a .pth file |
Audit the tree (uv pip compile); exact pins; hash-checked installs (5.9) |
| Over-engineering | LangGraph graph for a two-tool FAQ bot; crew of five agents for one classification | Start at the simplest rung that works (08A.9); the framework should fit the problem, not the reverse |
| Hidden cost | Framework's tracing/observability is a paid SaaS; "free" tier caps traces | Price the observability layer before commit; OTel export keeps you portable |
Part 8: Survey-only frameworks in detail#
Reference
Part 3 keeps one comparison table for the frameworks this lesson only surveys: 3.14. This Part holds the full entries for the four that had their own sections (CrewAI, smolagents, Haystack and DSPy). The text is the same as it was in Part 3; it moved here so that the survey reads faster. Read an entry when you are actually considering that framework. Versions in this Part are as of November 2026, as in the rest of the survey.
8.1 CrewAI#
- Package:
crewai1.15.35, MIT (PyPI, repo, docs). - What it is: the popular "crew of role-based agents" framework. Two primitives: Crews — agents with
role,goal,backstorythat collaborate autonomously (manager-driven or sequential/hierarchicalProcess) — and Flows — event-driven, deterministic orchestration for when you want precise control with crews as steps. Commercial tier: CrewAI AMP Suite (tracing, observability, governance) and CrewAI cloud. - API shape (verified from README/docs):
Agent(role=..., goal=..., backstory=..., tools=[...]),Task(description=..., expected_output=..., agent=...),Crew(agents=[...], tasks=[...]),crew.kickoff(inputs={...}); Flows via@start()/@listen()/@router()decorators on aFlowclass. - Watch out: the role-play metaphor is seductive but the underlying mechanism is still an LLM loop — crews don't think better, they just talk to each other expensively (token multiplication is real; see 08D.3). Best for demos and genuinely parallel role-separated work; overkill for a single-agent support bot.
8.2 smolagents#
- Package:
smolagents1.26.0 (PyPI, repo, docs). - What it is: Hugging Face's small, focused agent library built around one distinctive idea: the
CodeAgentwrites its actions as executable Python code rather than JSON tool calls, which composes many tool uses into one generation. Execution is sandboxed (Blaxel, E2B, Modal, Docker, or local). - Key API:
CodeAgent(tools=[...], model=..., stream_outputs=True); models viaInferenceClientModel(HF Inference Providers),LiteLLMModel,OpenAIModel,TransformersModel; tools viaWebSearchTool,Tool.from_hub,Tool.from_langchain,ToolCollection.from_mcp,Tool.from_space. - Watch out: "model-agnostic" yes, but the code-execution paradigm means you must take the sandbox seriously — arbitrary generated code runs somewhere. Great fit for data-analysis and tool-composition tasks; a different beast from the JSON-tool-call agents in this module.
8.3 Haystack#
- Package:
haystack-ai3.4.1, Apache-2.0, Python ≥3.11 (PyPI, repo). - What it is: deepset's framework for production RAG and agent pipelines. Its
Pipelineruns components (retrievers, rankers, routers, generators) in explicit order — synchronous or async, streaming; itsAgentcomponent adds tool-calling loops with lifecycle hooks (before_llm,before_tool,on_exit), built-instep_count/token_usage/tool-call tracking,SkillToolsetfor progressive skill discovery, and ready-made agents in Agent Pack (deep research, advanced RAG). - Watch out: Haystack thinks in pipelines first — if your task is "agent with many tools and little retrieval", its pipeline mental model can feel inverted. Strong choice when retrieval is central (it pairs naturally with Module 07's work); weaker as a general agent framework.
8.4 DSPy#
- Package:
dspy3.5.0, MIT (PyPI, repo, docs). - What it actually is: not an agent framework — and it's worth being precise about that, because people file it in the wrong mental drawer. DSPy ("Declarative Self-improving Python", Stanford NLP) is a programming model for LM pipelines: you write compositional Python (signatures,
dspy.Modules, predictors likeChainOfThought/ReAct) and optimizers compile it — generating and selecting prompts, few-shot demonstrations, and (in later versions) fine-tuning the LM weights themselves. - Where it fits: when your problem is "the prompts are the product" — classification, extraction, multi-hop QA pipelines whose quality you want to optimize against a metric rather than hand-tune. DSPy can sit inside an agent's steps, or replace hand-written agent scaffolding for structured LM programs. It doesn't give you sessions, tool loops or tracing out of the box.
Common misconceptions#
| Misconception | Reality |
|---|---|
| "A framework makes the agent smarter." | It packages the loop and infrastructure; the model's reasoning is unchanged. A bad prompt in LangGraph is still a bad prompt. |
| "Frameworks are provider-agnostic." | Some are (Pydantic AI, LangGraph via LangChain, Agents SDK via adapters), some aren't (Claude Agent SDK is Claude-only; ADK is Gemini-first). "Agnostic" always means "second-class for someone" — check which provider gets the deep features. |
| "The framework's typed output means the data is correct." | It means the shape validates (usually via the provider mechanisms of 03.4). Values can still be wrong; your validators still run. |
| "Sessions = durable execution." | A session stores conversation history; durable execution survives mid-run crashes and resumes state. Different mechanisms, different guarantees (5.4). |
| "Guardrails in the framework make the agent safe." | They catch format/policy violations, not prompt injection or dangerous-but-valid tool calls. Safety is Module 12's job. |
| "AutoGen and Semantic Kernel are the Microsoft choices." | Both are legacy paths — AutoGen is archived, Semantic Kernel redirects to Microsoft Agent Framework. |
| "More framework = more capable agent." | Crew/multi-agent frameworks multiply cost and error compounding (08D.3); the simplest thing that works is usually a single agent or a workflow. |
| "You can adopt a framework later." | You can, but the longer your tools/prompts stay framework-shaped, the more expensive the switch. Keep them plain from day one. |
| "0.x means unusable." | It means the API can move — pin it, read changelogs, and prefer the stable core over bleeding-edge extras. |
| "The hosted platform replaces your backend." | It replaces the runtime, not your tools, prompts, evals or business logic — which stay yours either way. |
Key takeaways#
- Frameworks package decisions you'd make anyway: the loop, tool registration, state, guardrails, HITL, tracing, retries, durability. Adopt one when it removes more complexity than it adds — not because it's fashionable.
- The real costs are abstraction leaks, lock-in, churn, debugging distance, hidden behaviour (double retries, auto-compaction) and dependency risk. Evaluate with the 10-question checklist in 1.3.
- "Agent framework" is five different products: agent-loop libraries, graph orchestrators, crew frameworks, coding-agent harnesses, and hosted platforms. Match the kind to the problem.
- Verified landscape (Nov 2026):
openai-agents0.24.0,claude-agent-sdk0.2.178 (alpha, drives Claude Code),google-adk2.13.0,langgraph1.2.22 +langchain1.5.0,pydantic-ai2.66.0,agent-framework1.24.0 (AutoGen archived, Semantic Kernel migrating),crewai1.15.35,llama-index0.14.25,smolagents1.26.0,semantic-kernel1.47.0,haystack-ai3.4.1,dspy3.5.0, plus TS options (ai7.x, Mastra). - The same agent four ways showed the real choice: Agents SDK and Pydantic AI hide the loop behind
run; LangGraph makes the loop the program; your own loop is the same idea unpackaged. Pick the visibility your team can debug. - Portability is the highest-leverage habit: tools as plain functions + JSON schemas, prompts as versioned text, thin adapters per framework. It makes every future decision reversible.
- Test with fakes, always:
ScriptedModel,TestModel, fake transports, scripted nodes — no unit test should call a real model. - Tracing, durability, approvals and guardrails are cross-cutting: pick an OTel-capable backend, externalise state for anything long-running, and treat framework guardrails as format-checks, not safety.
- Hosted platforms are strongest where the provider owns the model — and OpenAI's shrinking hosted story (Assistants API dead, Agent Builder and Evals sunsetting 30 Nov 2026) is a signal that the industry expects you to own the loop.
Terms introduced in this lesson#
| Term | One-line definition |
|---|---|
| Agent framework | A library that packages the agent loop and its surrounding infrastructure (state, tools, guardrails, tracing, HITL) |
| Agent-loop framework | A framework that runs the model→tools→repeat cycle for you (Agents SDK, Pydantic AI, Claude Agent SDK, ADK, smolagents) |
| Graph / orchestration framework | A framework where you define nodes and edges explicitly and it executes the graph (LangGraph, ADK workflows, MAF) |
| Crew / role framework | Agents defined by role/goal that delegate to each other (CrewAI, AutoGen→MAF) |
| Coding-agent harness | A batteries-included agent for software work with file/shell/repo tools (Claude Agent SDK, sandbox agents, coding CLIs) |
| Hosted agent platform | The agent runtime runs on a provider's/third party's infrastructure; you configure agents via API/console |
| Abstraction leak | When a framework's simplified model can't express a provider's real behaviour, and the gap bites |
| Lock-in | The cost of leaving a framework because agents/tools/state are expressed in its types |
| Churn | Rapid releases and breaking changes that make framework upgrades risky |
| Framework-neutral checklist | The 10 questions in 1.3 for evaluating any agent framework |
function_tool / @tool |
Decorators that turn a Python function into a model-callable tool with generated schema (Agents SDK / LangChain / Claude Agent SDK variants) |
needs_approval |
OpenAI Agents SDK flag that pauses a run for human approval before a tool executes |
RunState / interruptions |
The serializable paused-run state and pending-approval list in the Agents SDK HITL flow |
ClaudeAgentOptions |
The configuration object for the Claude Agent SDK (permissions, tools, hooks, subagents, skills) |
| In-process MCP server | Claude Agent SDK's create_sdk_mcp_server: Python functions exposed as MCP tools without a subprocess |
permission_mode |
Claude Agent SDK/Claude Code setting controlling when tools run without asking (default, acceptEdits, plan, dontAsk, bypassPermissions, auto) |
Agent + Runner (ADK) |
Google ADK's pair: the agent definition and the executor that drives run_async over sessions/events |
Session / session_service (ADK) |
ADK's conversation record and its storage backends (in-memory, database, Vertex, MongoDB) |
StateGraph / ToolNode / tools_condition |
LangGraph's graph builder, prebuilt tool-executing node, and router that decides tools-vs-end |
| Checkpointer | LangGraph component that persists graph state so runs resume across processes |
interrupt() / Command(resume=...) |
LangGraph's pause-and-continue primitives for human-in-the-loop |
output_type / deps_type / RunContext |
Pydantic AI's typed output, dependency injection, and per-run context object |
TestModel / FunctionModel / agent.override |
Pydantic AI's fakes for key-free unit testing |
| Capability (Pydantic AI) | A reusable bundle of tools/hooks/instructions/model-settings snapped onto an agent |
| Deferred tool request | Pydantic AI's mechanism for pausing a run to ask a human to approve a tool call |
ToolSpec |
This lesson's framework-neutral tool contract: name + description + JSON Schema + callable |
| Managed agent | A hosted agent runtime (Anthropic Managed Agents, Agent Engine, Foundry) where sessions/state live server-side |
| Raw tool loop first | The selection rule from 2.5: keep your own loop unless a framework does a specific job you can name |
| LlamaIndex Workflows | An event-driven, async, step-based framework where steps receive and emit events; run state lives in a context store |
| Black-box evaluation | Testing a system (such as a low-code flow) only through its inputs and outputs; see 08F.16 |
All terms are also collected in the glossary.
Exercises#
- Portability drill: take
support_tools.pyand write the thin adapters listed in the usage comment of 5.1 (one per framework's expected tool shape; the own-loop one is the easiest) as real functions. Don't install the frameworks — just produce the dicts/dataclasses each would consume, and unit-test the adapter forissue_refund(it must carry the "needs approval" hint through). - Four-way comparison: implement the read-only subset of the support agent (lookup_order + search_docs + run_report, no refund) in your own loop using
ScriptedModelfrom 08A.2. Then count the lines of orchestration code in each of the four implementations and argue which you'd pick for a two-tool FAQ bot — and why the answer differs from the five-tool refund agent. - Approval audit: for each framework in 5.5, write down (a) where the approval state is stored, (b) whether it survives a process restart, and (c) who can read/edit it. Which would you trust for a refund in production, and what would you add?
- Dependency audit: run
uv pip compile(oruv add --dry-run) foropenai-agents,pydantic-ai,langgraphandcrewaiin separate throwaway projects. Count resolved packages, note conflicts with theopenaiandanthropicSDKs you already use, and write a one-paragraph recommendation for a team that pins everything. - Churn drill: pick one framework and read its last 10 GitHub releases/changelog entries. List every breaking change or behaviour change that would have altered an agent's outputs without changing your code.
- Hosted vs code: write a one-page decision memo for "should our support agent run on Anthropic Managed Agents or our own LangGraph deployment?" Cover data residency, the ZDR/HIPAA exclusion, tool ecosystem (your in-house order API), cost model, and the exit path.
- Golden trajectory: using
TestModel(Pydantic AI) orScriptedModel(your loop), write a test that asserts the support agent callslookup_orderbeforeissue_refundfor the input "refund my order A-1042". Explain why this ordering property matters more than the final text. - Approval, edited: extend the Pydantic AI sample in 4.4 so a reviewer can change the refund amount: replace
Truein the decisions withToolApproved(override_args={"amount_cents": 2500})and explain what the model then sees. Which of the four implementations makes "approve with edits" easiest, and which makes it hardest?
Hints
- Each adapter returns the structure its framework consumes: an Agents SDK
function_toolwrapper, a Pydantic AItool_plain-decorated function, a LangChain@tool, an(name, description, schema)triple for Claude Agent SDK, a plain function for ADK. Putneeds_approval: boolon your neutralToolSpecand map it toneeds_approval=True,requires_approval=True, aninterrupt()wrapper, or acan_use_toolrule. - Count only lines that decide control flow (loop, routing, state, approval), not tool bodies. A two-tool FAQ bot has no destructive tool, so the approval machinery that dominates the refund agent disappears.
- Look for: in-memory flag (lost on restart), serialised run state (survives), external checkpointer (survives, auditable). Add an audit log row written before the tool runs.
- Expect hundreds of resolved packages for the larger frameworks; look for two different
pydanticorhttpxconstraints. Compare againstuv pip compileof justopenaiandanthropic. - Behaviour changes to look for: new default model, changed prompt template, different retry or compaction defaults, renamed events.
- Cover where session data lives, what ZDR/HIPAA eligibility the page states today, how your order API would be reached (remote MCP), per-session pricing against your own compute, and what you would have to rewrite to leave.
- The ordering matters because a refund issued without a lookup acts on an unverified order id; the final text can look fine either way.
- With
override_argsthe tool runs with the reviewer's arguments; tell the model what changed through the tool result, or it will report the original amount. In your own loop it is a dictionary update before dispatch; LangGraph can return edited values frominterrupt().
Check yourself#
- Name the five kinds of "agent framework" and one example of each.Agent-loop frameworks (OpenAI Agents SDK, Pydantic AI), graph/orchestration frameworks (LangGraph, ADK workflows, MAF), crew/role frameworks (CrewAI, AutoGen→MAF), coding-agent harnesses (Claude Agent SDK, sandbox agents), hosted agent platforms (Managed Agents, Agent Engine, Foundry).
- What does an agent framework actually replace from your own code? List at least five things.The loop, tool registration/schema handling, conversation state, handoffs/sub-agents, guardrails, HITL machinery, tracing, retries, provider abstraction, durable execution — any subset depending on the framework.
- What are the main costs of adopting a framework?Abstraction leaks, lock-in, churn (breaking changes), debugging difficulty/hidden behaviour, and dependency/supply-chain risk.
- Why is AutoGen a bad choice for a new project in November 2026?It's archived — no bug fixes, security fixes, features or support; Microsoft directs new work to
agent-framework(MAF) with a migration guide. - Which framework is "not an agent framework" and what does it actually do?DSPy — it's an LM program compiler/optimizer (signatures, modules, optimizers), not an agent loop.
- In the OpenAI Agents SDK sample, what does
needs_approval=Truedo, and what does the run return while paused?It marks the tool as requiring human approval; the run pauses andresult.interruptionslists the pending approvals instead of executing the tool. - What's the difference between Claude Agent SDK and the Anthropic Messages API?Claude Agent SDK drives the Claude Code CLI as a harness (built-in file/shell tools, permissions, subagents, skills); the Messages API is the raw model API you wrap yourself.
- In the LangGraph sample, what do
interrupt()andCommand(resume=...)do, and why does the checkpointer matter?interrupt()pauses the graph and checkpoints state;Command(resume=...)continues the samethread_idwith the human's decision. The checkpointer is what makes the paused state resumable (and durable if externalised). - Why does Pydantic AI's
TestModelmake unit testing easier than a raw SDK loop?It calls every tool and returns schema-valid dummy output with no API key, no latency and no variability — plusagent.overrideandALLOW_MODEL_REQUESTS=Falsefor airtight tests. - What's the single most valuable habit for keeping framework options open, and what does it look like in code?Keep tools as plain functions + JSON schemas and prompts as versioned text, with thin per-framework adapters — so migration is an adapter rewrite, not a rewrite.
- "Sessions" and "durable execution" — what's the difference?Sessions store conversation history for continuity; durable execution survives mid-run crashes and resumes full state. Different mechanisms and guarantees.
- Why did OpenAI's hosted-agent story shrink in 2026, and what does that signal?Assistants API shut down Aug 2026 and Agent Builder plus Evals sunset Nov 30 2026 — OpenAI is narrowing hosted agents to Agents SDK + ChatKit, signalling the industry expects you to own the loop.
- Your framework retries a failed model call, and the provider SDK also retries it. What's the problem and the fix?Double retries multiply attempts and cost, and can duplicate side effects (e.g. a refund). Fix: one layer owns retries — set the inner SDK's
max_retries=0when the framework retries. - When is a low-code builder (n8n/Dify) the right choice over code?When the workflow is deterministic/visual, the team isn't Python-fluent, or you need a managed runtime with audit trails more than loop control.
- What is the "raw tool loop first" rule, and what are the first two questions it asks?Keep your own loop (08A.2) as the default and adopt a framework only for a job you can name. The first questions: does the raw loop plus tracing already do the job, and if not, which specific job do you need help with (durable pause and resume, typed multi-provider code, built-in sessions and handoffs, a file-and-shell harness, or event-driven steps)?
- Why does the OpenAI Agents SDK's default tracing matter for an organisation on Zero Data Retention, and what are the two ways to deal with it?Per the Agents SDK docs (checked 2 December 2026), tracing is on by default and exports to OpenAI's backend, and it is unavailable for organisations under Zero Data Retention. Disable it (
OPENAI_AGENTS_DISABLE_TRACING=1orset_tracing_disabled(True)) or replace the trace processors with one that exports to a backend you control. - Name the job each of these is picked for: LangGraph, Pydantic AI, Claude Agent SDK, OpenAI Agents SDK, LlamaIndex Workflows.LangGraph: durable, stateful, explicit flows. Pydantic AI: typed, multi-provider code with easy fake-model testing. Claude Agent SDK: agents that work with files and commands using Claude Code's harness. OpenAI Agents SDK: a small package with sessions, handoffs, guardrails and built-in tracing on OpenAI. LlamaIndex Workflows: event-driven steps, especially around a LlamaIndex stack.
Further resources#
- OpenAI Agents SDK — docs and repo; HITL guide, sessions, tracing
- Claude Agent SDK — Python reference, permissions, hooks; Managed Agents — overview
- Google ADK — adk.dev, repo + CHANGELOG
- LangGraph / LangChain — LangGraph docs, persistence, interrupts
- Pydantic AI — docs, testing guide, V1→V2 migration
- Microsoft Agent Framework — repo, AutoGen migration guide
- Others — Strands Agents, Amazon Bedrock AgentCore, AG2, CrewAI docs, smolagents docs, Haystack docs, DSPy, LlamaIndex
- Provider deprecations — OpenAI deprecations (Assistants API, Agent Builder, Evals)
- Anthropic's own guidance on workflows vs agents — Building effective agents (linked from 08A.9)
← Module 08E: Protocols and Extensibility | Module 08F overview | 08F.2 — OpenAI Agents SDK →