<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/">
<channel>
<title>Pydantic Blog</title>
<link>https://pydantic.dev/articles</link>
<description>Product and feature updates from the Pydantic team, plus engineering deep dives on AI, LLMs, observability, and agent frameworks.</description>
<language>en</language>
<lastBuildDate>Fri, 13 Nov 2026 09:00:00 GMT</lastBuildDate>
<atom:link href="https://pydantic.dev/feed.xml" rel="self" type="application/rss+xml"/>
<item>
<title>Using coding agent traces to improve your workflows</title>
<link>https://pydantic.dev/articles/coding-harness-tracing</link>
<guid isPermaLink="true">https://pydantic.dev/articles/coding-harness-tracing</guid>
<pubDate>Fri, 13 Nov 2026 09:00:00 GMT</pubDate>
<dc:creator>Duncan McKinnon</dc:creator>
<category>Pydantic Logfire</category>
<category>MCP</category>
<description>How coding harness traces in Logfire show where time and tokens go, make past sessions reusable across harnesses, and turn repeated failures into tested skills.</description>
<content:encoded><![CDATA[<p>Ever since Claude Code was first released, we've experienced a continuous barrage of new models, capabilities, and harnesses to make LLMs the primary means of developing software. These advancements have greatly increased the scope of the applications of these tools, to the point where most teams are using them daily.</p>
<p>The massive improvements in harnesses have not removed one of the greatest challenges: the process remains opaque. When the agent fails or spins its wheels in endless exploration, it's not clear from the outside what is going on. To fully utilize your own harness, you need to know what it's doing and how to leverage that information.</p>
<p>In my day to day I work with teams that are interested in improving their coding harnesses but skeptical about the importance of tracing every interaction. I see harness improvement and tracing as intrinsically linked. From the outside it may look like simple telemetry data, but it carries rich signals that are necessary for a number of monitoring, evaluation, and improvement flows.</p>
<p>This article will walk through some of the most powerful use cases for coding harness tracing, and show how to close the loop by making traces available to the coding harness for optimizations across models, users, teams, and companies.</p>
<section id="why-coding-harnesses-need-observability-section"><h2 id="why-coding-harnesses-need-observability" role="presentation"><a href="#why-coding-harnesses-need-observability" class="heading-anchor"><button type="button" class="heading-anchor__btn">#</button></a><span role="heading" aria-level="2">Why coding harnesses need observability</span></h2>
<p>Coding harnesses work well in a wide range of scenarios. The gaps only become clear as you build intuition. The longer you work with these tools, the more often you end up asking questions like these:</p>
<ul>
<li>Where is my time and token budget actually going?</li>
<li>How do I pick up useful context from an old session?</li>
<li>Why is my agent getting lost during a task?</li>
<li>Which harness and model should I use for this task?</li>
<li>How do I close the loop so the agent can sort this out on its own?</li>
</ul>
<p>These questions will be our focus going forward. We will discuss how to approach each of these systematically in depth. Ultimately though, the answers require observability. The stuff harnesses <em>do</em> make available, the inputs/outputs of a session log, isn't all that useful for the purposes of analysis and improvement.</p>
<section id="the-harness-hides-the-process-section"><h3 id="the-harness-hides-the-process" role="presentation"><a href="#the-harness-hides-the-process" class="heading-anchor"><button type="button" class="heading-anchor__btn">#</button></a><span role="heading" aria-level="3">The harness hides the process</span></h3>
<p><img src="https://pydantic.dev/assets/blog/coding-harness-tracing/agent-harness-process.png" alt="The agent reads files, queries databases, runs tools, calls web APIs and edits code, while from outside the harness all you see is a terminal reading &#x22;working on it...&#x22;." decoding="async"></p>
<p><em>The agent reads files, queries databases, runs tools, calls web APIs and edits code, while from outside the harness all you see is a terminal reading "working on it...".</em></p>
<p>To get a real signal, you need an observability solution that works across providers and records the entire path from request to response, most of which is hidden inside the harness. Model invocations, tool calls, retries and dead ends happen out of view, and none of it is surfaced and persisted for long-term reflection. Before you can answer any of these questions, you need a record of everything the agent did.</p>
</section><section id="what-a-trace-gives-you-section"><h3 id="what-a-trace-gives-you" role="presentation"><a href="#what-a-trace-gives-you" class="heading-anchor"><button type="button" class="heading-anchor__btn">#</button></a><span role="heading" aria-level="3">What a trace gives you</span></h3>
<p>Logfire's <a href="https://pydantic.dev/events/closing-the-loop-coding-agent-traces">coding agent tracing</a> can capture the model invocations, tool call execution, and request/response pairings across a session for a variety of harnesses, depending on the capture policy you configure. Within each captured step it records metadata such as duration and usage when the harness and provider supply it, and cache reads and writes may also be available. For supported providers, Logfire estimates cost from the recorded tokens and pricing data, so you can see an estimated API cost for the supported, instrumented calls in a session.</p>
<p>That answers the first question, and the rest follow from the same data. The order of operations shows where an agent went off course. Each trace records which harness and model ran it, so you can compare runs. Sessions are stored and searchable with SQL, so old work stays within reach. And through the <a href="https://pydantic.dev/docs/ai/harness/logfire-mcp/">Logfire MCP server</a>, an agent can run SQL queries and leverage the context from past operations, which is ultimately how you close the loop.</p>
</section></section><section id="closing-the-loop-section"><h2 id="closing-the-loop" role="presentation"><a href="#closing-the-loop" class="heading-anchor"><button type="button" class="heading-anchor__btn">#</button></a><span role="heading" aria-level="2">Closing the loop</span></h2>
<p>Closing the loop means making the rich historical session context fully available within every coding harness you spin up. In the following sections we'll address each of the earlier questions using this pattern. We'll see how the Logfire MCP server can be used to run SQL operations on tracing data from within your harness to monitor, automate, and improve workflows.</p>
<p>These examples are not comprehensive, but they represent the use cases I've seen having the most impact for teams.</p>
</section><section id="metrics-for-the-work-you-care-about-section"><h2 id="metrics-for-the-work-you-care-about" role="presentation"><a href="#metrics-for-the-work-you-care-about" class="heading-anchor"><button type="button" class="heading-anchor__btn">#</button></a><span role="heading" aria-level="2">Metrics for the work you care about</span></h2>
<p>Coding harness traces carry more than just latency and token counts. They record rich information about what the team is working on, the patterns they're using, and where the inefficiencies are. Different organizations, teams, and users will care about these for different reasons. With the Logfire MCP server, anyone can easily develop metrics and dashboards for the things they want to track.</p>
<p>The same pattern holds regardless of the metric. From your preferred harness, just ask the agent to use Logfire MCP to create the dashboards and views you want to see. Because most components in Logfire are defined as SQL queries on traces, agents can help build and revise views.</p>
<p>The process is outlined below and was used in all the subsequent examples.</p>
<p><img src="https://pydantic.dev/assets/blog/coding-harness-tracing/metric-panel-workflow.png" alt="The process used for the examples that follow: a plain-language request to the coding agent goes through the Logfire MCP server, which runs SQL over the trace data, creates the panel (here, average cycles per completed turn by agent) and replies with a link to it." loading="lazy" decoding="async"></p>
<p><em>The process used for the examples that follow: a plain-language request to the coding agent goes through the Logfire MCP server, which runs SQL over the trace data, creates the panel (here, average cycles per completed turn by agent) and replies with a link to it.</em></p>
<p>In this example the agent took a request for "average cycles taken to complete a turn by agent", queried the data, found the relevant field, made the new panel, generated the query to represent average operations per turn grouped by harness, and responded once completed with a link to the panel.</p>
<section id="tracking-coding-productivity-section"><h3 id="tracking-coding-productivity" role="presentation"><a href="#tracking-coding-productivity" class="heading-anchor"><button type="button" class="heading-anchor__btn">#</button></a><span role="heading" aria-level="3">Tracking coding productivity</span></h3>
<p>Because the queries can access any facet of the trace, and the traces represent coding work, you can develop panels to track specific operations related to productivity, like commits and pull requests. The chart below shows commits over time with the number of lines added and deleted. This can be useful to immediately see if the agent has made large deletions or if the size of individual commit operations is unexpectedly small or large.</p>
<p><img src="https://pydantic.dev/assets/blog/coding-harness-tracing/lines-changed-per-commit.png" alt="Lines added and deleted per commit, taken from agent traces." loading="lazy" decoding="async"></p>
<p><em>Lines added and deleted per commit, taken from agent traces.</em></p>
<p>The following chart shows the time taken from first commit to PR creation, and from first edit to commit. Views like these are possible because the coding agents run git operations with bash tools that have a structure that can be reliably broken down with a SQL query. The traces contain the timing and associations between coding operations and eventual CI/CD, so we can track the amount of time that goes into commits and PRs directly from traces.</p>
<p><img src="https://pydantic.dev/assets/blog/coding-harness-tracing/pr-and-commit-timing.png" alt="Time from first commit to PR creation (top) and from first recorded edit to commit (bottom) across October, one point per PR or commit." loading="lazy" decoding="async"></p>
<p><em>Time from first commit to PR creation (top) and from first recorded edit to commit (bottom) across October, one point per PR or commit.</em></p>
</section><section id="tracking-cost-and-time-section"><h3 id="tracking-cost-and-time" role="presentation"><a href="#tracking-cost-and-time" class="heading-anchor"><button type="button" class="heading-anchor__btn">#</button></a><span role="heading" aria-level="3">Tracking cost and time</span></h3>
<p>If you need to understand where your tokens and time are going, charts that cover spending over time and durations of operations are a good starting point. The visualization below shows the token cost incurred over 2 months for 4 different agent harnesses. From this kind of visual, you can begin to assess inefficiencies and opportunities for improvement flows.</p>
<p><img src="https://pydantic.dev/assets/blog/coding-harness-tracing/cost-over-time.png" alt="Daily token cost in dollars from September through October for four harnesses: Claude Code, Codex, Cursor and Copilot." loading="lazy" decoding="async"></p>
<p><em>Daily token cost in dollars from September through October for four harnesses: Claude Code, Codex, Cursor and Copilot.</em></p>
<p>For general comparisons between harnesses and models, you can break down aspects of performance to get a sense of the efficiency of different configurations. The charts below show comparisons between harnesses and models on the average number of tool calls per turn and the average number of tokens per call. Monitoring these characteristics can provide early signals that one setup is more efficient than another and prompt focused experimentation flows that we'll discuss later.</p>
<p><img src="https://pydantic.dev/assets/blog/coding-harness-tracing/harness-model-efficiency.png" alt="Average tool calls per turn (top) and average tokens per call (bottom), grouped by harness (left) and by model (right)." loading="lazy" decoding="async"></p>
<p><em>Average tool calls per turn (top) and average tokens per call (bottom), grouped by harness (left) and by model (right).</em></p>
</section><section id="monitoring-a-software-factory-section"><h3 id="monitoring-a-software-factory" role="presentation"><a href="#monitoring-a-software-factory" class="heading-anchor"><button type="button" class="heading-anchor__btn">#</button></a><span role="heading" aria-level="3">Monitoring a software factory</span></h3>
<p>Software factories use a collection of collaborating agents to take code through the development pipeline. Recently I've been working to improve the configuration of my software factory and added harness telemetry to capture the sessions. I was particularly interested in how long the tasks were taking to get through the pipeline, and how many tokens were being used. The chart below exposed the problem.</p>
<p>While the implementation and test phases were generally cheaper than the review stages, the pipeline was getting stuck in expensive cycles of reviews and fixes, leading to high token use and cost at the review and review-fix stages. We'll revisit how to address this problem later when looking at evaluation and experimentation on different reviewer configurations.</p>
<p><img src="https://pydantic.dev/assets/blog/coding-harness-tracing/software-factory-cost-by-phase.png" alt="Cost by phase of the software factory pipeline, in US dollars. The review-fix ($43.30) and review ($36.80) phases together account for about 60% of the roughly $132 total." loading="lazy" decoding="async"></p>
<p><em>Cost by phase of the software factory pipeline, in US dollars. The review-fix ($43.30) and review ($36.80) phases together account for about 60% of the roughly $132 total.</em></p>
</section></section><section id="making-use-of-past-work-section"><h2 id="making-use-of-past-work" role="presentation"><a href="#making-use-of-past-work" class="heading-anchor"><button type="button" class="heading-anchor__btn">#</button></a><span role="heading" aria-level="2">Making use of past work</span></h2>
<p>Closing a session usually means abandoning the context. You generally have 3 options if you ever need to reference prior work again:</p>
<ol>
<li>Open the same session with the full context eating up tokens</li>
<li>Start from scratch</li>
<li>Set up some file system pattern that the agent must manage</li>
</ol>
<p>With coding harness tracing and Logfire MCP, you can retrieve prior workstreams in a new session, do it across harnesses, and extract only the relevant context without bloating your session.</p>
<p>That pattern opens up a lot of possibilities beyond just picking up prior work. The graphic here shows three of the patterns that coding harness tracing facilitates.</p>
<p><img src="https://pydantic.dev/assets/blog/coding-harness-tracing/session-context-patterns.png" alt="Three patterns that coding harness tracing makes possible: splitting shared context across multiple harnesses, giving debugging and review sessions the full history, and branching any recorded turn into a new session for experiments." loading="lazy" decoding="async"></p>
<p><em>Three patterns that coding harness tracing makes possible: shared context across harnesses, debugging and review with full history, and branching turns for experiments.</em></p>
<section id="splitting-shared-context-across-multiple-harnesses-section"><h3 id="splitting-shared-context-across-multiple-harnesses" role="presentation"><a href="#splitting-shared-context-across-multiple-harnesses" class="heading-anchor"><button type="button" class="heading-anchor__btn">#</button></a><span role="heading" aria-level="3">Splitting shared context across multiple harnesses</span></h3>
<p>The first pattern takes prior session context at a specific point, and branches it out into multiple harnesses to complete work collaboratively, essentially starting from shared knowledge, and then relying on their own tracing as a means to communicate. This is useful when breaking up work that has been planned out in one session to be implemented across several different harnesses. It's more reliable than creating a planning document, because every decision is already encoded in the session tracing.</p>
<p>This works equally well in experimentation flows where the full context must be held constant while evaluating variations across harnesses or models. This is demonstrated later when showing how to compare different harnesses on a set of code review tasks.</p>
</section><section id="debugging-and-review-sessions-section"><h3 id="debugging-and-review-sessions" role="presentation"><a href="#debugging-and-review-sessions" class="heading-anchor"><button type="button" class="heading-anchor__btn">#</button></a><span role="heading" aria-level="3">Debugging and review sessions</span></h3>
<p>We can also go a step further in debugging and reviewing. When performing code reviews, agents can assess the full session to determine the alignment of results. This is a better representation of the user's intent than simply checking if the code works and matches the description. I find that allowing the reviewer to use Logfire MCP results in better, more actionable feedback from a reviewer, and fewer subsequent revisions after the fact.</p>
<p>Having access to prior session context allows your agent to assess its own past mistakes when debugging the resulting issues today. In the common scenario where the thing your agent built fails, you have both the record of the failure and the full record of how it was implemented, as well as the original intention. This additional context can greatly speed up improvements and lead to long-term memories that will avoid the same mistakes the next time around.</p>
</section><section id="branching-turns-for-experimentation-section"><h3 id="branching-turns-for-experimentation" role="presentation"><a href="#branching-turns-for-experimentation" class="heading-anchor"><button type="button" class="heading-anchor__btn">#</button></a><span role="heading" aria-level="3">Branching turns for experimentation</span></h3>
<p>Most harnesses today give you the option to branch to a new session for a given turn. With coding harness tracing, you can branch to a new session from any harness and any recorded turn. This is perfect for experimental flows where you need an apples-to-apples comparison of different harnesses on the exact same task with the same context.</p>
<p>This is an especially useful pattern when building your own harness or software factory. You can gather scenarios and then compare established agents and their approach to the harness you are building, and evaluate them on the criteria that are important to you.</p>
</section></section><section id="turning-repeated-struggles-into-new-skills-section"><h2 id="turning-repeated-struggles-into-new-skills" role="presentation"><a href="#turning-repeated-struggles-into-new-skills" class="heading-anchor"><button type="button" class="heading-anchor__btn">#</button></a><span role="heading" aria-level="2">Turning repeated struggles into new skills</span></h2>
<p>Repeated tasks can produce inconsistent results when agents lack the context to stay on course. This often manifests as long tangential exploration, unnecessary check-ins, and incomplete tasks. With coding harness tracing, records of poor performance become critical signals for skills that map out the process end to end.</p>
<p>Where people most often get lost is in translating relevant signals to useful skills. With a coding harness and the Logfire MCP server, you can break the process down into 4 repeatable stages.</p>
<p>First, you gather evidence from the traces for the agent to use in creating a new skill. To ensure the skill aligns with your expectations and remove ambiguity, you work with the agent to map out a repeatable process using evidence from historical successes and failures. With the evidence and the process established, you can have the agent draft a new skill for the task. The final step is validating the skill to make sure it actually fixes the problem without causing new issues. To do this, you can take the session context collected in the first step and create an experiment that compares the same harness with and without the skill loaded.</p>
<p>The full process is shown below:</p>
<p><img src="https://pydantic.dev/assets/blog/coding-harness-tracing/skill-creation-process.png" alt="The four stages of building a skill from traces: collect evidence, identify the happy path, create the skill, and verify the improvement by comparing runs with and without it." loading="lazy" decoding="async"></p>
<p><em>The four stages of building a skill from traces: collect evidence, identify the happy path, create the skill, and verify the improvement by comparing runs with and without it.</em></p>
<p>To demonstrate this process and show that it really works, I'm going to walk through a scenario that came up recently.</p>
<section id="collecting-the-evidence-section"><h3 id="collecting-the-evidence" role="presentation"><a href="#collecting-the-evidence" class="heading-anchor"><button type="button" class="heading-anchor__btn">#</button></a><span role="heading" aria-level="3">Collecting the evidence</span></h3>
<p>If you encounter the same issue more than once in a process, that's usually a sign that the agent lacks the context or direction it needs. I often use the Logfire MCP server to create dashboard panels using queries over traces. In the creation of new dashboards, there were generally 1-2 invalid queries and a few panels that required revision and rework to get right.</p>
<p>To get a sense of the prevalence of this issue, I used the Logfire MCP to search the coding agent traces for invalid queries and rework. That resulted in the artifact shown below:</p>
<p><img src="https://pydantic.dev/assets/blog/coding-harness-tracing/dashboard-query-examples.png" alt="The evidence report the agent produced from the traces. Each case records a correction, such as a query that double-counted cached input tokens." loading="lazy" decoding="async"></p>
<p><em>The evidence report the agent produced from the traces. Each case records a correction, such as a query that double-counted cached input tokens.</em></p>
<p>The agent also catalogued the errors and listed them out individually. This collection of evidence was the perfect starting point for developing a new logfire-dashboard-query skill.</p>
</section><section id="identifying-the-happy-path-and-creating-a-skill-section"><h3 id="identifying-the-happy-path-and-creating-a-skill" role="presentation"><a href="#identifying-the-happy-path-and-creating-a-skill" class="heading-anchor"><button type="button" class="heading-anchor__btn">#</button></a><span role="heading" aria-level="3">Identifying the happy path and creating a skill</span></h3>
<p>Creating skills without evidence or based solely on an expectation of failure usually results in unnecessary bloat. With evidence of the issue and resolutions, you can iterate with the agent on the expectations for the skill. In this case, I wanted the agent to validate queries, avoid common pitfalls, and review the dashboards it created for alignment.</p>
<p>The interactions also contained evidence of my personal preferences and best practices, so I wanted those encoded generally across every panel that would be created. There is some nuance in this step, but it's where you can also begin to shape the criteria you'll use to evaluate the skill.</p>
<p>For this skill validation the criteria were based on the validity of the query, the number of steps required to create the panels, and the handling of different types of variables.</p>
</section><section id="verifying-the-improvement-section"><h3 id="verifying-the-improvement" role="presentation"><a href="#verifying-the-improvement" class="heading-anchor"><button type="button" class="heading-anchor__btn">#</button></a><span role="heading" aria-level="3">Verifying the improvement</span></h3>
<p>To actually validate the improvement, you need to carefully structure the experiment. The agent runs should all use the same harness configuration, on the same sessions and prompts. Only the presence or absence of the skill should account for differences. Luckily, you can use the traces already collected with the Logfire MCP server as the test set. This is an example of branching turns for experimentation, because you need to grab the prior context and invocation without anything hinting at the past turn's results.</p>
<p>For this experiment, I took 12 dashboard panel creation scenarios with a variety of errors mixed in, and ran them on the same codex harness with and without the skill loaded. The results are shown in the Logfire experiment view. Without the skill, 9/12 runs failed and several of the formatting mistakes showed up as well. With the skill, every scenario succeeded without mistakes.</p>
<p><img src="https://pydantic.dev/assets/blog/coding-harness-tracing/skill-experiment-results.png" alt="Logfire experiment view comparing the run without the skill (baseline) and with it (candidate). Cases passed went from 3/12 to 12/12 and assertions from 57/72 to 72/72. The largest gap was sql_executes, which went from 25% to 100%." loading="lazy" decoding="async"></p>
<p><em>Logfire experiment view comparing the run without the skill (baseline) and with it (candidate). Cases passed went from 3/12 to 12/12 and assertions from 57/72 to 72/72. The largest gap was sql_executes, which went from 25% to 100%.</em></p>
</section></section><section id="evaluating-and-improving-harnesses-section"><h2 id="evaluating-and-improving-harnesses" role="presentation"><a href="#evaluating-and-improving-harnesses" class="heading-anchor"><button type="button" class="heading-anchor__btn">#</button></a><span role="heading" aria-level="2">Evaluating and improving harnesses</span></h2>
<p>The last pattern we'll show here combines several of the methods already introduced here towards the goal of actually improving your harness or optimizing your workflows. When you're using coding agents long enough you start to notice the subtle differences in behaviors when invoked with different models, harnesses, or instructions. Some models waste more tokens with over-engineering, others halt prematurely in long tasks, and then there is always the possibility of getting stuck in exploration loops.</p>
<p>There are a couple options when looking at ways to fix issues with agent behavior. You can try adjusting any of the levers mentioned above. You can try building your own harness. You can ignore it and hope it gets better. The problem with each approach on its own is that you don't have the data to verify the change had the desired effect, and that it didn't introduce new problems that will need to be fixed.</p>
<p>That's where experimentation flows for agent improvement come into play. The approach follows steps similar to the development of new skills, as shown in the diagram below:</p>
<p><img src="https://pydantic.dev/assets/blog/coding-harness-tracing/evaluation-workflow.png" alt="The evaluation workflow: select comparable traces for a task, build a dataset that keeps each trace&#x27;s context along with the model and harness used, apply consistent criteria, then compare agents on group scores." loading="lazy" decoding="async"></p>
<p><em>The evaluation workflow: select comparable traces for a task, build a dataset that keeps each trace's context along with the model and harness used, apply consistent criteria, then compare agents on group scores.</em></p>
<section id="finding-the-traces-and-building-the-datasets-section"><h3 id="finding-the-traces-and-building-the-datasets" role="presentation"><a href="#finding-the-traces-and-building-the-datasets" class="heading-anchor"><button type="button" class="heading-anchor__btn">#</button></a><span role="heading" aria-level="3">Finding the traces and building the datasets</span></h3>
<p>The first step is gathering the example prompts for the scenario you're trying to improve. In this case, you need examples that reflect both good and bad behavior, both in order to validate your criteria as well as to prevent regressions. You don't want to change the behavior such that something else breaks.</p>
<p>In this case, I went back to the visualization earlier where I noticed that agent fixes were actually the most expensive operation in my software factory.</p>
<p><img src="https://pydantic.dev/assets/blog/coding-harness-tracing/software-factory-cost-by-phase.png" alt="Cost by phase of the software factory pipeline, repeated from above. Review-fix is the most expensive phase at $43.30, which is why the experiments target the reviewer and implementation agents." loading="lazy" decoding="async"></p>
<p><em>Cost by phase of the software factory pipeline, repeated from above. Review-fix is the most expensive phase at $43.30, which is why the experiments target the reviewer and implementation agents.</em></p>
<p>To reduce the need to fix things I develop a two step sequence of experiments:</p>
<ol>
<li>Optimize the reviewer agent so that it doesn't fail as many reviews due to small stylistic choices, while still adhering to the instructions and conventions provided in the prompt.</li>
<li>Optimize the implementation agent so that the code doesn't fail the reviews and require fixing cycles.</li>
</ol>
<p>For this example, we'll just focus on the first stage, improving the focus and performance of reviewer agents. To start out, I searched back through the traces across different harnesses to find examples of review runs. To keep the experiments manageable, I collected 5 examples from small PR reviews.</p>
<p><img src="https://pydantic.dev/assets/blog/coding-harness-tracing/review-case-diffs.png" alt="The five matched code review cases, each from a real change, with the size of each diff: an agent alias refactor across six modules, derivation models, a template boundary, a web derived view and a prompt-sync web client." loading="lazy" decoding="async"></p>
<p><em>The five matched code review cases, each from a real change, with the size of each diff: an agent alias refactor across six modules, derivation models, a template boundary, a web derived view and a prompt-sync web client.</em></p>
<p>Since this data needs to be used in an experiment, the context needed to be added to a Logfire dataset. Datasets are for this exact scenario: fixed example cases to use when re-running evaluations with different agent or harness configurations. Since the outcome of the original reviews was irrelevant, I collected only the context that was fed into the original review step for re-use in experimentation and built the dataset.</p>
<p>I chose to test these 5 reviews on 3 different coding harnesses to see which one I should plug in to the review stage in my software factory. I compared Claude Code with haiku-5.5, Codex with gpt-6-luna, and Cursor with composer-2.5 to see which one gave the most effective PR reviews.</p>
</section><section id="evaluation-criteria-section"><h3 id="evaluation-criteria" role="presentation"><a href="#evaluation-criteria" class="heading-anchor"><button type="button" class="heading-anchor__btn">#</button></a><span role="heading" aria-level="3">Evaluation criteria</span></h3>
<p>Probably the most critical component of the experimentation and improvement flow is the evaluation criteria. This is where you encode alignment into the system you're developing. It's important to remember that most criteria are bounding undesirable outcomes rather than pushing towards a minima or maxima. In the case of reviews, I developed two agent evaluations that would run asynchronously using the inputs and outputs of the review agent.</p>
<p>The first evaluation tested the amount of nit-picking the reviewer was doing. This evaluator penalized overly sensitive review failures that cited formatting or stylistic choices. To balance the risk of overly lenient reviewers, the second evaluator measured how well the agent adhered to the conventions specified in the instructions. For my software factory, every agent receives a set of conventions to follow that basically lays out which frameworks to use and how code should be structured. The second evaluator penalized misalignment with the stated coding expectations.</p>
</section><section id="experiments-and-results-section"><h3 id="experiments-and-results" role="presentation"><a href="#experiments-and-results" class="heading-anchor"><button type="button" class="heading-anchor__btn">#</button></a><span role="heading" aria-level="3">Experiments and results</span></h3>
<p>Once the dataset and evaluators are created, the only thing left to do is run the experiment and interpret the results. In this context, an experiment means invoking the agent with the prompt from the dataset, running evaluations on the results, and aggregating across the cases to see the overall performance on each criterion.</p>
<p>For the reviewer experiments, each evaluator rated the response on 1-4 scale, where more significant issues with the review receive lower scores. Below is a table with the actual scoring for each harness and model. The PR verdicts are not included in the analysis of the agent's performance, but it's worth noting that some harnesses proved more strict or lenient and that is reflected in the scoring.</p>
<p><img src="https://pydantic.dev/assets/blog/coding-harness-tracing/review-score-tables.png" alt="Score tables for the five review cases, in the order Agent alias, Web derived view, Derivation models, Template boundary, Web client. Each row lists the verdict, then the standards score and the avoids-nits score out of 4. Codex with gpt-6-luna: PASS 4 and 4, FAIL 4 and 3, PASS 4 and 4, PASS 4 and 4, FAIL 4 and 4. Claude with claude-haiku-5-5: PASS 3 and 1, FAIL 3 and 2, FAIL 2 and 1, FAIL 2 and 0, FAIL 3 and 2. Cursor with composer-2.5: PASS 3 and 3, PASS 3 and 1, PASS 3 and 1, PASS 3 and 1, PASS 3 and 1. The tables also show a truncated excerpt of each review and the rationale for each score." loading="lazy" decoding="async"></p>
<p><em>5 reviews each for Codex, Claude-Code, and Cursor. The tables show the individual scores for each review on the 2 evaluation criteria used to assess performance.</em></p>
<p>The aggregate results painted a clear picture. Codex with gpt-6-luna significantly outperformed Cursor composer-2.5 and Claude haiku-5.5 on both standards adherence and avoiding nit-picking. In fact, on both criteria the order was the same, with Claude performing worst. The quality average shown here is the average on the 2 evaluation criteria, while the overall average simply incorporates a third metric meant to ensure the review ended in a verdict (which all runs did).</p>
<p><img src="https://pydantic.dev/assets/blog/coding-harness-tracing/reviewer-scores.png" alt="Reviewer scores out of 4 for the Claude Code, Cursor and Codex setups on the five cases. Codex scores highest on every panel (overall 3.93), Cursor is next (2.80) and Claude Code is lowest (2.60)." loading="lazy" decoding="async"></p>
<p><em>Reviewer scores out of 4 for the Claude Code, Cursor and Codex setups on the five cases. Codex scores highest on every panel (overall 3.93), Cursor is next (2.80) and Claude Code is lowest (2.60).</em></p>
</section></section><section id="where-to-go-from-here-section"><h2 id="where-to-go-from-here" role="presentation"><a href="#where-to-go-from-here" class="heading-anchor"><button type="button" class="heading-anchor__btn">#</button></a><span role="heading" aria-level="2">Where to go from here</span></h2>
<p>The patterns shown here are useful today in most coding agent configurations, but they are by no means an exhaustive representation of what is possible with an observability framework like Logfire. There are new features coming out every day, but they all require data and experimentation to drive improvements in performance and efficiency like the ones outlined here. These patterns show how tracing and experimentation can help teams improve coding agent performance and efficiency.</p></section>]]></content:encoded>
</item>
<item>
<title>What we found testing OpAMP clients against the spec</title>
<link>https://pydantic.dev/articles/fleet-opamp-core</link>
<guid isPermaLink="true">https://pydantic.dev/articles/fleet-opamp-core</guid>
<pubDate>Wed, 11 Nov 2026 09:00:00 GMT</pubDate>
<dc:creator>Bill Easton</dc:creator>
<category>Pydantic Logfire</category>
<category>OpenTelemetry</category>
<category>Open Source</category>
<description>Fleet Management in Pydantic Logfire ships OpAMP clients that share one protocol core, written once in Rust and run in six languages. How we check it against the spec, and the bugs that checking found in the upstream OpenTelemetry clients.</description>
<content:encoded><![CDATA[<aside class="callout callout-note"><div class="callout-indicator"><svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="2" aria-hidden="true"><path d="M12 8h.01M12 12v4"></path><circle cx="12" cy="12" r="10"></circle></svg><div class="callout-title">Fleet launch week</div></div><div class="callout-content"><p>This is the third of three posts. Start with <a href="https://pydantic.dev/articles/fleet-management-launch">Manage your telemetry in Logfire, send it anywhere</a>, or see Fleet working in <a href="https://pydantic.dev/articles/fleet-hands-on">Turn down OpenTelemetry noise without a redeploy</a>.</p></div></aside>
<p><a href="https://pydantic.dev/logfire/fleet-management">Fleet Management</a> in <a href="https://pydantic.dev/logfire">Pydantic Logfire</a> speaks <a href="https://opentelemetry.io/docs/specs/opamp/">OpAMP</a>, the OpenTelemetry protocol for managing agents. We ship OpAMP clients for Rust, Go, Node.js, Python, Java and .NET. They share one protocol core, written once in Rust. This post is about how that core is built, checked and tested, and what those same checks found when we pointed them at the upstream OpenTelemetry clients.</p>
<section id="why-test-the-client-so-hard-section"><h2 id="why-test-the-client-so-hard" role="presentation"><a href="#why-test-the-client-so-hard" class="heading-anchor"><button type="button" class="heading-anchor__btn">#</button></a><span role="heading" aria-level="2">Why test the client so hard?</span></h2>
<p>With Fleet Management, a remote management protocol is now in every process you run. Its job is to let a server change what those processes do. If the client gets reconnects wrong, a server restart becomes a thousand clients reconnecting in the same second. If it gets credentials wrong, a key rotation locks out the fleet. If it applies two configs in the wrong order, every machine ends up on the old one. And it gets all of these wrong on every machine at once.</p>
</section><section id="one-core-six-languages-section"><h2 id="one-core-six-languages" role="presentation"><a href="#one-core-six-languages" class="heading-anchor"><button type="button" class="heading-anchor__btn">#</button></a><span role="heading" aria-level="2">One core, six languages</span></h2>
<p>An OpAMP client is mostly a state machine. It says hello, reports status, heartbeats, answers the server's requests for a full report, accepts or rejects remote config, rotates the credentials the server offers, keeps its instance ID across restarts, backs off when the server is down. None of that depends on the language. Writing it six times means six sets of bugs, found and fixed six times.</p>
<p>So we wrote it once. The core takes events (bytes arrived, a timer fired, the application changed its status) and returns what to do next (send these bytes, set this timer, hand this config to the application). It doesn't read the clock or the network. Time and randomness come in as arguments.</p>
<p>Each language runs the same code:</p>
<ul>
<li><strong>Go, Node.js and Java</strong> run it as a WebAssembly module: in <a href="https://wazero.io/">wazero</a>, in Node's own WebAssembly engine, and in <a href="https://github.com/dylibso/chicory">Chicory</a>, which is pure Java.</li>
<li><strong>Python and .NET</strong> run it as a native library built from the same Rust, and their tests hold every reply byte for byte to the WebAssembly module's.</li>
<li><strong>Rust</strong> links it directly.</li>
</ul>
<p>The WebAssembly module has no imports. It can't open a file or a socket even if a bug told it to. What's left in each language is a thin shell: open connections, start TLS, move bytes, call back into the application.</p>
</section><section id="how-we-check-it-section"><h2 id="how-we-check-it" role="presentation"><a href="#how-we-check-it" class="heading-anchor"><button type="button" class="heading-anchor__btn">#</button></a><span role="heading" aria-level="2">How we check it</span></h2>
<p>Each layer catches a different kind of mistake.</p>
<p><strong>The spec, as a list.</strong> We quoted every normative statement in the OpAMP spec, about 300 of them, each with an ID. Everything below traces back to one of those IDs, so for any MUST in the spec you can find what checks it.</p>
<p><strong>A model of the protocol.</strong> The client's protocol, each feature flow and the server are written as <a href="https://lamport.azurewebsites.net/tla/tla.html">TLA+</a> models and checked with TLC: every reachable state, within bounds, against safety invariants and liveness properties like "a client that loses its connection reconnects".</p>
<p><strong>Proofs of the pure functions.</strong> <a href="https://model-checking.github.io/kani/">Kani</a> proves properties of the core's functions for every input, and <a href="https://github.com/verus-lang/verus">Verus</a> proves the URL, header and redirect rules.</p>
<p><strong>Tying the model to the code.</strong> A model is only useful if the code does what the model says. Recorded runs of the real code are checked by TLC as behaviors of the model. Then the other direction: TLC draws behaviors from the model, and the code has to take each step the way the model does.</p>
<p><strong>Black-box conformance.</strong> A suite of scenarios runs every client against a reference server over HTTP and WebSocket. It runs ours and the upstream OpenTelemetry clients, unchanged. CI fails if any of ours misses a MUST.</p>
<p><strong>Torture.</strong> Hours of seeded faults at once: the server restarting, a proxy dropping and delaying packets, the process frozen and thawed. The checks are simple to state: status never goes backward, the client catches up when things go quiet, and nothing storms or leaks.</p>
<p>Then the usual hygiene, applied hard: fuzzing of every byte interface, 100% coverage of the core, Miri on the unsafe code at the WebAssembly boundary, and mutation testing, so a deliberate bug in the code, the model or a proof has to be caught by something.</p>
</section><section id="what-we-found-upstream-section"><h2 id="what-we-found-upstream" role="presentation"><a href="#what-we-found-upstream" class="heading-anchor"><button type="button" class="heading-anchor__btn">#</button></a><span role="heading" aria-level="2">What we found upstream</span></h2>
<p>Fleet has to work with the OpAMP clients people already run, so the upstream clients go through the same scenarios as ours, and we connect them to Fleet the way a customer would. That turned up bugs in the Collector's OpAMP extension and Supervisor, and in the Java, Python and .NET OpAMP clients. We reported each one, and sent a fix where we could.</p>
<p><strong>Instance identity.</strong> OpAMP identifies each agent by an instance UID, and the server can assign a new one.</p>
<ul>
<li>.NET didn't adopt a server-assigned UID, and sent its own in mixed-endian byte order (<a href="https://github.com/open-telemetry/opentelemetry-dotnet-contrib/issues/5406">#5406</a>, fixed in <a href="https://github.com/open-telemetry/opentelemetry-dotnet-contrib/pull/5420">#5420</a>).</li>
<li>Python ignored <code>new_instance_uid</code> (<a href="https://github.com/open-telemetry/opentelemetry-python-contrib/issues/5092">#5092</a>, fix in <a href="https://github.com/open-telemetry/opentelemetry-python-contrib/pull/5096">#5096</a>), and doesn't send the <code>OpAMP-Instance-UID</code> header (<a href="https://github.com/open-telemetry/opentelemetry-python-contrib/pull/5285">#5285</a>).</li>
<li>Python sent queued messages with the sequence number and UID from when they were queued, not when they were sent (<a href="https://github.com/open-telemetry/opentelemetry-python-contrib/issues/5097">#5097</a>, fixed in <a href="https://github.com/open-telemetry/opentelemetry-python-contrib/pull/5107">#5107</a>).</li>
</ul>
<p><strong>Reconnects and status.</strong> The cases that only show up when a connection drops.</p>
<ul>
<li>The Java client didn't reconnect after the server closed the WebSocket (<a href="https://github.com/open-telemetry/opentelemetry-java-contrib/issues/3182">#3182</a>, fixed in <a href="https://github.com/open-telemetry/opentelemetry-java-contrib/pull/3192">#3192</a>), and didn't send a fresh status report when it did reconnect (<a href="https://github.com/open-telemetry/opentelemetry-java-contrib/issues/3188">#3188</a>, fixed).</li>
<li>Its first WebSocket status report could be dropped while the connection was still opening (<a href="https://github.com/open-telemetry/opentelemetry-java-contrib/issues/3183">#3183</a>), and HTTP errors never reached the application's callbacks (<a href="https://github.com/open-telemetry/opentelemetry-java-contrib/issues/3184">#3184</a>).</li>
<li>The Python client's disconnect, heartbeat and retry behavior differs from the spec (<a href="https://github.com/open-telemetry/opentelemetry-python-contrib/issues/5119">#5119</a>).</li>
</ul>
<p><strong>Capabilities.</strong> A client declares what it does, and the server may only rely on what it declared.</p>
<ul>
<li>The Java client left out <code>ReportsStatus</code>, which every client must declare (<a href="https://github.com/open-telemetry/opentelemetry-java-contrib/issues/3185">#3185</a>, fixed in <a href="https://github.com/open-telemetry/opentelemetry-java-contrib/pull/3189">#3189</a>).</li>
<li>The Collector's OpAMP extension didn't declare <code>ReportsHeartbeat</code>, so a server couldn't change its heartbeat interval (<a href="https://github.com/open-telemetry/opentelemetry-collector-contrib/issues/51427">#51427</a>, added in <a href="https://github.com/open-telemetry/opentelemetry-collector-contrib/pull/51426">#51426</a>).</li>
<li>The Supervisor applied a heartbeat interval of 0, which turns heartbeats off over WebSocket, and reported remote config status when configured not to (<a href="https://github.com/open-telemetry/opentelemetry-collector-contrib/issues/48363">#48363</a>).</li>
</ul>
<p><strong>Crashes.</strong> The Supervisor panics at startup if its persistent state file is empty (<a href="https://github.com/open-telemetry/opentelemetry-collector-contrib/issues/52720">#52720</a>), and the OpAMP extension panics if a custom capability is unregistered twice (<a href="https://github.com/open-telemetry/opentelemetry-collector-contrib/issues/52719">#52719</a>).</p>
<p>One more finding is a critical security vulnerability. Our core isn't affected.</p>
<p>None of these are exotic. They're in the parts of the protocol a demo never reaches: a second connection, a server that renames you, a message that waits in a queue. That's the case for writing the protocol once, checking it against every MUST, and running every client through the same scenarios.</p>
</section><section id="getting-started-section"><h2 id="getting-started" role="presentation"><a href="#getting-started" class="heading-anchor"><button type="button" class="heading-anchor__btn">#</button></a><span role="heading" aria-level="2">Getting started</span></h2>
<ul>
<li><a href="https://pydantic.dev/docs/logfire/observe/fleet/">Fleet overview</a> in the Logfire docs.</li>
<li>The OpAMP clients and their language guides: <a href="https://github.com/pydantic/opamp-clients">pydantic/opamp-clients</a>.</li>
<li>The <a href="https://opentelemetry.io/docs/specs/opamp/">OpAMP specification</a>.</li>
</ul>
<p>If you work on OpAMP, or run it at scale, we'd like to compare notes. Find us on <a href="https://github.com/pydantic/opamp-clients/issues">GitHub</a> or through <a href="https://pydantic.dev/contact">contact</a>.</p></section>]]></content:encoded>
</item>
<item>
<title>Code mode is not a sandbox</title>
<link>https://pydantic.dev/articles/code-mode-vs-sandboxes</link>
<guid isPermaLink="true">https://pydantic.dev/articles/code-mode-vs-sandboxes</guid>
<pubDate>Tue, 10 Nov 2026 09:00:00 GMT</pubDate>
<dc:creator>Marcelo Trylesinski</dc:creator>
<category>Pydantic AI</category>
<category>Pydantic Monty</category>
<description>Code mode changes how a model calls your tools. A sandbox changes where code runs. How the two differ, the three places a sandbox boundary can go, and how Pydantic AI workspaces and Monty fit in.</description>
<content:encoded><![CDATA[<p>"Code mode" and "sandbox" come up in the same conversations, and they often get used as if they meant the same thing. They don't. Code mode is about how the model calls your tools. A sandbox is about where code runs and what it can touch.</p>
<p>You can have either one without the other, and you can combine them when the model's code and your tools need different boundaries. This post covers what each one does, the three places a sandbox boundary can go, and how workspaces in <a href="https://pydantic.dev/docs/ai/overview/">Pydantic AI</a> let you move that boundary without rewriting your tools.</p>
<section id="what-code-mode-is-section"><h2 id="what-code-mode-is" role="presentation"><a href="#what-code-mode-is" class="heading-anchor"><button type="button" class="heading-anchor__btn">#</button></a><span role="heading" aria-level="2">What code mode is</span></h2>
<p>With ordinary tool calling, the model picks one tool, fills in JSON arguments, and waits. You run the tool, send the result back, and the model decides what to do next. When one call depends on another, each step costs a model request, and every intermediate result lands in the context window.</p>
<p>With code mode, the model gets a single tool, <code>run_code</code>, and writes a short Python program that calls your tools as functions. Loops, filters, and <code>asyncio.gather</code> run as code instead of as more turns of conversation. <a href="https://blog.cloudflare.com/code-mode/">Cloudflare</a> named the pattern, and <a href="https://www.anthropic.com/engineering/code-execution-with-mcp">Anthropic</a> reached the same conclusion from the model side.</p>
<p>In Pydantic AI, code mode is the <code>CodeMode</code> capability from <a href="https://pydantic.dev/docs/ai/harness/">Pydantic AI Harness</a>:</p>
<pre><code class="hljs language-python"><span class="hljs-keyword">from</span> typing <span class="hljs-keyword">import</span> TypedDict

<span class="hljs-keyword">import</span> logfire
<span class="hljs-keyword">from</span> pydantic_ai <span class="hljs-keyword">import</span> Agent
<span class="hljs-keyword">from</span> pydantic_ai_harness <span class="hljs-keyword">import</span> CodeMode

logfire.configure(service_name=<span class="hljs-string">'code-mode'</span>)
logfire.instrument_pydantic_ai()


<span class="hljs-keyword">class</span> <span class="hljs-title class_">Order</span>(<span class="hljs-title class_ inherited__">TypedDict</span>):
    <span class="hljs-built_in">id</span>: <span class="hljs-built_in">str</span>
    total: <span class="hljs-built_in">float</span>


ORDERS = {<span class="hljs-string">'cus_42'</span>: [<span class="hljs-string">'ord_1'</span>, <span class="hljs-string">'ord_2'</span>, <span class="hljs-string">'ord_3'</span>]}
TOTALS = {<span class="hljs-string">'ord_1'</span>: <span class="hljs-number">120.0</span>, <span class="hljs-string">'ord_2'</span>: <span class="hljs-number">35.5</span>, <span class="hljs-string">'ord_3'</span>: <span class="hljs-number">210.0</span>}

agent = Agent(<span class="hljs-string">'anthropic:claude-sonnet-5-5'</span>, capabilities=[CodeMode()])


<span class="hljs-meta">@agent.tool_plain</span>
<span class="hljs-keyword">def</span> <span class="hljs-title function_">list_orders</span>(<span class="hljs-params">customer_id: <span class="hljs-built_in">str</span></span>) -> <span class="hljs-built_in">list</span>[<span class="hljs-built_in">str</span>]:
    <span class="hljs-string">"""List the order IDs for a customer."""</span>
    <span class="hljs-keyword">return</span> ORDERS.get(customer_id, [])


<span class="hljs-meta">@agent.tool_plain</span>
<span class="hljs-keyword">def</span> <span class="hljs-title function_">get_order</span>(<span class="hljs-params">order_id: <span class="hljs-built_in">str</span></span>) -> Order:
    <span class="hljs-string">"""Fetch one order."""</span>
    <span class="hljs-keyword">return</span> Order(<span class="hljs-built_in">id</span>=order_id, total=TOTALS[order_id])


result = agent.run_sync(<span class="hljs-string">'How many orders over $100 does cus_42 have, and what is their total?'</span>)
<span class="hljs-built_in">print</span>(result.output)
</code></pre>
<p>Install it with <code>uv add "pydantic-ai-harness[codemode,anthropic,logfire]"</code>, and set your model provider API keys, in this case <code>ANTHROPIC_API_KEY</code>.</p>
<p>The model never sees <code>list_orders</code> and <code>get_order</code> as separate tools. It sees them as typed Python functions in the description of <code>run_code</code>:</p>
<pre><code class="hljs language-python"><span class="hljs-keyword">class</span> <span class="hljs-title class_">Order</span>(<span class="hljs-title class_ inherited__">TypedDict</span>):
    <span class="hljs-built_in">id</span>: <span class="hljs-built_in">str</span>
    total: <span class="hljs-built_in">float</span>

<span class="hljs-keyword">async</span> <span class="hljs-keyword">def</span> <span class="hljs-title function_">list_orders</span>(<span class="hljs-params">*, customer_id: <span class="hljs-built_in">str</span></span>) -> <span class="hljs-built_in">list</span>[<span class="hljs-built_in">str</span>]:
    <span class="hljs-string">"""List the order IDs for a customer."""</span>
    ...

<span class="hljs-keyword">async</span> <span class="hljs-keyword">def</span> <span class="hljs-title function_">get_order</span>(<span class="hljs-params">*, order_id: <span class="hljs-built_in">str</span></span>) -> Order:
    <span class="hljs-string">"""Fetch one order."""</span>
    ...
</code></pre>
<p>And it writes one program:</p>
<pre><code class="hljs language-python"><span class="hljs-keyword">import</span> asyncio

order_ids = <span class="hljs-keyword">await</span> list_orders(customer_id=<span class="hljs-string">'cus_42'</span>)
orders = <span class="hljs-keyword">await</span> asyncio.gather(*[get_order(order_id=i) <span class="hljs-keyword">for</span> i <span class="hljs-keyword">in</span> order_ids])
big = [o <span class="hljs-keyword">for</span> o <span class="hljs-keyword">in</span> orders <span class="hljs-keyword">if</span> o[<span class="hljs-string">'total'</span>] > <span class="hljs-number">100</span>]
{<span class="hljs-string">'count'</span>: <span class="hljs-built_in">len</span>(big), <span class="hljs-string">'total'</span>: <span class="hljs-built_in">sum</span>(o[<span class="hljs-string">'total'</span>] <span class="hljs-keyword">for</span> o <span class="hljs-keyword">in</span> big)}
</code></pre>
<p><img src="https://pydantic.dev/assets/blog/code-mode-vs-sandboxes/tool-calling-vs-code-mode.svg" alt="With tool calling, the model makes three requests and every intermediate result enters its context. With code mode, it makes two, and only the final dict comes back." decoding="async"></p>
<p>Without code mode, the model needs one request to list the orders, another to fetch them, and a third to answer, with every order in its context along the way. With code mode, it writes one program and reads back one small dict. The gap grows with every dependent step.</p>
<p>Here is that run traced in <a href="https://pydantic.dev/logfire">Logfire</a>. <code>list_orders</code> and the three <code>get_order</code> calls sit inside the single <code>run_code</code> span, between the two model requests:</p>
<iframe src="https://logfire-eu.pydantic.dev/public-trace/b3ae185b-b724-403b-b2cb-12e76367b1ff?spanId=2773065b28658fe7&#x26;embedded=true&#x26;theme=light" height="400" style="width: 100%; border: 0;" loading="lazy" title="Logfire trace of a code mode agent run: one run_code tool call containing list_orders and three get_order calls, between two model requests"></iframe>
<p>Explore the spans above, or <a href="https://logfire-eu.pydantic.dev/public-trace/b3ae185b-b724-403b-b2cb-12e76367b1ff?spanId=2773065b28658fe7">open the full trace</a>.</p>
<p>The program is type-checked against those signatures before it runs. A model that compares a string with an int gets a type error back as a retry instead of producing a wrong answer.</p>
<p>Jiri wrote about <a href="https://pydantic.dev/articles/your-agent-would-rather-write-code">what this did for the Logfire MCP server</a>, where three tools replaced more than forty.</p>
</section><section id="code-mode-runs-next-to-your-agent-section"><h2 id="code-mode-runs-next-to-your-agent" role="presentation"><a href="#code-mode-runs-next-to-your-agent" class="heading-anchor"><button type="button" class="heading-anchor__btn">#</button></a><span role="heading" aria-level="2">Code mode runs next to your agent</span></h2>
<p>The program needs somewhere to run. In Pydantic AI, <code>run_code</code> runs in <a href="https://github.com/pydantic/monty">Monty</a>, a Python interpreter written in Rust, in a pool of worker processes on the same machine as your agent.</p>
<p>Inside <code>run_code</code>, the program has no filesystem, no network, no environment variables, and no clock unless you hand them in. It reaches the outside world only by calling the functions you exposed. When it calls <code>get_order</code>, Monty pauses, Pydantic AI runs your real <code>get_order</code> in the agent's process, and the result goes back into the program.</p>
<p>So two things are true at once:</p>
<ul>
<li><strong>The program is isolated.</strong> It can't open a socket or read <code>~/.ssh</code>. By default, each <code>run_code</code> call gets 30 seconds, 256 MiB, and 100 nested tool calls.</li>
<li><strong>Your tools are not.</strong> <code>get_order</code> runs with whatever access your agent process has: database credentials, API keys, the host filesystem.</li>
</ul>
<p>In code mode, the security boundary is the list of functions you expose. Put <code>refund_order</code> in that list and the model can write a loop that calls it 100 times. <code>CodeMode(tools=['list_orders', 'get_order'])</code> chooses which tools go inside <code>run_code</code>; the rest stay visible to the model as ordinary tool calls.</p>
<p>Monty also runs a subset of Python, with a short list of standard library modules and no third-party packages. The model can't <code>pip install pandas</code>, run <code>pytest</code>, or call <code>git</code> from inside it. For that you need a real execution environment: your own machine if you trust the work, or a sandbox if you don't.</p>
</section><section id="what-a-sandbox-is-section"><h2 id="what-a-sandbox-is" role="presentation"><a href="#what-a-sandbox-is" class="heading-anchor"><button type="button" class="heading-anchor__btn">#</button></a><span role="heading" aria-level="2">What a sandbox is</span></h2>
<p>A sandbox is an isolated environment: a container, a microVM, a cloud VM, or a restricted process on your own machine. Unlike Monty, it usually has a real filesystem, a shell, and CPython, so the model can run ordinary programs. What those programs can run and reach depends on the sandbox's image, network rules, and mounts.</p>
<div class="overflow-x-auto table-wrapper" tabindex="0"><table>
<thead>
<tr>
<th></th>
<th>Code mode with Monty</th>
<th>Sandbox</th>
</tr>
</thead>
<tbody>
<tr>
<td>Solves</td>
<td>Too many model round trips</td>
<td>Running programs you don't trust</td>
</tr>
<tr>
<td>Runs</td>
<td>A subset of Python</td>
<td>Whatever its image and permissions allow, usually CPython, a shell, <code>git</code>, <code>pytest</code></td>
</tr>
<tr>
<td>New session in</td>
<td><a href="https://pydantic.dev/docs/monty/reference/alternatives/">0.8 ms from a warm pool</a></td>
<td>About 1.5 s for a new Daytona sandbox, in <a href="https://pydantic.dev/docs/monty/reference/alternatives/#latency">one measurement</a></td>
</tr>
<tr>
<td>Reaches the outside through</td>
<td>Functions you expose</td>
<td>Whatever its network and mounts allow</td>
</tr>
<tr>
<td>Your tools run</td>
<td>In your agent's process</td>
<td>Wherever you point them</td>
</tr>
</tbody>
</table></div>
</section><section id="where-the-sandbox-boundary-goes-section"><h2 id="where-the-sandbox-boundary-goes" role="presentation"><a href="#where-the-sandbox-boundary-goes" class="heading-anchor"><button type="button" class="heading-anchor__btn">#</button></a><span role="heading" aria-level="2">Where the sandbox boundary goes</span></h2>
<p>Once you need a sandbox, the next question is what goes inside it. There are three answers.</p>
<p><img src="https://pydantic.dev/assets/blog/code-mode-vs-sandboxes/sandbox-boundaries.svg" alt="Three places to put the sandbox boundary: around the whole agent, including the model key; around only the tools, through a workspace; or around only the model&#x27;s program, in Monty." loading="lazy" decoding="async"></p>
<section id="the-whole-agent-section"><h3 id="the-whole-agent" role="presentation"><a href="#the-whole-agent" class="heading-anchor"><button type="button" class="heading-anchor__btn">#</button></a><span role="heading" aria-level="3">The whole agent</span></h3>
<p>The entire agent runs inside the sandbox: the agent loop, the model client, the tools, and the files it works on. Cloud coding agents work this way. <a href="https://code.claude.com/docs/en/claude-code-on-the-web">Claude Code on the web</a> runs each session in an isolated VM, with the agent loop inside it. A coding agent in a dev container or a CI job is the self-hosted version.</p>
<p>It is the simplest setup, with one boundary around everything. The cost is that everything the agent needs has to live in there too. A model that can run shell commands can read any credential the agent holds, unless you build a proxy that adds credentials outside the VM, as Claude Code on the web does for git. Every conversation also needs a sandbox for its whole lifetime, and the agent's state lives and dies with it.</p>
</section><section id="only-the-tools-section"><h3 id="only-the-tools" role="presentation"><a href="#only-the-tools" class="heading-anchor"><button type="button" class="heading-anchor__btn">#</button></a><span role="heading" aria-level="3">Only the tools</span></h3>
<p>The agent loop runs in your process, with your keys and your database. The tools that touch files and run commands act in a sandbox somewhere else. The model reaches the sandbox only through those tools, and credentials the sandbox doesn't need never go in.</p>
<p>This is the shape a Pydantic AI workspace gives you. Tools are the main users, but anything with a <code>RunContext</code> can reach the workspace, including hooks, and your own code can use <code>result.workspace</code> after the run.</p>
</section><section id="only-the-code-section"><h3 id="only-the-code" role="presentation"><a href="#only-the-code" class="heading-anchor"><button type="button" class="heading-anchor__btn">#</button></a><span role="heading" aria-level="3">Only the code</span></h3>
<p>The agent and its tools run in your process, and only the program the model writes is isolated. This is code mode, with Monty as the sandbox and the exposed functions as its only way out. To keep even the interpreter off your agent's machine, <code>CodeMode(monty_sandbox_url=...)</code> sends the program to a remote Monty worker such as <a href="https://pydantic.dev/docs/monty/commercial-support/server/">Monty's Commercial Support</a>, while your tools keep running locally.</p>
<p>The last two compose: an agent can run its code in Monty and its tools in a sandbox. That combination needs a way to point tools at an environment, which is what a workspace is.</p>
</section></section><section id="workspaces-in-pydantic-ai-section"><h2 id="workspaces-in-pydantic-ai" role="presentation"><a href="#workspaces-in-pydantic-ai" class="heading-anchor"><button type="button" class="heading-anchor__btn">#</button></a><span role="heading" aria-level="2">Workspaces in Pydantic AI</span></h2>
<p>A <a href="https://pydantic.dev/docs/ai/core-concepts/workspace/">workspace</a> is the environment an agent's tools work in: where commands run and where files are read and written. Tools reach it through <code>ctx.workspace</code>, and they don't know whether it is a directory on your laptop or a VM in the cloud.</p>
<pre><code class="hljs language-python"><span class="hljs-keyword">import</span> logfire
<span class="hljs-keyword">from</span> pydantic_ai <span class="hljs-keyword">import</span> Agent, ModelRetry, RunContext
<span class="hljs-keyword">from</span> pydantic_ai.capabilities <span class="hljs-keyword">import</span> LocalWorkspace
<span class="hljs-keyword">from</span> pydantic_ai.workspaces <span class="hljs-keyword">import</span> WorkspaceError

logfire.configure(service_name=<span class="hljs-string">'workspaces'</span>)
logfire.instrument_pydantic_ai()

agent = Agent(<span class="hljs-string">'anthropic:claude-sonnet-5-5'</span>, capabilities=[LocalWorkspace(<span class="hljs-string">'.'</span>)])


<span class="hljs-meta">@agent.tool</span>
<span class="hljs-keyword">async</span> <span class="hljs-keyword">def</span> <span class="hljs-title function_">execute</span>(<span class="hljs-params">ctx: RunContext, command: <span class="hljs-built_in">list</span>[<span class="hljs-built_in">str</span>]</span>) -> <span class="hljs-built_in">str</span>:
    <span class="hljs-string">"""Run a command in the project directory."""</span>
    <span class="hljs-keyword">try</span>:
        result = <span class="hljs-keyword">await</span> ctx.workspace.run(command, timeout=<span class="hljs-number">60</span>)
    <span class="hljs-keyword">except</span> WorkspaceError <span class="hljs-keyword">as</span> error:
        <span class="hljs-keyword">raise</span> ModelRetry(<span class="hljs-built_in">str</span>(error))
    <span class="hljs-keyword">return</span> result.stdout <span class="hljs-keyword">if</span> result.exit_code == <span class="hljs-number">0</span> <span class="hljs-keyword">else</span> <span class="hljs-string">f'[exit <span class="hljs-subst">{result.exit_code}</span>] <span class="hljs-subst">{result.stderr}</span>'</span>


result = agent.run_sync(<span class="hljs-string">'Write fizzbuzz to fizzbuzz.py and run it.'</span>)
<span class="hljs-built_in">print</span>(result.output)
</code></pre>
<p><code>LocalWorkspace</code> is not a sandbox. Commands run on your machine, as you, and the directory only sets where they start. They get <code>PATH</code>, <code>HOME</code>, and the locale variables and nothing else from your environment, so the model's commands don't inherit your API keys. Use it for your own, trusted work.</p>
<p>To isolate the agent, swap the workspace capability. <code>execute</code> keeps working unchanged, because it only talks to <code>ctx.workspace</code>.</p>
<p>You rarely need to write tools like <code>execute</code> yourself, though. The harness capabilities <code>Coder</code>, <code>FileSystem</code>, and <code>Shell</code> give the model file, search, and shell tools that work in whatever workspace the run has. This agent gets <code>Coder</code> in a <a href="https://pydantic.dev/articles/harness-modal">Modal</a> sandbox:</p>
<pre><code class="hljs language-python"><span class="hljs-keyword">import</span> logfire
<span class="hljs-keyword">from</span> pydantic_ai <span class="hljs-keyword">import</span> Agent
<span class="hljs-keyword">from</span> pydantic_ai_harness <span class="hljs-keyword">import</span> Coder, ModalSandbox

logfire.configure()
logfire.instrument_pydantic_ai()

agent = Agent(<span class="hljs-string">'anthropic:claude-sonnet-5-5'</span>, capabilities=[ModalSandbox(), Coder()])
</code></pre>
<p>Install it with <code>uv add "pydantic-ai-harness[modal,anthropic,logfire]"</code>, and log in to Modal with <code>modal token new</code>. Every command and file edit now happens in the sandbox.</p>
<p>This trace is the <code>LocalWorkspace</code> agent from earlier writing and running fizzbuzz. Each <code>execute</code> call is one span, with a model request on either side:</p>
<iframe src="https://logfire-eu.pydantic.dev/public-trace/e9ca4b63-b5cc-470b-b15e-0294d65fdf8f?spanId=bc77584d9dad4fe1&#x26;embedded=true&#x26;theme=light" height="400" style="width: 100%; border: 0;" loading="lazy" title="Logfire trace of a Pydantic AI agent with a local workspace: two execute tool calls that write and run fizzbuzz.py, between three model requests"></iframe>
<p>Explore the spans above, or <a href="https://logfire-eu.pydantic.dev/public-trace/e9ca4b63-b5cc-470b-b15e-0294d65fdf8f?spanId=bc77584d9dad4fe1">open the full trace</a>.</p>
<p>Pydantic AI and Pydantic AI Harness ship these workspaces:</p>
<div class="overflow-x-auto table-wrapper" tabindex="0"><table>
<thead>
<tr>
<th>Workspace</th>
<th>Where commands run</th>
<th>Isolation</th>
</tr>
</thead>
<tbody>
<tr>
<td><code>LocalWorkspace</code></td>
<td>This machine, as you</td>
<td>None</td>
</tr>
<tr>
<td><code>SSHWorkspace</code></td>
<td>A remote host, through your <code>ssh</code></td>
<td>None</td>
</tr>
<tr>
<td><a href="https://pydantic.dev/docs/ai/harness/bubblewrap-sandbox/"><code>BubblewrapSandbox</code></a></td>
<td>A local or SSH workspace, under <code>bwrap</code></td>
<td>Read-only host, writable working directory, no network by default. Stops accidents, not a hostile agent</td>
</tr>
<tr>
<td><a href="https://pydantic.dev/docs/ai/harness/smol-sandbox/"><code>SmolSandbox</code></a></td>
<td>A microVM on this machine</td>
<td>A VM, without a cloud account</td>
</tr>
<tr>
<td><a href="https://pydantic.dev/docs/ai/harness/modal-sandbox/"><code>ModalSandbox</code></a>, <a href="https://pydantic.dev/docs/ai/harness/e2b-sandbox/"><code>E2BSandbox</code></a>, <a href="https://pydantic.dev/docs/ai/harness/sprites-sandbox/"><code>SpritesSandbox</code></a></td>
<td>A cloud sandbox</td>
<td>A separate machine</td>
</tr>
</tbody>
</table></div>
<p>A workspace outlives a single run. Once a run has used a sandbox, passing its message history to the next run continues in the same sandbox, with the same files and installed packages:</p>
<pre><code class="hljs language-python">first = agent.run_sync(<span class="hljs-string">'Clone https://github.com/pydantic/pydantic-ai and run its tests.'</span>)
second = agent.run_sync(<span class="hljs-string">'Fix the first failing test.'</span>, message_history=first.all_messages())
</code></pre>
<aside class="callout callout-warn"><div class="callout-indicator"><svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="2" aria-hidden="true"><path d="M12 9v4m0 4h.01M8.681 4.082C9.351 2.797 10.621 2 12 2s2.649.797 3.319 2.082l6.203 11.904a4.28 4.28 0 0 1-.046 4.019C20.793 21.241 19.549 22 18.203 22H5.797c-1.346 0-2.59-.759-3.273-1.995a4.28 4.28 0 0 1-.046-4.019L8.681 4.082Z"></path></svg><div class="callout-title">Sandboxes outlive the run</div></div><div class="callout-content"><p>Pydantic AI never deletes a sandbox. It keeps running, and billing, until you destroy it or the provider's lifetime limit stops it. The <a href="https://pydantic.dev/docs/ai/core-concepts/workspace/#cleaning-up">workspace docs</a> show where to clean up.</p></div></aside>
</section><section id="code-mode-and-a-workspace-together-section"><h2 id="code-mode-and-a-workspace-together" role="presentation"><a href="#code-mode-and-a-workspace-together" class="heading-anchor"><button type="button" class="heading-anchor__btn">#</button></a><span role="heading" aria-level="2">Code mode and a workspace together</span></h2>
<p>Code mode and workspaces solve different problems, so they combine. Here the model's Python runs in Monty next to the agent, and the file tools it calls from that Python act in a Modal sandbox:</p>
<pre><code class="hljs language-python"><span class="hljs-keyword">import</span> logfire
<span class="hljs-keyword">from</span> pydantic_ai <span class="hljs-keyword">import</span> Agent
<span class="hljs-keyword">from</span> pydantic_ai_harness <span class="hljs-keyword">import</span> CodeMode, FileSystem, ModalSandbox, Shell

logfire.configure()
logfire.instrument_pydantic_ai()

agent = Agent(
    <span class="hljs-string">'anthropic:claude-sonnet-5-5'</span>,
    capabilities=[ModalSandbox(working_dir=<span class="hljs-string">'/root/project'</span>), FileSystem(), Shell(), CodeMode()],
)

result = agent.run_sync(<span class="hljs-string">'Find every TODO in the project and summarize them by file.'</span>)
<span class="hljs-built_in">print</span>(result.output)
</code></pre>
<p>Install it with <code>uv add "pydantic-ai-harness[codemode,modal,anthropic,logfire]"</code>, and log in to Modal with <code>modal token new</code>.</p>
<p>The model sees three tools: <code>run_code</code>, <code>run_command</code>, and <code>start_command</code>. <code>read_file</code>, <code>edit_file</code>, <code>list_directory</code>, and the other file tools become functions inside <code>run_code</code>, so one program can read twenty files, filter them, and edit the three that matter. Shell commands stay outside as ordinary tool calls, so the model never has to quote a shell command inside a Python string.</p>
<p><img src="https://pydantic.dev/assets/blog/code-mode-vs-sandboxes/code-mode-with-workspace.svg" alt="Your process holds the agent loop, the model key, Monty, and the tool functions. The model&#x27;s program in Monty and the agent loop both call the tool functions, which act in the Modal sandbox through ctx.workspace." loading="lazy" decoding="async"></p>
<p>Each layer has one job:</p>
<ul>
<li>The agent loop and your model key stay in your process.</li>
<li>The program the model writes runs in Monty, which can reach only the functions you exposed.</li>
<li>The file and shell tools act in the Modal sandbox, so edits and commands never touch your machine.</li>
</ul>
<aside class="callout callout-note"><div class="callout-indicator"><svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="2" aria-hidden="true"><path d="M12 8h.01M12 12v4"></path><circle cx="12" cy="12" r="10"></circle></svg><div class="callout-title">Mounts are host directories</div></div><div class="callout-content"><p><code>CodeMode(mount=...)</code> shares directories from the machine running the agent, not from the workspace. With a remote sandbox, use the file tools for files the model shares with its commands.</p></div></aside>
</section><section id="which-one-you-need-section"><h2 id="which-one-you-need" role="presentation"><a href="#which-one-you-need" class="heading-anchor"><button type="button" class="heading-anchor__btn">#</button></a><span role="heading" aria-level="2">Which one you need</span></h2>
<div class="overflow-x-auto table-wrapper" tabindex="0"><table>
<thead>
<tr>
<th>You want</th>
<th>Use</th>
</tr>
</thead>
<tbody>
<tr>
<td>Fewer model round trips when a task chains several tool calls</td>
<td><code>CodeMode()</code></td>
</tr>
<tr>
<td>The model to run tests, install packages, or use <code>git</code> on your own repo</td>
<td><code>LocalWorkspace</code> with <code>Coder()</code></td>
</tr>
<tr>
<td>The same, for a repo or prompt you don't trust</td>
<td>A sandbox workspace with <code>Coder()</code></td>
</tr>
<tr>
<td>A managed cloud sandbox</td>
<td><code>E2BSandbox()</code>, <code>ModalSandbox()</code>, or <code>SpritesSandbox()</code></td>
</tr>
<tr>
<td>Isolation without a cloud account</td>
<td><code>SmolSandbox()</code></td>
</tr>
<tr>
<td>Both orchestration and isolation</td>
<td><code>CodeMode()</code> plus a sandbox workspace</td>
</tr>
</tbody>
</table></div>
</section><section id="monty-section"><h2 id="monty" role="presentation"><a href="#monty" class="heading-anchor"><button type="button" class="heading-anchor__btn">#</button></a><span role="heading" aria-level="2">Monty</span></h2>
<p>Code mode is cheap enough to leave on because of <a href="https://github.com/pydantic/monty">Monty</a>. It is an MIT-licensed Python interpreter written in Rust, built for code written by models. You can use it without Pydantic AI, from Python, JavaScript, or Rust:</p>
<pre><code class="hljs language-python"><span class="hljs-keyword">import</span> logfire
<span class="hljs-keyword">from</span> pydantic_monty <span class="hljs-keyword">import</span> Monty

logfire.configure(service_name=<span class="hljs-string">'monty'</span>)
logfire.instrument_monty()

code = <span class="hljs-string">"""
kcal = nutrition('chocolate bar')['kcal']
hours = kcal * 4184 / (bulb_watts * 3600)
print(f'a chocolate bar powers a {bulb_watts} W bulb for {hours:.1f} hours')
"""</span>

<span class="hljs-keyword">with</span> Monty() <span class="hljs-keyword">as</span> pool:
    <span class="hljs-keyword">with</span> pool.checkout() <span class="hljs-keyword">as</span> session:
        session.feed_run(
            code,
            inputs={<span class="hljs-string">'bulb_watts'</span>: <span class="hljs-number">10</span>},
            external_lookup={<span class="hljs-string">'nutrition'</span>: <span class="hljs-keyword">lambda</span> food: {<span class="hljs-string">'kcal'</span>: <span class="hljs-number">230</span>}},
        )
        <span class="hljs-comment">#> a chocolate bar powers a 10 W bulb for 26.7 hours</span>
</code></pre>
<p><code>Monty()</code> starts a <code>monty</code> worker process, and <code>code</code> runs inside it. <code>inputs</code> puts a variable called <code>bulb_watts</code> in the sandbox, with the value 10. external_lookup lets code call nutrition, but the function stays in your own Python process. When <code>code</code> calls <code>nutrition('chocolate bar')</code>, the worker waits, your process runs the function, and <code>{'kcal': 230}</code> goes back to <code>code</code>. <code>code</code> can call the function and read what it returns, but the function itself never runs inside Monty.</p>
<p>Install it with <code>uv add pydantic-monty logfire</code>.</p>
<section id="why-use-monty-section"><h3 id="why-use-monty" role="presentation"><a href="#why-use-monty" class="heading-anchor"><button type="button" class="heading-anchor__btn">#</button></a><span role="heading" aria-level="3">Why use Monty</span></h3>
<ul>
<li><strong>Your secrets stay in your process.</strong> <code>nutrition</code> could query a database with your credentials, and the code the model wrote would still see only <code>{'kcal': 230}</code>.</li>
<li><strong>It can pause and pick up later.</strong> While the worker waits for <code>nutrition</code>, Monty can <a href="https://pydantic.dev/docs/monty/concepts/snapshots/">save the whole run to bytes</a>. You can resume it later, in another process or on another machine.</li>
<li><strong>It is small.</strong> Monty is built for the short scripts agents write. It runs as a process next to your agent, with no container and no cloud account.</li>
</ul>
<p>Use <code>CodeMode()</code> when a task chains several tool calls and you want fewer model round trips. When the model has to run tests, install packages, or use <code>git</code>, give it <code>Coder()</code>: with <code>LocalWorkspace</code> on your own repo, or with a sandbox workspace for a repo or prompt you don't trust. That sandbox can be a managed cloud one, <code>E2BSandbox()</code>, <code>ModalSandbox()</code>, or <code>SpritesSandbox()</code>, or <code>SmolSandbox()</code> if you have no cloud account. For both fewer round trips and isolation, use <code>CodeMode()</code> with a sandbox workspace.</p>
<ul>
<li><a href="https://github.com/pydantic/monty">Monty on GitHub</a></li>
<li><a href="https://pydantic.dev/docs/monty/">Monty documentation</a>, including the <a href="https://pydantic.dev/docs/monty/concepts/security/">security model</a> and a <a href="https://pydantic.dev/docs/monty/reference/alternatives/">comparison with the alternatives</a></li>
<li><a href="https://pydantic.dev/articles/pydantic-monty">Pydantic Monty: you probably don't need a full sandbox</a>, Samuel's post on why Monty exists</li>
<li><a href="https://pydantic.dev/docs/ai/harness/code-mode/">Code mode</a> and <a href="https://pydantic.dev/docs/ai/core-concepts/workspace/">workspaces</a> in the Pydantic AI docs</li>
</ul></section></section>]]></content:encoded>
</item>
<item>
<title>Turn down OpenTelemetry noise without a redeploy</title>
<link>https://pydantic.dev/articles/fleet-hands-on</link>
<guid isPermaLink="true">https://pydantic.dev/articles/fleet-hands-on</guid>
<pubDate>Tue, 10 Nov 2026 09:00:00 GMT</pubDate>
<dc:creator>Bill Easton</dc:creator>
<category>Pydantic Logfire</category>
<category>OpenTelemetry</category>
<category>New Features</category>
<description>Connect a Python service and a host to Fleet Management in Pydantic Logfire, then change the service&apos;s log level, redaction and sampling, and the host&apos;s Collector, while both keep running.</description>
<content:encoded><![CDATA[<aside class="callout callout-note"><div class="callout-indicator"><svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="2" aria-hidden="true"><path d="M12 8h.01M12 12v4"></path><circle cx="12" cy="12" r="10"></circle></svg><div class="callout-title">Fleet launch week</div></div><div class="callout-content"><p>This is the second of three posts. The first, <a href="https://pydantic.dev/articles/fleet-management-launch">Manage your telemetry in Logfire, send it anywhere</a>, explains what Fleet Management is. The third, <a href="https://pydantic.dev/articles/fleet-opamp-core">What we found testing OpAMP clients against the spec</a>, covers how we check the OpAMP clients behind Fleet.</p></div></aside>
<p>This post connects a service and the host it runs on to <a href="https://pydantic.dev/logfire/fleet-management">Fleet Management</a> in Pydantic Logfire, then changes the service's log level, redaction and sampling and the host's Collector while both keep running.</p>
<p>You need a Logfire project (Fleet is on for every plan), a <a href="https://pydantic.dev/docs/logfire/manage/create-write-tokens/">write token</a>, Python 3.11 or later, and <a href="https://docs.astral.sh/uv/getting-started/installation/">uv</a>. Every step below also works for Node.js, Java, .NET and Go; the differences are in one table.</p>
<section id="why-change-it-live-section"><h2 id="why-change-it-live" role="presentation"><a href="#why-change-it-live" class="heading-anchor"><button type="button" class="heading-anchor__btn">#</button></a><span role="heading" aria-level="2">Why change it live?</span></h2>
<p><code>checkout-api</code> logs at debug, puts a card token on one of its spans, and traffic just tripled, taking the ingest bill with it. You want less of all three, and you want it now, not after a deploy.</p>
</section><section id="the-service-a-fastapi-app-with-fleettrue-section"><h2 id="the-service-a-fastapi-app-with-fleettrue" role="presentation"><a href="#the-service-a-fastapi-app-with-fleettrue" class="heading-anchor"><button type="button" class="heading-anchor__btn">#</button></a><span role="heading" aria-level="2">The service: a FastAPI app with <code>fleet=True</code></span></h2>
<p>Here's <code>checkout-api</code>, a FastAPI app on the Logfire SDK. The only Fleet-specific part is <code>fleet=True</code>:</p>
<pre><code class="hljs language-python"><span class="hljs-keyword">import</span> logfire
<span class="hljs-keyword">from</span> fastapi <span class="hljs-keyword">import</span> FastAPI

logfire.configure(service_name=<span class="hljs-string">'checkout-api'</span>, fleet=<span class="hljs-literal">True</span>)

app = FastAPI()
logfire.instrument_fastapi(app)


<span class="hljs-meta">@app.post(<span class="hljs-params"><span class="hljs-string">'/checkout/{order_id}'</span></span>)</span>
<span class="hljs-keyword">async</span> <span class="hljs-keyword">def</span> <span class="hljs-title function_">checkout</span>(<span class="hljs-params">order_id: <span class="hljs-built_in">str</span>, card_token: <span class="hljs-built_in">str</span></span>) -> <span class="hljs-built_in">dict</span>[<span class="hljs-built_in">str</span>, <span class="hljs-built_in">str</span>]:
    logfire.debug(<span class="hljs-string">'cart loaded for {order_id}'</span>, order_id=order_id)
    <span class="hljs-keyword">with</span> logfire.span(<span class="hljs-string">'charge card'</span>, order_id=order_id, card_token=card_token):
        logfire.info(<span class="hljs-string">'charged {order_id}'</span>, order_id=order_id)
    <span class="hljs-keyword">return</span> {<span class="hljs-string">'status'</span>: <span class="hljs-string">'ok'</span>}
</code></pre>
<p><code>fleet=True</code> needs Logfire 5.5.0 or later with the <code>fleet</code> extra. Setting <code>LOGFIRE_FLEET=true</code> does the same without a code change. Without a Fleet endpoint, <code>configure()</code> warns and the app runs unmanaged, so you can deploy the code before the Fleet settings.</p>
<pre><code class="hljs language-bash">uv venv
<span class="hljs-built_in">source</span> .venv/bin/activate
uv pip install --upgrade <span class="hljs-string">'logfire[fleet,fastapi]'</span> fastapi uvicorn
</code></pre>
</section><section id="connect-the-app-to-fleet-section"><h2 id="connect-the-app-to-fleet" role="presentation"><a href="#connect-the-app-to-fleet" class="heading-anchor"><button type="button" class="heading-anchor__btn">#</button></a><span role="heading" aria-level="2">Connect the app to Fleet</span></h2>
<p>In <strong>Fleet management</strong>, open <strong>SDKs</strong> and select <strong>Add application</strong>. Name it <code>checkout-api</code>, choose <strong>Python with Logfire</strong>, and select <strong>Get setup instructions</strong>.</p>
<p>Logfire shows a <strong>Fleet connection key</strong> once. Put it in your secret manager. Then set the variables the setup shows and start the app:</p>
<pre><code class="hljs language-bash"><span class="hljs-built_in">export</span> OTEL_SERVICE_NAME=checkout-api
<span class="hljs-built_in">export</span> OTEL_OPAMP_ENDPOINT=...   <span class="hljs-comment"># from the setup</span>
<span class="hljs-built_in">export</span> OTEL_OPAMP_HEADERS=...    <span class="hljs-comment"># Authorization with your connection key</span>
uvicorn app:app
</code></pre>
<p>The app logs <code>OpAMP: connected to ...; this SDK is managed as checkout-api</code> when it reaches Fleet. Select <strong>Check connection</strong> in the setup, and the service shows as connected with its policy applied.</p>
<p><img src="https://pydantic.dev/assets/blog/fleet-hands-on/connected.webp" alt="The last step of the application setup: Application connected, policy applied on 1 instance" decoding="async"></p>
<p>The connection key only manages settings. Your app keeps sending telemetry with its existing write token.</p>
<p>Other languages connect the same way, with one change at start:</p>
<ul>
<li><strong>Python, plain OpenTelemetry:</strong> <code>uv pip install logfire-fleet-otel</code>, then run under <code>opentelemetry-instrument</code>.</li>
<li><strong>Node.js 22+, Logfire SDK:</strong> <code>npm install @pydantic/logfire-node @pydantic/logfire-fleet-otel</code>, then pass <code>fleet: true</code> to <code>logfire.configure()</code> (0.22.0 or later).</li>
<li><strong>Node.js 22+, plain OpenTelemetry:</strong> <code>npm install @pydantic/logfire-fleet-otel</code>, then start with <code>node --import @pydantic/logfire-fleet-otel/register app.js</code>.</li>
<li><strong>Java 17+:</strong> add the Fleet extension to the OpenTelemetry Java agent with <code>-Dotel.javaagent.extensions=logfire-fleet-javaagent-extension.jar</code>.</li>
<li><strong>.NET 8+:</strong> add the <code>Logfire.Fleet.AutoInstrumentation</code> plugin to OpenTelemetry automatic instrumentation.</li>
<li><strong>Go 1.25+:</strong> call <code>opampotel.Setup(ctx)</code> in <code>main</code>, in place of your SDK setup.</li>
</ul>
<p>The <a href="https://pydantic.dev/docs/logfire/observe/fleet/applications/">applications guide</a> has the full commands for each.</p>
</section><section id="change-1-stop-the-debug-flood-section"><h2 id="change-1-stop-the-debug-flood" role="presentation"><a href="#change-1-stop-the-debug-flood" class="heading-anchor"><button type="button" class="heading-anchor__btn">#</button></a><span role="heading" aria-level="2">Change 1: stop the debug flood</span></h2>
<p>Open <code>checkout-api</code>'s SDK policy from the <strong>SDKs</strong> tab. Each section says <strong>Set by policy</strong> or <strong>Application controlled</strong>. Everything starts as Application controlled: a policy only changes what you tell it to.</p>
<p>Under <strong>Volume controls</strong>, set <strong>Minimum log level</strong> to <strong>Warn</strong>. Select <strong>Review policy</strong>, check the change, and publish.</p>
<p><img src="https://pydantic.dev/assets/blog/fleet-hands-on/warn-level.webp" alt="The Volume controls section of the SDK policy, set by policy, with Minimum log level set to Warn" loading="lazy" decoding="async"></p>
<p>Within seconds the debug and info logs stop arriving in the <a href="https://pydantic.dev/docs/logfire/observe/live/">Live view</a>. The process didn't restart. Its own log level didn't change either: Fleet drops the records at export, so a later policy can bring them back.</p>
<p>The application's page in Fleet lists each setting with what the policy asks for and what the instances are running.</p>
<p><img src="https://pydantic.dev/assets/blog/fleet-hands-on/log-level-applied.webp" alt="checkout-api in Fleet: three instances connected, the SDK policy applied on all three, and Log levels set to Warn and above by the policy and running" loading="lazy" decoding="async"></p>
</section><section id="change-2-redact-the-token-section"><h2 id="change-2-redact-the-token" role="presentation"><a href="#change-2-redact-the-token" class="heading-anchor"><button type="button" class="heading-anchor__btn">#</button></a><span role="heading" aria-level="2">Change 2: redact the token</span></h2>
<p>Under <strong>Attribute redaction</strong>, add <code>*token*</code> to the attributes to mask, and publish. The SDK replaces each matching attribute's value with <code>[REDACTED]</code> before the span is exported, so it never reaches Logfire or any other backend the SDK sends to. <strong>Scrubbing</strong> goes further and matches values as well as keys, using the same patterns the Logfire SDK scrubs by default.</p>
<p><img src="https://pydantic.dev/assets/blog/fleet-hands-on/redaction.webp" alt="The Attribute redaction section of the SDK policy, set by policy, masking attributes that match token" loading="lazy" decoding="async"></p>
</section><section id="change-3-sample-a-tenth-of-the-traffic-section"><h2 id="change-3-sample-a-tenth-of-the-traffic" role="presentation"><a href="#change-3-sample-a-tenth-of-the-traffic" class="heading-anchor"><button type="button" class="heading-anchor__btn">#</button></a><span role="heading" aria-level="2">Change 3: sample a tenth of the traffic</span></h2>
<p>Under <strong>Trace sampling</strong>, set the rate to 10%. Under <strong>Sampling rules</strong>, add a rule that drops <code>/health*</code> entirely; the first rule a new trace's root span matches decides its rate, before the overall rate applies. A span whose parent was sampled is still sampled, so traces stay whole.</p>
<p>Publish. Traces you don't sample never reach Logfire, so the review step is worth reading.</p>
</section><section id="try-it-on-two-instances-first-section"><h2 id="try-it-on-two-instances-first" role="presentation"><a href="#try-it-on-two-instances-first" class="heading-anchor"><button type="button" class="heading-anchor__btn">#</button></a><span role="heading" aria-level="2">Try it on two instances first</span></h2>
<p>That last change is the kind you'd rather try small. Rollouts are in early access now. Where you have them, select <strong>Settings</strong> in Fleet management and turn on <strong>Use rollouts</strong>. Now publishing a version sends it to nobody until you start a rollout:</p>
<ol>
<li>Publish the policy, then select <strong>Roll out policy</strong>.</li>
<li>Choose how many instances join the pilot, say two, and start it.</li>
<li>Watch <strong>Policies › Rollouts</strong>: it counts the instances that applied the version and any that failed.</li>
</ol>
<p>A pilot doesn't grow on its own. When the two instances look right, start another rollout with more. If they don't, open the previous version from the policy's history, select <strong>Restore into editor</strong>, and publish it.</p>
<p><img src="https://pydantic.dev/assets/blog/fleet-hands-on/rollout.webp" alt="Rollouts in Fleet: a Collector pilot with 1 of 2 applied, another with 1 of 4 applied and 1 failed, and a completed SDK rollout with 42 of 42 applied" loading="lazy" decoding="async"></p>
</section><section id="add-the-hosts-collector-section"><h2 id="add-the-hosts-collector" role="presentation"><a href="#add-the-hosts-collector" class="heading-anchor"><button type="button" class="heading-anchor__btn">#</button></a><span role="heading" aria-level="2">Add the host's Collector</span></h2>
<p><code>checkout-api</code> runs on a Linux VM, and you want that VM's metrics and its nginx logs too. In <strong>Collectors</strong>, select <strong>Add Collector</strong>, then <strong>Host</strong>. Under <strong>What to collect</strong>, pick host monitoring, then <strong>Get install command</strong>.</p>
<p>Copy the <strong>enrollment key</strong> (Logfire shows it once) and run the command on the host. For a project in the US region:</p>
<pre><code class="hljs language-bash">uvx --from <span class="hljs-string">'logfire-cli>=0.1.19'</span> logfire-cli --beta --region us --org &#x3C;your-org> collector install \
  --project &#x3C;your-project> --token-stdin --<span class="hljs-built_in">yes</span>
</code></pre>
<p><code>--token-stdin</code> asks for the key without echoing it, so it stays out of your shell history. The installer asks for administrator access and sets up an OpenTelemetry Collector as a service. The host doesn't sign in to Logfire: the key places it in your project. The setup shows when its first data arrives. The host's metrics then show in the Hosts view, which <a href="https://pydantic.dev/articles/logfire-hosts-view">The OOM that was not your agent</a> introduces.</p>
<p>To add the nginx logs, open the host's Collector policy, add <code>/var/log/nginx/*.log</code> to the file logs, and select <strong>Review version</strong>. If a Collector on the policy lacks a component the new version uses, the review says which. Publish, and the Collector picks it up. A Collector that can't run a version refuses it and keeps its current configuration, and Fleet shows <strong>Failed</strong> with the reason.</p>
</section><section id="kubernetes-and-the-collectors-you-already-run-section"><h2 id="kubernetes-and-the-collectors-you-already-run" role="presentation"><a href="#kubernetes-and-the-collectors-you-already-run" class="heading-anchor"><button type="button" class="heading-anchor__btn">#</button></a><span role="heading" aria-level="2">Kubernetes, and the Collectors you already run</span></h2>
<p>For a cluster, <strong>Add Collector › Kubernetes</strong> installs one small bridge that drives the <a href="https://github.com/open-telemetry/opentelemetry-operator">OpenTelemetry Operator</a>. Fleet's policy describes the cluster's Collectors, and the bridge creates, updates and deletes the <code>OpenTelemetryCollector</code> resources to match. The setup walks you through four steps, from checking your <code>kubectl</code> context to <code>kubectl apply -f fleet-bridge.yaml</code>.</p>
<p>If Helm or GitOps already manages your Collectors, or you set one up by hand as in <a href="https://pydantic.dev/articles/logfire-opentelemetry-collector">Observability with Logfire and OpenTelemetry Collector</a>, keep it that way. Select <strong>Add Collector › Existing Collector</strong> to get a connection key and a snippet for the <code>opamp</code> extension in Collector Contrib. Each Collector then shows in Fleet with its health, components and the configuration it runs, marked <strong>Report only</strong>. Fleet doesn't change that configuration. See <a href="https://pydantic.dev/docs/logfire/observe/fleet/existing-collectors/">Connect an existing Collector</a>.</p>
</section><section id="see-what-a-policy-changed-section"><h2 id="see-what-a-policy-changed" role="presentation"><a href="#see-what-a-policy-changed" class="heading-anchor"><button type="button" class="heading-anchor__btn">#</button></a><span role="heading" aria-level="2">See what a policy changed</span></h2>
<p><strong>Overview</strong> compares how much your Collectors sent with the period before, by Collector and by policy, so you can see what a Collector policy change did to volume. <strong>Flows</strong> draws where each Collector receives data and where it sends it.</p>
<p><img src="https://pydantic.dev/assets/blog/fleet-hands-on/traffic.webp" alt="Fleet Overview: metric data points, log records and spans sent over the last day against the period before, with the top Collectors and policies" loading="lazy" decoding="async"></p>
</section><section id="when-it-doesnt-connect-section"><h2 id="when-it-doesnt-connect" role="presentation"><a href="#when-it-doesnt-connect" class="heading-anchor"><button type="button" class="heading-anchor__btn">#</button></a><span role="heading" aria-level="2">When it doesn't connect</span></h2>
<div class="overflow-x-auto table-wrapper" tabindex="0"><table>
<thead>
<tr>
<th>What you see</th>
<th>What to check</th>
</tr>
</thead>
<tbody>
<tr>
<td>The app never connects</td>
<td>The Fleet package loads before your app starts, and <code>OTEL_OPAMP_ENDPOINT</code> and <code>OTEL_OPAMP_HEADERS</code> are set. The app's logs name connection and authentication errors.</td>
</tr>
<tr>
<td><strong>Policy status</strong> shows <strong>Failed</strong></td>
<td>Open the app or Collector in Fleet. It names the setting or component it couldn't apply.</td>
</tr>
<tr>
<td>No telemetry arrives</td>
<td>Fleet doesn't carry telemetry. Check the write token and region.</td>
</tr>
</tbody>
</table></div>
</section><section id="getting-started-section"><h2 id="getting-started" role="presentation"><a href="#getting-started" class="heading-anchor"><button type="button" class="heading-anchor__btn">#</button></a><span role="heading" aria-level="2">Getting started</span></h2>
<ul>
<li><a href="https://pydantic.dev/docs/logfire/observe/fleet/applications/">Manage applications</a>, with the commands for every language.</li>
<li><a href="https://pydantic.dev/docs/logfire/observe/fleet/collectors/">Manage Collectors</a>, for hosts and Kubernetes.</li>
<li><a href="https://pydantic.dev/docs/logfire/observe/fleet/policies/">Change policies</a>, for rollouts and version history.</li>
<li>The language guides in <a href="https://github.com/pydantic/opamp-clients">pydantic/opamp-clients</a>, with framework and deployment examples.</li>
</ul>
<p>Next: how we check the OpAMP clients behind Fleet, ours and upstream, in <a href="https://pydantic.dev/articles/fleet-opamp-core">What we found testing OpAMP clients against the spec</a>.</p></section>]]></content:encoded>
</item>
<item>
<title>The best Python agent harnesses in 2026</title>
<link>https://pydantic.dev/articles/best-python-agent-harnesses</link>
<guid isPermaLink="true">https://pydantic.dev/articles/best-python-agent-harnesses</guid>
<pubDate>Mon, 09 Nov 2026 09:00:00 GMT</pubDate>
<dc:creator>Douwe Maan</dc:creator>
<category>Pydantic AI</category>
<description>A practical comparison of the Python agent harnesses you can build on: which models each runs, where its agent works, how much of it you can take apart, how runs survive a restart, and when each one is the right pick.</description>
<content:encoded><![CDATA[<!-- cspell:ignore LangGraph LangChain LangChain's LangSmith checkpointer checkpointers unsandboxed Dapr barebones OpenHands Strands Hermes smolagents Mastra Daytona Sprites boxd smolvm BoxLite Bubblewrap Blaxel Runloop AgentCore OpenShell Apptainer Zechner dcode deepagents deepagentsjs -->
<p>Every agent that does real work ends up with the same parts around the model: a place to read and write files, a shell, a plan it keeps current, sub-agents to hand work to, a way to keep the context window useful in hour three, rules about what it may do without asking, and a way to pick up where it left off after a restart. The field calls that the harness. In 2026 you rarely write one from scratch. You pick a harness SDK and build on it, and that choice decides which models you can run, where your agent's commands execute, and how much of its behavior is yours to change.</p>
<p><strong>TL;DR.</strong> <a href="https://pydantic.dev/docs/ai/harness/">Pydantic AI Harness</a> is our pick overall: 80+ capabilities across Pydantic AI and the Harness, from file and shell tools, planning, memory, skills and sub-agents to context management, guardrails and twelve sandboxes and remote workspaces, that you add to any <a href="https://pydantic.dev/docs/ai/">Pydantic AI</a> agent one at a time, on 30+ model providers, with runs that survive a crash on nine durable execution engines. Its complete agents, <code>Coder</code> and <code>Researcher</code>, are those same capabilities combined, so you can start from a working coding agent and take it apart. Choose <strong>LangChain Deep Agents</strong> if your agents already run on LangGraph and LangSmith. The <strong>Claude Agent SDK</strong> if the agent you want is Claude Code itself, on Claude models. The <strong>OpenAI Agents SDK</strong> if OpenAI is your model provider and tracing platform, and the <strong>Codex SDK</strong> if the agent you want is Codex. The <strong>OpenHands Software Agent SDK</strong> if you are building a software engineering agent and want an agent server, sandboxes and a long benchmark record with it. The <strong>Strands harness</strong> if you build on AWS and Bedrock. <strong>Microsoft Agent Framework's Harness</strong> if you need the same harness in .NET or Go.</p>
<p><em>Last updated: November 9, 2026. Capabilities, counts and licenses were read from each project's own docs and repository on October 30, 2026; the Pydantic AI Harness and OpenHands Index figures were re-read on November 9.</em></p>
<section id="what-to-look-for-in-an-agent-harness-section"><h2 id="what-to-look-for-in-an-agent-harness" role="presentation"><a href="#what-to-look-for-in-an-agent-harness" class="heading-anchor"><button type="button" class="heading-anchor__btn">#</button></a><span role="heading" aria-level="2">What to look for in an agent harness</span></h2>
<p>Two kinds of thing get called a harness. A harness product is someone else's agent (its loop, prompts, tools and permissions) that you configure: Claude Code and Codex are prominent examples. A harness SDK gives you the same pieces as a library you build your own agent from. This post compares harness SDKs you use from Python, including the ones that wrap a harness product, and these are our criteria. They are opinionated.</p>
<ul>
<li><strong>Can you change models without rewriting the agent?</strong> Prices, quality and rate limits move every month, and the best model for a coding agent is not always the best one for a research agent. A harness built around one vendor's models makes every other vendor a second-class path, or no path at all.</li>
<li><strong>How much can you take apart?</strong> A ready-made agent is the fastest start. The question is what you can change when it does not fit: remove a tool, replace the planning step, swap the context strategy, or rewrite the instructions, without forking the harness or fighting defaults you cannot see.</li>
<li><strong>Where do the agent's commands run?</strong> On your machine, in a container, or in a cloud sandbox. Check which sandboxes the harness supports natively and whether the same agent code runs in each.</li>
<li><strong>What may it do without asking?</strong> Look for approval on individual tool calls that survives the process going away, and for limits on the shell and file system that you set, not the model.</li>
<li><strong>What happens when the process dies mid-run?</strong> Long agent runs meet deploys, crashes and rate limits. Resuming a saved conversation is not the same as durable execution, which records each completed model and tool call and, after a restart, replays its result instead of running it again. Check which one the harness offers, and whether it works with an engine your company already runs or only with its own store.</li>
<li><strong>Does it stay coherent on long runs?</strong> Compaction, clearing old tool results, spilling oversized output to files, and loading tools and skills on demand are the difference between an agent that degrades after an hour and one that does not.</li>
<li><strong>Do traces go where your other traces go?</strong> OpenTelemetry to any backend, or a vendor's own tracing product.</li>
<li><strong>Can you buy support for the harness itself?</strong> Once an agent is in production you want an escalation path beyond a public issue tracker. Check whether a support agreement covers the open-source SDK, or only a hosted platform or cloud you would also have to adopt.</li>
</ul>
</section><section id="how-we-compared-section"><h2 id="how-we-compared" role="presentation"><a href="#how-we-compared" class="heading-anchor"><button type="button" class="heading-anchor__btn">#</button></a><span role="heading" aria-level="2">How we compared</span></h2>
<p>For each harness we read its documentation, opened its license file and checked its latest release on the date above. We recorded which models it runs natively, what its ready-made agent contains and how much of that you can remove or replace, which sandboxes it supports, how a person approves an action, how a run survives a restart, how it manages context on long runs, what tracing it emits, who makes it under which license, and what you have to buy to get commercial support for it. Where we could count something, we did, using the project's own docs. Where a project's docs mark something experimental, preview or beta, we say so. Every entry, ours included, gets a catch.</p>
<p>"Agent harness SDK" here means a library you import from Python that ships the batteries around the loop (file and shell tools, planning, sub-agents, context management and somewhere for the agent to work) plus a ready-made agent assembled from them. They come in several shapes, named in the table's "Kind" column: from libraries of parts with agents built from them, through assembled harnesses on top of a framework, to SDKs that embed a finished agent such as Claude Code or Codex. We include the last because it is how many teams start, and judge it against the same criteria. A plain agent framework, the loop and tools without those batteries, is the subject of our companion post, <a href="https://pydantic.dev/articles/best-python-ai-agent-frameworks">The best Python AI agent frameworks in 2026</a>. Finished agents you run rather than build on are covered briefly <a href="https://pydantic.dev/articles/best-python-agent-harnesses#finished-agents-and-smaller-libraries">further down</a>. After Pydantic AI Harness, the order is not a score. "Native" means built into the harness or an officially maintained package, not reached through a generic adapter such as LiteLLM. "None documented" means we found nothing in the project's own docs on that date, not that it cannot be built.</p>
<p>Harnesses change every month, so this post does too. We re-check it against each project's own docs and releases every month, and the "Last updated" date above changes whenever anything in it does. If you maintain one of these projects and something here is wrong or out of date, email <a href="mailto:hello@pydantic.dev">hello@pydantic.dev</a> and we will fix it.</p>
</section><section id="the-best-python-agent-harnesses-in-2026-section"><h2 id="the-best-python-agent-harnesses-in-2026" role="presentation"><a href="#the-best-python-agent-harnesses-in-2026" class="heading-anchor"><button type="button" class="heading-anchor__btn">#</button></a><span role="heading" aria-level="2">The best Python agent harnesses in 2026</span></h2>
<section id="1-pydantic-ai-harness-best-python-agent-harness-overall-section"><h3 id="1-pydantic-ai-harness-best-python-agent-harness-overall" role="presentation"><a href="#1-pydantic-ai-harness-best-python-agent-harness-overall" class="heading-anchor"><button type="button" class="heading-anchor__btn">#</button></a><span role="heading" aria-level="3">1. Pydantic AI Harness: best Python agent harness overall</span></h3>
<p>Pydantic AI Harness (that's us) is the open-source capability library for Pydantic AI, from the team behind Pydantic. Everything in it is one primitive: a capability, a self-contained unit of agent behavior you add to <code>capabilities=[...]</code> on any Pydantic AI agent. The <a href="https://pydantic.dev/docs/ai/harness/#capabilities">Harness docs</a> list 80+ of them across Pydantic AI and the Harness package, and the complete agents are capabilities too. <a href="https://pydantic.dev/docs/ai/harness/coder/"><code>Coder</code></a> is file tools, a persistent shell, repository instructions, delegation to a fresh run of itself and context controls, combined; <a href="https://pydantic.dev/docs/ai/harness/researcher/"><code>Researcher</code></a> is web search, page fetching, a sub-researcher and bounded tool output.</p>
<p>Here is <code>Coder</code> fixing a failing test in the current directory, traced with Pydantic Logfire. Install it with <code>pip install "pydantic-ai-harness[coder,anthropic,logfire]"</code>, set <code>ANTHROPIC_API_KEY</code>, and run <code>logfire auth</code> once, or drop the two <code>logfire</code> lines:</p>
<pre><code class="hljs language-python"><span class="hljs-keyword">import</span> logfire
<span class="hljs-keyword">from</span> pydantic_ai <span class="hljs-keyword">import</span> Agent
<span class="hljs-keyword">from</span> pydantic_ai.capabilities <span class="hljs-keyword">import</span> LocalWorkspace
<span class="hljs-keyword">from</span> pydantic_ai_harness <span class="hljs-keyword">import</span> Coder

logfire.configure()
logfire.instrument_pydantic_ai()

agent = Agent(
    <span class="hljs-string">'anthropic:claude-fable-5-1'</span>,
    capabilities=[LocalWorkspace(<span class="hljs-string">'.'</span>), Coder()],
)
result = agent.run_sync(<span class="hljs-string">'Find out why tests/test_parser.py fails and fix the bug it caught.'</span>)
<span class="hljs-built_in">print</span>(result.output)
</code></pre>
<p>Change the model string to run the same agent on another provider. To run its commands in a cloud sandbox instead, install the <code>modal</code> extra as well (<code>pip install "pydantic-ai-harness[coder,modal,anthropic,logfire]"</code>) and swap the workspace. The sandbox starts empty, with <code>git</code> but none of your dependencies, so the prompt has to bring the repository in:</p>
<pre><code class="hljs language-python"><span class="hljs-keyword">from</span> pydantic_ai <span class="hljs-keyword">import</span> Agent
<span class="hljs-keyword">from</span> pydantic_ai_harness <span class="hljs-keyword">import</span> Coder
<span class="hljs-keyword">from</span> pydantic_ai_harness.modal_sandbox <span class="hljs-keyword">import</span> ModalSandbox

agent = Agent(<span class="hljs-string">'anthropic:claude-fable-5-1'</span>, capabilities=[ModalSandbox(), Coder()])
result = agent.run_sync(
    <span class="hljs-string">'Clone https://github.com/you/your-repo, install it, then find out why tests/test_parser.py fails and fix the bug it caught.'</span>
)
</code></pre>
<p>When <code>Coder</code> stops fitting, rebuild it from <a href="https://pydantic.dev/docs/ai/harness/coder/">its parts</a> and change the one you need: an allowlist on the shell, a different compaction strategy, no delegation.</p>
<p>Why it is first: measured against the criteria above, it is the only harness here that answers all of them in the open-source library. Each of the others misses at least one, by its own docs. The Claude Agent SDK runs one vendor's models, and the OpenAI Agents SDK treats other vendors' as beta. Deep Agents keeps durability in LangGraph's checkpointers and sells support with LangSmith. OpenHands and Strands document no external durable execution engine, Microsoft's Harness documents only its own Durable Extension, and Strands and Microsoft document no commercial support for their SDKs. What answering all of them looks like in practice:</p>
<ul>
<li><strong><a href="https://pydantic.dev/docs/ai/models/overview/">30+ model providers</a>, natively</strong>, from OpenAI, Anthropic and Gemini to Bedrock, Vertex AI, Azure, Mistral, Groq, xAI, Ollama and OpenRouter, plus any OpenAI-compatible endpoint, with fallback to another model when a request fails.</li>
<li><strong>Parts you can take out one at a time.</strong> Each capability works on its own and composes with the rest and with your own: <a href="https://pydantic.dev/docs/ai/harness/filesystem/">file system</a> and <a href="https://pydantic.dev/docs/ai/harness/shell/">shell</a> tools with allowlists and denylists, <a href="https://pydantic.dev/docs/ai/harness/planning/">planning</a>, <a href="https://pydantic.dev/docs/ai/harness/subagents/">sub-agents</a>, <a href="https://pydantic.dev/docs/ai/harness/memory/">memory</a> across sessions, <a href="https://pydantic.dev/docs/ai/harness/skills/">skills</a> loaded on demand, web search and browsers, and integrations such as GitHub, Linear and Slack.</li>
<li><strong>A local directory plus twelve <a href="https://pydantic.dev/docs/ai/harness/#execution-environments">sandboxes and remote workspaces</a></strong>: Modal, E2B, Render, Sprites, Daytona, boxd, smolvm, BoxLite, OpenSandbox, Docker, Bubblewrap and SSH. The same file and shell tools work in whichever one the run has.</li>
<li><strong>Context management for long runs</strong>: model-agnostic <a href="https://pydantic.dev/docs/ai/harness/compaction/">compaction strategies</a> (tool-result clearing, sliding windows, summarization), provider-native compaction on OpenAI and Anthropic, oversized tool output spilled to a file the agent can query, tool search, and <a href="https://pydantic.dev/docs/ai/harness/code-mode/">Code Mode</a>, where the model calls many tools from one script in a sandboxed interpreter.</li>
<li><strong>Control over what it does</strong>: <a href="https://pydantic.dev/docs/ai/tools-toolsets/deferred-tools/">tool approval</a> that ends the run with the pending call so a later run in any process resumes it, an <a href="https://pydantic.dev/docs/ai/harness/approval-reviewer/">approval reviewer</a> that lets a second model approve low-risk calls and leaves the rest to a person, a <a href="https://pydantic.dev/docs/ai/harness/tool-call-judge/">tool call judge</a>, <a href="https://pydantic.dev/docs/ai/harness/guardrails/">guardrails</a> with secret masking, and spend limits.</li>
<li><strong>Nine <a href="https://pydantic.dev/docs/ai/capabilities/durable_execution/overview/">durable execution</a> engines</strong>: Temporal, DBOS, Prefect, Restate, AWS Lambda, Absurd, pgtask, Azure Durable Task and Apache Airflow, plus <a href="https://pydantic.dev/docs/ai/harness/step-persistence/">step persistence</a> to resume or fork a run from files, SQLite, MongoDB or PostgreSQL.</li>
<li><strong>OpenTelemetry</strong> spans for every model and tool call, following the GenAI semantic conventions, to any backend. <a href="https://pydantic.dev/logfire">Pydantic Logfire</a> is the easiest way to see them, and optional.</li>
</ul>
<p>The same agent runs in a terminal chat, a web chat, editors through the Agent Client Protocol (experimental), and frontends through AG-UI and the Vercel AI protocol. Pydantic offers <a href="https://pydantic.dev/docs/ai/overview/enterprise-support/">enterprise support</a> for Pydantic AI and the Harness, from the team that builds them, with an SLA and no platform to buy. Both are MIT licensed.</p>
<p>The catch: it is Python only, and it is a library, not a product. There is no hosted runtime and no management UI; agents run in your process on your infrastructure, and durability comes from an engine you choose and operate. <code>Coder</code> in a <code>LocalWorkspace</code> runs shell commands on your machine without an allowlist, so production use belongs in a sandbox or behind the approval and shell controls above. More parts also means more choices: <code>Coder</code>'s defaults are ours, but once you rebuild it, testing your combination in your workspace is your job.</p>
<p>Best for Python teams that want a working agent today and expect to change its parts, its model and where it runs as their product grows.</p>
</section><section id="2-langchain-deep-agents-if-your-agents-already-run-on-langgraph-and-langsmith-section"><h3 id="2-langchain-deep-agents-if-your-agents-already-run-on-langgraph-and-langsmith" role="presentation"><a href="#2-langchain-deep-agents-if-your-agents-already-run-on-langgraph-and-langsmith" class="heading-anchor"><button type="button" class="heading-anchor__btn">#</button></a><span role="heading" aria-level="3">2. LangChain Deep Agents: if your agents already run on LangGraph and LangSmith</span></h3>
<p><a href="https://docs.langchain.com/oss/python/deepagents/overview">Deep Agents</a> calls itself "the batteries-included agent harness". In LangChain's own layering, LangGraph is the graph runtime, <code>create_agent</code> is a minimal harness on top of it, and Deep Agents is a more opinionated harness on top of <code>create_agent</code>. It is <a href="https://github.com/langchain-ai/deepagents">MIT licensed</a>, from LangChain, Inc., and also exists for JavaScript.</p>
<p>The default agent has file tools (<code>ls</code>, <code>read_file</code>, <code>write_file</code>, <code>edit_file</code>, <code>glob</code>, <code>grep</code>), a <code>task</code> tool for sub-agents, summarization of long threads and offloading of large tool results. Memory, skills and human approval are opt-in, and since version 0.7 so is the <code>write_todos</code> planning tool. You change it through middleware: an override replaces the default instance, and any LangGraph graph can be a sub-agent. It runs on any LangChain chat model. Commands run in a <a href="https://docs.langchain.com/oss/python/deepagents/sandboxes">sandbox backend</a>: LangSmith Sandbox, AWS AgentCore, Databricks, Daytona, E2B, Modal, NVIDIA OpenShell, Runloop or Vercel. LangChain also ships Deep Agents Code (<code>dcode</code>), a terminal coding agent built on it, and in February <a href="https://www.langchain.com/blog/improving-deep-agents-with-harness-engineering">reported</a> a Terminal-Bench 2.0 score of 66.5 for its earlier CLI on <code>gpt-5.2-codex</code>.</p>
<p>The catch: it brings the LangChain stack with it. The package depends on <code>langsmith</code>, <code>langchain-anthropic</code> and <code>langchain-google-genai</code>. <a href="https://docs.langchain.com/oss/python/deepagents/human-in-the-loop">Human approval</a> requires a LangGraph checkpointer, durability is LangGraph's own checkpointers with no external durable execution engine documented, and tracing is LangSmith's, with <a href="https://docs.langchain.com/langsmith/trace-with-opentelemetry">OpenTelemetry through the LangSmith SDK</a>. Its README describes a "trust the LLM" security model, and its local backends give no isolation. The API moves quickly: 0.7.0 removed the default planning tool and default prompts.</p>
<p>Pick it when your agents, checkpoints and traces already live in LangGraph and LangSmith, and you want a harness from the same vendor.</p>
</section><section id="3-claude-agent-sdk-if-the-agent-you-want-is-claude-code-on-claude-section"><h3 id="3-claude-agent-sdk-if-the-agent-you-want-is-claude-code-on-claude" role="presentation"><a href="#3-claude-agent-sdk-if-the-agent-you-want-is-claude-code-on-claude" class="heading-anchor"><button type="button" class="heading-anchor__btn">#</button></a><span role="heading" aria-level="3">3. Claude Agent SDK: if the agent you want is Claude Code, on Claude</span></h3>
<p>The <a href="https://code.claude.com/docs/en/agent-sdk/overview">Claude Agent SDK</a> gives you "the same tools, agent loop, and context management that power Claude Code", in Python or TypeScript. It runs a bundled Claude Code binary as a subprocess, so file editing, shell commands, web search, sub-agents, skills, automatic compaction, permission modes and sessions arrive already wired. The Python package is <a href="https://github.com/anthropics/claude-agent-sdk-python/blob/main/LICENSE">MIT licensed</a>, and use of the SDK is governed by Anthropic's Commercial Terms of Service.</p>
<p>You can <a href="https://code.claude.com/docs/en/agent-sdk/permissions">remove built-in tools</a> and replace the system prompt. <a href="https://code.claude.com/docs/en/agent-sdk/user-input">Permission callbacks</a> approve, deny or modify each tool call, and a <a href="https://code.claude.com/docs/en/agent-sdk/hooks">hook can defer</a> a call so you resume it later. Your own tools arrive as in-process MCP servers.</p>
<p>The catch: Claude models only, through <a href="https://code.claude.com/docs/en/agent-sdk/quickstart">Anthropic, Bedrock, Vertex AI or Microsoft Foundry</a>. Its <a href="https://code.claude.com/docs/en/agent-sdk/hosting">hosting docs</a> describe every running agent as "a long-lived process tied to local state", suggest 1 GiB of RAM per agent as a floor, and say sessions do not survive a container restart unless you mirror transcripts to a <code>SessionStore</code>, which is best-effort. With a custom system prompt, Claude Code's own reminders still reach the model until you <a href="https://code.claude.com/docs/en/agent-sdk/modifying-system-prompts">turn each one off</a>. Its built-in sandbox is off by default, and when it is enabled but cannot start, commands run unsandboxed with a warning. OpenTelemetry tracing is opt-in and marked beta, and no durable execution engine integration is documented. Aditya's post <a href="https://pydantic.dev/articles/pydantic-ai-vs-claude-agent-sdk">Would you deploy an agent you don't control?</a> makes the longer argument.</p>
<p>Pick it when the product you want is Claude Code itself, embedded, and a single model vendor is acceptable.</p>
</section><section id="4-openai-agents-sdk-if-you-are-all-in-on-openai-section"><h3 id="4-openai-agents-sdk-if-you-are-all-in-on-openai" role="presentation"><a href="#4-openai-agents-sdk-if-you-are-all-in-on-openai" class="heading-anchor"><button type="button" class="heading-anchor__btn">#</button></a><span role="heading" aria-level="3">4. OpenAI Agents SDK: if you are all-in on OpenAI</span></h3>
<p>OpenAI <a href="https://openai.com/index/the-next-evolution-of-the-agents-sdk/">described</a> its April update to the <a href="https://openai.github.io/openai-agents-python/">OpenAI Agents SDK</a> as a "model-native harness". Alongside agents, handoffs and guardrails, <a href="https://openai.github.io/openai-agents-python/sandbox/guide/">sandbox agents</a> now work in a container with shell and file tools, skills, memory and compaction. <a href="https://openai.github.io/openai-agents-python/sandbox/clients/">Sandbox clients</a> cover a local Unix sandbox, Docker, Blaxel, Cloudflare, Daytona, E2B, Modal and Vercel. Tools take <a href="https://openai.github.io/openai-agents-python/human_in_the_loop/"><code>needs_approval</code></a>, and the paused run's state serializes to JSON so you can resume it later. Its docs list <a href="https://openai.github.io/openai-agents-python/running_agents/">four durable execution integrations</a>: Temporal, DBOS, Restate and Dapr. It is <a href="https://github.com/openai/openai-agents-python">MIT licensed</a> and also exists for TypeScript.</p>
<p>The catch: its default path is OpenAI's Responses API, and <a href="https://openai.github.io/openai-agents-python/models/">other providers</a> go through LiteLLM and Any-LLM adapters its docs call "best-effort, beta", which lose Responses-only features. <a href="https://openai.github.io/openai-agents-python/tracing/">Tracing</a> is on by default, goes to OpenAI, and is unavailable to organizations under Zero Data Retention.
Right for teams whose model provider and tracing platform are both OpenAI.</p>
</section><section id="5-codex-sdk-if-the-agent-you-want-is-codex-section"><h3 id="5-codex-sdk-if-the-agent-you-want-is-codex" role="presentation"><a href="#5-codex-sdk-if-the-agent-you-want-is-codex" class="heading-anchor"><button type="button" class="heading-anchor__btn">#</button></a><span role="heading" aria-level="3">5. Codex SDK: if the agent you want is Codex</span></h3>
<p>The <a href="https://learn.chatgpt.com/docs/codex-sdk">Codex SDK</a> has a stable Python package, <code>openai-codex</code>, that "controls the local Codex app-server over JSON-RPC", and a TypeScript package that wraps the <code>codex</code> CLI. You get Codex's own agent, with its tools, read-only, workspace-write or full-access sandbox presets, base and developer instructions you set, and local threads you can resume and fork. It is <a href="https://github.com/openai/codex/blob/main/LICENSE">Apache 2.0 licensed</a>.</p>
<p>The catch: it wraps a Codex process, so you configure that agent rather than recompose it. Its docs are written around OpenAI's models; other providers are a Codex configuration matter. Its Python approval setting has two values: deny everything, or let an automatic reviewer decide. Commercial support for the SDK: none documented.</p>
<p>Use it when the product you want is Codex itself, embedded.</p>
</section><section id="6-openhands-software-agent-sdk-if-you-are-building-a-software-engineering-agent-section"><h3 id="6-openhands-software-agent-sdk-if-you-are-building-a-software-engineering-agent" role="presentation"><a href="#6-openhands-software-agent-sdk-if-you-are-building-a-software-engineering-agent" class="heading-anchor"><button type="button" class="heading-anchor__btn">#</button></a><span role="heading" aria-level="3">6. OpenHands Software Agent SDK: if you are building a software engineering agent</span></h3>
<p>The <a href="https://docs.openhands.dev/sdk">OpenHands Software Agent SDK</a> provides "Python, TypeScript, and REST APIs for building agents that work with code", and is the engine behind the OpenHands CLI and OpenHands Cloud. It needs Python 3.12 or later and is <a href="https://github.com/OpenHands/software-agent-sdk/blob/main/LICENSE">MIT licensed</a>. It is a separate project from the <a href="https://github.com/OpenHands/OpenHands"><code>OpenHands/OpenHands</code></a> repository, which is now Agent Canvas, a TypeScript control center that runs OpenHands, Claude Code, Codex and other agents over ACP; the <a href="https://pypi.org/project/openhands-ai/"><code>openhands-ai</code></a> Python package from that repository had its last release, 1.11.0, in July 2026.</p>
<p>An agent is built from <a href="https://docs.openhands.dev/sdk/arch/overview">swappable components</a>: terminal, file editor, task tracker and <a href="https://docs.openhands.dev/sdk/guides/agent-browser-use.md">browser</a> tools, sub-agents, a <a href="https://docs.openhands.dev/sdk/guides/context-condenser.md">context condenser</a>, skills, MCP and hooks. The same agent code runs in a local workspace or, through its agent server, in Docker, Apptainer, an API-based sandbox or OpenHands Cloud. <a href="https://docs.openhands.dev/sdk/guides/security.md">Confirmation policies</a> ask before every action, never, or only for actions a security analyzer rates risky. Conversations <a href="https://docs.openhands.dev/sdk/guides/convo-persistence.md">persist to disk</a> and resume, and <a href="https://docs.openhands.dev/sdk/guides/observability.md">traces</a> are OpenTelemetry to any OTLP backend.</p>
<p>Its benchmark record is long. OpenHands has submitted to the official <a href="https://www.swebench.com/">SWE-bench Verified</a> leaderboard since October 2024, and its newest entry there marked as checked by the SWE-bench team is 71.8, with GPT-5, from August 2025. OpenHands also runs its own <a href="https://index.openhands.dev/">OpenHands Index</a> across five benchmarks, including SWE-bench and GAIA, and posts each run's results and trajectories; its newest entry, from June 11, 2026, averages 81.0 with Claude Fable 5. The Index numbers are OpenHands' own runs.</p>
<p>The catch: it is built for agents that work with code. Models come through <a href="https://docs.openhands.dev/sdk/guides/llm-registry.md">LiteLLM</a> model strings rather than native provider clients. Isolation means running its separate agent server in a container or remote sandbox; the local workspace acts on the host. Its default security analyzer has the acting model label the risk of its own actions, so the risky-only policy depends on the agent's own judgment. Persistence is a directory of events, with no external durable execution engine documented. The paid offerings are hosting: OpenHands Cloud, and <a href="https://openhands.dev/enterprise">OpenHands Enterprise</a>, which adds self-hosting and guidance from its engineers, as a platform.</p>
<p>Pick it when your product is a coding agent and you want an agent server, its sandboxes and a long benchmark record with it.</p>
</section><section id="7-strands-harness-if-you-build-on-aws-and-bedrock-section"><h3 id="7-strands-harness-if-you-build-on-aws-and-bedrock" role="presentation"><a href="#7-strands-harness-if-you-build-on-aws-and-bedrock" class="heading-anchor"><button type="button" class="heading-anchor__btn">#</button></a><span role="heading" aria-level="3">7. Strands harness: if you build on AWS and Bedrock</span></h3>
<p>AWS's Strands Agents now ships <a href="https://strandsagents.com/docs/user-guide/harness/">Strands harness</a>, "a fully assembled agent harness", on top of its SDK, in Python and TypeScript. One <code>create_harness()</code> call gives you shell, read, write and edit tools, web fetch and search, a built-in sub-agent, a todo list, skills, file-based memory, sessions you resume by id, and context management. It is <a href="https://github.com/strands-agents/harness-sdk">Apache 2.0 licensed</a>.</p>
<p>The <a href="https://strandsagents.com/docs/user-guide/harness/reference/configuration/">configuration reference</a> documents every default you can override, and <a href="https://strandsagents.com/docs/user-guide/harness/configure/interventions/index.md">interventions</a> gate tool calls behind human approval, a natural-language rule or a Cedar policy. Models come from Bedrock, Anthropic, OpenAI, Google and Ollama, and the SDK emits OpenTelemetry traces.</p>
<p>The catch: Amazon Bedrock is the default provider, and the harness package is new, first published in September 2026. Its sandboxes are Docker, SSH and Strands Shell, an in-process shell sandbox, and no durable execution engine integration is documented. Commercial support for the SDK: none documented.</p>
<p>Suited to teams whose models, credentials and deployment are already on AWS and want an assembled harness from the same place.</p>
</section><section id="8-microsoft-agent-framework-harness-if-you-need-the-same-harness-in-net-or-go-section"><h3 id="8-microsoft-agent-framework-harness-if-you-need-the-same-harness-in-net-or-go" role="presentation"><a href="#8-microsoft-agent-framework-harness-if-you-need-the-same-harness-in-net-or-go" class="heading-anchor"><button type="button" class="heading-anchor__btn">#</button></a><span role="heading" aria-level="3">8. Microsoft Agent Framework Harness: if you need the same harness in .NET or Go</span></h3>
<p>Microsoft Agent Framework <a href="https://learn.microsoft.com/en-us/agent-framework/concepts/harness">provides</a> "an opinionated, batteries-included Harness for research, coding, data analysis, and other long-running work", in .NET, Python and Go. In Python, <code>create_harness_agent</code> returns an ordinary Agent Framework agent with todo tracking, plan and execute modes, session file memory, tool approval rules, web search where the model supports it, and OpenTelemetry, all on by default. Compaction, skills, file access, background sub-agents, shell and bounded looping are opt-in. The framework is <a href="https://github.com/microsoft/agent-framework">MIT licensed</a>.</p>
<p>Each default has a switch to disable it, and you can replace the todo and mode providers or add your own context providers. For durability, Microsoft's <a href="https://learn.microsoft.com/en-us/agent-framework/integrations/durable-extension">Durable Extension</a> runs agents on the Durable Task Scheduler, on Azure Functions or your own compute.</p>
<p>The catch: in Python, background agents, file access and looping are marked experimental, shell tooling comes from a pre-release package, and the Durable Extension installs as a pre-release. Sandboxes for the agent's commands: none documented on the Harness page. Commercial support for the framework: none documented.</p>
<p>The choice for teams that need one harness across Python, .NET and Go.</p>
</section></section><section id="comparison-at-a-glance-section"><h2 id="comparison-at-a-glance" role="presentation"><a href="#comparison-at-a-glance" class="heading-anchor"><button type="button" class="heading-anchor__btn">#</button></a><span role="heading" aria-level="2">Comparison at a glance</span></h2>
<p>Checked October 30, 2026, with the Pydantic AI Harness row re-checked November 9, 2026. Counts are what each project's own docs list natively; "via" means through an adapter or a separate integration; "none documented" means its docs describe none.</p>
<div class="overflow-x-auto table-wrapper" tabindex="0"><table>
<thead>
<tr>
<th>Harness</th>
<th>Kind</th>
<th>Models</th>
<th>Taking it apart</th>
<th>Where commands run</th>
<th>Durability and resume</th>
<th>Tracing</th>
<th>Commercial support</th>
<th>License and maker</th>
</tr>
</thead>
<tbody>
<tr>
<td>Pydantic AI Harness</td>
<td>Capability library; <code>Coder</code> and <code>Researcher</code> built from it</td>
<td>30+ providers, plus any OpenAI-compatible endpoint</td>
<td>Each of 80+ capabilities works alone, including the parts of <code>Coder</code></td>
<td>Local, plus 12 sandboxes and remote workspaces</td>
<td>Replay on 9 durable engines; step persistence to files, SQLite, MongoDB, PostgreSQL</td>
<td>OpenTelemetry (GenAI conventions) to any backend</td>
<td>For Pydantic AI and the Harness, from Pydantic; no platform plan needed</td>
<td>MIT; Pydantic</td>
</tr>
<tr>
<td>LangChain Deep Agents</td>
<td>Opinionated harness on LangGraph; Deep Agents Code</td>
<td>Any LangChain chat model</td>
<td>Middleware overrides; any LangGraph graph as a sub-agent</td>
<td>Local backends, plus 9 sandbox integrations</td>
<td>LangGraph checkpointers; no external engine documented</td>
<td>LangSmith; OTel via the LangSmith SDK</td>
<td>With a LangSmith Enterprise plan</td>
<td>MIT; LangChain, Inc.</td>
</tr>
<tr>
<td>Claude Agent SDK</td>
<td>Embedded finished agent (Claude Code)</td>
<td>Claude only, on 4 platforms</td>
<td>Remove tools, replace the system prompt, hooks</td>
<td>Local subprocess; own sandbox off by default</td>
<td>Sessions on disk, or a best-effort <code>SessionStore</code>; no engine documented</td>
<td>OpenTelemetry, opt-in (beta)</td>
<td>None documented</td>
<td>MIT, under Anthropic's Commercial Terms; Anthropic</td>
</tr>
<tr>
<td>OpenAI Agents SDK</td>
<td>Framework with sandbox agents</td>
<td>OpenAI; others via beta LiteLLM and Any-LLM adapters</td>
<td>Capabilities on sandbox agents</td>
<td>Local Unix, Docker, plus 6 hosted sandboxes</td>
<td>Serialized run state; 4 engines: Temporal, DBOS, Restate, Dapr</td>
<td>OpenAI tracing on by default; third-party processors</td>
<td>None documented for the SDK</td>
<td>MIT; OpenAI</td>
</tr>
<tr>
<td>Codex SDK</td>
<td>Embedded finished agent (Codex)</td>
<td>OpenAI-oriented; others through Codex configuration</td>
<td>Instructions, sandbox and approval settings</td>
<td>Codex sandbox presets</td>
<td>Local threads you resume and fork; no engine documented</td>
<td>OpenTelemetry log export, opt-in, through Codex configuration</td>
<td>None documented</td>
<td>Apache 2.0; OpenAI</td>
</tr>
<tr>
<td>OpenHands SDK</td>
<td>Coding agent SDK (Python, TypeScript, REST) with an agent server</td>
<td>Via LiteLLM</td>
<td>Swappable tools, condenser, workspace</td>
<td>Local, or Docker, Apptainer, API sandboxes and Cloud via its agent server</td>
<td>Conversation persistence to disk; no engine documented</td>
<td>OpenTelemetry to any OTLP backend</td>
<td>With OpenHands Enterprise</td>
<td>MIT; OpenHands</td>
</tr>
<tr>
<td>Strands harness</td>
<td>Assembled harness on the Strands SDK</td>
<td>Bedrock by default; Anthropic, OpenAI, Google, Ollama</td>
<td>Override every default; drop to the SDK</td>
<td>Docker, SSH, Strands Shell</td>
<td>Sessions by id; no engine documented</td>
<td>OpenTelemetry</td>
<td>None documented</td>
<td>Apache 2.0; AWS</td>
</tr>
<tr>
<td>Microsoft Agent Framework Harness</td>
<td>Assembled harness on Agent Framework</td>
<td>Agent Framework chat clients</td>
<td>Disable or replace each default</td>
<td>None documented on the Harness page</td>
<td>Durable Extension on Durable Task (pre-release)</td>
<td>OpenTelemetry</td>
<td>None documented</td>
<td>MIT; Microsoft</td>
</tr>
</tbody>
</table></div>
</section><section id="finished-agents-and-smaller-libraries-section"><h2 id="finished-agents-and-smaller-libraries" role="presentation"><a href="#finished-agents-and-smaller-libraries" class="heading-anchor"><button type="button" class="heading-anchor__btn">#</button></a><span role="heading" aria-level="2">Finished agents and smaller libraries</span></h2>
<p>Five projects come up in harness lists and searches that we left out of the ranking, each for a reason.</p>
<ul>
<li><strong><a href="https://github.com/NousResearch/hermes-agent">Hermes Agent</a></strong> from Nous Research is a finished, self-improving agent with a terminal UI, a messaging gateway, memory, skills and six terminal backends, under the MIT license. You can import its <code>AIAgent</code> from Python, but only from a git checkout: its docs say it publishes no supported wheel. Use it as an agent, not as a library.</li>
<li><strong><a href="https://docs.mistral.ai/vibe/code/overview">Mistral Vibe</a></strong> is Mistral's Python coding agent, a finished CLI under the Apache 2.0 license, with a separate pre-1.0 <a href="https://pypi.org/project/mistralai-vibe-sdk/">SDK</a> for building agents.</li>
<li><strong><a href="https://github.com/deepseek-ai/deepseek-harness/blob/master/python/sdk/README.md">DeepSeek Harness Python SDK</a></strong> is a client, still a developer preview, that drives DeepSeek's TypeScript harness over JSON-RPC, and its shipped profiles <a href="https://github.com/deepseek-ai/deepseek-harness/blob/master/packages/session/session-log-deepseek/README.md">send the session log</a> to DeepSeek's official API by default until a profile patch turns that off.</li>
<li><strong><a href="https://github.com/huggingface/smolagents">smolagents</a></strong> from Hugging Face is "a barebones library for agents that think in code", with code executors on E2B, Modal, Blaxel and Docker. Its docs describe no file or shell tools, compaction, skills or tool approvals, and its last release was in May.</li>
<li><strong><a href="https://github.com/SWE-agent/mini-swe-agent">mini-swe-agent</a></strong> is a minimal coding agent whose only tool is bash, built for research and benchmarks.</li>
</ul>
<p>If what you want is a coding agent to use rather than one to build, Claude Code, Codex, OpenCode and Pi are finished harnesses, and several of the SDKs above are how you embed them.</p>
</section><section id="if-you-work-in-typescript-section"><h2 id="if-you-work-in-typescript" role="presentation"><a href="#if-you-work-in-typescript" class="heading-anchor"><button type="button" class="heading-anchor__btn">#</button></a><span role="heading" aria-level="2">If you work in TypeScript</span></h2>
<p>This list is Python only, and several widely used harnesses are TypeScript-first.</p>
<ul>
<li><strong><a href="https://github.com/earendil-works/pi">Pi</a></strong>, by Mario Zechner, is "a minimal, extensible agent harness that you can make your own", with an agent core package, a coding agent CLI and an SDK, under the MIT license. It leaves out sub-agents and plan mode by design.</li>
<li><strong><a href="https://github.com/deepseek-ai/deepseek-harness">DeepSeek Harness</a></strong> (<code>dsh</code>) is itself a TypeScript harness, with a web UI and a desktop app, and its plugins are TypeScript packages; the Python SDK mentioned above drives it.</li>
<li><strong><a href="https://github.com/langchain-ai/deepagentsjs">Deep Agents JS</a></strong> is the TypeScript version of Deep Agents, MIT licensed.</li>
<li><strong><a href="https://mastra.ai/docs/harness/overview">Mastra</a></strong> uses "harness" for a set of capabilities around its agents (durable agents, background tasks, schedules and <code>AgentController</code>) and has a <code>createCodingAgent()</code> helper.</li>
<li>The <strong>Strands harness</strong>, <strong>OpenAI Agents SDK</strong> and <strong>Codex SDK</strong> also ship TypeScript versions. The TypeScript <strong>Claude Agent SDK</strong> is not open source: its license file reserves all rights under Anthropic's Commercial Terms.</li>
<li>The <strong><a href="https://ai-sdk.dev/docs/ai-sdk-harnesses">Vercel AI SDK</a></strong> has an experimental <code>HarnessAgent</code> that runs other harnesses, such as Claude Code, Codex, Pi and Deep Agents, behind one interface.</li>
</ul>
</section><section id="how-to-choose-section"><h2 id="how-to-choose" role="presentation"><a href="#how-to-choose" class="heading-anchor"><button type="button" class="heading-anchor__btn">#</button></a><span role="heading" aria-level="2">How to choose</span></h2>
<ul>
<li>You are building a Python agent and want a working one now, on any model, with parts you can replace as it grows: <strong>Pydantic AI Harness</strong>.</li>
<li>Your agent's runs must survive a crash, on an engine your company already operates: <strong>Pydantic AI Harness</strong> (nine engines), or the <strong>OpenAI Agents SDK</strong> (four) if you are on OpenAI's models.</li>
<li>Your agents, checkpoints and traces already live in LangGraph and LangSmith: <strong>LangChain Deep Agents</strong>.</li>
<li>You want Claude Code itself inside your product, on Claude models: the <strong>Claude Agent SDK</strong>.</li>
<li>OpenAI is your model provider and tracing platform: the <strong>OpenAI Agents SDK</strong>.</li>
<li>You want Codex itself inside your product: the <strong>Codex SDK</strong>.</li>
<li>Your product is a coding agent and you want an agent server, sandboxes and a long benchmark record: the <strong>OpenHands Software Agent SDK</strong>.</li>
<li>Your models and deployment are on AWS: the <strong>Strands harness</strong>.</li>
<li>You need the same harness across Python, .NET and Go: <strong>Microsoft Agent Framework's Harness</strong>.</li>
</ul>
</section><section id="when-another-harness-is-the-better-pick-section"><h2 id="when-another-harness-is-the-better-pick" role="presentation"><a href="#when-another-harness-is-the-better-pick" class="heading-anchor"><button type="button" class="heading-anchor__btn">#</button></a><span role="heading" aria-level="2">When another harness is the better pick</span></h2>
<p>Three situations favor something else over Pydantic AI Harness.</p>
<p>The first is wanting a specific vendor's agent. If the product you want is Claude Code or Codex, embedded, their own SDKs give you the agent its makers ship and tune. Rebuilding it from parts only pays off if you expect to change it.</p>
<p>The second is a stack you already run. A team with LangGraph agents in production and traces in LangSmith gets Deep Agents on the runtime, checkpointers and tracing it already operates. The same goes for Strands on Bedrock.</p>
<p>The third is a language other than Python. Pi, DeepSeek Harness, Deep Agents JS and Mastra in TypeScript, and Microsoft's Harness in .NET and Go, are where those teams should look.</p>
<p>If your product is not a coding agent, think twice before starting from one. Our earlier posts on <a href="https://pydantic.dev/articles/the-harness-thesis">the harness thesis</a>, <a href="https://pydantic.dev/articles/what-makes-a-good-harness">what makes a good harness</a> and <a href="https://pydantic.dev/articles/harness-week">Harness Week</a> go further into why we build the harness as parts.</p>
</section><section id="frequently-asked-questions-section"><h2 id="frequently-asked-questions" role="presentation"><a href="#frequently-asked-questions" class="heading-anchor"><button type="button" class="heading-anchor__btn">#</button></a><span role="heading" aria-level="2">Frequently asked questions</span></h2>
<p><strong>What is the best Python agent harness?</strong>
Our answer is Pydantic AI Harness: 80+ capabilities across Pydantic AI and the Harness on any of 30+ model providers, twelve sandboxes and remote workspaces, nine durable execution engines and OpenTelemetry tracing, with ready-made agents built from the same parts. The exceptions are teams that want a specific vendor's agent (the Claude Agent SDK or the Codex SDK), teams already on LangGraph and LangSmith (Deep Agents), and teams standardized on AWS or Azure.</p>
<p><strong>Which harness should I use to build my own coding agent in Python?</strong>
Start from <code>Coder</code> in Pydantic AI Harness if you want to choose the model and change the agent's parts; it runs locally or in a sandbox, and you can rebuild it from its capabilities. The OpenHands Software Agent SDK is the pick if you want its agent server and its record of SWE-bench runs, and the Claude Agent SDK if you want Claude Code itself.</p>
<p><strong>Which agent harnesses work with any model?</strong>
Pydantic AI Harness (30+ providers natively), LangChain Deep Agents (any LangChain chat model) and the OpenHands SDK (through LiteLLM). The Strands harness defaults to Bedrock and supports other providers. The Claude Agent SDK runs Claude models only, and the OpenAI Agents SDK reaches other providers through beta adapters.</p>
<p><strong>Is Pydantic AI Harness the same as Pydantic AI?</strong>
No. <a href="https://pydantic.dev/docs/ai/">Pydantic AI</a> is the agent framework: the typed agent loop, models, tools and structured output. Pydantic AI Harness is a separate package of capabilities you add to a Pydantic AI agent, and it installs Pydantic AI with it.</p>
</section><section id="sources-section"><h2 id="sources" role="presentation"><a href="#sources" class="heading-anchor"><button type="button" class="heading-anchor__btn">#</button></a><span role="heading" aria-level="2">Sources</span></h2>
<p>Every source below was checked on October 30, 2026; the Pydantic AI Harness sources and the OpenHands Index were re-checked on November 9, 2026.</p>
<ul>
<li><strong>Pydantic AI Harness</strong>: <a href="https://pydantic.dev/docs/ai/harness/">overview</a>, <a href="https://pydantic.dev/docs/ai/harness/coder/">Coder</a>, <a href="https://pydantic.dev/docs/ai/harness/researcher/">Researcher</a>, <a href="https://pydantic.dev/docs/ai/harness/compaction/">compaction</a>, <a href="https://pydantic.dev/docs/ai/harness/step-persistence/">step persistence</a>, <a href="https://pydantic.dev/docs/ai/core-concepts/workspace/">workspaces</a>, <a href="https://pydantic.dev/docs/ai/capabilities/durable_execution/overview/">durable execution</a> and <a href="https://pydantic.dev/docs/ai/harness/azure-durable-task/">Azure Durable Task</a>, <a href="https://pydantic.dev/docs/ai/models/overview/">models</a>, <a href="https://pydantic.dev/docs/ai/overview/enterprise-support/">enterprise support</a>.</li>
<li><strong>LangChain Deep Agents</strong>: <a href="https://docs.langchain.com/oss/python/deepagents/overview">overview</a>, <a href="https://docs.langchain.com/oss/python/deepagents/customization">customization</a>, <a href="https://docs.langchain.com/oss/python/deepagents/sandboxes">sandboxes</a>, <a href="https://docs.langchain.com/oss/python/deepagents/human-in-the-loop">human-in-the-loop</a>, <a href="https://github.com/langchain-ai/deepagents">repository and changelog</a>, <a href="https://docs.langchain.com/langsmith/trace-with-opentelemetry">OpenTelemetry</a>, <a href="https://www.langchain.com/pricing">pricing</a>.</li>
<li><strong>Claude Agent SDK</strong>: <a href="https://code.claude.com/docs/en/agent-sdk/overview">overview</a>, <a href="https://code.claude.com/docs/en/agent-sdk/quickstart">quickstart</a>, <a href="https://code.claude.com/docs/en/agent-sdk/hosting">hosting</a>, <a href="https://code.claude.com/docs/en/agent-sdk/permissions">permissions</a>, <a href="https://code.claude.com/docs/en/agent-sdk/hooks">hooks</a>, <a href="https://code.claude.com/docs/en/agent-sdk/modifying-system-prompts">system prompts</a>, <a href="https://github.com/anthropics/claude-agent-sdk-python">repository</a>.</li>
<li><strong>OpenAI Agents SDK and Codex SDK</strong>: <a href="https://openai.com/index/the-next-evolution-of-the-agents-sdk/">announcement</a>, <a href="https://openai.github.io/openai-agents-python/sandbox/guide/">sandbox agents</a>, <a href="https://openai.github.io/openai-agents-python/sandbox/clients/">sandbox clients</a>, <a href="https://openai.github.io/openai-agents-python/models/">models</a>, <a href="https://openai.github.io/openai-agents-python/human_in_the_loop/">human-in-the-loop</a>, <a href="https://openai.github.io/openai-agents-python/running_agents/">running agents</a>, <a href="https://openai.github.io/openai-agents-python/tracing/">tracing</a>, <a href="https://learn.chatgpt.com/docs/codex-sdk">Codex SDK</a>, <a href="https://learn.chatgpt.com/docs/config-file/config-advanced">Codex configuration</a>, <a href="https://github.com/openai/codex">Codex repository</a>.</li>
<li><strong>OpenHands Software Agent SDK</strong>: <a href="https://docs.openhands.dev/sdk">docs</a>, <a href="https://docs.openhands.dev/sdk/arch/overview">architecture</a>, <a href="https://docs.openhands.dev/sdk/guides/security.md">security</a>, <a href="https://docs.openhands.dev/sdk/guides/convo-persistence.md">persistence</a>, <a href="https://docs.openhands.dev/sdk/guides/observability.md">observability</a>, <a href="https://docs.openhands.dev/sdk/guides/llm-registry.md">models</a>, <a href="https://github.com/OpenHands/software-agent-sdk">repository</a>, <a href="https://github.com/OpenHands/OpenHands">Agent Canvas</a>, <a href="https://pypi.org/project/openhands-ai/"><code>openhands-ai</code> on PyPI</a>, <a href="https://index.openhands.dev/">OpenHands Index</a>, <a href="https://www.swebench.com/">SWE-bench leaderboards</a>, <a href="https://openhands.dev/enterprise">enterprise</a>.</li>
<li><strong>Strands harness</strong>: <a href="https://strandsagents.com/docs/user-guide/harness/">harness guide</a>, <a href="https://strandsagents.com/docs/user-guide/harness/reference/configuration/">configuration</a>, <a href="https://strandsagents.com/docs/user-guide/harness/configure/interventions/index.md">interventions</a>, <a href="https://github.com/strands-agents/harness-sdk">repository</a>.</li>
<li><strong>Microsoft Agent Framework Harness</strong>: <a href="https://learn.microsoft.com/en-us/agent-framework/concepts/harness">Harness</a>, <a href="https://learn.microsoft.com/en-us/agent-framework/integrations/durable-extension">Durable Extension</a>, <a href="https://github.com/microsoft/agent-framework">repository</a>.</li>
<li><strong>Also covered</strong>: <a href="https://github.com/NousResearch/hermes-agent">Hermes Agent</a>, <a href="https://docs.mistral.ai/vibe/code/overview">Mistral Vibe</a>, <a href="https://github.com/mistralai/mistral-vibe">Vibe CLI repository</a>, <a href="https://pypi.org/project/mistralai-vibe-sdk/">Vibe SDK on PyPI</a>, <a href="https://github.com/deepseek-ai/deepseek-harness">DeepSeek Harness</a>, <a href="https://github.com/deepseek-ai/deepseek-harness/blob/master/python/sdk/README.md">DeepSeek Python SDK reference</a>, <a href="https://github.com/deepseek-ai/deepseek-harness/blob/master/packages/session/session-log-deepseek/README.md">DeepSeek session-log upload</a>, <a href="https://github.com/huggingface/smolagents">smolagents</a>, <a href="https://github.com/SWE-agent/mini-swe-agent">mini-swe-agent</a>, <a href="https://github.com/earendil-works/pi">Pi</a>, <a href="https://github.com/langchain-ai/deepagentsjs">Deep Agents JS</a>, <a href="https://mastra.ai/docs/harness/overview">Mastra</a>, <a href="https://ai-sdk.dev/docs/ai-sdk-harnesses">Vercel AI SDK harnesses</a>.</li>
</ul>
</section><section id="try-pydantic-ai-harness-section"><h2 id="try-pydantic-ai-harness" role="presentation"><a href="#try-pydantic-ai-harness" class="heading-anchor"><button type="button" class="heading-anchor__btn">#</button></a><span role="heading" aria-level="2">Try Pydantic AI Harness</span></h2>
<p><code>pip install "pydantic-ai-harness[coder,anthropic]"</code> (or the extra for your model provider), then follow the <a href="https://pydantic.dev/docs/ai/harness/">Harness docs</a> from <code>Coder</code> on your own repository to an agent built from the capabilities you choose. Choosing the framework underneath instead? Our companion post, <a href="https://pydantic.dev/articles/best-python-ai-agent-frameworks">The best Python AI agent frameworks in 2026</a>, compares those.</p></section>]]></content:encoded>
</item>
<item>
<title>Manage your telemetry in Logfire, send it anywhere</title>
<link>https://pydantic.dev/articles/fleet-management-launch</link>
<guid isPermaLink="true">https://pydantic.dev/articles/fleet-management-launch</guid>
<pubDate>Mon, 09 Nov 2026 09:00:00 GMT</pubDate>
<dc:creator>Bill Easton</dc:creator>
<category>Pydantic Logfire</category>
<category>OpenTelemetry</category>
<category>New Features</category>
<category>Announcements</category>
<description>Fleet in Pydantic Logfire changes what your OpenTelemetry Collectors and application SDKs collect, and where they send it, from one place. No config files to edit on each machine, and no redeploys.</description>
<content:encoded><![CDATA[<p>Today we're shipping <strong>Fleet Management</strong> in <a href="https://pydantic.dev/logfire">Pydantic Logfire</a>: change what your OpenTelemetry Collectors and application SDKs collect, and where they send it, from Logfire. No config files to edit on each machine. Adjust sampling, redact newly discovered sensitive data, and do it without redeploying the app. Fleet is in Beta and on for every plan.</p>
<section id="why-fleet-management-section"><h2 id="why-fleet-management" role="presentation"><a href="#why-fleet-management" class="heading-anchor"><button type="button" class="heading-anchor__btn">#</button></a><span role="heading" aria-level="2">Why Fleet management?</span></h2>
<p>It's 2am and <code>checkout-api</code> is on fire. Someone shipped it with debug logging on, so every request writes forty log lines. One span attribute carries a card token it shouldn't. The same data goes to Logfire and to the second backend your platform team runs. Turning any of that off means a pull request, a CI run and a deploy. Forty minutes, if CI is kind. Keeping it on means thousands of dollars per hour in additional cost. The card tokens that went out in the meantime are already in two places.</p>
<p>Your Collectors have the same problem, one layer down. Their settings live in a YAML file on every host, and changing one means an Ansible run or a Helm upgrade across all of them.</p>
<p>Open the service's SDK policy in Logfire, set <strong>Minimum log level</strong> to <strong>Warn</strong>, add the token's attribute to <strong>Attribute redaction</strong>, and publish.</p>
<p><img src="https://pydantic.dev/assets/blog/fleet-management-launch/warn-level.webp" alt="Changing an SDK policy in Fleet: Minimum log level is set to Warn, the review shows Log levels going from Application controlled to Warn and above, the policy is published, and checkout-api then shows Warn and above as both the policy and the running setting" decoding="async"></p>
<p>Within seconds the running processes stop sending info and debug logs, and the token is removed before the span leaves the process. Nothing restarted. When the incident is over, set the log level back to <strong>Application controlled</strong> and publish again.</p>
</section><section id="how-it-works-section"><h2 id="how-it-works" role="presentation"><a href="#how-it-works" class="heading-anchor"><button type="button" class="heading-anchor__btn">#</button></a><span role="heading" aria-level="2">How it works</span></h2>
<p><img src="https://pydantic.dev/assets/blog/fleet-management-launch/how-it-works.webp" alt="Diagram from Fleet&#x27;s How Fleet works guide: Logfire Fleet sends the policies you publish to Collectors on hosts, Collectors in a Kubernetes cluster, and application SDKs" loading="lazy" decoding="async"></p>
<p>Each Collector and each application takes its settings from a <strong>policy</strong>: a versioned set of settings you edit and publish in Logfire. Fleet Management is the set of capabilities in Pydantic Logfire for doing this: an OpAMP server built into Logfire that Collectors and SDKs connect to, and the UI where you see them and edit and publish policies. Clients connect to Fleet over <a href="https://opentelemetry.io/docs/specs/opamp/">OpAMP</a>, the OpenTelemetry standard for managing telemetry software remotely. They report their health and the settings they're running, and connected clients pick up a new version within seconds of you publishing it. With rollouts on, it waits until you start a pilot group.</p>
<p>Fleet carries settings, not telemetry. Your applications keep sending data with the write token they already have, and your Collectors keep sending wherever their pipeline says.</p>
</section><section id="manage-in-logfire-send-anywhere-section"><h2 id="manage-in-logfire-send-anywhere" role="presentation"><a href="#manage-in-logfire-send-anywhere" class="heading-anchor"><button type="button" class="heading-anchor__btn">#</button></a><span role="heading" aria-level="2">Manage in Logfire, send anywhere</span></h2>
<p>A Collector policy holds the Collector's whole pipeline, exporters included. If it sends to Logfire and to another backend, you manage both from Fleet.</p>
<p>The same goes for applications. In Python, Node.js, Java and .NET, the SDK policy governs every exporter the SDK exports through, not only the one pointed at Logfire: the console exporter, a second OTLP exporter for another vendor, an exporter a plugin added. So redaction, sampling and volume controls hold for every destination, and one sampling decision per span holds across all of them. An exporter the application wires up outside the SDK is outside the policy too.</p>
</section><section id="what-you-can-manage-section"><h2 id="what-you-can-manage" role="presentation"><a href="#what-you-can-manage" class="heading-anchor"><button type="button" class="heading-anchor__btn">#</button></a><span role="heading" aria-level="2">What you can manage</span></h2>
<ul>
<li><strong>Collectors on hosts.</strong> One command installs an OpenTelemetry Collector as a service on Linux, macOS or Windows and joins it to your project. Pick a starting point (host monitoring, file logs) and Fleet creates the policy.</li>
<li><strong>Kubernetes clusters.</strong> A small bridge in the cluster drives the <a href="https://github.com/open-telemetry/opentelemetry-operator">OpenTelemetry Operator</a>. Your Collectors stay standard <code>OpenTelemetryCollector</code> resources.</li>
<li><strong>Collectors you already run.</strong> <strong>Add Collector › Existing Collector</strong> gives you a connection key and a snippet for the <code>opamp</code> extension in Collector Contrib. A Collector managed by Helm or GitOps then shows in Fleet with its health, components and configuration, marked <strong>Report only</strong>. Its configuration stays yours.</li>
<li><strong>Applications.</strong> Python, Node.js, Java, .NET and Go, on the Logfire SDK or a plain OpenTelemetry SDK. On the Logfire SDK it's one option: <code>logfire.configure(fleet=True)</code> in Python (Logfire 5.5.0, Python 3.11+) and <code>logfire.configure({ fleet: true })</code> in Node.js (0.22.0). A policy can set trace sampling, sampling rules, minimum log level, which signals to export, volume controls, attribute redaction and scrubbing. Everything it doesn't set stays the way the application configured it.</li>
</ul>
<p>One page shows all of it: every Collector and application, whether it's connected, its health, the policy it runs and whether that policy applied. <strong>Flows</strong> draws where your Collectors receive data and where they send it, and <strong>Overview</strong> compares how much each one sent with the period before.</p>
<p><img src="https://pydantic.dev/assets/blog/fleet-management-launch/collectors.webp" alt="The Collectors tab in Fleet management, listing host Collectors with their connection, health, policy status and policy version" loading="lazy" decoding="async"></p>
</section><section id="changing-a-thousand-machines-should-be-boring-section"><h2 id="changing-a-thousand-machines-should-be-boring" role="presentation"><a href="#changing-a-thousand-machines-should-be-boring" class="heading-anchor"><button type="button" class="heading-anchor__btn">#</button></a><span role="heading" aria-level="2">Changing a thousand machines should be boring</span></h2>
<p>A tool that can change every process you run had better make that safe.</p>
<ul>
<li><strong>Every policy is versioned.</strong> Review shows the change against the published version before you publish, and warns when a Collector lacks a component the new version uses.</li>
<li><strong>A host Collector or application that can't run a version refuses it</strong> and keeps the configuration it has. Fleet shows it as <strong>Failed</strong> and names the setting or component. Kubernetes Collectors don't check first, so test a change on a pilot group there.</li>
<li><strong>Roll out to a few first.</strong> Turn on rollouts (in early access now) and a new version goes to a pilot group you choose. It doesn't expand on its own: widen it when the results look right.</li>
<li><strong>Roll back.</strong> Open any past version and restore it into the editor.</li>
</ul>
</section><section id="built-on-opentelemetry-section"><h2 id="built-on-opentelemetry" role="presentation"><a href="#built-on-opentelemetry" class="heading-anchor"><button type="button" class="heading-anchor__btn">#</button></a><span role="heading" aria-level="2">Built on OpenTelemetry</span></h2>
<p>Fleet speaks OpAMP, manages standard Collectors through the standard Operator, and connects to SDKs through small packages that sit inside the OpenTelemetry SDK you already run. Our OpAMP clients share one protocol core, written in Rust and run in every language, and they run in the same conformance suite as the upstream OpenTelemetry clients. <a href="https://pydantic.dev/articles/fleet-opamp-core">What we found testing OpAMP clients against the spec</a> covers how we built and checked that core.</p>
</section><section id="getting-started-section"><h2 id="getting-started" role="presentation"><a href="#getting-started" class="heading-anchor"><button type="button" class="heading-anchor__btn">#</button></a><span role="heading" aria-level="2">Getting started</span></h2>
<p>Open <strong>Fleet management</strong> in your project's sidebar. It's on for every plan.</p>
<ul>
<li><strong>Read the docs.</strong> <a href="https://pydantic.dev/docs/logfire/observe/fleet/">Fleet overview</a>, <a href="https://pydantic.dev/docs/logfire/observe/fleet/collectors/">Manage Collectors</a>, <a href="https://pydantic.dev/docs/logfire/observe/fleet/applications/">Manage applications</a> and <a href="https://pydantic.dev/docs/logfire/observe/fleet/policies/">Change policies</a>.</li>
<li><strong>See it working.</strong> <a href="https://pydantic.dev/articles/fleet-hands-on">Turn down OpenTelemetry noise without a redeploy</a> connects an application and a host, then changes both.</li>
<li><strong>See how it's checked.</strong> <a href="https://pydantic.dev/articles/fleet-opamp-core">What we found testing OpAMP clients against the spec</a> lists the bugs our tests found in the upstream OpAMP clients.</li>
<li><strong>See the product page.</strong> <a href="https://pydantic.dev/logfire/fleet-management">Fleet management</a>.</li>
</ul>
<p>Your plan sets how many applications and Collector policies Fleet manages, and Fleet shows your usage as you go.</p>
<p>Try it on one service this week. If something's missing, tell us on <a href="https://github.com/pydantic/logfire/issues">GitHub</a> or through <a href="https://pydantic.dev/contact">contact</a>.</p></section>]]></content:encoded>
</item>
<item>
<title>Pydantic AI is now a supported agent in AgentEnv Framework</title>
<link>https://pydantic.dev/articles/agentenv-pydantic-ai</link>
<guid isPermaLink="true">https://pydantic.dev/articles/agentenv-pydantic-ai</guid>
<pubDate>Fri, 06 Nov 2026 09:00:00 GMT</pubDate>
<dc:creator>Laís Carvalho</dc:creator>
<category>Pydantic AI</category>
<category>Integrations</category>
<category>Open Source</category>
<description>Scale AI&apos;s AgentEnv Framework now ships Pydantic AI as a supported agent. Deploy it into an environment, give it a task, and grade what it does.</description>
<content:encoded><![CDATA[<p><img src="https://pydantic.dev/assets/blog/agentenv-pydantic-ai/agentenv-pydantic.webp" alt="AgentEnv Framework and Pydantic logos" decoding="async"></p>
<p>Testing an agent against a toy prompt tells you very little. Testing it against an inbox full of email, a help desk with real tickets, and a clock that moves tells you a lot more. That is what <a href="https://www.agentenvframework.com/?utm_source=pydantic&#x26;utm_medium=partnership&#x26;utm_campaign=agentenv-pydantic-ai">AgentEnv Framework</a> is for, and as of today <a href="https://pydantic.dev/pydantic-ai">Pydantic AI</a> ships as one of its supported agents.</p>
<section id="what-agentenv-framework-is-section"><h2 id="what-agentenv-framework-is" role="presentation"><a href="#what-agentenv-framework-is" class="heading-anchor"><button type="button" class="heading-anchor__btn">#</button></a><span role="heading" aria-level="2">What AgentEnv Framework is</span></h2>
<p>AgentEnv Framework is Scale AI's open source framework for building environments where agents practice on realistic apps, data, and multi-step tasks. An environment is a composable world: email, Slack, a help desk, with seed data. A task is a graph of steps that deploys an environment, deploys an agent, prompts it, and verifies the outcome. Tasks pin their versions, so a rerun reproduces the original. Environments expose their tools over MCP, and agents connect over A2A.</p>
<p>One environment can host many tasks and many agents, which makes it a good place to compare agents on equal footing.</p>
</section><section id="pydantic-ai-inside-agentenv-section"><h2 id="pydantic-ai-inside-agentenv" role="presentation"><a href="#pydantic-ai-inside-agentenv" class="heading-anchor"><button type="button" class="heading-anchor__btn">#</button></a><span role="heading" aria-level="2">Pydantic AI inside AgentEnv</span></h2>
<p>The <code>pydantic-ai</code> agent runs Pydantic AI in process, not behind a wrapped CLI. Each task is one run of an <code>Agent</code> with the <code>Coder</code> capability from <a href="https://pydantic.dev/docs/ai/harness/">Pydantic AI Harness</a>, the same coding tools CLAI is built on: <code>shell</code>, <code>read_file</code>, <code>write_file</code>, <code>edit_file</code>, <code>list_files</code>, <code>grep</code>, and <code>delegate_task</code>. Shell commands see <code>PATH</code>, <code>HOME</code>, and the locale, never the model key.</p>
<p>It talks to any OpenAI-compatible endpoint. A <code>vllm:</code> prefix on the model name picks Pydantic AI's vLLM provider, which shapes requests for the model's family (Qwen, DeepSeek, GLM, Llama, and others) the way a vLLM server expects. Each context maps to one conversation, kept on the agent's own disk, so follow-up tasks in that context continue it while the agent is up. Moving it to a new instance goes through the snapshot flow, which saves and restores the conversation and, when asked, the workspace. MCP servers, skills, peer agents, and live trajectories all come through the standard A2A extensions.</p>
<p>If you already run Pydantic AI in production, this is the same agent, now in a sandbox you can grade. The Harness is the <a href="https://pydantic.dev/articles/harness-week">capability library behind Pydantic AI agents</a>, the same one that recently picked up <a href="https://pydantic.dev/articles/youdotcom-pydantic-ai-harness">You.com web search and research</a>.</p>
</section><section id="try-it-section"><h2 id="try-it" role="presentation"><a href="#try-it" class="heading-anchor"><button type="button" class="heading-anchor__btn">#</button></a><span role="heading" aria-level="2">Try it</span></h2>
<p>Install the framework and check that it runs:</p>
<pre><code class="hljs language-bash">uv tool install agentenv-framework
agent-env run hello
</code></pre>
<p>Nothing is configured by default, so give it a model endpoint and make Pydantic AI the default agent for every task step that does not name one. The endpoint can be anything that speaks the OpenAI chat completions API. This example uses the <a href="https://pydantic.dev/ai-gateway">Logfire Gateway</a> instead. Turn on telemetry under Gateway, Settings, Telemetry and pick a project, and every model call the agent makes with a Gateway API key shows up as a span in <a href="https://pydantic.dev/logfire">Pydantic Logfire</a> with no change to the agent. In the URL, <code>openai</code> is the provider route and <code>us</code> is the Gateway region. The Gateway's Connect page generates this base URL for your organization, so copy it from there: an EU organization gets <code>gateway-eu.pydantic.dev</code>. Keep it as is, with no <code>/v1</code> suffix, because the agent appends <code>/chat/completions</code> itself:</p>
<pre><code class="hljs language-toml"><span class="hljs-comment"># .agentenv/config.toml</span>
<span class="hljs-section">[model]</span>
<span class="hljs-attr">base_url</span> = <span class="hljs-string">"https://gateway-us.pydantic.dev/proxy/openai"</span>
<span class="hljs-attr">api_key</span>  = <span class="hljs-string">"env:PYDANTIC_AI_GATEWAY_API_KEY"</span>

<span class="hljs-section">[model.roles]</span>
<span class="hljs-attr">agent</span> = <span class="hljs-string">"gpt-5.5"</span>

<span class="hljs-section">[agents]</span>
<span class="hljs-attr">default_a2a_agent_id</span> = <span class="hljs-string">"pydantic-ai"</span>
</code></pre>
<p>Export <code>PYDANTIC_AI_GATEWAY_API_KEY</code> before you run anything. <code>env:</code> reads it at run time. Other endpoints are covered in the <a href="https://www.agentenvframework.com/docs/model-providers?utm_source=pydantic&#x26;utm_medium=partnership&#x26;utm_campaign=agentenv-pydantic-ai">model provider docs</a>.</p>
<p>The framework ships a small example bundle, <a href="https://github.com/scaleapi/agentenv-framework/tree/main/src/agent_env/examples/mail-mcp"><code>mail-mcp</code></a>: an MCP server with a fixed inbox of three emails, one of them an invoice, and a verifier that checks the invoice can be found. Its task only deploys the environment and runs the verifier. Copy the bundle, then put Pydantic AI in the loop by adding two steps to <code>tasks/smoke.json</code>:</p>
<pre><code class="hljs language-json"><span class="hljs-punctuation">[</span>
  <span class="hljs-punctuation">{</span><span class="hljs-attr">"id"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"env"</span><span class="hljs-punctuation">,</span> <span class="hljs-attr">"type"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"deploy_env"</span><span class="hljs-punctuation">,</span> <span class="hljs-attr">"env_id"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"mail"</span><span class="hljs-punctuation">}</span><span class="hljs-punctuation">,</span>
  <span class="hljs-punctuation">{</span><span class="hljs-attr">"id"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"assistant"</span><span class="hljs-punctuation">,</span> <span class="hljs-attr">"type"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"deploy_agent"</span><span class="hljs-punctuation">,</span> <span class="hljs-attr">"env_ids"</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">[</span><span class="hljs-string">"mail"</span><span class="hljs-punctuation">]</span><span class="hljs-punctuation">,</span> <span class="hljs-attr">"a2a_agent_id"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"pydantic-ai"</span><span class="hljs-punctuation">,</span> <span class="hljs-attr">"agent_name"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"assistant"</span><span class="hljs-punctuation">,</span> <span class="hljs-attr">"depends_on"</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">[</span><span class="hljs-punctuation">{</span><span class="hljs-attr">"task_step_id"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"env"</span><span class="hljs-punctuation">}</span><span class="hljs-punctuation">]</span><span class="hljs-punctuation">}</span><span class="hljs-punctuation">,</span>
  <span class="hljs-punctuation">{</span><span class="hljs-attr">"id"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"find-invoice"</span><span class="hljs-punctuation">,</span> <span class="hljs-attr">"type"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"prompt_agent"</span><span class="hljs-punctuation">,</span> <span class="hljs-attr">"agent_name"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"assistant"</span><span class="hljs-punctuation">,</span> <span class="hljs-attr">"prompt_id"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"find-invoice"</span><span class="hljs-punctuation">,</span> <span class="hljs-attr">"prompt"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"Find the invoice in the inbox and tell me who sent it."</span><span class="hljs-punctuation">,</span> <span class="hljs-attr">"depends_on"</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">[</span><span class="hljs-punctuation">{</span><span class="hljs-attr">"task_step_id"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"assistant"</span><span class="hljs-punctuation">}</span><span class="hljs-punctuation">]</span><span class="hljs-punctuation">}</span><span class="hljs-punctuation">,</span>
  <span class="hljs-punctuation">{</span><span class="hljs-attr">"id"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"finds-the-invoice"</span><span class="hljs-punctuation">,</span> <span class="hljs-attr">"type"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"env_outcome_verifier"</span><span class="hljs-punctuation">,</span> <span class="hljs-attr">"env_id"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"mail"</span><span class="hljs-punctuation">,</span> <span class="hljs-attr">"file_artifact_id"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"check_mail"</span><span class="hljs-punctuation">,</span> <span class="hljs-attr">"verifier_id"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"finds-the-invoice"</span><span class="hljs-punctuation">,</span> <span class="hljs-attr">"depends_on"</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">[</span><span class="hljs-punctuation">{</span><span class="hljs-attr">"task_step_id"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"find-invoice"</span><span class="hljs-punctuation">}</span><span class="hljs-punctuation">]</span><span class="hljs-punctuation">}</span>
<span class="hljs-punctuation">]</span>
</code></pre>
<p>Run the copy:</p>
<pre><code class="hljs language-bash">agent-env run ./my-mail
</code></pre>
<p>The agent gets the inbox's <code>search_emails</code> tool over MCP, its reply and full trajectory land in the run's output, the verifier scores the result, and each model request is a span in Logfire. The first run also builds the gateway the environment deploys on, which takes a few minutes.</p>
<p>Want to see how Pydantic AI compares with another agent on the same task? Change <code>a2a_agent_id</code> to <code>claude-code</code> and run it again. Same environment, same prompt, same verifier. Different agent.</p>
</section><section id="why-this-matters-section"><h2 id="why-this-matters" role="presentation"><a href="#why-this-matters" class="heading-anchor"><button type="button" class="heading-anchor__btn">#</button></a><span role="heading" aria-level="2">Why this matters</span></h2>
<p><a href="https://pydantic.dev/articles/focus-on-evals-with-logfire">Evals on fixed datasets</a> catch regressions. They miss the agent that sends the right email to the wrong person because the inbox looked different yesterday. A realistic environment with a reproducible seed catches that, and its verifier says what went wrong. That is the feedback loop we want for Pydantic AI. Every agent framework should have one.</p>
<p>The agent lives in the <a href="https://github.com/scaleapi/agentenv-framework/blob/main/src/agent_env/agents/agents/pydantic-ai/README.md">AgentEnv Framework repo</a>. Docs for all supported agents are <a href="https://www.agentenvframework.com/docs/agents/supported-agents?utm_source=pydantic&#x26;utm_medium=partnership&#x26;utm_campaign=agentenv-pydantic-ai#pydantic-ai">here</a>. Try it, and tell us what breaks.</p></section>]]></content:encoded>
</item>
<item>
<title>The best Python AI agent frameworks in 2026</title>
<link>https://pydantic.dev/articles/best-python-ai-agent-frameworks</link>
<guid isPermaLink="true">https://pydantic.dev/articles/best-python-ai-agent-frameworks</guid>
<pubDate>Mon, 02 Nov 2026 09:00:00 GMT</pubDate>
<dc:creator>Douwe Maan</dc:creator>
<category>Pydantic AI</category>
<description>A practical comparison of nine Python AI agent frameworks, plus the voice-agent frameworks: which models each runs, how runs survive a crash, how agents reach users, and when each one is the right pick.</description>
<content:encoded><![CDATA[<!-- cspell:ignore boxd smolvm Bubblewrap toolkits LangGraph LangGraph's LangChain checkpointers DTMF PSTN LangSmith CrewAI Agno AgentOS Pipecat LiveKit Mastra DBOS Restate Dapr pgtask Absurd ElevenLabs ElevenLabs' ElevenAgents Twilio -->
<p>A support agent works in the demo. Then the real requirements arrive. A refund over a limit needs a person to approve it, and that person answers two days later. A deploy restarts the process halfway through a run. The model provider rate-limits on a Monday morning and the agent should fall back to another one. The product team wants it in the React app, and a month later on the phone. Each of those is a few lines in one framework and a project in another, and the framework you picked in week one decides which.</p>
<p><strong>TL;DR.</strong> <a href="https://pydantic.dev/docs/ai/">Pydantic AI</a> is our pick overall: one typed <code>Agent</code> that runs on 30+ model providers, survives crashes on nine durable execution engines (Temporal, DBOS, Prefect, Restate, AWS Lambda, Absurd, pgtask, Azure Durable Task and Apache Airflow), runs code in ten sandboxes and remote workspaces, uses any MCP server's tools, pauses for human approval, and reaches users through chat frontends, editors and five speech-to-speech providers, with OpenTelemetry tracing to any backend. Choose <strong>LangGraph and LangChain</strong> if your team already runs on them and LangSmith. The <strong>OpenAI Agents SDK</strong> if OpenAI is your model provider and tracing platform. <strong>Google ADK</strong> if you are standardized on Google Cloud and Gemini, or need the same framework in Java or Go. <strong>Microsoft Agent Framework</strong> if you build on Azure and Microsoft Foundry, or need the same framework in .NET. <strong>Strands Agents</strong> if you build on AWS and Amazon Bedrock. <strong>CrewAI</strong> if you would rather declare roles and tasks than write the control flow. The <strong>Claude Agent SDK</strong> if what you want is Claude Code's own loop inside your product, on Claude models. <strong>Agno</strong> if you want a ready-made server and management UI for many agents. For voice, <strong>LiveKit Agents</strong> or <strong>Pipecat</strong> if you want to own the transport and compose the pipeline.</p>
<p><em>Last updated: October 29, 2026. Capabilities, counts and licenses were read from each project's own docs and repository on that date.</em></p>
<section id="what-to-look-for-in-an-agent-framework-section"><h2 id="what-to-look-for-in-an-agent-framework" role="presentation"><a href="#what-to-look-for-in-an-agent-framework" class="heading-anchor"><button type="button" class="heading-anchor__btn">#</button></a><span role="heading" aria-level="2">What to look for in an agent framework</span></h2>
<p>These are our criteria, and they are opinionated.</p>
<ul>
<li><strong>Can you change models without rewriting the agent?</strong> Prices, quality and rate limits move every month. A framework built around one vendor's API makes every other vendor a second-class path, usually through an adapter the docs call beta.</li>
<li><strong>What happens when the process dies mid-run?</strong> Agents that call tools for minutes, or wait days for a person, need durable execution: a journal of completed model and tool calls that a restarted run replays. Check whether the framework works with the engine your company already runs, or only with its own store.</li>
<li><strong>How does a person approve an action?</strong> Look for a pause that survives the process going away, not a callback that blocks a thread.</li>
<li><strong>How does the agent reach users?</strong> A chat frontend, an editor, another agent, a phone call. Check which protocols the framework speaks natively, and whether voice is the same agent or a separate stack.</li>
<li><strong>Do traces go where your other traces go?</strong> OpenTelemetry to any backend, or a vendor's own tracing product.</li>
<li><strong>How much can you take apart?</strong> A ready-made agent is fast to start with. The question is what you can change when it does not fit.</li>
<li><strong>Can you buy support for the framework itself?</strong> Once an agent is in production, you want an escalation path beyond a public issue tracker. Check whether a commercial support agreement covers the open-source framework, or only comes with a hosted platform or cloud plan you would also have to adopt.</li>
</ul>
</section><section id="how-we-compared-section"><h2 id="how-we-compared" role="presentation"><a href="#how-we-compared" class="heading-anchor"><button type="button" class="heading-anchor__btn">#</button></a><span role="heading" aria-level="2">How we compared</span></h2>
<p>For each framework we read its documentation and opened its license file on the date above, and recorded which models it runs natively, how a run survives a crash or a long wait, how a person approves an action, which voice and frontend protocols it supports, whether it speaks the Model Context Protocol (MCP), what tracing it emits, who makes it under which license, and what you have to buy to get commercial support for it. Where we could count something, we did, using the framework's own docs. Where a framework's docs mark something experimental, preview or beta, we say so. Every entry, ours included, gets a catch.</p>
<p>"Agent framework" here means a library for writing the loop around a model: call the model, run the tools it asks for, repeat until done, with the state, context and stopping rules around that. Some frameworks below also sell a hosted platform; we note where one exists, but compare the open-source framework. The set is the frameworks people ask us about most, for each of which we keep a detailed <a href="https://pydantic.dev/docs/ai/comparisons/">comparison page</a> current as the frameworks change; LlamaIndex, smolagents and Haystack are left out because we keep no such page for them. After Pydantic AI, entries are ordered by how often AI search answers name them, not by a score. "Native" means built into the framework or an officially maintained package, not reached through a generic adapter such as LiteLLM. "None documented" means we found nothing in the framework's own docs on that date, not that it cannot be built.</p>
<p>Frameworks change every month, so this post does too. We re-check the comparison against each project's own docs and releases every month, and the "Last updated" date above changes whenever anything in it does. If you maintain one of these frameworks and something here is wrong or out of date, email <a href="mailto:hello@pydantic.dev">hello@pydantic.dev</a> and we will fix it.</p>
</section><section id="the-best-python-ai-agent-frameworks-in-2026-section"><h2 id="the-best-python-ai-agent-frameworks-in-2026" role="presentation"><a href="#the-best-python-ai-agent-frameworks-in-2026" class="heading-anchor"><button type="button" class="heading-anchor__btn">#</button></a><span role="heading" aria-level="2">The best Python AI agent frameworks in 2026</span></h2>
<section id="1-pydantic-ai-best-python-agent-framework-overall-section"><h3 id="1-pydantic-ai-best-python-agent-framework-overall" role="presentation"><a href="#1-pydantic-ai-best-python-agent-framework-overall" class="heading-anchor"><button type="button" class="heading-anchor__btn">#</button></a><span role="heading" aria-level="3">1. Pydantic AI: best Python agent framework overall</span></h3>
<p>Pydantic AI (that's us) is an open-source Python agent framework from the team behind Pydantic. An agent is one typed <code>Agent</code> object: give it an output type and every run returns a validated Pydantic model, give it tools and their arguments are validated before your code runs, and switch providers by changing one string. <a href="https://pydantic.dev/docs/ai/harness/">Pydantic AI Harness</a> adds 80+ ready-made capabilities, from memory, planning and sub-agents to sandboxes and a complete coding agent, so you can build your own agent harness from parts, or start from a finished one such as <a href="https://pydantic.dev/docs/ai/harness/coder/"><code>Coder</code></a> and take it apart.</p>
<pre><code class="hljs language-python"><span class="hljs-keyword">import</span> logfire
<span class="hljs-keyword">from</span> pydantic <span class="hljs-keyword">import</span> BaseModel
<span class="hljs-keyword">from</span> pydantic_ai <span class="hljs-keyword">import</span> Agent

logfire.configure()
logfire.instrument_pydantic_ai()


<span class="hljs-keyword">class</span> <span class="hljs-title class_">City</span>(<span class="hljs-title class_ inherited__">BaseModel</span>):
    name: <span class="hljs-built_in">str</span>
    country: <span class="hljs-built_in">str</span>


agent = Agent(<span class="hljs-string">'anthropic:claude-fable-5-1'</span>, output_type=City)
<span class="hljs-built_in">print</span>(agent.run_sync(<span class="hljs-string">'Where were the 2012 Olympics held?'</span>).output)
<span class="hljs-comment">#> name='London' country='United Kingdom'</span>
</code></pre>
<p>Why it is first: measured against the criteria above, it is the only framework here that answers all of them in the open-source library, without a vendor tie, a beta adapter, or a runtime you have to adopt. The others each answer some of them well. The breadth behind that, in numbers:</p>
<ul>
<li><strong>30+ <a href="https://pydantic.dev/docs/ai/models/overview/">model providers</a></strong>, from OpenAI, Anthropic and Gemini to Bedrock, Vertex AI, Azure, Mistral, Groq, xAI, Ollama, vLLM and OpenRouter, each selected by a <code>provider:model</code> string, plus any OpenAI-compatible endpoint, and fallback to another model when a provider fails.</li>
<li><strong>Nine <a href="https://pydantic.dev/docs/ai/capabilities/durable_execution/overview/">durable execution</a> engines</strong>: Temporal, DBOS, Prefect, Restate, AWS Lambda, Absurd, pgtask, Azure Durable Task and Apache Airflow, plus a builder for any other. Five of them (Temporal, DBOS, Prefect, Restate, AWS Lambda) are co-maintained with the engine's own team. No other framework here documents more than four.</li>
<li><strong>Five <a href="https://pydantic.dev/docs/ai/realtime/overview/">speech-to-speech</a> providers behind one API</strong>: OpenAI, Azure OpenAI, Gemini Live, xAI and ElevenLabs. The voice session uses the same <code>Agent</code>, tools and dependencies, and the call becomes ordinary message history a text agent can pick up, for example for structured output, which realtime sessions do not produce directly.</li>
<li><strong>Two <a href="https://pydantic.dev/docs/ai/integrations/ui/overview/">UI event stream protocols</a></strong> natively, AG-UI and the Vercel AI Data Stream Protocol (so Vercel's <code>useChat</code> renders a Python agent), plus a terminal CLI, a built-in web chat, and the Agent Client Protocol for editors (experimental): one agent, <a href="https://pydantic.dev/docs/ai/overview/interfaces/">every surface</a>.</li>
<li><strong>A local directory plus ten <a href="https://pydantic.dev/docs/ai/core-concepts/workspace/">sandboxes and remote workspaces</a></strong> for agents that run code: Modal, E2B, Sprites, Daytona, boxd, smolvm, BoxLite, Docker, Bubblewrap and SSH. The same file and shell tools work in whichever one the run has.</li>
<li><strong><a href="https://pydantic.dev/docs/ai/mcp/overview/">MCP</a> as client and server</strong>, with any MCP server's tools available to an agent as a toolset, OpenTelemetry tracing that follows the GenAI semantic conventions, and <a href="https://pydantic.dev/docs/ai/evals/evals/">Pydantic Evals</a> and <a href="https://pydantic.dev/docs/ai/graph/graph/">Pydantic Graph</a> in the same repository and release.</li>
</ul>
<p>For human-in-the-loop, mark a tool <code>requires_approval=True</code>: the run <a href="https://pydantic.dev/docs/ai/tools-toolsets/deferred-tools/">ends with the pending call</a>, you store the message history like any other data, and a later run, in any process, resumes from it with the decision; a durable engine does the same inside a workflow. Multi-agent works by delegation, programmatic hand-off, the Harness <code>SubAgents</code> capability, or a typed graph. <a href="https://pydantic.dev/logfire">Pydantic Logfire</a> is the easiest way to see the traces, and optional: <a href="https://pydantic.dev/docs/ai/integrations/logfire/">any OpenTelemetry backend works</a>. Pydantic offers <a href="https://pydantic.dev/docs/ai/overview/enterprise-support/">enterprise support for the framework itself</a>, from the team that builds it, with an SLA and no platform to buy. The framework is <a href="https://github.com/pydantic/pydantic-ai/blob/main/LICENSE">MIT licensed</a>.</p>
<p>The catch: it is Python only, and it is a library, not a hosted platform. Agents run in your process on your infrastructure, durability comes from an engine you choose and operate, and there is no management UI to hand to an operations team. LangChain has more retrieval integrations: about 80 <a href="https://docs.langchain.com/oss/python/integrations/document_loaders">document loaders</a>, 80 <a href="https://docs.langchain.com/oss/python/integrations/vectorstores">vector stores</a> and 90 <a href="https://docs.langchain.com/oss/python/integrations/retrievers">retrievers</a>, where Pydantic AI provides <a href="https://pydantic.dev/docs/ai/guides/embeddings/">embeddings</a> and leaves loading and vector storage to the library or database you already use. For the rest of what an agent touches, the breadth is on our side: 30+ model providers, nine durable execution engines, ten sandboxes and remote workspaces, and any MCP server as a toolset. LangChain's 300+ <a href="https://docs.langchain.com/oss/python/integrations/tools">tools and toolkits</a> also <a href="https://pydantic.dev/docs/ai/tools-toolsets/third-party-tools/">plug into a Pydantic AI agent</a> through <code>LangChainToolset</code>. For voice, you bring the audio transport and telephony bridge, and a cascaded speech-to-text, LLM and text-to-speech pipeline is available hosted (through ElevenLabs Agents or Azure AI Voice Live) rather than composed from vendor plugins in your own process.</p>
<p>Best for Python teams that want the agent to stay ordinary, typed Python across model providers, and to add durability, approvals, frontends and voice one at a time rather than adopt a runtime.</p>
</section><section id="2-langgraph-and-langchain-if-your-team-already-runs-on-langchain-and-langsmith-section"><h3 id="2-langgraph-and-langchain-if-your-team-already-runs-on-langchain-and-langsmith" role="presentation"><a href="#2-langgraph-and-langchain-if-your-team-already-runs-on-langchain-and-langsmith" class="heading-anchor"><button type="button" class="heading-anchor__btn">#</button></a><span role="heading" aria-level="3">2. LangGraph and LangChain: if your team already runs on LangChain and LangSmith</span></h3>
<p><a href="https://docs.langchain.com/oss/python/langgraph/overview">LangGraph</a> describes itself as a low-level orchestration framework and runtime for long-running, stateful agents. <a href="https://docs.langchain.com/oss/python/langchain/overview">LangChain's <code>create_agent</code></a> is an agent harness built on top of LangGraph, <a href="https://docs.langchain.com/oss/python/deepagents/overview">Deep Agents</a> is a fuller harness for planning, sub-agents and file-system context, and LangChain ships its integrations as separate <code>langchain-&#x3C;provider></code> packages; its <a href="https://docs.langchain.com/oss/python/integrations/chat">chat model list</a> has about 90 entries. Both are MIT licensed (<a href="https://github.com/langchain-ai/langchain/blob/master/LICENSE">LangChain</a>, <a href="https://github.com/langchain-ai/langgraph/blob/main/LICENSE">LangGraph</a>), from LangChain, Inc., which sells LangSmith for tracing, evaluation and deployment, and both also exist in JavaScript and TypeScript.</p>
<p><a href="https://docs.langchain.com/oss/python/langgraph/durable-execution">Checkpointing</a> is built into the graph runtime, with Postgres, SQLite and in-memory checkpointers. <a href="https://docs.langchain.com/oss/python/langchain/human-in-the-loop">Interrupts</a> let a person approve, edit or reject a tool call, and the <a href="https://docs.langchain.com/oss/python/langchain/multi-agent">multi-agent docs</a> lay out subagents, handoffs, routers and custom graphs. <a href="https://docs.langchain.com/oss/python/langchain/structured-output">Structured output</a> returns validated Pydantic models.</p>
<p>The catch: an agent spans layers (the LangChain harness on the LangGraph runtime). Durability is LangGraph's own checkpointers; its docs describe no external durable execution engine. Tracing is <a href="https://docs.langchain.com/oss/python/langchain/observability">LangSmith's</a>, with <a href="https://docs.langchain.com/langsmith/trace-with-opentelemetry">OpenTelemetry export through LangSmith</a>. <a href="https://docs.langchain.com/oss/python/langchain/mcp">MCP support</a> is a client, and marked beta. For voice, its docs have a <a href="https://docs.langchain.com/oss/python/langchain/voice-agent">tutorial</a> that composes speech-to-text, the agent and text-to-speech services yourself; there is no built-in speech-to-speech support.</p>
<p>Pick it when your agents, checkpoints and traces already live in LangGraph and LangSmith and work, or when you depend on a specific LangChain integration with no equivalent elsewhere.</p>
</section><section id="3-openai-agents-sdk-if-you-are-all-in-on-openai-section"><h3 id="3-openai-agents-sdk-if-you-are-all-in-on-openai" role="presentation"><a href="#3-openai-agents-sdk-if-you-are-all-in-on-openai" class="heading-anchor"><button type="button" class="heading-anchor__btn">#</button></a><span role="heading" aria-level="3">3. OpenAI Agents SDK: if you are all-in on OpenAI</span></h3>
<p>The <a href="https://openai.github.io/openai-agents-python/">OpenAI Agents SDK</a> is a small library centered on agents, handoffs between agents (or agents used as tools), and guardrails, plus sessions, sandbox agents, realtime voice agents and tracing. It is <a href="https://github.com/openai/openai-agents-python">MIT licensed</a> and also available for TypeScript.</p>
<p>Tools take <a href="https://openai.github.io/openai-agents-python/human_in_the_loop/"><code>needs_approval</code></a>, and the paused run's state serializes to JSON, so you can store it and resume later. Its docs list <a href="https://openai.github.io/openai-agents-python/running_agents/">four durable execution integrations</a>: Temporal, DBOS, Restate and Dapr. Typed output goes through <a href="https://openai.github.io/openai-agents-python/agents/"><code>output_type</code></a>, which accepts anything a Pydantic <code>TypeAdapter</code> can wrap. <a href="https://openai.github.io/openai-agents-python/realtime/guide/">Realtime agents</a> run on OpenAI's realtime models, including through Azure OpenAI.</p>
<p>The catch: its default path is OpenAI's Responses API, and <a href="https://openai.github.io/openai-agents-python/models/">other providers</a> go through LiteLLM and Any-LLM adapters that its docs call best-effort and beta. <a href="https://openai.github.io/openai-agents-python/tracing/">Tracing</a> is on by default and uploads to OpenAI's dashboard; with a non-OpenAI model you disable it, supply an OpenAI key for it, or add a third-party trace processor. <a href="https://openai.github.io/openai-agents-python/mcp/">MCP</a> is a client.</p>
<p>Right for teams whose model provider and tracing platform are both OpenAI, and who want the tightest fit with them.</p>
</section><section id="4-google-adk-if-you-are-standardized-on-google-cloud-or-need-java-or-go-section"><h3 id="4-google-adk-if-you-are-standardized-on-google-cloud-or-need-java-or-go" role="presentation"><a href="#4-google-adk-if-you-are-standardized-on-google-cloud-or-need-java-or-go" class="heading-anchor"><button type="button" class="heading-anchor__btn">#</button></a><span role="heading" aria-level="3">4. Google ADK: if you are standardized on Google Cloud, or need Java or Go</span></h3>
<p>Google's <a href="https://adk.dev/">Agent Development Kit</a> (ADK) is an open-source, code-first toolkit for building, evaluating and deploying agents, in Python, TypeScript, Go, Java and Kotlin. ADK 2.0 added a graph-based workflow runtime alongside LLM agents. It is <a href="https://github.com/google/adk-python/blob/main/LICENSE">Apache 2.0 licensed</a>.</p>
<p>Deployment paths lead to Google Cloud's <a href="https://adk.dev/deploy/agent-runtime/">Agent Runtime</a> (a paid service), Cloud Run and GKE. <a href="https://adk.dev/observability/traces/">Traces</a> are OpenTelemetry and go to any OTel backend. <a href="https://adk.dev/tools-custom/mcp-tools/">MCP</a> works as client and server. A <a href="https://adk.dev/runtime/resume/">resumable app</a> restores completed agents and tool results from its event log after a restart; a tool interrupted mid-call runs again (at-least-once). <a href="https://adk.dev/live/">Live agents</a> run speech-to-speech on the Gemini Live API, or a cascaded pipeline with a text model.</p>
<p>The catch: Gemini and other Google Cloud models are first-class; <a href="https://adk.dev/agents/models/">models outside Google's ecosystem</a> come through connectors such as LiteLLM, Ollama and vLLM. Its docs describe no external durable execution engine. Combining structured output with tools is <a href="https://adk.dev/agents/llm-agents/">supported natively only on specific models</a>, with a fallback on others. Tool confirmation, ADK's human-in-the-loop feature, is marked <a href="https://adk.dev/tools-custom/confirmation/">experimental</a>.</p>
<p>Best for teams whose models, deployment and support contract are already Google Cloud's, or that need one agent framework across Python and the JVM or Go.</p>
</section><section id="5-microsoft-agent-framework-if-you-build-on-azure-and-microsoft-foundry-section"><h3 id="5-microsoft-agent-framework-if-you-build-on-azure-and-microsoft-foundry" role="presentation"><a href="#5-microsoft-agent-framework-if-you-build-on-azure-and-microsoft-foundry" class="heading-anchor"><button type="button" class="heading-anchor__btn">#</button></a><span role="heading" aria-level="3">5. Microsoft Agent Framework: if you build on Azure and Microsoft Foundry</span></h3>
<p><a href="https://learn.microsoft.com/en-us/agent-framework/overview/">Microsoft Agent Framework</a> is the successor to AutoGen and Semantic Kernel, from the same teams. It brings together agents, a configurable harness agent for long multi-step tasks, and <a href="https://learn.microsoft.com/en-us/agent-framework/concepts/workflows/">graph-based workflows</a> that connect agents and functions through explicit execution paths, in Python and .NET, with a Go SDK in public preview. It is <a href="https://github.com/microsoft/agent-framework/blob/main/LICENSE">MIT licensed</a>, from Microsoft. Our <a href="https://pydantic.dev/docs/ai/comparisons/vs-microsoft-agent-framework/">comparison page</a> goes row by row.</p>
<p>The Python SDK runs on <a href="https://learn.microsoft.com/en-us/agent-framework/integrations/by-component/model-providers/?pivots=programming-language-python">OpenAI, Azure OpenAI, Microsoft Foundry, Anthropic, Bedrock, Gemini, Ollama and others</a>. Workflows <a href="https://learn.microsoft.com/en-us/agent-framework/workflows/checkpoints">checkpoint</a> their state, and the <a href="https://learn.microsoft.com/en-us/agent-framework/hosting/durable-extension">Durable Extension</a> adds recovery on Durable Task infrastructure, in Azure Functions or self-hosted workers. Tools can <a href="https://learn.microsoft.com/en-us/agent-framework/agents/tools/tool-approval">pause for approval</a>, <a href="https://learn.microsoft.com/en-us/agent-framework/agents/structured-outputs">structured output</a> accepts Pydantic models or JSON Schema, and <a href="https://learn.microsoft.com/en-us/agent-framework/agents/observability">traces</a> are OpenTelemetry. Agents reach other agents over <a href="https://github.com/microsoft/agent-framework/blob/main/python/packages/hosting-a2a/README.md">A2A</a>, as client and host, and frontends over <a href="https://github.com/microsoft/agent-framework/blob/main/python/packages/ag-ui/README.md">AG-UI</a>. <a href="https://learn.microsoft.com/en-us/agent-framework/hosting/foundry-hosted-agent">Foundry hosting</a> gives them a documented deployment path on Azure.</p>
<p>The catch: Microsoft's <a href="https://github.com/microsoft/agent-framework/blob/main/SUPPORT.md">support policy</a> covers Agent Framework issues for customers under a Unified support agreement, and only when the issue arises from Azure AI services; other use is treated as an open-source tool, supported on GitHub. Durable execution is the Durable Task extension; no other engine is documented. The Python SDK documents no realtime voice. Many Foundry-hosted tools, such as browser automation, are marked preview or experimental, and its code sandboxes are beta. Capabilities and release status differ between the Python and .NET SDKs.</p>
<p>Suited to teams whose models, hosting and support contract are already Azure and Microsoft Foundry, or that are moving from Semantic Kernel or AutoGen, or need one agent framework across Python and .NET.</p>
</section><section id="6-strands-agents-if-you-build-on-aws-and-amazon-bedrock-section"><h3 id="6-strands-agents-if-you-build-on-aws-and-amazon-bedrock" role="presentation"><a href="#6-strands-agents-if-you-build-on-aws-and-amazon-bedrock" class="heading-anchor"><button type="button" class="heading-anchor__btn">#</button></a><span role="heading" aria-level="3">6. Strands Agents: if you build on AWS and Amazon Bedrock</span></h3>
<p><a href="https://strandsagents.com/">Strands Agents</a> is an open-source SDK for building agents around a model-driven loop, in Python and TypeScript. On top of the SDK, the <a href="https://strandsagents.com/docs/user-guide/harness/">Strands harness</a> is a fully assembled agent: one <code>create_harness()</code> call gives you default tools, context management, sessions and memory. It is <a href="https://github.com/strands-agents/harness-sdk/blob/main/LICENSE.APACHE">Apache 2.0 licensed</a>, from AWS.</p>
<!-- TODO: link our comparison page, https://pydantic.dev/docs/ai/comparisons/vs-strands/, once it is live (pydantic/pydantic-ai#12026). -->
<p>Agents use Amazon Bedrock by default, and the <a href="https://strandsagents.com/docs/user-guide/sdk/model-providers/">model provider list</a> has about 20 more for Python, including Anthropic, OpenAI, Gemini, Mistral, Ollama and LiteLLM. <a href="https://strandsagents.com/docs/user-guide/sdk/interrupts/">Interrupts</a> pause a run for a person's approval or input, from a hook or a tool, and a <a href="https://strandsagents.com/docs/user-guide/sdk/agents/session-management/">session manager</a> persists the agent's state so a later request can resume it. <a href="https://strandsagents.com/docs/user-guide/sdk/agents/structured-output/">Structured output</a> returns a validated Pydantic model. Multi-agent comes as <a href="https://strandsagents.com/docs/user-guide/sdk/multi-agent/multi-agent-patterns/">agents as tools, swarms, graphs and workflows</a>, and agents reach other agents over <a href="https://strandsagents.com/docs/user-guide/sdk/multi-agent/agent-to-agent/">A2A</a>. <a href="https://strandsagents.com/docs/user-guide/sdk/tools/mcp-tools/">MCP</a> is a client, <a href="https://strandsagents.com/docs/user-guide/sdk/observability-evaluation/traces/">traces</a> are OpenTelemetry to any OTLP backend, and <a href="https://strandsagents.com/docs/user-guide/sdk/bidi/">bidirectional streaming</a> runs voice agents on Nova Sonic, Gemini Live or OpenAI's realtime models. <a href="https://strandsagents.com/docs/user-guide/sdk/deploy/">Deployment guides</a> cover Amazon Bedrock AgentCore, Lambda, Fargate, EKS and EC2.</p>
<p>The catch: durable execution comes from Temporal's <a href="https://docs.temporal.io/develop/python/integrations/strands-agents">Strands Agents plugin</a>, which Temporal maintains and marks public preview; Strands' built-in sessions persist state to local files or S3, and its docs describe no other engine. Voice is Python only. AG-UI frontends connect through a <a href="https://strandsagents.com/docs/integrations/integrations/ag-ui/">partner package</a> rather than the SDK. No commercial support for the SDK itself is documented; AWS Support plans cover AWS services. If AWS is your cloud and you want a different framework, Pydantic AI runs on <a href="https://pydantic.dev/docs/ai/models/bedrock/">Bedrock</a> and makes agents durable on <a href="https://pydantic.dev/docs/ai/harness/aws-lambda/">AWS Lambda durable functions</a>, an integration <a href="https://aws.amazon.com/about-aws/whats-new/2026/09/aws-lambda-durable-pydantic-ai/">AWS announced</a> and documents in its <a href="https://docs.aws.amazon.com/durable-execution/sdk-reference/integrations/pydantic-ai/">Durable Execution SDK guide</a>.</p>
<p>Suited to teams whose models and deployment are already on AWS, with Amazon Bedrock and AgentCore, or that want one agent SDK across Python and TypeScript with a ready-made harness to start from.</p>
</section><section id="7-crewai-if-you-would-rather-declare-roles-and-tasks-than-write-the-control-flow-section"><h3 id="7-crewai-if-you-would-rather-declare-roles-and-tasks-than-write-the-control-flow" role="presentation"><a href="#7-crewai-if-you-would-rather-declare-roles-and-tasks-than-write-the-control-flow" class="heading-anchor"><button type="button" class="heading-anchor__btn">#</button></a><span role="heading" aria-level="3">7. CrewAI: if you would rather declare roles and tasks than write the control flow</span></h3>
<p><a href="https://docs.crewai.com/en/introduction">CrewAI</a> is an <a href="https://github.com/crewAIInc/crewAI">MIT-licensed</a> Python framework for orchestrating role-playing, autonomous agents. Crews are teams of agents with roles and goals that collaborate and delegate; Flows are event-driven workflows that manage state around them. CrewAI, Inc. sells AMP, a commercial platform for deploying, monitoring and scaling crews.</p>
<p>You describe roles, goals and tasks, and the crew runs them <a href="https://docs.crewai.com/en/concepts/processes">sequentially or under a manager agent</a>. <a href="https://docs.crewai.com/en/concepts/flows">Flows</a> have built-in persistence (<code>@persist</code>, SQLite by default) and <a href="https://docs.crewai.com/en/concepts/checkpointing">checkpointing</a>, so crews and flows can resume after failures. <a href="https://docs.crewai.com/en/concepts/tasks">Tasks</a> return Pydantic output (<code>output_pydantic</code>) with guardrails and retries. <a href="https://docs.crewai.com/en/concepts/llms">Model support</a> is native for six providers (OpenAI, Anthropic, Gemini, Azure, Bedrock and Snowflake Cortex) and goes through LiteLLM for the rest.</p>
<p>The catch: problems that do not map onto roles and tasks have to be translated into crew vocabulary first, or written as Flows around the crew, which gives you two models to learn. Built-in <a href="https://docs.crewai.com/en/observability/tracing">tracing</a> goes to AMP, with OpenTelemetry through integrations such as OpenLIT. In the open-source framework, Flows take human input with a <code>@human_feedback</code> decorator; webhook-based <a href="https://docs.crewai.com/en/learn/human-in-the-loop">human-in-the-loop</a> is an enterprise feature. <a href="https://docs.crewai.com/en/mcp/overview">MCP</a> is a client, and its docs describe no realtime voice.</p>
<p>Suited to teams who think of the work as a crew of roles handing tasks to each other, and want the framework to own the hand-offs.</p>
</section><section id="8-claude-agent-sdk-if-you-want-claude-codes-own-loop-on-claude-section"><h3 id="8-claude-agent-sdk-if-you-want-claude-codes-own-loop-on-claude" role="presentation"><a href="#8-claude-agent-sdk-if-you-want-claude-codes-own-loop-on-claude" class="heading-anchor"><button type="button" class="heading-anchor__btn">#</button></a><span role="heading" aria-level="3">8. Claude Agent SDK: if you want Claude Code's own loop, on Claude</span></h3>
<p>The <a href="https://code.claude.com/docs/en/agent-sdk/overview">Claude Agent SDK</a> gives you the same tools, agent loop and context management that power Claude Code, as a Python or TypeScript library. It drives the Claude Code CLI as a subprocess, so file editing, shell commands, web search, permissions, sub-agents and sessions arrive already wired. The Python package is <a href="https://github.com/anthropics/claude-agent-sdk-python/blob/main/LICENSE">MIT licensed</a>; use of the SDK is governed by Anthropic's Commercial Terms of Service.</p>
<p><a href="https://code.claude.com/docs/en/agent-sdk/user-input">Permission callbacks</a> approve, deny or modify each tool call, and a hook can defer a decision so the process exits and resumes later. <a href="https://code.claude.com/docs/en/agent-sdk/subagents">Subagents</a>, <a href="https://code.claude.com/docs/en/agent-sdk/mcp">MCP servers</a> (local, HTTP or in-process) and <a href="https://code.claude.com/docs/en/agent-sdk/structured-outputs">structured output</a> validated against a JSON Schema are built in.</p>
<p>The catch: Claude models only, through <a href="https://code.claude.com/docs/en/agent-sdk/quickstart">Anthropic, Bedrock, Vertex AI or Microsoft Foundry</a>. Its <a href="https://code.claude.com/docs/en/agent-sdk/hosting">hosting docs</a> describe every running agent as "a long-lived process tied to local state", with transcripts mirrored to a <code>SessionStore</code> if they must survive the container, and suggest 1 GiB of RAM per agent as a starting point. It is a finished harness rather than parts to build one: you extend the loop with hooks and permissions rather than recompose it. OpenTelemetry tracing is opt-in and marked <a href="https://code.claude.com/docs/en/agent-sdk/observability">beta</a>, and no durable execution engine integration is documented. For a coding agent on other models, the Harness's <a href="https://pydantic.dev/docs/ai/harness/coder/"><code>Coder</code></a> is built from capabilities you can swap.</p>
<p>Pick it when the product you want is Claude Code itself, embedded, and a single model vendor is acceptable.</p>
</section><section id="9-agno-if-you-want-a-ready-made-server-and-ui-for-many-agents-section"><h3 id="9-agno-if-you-want-a-ready-made-server-and-ui-for-many-agents" role="presentation"><a href="#9-agno-if-you-want-a-ready-made-server-and-ui-for-many-agents" class="heading-anchor"><button type="button" class="heading-anchor__btn">#</button></a><span role="heading" aria-level="3">9. Agno: if you want a ready-made server and UI for many agents</span></h3>
<p><a href="https://docs.agno.com/introduction">Agno</a> is a Python SDK for building agent platforms. Alongside agents, teams and workflows, AgentOS runs your agents as services with a built-in API and MCP server, storage in Postgres, and durable background jobs. Agno is <a href="https://github.com/agno-agi/agno/blob/main/LICENSE">Apache 2.0 licensed</a>; the runtime is free and self-hosted, and <a href="https://www.agno.com/pricing">paid plans</a> add a control plane with role-based access control.</p>
<p>It comes with storage, OpenTelemetry tracing, <a href="https://docs.agno.com/hitl/overview">tool approval</a> with <code>continue_run</code>, <a href="https://docs.agno.com/features/mcp-server">MCP in both directions</a>, AG-UI and A2A interfaces, and a large tool catalog. Its <a href="https://docs.agno.com/features/sdk">SDK page</a> puts 30+ model providers behind one API, with Pydantic input and output schemas.</p>
<p>The catch: the server, storage and management features come from adopting AgentOS and its database as the shape of your service, and continuing a paused run requires the same database and session. Durability is Agno's own background jobs; no external engine is documented. AgentOS <a href="https://docs.agno.com/agent-os/tracing/overview">traces</a> use OpenTelemetry instrumentation and are stored in an Agno database. Some management features are in the paid plans.</p>
<p>Right for teams that want a server, storage and a management UI for many agents provided, and are happy to build inside that runtime.</p>
</section></section><section id="comparison-at-a-glance-section"><h2 id="comparison-at-a-glance" role="presentation"><a href="#comparison-at-a-glance" class="heading-anchor"><button type="button" class="heading-anchor__btn">#</button></a><span role="heading" aria-level="2">Comparison at a glance</span></h2>
<p>Checked October 29, 2026. Counts are what each framework's own docs list natively; "via" means through an adapter or a separate integration; "none documented" means its docs describe none.</p>
<div class="overflow-x-auto table-wrapper" tabindex="0"><table>
<thead>
<tr>
<th>Framework</th>
<th>Model providers</th>
<th>Durable execution</th>
<th>Speech-to-speech voice</th>
<th>Frontends and interfaces</th>
<th>MCP</th>
<th>Observability</th>
<th>Commercial support</th>
<th>License and maker</th>
</tr>
</thead>
<tbody>
<tr>
<td>Pydantic AI</td>
<td>30+, plus any OpenAI-compatible endpoint</td>
<td>9 engines: Temporal, DBOS, Prefect, Restate, AWS Lambda, Absurd, pgtask, Azure Durable Task, Apache Airflow</td>
<td>5 providers: OpenAI, Azure OpenAI, Gemini Live, xAI, ElevenLabs</td>
<td>AG-UI, Vercel AI, CLI, web chat, ACP (experimental)</td>
<td>Client and server</td>
<td>OpenTelemetry (GenAI conventions) to any backend; Logfire optional</td>
<td>For the framework itself, from Pydantic; no platform plan needed</td>
<td>MIT; Pydantic</td>
</tr>
<tr>
<td>LangGraph / LangChain</td>
<td>About 90 chat model integrations, as separate packages</td>
<td>Own checkpointers (Postgres, SQLite, memory); no external engine documented</td>
<td>None built in; a tutorial composes STT, agent and TTS</td>
<td>LangSmith Agent Server, Fleet</td>
<td>Client (beta)</td>
<td>LangSmith; OTel via LangSmith</td>
<td>With a LangSmith Enterprise plan</td>
<td>MIT; LangChain, Inc. (LangSmith)</td>
</tr>
<tr>
<td>OpenAI Agents SDK</td>
<td>OpenAI; others via beta LiteLLM and Any-LLM adapters</td>
<td>4 integrations: Temporal, DBOS, Restate, Dapr</td>
<td>OpenAI realtime models, including on Azure</td>
<td>REPL demo loop</td>
<td>Client</td>
<td>OpenAI tracing on by default; third-party processors</td>
<td>None documented for the SDK; OpenAI's API Enterprise plan covers the API</td>
<td>MIT; OpenAI</td>
</tr>
<tr>
<td>Google ADK</td>
<td>Gemini first; others via LiteLLM, Ollama, vLLM connectors</td>
<td>Own resume from logged events; no external engine documented</td>
<td>Gemini Live</td>
<td>CLI, web, A2A</td>
<td>Client and server</td>
<td>OpenTelemetry to any backend</td>
<td>None documented for ADK; Google Cloud support plans cover Google Cloud services</td>
<td>Apache 2.0; Google (Agent Runtime)</td>
</tr>
<tr>
<td>Microsoft Agent Framework</td>
<td>OpenAI, Azure OpenAI, Foundry, Anthropic, Bedrock, Gemini, Ollama and others</td>
<td>Durable Task extension (Azure Functions or self-hosted workers); workflow checkpoints</td>
<td>None documented for Python</td>
<td>AG-UI, A2A, DevUI sample app</td>
<td>Client</td>
<td>OpenTelemetry</td>
<td>Under a Microsoft Unified support agreement, for issues arising from Azure AI services</td>
<td>MIT; Microsoft (Foundry)</td>
</tr>
<tr>
<td>Strands Agents</td>
<td>Bedrock by default; about 20 more for Python, including LiteLLM</td>
<td>Temporal plugin (public preview, maintained by Temporal); sessions in files or S3</td>
<td>Python only: Nova Sonic, Gemini Live, OpenAI realtime</td>
<td>A2A, CLI; AG-UI via a partner package</td>
<td>Client</td>
<td>OpenTelemetry to any backend</td>
<td>None documented for Strands; AWS Support plans cover AWS services</td>
<td>Apache 2.0; AWS (AgentCore)</td>
</tr>
<tr>
<td>CrewAI</td>
<td>6 native; others via LiteLLM</td>
<td>Own checkpointing; Flow persistence (SQLite)</td>
<td>None documented</td>
<td>Enterprise UI, A2A</td>
<td>Client</td>
<td>AMP tracing; OTel via integrations</td>
<td>With the CrewAI Enterprise platform plan</td>
<td>MIT; CrewAI, Inc. (AMP)</td>
</tr>
<tr>
<td>Claude Agent SDK</td>
<td>Claude only, on 4 platforms (Anthropic, Bedrock, Vertex AI, Foundry)</td>
<td>Sessions on disk, or a <code>SessionStore</code>; no engine integration documented</td>
<td>None documented</td>
<td>CLI, GitHub Action</td>
<td>Client; in-process servers for its own tools</td>
<td>OpenTelemetry, opt-in (beta)</td>
<td>None documented</td>
<td>MIT, under Anthropic's Commercial Terms; Anthropic</td>
</tr>
<tr>
<td>Agno</td>
<td>30+</td>
<td>AgentOS durable background jobs; Postgres storage</td>
<td>None documented</td>
<td>AG-UI, A2A, chat platforms</td>
<td>Client and server</td>
<td>OpenTelemetry instrumentation, stored in an Agno database</td>
<td>With Agno's paid plans: email support on Pro, SLAs on Enterprise</td>
<td>Apache 2.0; Agno (AgentOS plans)</td>
</tr>
</tbody>
</table></div>
</section><section id="if-youre-building-voice-agents-section"><h2 id="if-youre-building-voice-agents" role="presentation"><a href="#if-youre-building-voice-agents" class="heading-anchor"><button type="button" class="heading-anchor__btn">#</button></a><span role="heading" aria-level="2">If you're building voice agents</span></h2>
<p>Voice agents split the work differently. The hard parts are the call itself (audio transport, telephony, turn detection, noise) and the agent behind it (tools, data, what happens after the call). Two frameworks are built around the call, and Pydantic AI is built around the agent; they combine more often than they compete.</p>
<ul>
<li><strong><a href="https://docs.livekit.io/agents/">LiveKit Agents</a></strong> adds Python or Node programs to LiveKit's WebRTC rooms as realtime participants: a cascaded speech-to-text, LLM and text-to-speech pipeline from <a href="https://docs.livekit.io/agents/models/">per-provider plugins</a>, or a speech-to-speech model, with <a href="https://docs.livekit.io/telephony/">SIP telephony</a>, turn detection, noise cancellation and mid-call handoffs between agents. It is Apache 2.0 licensed and runs self-hosted or on LiveKit Cloud.</li>
<li><strong><a href="https://docs.pipecat.ai/getting-started/introduction">Pipecat</a></strong>, built and maintained by Daily, composes frame processors into a pipeline: transports carry the audio, and speech-to-text, LLM, text-to-speech and speech-to-speech <a href="https://docs.pipecat.ai/server/services/supported-services">services</a> slot in as stages. <a href="https://docs.pipecat.ai/guides/features/pipecat-flows">Pipecat Flows</a> adds a node graph for structured conversations on cascaded pipelines. It is BSD-2-Clause licensed and runs self-hosted or on Pipecat Cloud.</li>
</ul>
<div class="overflow-x-auto table-wrapper" tabindex="0"><table>
<thead>
<tr>
<th></th>
<th>Speech-to-speech</th>
<th>Cascaded STT, LLM and TTS</th>
<th>Transport and telephony</th>
<th>Tools and MCP</th>
<th>After the call</th>
<th>Hosting</th>
<th>Commercial support</th>
<th>License and maker</th>
</tr>
</thead>
<tbody>
<tr>
<td>Pydantic AI</td>
<td>5 providers behind one API: OpenAI, Azure OpenAI, Gemini Live, xAI, ElevenLabs</td>
<td>Hosted, through ElevenLabs Agents or Azure AI Voice Live; or compose your own around a text agent</td>
<td>You bring it: browser WebRTC (OpenAI, Azure) or a WebSocket relay; phone through a bridge such as Twilio</td>
<td>The same tools, dependencies and capabilities as the text agent; MCP through toolsets</td>
<td>The call is message history; hand it to a text agent for structured output; OpenTelemetry tracing</td>
<td>Your process, your backend</td>
<td>For the framework itself, from Pydantic</td>
<td>MIT; Pydantic</td>
</tr>
<tr>
<td>LiveKit Agents</td>
<td>Yes, realtime model plugins</td>
<td>Yes, from per-provider plugins</td>
<td>LiveKit WebRTC rooms; SIP in and out, DTMF, transfers; phone numbers on Cloud</td>
<td>Function tools; MCP (Python)</td>
<td>Session history; text-mode tests and agent simulations</td>
<td>Self-host or LiveKit Cloud</td>
<td>With a LiveKit Cloud plan; none documented for self-hosting</td>
<td>Apache 2.0; LiveKit</td>
</tr>
<tr>
<td>Pipecat</td>
<td>Yes, speech-to-speech services</td>
<td>Yes, the primary path, from swappable services</td>
<td>Daily, LiveKit, WebRTC and WebSocket transports; PSTN and SIP dial-in and dial-out; Twilio and others</td>
<td>Function calling; MCP client</td>
<td>Pipecat Flows for structured conversations; Pipecat Evals</td>
<td>Self-host or Pipecat Cloud</td>
<td>From Daily, for Pipecat and Pipecat Cloud</td>
<td>BSD-2-Clause; Daily</td>
</tr>
</tbody>
</table></div>
<p>Pydantic AI's <a href="https://pydantic.dev/docs/ai/realtime/overview/">realtime support</a> runs the same typed agent over a voice session. It can also run on a hosted voice platform: an <code>elevenlabs-agents:&#x3C;agent_id></code> model <a href="https://pydantic.dev/docs/ai/realtime/elevenlabs/">runs the conversation on a hosted ElevenLabs agent</a>: ElevenLabs keeps the speech pipeline, turn-taking, knowledge base and workflows, while your Pydantic AI instructions override the agent per conversation and your Pydantic AI tools run in your backend. And a LiveKit call's history <a href="https://pydantic.dev/docs/ai/comparisons/vs-livekit/">converts to Pydantic AI message history</a>, so a Pydantic AI agent can produce structured output or the follow-up from it.</p>
<p>Pick LiveKit Agents or Pipecat when you want to own and self-host the transport, telephony and a pipeline of interchangeable speech vendors. Pick Pydantic AI when the agent is the product and voice is one of its interfaces, including on top of a hosted platform such as ElevenLabs Agents. Our <a href="https://pydantic.dev/docs/ai/comparisons/vs-livekit/">LiveKit</a> and <a href="https://pydantic.dev/docs/ai/comparisons/vs-pipecat/">Pipecat</a> comparison pages go row by row.</p>
</section><section id="if-you-work-in-typescript-section"><h2 id="if-you-work-in-typescript" role="presentation"><a href="#if-you-work-in-typescript" class="heading-anchor"><button type="button" class="heading-anchor__btn">#</button></a><span role="heading" aria-level="2">If you work in TypeScript</span></h2>
<p>This list is Python only. In TypeScript, look at <a href="https://mastra.ai/">Mastra</a>, an agent framework with step workflows, memory, evals, a local playground and a hosted Studio, and the <a href="https://ai-sdk.dev/">Vercel AI SDK</a>, which adds model calls, tool loops and streaming chat to a TypeScript app. LangChain, the OpenAI Agents SDK, Google ADK, Strands Agents and the Claude Agent SDK also have TypeScript versions. If your frontend is on the Vercel AI SDK and your agent is in Python, Pydantic AI's <a href="https://pydantic.dev/docs/ai/comparisons/vs-vercel-ai-sdk/">Vercel AI adapter</a> lets <code>useChat</code> render it unchanged.</p>
</section><section id="how-to-choose-section"><h2 id="how-to-choose" role="presentation"><a href="#how-to-choose" class="heading-anchor"><button type="button" class="heading-anchor__btn">#</button></a><span role="heading" aria-level="2">How to choose</span></h2>
<ul>
<li>You are starting a Python agent and want typed code across model providers, with durability, approvals, frontends and voice available when you need them: <strong>Pydantic AI</strong>.</li>
<li>Your runs must survive a crash, on an engine your company already operates: <strong>Pydantic AI</strong> (nine engines), or the <strong>OpenAI Agents SDK</strong> (four) if you are on OpenAI's models.</li>
<li>Your agents, checkpoints and traces already live in LangGraph and LangSmith: <strong>LangGraph and LangChain</strong>.</li>
<li>OpenAI is your model provider and tracing platform: the <strong>OpenAI Agents SDK</strong>.</li>
<li>You deploy on Google Cloud with Gemini, or need Java or Go too: <strong>Google ADK</strong>.</li>
<li>You build on Azure and Microsoft Foundry, or need .NET too: <strong>Microsoft Agent Framework</strong>.</li>
<li>You build on AWS and Amazon Bedrock: <strong>Strands Agents</strong>.</li>
<li>You want to declare a crew of roles and tasks and let the framework run the hand-offs: <strong>CrewAI</strong>.</li>
<li>You want Claude Code itself inside your product, on Claude models: the <strong>Claude Agent SDK</strong>.</li>
<li>You want a ready-made server and management UI for many agents: <strong>Agno</strong>.</li>
<li>You are building a voice agent: <strong>Pydantic AI</strong> when the agent is the product and voice is one of its interfaces; <strong>LiveKit Agents</strong> or <strong>Pipecat</strong> when you want to own the WebRTC transport and compose the pipeline.</li>
</ul>
</section><section id="when-another-framework-is-the-better-pick-section"><h2 id="when-another-framework-is-the-better-pick" role="presentation"><a href="#when-another-framework-is-the-better-pick" class="heading-anchor"><button type="button" class="heading-anchor__btn">#</button></a><span role="heading" aria-level="2">When another framework is the better pick</span></h2>
<p>Four situations favor something else over Pydantic AI.</p>
<p>The first is a single vendor, all the way down. If your models, tracing and deployment are all OpenAI, all Google Cloud, all Azure, or all AWS, that vendor's SDK has the shortest path to its own platform features, and model portability is a benefit you will not use. The same goes for the Claude Agent SDK when the product you want is Claude Code itself.</p>
<p>The second is a system you already have. A team with LangGraph agents in production, checkpoints in Postgres and traces in LangSmith has a working system; moving is worth it when something you cannot do today costs more than the rewrite.</p>
<p>The third is a hosted runtime. Pydantic AI is a library that runs in your process. If you want a server, storage and a management UI provided, Agno's AgentOS, CrewAI's AMP and LangSmith deployments are built for that.</p>
<p>The fourth is voice where the call is the product. For self-hosted WebRTC rooms, telephony and a pipeline of interchangeable speech vendors in your own process, LiveKit Agents and Pipecat do more out of the box.</p>
</section><section id="frequently-asked-questions-section"><h2 id="frequently-asked-questions" role="presentation"><a href="#frequently-asked-questions" class="heading-anchor"><button type="button" class="heading-anchor__btn">#</button></a><span role="heading" aria-level="2">Frequently asked questions</span></h2>
<p><strong>What is the best Python framework for building AI agents?</strong>
Our answer is Pydantic AI: it runs on 30+ model providers and, of the frameworks compared here, supports the most durable execution engines, speech-to-speech providers and frontend protocols, plus ten sandboxes and remote workspaces for agents that run code, all in one typed agent. The exceptions are teams tied to one vendor (the OpenAI Agents SDK, Google ADK, Microsoft Agent Framework, Strands Agents or the Claude Agent SDK), teams with LangGraph already in production, and teams that want a hosted runtime rather than a library.</p>
<p><strong>Which Python agent frameworks support durable execution?</strong>
Pydantic AI runs agents durably on nine engines: Temporal, DBOS, Prefect, Restate, AWS Lambda, Absurd, pgtask, Azure Durable Task and Apache Airflow. The OpenAI Agents SDK documents Temporal, DBOS, Restate and Dapr integrations. Microsoft Agent Framework documents a Durable Task extension, and Strands Agents a Temporal plugin that Temporal maintains, in public preview. LangGraph has built-in checkpointers. Google ADK, CrewAI and Agno resume or checkpoint within their own runtimes. The Claude Agent SDK keeps sessions on disk and documents no engine integration.</p>
<p><strong>Which agent frameworks work with the most model providers?</strong>
Pydantic AI supports 30+ providers, selected by one string, plus any OpenAI-compatible endpoint. LangChain lists the most chat model integrations, about 90, as separate packages. Agno lists 30+ providers, Strands Agents about 20 for Python with Amazon Bedrock as the default, and CrewAI six natively with LiteLLM for the rest. The OpenAI Agents SDK, Google ADK and the Claude Agent SDK are built around one vendor's models first.</p>
<p><strong>Can I build a voice agent with Pydantic AI?</strong>
Yes. The same agent runs over a speech-to-speech session on OpenAI, Azure OpenAI, Gemini Live, xAI or ElevenLabs, with the same tools. It can also take over a hosted ElevenLabs agent per conversation. You bring the audio transport; LiveKit Agents and Pipecat provide one, and a LiveKit call's history converts to Pydantic AI messages. Realtime sessions do not return structured output directly; hand the call's history to a text agent for that.</p>
<p><strong>Does Pydantic AI require Logfire?</strong>
No. Pydantic AI emits standard OpenTelemetry traces that follow the GenAI semantic conventions, and any OpenTelemetry backend works. Pydantic Logfire is an optional hosted service from the same team.</p>
</section><section id="sources-section"><h2 id="sources" role="presentation"><a href="#sources" class="heading-anchor"><button type="button" class="heading-anchor__btn">#</button></a><span role="heading" aria-level="2">Sources</span></h2>
<p>Every source below was checked on October 29, 2026.</p>
<ul>
<li><strong>Pydantic AI</strong>: <a href="https://pydantic.dev/docs/ai/models/overview/">models and providers</a>, <a href="https://pydantic.dev/docs/ai/capabilities/durable_execution/overview/">durable execution</a> and <a href="https://pydantic.dev/docs/ai/harness/azure-durable-task/">Azure Durable Task</a> (both checked November 4, 2026), <a href="https://pydantic.dev/docs/ai/core-concepts/workspace/">workspaces and sandboxes</a>, <a href="https://pydantic.dev/docs/ai/realtime/overview/">realtime</a>, <a href="https://pydantic.dev/docs/ai/integrations/ui/overview/">UI protocols</a>, <a href="https://pydantic.dev/docs/ai/mcp/overview/">MCP</a>, <a href="https://pydantic.dev/docs/ai/tools-toolsets/deferred-tools/">deferred tools</a>, <a href="https://pydantic.dev/docs/ai/harness/">Harness</a>, and our <a href="https://pydantic.dev/docs/ai/comparisons/">comparison pages</a>, <a href="https://pydantic.dev/docs/ai/overview/enterprise-support/">enterprise support</a>.</li>
<li><strong>LangGraph and LangChain</strong>: <a href="https://docs.langchain.com/oss/python/langgraph/overview">LangGraph overview</a>, <a href="https://docs.langchain.com/oss/python/langgraph/durable-execution">durable execution</a>, <a href="https://docs.langchain.com/oss/python/langchain/human-in-the-loop">human-in-the-loop</a>, <a href="https://docs.langchain.com/oss/python/langchain/mcp">MCP</a>, <a href="https://docs.langchain.com/oss/python/integrations/chat">chat models</a>, <a href="https://docs.langchain.com/oss/python/langchain/observability">observability</a>, <a href="https://docs.langchain.com/oss/python/langchain/voice-agent">voice agent tutorial</a>, <a href="https://www.langchain.com/enterprise">LangSmith Enterprise</a>.</li>
<li><strong>OpenAI Agents SDK</strong>: <a href="https://openai.github.io/openai-agents-python/">overview</a>, <a href="https://openai.github.io/openai-agents-python/models/">models</a>, <a href="https://openai.github.io/openai-agents-python/running_agents/">running agents</a>, <a href="https://openai.github.io/openai-agents-python/human_in_the_loop/">human-in-the-loop</a>, <a href="https://openai.github.io/openai-agents-python/tracing/">tracing</a>, <a href="https://openai.github.io/openai-agents-python/realtime/guide/">realtime</a>, <a href="https://github.com/openai/openai-agents-python">repository</a>, <a href="https://openai.com/api/pricing/">API pricing</a>.</li>
<li><strong>Google ADK</strong>: <a href="https://adk.dev/">overview</a>, <a href="https://adk.dev/agents/models/">models</a>, <a href="https://adk.dev/agents/llm-agents/">LLM agents</a>, <a href="https://adk.dev/runtime/resume/">resume</a>, <a href="https://adk.dev/tools-custom/confirmation/">tool confirmation</a>, <a href="https://adk.dev/observability/traces/">traces</a>, <a href="https://adk.dev/live/">live agents</a>, <a href="https://github.com/google/adk-python">repository</a>, <a href="https://docs.cloud.google.com/support/docs">Google Cloud support</a>.</li>
<li><strong>Microsoft Agent Framework</strong>: <a href="https://learn.microsoft.com/en-us/agent-framework/overview/">overview</a>, <a href="https://learn.microsoft.com/en-us/agent-framework/integrations/by-component/model-providers/?pivots=programming-language-python">model providers</a>, <a href="https://learn.microsoft.com/en-us/agent-framework/agents/tools/">tools</a>, <a href="https://learn.microsoft.com/en-us/agent-framework/agents/tools/tool-approval">tool approval</a>, <a href="https://learn.microsoft.com/en-us/agent-framework/agents/structured-outputs">structured output</a>, <a href="https://learn.microsoft.com/en-us/agent-framework/concepts/workflows/">workflows</a>, <a href="https://learn.microsoft.com/en-us/agent-framework/workflows/checkpoints">checkpoints</a>, <a href="https://learn.microsoft.com/en-us/agent-framework/hosting/durable-extension">Durable Extension</a>, <a href="https://learn.microsoft.com/en-us/agent-framework/hosting/foundry-hosted-agent">Foundry hosting</a>, <a href="https://learn.microsoft.com/en-us/agent-framework/agents/observability">observability</a>, <a href="https://github.com/microsoft/agent-framework/blob/main/python/packages/ag-ui/README.md">AG-UI</a>, <a href="https://github.com/microsoft/agent-framework/blob/main/python/packages/hosting-a2a/README.md">A2A hosting</a>, <a href="https://github.com/microsoft/agent-framework/blob/main/SUPPORT.md">support policy</a>, <a href="https://github.com/microsoft/agent-framework">repository</a>.</li>
<li><strong>Strands Agents</strong> (checked November 2, 2026): <a href="https://strandsagents.com/">overview</a>, <a href="https://strandsagents.com/docs/user-guide/harness/">harness</a>, <a href="https://strandsagents.com/docs/user-guide/sdk/model-providers/">model providers</a>, <a href="https://strandsagents.com/docs/user-guide/sdk/interrupts/">interrupts</a>, <a href="https://strandsagents.com/docs/user-guide/sdk/agents/session-management/">session management</a>, <a href="https://strandsagents.com/docs/user-guide/sdk/agents/structured-output/">structured output</a>, <a href="https://strandsagents.com/docs/user-guide/sdk/multi-agent/multi-agent-patterns/">multi-agent patterns</a>, <a href="https://strandsagents.com/docs/user-guide/sdk/multi-agent/agent-to-agent/">A2A</a>, <a href="https://strandsagents.com/docs/user-guide/sdk/tools/mcp-tools/">MCP</a>, <a href="https://strandsagents.com/docs/user-guide/sdk/observability-evaluation/traces/">traces</a>, <a href="https://strandsagents.com/docs/user-guide/sdk/bidi/">bidirectional streaming</a>, <a href="https://strandsagents.com/docs/user-guide/sdk/deploy/">deployment</a>, <a href="https://strandsagents.com/docs/integrations/integrations/ag-ui/">AG-UI</a>, <a href="https://strandsagents.com/docs/user-guide/sdk/versioning-and-support/">versioning and support</a>, <a href="https://github.com/strands-agents/harness-sdk">repository</a>, and Temporal's <a href="https://docs.temporal.io/develop/python/integrations/strands-agents">Strands Agents plugin</a>.</li>
<li><strong>CrewAI</strong>: <a href="https://docs.crewai.com/en/introduction">introduction</a>, <a href="https://docs.crewai.com/en/concepts/llms">LLMs</a>, <a href="https://docs.crewai.com/en/concepts/flows">flows</a>, <a href="https://docs.crewai.com/en/concepts/checkpointing">checkpointing</a>, <a href="https://docs.crewai.com/en/learn/human-in-the-loop">human-in-the-loop</a>, <a href="https://docs.crewai.com/en/observability/tracing">tracing</a>, <a href="https://github.com/crewAIInc/crewAI">repository</a>, <a href="https://www.crewai.com/pricing">pricing</a>.</li>
<li><strong>Claude Agent SDK</strong>: <a href="https://code.claude.com/docs/en/agent-sdk/overview">overview</a>, <a href="https://code.claude.com/docs/en/agent-sdk/quickstart">quickstart</a>, <a href="https://code.claude.com/docs/en/agent-sdk/hosting">hosting</a>, <a href="https://code.claude.com/docs/en/agent-sdk/user-input">user input</a>, <a href="https://code.claude.com/docs/en/agent-sdk/observability">observability</a>, <a href="https://github.com/anthropics/claude-agent-sdk-python">repository</a>.</li>
<li><strong>Agno</strong>: <a href="https://docs.agno.com/introduction">introduction</a>, <a href="https://docs.agno.com/features/sdk">SDK</a>, <a href="https://docs.agno.com/hitl/overview">human-in-the-loop</a>, <a href="https://docs.agno.com/agent-os/tracing/overview">tracing</a>, <a href="https://www.agno.com/pricing">pricing</a>, <a href="https://www.agno.com/enterprise">enterprise</a>, <a href="https://github.com/agno-agi/agno">repository</a>.</li>
<li><strong>Voice</strong>: LiveKit <a href="https://docs.livekit.io/agents/">Agents</a>, <a href="https://docs.livekit.io/agents/models/">models</a>, <a href="https://docs.livekit.io/telephony/">telephony</a> and <a href="https://livekit.com/pricing">pricing</a>; Pipecat <a href="https://docs.pipecat.ai/getting-started/introduction">introduction</a>, <a href="https://docs.pipecat.ai/server/services/supported-services">services</a>, <a href="https://docs.pipecat.ai/guides/telephony/overview">telephony</a> and <a href="https://docs.pipecat.ai/enterprise-support">enterprise support</a>; ElevenLabs Agents <a href="https://elevenlabs.io/docs/eleven-agents/overview">overview</a>.</li>
</ul>
</section><section id="try-pydantic-ai-section"><h2 id="try-pydantic-ai" role="presentation"><a href="#try-pydantic-ai" class="heading-anchor"><button type="button" class="heading-anchor__btn">#</button></a><span role="heading" aria-level="2">Try Pydantic AI</span></h2>
<p><code>pip install pydantic-ai</code>, then follow the <a href="https://pydantic.dev/docs/ai/">docs</a> from a typed agent to durable execution, a frontend or a voice call. Coming from another framework? Our <a href="https://pydantic.dev/docs/ai/comparisons/">comparison pages</a> go row by row, and the <a href="https://pydantic.dev/docs/ai/comparisons/migrate-from-other-frameworks/">migration skills</a> port an existing application one working path at a time.</p></section>]]></content:encoded>
</item>
<item>
<title>Pydantic Validation: Next Steps</title>
<link>https://pydantic.dev/articles/pydantic-validation-next-steps</link>
<guid isPermaLink="true">https://pydantic.dev/articles/pydantic-validation-next-steps</guid>
<pubDate>Fri, 30 Oct 2026 00:00:00 GMT</pubDate>
<dc:creator>Victorien Plot</dc:creator>
<category>Pydantic Validation</category>
<category>Announcements</category>
<description>Pydantic Validation V3 is coming without a painful migration. Here is what to expect, and what it means for V1 and V2 support.</description>
<content:encoded><![CDATA[<p>Pydantic Validation has come a long way since the <a href="https://github.com/pydantic/pydantic/releases/tag/v2.0">V2 release</a> in June 2023.
Fourteen minor releases later (the most recent being <a href="https://pydantic.dev/articles/pydantic-v2-14-release">V2.14</a>), V2 is faster, more correct, and supports far more of the Python type system than it did at launch.</p>
<p>Usage has grown with it. Pydantic is now <a href="https://pypistats.org/top">one of the 20</a> most downloaded packages on PyPI, at more than 800 million downloads a month.</p>
<p>We are starting work on the next major release, Pydantic V3. Here is what to expect, and what it means for V1 and V2.</p>
<section id="pydantic-v3--not--section"><h2 id="pydantic-v3--not-" role="presentation"><a href="#pydantic-v3--not-" class="heading-anchor"><button type="button" class="heading-anchor__btn">#</button></a><span role="heading" aria-level="2">Pydantic V3: 🙂 not 😱</span></h2>
<p>We know the V1 to V2 migration was painful for some of you. That is why we have kept V1 maintained for the past three years.</p>
<p>V3 will be different. As described in the <a href="https://github.com/pydantic/pydantic/issues/10033">tracking issue</a>, every breaking change will be one of:</p>
<ul>
<li>a correctness fix, such as a bug that affects a minority of users (for example, <a href="https://github.com/pydantic/pydantic/issues/9992">#9992</a>).</li>
<li>a change where you can easily opt back in to the previous behavior.</li>
</ul>
<p>V1 deprecations and the <code>pydantic.v1</code> namespace will also be removed.</p>
<p>There will be no API overhaul on the scale of the V1 to V2 migration.</p>
<p>Over time, we have collected a long list of <a href="https://github.com/pydantic/pydantic/issues?q=is%3Aissue+state%3Aopen+label%3Av3">issues</a> that can only be fixed in a major release.
We won't tackle every one of them, but we want to get as many as possible into V3.</p>
<p>There is no release date yet, but we are aiming to have V3 close to its final state by the end of the year.</p>
</section><section id="pydantic-v1-section"><h2 id="pydantic-v1" role="presentation"><a href="#pydantic-v1" class="heading-anchor"><button type="button" class="heading-anchor__btn">#</button></a><span role="heading" aria-level="2">Pydantic V1</span></h2>
<p>We have released <a href="https://github.com/pydantic/pydantic/releases/tag/v1.10.27">Pydantic V1.10.27</a>, the final V1 release. This release fixes some security issues, described in the changelog.</p>
<p>The same fixes are included in the <code>pydantic.v1</code> namespace shipped with <a href="https://github.com/pydantic/pydantic/releases/tag/v2.14.2">Pydantic V2.14.2</a>.</p>
<aside class="callout callout-warn"><div class="callout-indicator"><svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="2" aria-hidden="true"><path d="M12 9v4m0 4h.01M8.681 4.082C9.351 2.797 10.621 2 12 2s2.649.797 3.319 2.082l6.203 11.904a4.28 4.28 0 0 1-.046 4.019C20.793 21.241 19.549 22 18.203 22H5.797c-1.346 0-2.59-.759-3.273-1.995a4.28 4.28 0 0 1-.046-4.019L8.681 4.082Z"></path></svg><div class="callout-title">Warning</div></div><div class="callout-content"><p>This is the last release of Pydantic V1, and V1 support has now ended, including the <code>pydantic.v1</code> namespace in V2. Any security issue found from now on will <em>not</em> be fixed.</p></div></aside>
</section><section id="pydantic-v2-section"><h2 id="pydantic-v2" role="presentation"><a href="#pydantic-v2" class="heading-anchor"><button type="button" class="heading-anchor__btn">#</button></a><span role="heading" aria-level="2">Pydantic V2</span></h2>
<p>Once V3 is out, V2 will keep receiving fixes for major bugs and security issues.
How long that lasts depends on how smoothly the migration to V3 goes, so we aren't setting an end date yet.
We won't drop V2 until we are confident most users have moved to V3.</p>
</section><section id="enterprise-support-section"><h2 id="enterprise-support" role="presentation"><a href="#enterprise-support" class="heading-anchor"><button type="button" class="heading-anchor__btn">#</button></a><span role="heading" aria-level="2">Enterprise support</span></h2>
<p>Pydantic itself stays open source. Its license, releases, documentation, and issue tracker remain open to everyone.</p>
<p>Some teams need more than that. You might still run V1 in production and can't migrate yet, or you might want help planning the move to V3.
For those cases, we offer <a href="https://pydantic.dev/docs/validation/latest/get-started/enterprise-support/">enterprise support</a>: direct access to Pydantic engineers, 24/7 priority support, and an SLA matched to how you operate.
Your agreement defines the release lines we cover and how we coordinate with you when a vulnerability affects one of them.</p>
<p><a href="https://pydantic.dev/contact">Contact us</a> to discuss what your team needs.</p>
<hr>
<p>Have questions or feedback on the roadmap? Join the conversation on our community <a href="https://pydantic.dev/docs/logfire/join-slack/">Slack</a> or open a discussion on <a href="https://github.com/pydantic/pydantic/discussions">GitHub</a>.</p></section>]]></content:encoded>
</item>
<item>
<title>Rendreal takes print orders inside the assistant you already use</title>
<link>https://pydantic.dev/articles/rendreal-case-study</link>
<guid isPermaLink="true">https://pydantic.dev/articles/rendreal-case-study</guid>
<pubDate>Fri, 30 Oct 2026 00:00:00 GMT</pubDate>
<dc:creator>Laís Carvalho</dc:creator>
<category>Pydantic AI</category>
<category>Announcements</category>
<description>Rendreal turns a chat into a paid print order: artwork, quote, and checkout. Vstorm built every agent with Pydantic AI; Rendreal exposes their tools over MCP.</description>
<content:encoded><![CDATA[<p>Ask a general-purpose assistant for a leaflet and you get something that looks good on screen. It is not a print file, it has no price, and there is nowhere to send it. <a href="https://pydantic.dev/case-studies/rendreal">Rendreal</a> closes that gap: the customer describes what they need, gets print-ready artwork and a quote, and finishes with a checkout link, without leaving the conversation.</p>
<p>"I can imagine the future of services without websites," says Ram Zetuny, Founder and CEO of Rendreal. "But to make it happen for printed materials, agents need Rendreal to ensure print-ready design and fulfillment."</p>
<section id="ordering-print-still-meant-leaving-the-chat-section"><h2 id="ordering-print-still-meant-leaving-the-chat" role="presentation"><a href="#ordering-print-still-meant-leaving-the-chat" class="heading-anchor"><button type="button" class="heading-anchor__btn">#</button></a><span role="heading" aria-level="2">Ordering print still meant leaving the chat</span></h2>
<p>The old route runs through a printer's website. A customer works through a product configurator, then designs artwork in a browser tool, pays a designer, or uploads a file made somewhere else. Someone checks that file against the product: bleed, resolution, whether the text fits the space. When the file fails, the order waits.</p>
<p>Rendreal builds on experience from <a href="https://pydantic.dev/case-studies/mixam">Mixam</a>'s web-to-print business, where an agent on the printer's own site already guides customers through complex specifications. Rendreal asks the next question. What if the customer never visits the printer's website at all?</p>
</section><section id="one-set-of-tools-three-ways-in-section"><h2 id="one-set-of-tools-three-ways-in" role="presentation"><a href="#one-set-of-tools-three-ways-in" class="heading-anchor"><button type="button" class="heading-anchor__btn">#</button></a><span role="heading" aria-level="2">One set of tools, three ways in</span></h2>
<p>Vstorm, an official Pydantic implementation partner, built the system. Customers reach it through web chat, through a WhatsApp bot, or through any external assistant that connects to Rendreal's MCP server and calls its tools directly. Each channel handles its own conversation. All three share the same business services for products, designs, and orders, so a configuration means the same thing wherever the customer starts.</p>
<p>Behind the MCP tools sit specialist agents, one for product configuration and one for design. Vstorm orchestrated the main agent and every specialist with <a href="https://ai.pydantic.dev/">Pydantic AI</a>, so the whole system shares one set of typed tool definitions. The payoff lands at the last step. A print specification that reaches Rendreal's order validation is already well-formed, because Pydantic AI validated the tool arguments and structured outputs on the way through and sent malformed responses back to the model for another attempt.</p>
<p>The design service does the other hard part. A customer drops in assets, describes the goal, and gets a printable file for flyers, posters, business cards, postcards, or bookmarks. It can generate from a prompt, take reference material as direction, edit the current design, switch visual styles, and snapshot versions along the way.</p>
</section><section id="the-result-section"><h2 id="the-result" role="presentation"><a href="#the-result" class="heading-anchor"><button type="button" class="heading-anchor__btn">#</button></a><span role="heading" aria-level="2">The result</span></h2>
<p>Rendreal now offers a working path from a sentence to a paid print order across three channels and five product types, with every configuration checked against the catalog before a quote is issued. Because Pydantic AI is model-agnostic, moving to a newer model does not mean rewriting the agent logic, and the evaluation set stays with the system so the same tests run again when new models ship.</p>
<p>Rendreal is careful about what it claims. Assistants get tool access to Rendreal's own integrated services. It is not an open network of independent supplier agents that find each other and negotiate orders. That is where the company is heading, not what it says it has today.</p>
</section><section id="why-this-matters-section"><h2 id="why-this-matters" role="presentation"><a href="#why-this-matters" class="heading-anchor"><button type="button" class="heading-anchor__btn">#</button></a><span role="heading" aria-level="2">Why this matters</span></h2>
<p>Most products that want to be reachable from an assistant face the same shape of problem: the assistant can talk, but the business has rules the conversation cannot be allowed to break. Rendreal's answer is to expose the business as tools, keep one validated service layer behind every channel, and let typed schemas reject bad output inside the agent loop before it reaches the order system. That pattern transfers to anything with a catalog, a quote, and a checkout.</p>
<p>Read the <a href="https://pydantic.dev/case-studies/rendreal">Rendreal case study</a>, or the <a href="https://vstorm.co/case-study/rendreal-agent-to-agent-print-ordering/?utm_source=pydantic&#x26;utm_medium=partnership&#x26;utm_campaign=rendreal">full write-up on vstorm.co</a>. If you are building agents that other assistants can call, start with <a href="https://ai.pydantic.dev/mcp/client">Pydantic AI's MCP support</a>.</p></section>]]></content:encoded>
</item>
<item>
<title>Code mode: make your agents 2x faster and 2x cheaper on long tasks</title>
<link>https://pydantic.dev/articles/why-code-mode-is-the-future</link>
<guid isPermaLink="true">https://pydantic.dev/articles/why-code-mode-is-the-future</guid>
<pubDate>Wed, 28 Oct 2026 09:00:00 GMT</pubDate>
<dc:creator>Michael Pfaffenberger</dc:creator>
<category>Pydantic AI</category>
<category>Pydantic Monty</category>
<description>5,276 graded agent runs on eight models, from one-line edits to 200-item jobs. On long tasks code mode cut cost 58% and wall time 51% and got 16 points more right. On tiny ones it costs more. Here is all of it.</description>
<content:encoded><![CDATA[<picture>
<source media="(max-width: 600px)" srcset="/assets/blog/why-code-mode-is-the-future/hero-mobile.svg" width="600" height="808">
<img src="https://pydantic.dev/assets/blog/why-code-mode-is-the-future/hero.svg" alt="Illustration. On the left, tool calling: a model and its tools trade round trip after round trip, and the context the model re-reads grows on every lap. On the right, code mode: the model writes one Python program that pages through a cart, filters it and removes every expensive item, the program fans out into twelve tool calls, and only the answer comes back" width="1200" height="520" fetchpriority="high" decoding="async" style="width: 100%; height: auto; margin: 1.75rem auto; display: block;">
</picture>
<p>Everyone I talk to has an opinion about code mode right now. Mine was lit by Prime Intellect's <a href="https://www.primeintellect.ai/blog/prime-agent">Prime Agent</a>, a coding harness built around a persistent REPL, and by Alex Zhang's <a href="https://alexzhang13.github.io/blog/2026/spec-ptc/">speculative programmatic tool calling</a>, which (among other things) can run tools while the model is still streaming code. <a href="https://blog.cloudflare.com/code-mode/">Cloudflare</a> has one. <a href="https://www.anthropic.com/research/code-execution-with-mcp">Anthropic</a> has one. We've had a few of our own, from <a href="https://pydantic.dev/articles/your-agent-would-rather-write-code">MCP code execution</a> to <a href="https://pydantic.dev/articles/pydantic-monty">Pydantic Monty</a>. Coding agents are moving the same way: <a href="https://opencode.ai/v2/docs/mcp-servers/">OpenCode 2</a> now sends MCP tools through Code Mode by default, and <a href="https://pi.dev/docs/latest/codemode">Pi</a> ships a <code>codemode</code> tool. The pitch usually goes like this: stop making the model call your tools one at a time, let it write a little program that calls them instead, and everything gets cheaper, faster and better.</p>
<p>I believe that. But almost every number I'd seen came from agents with hundreds of tools or huge payloads, and many agents in the wild are boring: a handful of CRUD tools and a job to do. So I built a benchmark out of exactly that. Five small <a href="https://pydantic.dev/docs/ai/overview/">Pydantic AI</a> apps, single-item tools only, and three kinds of work: everyday requests, long multi-step jobs, and five tasks I could dial from 5 items to 200. Eight models, code mode off and on, 5,276 graded runs on an internal benchmark.</p>
<p>The short version: the longer the task, the bigger the win. And it gets big.</p>
<section id="tldr-section"><h2 id="tldr" role="presentation"><a href="#tldr" class="heading-anchor"><button type="button" class="heading-anchor__btn">#</button></a><span role="heading" aria-level="2">TL;DR</span></h2>
<ul>
<li><strong>On long tasks, code mode roughly halved cost and wall time.</strong> Across all eight models: cost <strong>-58%</strong>, wall time <strong>-51%</strong>, success <strong>+16.0 points</strong>. Without code mode 67 of 288 runs failed; with it, 21.</li>
<li><strong>It scales.</strong> For gpt-6.1-sol, every 100 extra items cost 30 to 79 seconds and $0.04 to $0.07 per run without code mode. With it: 4 to 9 seconds on four of the five tasks, and under a cent on three. At 200 items, code mode was 47% to 75% cheaper.</li>
<li><strong>Correctness falls off without it.</strong> From 5 items to 200, success without code mode dropped from 92-100% to 62-79%. With code mode it was 92-100% at 200.</li>
<li><strong>It isn't about round trips.</strong> Models already batch: one response carried 200 tool calls. At 200 items, averaged over the eight models, model requests fell by between 1% and 22% per task; deepseek-v4.1-flash on its own fell much further. What code mode cuts is what goes <em>into</em> each request.</li>
<li><strong>Small jobs pay a tax.</strong> At 5 items code mode cost more on three of the five tasks (+21% to +38%). On the 50 everyday tasks it was 16% cheaper overall, but success was flat (+1.6 points, noise).</li>
<li><strong>It's sandboxed, and it leaves a trail.</strong> In Pydantic AI Harness the model's code runs in Monty, which starts with no access to the host and, by default, stops any snippet after 30 seconds of execution time or at a 256 MiB heap. With Pydantic Logfire <a href="https://pydantic.dev/logfire/llm-observability">tracing the agent</a>, every tool call that code makes shows up as its own span.</li>
</ul>
<p>How much faster and cheaper each extra 100 items are with code mode on, for gpt-6.1-sol:</p>
<div class="overflow-x-auto table-wrapper" tabindex="0"><table>
<thead>
<tr>
<th>Task</th>
<th>Faster</th>
<th>Cheaper</th>
</tr>
</thead>
<tbody>
<tr>
<td>cart</td>
<td>7x</td>
<td>8x</td>
</tr>
<tr>
<td>calendar</td>
<td>9x</td>
<td>25x+</td>
</tr>
<tr>
<td>chat</td>
<td>5x</td>
<td>2.4x</td>
</tr>
<tr>
<td>kanban</td>
<td>20x</td>
<td>11x</td>
</tr>
<tr>
<td>inventory</td>
<td>2.2x</td>
<td>2.2x</td>
</tr>
</tbody>
</table></div>
<p>My read: models are much better at writing a loop than at being one, and the gap grows with the length of the task.</p>
</section><section id="the-loop-and-why-it-hurts-section"><h2 id="the-loop-and-why-it-hurts" role="presentation"><a href="#the-loop-and-why-it-hurts" class="heading-anchor"><button type="button" class="heading-anchor__btn">#</button></a><span role="heading" aria-level="2">The loop, and why it hurts</span></h2>
<p>In a normal tool-calling agent, the model picks a tool, emits some JSON, stops, waits for the harness to run it, reads the result, and picks again. The model sits in the middle of every step, and the costs compound: tool definitions crowd the context, every intermediate result flows through the model, and, the usual story goes, every tool call is another model turn that resends the whole growing context.</p>
<p>Code mode flips it. The tools become functions inside a sandbox, the model writes one program that loops and branches over them, and only the result comes back. In <a href="https://pydantic.dev/docs/ai/harness/code-mode/">Pydantic AI Harness</a> that sandbox is <a href="https://pydantic.dev/articles/pydantic-monty">Monty</a>, our Python interpreter written in Rust, and the model sees a single <code>run_code</code> tool.</p>
<picture>
<source media="(max-width: 600px)" srcset="/assets/blog/why-code-mode-is-the-future/loop-vs-code-mobile.svg" width="480" height="1102">
<img src="https://pydantic.dev/assets/blog/why-code-mode-is-the-future/loop-vs-code.svg" alt="Schematic of one task done two ways. Tool calling: a loop of model, tool call and result, 25 tool calls, with the context the model re-reads growing across five requests. Code mode: the model calls run_code once per step, a Monty sandbox makes 3 list_items calls and 22 remove_item calls and does the filtering in Python, and the context stays small apart from the code mode guidance added to every request" width="960" height="610" loading="lazy" decoding="async" style="width: 100%; height: auto; margin: 1.75rem auto; display: block;">
</picture>
<p>Here's one of the 50 tasks, verbatim: <em>"can you get rid of everything in my cart that costs more than $50 a piece? it's getting out of hand"</em>. The cart has 122 lines, a list tool that returns at most 50 per page, and a remove tool that takes one id. 22 lines need to go. Without code mode that's three pages of listing and 22 removes, every one of them chosen by the model. With code mode, it's this:</p>
<pre><code class="hljs language-python"><span class="hljs-keyword">import</span> asyncio

items, offset = [], <span class="hljs-number">0</span>
<span class="hljs-keyword">while</span> offset <span class="hljs-keyword">is</span> <span class="hljs-keyword">not</span> <span class="hljs-literal">None</span>:
    page = <span class="hljs-keyword">await</span> list_items(offset=offset, limit=<span class="hljs-number">50</span>)
    items += page[<span class="hljs-string">"items"</span>]
    offset = page[<span class="hljs-string">"next_offset"</span>]

pricey = [i <span class="hljs-keyword">for</span> i <span class="hljs-keyword">in</span> items <span class="hljs-keyword">if</span> i[<span class="hljs-string">"unit_price"</span>] > <span class="hljs-number">50</span>]
<span class="hljs-keyword">await</span> asyncio.gather(*(remove_item(item_id=i[<span class="hljs-string">"id"</span>]) <span class="hljs-keyword">for</span> i <span class="hljs-keyword">in</span> pricey))
<span class="hljs-built_in">len</span>(pricey)
</code></pre>
<p>The model never reads the 100 cheap lines. It doesn't have to remember which ids it already removed. The comparison <code>> 50</code> is done by Python, not by a language model squinting at a float.</p>
</section><section id="code-mode-with-guardrails-section"><h2 id="code-mode-with-guardrails" role="presentation"><a href="#code-mode-with-guardrails" class="heading-anchor"><button type="button" class="heading-anchor__btn">#</button></a><span role="heading" aria-level="2">Code mode with guardrails</span></h2>
<p>That program is code a model wrote, and something has to run it. What that something lets the code touch is the biggest design decision in code mode.</p>
<p>Prime Agent makes the open choice. Its model's only tool is a persistent IPython kernel, and the rest of the harness, sub-agents included, lives in that kernel as functions. An IPython kernel is a full Python process: unless something around it says otherwise, the code can import any library, read and write files and open network connections. For a coding assistant on your own machine, that's what you want. It's not something I'd put in a web server and let every user's prompt drive.</p>
<p>Pydantic AI Harness makes the opposite choice. <code>CodeMode</code> runs the model's program in <a href="https://pydantic.dev/articles/pydantic-monty">Monty</a>, our Python interpreter written in Rust, which starts from nothing and adds only what you allow:</p>
<ul>
<li><strong>No host access by default.</strong> Sandboxed code <a href="https://pydantic.dev/docs/ai/harness/code-mode/#filesystem-and-os-access">starts with no access</a> to the host's files, environment or clock, and there is no network. If the agent needs a directory, an environment variable or the time, you grant it per request. This benchmark granted the built-in <code>OSAccess</code> handler: an in-memory filesystem and environment, and the host clock.</li>
<li><strong>Your tools are the way out.</strong> The program reaches the world through the functions you register, plus any OS access you grant it, and each tool call goes through Pydantic AI to your real tool. It can do what those allow, and nothing else.</li>
<li><strong>Hard limits.</strong> By default each <code>run_code</code> snippet gets 30 seconds of execution time and a 256 MiB heap (<a href="https://pydantic.dev/docs/ai/harness/code-mode/">details</a>), which is what stops a runaway loop.</li>
<li><strong>Fast to start.</strong> Each Monty session runs in a local worker process, and a <a href="https://github.com/pydantic/monty">new sandbox</a> takes under a millisecond from a running pool, so the guardrails don't add a container start to every snippet.</li>
</ul>
<p>So you get code mode with guardrails. Every code mode run in this benchmark ran in Monty.</p>
</section><section id="the-code-is-the-graph-section"><h2 id="the-code-is-the-graph" role="presentation"><a href="#the-code-is-the-graph" class="heading-anchor"><button type="button" class="heading-anchor__btn">#</button></a><span role="heading" aria-level="2">The code is the graph</span></h2>
<p>Samuel wrote a whole post about this, <a href="https://pydantic.dev/articles/the-code-is-the-graph">The code is the graph</a>, and if you build agents you should read it. His argument is that graph libraries rebuild control flow badly: "<code>if</code> is a branch. <code>for</code> is a loop. A function call is an edge", and <code>asyncio.gather</code> is a fan-out and a join. Or in his words about a five-line example: "Fan out, join, branch. That is a graph, and it's also a Python function."</p>
<p>The program above is exactly that. Here's the graph it encodes:</p>
<picture>
<source media="(max-width: 600px)" srcset="/assets/blog/why-code-mode-is-the-future/code-is-the-graph-mobile.svg" width="480" height="812">
<img src="https://pydantic.dev/assets/blog/why-code-mode-is-the-future/code-is-the-graph.svg" alt="A ten-line Python program that pages through a cart, filters lines over $50, removes them with asyncio.gather and returns the count, next to the graph it encodes: a list_items node with a next-page cycle, a filter node, a fan-out to 22 remove calls, a join, and the answer. The while loop is the cycle, the comprehension is the filter, gather is the fan-out and the return value is the join" width="960" height="522" loading="lazy" decoding="async" style="width: 100%; height: auto; margin: 1.75rem auto; display: block;">
</picture>
<p>I wrote that program for the figure, but the models write the same shape on their own in the benchmark, at run time, for a task they've never seen (in one cart run, gpt-6.1-sol spread it over three <code>run_code</code> calls). Nobody drew that graph in advance. That's the bit that makes me think code mode is where agents are going: the model isn't just calling your tools more cheaply, it's designing the workflow on the fly.</p>
<p>But this is a blog post with a benchmark in it, so let's find out whether any of that is true.</p>
</section><section id="the-benchmark-section"><h2 id="the-benchmark" role="presentation"><a href="#the-benchmark" class="heading-anchor"><button type="button" class="heading-anchor__btn">#</button></a><span role="heading" aria-level="2">The benchmark</span></h2>
<p>The benchmark is trivial on purpose. Five tiny Pydantic AI apps: a shopping cart, a calendar, a chatroom, a kanban board and an inventory system. Each one has only single-item CRUD tools (list, get, create, update, delete), with paginated lists. No shell, no filesystem, no bulk endpoints. If the agent wants to change 200 things, it has to make 200 calls, or write a loop.</p>
<p>No single step here is hard. What's hard is doing an easy step a few hundred times, in the right order, without losing count, and that's the part I wanted to isolate: iteration over a long horizon. The code is the graph. Let your agent write the graph.</p>
<p>On top of those apps sit three tiers of work:</p>
<picture>
<source media="(max-width: 600px)" srcset="/assets/blog/why-code-mode-is-the-future/benchmark-design-mobile.svg" width="480" height="957">
<img src="https://pydantic.dev/assets/blog/why-code-mode-is-the-future/benchmark-design.svg" alt="The benchmark design. Five apps (cart, calendar, chat, kanban, inventory) with single-item CRUD tools only, and three tiers, each run on eight models. Everyday: 50 tests, 10 per app, 4 reps, 3,500 runs, about 13 tool calls per run without code mode. Long horizon: 12 multi-step tests over 60 to 500 records, 3 reps, 576 runs, about 68 tool calls per run. Scaling: one task per app at N = 5, 20, 50, 100 and 200 items, 3 reps, 1,200 runs, 168 tool calls per run at N = 200. Each tile is one tool call. 5,276 graded runs, deterministic graders, no LLM judge" width="960" height="479" loading="lazy" decoding="async" style="width: 100%; height: auto; margin: 1.75rem auto; display: block;">
</picture>
<ul>
<li><strong>Everyday:</strong> 50 tests, ten per app. Single edits, bulk changes, rules with branches, lookups and sums. Without code mode, a run made about 13 tool calls.</li>
<li><strong>Long horizon:</strong> 12 multi-step jobs over 60 to 500 records, two per app and two that cross apps. <em>"Alex is leaving the team. go through Alex's open tasks (not done) in order of id: if it's urgent or high priority, give it to whoever has the fewest open points at that moment..."</em> About 68 tool calls per run.</li>
<li><strong>Scaling:</strong> one task per app, with the same rule at N = 5, 20, 50, 100 and 200 items. <em>"I have a pile of meeting invites I never answered. for each one: accept it if it's on a weekday and ends by 5pm, decline it if it's on a weekend or ends after 5pm."</em> At N = 200, runs without code mode averaged 168 tool calls.</li>
</ul>
<p>Each app is a Pydantic AI agent. With code mode on, it gets Pydantic AI Harness's <a href="https://pydantic.dev/docs/ai/harness/code-mode/"><code>CodeMode</code></a> capability with <a href="https://pydantic.dev/docs/ai/harness/code-mode/#eager-execution">eager execution</a>, which can start running a complete statement before the model finishes writing the <code>run_code</code> call. With code mode off, the same agent calls the same tools directly. Everything was pinned to one commit, and code mode was flipped with a single setting, so the only difference between arms is code mode itself. The prompts are written the way a person actually types, and every run is graded by a deterministic oracle: the app's end state has to match the expected state exactly (money within a cent), and the reply has to contain the right numbers. No LLM judge.</p>
<aside class="callout callout-note"><div class="callout-indicator"><svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="2" aria-hidden="true"><path d="M12 8h.01M12 12v4"></path><circle cx="12" cy="12" r="10"></circle></svg><div class="callout-title">Methodology</div></div><div class="callout-content"><ul>
<li><strong>Availability:</strong> the benchmark code isn't public, so this note gives the full setup: versions, models, cost, arms, runs, validation and statistics, plus its known warts.</li>
<li><strong>System under test:</strong> Pydantic AI <code>2.56.1.dev13</code> and Pydantic AI Harness <code>0.56.1.dev13</code>, both built from <code>pydantic/pydantic-ai</code> commit <code>b82f0f258f4d</code>, the same settings in every arm apart from code mode.</li>
<li><strong>Models:</strong> <code>gpt-6.1-sol</code>, <code>gpt-6-luna</code> and <code>gpt-6-astra</code> through a Codex subscription, <code>claude-sonnet-5-5</code> and <code>claude-haiku-5-5</code> through a Claude Code subscription, <code>muse-spark-1.3-contributor</code> and <code>muse-wonder-1.0-contributor</code> through Meta's contributor API, and <code>deepseek-v4.1-flash</code> on our own vLLM server. All eight ran every tier, each with its provider's default settings.</li>
<li><strong>Cost:</strong> API list prices from <code>genai-prices</code> for the GPT and Claude models. It has no prices for the other three, so their runs are priced from their recorded tokens: the Muse models at Meta's standard list prices for <code>muse-spark-1.3</code> and <code>muse-wonder-1.0</code> (not the cheaper contributor rates), and <code>deepseek-v4.1-flash</code> at its price in OpenRouter's model catalog on October 22, 2026 (<a href="https://web.archive.org/web/20261023141351/https://openrouter.ai/api/v1/models">archived copy</a>): $0.30 per million input tokens, $0.006 cached and $1.20 output. That's also the most common rate across the model's 40 provider endpoints there (12 charge it). Input prices ranged from $0.07 to $0.60, so your deepseek bill depends on where you run it.</li>
<li><strong>Arms:</strong> code mode off (plain tool calling) and code mode on (<code>CodeMode(eager=True)</code> with the default resource limits and the built-in <code>OSAccess</code> handler: an in-memory filesystem and environment, and the host clock). The first everyday batch also ran code mode with speculative execution.</li>
<li><strong>Runs:</strong> everyday 3,500 (50 tests × 2 arms × 8 models × 4 reps, plus a third arm in the first batch); long horizon 576 (12 tests × 2 arms × 8 models × 3 reps); scaling 1,200 (25 tests × 2 arms × 8 models × 3 reps). 5,276 graded runs in randomized blocks. 27 infrastructure failures were retried. No run timed out, and no cell is missing.</li>
<li><strong>Validation before any model run:</strong> for every test, the untouched seed fails its grader, a scripted reference solution passes, and a deliberately wrong one (a missed page, an off-by-one boundary) fails.</li>
<li><strong>Statistics:</strong> task-balanced means and 95% bootstrap intervals over tests, planned before each batch ran. The benchmark grew in stages, each planned after the previous results were in: the GPT models first, then the Claude models and the long and scaling tiers, then the Muse and deepseek models. Pooling all eight models in every tier was decided before their last batches ran, and the Muse and deepseek prices were added after every run had finished. deepseek-v4.1-flash's everyday runs shared its server with up to 15 others, so compare its wall time across arms, not across tiers.</li>
<li><strong>Known warts:</strong> two prompts are ambiguous, one everyday and one long ("how many lines are still in the cart"). Both are graded as frozen. Leaving them out changes no headline by more than a point.</li>
</ul></div></aside>
<p>Everything below compares code mode on to code mode off.</p>
</section><section id="the-longer-the-task-the-bigger-the-gap-section"><h2 id="the-longer-the-task-the-bigger-the-gap" role="presentation"><a href="#the-longer-the-task-the-bigger-the-gap" class="heading-anchor"><button type="button" class="heading-anchor__btn">#</button></a><span role="heading" aria-level="2">The longer the task, the bigger the gap</span></h2>
<p>Start with the scaling tier, because it's the cleanest experiment in the whole benchmark: same app, same rule, same prompt, and the only thing that changes is how many items the rule touches. Here's gpt-6.1-sol on all five tasks, wall time on top and cost below:</p>
<picture>
<source media="(max-width: 600px)" srcset="/assets/blog/why-code-mode-is-the-future/chart-scale-curves-mobile.svg" width="480" height="1096">
<img src="https://pydantic.dev/assets/blog/why-code-mode-is-the-future/chart-scale-curves.svg" alt="Wall time and cost per run against N for gpt-6.1-sol on five tasks. Without code mode both climb steeply with N; at N = 200 wall time is 147 s for cart, 119 s for calendar, 71 s for chat, 167 s for kanban and 141 s for inventory. With code mode the lines stay nearly flat, at 25 to 32 seconds, except inventory at 73 s. Cost at N = 200 falls from $0.08 to $0.15 without code mode to $0.02 to $0.07 with it" width="960" height="646" loading="lazy" decoding="async" style="width: 100%; height: auto; margin: 1.75rem auto; display: block;">
</picture>
<p>Without code mode, both lines climb with every item. That's what tool calling <em>is</em>: every item is a call the model has to write, and every result is something it has to read back. For gpt-6.1-sol, each extra 100 items added 30 to 79 seconds and $0.04 to $0.07 per run.</p>
<p>With code mode, four of the five lines are close to flat. Closing out a sprint of 200 cards took 166.6 seconds without code mode and 26.6 seconds with it. Each extra 100 cards added 79 seconds without code mode and 4 seconds with it.</p>
<p>What each extra 100 items cost gpt-6.1-sol, per task:</p>
<div class="overflow-x-auto table-wrapper" tabindex="0"><table>
<thead>
<tr>
<th>Task</th>
<th>Code mode off</th>
<th>Code mode on</th>
</tr>
</thead>
<tbody>
<tr>
<td>cart</td>
<td>+66 s, +$0.065</td>
<td>+9 s, +$0.008</td>
</tr>
<tr>
<td>calendar</td>
<td>+54 s, +$0.068</td>
<td>+6 s, +$0.002</td>
</tr>
<tr>
<td>chat</td>
<td>+30 s, +$0.039</td>
<td>+6 s, +$0.016</td>
</tr>
<tr>
<td>kanban</td>
<td>+79 s, +$0.067</td>
<td>+4 s, +$0.006</td>
</tr>
<tr>
<td>inventory</td>
<td>+63 s, +$0.061</td>
<td>+29 s, +$0.028</td>
</tr>
</tbody>
</table></div>
<p>Inventory is the exception, and it's a fair one: the delivery is pasted into the prompt as a list of N lines, so with or without code mode, the model has to read all of it.</p>
<p>Across all eight models, here's where code mode starts to pay:</p>
<picture>
<source media="(max-width: 600px)" srcset="/assets/blog/why-code-mode-is-the-future/chart-scale-change-mobile.svg" width="480" height="940">
<img src="https://pydantic.dev/assets/blog/why-code-mode-is-the-future/chart-scale-change.svg" alt="Change with code mode against off by N, mean of the per-model changes over eight models. Cost: at N = 5, cart minus 11%, calendar plus 21%, chat plus 38%, kanban plus 35%, inventory plus 3% (noise); at N = 200, minus 71%, minus 75%, minus 51%, minus 66% and minus 47%. Wall time at N = 200: minus 67%, minus 61%, minus 45%, minus 65%, minus 42%. Model requests at N = 200 fall by 1% to 22%, most within noise" width="960" height="442" loading="lazy" decoding="async" style="width: 100%; height: auto; margin: 1.75rem auto; display: block;">
</picture>
<p>At 5 items, code mode costs more on three of the five tasks, by 21% to 38%. Its guidance rides along on every request, and five calls is not much work to fold into a loop. By 50 items it's cheaper on four of the five, and by 200 it saves 47% to 75% of the cost and 42% to 67% of the wall time on every task.</p>
<p>Look at the bottom panel, though: even at 200 items, model requests barely move on average, down 1% to 22%. More on that below.</p>
<p>And then there's correctness:</p>
<picture>
<source media="(max-width: 600px)" srcset="/assets/blog/why-code-mode-is-the-future/chart-scale-success-mobile.svg" width="480" height="794">
<img src="https://pydantic.dev/assets/blog/why-code-mode-is-the-future/chart-scale-success.svg" alt="Share of runs graded correct by N, pooled over eight models, 24 runs per arm at each N. Without code mode success falls from 92 to 100% at N = 5 to 75% for cart, 79% for calendar, 62% for chat, 75% for kanban and 75% for inventory at N = 200. With code mode it ends at 92%, 92%, 100%, 96% and 92%. Over all sizes: 518 of 600 runs correct without code mode, 577 of 600 with it" width="960" height="443" loading="lazy" decoding="async" style="width: 100%; height: auto; margin: 1.75rem auto; display: block;">
</picture>
<p>Without code mode, success slides as N grows: from 92-100% at 5 items to 62-79% at 200. With code mode it ends at 92-100%. Across every size, that's 518 of 600 runs right without code mode and 577 of 600 with it. Per size the samples are small (24 runs per arm), and only 5 of the 25 gaps clear zero on their own, but the direction is the same on all five tasks: at 200 items, code mode was ahead on every one.</p>
<p>The weakest model shows it most. At 200 items gpt-6-luna got <strong>0 of 15</strong> runs right without code mode, and in 7 of them it never changed anything. It just explained why it couldn't:</p>
<blockquote>
<p>I found 200 cards labelled <code>sprint-42</code>, but I haven't changed them yet: the board tools require updating each card individually, and the card list is too large to safely process in a single operation here.</p>
</blockquote>
<p>With code mode, the same model got 8 of those 15 right. It wasn't a crash, a timeout or a context overflow: no run without code mode had any of those. It's a model looking at 200 calls and declining to make them.</p>
<p>Some models never missed with code mode. Across all five tasks, muse-spark-1.3-contributor, muse-wonder-1.0-contributor and deepseek-v4.1-flash got all 225 of their code mode runs right, against 202 of 225 without.</p>
<div class="overflow-x-auto table-wrapper" tabindex="0"><table>
<thead>
<tr>
<th>Model</th>
<th>Correct runs, off → on</th>
<th>Wall time at 200 items</th>
</tr>
</thead>
<tbody>
<tr>
<td>muse-spark-1.3-contributor</td>
<td>65 → 75 of 75</td>
<td>-28% to -50%</td>
</tr>
<tr>
<td>muse-wonder-1.0-contributor</td>
<td>75 → 75 of 75</td>
<td>-41% to -61%</td>
</tr>
<tr>
<td>deepseek-v4.1-flash</td>
<td>62 → 75 of 75</td>
<td>-58% to -87%</td>
</tr>
</tbody>
</table></div>
<p>Eight of muse-spark-1.3-contributor's ten failures were one habit: it triaged the chat correctly, then posted a summary as a new message in #support, which the prompt didn't ask for. As graded, those runs are wrong. Ignore the posted messages and it got 14 of 15 chat runs right without code mode. With code mode it never posted one.</p>
</section><section id="one-task-at-200-items-section"><h2 id="one-task-at-200-items" role="presentation"><a href="#one-task-at-200-items" class="heading-anchor"><button type="button" class="heading-anchor__btn">#</button></a><span role="heading" aria-level="2">One task at 200 items</span></h2>
<p>One of those runs, up close: gpt-6.1-sol answering 200 invites, both arms graded correct.</p>
<picture>
<source media="(max-width: 600px)" srcset="/assets/blog/why-code-mode-is-the-future/one-run-200-mobile.svg" width="480" height="750">
<img src="https://pydantic.dev/assets/blog/why-code-mode-is-the-future/one-run-200.svg" alt="One calendar task at N = 200 for gpt-6.1-sol, both runs correct. Without code mode: 8 model requests, 205 tool calls, 183,723 input tokens, 4,430 output tokens, 119.5 seconds, $0.1425. With code mode: 6 requests (minus 25%), 215 tool calls, 34,461 input tokens (minus 81%), 573 output tokens (minus 87%), 28.5 seconds (minus 76%), $0.0231 (minus 84%)" width="960" height="564" loading="lazy" decoding="async" style="width: 100%; height: auto; margin: 1.75rem auto; display: block;">
</picture>
<p>Without code mode it made 205 tool calls, packed into 7 responses, up to 43 in one. The batching was already good. The trouble is what each request carries: the conversation so far, including every tool result. By the end it had read 183,723 input tokens, written 4,430 output tokens to spell out those 205 calls and the answer, and taken two minutes.</p>
<p>With code mode it wrote 5 snippets, the calendar served 215 calls, and the model read 34,461 tokens and wrote 573. Wall time fell 76%, cost 84%. Requests went from 8 to 6.</p>
</section><section id="models-already-batch-section"><h2 id="models-already-batch" role="presentation"><a href="#models-already-batch" class="heading-anchor"><button type="button" class="heading-anchor__btn">#</button></a><span role="heading" aria-level="2">Models already batch</span></h2>
<p>I assumed going in that "remove 22 items" meant 22 round trips without code mode. It doesn't. Modern models emit <a href="https://developers.openai.com/api/docs/guides/function-calling#parallel-function-calling">parallel tool calls</a>, and they emit a lot of them. In the long tier, the busiest single response carried 77 calls from gpt-6.1-sol and 119 from both Claude models. At 200 items, claude-haiku-5-5 put all 200 calls in one response.</p>
<p>So round trips don't fall the way the pitch says, at least not for the models that batch hardest. Across the long tier, model requests fell 22%, but it depends on the model. The GPT models made a third fewer requests (-33%), and the Claude models made <em>more</em>, +24% for claude-haiku-5-5 and +26% for claude-sonnet-5-5. Without code mode they fire one huge burst; with it they write about five short snippets per run and read each result before writing the next. They still cost 67% and 70% less. The models that batch least gained the most: muse-spark-1.3-contributor, muse-wonder-1.0-contributor and deepseek-v4.1-flash put at most 25 to 50 calls in one response, made 13 to 22 requests per run without code mode, and 27% to 52% fewer with it (muse-spark-1.3-contributor's drop is within noise).</p>
<p>This is where I'd push on the usual pitch, that every tool call costs another model turn. For independent calls on current models, that mostly isn't true. What still costs a turn is a <em>dependent</em> step: you can't answer an invite until you've listed the page it's on. What code mode removes is the part of each turn that grows with the work: the calls the model has to write out, and the results it has to read back in.</p>
<p>The exception is deepseek-v4.1-flash. It does batch, up to 80 calls in one response, but at 200 items without code mode it averaged 64 requests per run (up to 171) and read 2.8 million input tokens. With code mode: 11 requests and 86,000 tokens. Answering 200 invites took it 1,070 seconds per run without code mode and 138 with it. It ran on one vLLM server whose load we didn't control, so read its seconds loosely; the requests and tokens don't depend on the server.</p>
</section><section id="long-horizon-tasks-cheaper-faster-and-right-more-often-section"><h2 id="long-horizon-tasks-cheaper-faster-and-right-more-often" role="presentation"><a href="#long-horizon-tasks-cheaper-faster-and-right-more-often" class="heading-anchor"><button type="button" class="heading-anchor__btn">#</button></a><span role="heading" aria-level="2">Long-horizon tasks: cheaper, faster, and right more often</span></h2>
<p>The long tier is the closest thing here to real agent work: a dozen steps, rules that interact, and a few hundred records to keep straight. <em>"supplier price update plus some housekeeping, in this order: 1. raise the unit cost of every fastener and every electrical product by 6%..."</em></p>
<picture>
<source media="(max-width: 600px)" srcset="/assets/blog/why-code-mode-is-the-future/chart-long-success-mobile.svg" width="480" height="926">
<img src="https://pydantic.dev/assets/blog/why-code-mode-is-the-future/chart-long-success.svg" alt="Share of long-horizon runs graded correct, code mode off versus on. gpt-6.1-sol 92% to 100% (noise), gpt-6-luna 14% to 58%, gpt-6-astra 86% to 92% (noise), claude-haiku-5-5 64% to 94%, claude-sonnet-5-5 83% to 100%, muse-spark-1.3-contributor 94% to 97% (noise), muse-wonder-1.0-contributor 100% in both, deepseek-v4.1-flash 81% to 100%; all models plus 16.0 points" width="960" height="713" loading="lazy" decoding="async" style="width: 100%; height: auto; margin: 1.75rem auto; display: block;">
</picture>
<p>Code mode was right at least as often on every model, and the weaker the model, the bigger the jump: gpt-6-luna went from 14% to <strong>58%</strong>, claude-haiku-5-5 from 64% to <strong>94%</strong>, deepseek-v4.1-flash from 81% to <strong>100%</strong>. gpt-6.1-sol and claude-sonnet-5-5 reached 100% too, and muse-wonder-1.0-contributor didn't miss in either arm.</p>
<p>And it did that while cutting cost and wall time on every model, every interval clear of zero:</p>
<picture>
<source media="(max-width: 600px)" srcset="/assets/blog/why-code-mode-is-the-future/chart-long-deltas-mobile.svg" width="480" height="2498">
<img src="https://pydantic.dev/assets/blog/why-code-mode-is-the-future/chart-long-deltas.svg" alt="Change with code mode against off on the long tests, per model, with 95% intervals, in the order gpt-6.1-sol, gpt-6-luna, gpt-6-astra, claude-haiku-5-5, claude-sonnet-5-5, muse-spark-1.3-contributor, muse-wonder-1.0-contributor, deepseek-v4.1-flash. Cost: minus 55%, minus 30%, minus 59%, minus 67%, minus 70%, minus 55%, minus 56%, minus 73%, all models minus 58%. Wall time: minus 62%, minus 21%, minus 61%, minus 58%, minus 62%, minus 39%, minus 50%, minus 56%, all minus 51%. Model requests: minus 43%, minus 5% (noise), minus 50%, plus 24%, plus 26%, minus 27% (noise), minus 52%, minus 48%, all minus 22%. Success: plus 8.3 (noise), plus 44.4, plus 5.6 (noise), plus 30.6, plus 16.7, plus 2.8 (noise), 0, plus 19.4, all plus 16.0 points" width="960" height="827" loading="lazy" decoding="async" style="width: 100%; height: auto; margin: 1.75rem auto; display: block;">
</picture>
<p>In dollars and seconds per run:</p>
<div class="overflow-x-auto table-wrapper" tabindex="0"><table>
<thead>
<tr>
<th>Model</th>
<th>Cost per run</th>
<th>Wall time</th>
</tr>
</thead>
<tbody>
<tr>
<td>gpt-6.1-sol</td>
<td>$0.074 → $0.033 (<strong>-55%</strong>)</td>
<td>75.0 → 28.2 s (<strong>-62%</strong>)</td>
</tr>
<tr>
<td>gpt-6-luna</td>
<td>$0.0029 → $0.0021 (<strong>-30%</strong>)</td>
<td>48.5 → 38.2 s (<strong>-21%</strong>)</td>
</tr>
<tr>
<td>gpt-6-astra</td>
<td>$0.365 → $0.149 (<strong>-59%</strong>)</td>
<td>72.8 → 28.4 s (<strong>-61%</strong>)</td>
</tr>
<tr>
<td>claude-haiku-5-5</td>
<td>$0.0127 → $0.0042 (<strong>-67%</strong>)</td>
<td>55.2 → 23.0 s (<strong>-58%</strong>)</td>
</tr>
<tr>
<td>claude-sonnet-5-5</td>
<td>$0.176 → $0.053 (<strong>-70%</strong>)</td>
<td>56.7 → 21.6 s (<strong>-62%</strong>)</td>
</tr>
<tr>
<td>muse-spark-1.3-contributor</td>
<td>$0.245 → $0.110 (<strong>-55%</strong>)</td>
<td>137.0 → 84.1 s (<strong>-39%</strong>)</td>
</tr>
<tr>
<td>muse-wonder-1.0-contributor</td>
<td>$0.470 → $0.207 (<strong>-56%</strong>)</td>
<td>57.8 → 29.1 s (<strong>-50%</strong>)</td>
</tr>
<tr>
<td>deepseek-v4.1-flash</td>
<td>$0.027 → $0.0072 (<strong>-73%</strong>)</td>
<td>311.9 → 136.4 s (<strong>-56%</strong>)</td>
</tr>
<tr>
<td>all models</td>
<td><strong>-58%</strong></td>
<td><strong>-51%</strong></td>
</tr>
</tbody>
</table></div>
<p>The failures without code mode are the same kind I saw on the everyday tasks, just more of them: arithmetic and bookkeeping over hundreds of records. In the supplier-price test, 16 of 24 runs without code mode failed, against 1 of 24 with it. Six of those runs, from three different models, reported a stock value of $1,671,683.13. The right answer was $1,671,682.13, and their own end states were worth exactly that. The edits were fine; the sum in the reply was not. Every code mode run that gave a value gave $1,671,682.13.</p>
<p>Counting every failure in the long tier, without code mode: 52 wrong end states, 11 right end states with a wrong reply, and 4 runs that changed nothing (all gpt-6-luna). With code mode: 16, 5 and 0.</p>
</section><section id="where-the-tokens-go-section"><h2 id="where-the-tokens-go" role="presentation"><a href="#where-the-tokens-go" class="heading-anchor"><button type="button" class="heading-anchor__btn">#</button></a><span role="heading" aria-level="2">Where the tokens go</span></h2>
<p>The token picture is what explains the cost:</p>
<picture>
<source media="(max-width: 600px)" srcset="/assets/blog/why-code-mode-is-the-future/chart-long-tokens-mobile.svg" width="480" height="1304">
<img src="https://pydantic.dev/assets/blog/why-code-mode-is-the-future/chart-long-tokens.svg" alt="Tokens per long-horizon run, code mode off versus on. Output tokens fall on every model: gpt-6.1-sol 2,428 to 688, gpt-6-luna 1,339 to 765, gpt-6-astra 2,209 to 669, claude-haiku-5-5 15,506 to 4,065, claude-sonnet-5-5 9,856 to 1,970, muse-spark-1.3-contributor 15,470 to 7,566, muse-wonder-1.0-contributor 10,348 to 3,211, deepseek-v4.1-flash 11,966 to 3,726. Input tokens fall too: 76,256 to 30,945, 49,739 to 39,611, 84,162 to 31,423, 104,140 to 75,474, 83,747 to 54,891, 659,026 to 220,188, 255,810 to 90,258, 601,528 to 71,882" width="960" height="725" loading="lazy" decoding="async" style="width: 100%; height: auto; margin: 1.75rem auto; display: block;">
</picture>
<p>Output tokens fell 66% across the eight models, from -43% on gpt-6-luna to -80% on claude-sonnet-5-5. Output is the slow, expensive part, and it's what the model spends writing out every call and every intermediate value. Input tokens fell 53% too, because fewer results pile up in the context.</p>
<p>On short tasks the input side goes the other way. Code mode's guidance (how <code>run_code</code> works, what's available in the sandbox) adds about 2,600 characters to every request, a flat fee you pay per request no matter how small the job. On the everyday tasks input rose 29% while output fell 37%. At 5 items in the scaling tier total tokens rose 65% to 114%. That flat fee is most of the tax, and on long work it disappears into the savings.</p>
</section><section id="everyday-tasks-cheaper-about-as-correct-section"><h2 id="everyday-tasks-cheaper-about-as-correct" role="presentation"><a href="#everyday-tasks-cheaper-about-as-correct" class="heading-anchor"><button type="button" class="heading-anchor__btn">#</button></a><span role="heading" aria-level="2">Everyday tasks: cheaper, about as correct</span></h2>
<p>The 50 everyday tests are short: four or five requests and a dozen tool calls each. This is where I started, and where code mode's case is quietest.</p>
<div class="overflow-x-auto table-wrapper" tabindex="0"><table>
<thead>
<tr>
<th>Model (4 reps, 3,200 runs)</th>
<th>Success</th>
<th>Cost per run</th>
</tr>
</thead>
<tbody>
<tr>
<td>gpt-6.1-sol</td>
<td>96% → 98% (noise)</td>
<td><strong>-9%</strong></td>
</tr>
<tr>
<td>gpt-6-luna</td>
<td><strong>66% → 85%</strong></td>
<td><strong>+19%</strong></td>
</tr>
<tr>
<td>gpt-6-astra</td>
<td><strong>94% → 98%</strong></td>
<td>-7% (noise)</td>
</tr>
<tr>
<td>claude-haiku-5-5</td>
<td>96% → 96% (noise)</td>
<td><strong>-40%</strong></td>
</tr>
<tr>
<td>claude-sonnet-5-5</td>
<td>97% → 95% (noise)</td>
<td><strong>-38%</strong></td>
</tr>
<tr>
<td>muse-spark-1.3-contributor</td>
<td><strong>98% → 92%</strong> (worse)</td>
<td><strong>-13%</strong></td>
</tr>
<tr>
<td>muse-wonder-1.0-contributor</td>
<td>98% → 94% (noise)</td>
<td>-8% (noise)</td>
</tr>
<tr>
<td>deepseek-v4.1-flash</td>
<td>96% → 95% (noise)</td>
<td><strong>-34%</strong></td>
</tr>
<tr>
<td>all models</td>
<td>+1.6 pts (noise)</td>
<td><strong>-16%</strong></td>
</tr>
</tbody>
</table></div>
<p>Across all eight models, code mode was 16% cheaper and 11% faster, and right about as often. The average hides a split. Most of the models were already right 94% to 98% of the time without code mode, and stayed there. gpt-6-luna is the exception, and most of its gain is on questions. In the first batch, twelve of the tests asked for a number ("what's my cart total going to be if dairy is 10% off?"), and gpt-6-luna got 38% of them right without code mode and 88% with it. Without code mode the models added up 30 to 120 rows in their heads and missed, stopped after two of three pages, or just declined: <em>"I can't reliably calculate the total from this many cart lines."</em> In the other direction, muse-spark-1.3-contributor was right less often with code mode, and every one of those misses left the app in the wrong state.</p>
<p>Splitting by kind of task shows where the tax lands:</p>
<picture>
<source media="(max-width: 600px)" srcset="/assets/blog/why-code-mode-is-the-future/chart-categories-mobile.svg" width="480" height="1172">
<img src="https://pydantic.dev/assets/blog/why-code-mode-is-the-future/chart-categories.svg" alt="Change with code mode by everyday test category, mean of the eight models, 4 reps. Success: aggregate plus 8.1 points (90% to 98%), conditional plus 2.5 (90% to 93%), bulk minus 5 (95% to 90%), sequence plus 2.5 (82% to 85%), lookup plus 0.3, control plus 1.2. Cost: aggregate minus 27%, conditional minus 22%, bulk minus 15%, sequence minus 9%, lookup 0%, control plus 8%. Wall time: minus 26%, minus 15%, minus 6%, minus 14%, plus 6%, plus 16%" width="960" height="531" loading="lazy" decoding="async" style="width: 100%; height: auto; margin: 1.75rem auto; display: block;">
</picture>
<p>Aggregates (questions over many rows) are where code mode shines: 90% to 98% correct, 27% cheaper, 26% faster. Then there's the control group, five tests that are a single operation ("change the sourdough to 2 please"). There code mode cost 8% more and took 16% longer, because the model paid for the guidance and wrote a program to make one call. Bulk edits were cheaper too, but less often right (95% to 90%), and the Muse models account for most of that drop. Categories have 5 to 10 tests each, too few for intervals, so treat those bars as direction.</p>
</section><section id="where-code-mode-costs-section"><h2 id="where-code-mode-costs" role="presentation"><a href="#where-code-mode-costs" class="heading-anchor"><button type="button" class="heading-anchor__btn">#</button></a><span role="heading" aria-level="2">Where code mode costs</span></h2>
<p>The honest list, because there is one:</p>
<ul>
<li><strong>Small jobs.</strong> At 5 items, code mode cost more on three of the five scaling tasks; by 20 it was cheaper on three and level on one. Chat triage crossed over last: it cost more at 5 and 20 messages and only got cheaper from 100. Telling a refund request from other messages means reading the text, so with code mode the messages still pass through the model.</li>
<li><strong>Small models that write buggy code.</strong> gpt-6-luna paid 19% more on the everyday tasks, with 0.56 failed <code>run_code</code> snippets per run, and every failure is another round trip. Per correct run it still came out cheaper: $0.00121 against $0.00130. On the inventory scaling task its cost grew <em>faster</em> with code mode than without, while it got 9 of 15 runs right instead of 3.</li>
<li><strong>Models that print the data back.</strong> muse-spark-1.3-contributor's code mode runs printed much of the data into the conversation, so at 200 items its tokens fell only 5% to 64%. For muse-wonder-1.0-contributor and deepseek-v4.1-flash they fell 57% to 99%.</li>
<li><strong>Retries can repeat writes.</strong> A snippet that fails halfway and gets rerun can do its first half twice. Three of gpt-6-luna's failures in the long tier created the same records twice.</li>
<li><strong>It can still get things wrong.</strong> On the everyday tasks, muse-spark-1.3-contributor was right 92% of the time with code mode and 98% without, the one drop whose interval clears zero. Most of its misses were bulk edits that left the app in the wrong state. In the scaling tier, two cells went the wrong way, both within noise. In calendar invites at N = 20 (92% → 83%), gpt-6-luna left invites unanswered and claude-haiku-5-5 miscounted its own work. In inventory at N = 5 (100% → 92%), claude-haiku-5-5 twice left a required number out of its reply.</li>
</ul>
<p>So code mode earns its keep once the data or the task grows past what plain tool calling handles well. On these apps, for most tasks, that point was somewhere between 20 and 50 items.</p>
</section><section id="so-why-is-it-the-future-section"><h2 id="so-why-is-it-the-future" role="presentation"><a href="#so-why-is-it-the-future" class="heading-anchor"><button type="button" class="heading-anchor__btn">#</button></a><span role="heading" aria-level="2">So why is it the future?</span></h2>
<p>Because the curve is real, and it points one way. Code mode charges a flat fee: a couple of thousand characters of guidance per request. Tool calling charges per item: every call written out, every result read back in, every running total held in the model's head. On a single edit the flat fee loses. A few dozen items in, it starts winning, and by 200 items it's not close. I expect agent tasks to keep getting longer. I haven't measured that, but if they do, more and more of them will land on the right side of that curve.</p>
<p>The tradeoffs are real, and worth taking seriously:</p>
<ul>
<li><strong>You're running LLM-generated code.</strong> Yes, which is why the sandbox matters as much as the model. Generated code can only reach what you hand it, and it runs inside time and memory limits. Your tools are what you hand it, and they run with your app's authority, so they still need their own validation and authorization. <a href="https://pydantic.dev/articles/pydantic-monty">Samuel's Monty post</a> explains why we built an interpreter that starts from nothing instead of locking down a full Python.</li>
<li><strong>It's harder to debug.</strong> Also yes. A failing program hides its intermediate values in the sandbox, and as gpt-6-luna showed, a rerun snippet can repeat its writes. You do have to read code now, not just JSON. What helps is that the program's calls still go through Pydantic AI to your real tools, so with <a href="https://pydantic.dev/docs/ai/integrations/logfire/">Logfire</a> or any OpenTelemetry backend instrumenting the agent, each <code>run_code</code> call is a span and every tool call inside it <a href="https://pydantic.dev/docs/ai/harness/code-mode/#observability">gets its own span</a> underneath.</li>
<li><strong>You may not need it at all.</strong> True, and our small-N results back it up. The answer there is less code mode, not none. Pydantic AI's <code>CodeMode</code> takes a <a href="https://pydantic.dev/docs/ai/harness/code-mode/#selective-tool-sandboxing">tool selector</a>, so you can sandbox the tools that get looped over and leave the rest as plain tool calls.</li>
</ul>
<p>Code mode is also just where the models are heading: writing code looks like the skill they're improving at fastest. My guess is that's because code is checkable, which makes it easy to train on. Either way, giving the model a programming language to drive your tools plays to the strength that's improving fastest.</p>
<p>It also has to be safe to run. Every result above came from code mode inside a sandbox that could reach these apps' tools, an in-memory filesystem and environment, and the clock, and nothing else: no host files and no network. That's the setup we built Monty for.</p>
<p>The next step is the same idea one level up. In <a href="https://pydantic.dev/articles/dynamic-workflows">dynamic workflows</a>, the functions in the sandbox are sub-agents instead of tools, and the program the model writes is the orchestration. Samuel's graph, written by the model, at runtime, with agents as the nodes. That's the future I mean.</p>
</section><section id="try-it-section"><h2 id="try-it" role="presentation"><a href="#try-it" class="heading-anchor"><button type="button" class="heading-anchor__btn">#</button></a><span role="heading" aria-level="2">Try it</span></h2>
<p>In your own Pydantic AI agent, code mode is one capability from Pydantic AI Harness:</p>
<pre><code class="hljs language-bash">uv add <span class="hljs-string">"pydantic-ai-harness[codemode]"</span> <span class="hljs-string">"pydantic-ai-slim[openai]"</span>
<span class="hljs-built_in">export</span> OPENAI_API_KEY=<span class="hljs-string">"your-api-key"</span>
</code></pre>
<p>Then give the agent its tools:</p>
<pre><code class="hljs language-python"><span class="hljs-keyword">from</span> pydantic_ai <span class="hljs-keyword">import</span> Agent
<span class="hljs-keyword">from</span> pydantic_ai_harness <span class="hljs-keyword">import</span> CodeMode

CART = {
    <span class="hljs-number">1</span>: {<span class="hljs-string">'name'</span>: <span class="hljs-string">'Espresso machine'</span>, <span class="hljs-string">'unit_price'</span>: <span class="hljs-number">249.00</span>},
    <span class="hljs-number">2</span>: {<span class="hljs-string">'name'</span>: <span class="hljs-string">'Oat milk'</span>, <span class="hljs-string">'unit_price'</span>: <span class="hljs-number">3.49</span>},
    <span class="hljs-number">3</span>: {<span class="hljs-string">'name'</span>: <span class="hljs-string">'Cast iron pan'</span>, <span class="hljs-string">'unit_price'</span>: <span class="hljs-number">64.95</span>},
}

agent = Agent(
    <span class="hljs-string">'openai:gpt-6.1-sol'</span>,
    instructions=<span class="hljs-string">'You help the user manage their shopping cart. Prices are in US dollars.'</span>,
    capabilities=[CodeMode()],
)


<span class="hljs-meta">@agent.tool_plain</span>
<span class="hljs-keyword">def</span> <span class="hljs-title function_">list_items</span>(<span class="hljs-params">offset: <span class="hljs-built_in">int</span> = <span class="hljs-number">0</span>, limit: <span class="hljs-built_in">int</span> = <span class="hljs-number">20</span></span>) -> <span class="hljs-built_in">dict</span>:
    <span class="hljs-string">"""List cart items in id order, one page at a time."""</span>
    ids = <span class="hljs-built_in">sorted</span>(CART)[offset : offset + limit]
    next_offset = offset + limit <span class="hljs-keyword">if</span> offset + limit &#x3C; <span class="hljs-built_in">len</span>(CART) <span class="hljs-keyword">else</span> <span class="hljs-literal">None</span>
    <span class="hljs-keyword">return</span> {<span class="hljs-string">'items'</span>: [{<span class="hljs-string">'id'</span>: i, **CART[i]} <span class="hljs-keyword">for</span> i <span class="hljs-keyword">in</span> ids], <span class="hljs-string">'next_offset'</span>: next_offset}


<span class="hljs-meta">@agent.tool_plain</span>
<span class="hljs-keyword">def</span> <span class="hljs-title function_">remove_item</span>(<span class="hljs-params">item_id: <span class="hljs-built_in">int</span></span>) -> <span class="hljs-built_in">str</span>:
    <span class="hljs-string">"""Remove one item from the cart."""</span>
    <span class="hljs-keyword">return</span> <span class="hljs-string">f'removed <span class="hljs-subst">{CART.pop(item_id)[<span class="hljs-string">"name"</span>]}</span>'</span>


result = agent.run_sync(
    <span class="hljs-string">'can you get rid of everything in my cart that costs more than $50 a piece?'</span>
)
<span class="hljs-built_in">print</span>(result.output)
</code></pre>
<p>The model sees one tool, <code>run_code</code>, and calls <code>list_items</code> and <code>remove_item</code> as async functions from inside it. That code runs in Monty, so those two functions are all it can reach. The benchmark ran it with <code>eager=True</code>. The <a href="https://pydantic.dev/docs/ai/harness/code-mode/">code mode docs</a> cover eager and <a href="https://pydantic.dev/docs/ai/harness/code-mode/#speculative-execution">speculative execution</a>, tool selection, resource limits and the rest.</p>
</section><section id="what-about-speculation-section"><h2 id="what-about-speculation" role="presentation"><a href="#what-about-speculation" class="heading-anchor"><button type="button" class="heading-anchor__btn">#</button></a><span role="heading" aria-level="2">What about speculation?</span></h2>
<p>Pydantic AI Harness's <code>CodeMode</code> also has <a href="https://pydantic.dev/docs/ai/harness/code-mode/#speculative-execution">speculative execution</a>: the speculative programmatic tool calling from the top of this post, which starts calls to tools you've declared safe to run early while the model is still writing the <code>run_code</code> call. None of these apps' tools were declared for it, so speculation had nothing to start early. In the first everyday batch it differed from plain code mode only in its longer guidance, and it showed: +7.7 points of success instead of +10.3, and +4% cost instead of -2%. The later batches skipped it. That's not a test of speculation, so I'm not drawing conclusions from it.</p>
<p>Thank you for reading!</p>
</section><section id="acknowledgements-section"><h2 id="acknowledgements" role="presentation"><a href="#acknowledgements" class="heading-anchor"><button type="button" class="heading-anchor__btn">#</button></a><span role="heading" aria-level="2">Acknowledgements</span></h2>
<ul>
<li><a href="https://pydantic.dev/articles/the-code-is-the-graph">Samuel Colvin</a> for the graph argument, and for pushing me to find bigger differences.</li>
<li>Maverick (<a href="https://github.com/maverick-jackson">@maverick-jackson</a>), whose code mode study set the A/B method this benchmark follows.</li>
<li>Ruben, for spotting that the first version of my success chart had "more correct" pointing the wrong way.</li>
</ul></section>]]></content:encoded>
</item>
<item>
<title>I received the AAIF Outstanding Technical Contribution Award</title>
<link>https://pydantic.dev/articles/aaif-outstanding-technical-contribution-award</link>
<guid isPermaLink="true">https://pydantic.dev/articles/aaif-outstanding-technical-contribution-award</guid>
<pubDate>Tue, 27 Oct 2026 09:00:00 GMT</pubDate>
<dc:creator>Marcelo Trylesinski</dc:creator>
<category>MCP</category>
<category>Open Source</category>
<category>Company</category>
<category>Pydantic Logfire</category>
<description>At AGNTCon + MCPCon North America, the Agentic AI Foundation recognized my work maintaining the MCP Python SDK. A short thank you to the people who made it possible.</description>
<content:encoded><![CDATA[<!-- cspell:ignore AGNT Bartosz Gonczarek -->
<p>Last Friday, on day two of <a href="https://events.linuxfoundation.org/agntcon-mcpcon-north-america/">AGNTCon + MCPCon North America</a>,
the <a href="https://aaif.io">Agentic AI Foundation</a> gave me the <strong>Outstanding Technical Contribution Award</strong> for my work on the
<a href="https://github.com/modelcontextprotocol/python-sdk">MCP Python SDK</a>.</p>
<p><img src="https://pydantic.dev/assets/blog/aaif-outstanding-technical-contribution-award/award-on-stage.jpg" alt="Marcelo Trylesinski holding the AAIF Outstanding Technical Contribution Award above his head on the AGNTCon + MCPCon North America stage, between Antoni Kozelski and Bartosz Gonczarek from Vstorm" decoding="async"></p>
<p>You can watch the moment on the day two livestream, right after the opening keynote.</p>
<div class="responsive-video-container">
  <iframe width="560" height="315" src="https://www.youtube.com/embed/eB9I4Ixx2wc?start=615" title="AAIF award presentation at AGNTCon + MCPCon North America, day two" style="border: 0;" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen></iframe>
</div>
<section id="what-the-award-is-for-section"><h2 id="what-the-award-is-for" role="presentation"><a href="#what-the-award-is-for" class="heading-anchor"><button type="button" class="heading-anchor__btn">#</button></a><span role="heading" aria-level="2">What the award is for</span></h2>
<p>I'm one of the two maintainers of the MCP Python SDK. Python developers use it to build MCP servers and clients, and
it's where a lot of my time has gone this year.</p>
<p>The biggest piece of that work was v2. We shipped the <a href="https://pydantic.dev/articles/mcp-python-sdk-v2-beta">v2 beta</a> alongside the
2026-07-28 revision of the MCP specification, with a new <code>MCPServer</code> API and multi-round-trip requests. v2 is now the
stable release line.</p>
<p>A lot of v2 is the new specification, implemented in Python: standard error codes, authorization hardening, routable
transport headers, a deprecation policy, and OpenTelemetry tracing on by default.</p>
<p>On the specification side, I sponsored <a href="https://github.com/modelcontextprotocol/modelcontextprotocol/issues/1288">SEP-1288</a>,
the WebSocket transport. The HTTP transport also runs on <a href="https://github.com/Kludex/starlette">Starlette</a> and
<a href="https://github.com/Kludex/uvicorn">Uvicorn</a>, which I maintain, so when the SDK finds a bug underneath it, I can fix it
in the layer where it belongs.</p>
<p>Most of that work happens in issues, pull requests, and spec discussions that nobody sees on a conference stage. It's
nice to have it noticed.</p>
</section><section id="thank-you-section"><h2 id="thank-you" role="presentation"><a href="#thank-you" class="heading-anchor"><button type="button" class="heading-anchor__btn">#</button></a><span role="heading" aria-level="2">Thank you</span></h2>
<p>First, a special thank you to my colleague <a href="https://pydantic.dev/authors/lais-carvalho">Laís Carvalho</a>. She nominated me, and I would not
have been on that stage without her.</p>
<p>To the MCP maintainers and contributors: the SDK is better because of every issue, review, and pull request you sent.</p>
<p>To <a href="https://pydantic.dev">Pydantic</a>: you pay me to work on open source, and you let me spend that time where the
community needs it. That is rarer than it should be.</p>
<p>It also goes both ways. I work on <a href="https://pydantic.dev/logfire">Pydantic Logfire</a> too, so v2 ships an OpenTelemetry
middleware enabled by default. Call <code>logfire.configure(distributed_tracing=True)</code> in your MCP server and
<code>logfire.configure()</code> in your client, and every request between them arrives in Logfire as one trace. The <a href="https://pydantic.dev/articles/mcp-python-sdk-v2-beta">v2 beta post</a> walks through it.</p>
<p>I also shared the stage with our friends Antoni Kozelski and Bartosz Gonczarek from
<a href="https://vstorm.co/?utm_source=pydantic&#x26;utm_medium=partnership&#x26;utm_campaign=aaif-outstanding-technical-contribution-award">Vstorm</a>, who won the <strong>Open Agentic
AI Innovation Award</strong>. Congratulations to both of you, and thank you for making the photo a lot better.</p>
<p>The <a href="https://pydantic.dev/docs/logfire/guides/mcp-server/">Logfire MCP server</a> is where this work lands first. It runs on
the same Python SDK, so the standard error codes, the authorization hardening, and the tracing middleware above all show
up there before anywhere else. I want it to be the best MCP server you connect your coding agent to, and I spend a lot of
my week making that true. If you have a Logfire project, add <code>https://logfire-us.pydantic.dev/mcp</code> (or the EU URL) to
your agent and ask it what broke in production last night. Setup takes a few minutes, and the answer usually takes less.</p>
<p>See you at the next MCPCon.</p></section>]]></content:encoded>
</item>
<item>
<title>Why do you need traces if you already have logs?</title>
<link>https://pydantic.dev/articles/why-traces-when-you-have-logs</link>
<guid isPermaLink="true">https://pydantic.dev/articles/why-traces-when-you-have-logs</guid>
<pubDate>Mon, 26 Oct 2026 09:00:00 GMT</pubDate>
<dc:creator>Marcelo Trylesinski</dc:creator>
<category>Pydantic Logfire</category>
<description>Logs record that something happened. Traces also record which request it belonged to, what called it, and how long it took. A small async example shows where logs stop being enough.</description>
<content:encoded><![CDATA[<p>Developers ask me this a lot: "Why do I need traces? I have logs." I asked the same question for years.</p>
<p>The short answer: a log line records that something happened at one point in time. A span records an operation, with a trace ID, a span ID, a parent span ID, and a start and end time. Those fields tell you which operations belong to the same request, what called what, and where the time went. Plain logs don't carry them, so you end up guessing.</p>
<p>The long answer is easier to show than to explain.</p>
<section id="a-checkout-that-takes-two-seconds-section"><h2 id="a-checkout-that-takes-two-seconds" role="presentation"><a href="#a-checkout-that-takes-two-seconds" class="heading-anchor"><button type="button" class="heading-anchor__btn">#</button></a><span role="heading" aria-level="2">A checkout that takes two seconds</span></h2>
<p>Here is a checkout handler. It loads the cart and the discounts concurrently, then charges the user. Three users check out at the same time, and the discount service is slow for one of them.</p>
<pre><code class="hljs language-python"><span class="hljs-keyword">import</span> asyncio
<span class="hljs-keyword">import</span> logging
<span class="hljs-keyword">import</span> random

logging.basicConfig(<span class="hljs-built_in">format</span>=<span class="hljs-string">"%(asctime)s %(levelname)s %(message)s"</span>, level=logging.INFO)
logger = logging.getLogger(<span class="hljs-string">"checkout"</span>)


<span class="hljs-keyword">async</span> <span class="hljs-keyword">def</span> <span class="hljs-title function_">fetch_cart</span>(<span class="hljs-params">user_id: <span class="hljs-built_in">int</span></span>) -> <span class="hljs-built_in">list</span>[<span class="hljs-built_in">str</span>]:
    <span class="hljs-keyword">await</span> asyncio.sleep(random.uniform(<span class="hljs-number">0.05</span>, <span class="hljs-number">0.1</span>))
    logger.info(<span class="hljs-string">"cart loaded"</span>)
    <span class="hljs-keyword">return</span> [<span class="hljs-string">"book"</span>, <span class="hljs-string">"mug"</span>]


<span class="hljs-keyword">async</span> <span class="hljs-keyword">def</span> <span class="hljs-title function_">fetch_discounts</span>(<span class="hljs-params">user_id: <span class="hljs-built_in">int</span></span>) -> <span class="hljs-built_in">float</span>:
    <span class="hljs-keyword">await</span> asyncio.sleep(<span class="hljs-number">2.0</span> <span class="hljs-keyword">if</span> user_id == <span class="hljs-number">2</span> <span class="hljs-keyword">else</span> random.uniform(<span class="hljs-number">0.05</span>, <span class="hljs-number">0.1</span>))
    logger.info(<span class="hljs-string">"discounts loaded"</span>)
    <span class="hljs-keyword">return</span> <span class="hljs-number">0.1</span>


<span class="hljs-keyword">async</span> <span class="hljs-keyword">def</span> <span class="hljs-title function_">charge</span>(<span class="hljs-params">user_id: <span class="hljs-built_in">int</span>, items: <span class="hljs-built_in">list</span>[<span class="hljs-built_in">str</span>], discount: <span class="hljs-built_in">float</span></span>) -> <span class="hljs-literal">None</span>:
    <span class="hljs-keyword">await</span> asyncio.sleep(random.uniform(<span class="hljs-number">0.1</span>, <span class="hljs-number">0.2</span>))
    logger.info(<span class="hljs-string">"payment charged"</span>)


<span class="hljs-keyword">async</span> <span class="hljs-keyword">def</span> <span class="hljs-title function_">checkout</span>(<span class="hljs-params">user_id: <span class="hljs-built_in">int</span></span>) -> <span class="hljs-literal">None</span>:
    logger.info(<span class="hljs-string">"checkout started"</span>)
    items, discount = <span class="hljs-keyword">await</span> asyncio.gather(fetch_cart(user_id), fetch_discounts(user_id))
    <span class="hljs-keyword">await</span> charge(user_id, items, discount)
    logger.info(<span class="hljs-string">"checkout finished"</span>)


<span class="hljs-keyword">async</span> <span class="hljs-keyword">def</span> <span class="hljs-title function_">main</span>() -> <span class="hljs-literal">None</span>:
    <span class="hljs-keyword">await</span> asyncio.gather(*(checkout(user_id) <span class="hljs-keyword">for</span> user_id <span class="hljs-keyword">in</span> (<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>)))


asyncio.run(main())
</code></pre>
<p>This is the output:</p>
<pre><code>2026-10-19 11:15:13,441 INFO checkout started
2026-10-19 11:15:13,441 INFO checkout started
2026-10-19 11:15:13,441 INFO checkout started
2026-10-19 11:15:13,493 INFO cart loaded
2026-10-19 11:15:13,494 INFO cart loaded
2026-10-19 11:15:13,503 INFO discounts loaded
2026-10-19 11:15:13,506 INFO cart loaded
2026-10-19 11:15:13,527 INFO discounts loaded
2026-10-19 11:15:13,605 INFO payment charged
2026-10-19 11:15:13,606 INFO checkout finished
2026-10-19 11:15:13,659 INFO payment charged
2026-10-19 11:15:13,659 INFO checkout finished
2026-10-19 11:15:15,442 INFO discounts loaded
2026-10-19 11:15:15,588 INFO payment charged
2026-10-19 11:15:15,588 INFO checkout finished
</code></pre>
<p>One checkout took about two seconds. Which user was it? Which of the three "checkout started" lines does the last "checkout finished" belong to? The logs can't say.</p>
<p>With three requests you can squint and work it out. With three hundred requests per second, the lines from different requests interleave and you can't.</p>
</section><section id="adding-a-request-id-section"><h2 id="adding-a-request-id" role="presentation"><a href="#adding-a-request-id" class="heading-anchor"><button type="button" class="heading-anchor__btn">#</button></a><span role="heading" aria-level="2">Adding a request ID</span></h2>
<p>The usual fix is a request ID. You store it in a <code>contextvars.ContextVar</code> and add it to every log record with a filter. This replaces the <code>logging.basicConfig</code> call in the first example:</p>
<pre><code class="hljs language-python"><span class="hljs-keyword">import</span> contextvars
<span class="hljs-keyword">import</span> logging
<span class="hljs-keyword">import</span> uuid

request_id: contextvars.ContextVar[<span class="hljs-built_in">str</span>] = contextvars.ContextVar(<span class="hljs-string">"request_id"</span>, default=<span class="hljs-string">"-"</span>)


<span class="hljs-keyword">class</span> <span class="hljs-title class_">RequestIDFilter</span>(logging.Filter):
    <span class="hljs-keyword">def</span> <span class="hljs-title function_">filter</span>(<span class="hljs-params">self, record: logging.LogRecord</span>) -> <span class="hljs-built_in">bool</span>:
        record.request_id = request_id.get()
        <span class="hljs-keyword">return</span> <span class="hljs-literal">True</span>


handler = logging.StreamHandler()
handler.addFilter(RequestIDFilter())
logging.basicConfig(<span class="hljs-built_in">format</span>=<span class="hljs-string">"%(asctime)s %(request_id)s %(message)s"</span>, level=logging.INFO, handlers=[handler])
</code></pre>
<p>Then <code>checkout</code> calls <code>request_id.set(uuid.uuid4().hex[:8])</code> before its first log line. <code>asyncio</code> copies the context into each task, so <code>fetch_cart</code> and <code>fetch_discounts</code> see the same ID:</p>
<pre><code>2026-10-19 11:16:29,713 16bac7c6 checkout started
2026-10-19 11:16:29,791 16bac7c6 cart loaded
2026-10-19 11:16:31,714 16bac7c6 discounts loaded
2026-10-19 11:16:31,816 16bac7c6 payment charged
2026-10-19 11:16:31,817 16bac7c6 checkout finished
</code></pre>
<p>That's better. You can filter by <code>16bac7c6</code> and see one request. To read it, though, you subtract timestamps.</p>
<p>The gap between "cart loaded" and "discounts loaded" is 1.9 seconds. That isn't how long the discounts took. Both calls started at the same time, so the discounts took 2.0 seconds and the cart took 78 milliseconds. Every gap between two lines is attributed to whatever code ran in between, and the logs don't name that code. A blocking call nobody logged looks exactly like a slow discount service.</p>
</section><section id="but-i-have-structured-logs-with-a-request-id-section"><h2 id="but-i-have-structured-logs-with-a-request-id" role="presentation"><a href="#but-i-have-structured-logs-with-a-request-id" class="heading-anchor"><button type="button" class="heading-anchor__btn">#</button></a><span role="heading" aria-level="2">"But I have structured logs with a request ID"</span></h2>
<p>This is the answer I hear most, and it's a good one. Say every line is JSON, every service passes the request ID along, and every operation logs <code>duration_ms</code> when it finishes. This is the slow checkout from the same program with a JSON formatter:</p>
<pre><code class="hljs language-json"><span class="hljs-punctuation">{</span><span class="hljs-attr">"ts"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"11:37:35.684"</span><span class="hljs-punctuation">,</span> <span class="hljs-attr">"request_id"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"5adf2211"</span><span class="hljs-punctuation">,</span> <span class="hljs-attr">"event"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"checkout started"</span><span class="hljs-punctuation">,</span> <span class="hljs-attr">"user_id"</span><span class="hljs-punctuation">:</span> <span class="hljs-number">2</span><span class="hljs-punctuation">}</span>
<span class="hljs-punctuation">{</span><span class="hljs-attr">"ts"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"11:37:35.765"</span><span class="hljs-punctuation">,</span> <span class="hljs-attr">"request_id"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"5adf2211"</span><span class="hljs-punctuation">,</span> <span class="hljs-attr">"event"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"cart loaded"</span><span class="hljs-punctuation">,</span> <span class="hljs-attr">"duration_ms"</span><span class="hljs-punctuation">:</span> <span class="hljs-number">81</span><span class="hljs-punctuation">}</span>
<span class="hljs-punctuation">{</span><span class="hljs-attr">"ts"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"11:37:37.685"</span><span class="hljs-punctuation">,</span> <span class="hljs-attr">"request_id"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"5adf2211"</span><span class="hljs-punctuation">,</span> <span class="hljs-attr">"event"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"discounts loaded"</span><span class="hljs-punctuation">,</span> <span class="hljs-attr">"duration_ms"</span><span class="hljs-punctuation">:</span> <span class="hljs-number">2001</span><span class="hljs-punctuation">}</span>
<span class="hljs-punctuation">{</span><span class="hljs-attr">"ts"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"11:37:37.828"</span><span class="hljs-punctuation">,</span> <span class="hljs-attr">"request_id"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"5adf2211"</span><span class="hljs-punctuation">,</span> <span class="hljs-attr">"event"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"payment charged"</span><span class="hljs-punctuation">,</span> <span class="hljs-attr">"duration_ms"</span><span class="hljs-punctuation">:</span> <span class="hljs-number">142</span><span class="hljs-punctuation">}</span>
<span class="hljs-punctuation">{</span><span class="hljs-attr">"ts"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"11:37:37.828"</span><span class="hljs-punctuation">,</span> <span class="hljs-attr">"request_id"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"5adf2211"</span><span class="hljs-punctuation">,</span> <span class="hljs-attr">"event"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"checkout finished"</span><span class="hljs-punctuation">,</span> <span class="hljs-attr">"duration_ms"</span><span class="hljs-punctuation">:</span> <span class="hljs-number">2144</span><span class="hljs-punctuation">}</span>
</code></pre>
<p>For this request, that's enough. <code>duration_ms</code> says the discounts took 2001 ms. If all your requests look like this one, keep your logs.</p>
<p>It stops being enough in three situations.</p>
<section id="the-same-operation-runs-twice-section"><h3 id="the-same-operation-runs-twice" role="presentation"><a href="#the-same-operation-runs-twice" class="heading-anchor"><button type="button" class="heading-anchor__btn">#</button></a><span role="heading" aria-level="3">The same operation runs twice</span></h3>
<p>Say <code>fetch_discounts</code> retries after a timeout, or the checkout loads discounts once per item. Now the request has two <code>discounts loaded</code> lines. The request ID says both belong to this request. It doesn't say which one <code>charge</code> waited for, or which call in the checkout made each one. For that, every operation needs its own ID and its caller's ID.</p>
</section><section id="the-operation-never-finishes-section"><h3 id="the-operation-never-finishes" role="presentation"><a href="#the-operation-never-finishes" class="heading-anchor"><button type="button" class="heading-anchor__btn">#</button></a><span role="heading" aria-level="3">The operation never finishes</span></h3>
<p><code>duration_ms</code> is written when the operation ends. If the discount service hangs until the client gives up, or the process is killed, the request has a <code>checkout started</code> line and nothing else. You know something went wrong, not where. When the Logfire SDK starts a span, it can send a <a href="https://pydantic.dev/docs/logfire/reference/sql/">pending span</a>, so there's a record of the operation and its parent even if it never finishes.</p>
</section><section id="your-libraries-dont-log-your-request-id-section"><h3 id="your-libraries-dont-log-your-request-id" role="presentation"><a href="#your-libraries-dont-log-your-request-id" class="heading-anchor"><button type="button" class="heading-anchor__btn">#</button></a><span role="heading" aria-level="3">Your libraries don't log your request ID</span></h3>
<p>Your HTTP client, database driver, and payment SDK don't know about your <code>request_id</code> field. Another team's service may call it <code>correlation_id</code>. The request ID covers the lines you wrote. OpenTelemetry instrumentation covers the libraries too, and OpenTelemetry SDKs read and write the same <code>traceparent</code> header by default.</p>
<p>Fixing those means more fields: an ID for every operation, its caller's ID, a "started" event, and a header that carries the IDs between services. Here is what you built:</p>
<div class="overflow-x-auto table-wrapper" tabindex="0"><table>
<thead>
<tr>
<th>What you added to your logs</th>
<th>OpenTelemetry's equivalent</th>
</tr>
</thead>
<tbody>
<tr>
<td>Request ID</td>
<td><code>trace_id</code></td>
</tr>
<tr>
<td>Operation ID</td>
<td><code>span_id</code></td>
</tr>
<tr>
<td>Caller's operation ID</td>
<td><code>parent_span_id</code></td>
</tr>
<tr>
<td>"started" event and <code>duration_ms</code></td>
<td>Span <code>start_time</code> and <code>end_time</code></td>
</tr>
<tr>
<td>A header with the request ID and the calling operation's ID</td>
<td><code>traceparent</code> header, with the <code>trace_id</code> and the caller's <code>span_id</code></td>
</tr>
</tbody>
</table></div>
<p>Those are the fields of a span, kept by hand in your log records. You reinvented tracing, one field at a time, with no standard format and no tool that understands it.</p>
<p>The header in the last row is already a standard. <a href="https://www.w3.org/TR/trace-context/">W3C Trace Context</a> defines <code>traceparent</code>, which carries the trace ID and the caller's span ID between services:</p>
<pre><code>traceparent: 00-0af7651916cd43dd8448eb211c80319c-b7ad6b7169203331-01
</code></pre>
<p>OpenTelemetry instrumentation for HTTP clients and servers reads and writes it, so you don't have to.</p>
</section></section><section id="the-same-code-with-spans-section"><h2 id="the-same-code-with-spans" role="presentation"><a href="#the-same-code-with-spans" class="heading-anchor"><button type="button" class="heading-anchor__btn">#</button></a><span role="heading" aria-level="2">The same code with spans</span></h2>
<p>Here is the checkout again with <a href="https://pydantic.dev/logfire">Pydantic Logfire</a>. Each function is a span, created with <a href="https://pydantic.dev/docs/logfire/instrument/python/add-manual-tracing/#convenient-function-spans-with-logfireinstrument"><code>@logfire.instrument</code></a>. To run it, install Logfire with <code>pip install logfire</code> and authenticate with <code>logfire auth</code>, as the <a href="https://pydantic.dev/docs/logfire/get-started/">getting started guide</a> describes:</p>
<pre><code class="hljs language-python"><span class="hljs-keyword">import</span> asyncio
<span class="hljs-keyword">import</span> random

<span class="hljs-keyword">import</span> logfire

logfire.configure(service_name=<span class="hljs-string">"checkout"</span>)


<span class="hljs-meta">@logfire.instrument(<span class="hljs-params"><span class="hljs-string">"fetch cart"</span></span>)</span>
<span class="hljs-keyword">async</span> <span class="hljs-keyword">def</span> <span class="hljs-title function_">fetch_cart</span>(<span class="hljs-params">user_id: <span class="hljs-built_in">int</span></span>) -> <span class="hljs-built_in">list</span>[<span class="hljs-built_in">str</span>]:
    <span class="hljs-keyword">await</span> asyncio.sleep(random.uniform(<span class="hljs-number">0.05</span>, <span class="hljs-number">0.1</span>))
    <span class="hljs-keyword">return</span> [<span class="hljs-string">"book"</span>, <span class="hljs-string">"mug"</span>]


<span class="hljs-meta">@logfire.instrument(<span class="hljs-params"><span class="hljs-string">"fetch discounts"</span></span>)</span>
<span class="hljs-keyword">async</span> <span class="hljs-keyword">def</span> <span class="hljs-title function_">fetch_discounts</span>(<span class="hljs-params">user_id: <span class="hljs-built_in">int</span></span>) -> <span class="hljs-built_in">float</span>:
    <span class="hljs-keyword">await</span> asyncio.sleep(<span class="hljs-number">2.0</span> <span class="hljs-keyword">if</span> user_id == <span class="hljs-number">2</span> <span class="hljs-keyword">else</span> random.uniform(<span class="hljs-number">0.05</span>, <span class="hljs-number">0.1</span>))
    <span class="hljs-keyword">return</span> <span class="hljs-number">0.1</span>


<span class="hljs-meta">@logfire.instrument(<span class="hljs-params"><span class="hljs-string">"charge"</span></span>)</span>
<span class="hljs-keyword">async</span> <span class="hljs-keyword">def</span> <span class="hljs-title function_">charge</span>(<span class="hljs-params">user_id: <span class="hljs-built_in">int</span>, items: <span class="hljs-built_in">list</span>[<span class="hljs-built_in">str</span>], discount: <span class="hljs-built_in">float</span></span>) -> <span class="hljs-literal">None</span>:
    <span class="hljs-keyword">await</span> asyncio.sleep(random.uniform(<span class="hljs-number">0.1</span>, <span class="hljs-number">0.2</span>))


<span class="hljs-meta">@logfire.instrument(<span class="hljs-params"><span class="hljs-string">"checkout {user_id=}"</span></span>)</span>
<span class="hljs-keyword">async</span> <span class="hljs-keyword">def</span> <span class="hljs-title function_">checkout</span>(<span class="hljs-params">user_id: <span class="hljs-built_in">int</span></span>) -> <span class="hljs-literal">None</span>:
    items, discount = <span class="hljs-keyword">await</span> asyncio.gather(fetch_cart(user_id), fetch_discounts(user_id))
    <span class="hljs-keyword">await</span> charge(user_id, items, discount)


<span class="hljs-keyword">async</span> <span class="hljs-keyword">def</span> <span class="hljs-title function_">main</span>() -> <span class="hljs-literal">None</span>:
    <span class="hljs-keyword">await</span> asyncio.gather(*(checkout(user_id) <span class="hljs-keyword">for</span> user_id <span class="hljs-keyword">in</span> (<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>)))


asyncio.run(main())
</code></pre>
<p>There is no request ID, no filter, and no "started" line. Each checkout gets its own trace. These are the spans of the slow one. The last three are children of the <code>checkout</code> span:</p>
<div class="overflow-x-auto table-wrapper" tabindex="0"><table>
<thead>
<tr>
<th>Span</th>
<th>Start</th>
<th>Duration</th>
</tr>
</thead>
<tbody>
<tr>
<td>checkout user_id=2</td>
<td>0 ms</td>
<td>2176 ms</td>
</tr>
<tr>
<td>fetch cart</td>
<td>0 ms</td>
<td>69 ms</td>
</tr>
<tr>
<td>fetch discounts</td>
<td>1 ms</td>
<td>2001 ms</td>
</tr>
<tr>
<td>charge</td>
<td>2002 ms</td>
<td>174 ms</td>
</tr>
</tbody>
</table></div>
<p>Logfire draws these as a waterfall, but the table already answers the question. <code>fetch cart</code> and <code>fetch discounts</code> ran in parallel, the discounts took 2001 ms, and <code>charge</code> started only after both finished. You didn't subtract anything.</p>
</section><section id="questions-you-can-ask-across-requests-section"><h2 id="questions-you-can-ask-across-requests" role="presentation"><a href="#questions-you-can-ask-across-requests" class="heading-anchor"><button type="button" class="heading-anchor__btn">#</button></a><span role="heading" aria-level="2">Questions you can ask across requests</span></h2>
<p>One slow request is a debugging session. The next question is usually "how often does this happen, and where?" With logs, you parse durations out of message strings. With spans, <code>duration</code> is a column.</p>
<p>Logfire stores completed spans in a <code>records</code> table you can query with <a href="https://pydantic.dev/docs/logfire/reference/sql/">SQL</a>:</p>
<pre><code class="hljs language-sql"><span class="hljs-keyword">SELECT</span>
    span_name,
    <span class="hljs-built_in">count</span>(<span class="hljs-operator">*</span>) <span class="hljs-keyword">AS</span> calls,
    approx_percentile_cont(duration, <span class="hljs-number">0.95</span>) <span class="hljs-keyword">AS</span> p95_seconds
<span class="hljs-keyword">FROM</span> records
<span class="hljs-keyword">WHERE</span> service_name <span class="hljs-operator">=</span> <span class="hljs-string">'checkout'</span> <span class="hljs-keyword">AND</span> kind <span class="hljs-operator">=</span> <span class="hljs-string">'span'</span>
<span class="hljs-keyword">GROUP</span> <span class="hljs-keyword">BY</span> span_name
<span class="hljs-keyword">ORDER</span> <span class="hljs-keyword">BY</span> p95_seconds <span class="hljs-keyword">DESC</span>
</code></pre>
<p>That gives you the p95 of every step in the checkout. Filter on <code>parent_span_id IS NULL</code> to get whole checkouts only, or group by <code>attributes->>'user_id'</code> to split them per user.</p>
</section><section id="the-lines-nobody-wrote-section"><h2 id="the-lines-nobody-wrote" role="presentation"><a href="#the-lines-nobody-wrote" class="heading-anchor"><button type="button" class="heading-anchor__btn">#</button></a><span role="heading" aria-level="2">The lines nobody wrote</span></h2>
<p>Logs only contain what someone decided to log. If nobody logged the database query, it's a gap between two timestamps.</p>
<p>Instrumentation libraries create spans for code you didn't write. In Logfire that is one line per library:</p>
<pre><code class="hljs language-python">logfire.instrument_fastapi(app)
logfire.instrument_httpx()
logfire.instrument_asyncpg()
</code></pre>
<p>Every request, outgoing HTTP call, and SQL query becomes a span with its duration and its parent. The HTTPX and FastAPI instrumentation also writes and reads the <code>traceparent</code> header, so a request that crosses three services is one trace.</p>
</section><section id="keep-your-logs-section"><h2 id="keep-your-logs" role="presentation"><a href="#keep-your-logs" class="heading-anchor"><button type="button" class="heading-anchor__btn">#</button></a><span role="heading" aria-level="2">Keep your logs</span></h2>
<p>Traces don't replace logs. Some things are events, not operations: a cache miss, a retry decision, a validation warning. They have no duration, and a log line is the right shape for them.</p>
<p>What changes is that a log line inside a span gets the span's context. Send your standard library logs to Logfire with the <a href="https://pydantic.dev/docs/logfire/integrations/logging/logging/"><code>LogfireLoggingHandler</code></a>:</p>
<pre><code class="hljs language-python"><span class="hljs-keyword">import</span> logging

<span class="hljs-keyword">import</span> logfire

logfire.configure()
logging.basicConfig(handlers=[logfire.LogfireLoggingHandler()], level=logging.INFO)
logger = logging.getLogger(<span class="hljs-string">"checkout"</span>)

<span class="hljs-keyword">with</span> logfire.span(<span class="hljs-string">"checkout {user_id=}"</span>, user_id=<span class="hljs-number">2</span>):
    logger.info(<span class="hljs-string">"discounts loaded"</span>)
</code></pre>
<p><code>discounts loaded</code> is stored as a child of the <code>checkout</code> span, with the same trace ID. Your existing <code>logger.info</code> calls keep working, and each one now says which request it came from.</p>
<p>So, do you need traces if you have logs? If your logs already carry a request ID, an operation ID, the caller's operation ID, and start and end times, you have the data of a trace, stored as text. Spans carry the same fields in the OpenTelemetry format, which tracing backends read, and Logfire also lets you query them as <a href="https://pydantic.dev/docs/logfire/reference/sql/">SQL columns</a>.</p></section>]]></content:encoded>
</item>
<item>
<title>Run Pydantic AI coding agents in E2B sandboxes</title>
<link>https://pydantic.dev/articles/pydantic-ai-e2b-sandboxes</link>
<guid isPermaLink="true">https://pydantic.dev/articles/pydantic-ai-e2b-sandboxes</guid>
<pubDate>Thu, 22 Oct 2026 09:00:00 GMT</pubDate>
<dc:creator>Laís Carvalho</dc:creator>
<category>Pydantic AI</category>
<category>Integrations</category>
<description>E2BSandbox is a native Pydantic AI Harness capability. The agent&apos;s shell commands and file edits run inside an isolated E2B microVM, the sandbox pauses and resumes between runs, and a Temporal worker can crash without losing the workspace.</description>
<content:encoded><![CDATA[<p>A coding agent that can run <code>python -m unittest</code> and edit files is useful. A coding agent that runs them on your laptop, as you, with your SSH keys in <code>~/.ssh</code> and your production <code>.env</code> two directories up, is a liability you have agreed to without reading the terms and conditions. The agent decided what to run, and nobody reviewed the command before it ran. An agent that waited for review would not be an agent.</p>
<p><a href="https://e2b.dev">E2B</a> is now a native sandbox provider in <a href="https://pydantic.dev/docs/ai/">Pydantic AI</a>. Add <code>E2BSandbox()</code> to an agent's capabilities and every shell command and file operation the agent makes runs inside an isolated E2B microVM instead of on your machine. Nothing from your environment reaches the sandbox. The sandbox can pause when a run ends and resume when the next one starts, with its filesystem and memory intact. And because the workspace is identified by a credential-free reference, a durable workflow can carry it across a worker crash.</p>
<p>This post walks through two examples from the <a href="https://github.com/e2b-dev/e2b-cookbook">E2B cookbook</a>: a two-run diagnose-then-fix agent that pauses the sandbox between runs, and the same task inside a Temporal workflow where the worker process gets killed halfway through.</p>
<section id="one-line-and-the-agent-is-off-your-machine-section"><h2 id="one-line-and-the-agent-is-off-your-machine" role="presentation"><a href="#one-line-and-the-agent-is-off-your-machine" class="heading-anchor"><button type="button" class="heading-anchor__btn">#</button></a><span role="heading" aria-level="2">One line, and the agent is off your machine</span></h2>
<p>Install the harness with the E2B and Temporal extras, the provider extras the snippets below use (the quick start calls Anthropic, the cookbook examples call OpenAI), and the Logfire extra so the runs are traced. Then set <code>E2B_API_KEY</code> and the provider key:</p>
<pre><code class="hljs language-bash">uv add <span class="hljs-string">"pydantic-ai-harness[e2b,anthropic,temporal]"</span> <span class="hljs-string">"pydantic-ai-slim[openai,logfire]"</span>
</code></pre>
<p>Then give the agent the sandbox alongside the tools that will use it:</p>
<pre><code class="hljs language-python"><span class="hljs-keyword">import</span> logfire
<span class="hljs-keyword">from</span> pydantic_ai <span class="hljs-keyword">import</span> Agent
<span class="hljs-keyword">from</span> pydantic_ai_harness.coder <span class="hljs-keyword">import</span> Coder
<span class="hljs-keyword">from</span> pydantic_ai_harness.e2b_sandbox <span class="hljs-keyword">import</span> E2BSandbox

logfire.configure()
logfire.instrument_pydantic_ai()

agent = Agent(<span class="hljs-string">'anthropic:claude-opus-5-5'</span>, capabilities=[E2BSandbox(), Coder()])
result = agent.run_sync(<span class="hljs-string">'Clone https://github.com/pydantic/pydantic-ai and summarize how capabilities work.'</span>)
</code></pre>
<p><code>E2BSandbox</code> supplies execution only. <code>Coder</code>, or the narrower <code>Shell</code> and <code>FileSystem</code> capabilities, supply the tools, and those tools now run in the sandbox. There is no custom E2B adapter and no template to build. E2B's default template ships with Python and git, which is enough for this post; a project with its own dependencies installs them in a <a href="https://pydantic.dev/docs/ai/harness/e2b-sandbox/">custom template</a> or with a <code>pip install</code> run inside the sandbox before the agent starts, since the default template has pip but not uv.</p>
<p>A few defaults worth knowing before the first run. A sandbox lives for an hour unless you pass <code>sandbox_timeout</code>, and when that runs out E2B pauses it rather than killing it. Internet access is on unless you turn it off with <code>allow_internet_access=False</code>. And Pydantic AI never kills a sandbox when a run ends: the application that created it owns its lifetime, and a sandbox you forget is a sandbox you are paying for. The <a href="https://pydantic.dev/docs/ai/harness/e2b-sandbox/">E2B sandbox guide</a> covers cleanup, including an <code>on_run_error</code> hook for runs that fail before there is a result to read a reference from.</p>
</section><section id="diagnose-pause-resume-fix-section"><h2 id="diagnose-pause-resume-fix" role="presentation"><a href="#diagnose-pause-resume-fix" class="heading-anchor"><button type="button" class="heading-anchor__btn">#</button></a><span role="heading" aria-level="2">Diagnose, pause, resume, fix</span></h2>
<p>The <a href="https://github.com/e2b-dev/e2b-cookbook/tree/main/examples/pydantic-ai-python">first cookbook example</a> gives the agent a small Python CLI that summarizes JSONL API request logs. Its tests fail: the CLI counts server errors wrong and computes p95 latency wrong. The agent gets two runs. The first reads the code and the failing tests and writes <code>diagnosis.md</code> without touching the source. The application then pauses the sandbox, builds a fresh backend attached to it, and a second run fixes the bug using the saved diagnosis and the first run's conversation history.</p>
<p>The agent definition is ordinary Pydantic AI. The only E2B-specific part is the capability:</p>
<pre><code class="hljs language-python"><span class="hljs-keyword">import</span> logfire
<span class="hljs-keyword">from</span> pydantic_ai <span class="hljs-keyword">import</span> Agent
<span class="hljs-keyword">from</span> pydantic_ai_harness.e2b_sandbox <span class="hljs-keyword">import</span> E2BSandbox
<span class="hljs-keyword">from</span> pydantic_ai_harness.filesystem <span class="hljs-keyword">import</span> FileSystem
<span class="hljs-keyword">from</span> pydantic_ai_harness.shell <span class="hljs-keyword">import</span> Shell

logfire.configure()
logfire.instrument_pydantic_ai()

WORKDIR = <span class="hljs-string">'/home/user/log-cli'</span>

agent = Agent(
    <span class="hljs-string">'openai:gpt-4.1-mini'</span>,
    name=<span class="hljs-string">'log_cli_fixer'</span>,
    instructions=<span class="hljs-string">'Work only in this sandbox project. Use the supplied tools; verify claims by running tests.'</span>,
    capabilities=[
        E2BSandbox(
            working_dir=WORKDIR,
            sandbox_timeout=<span class="hljs-number">600</span>,
            allow_internet_access=<span class="hljs-literal">False</span>,
        ),
        Shell(tools=[<span class="hljs-string">'run_command'</span>], default_timeout=<span class="hljs-number">20</span>, max_output_chars=<span class="hljs-number">6000</span>),
        FileSystem(tools=[<span class="hljs-string">'read_file'</span>, <span class="hljs-string">'write_file'</span>, <span class="hljs-string">'edit_file'</span>]),
    ],
)
</code></pre>
<p>The cookbook narrows the tool surface on purpose. <code>Shell</code> exposes only <code>run_command</code>, <code>FileSystem</code> exposes three file tools, and internet access is off because the fixture needs no downloads. A sandbox is a boundary, and a narrow tool list makes the boundary cheaper to reason about.</p>
<p>The application seeds the fixture before the agent starts, by constructing the backend itself and working in it through <code>Workspace</code>:</p>
<pre><code class="hljs language-python"><span class="hljs-keyword">from</span> pydantic_ai.workspaces <span class="hljs-keyword">import</span> Workspace
<span class="hljs-keyword">from</span> pydantic_ai_harness.e2b_sandbox <span class="hljs-keyword">import</span> E2BSandbox, E2BSandboxBackend

backend = E2BSandboxBackend(working_dir=WORKDIR, sandbox_timeout=<span class="hljs-number">600</span>, allow_internet_access=<span class="hljs-literal">False</span>)
workspace = Workspace(backend)
<span class="hljs-keyword">for</span> name <span class="hljs-keyword">in</span> (<span class="hljs-string">'log_stats.py'</span>, <span class="hljs-string">'test_log_stats.py'</span>, <span class="hljs-string">'requests.jsonl'</span>):
    <span class="hljs-keyword">await</span> workspace.write_bytes(name, (FIXTURE / name).read_bytes())

first = <span class="hljs-keyword">await</span> agent.run(DIAGNOSE, workspace=backend, usage_limits=limits())
ref = first.workspace.ref
</code></pre>
<p>Building the backend does no I/O. The first <code>write_bytes</code> creates the sandbox, and from then on <code>backend.ref</code> identifies it. The run result carries the same reference in <code>first.workspace.ref</code>.</p>
<p>Now the pause. The application asks the backend for the typed <code>e2b.AsyncSandbox</code>, pauses it, and then constructs a new backend that knows only the reference:</p>
<pre><code class="hljs language-python">sandbox = <span class="hljs-keyword">await</span> backend.get_sandbox()
<span class="hljs-keyword">assert</span> <span class="hljs-keyword">await</span> sandbox.pause()

attached = E2BSandbox(working_dir=WORKDIR, sandbox_timeout=<span class="hljs-number">600</span>).backend(ref)
continued = Workspace(attached)
<span class="hljs-keyword">assert</span> (<span class="hljs-keyword">await</span> continued.read_text(<span class="hljs-string">'diagnosis.md'</span>)).strip()

second = <span class="hljs-keyword">await</span> agent.run(
    FIX,
    workspace=ref,
    message_history=first.all_messages(),
    usage_limits=limits(),
)
<span class="hljs-keyword">assert</span> second.workspace.ref == ref
</code></pre>
<p>The attached backend's first file read resumes the paused sandbox. <a href="https://e2b.dev/docs/sandbox/persistence">E2B keeps a paused sandbox indefinitely</a>, filesystem and memory both, so <code>diagnosis.md</code> is where the first run left it. The second run gets <code>workspace=ref</code> to select the sandbox and <code>message_history</code> to carry the conversation. Either the ref or a history that names it will select the sandbox, but only the history carries what the agent already knows, and the cookbook passes both.</p>
<p>The example then does something I want more agent demos to do: it checks the agent's work instead of trusting the agent's summary. It restores the test file from the trusted host fixture, because a shell command can bypass a file tool's restrictions, confirms the input logs were not edited, and runs the tests itself. Four tests pass, the CLI prints the right counts, and the application kills the sandbox in a <code>finally</code> block and confirms it is gone from the account.</p>
<pre><code class="hljs language-text">Created sandbox: &#x3C;id>
Diagnosis saved. Model usage: ...
Paused sandbox: &#x3C;id>
Resumed sandbox: &#x3C;same id>; checksums unchanged before repair
...
Ran 4 tests ...
OK
CLI: {"requests": 4, "server_errors": 2, "p95_ms": 100}
Cleanup verified: &#x3C;same id>
</code></pre>
<p>The script asserts sandbox identity and SHA-256 checksums before and after the pause. The same id, the same bytes.</p>
</section><section id="kill-the-worker-keep-the-sandbox-section"><h2 id="kill-the-worker-keep-the-sandbox" role="presentation"><a href="#kill-the-worker-keep-the-sandbox" class="heading-anchor"><button type="button" class="heading-anchor__btn">#</button></a><span role="heading" aria-level="2">Kill the worker, keep the sandbox</span></h2>
<p>The pause-and-resume example proves the sandbox outlives a run. The <a href="https://github.com/e2b-dev/e2b-cookbook/tree/main/examples/pydantic-ai-temporal-python">Temporal example</a> proves it outlives the process that was driving the agent.</p>
<p>The task is the same log CLI. This time the two agent runs live inside a Temporal workflow, and between them the demo sends <code>SIGKILL</code> to the worker. No Python <code>finally</code>, no graceful shutdown. A new worker starts on the same task queue, Temporal replays the recorded history, and the workflow continues the repair in the sandbox the dead worker left behind.</p>
<p><code>TemporalDurability</code> joins the capability list and the agent is otherwise the one from the first example. The cookbook builds it in a shared <code>make_agent()</code> helper; written out in full, with the Temporal activity settings the example uses, it is:</p>
<pre><code class="hljs language-python"><span class="hljs-keyword">from</span> datetime <span class="hljs-keyword">import</span> timedelta

<span class="hljs-keyword">import</span> logfire
<span class="hljs-keyword">from</span> pydantic_ai <span class="hljs-keyword">import</span> Agent
<span class="hljs-keyword">from</span> pydantic_ai.durable_exec.temporal <span class="hljs-keyword">import</span> TemporalDurability
<span class="hljs-keyword">from</span> pydantic_ai_harness.e2b_sandbox <span class="hljs-keyword">import</span> E2BSandbox
<span class="hljs-keyword">from</span> pydantic_ai_harness.filesystem <span class="hljs-keyword">import</span> FileSystem
<span class="hljs-keyword">from</span> pydantic_ai_harness.shell <span class="hljs-keyword">import</span> Shell
<span class="hljs-keyword">from</span> temporalio.common <span class="hljs-keyword">import</span> RetryPolicy

logfire.configure()
logfire.instrument_pydantic_ai()

WORKDIR = <span class="hljs-string">'/home/user/log-cli'</span>

agent = Agent(
    <span class="hljs-string">'openai:gpt-4.1-mini'</span>,
    name=<span class="hljs-string">'log_cli_fixer'</span>,
    instructions=<span class="hljs-string">'Work only in this sandbox project. Use the supplied tools; verify claims by running tests.'</span>,
    capabilities=[
        E2BSandbox(working_dir=WORKDIR, sandbox_timeout=<span class="hljs-number">600</span>, allow_internet_access=<span class="hljs-literal">False</span>),
        Shell(tools=[<span class="hljs-string">'run_command'</span>], default_timeout=<span class="hljs-number">20</span>, max_output_chars=<span class="hljs-number">6000</span>),
        FileSystem(tools=[<span class="hljs-string">'read_file'</span>, <span class="hljs-string">'write_file'</span>, <span class="hljs-string">'edit_file'</span>]),
        TemporalDurability(
            activity_config={
                <span class="hljs-string">'start_to_close_timeout'</span>: timedelta(seconds=<span class="hljs-number">45</span>),
                <span class="hljs-string">'retry_policy'</span>: RetryPolicy(maximum_attempts=<span class="hljs-number">2</span>),
            },
        ),
    ],
)
</code></pre>
<p>The agent needs a <code>name</code>, and both it and the workflow must be defined at module level so Temporal can register the activities. Both worker processes import the same module.</p>
<p>The workflow takes the sandbox reference as its input. That matters: the controller creates and seeds one sandbox, then hands the workflow a <code>WorkspaceRef</code>, which holds no credentials. Temporal records that input before any worker touches the agent, so whichever worker ends up running the second half of the job knows which sandbox to attach to.</p>
<p>This is the cookbook's <code>workflow.py</code>, trimmed to the parts that matter. <code>DIAGNOSE</code>, <code>FIX</code>, <code>fingerprints</code>, and <code>limits</code> are the prompts, the checksum helper, and the <code>UsageLimits</code> from the example's <code>project.py</code>:</p>
<pre><code class="hljs language-python"><span class="hljs-keyword">from</span> temporalio <span class="hljs-keyword">import</span> workflow

<span class="hljs-keyword">with</span> workflow.unsafe.imports_passed_through():
    <span class="hljs-keyword">from</span> agent <span class="hljs-keyword">import</span> agent
    <span class="hljs-keyword">from</span> project <span class="hljs-keyword">import</span> DIAGNOSE, FIX, fingerprints, limits
    <span class="hljs-keyword">from</span> pydantic_ai.durable_exec.temporal <span class="hljs-keyword">import</span> PydanticAIWorkflow
    <span class="hljs-keyword">from</span> pydantic_ai.workspaces <span class="hljs-keyword">import</span> WorkspaceRef


<span class="hljs-meta">@workflow.defn</span>
<span class="hljs-keyword">class</span> <span class="hljs-title class_">FixLogCLI</span>(<span class="hljs-title class_ inherited__">PydanticAIWorkflow</span>):
    __pydantic_ai_agents__ = (agent,)

    <span class="hljs-keyword">def</span> <span class="hljs-title function_">__init__</span>(<span class="hljs-params">self</span>):
        self.checkpoint = <span class="hljs-literal">None</span>
        self.proceed = <span class="hljs-literal">False</span>

<span class="hljs-meta">    @workflow.query</span>
    <span class="hljs-keyword">def</span> <span class="hljs-title function_">diagnosis_checkpoint</span>(<span class="hljs-params">self</span>) -> <span class="hljs-built_in">dict</span> | <span class="hljs-literal">None</span>:
        <span class="hljs-keyword">return</span> self.checkpoint

<span class="hljs-meta">    @workflow.signal</span>
    <span class="hljs-keyword">def</span> <span class="hljs-title function_">continue_fix</span>(<span class="hljs-params">self</span>) -> <span class="hljs-literal">None</span>:
        self.proceed = <span class="hljs-literal">True</span>

<span class="hljs-meta">    @workflow.run</span>
    <span class="hljs-keyword">async</span> <span class="hljs-keyword">def</span> <span class="hljs-title function_">run</span>(<span class="hljs-params">self, ref: WorkspaceRef</span>) -> <span class="hljs-built_in">dict</span>:
        first = <span class="hljs-keyword">await</span> agent.run(DIAGNOSE, workspace=ref, usage_limits=limits())
        saved = <span class="hljs-keyword">await</span> fingerprints(first.workspace)
        self.checkpoint = {<span class="hljs-string">'sandbox_id'</span>: ref.<span class="hljs-built_in">id</span>, <span class="hljs-string">'checksums'</span>: saved}

        <span class="hljs-keyword">await</span> workflow.wait_condition(<span class="hljs-keyword">lambda</span>: self.proceed, timeout=<span class="hljs-number">180</span>)
        <span class="hljs-keyword">assert</span> <span class="hljs-keyword">await</span> fingerprints(first.workspace) == saved
        second = <span class="hljs-keyword">await</span> agent.run(
            FIX,
            workspace=ref,
            message_history=first.all_messages(),
            usage_limits=limits(),
        )
        <span class="hljs-keyword">return</span> {<span class="hljs-string">'sandbox_id'</span>: ref.<span class="hljs-built_in">id</span>, <span class="hljs-string">'summary'</span>: second.output}
</code></pre>
<p>The <code>wait_condition</code> between diagnosis and repair gives the crash a repeatable place to happen. The controller polls the <code>diagnosis_checkpoint</code> query until the first run has saved its diagnosis, kills the worker, starts another, polls the same query again, and only then sends <code>continue_fix</code>. The recovered checkpoint matches the one the dead worker recorded.</p>
<pre><code class="hljs language-text">Created sandbox: &#x3C;id>
Worker started: pid=&#x3C;first pid>
Durable checkpoint: &#x3C;id>; diagnosis and files saved
Worker crashed: pid=&#x3C;first pid>, exit=-9
Worker started: pid=&#x3C;different pid>
Checkpoint recovered by pid=&#x3C;different pid>; sandbox=&#x3C;same id>
...
Ran 4 tests ...
OK
Exactly one sandbox; original workflow completed after worker restart
Cleanup verified: &#x3C;same id>
</code></pre>
<p>The final resource check is the line I would read first. Exactly one new sandbox exists in the account after the whole sequence, running or paused. A naive recovery would have created a second one and started the job over in an empty directory. <code>E2BSandbox</code> raises <code>WorkspaceUnavailableError</code> when a reference points at a sandbox that no longer exists, rather than quietly provisioning a replacement. Recovery either continues where the diagnosis left off or fails loudly.</p>
<p>The cookbook README is careful about what this does and does not prove, and the care is worth repeating. The crash happens at an idle checkpoint, with no command in flight. Temporal activities can run again if a worker disappears before completion is recorded, so shell commands are at-least-once, not exactly-once. Recovery does not roll back file writes. Write tools that replace a named result rather than appending to one, and you get the same answer however many times the activity runs.</p>
</section><section id="where-the-trace-goes-section"><h2 id="where-the-trace-goes" role="presentation"><a href="#where-the-trace-goes" class="heading-anchor"><button type="button" class="heading-anchor__btn">#</button></a><span role="heading" aria-level="2">Where the trace goes</span></h2>
<p><code>E2BSandbox</code> emits no spans of its own. Pydantic AI's instrumentation records the sandbox on the agent run span as <code>pydantic_ai.workspace.provider</code> and <code>pydantic_ai.workspace.id</code>, and every command or file operation a tool makes runs inside that tool call's span. With the two <code>logfire</code> lines from the snippets above in place, <a href="https://pydantic.dev/logfire">Pydantic Logfire</a> shows the diagnosis run and the resumed run, each <code>run_command</code> inside them, and the same sandbox id on both, so a trace matches up with the E2B dashboard. In the Temporal example the two runs sit under the same workflow, so the crash reads as a gap between two activities rather than as two unrelated jobs.</p>
<p>If you are not sending traces yet, <a href="https://pydantic.dev/logfire">Pydantic Logfire</a> has a Personal plan with 10 million telemetry records a month and a $0 hard cap, which is plenty for both cookbook examples. Create a project, run <code>logfire auth</code> once, and the two lines in the snippets above do the rest: every model request, every <code>run_command</code>, and the sandbox id that ties a run to the E2B dashboard, in one trace you can query with SQL.</p>
</section><section id="choosing-e2b-over-modal-or-both-section"><h2 id="choosing-e2b-over-modal-or-both" role="presentation"><a href="#choosing-e2b-over-modal-or-both" class="heading-anchor"><button type="button" class="heading-anchor__btn">#</button></a><span role="heading" aria-level="2">Choosing E2B over Modal, or both</span></h2>
<p>Pydantic AI Harness also ships <a href="https://pydantic.dev/docs/ai/harness/modal-sandbox/"><code>ModalSandbox</code></a>, which we wrote about <a href="https://pydantic.dev/articles/harness-modal">during Harness Week</a>. Both put the agent's shell in an isolated environment you did not provision, and both are one capability in the list. The Modal post was about fan-out: five hundred containers for six minutes each, gone when the suites finish. This one is about keeping a sandbox: pause it after a run, store the reference, resume it next week with the clone, the virtualenv, and the half-finished branch still there. A coding session that spans many agent runs, or a workflow that must survive its own worker, is the E2B shape. A test matrix is the Modal shape. Nothing stops an application from using one for each.</p>
</section><section id="get-started-section"><h2 id="get-started" role="presentation"><a href="#get-started" class="heading-anchor"><button type="button" class="heading-anchor__btn">#</button></a><span role="heading" aria-level="2">Get started</span></h2>
<p>Both cookbook examples run from a checkout with <code>uv sync --locked</code> and two environment variables, <code>E2B_API_KEY</code> and a model provider key. Each agent run is bounded to eight model requests and a $0.10 estimated-cost limit through <code>UsageLimits</code>, so a mistake in the prompt is cheap to find. The cost estimate depends on provider pricing data, the final request can exceed it, and neither limit is an account spending cap. The Temporal example starts its own local dev server and needs no Docker.</p>
<ul>
<li>New to <a href="https://pydantic.dev/docs/ai/">Pydantic AI</a>? The quick start takes about five minutes, and <code>E2BSandbox</code> is one capability in the list once you have an agent that runs. The install command at the top of this post covers every example here, including the Temporal one.</li>
<li><a href="https://pydantic.dev/docs/ai/harness/e2b-sandbox/">E2B sandbox guide</a> in the Pydantic AI docs, including configuration, cleanup hooks, and the dev-server preview pattern.</li>
<li><a href="https://github.com/e2b-dev/e2b-cookbook/tree/main/examples/pydantic-ai-python">Pause and resume example</a> in the E2B cookbook.</li>
<li><a href="https://github.com/e2b-dev/e2b-cookbook/tree/main/examples/pydantic-ai-temporal-python">Temporal crash-recovery example</a> in the E2B cookbook.</li>
<li><a href="https://pydantic.dev/docs/ai/capabilities/durable_execution/temporal/">Durable execution with Temporal</a> in the Pydantic AI docs.</li>
<li><a href="https://e2b.dev/docs/sandbox/persistence">E2B sandbox persistence</a> for what pause and resume preserve, and for how long.</li>
</ul>
<p>The agent still runs <code>python -m unittest</code> and edits files. It just does it somewhere that is not your laptop, and picks up where it left off when you ask it to.</p></section>]]></content:encoded>
</item>
<item>
<title>Pydantic runs on RunsOn</title>
<link>https://pydantic.dev/articles/ai-oh-my-ci</link>
<guid isPermaLink="true">https://pydantic.dev/articles/ai-oh-my-ci</guid>
<pubDate>Fri, 16 Oct 2026 09:00:00 GMT</pubDate>
<dc:creator>Bill Easton</dc:creator>
<category>Engineering</category>
<category>AI</category>
<category>CI/CD</category>
<description>How we moved Logfire&apos;s million-minute CI workload to RunsOn and used ARM, Spot, caching, and right-sized EC2 instances to cut our monthly CI bill by roughly two-thirds.</description>
<content:encoded><![CDATA[<p><a href="https://runs-on.com/">Pydantic runs on RunsOn</a>. We moved to RunsOn on September 1. It launches ephemeral EC2 runners for Logfire's GitHub Actions workflows in our AWS account. Logfire is built in our <code>pydantic/platform</code> repository. Previously, we used a mix of GitHub Actions, Depot, and Ubicloud for our CI infrastructure.</p>
<p>Why did we make the move? Our CI bill rose from $3,990 in June to $10,778 in July, nearly three times April's spend. By August, it had reached $18,200. By August 30, the Logfire team had merged 2,032 pull requests that month. Over the same 30 days in 2025, a team of the same size merged 365 pull requests. Our CI costs were exploding as the team adopted AI and began shipping more than ever before.</p>
<section id="the-growth-was-not-slowing-down-section"><h2 id="the-growth-was-not-slowing-down" role="presentation"><a href="#the-growth-was-not-slowing-down" class="heading-anchor"><button type="button" class="heading-anchor__btn">#</button></a><span role="heading" aria-level="2">The growth was not slowing down</span></h2>
<div class="overflow-x-auto table-wrapper" tabindex="0"><table>
<thead>
<tr>
<th>Month</th>
<th>Total CI cost</th>
<th>Total runner minutes</th>
</tr>
</thead>
<tbody>
<tr>
<td>April 2026</td>
<td>$3,813</td>
<td>—</td>
</tr>
<tr>
<td>May 2026</td>
<td>$3,665</td>
<td>—</td>
</tr>
<tr>
<td>June 2026</td>
<td>$3,990</td>
<td>—</td>
</tr>
<tr>
<td>July 2026</td>
<td>$10,778</td>
<td>—</td>
</tr>
<tr>
<td>August 2026</td>
<td>$18,200</td>
<td>1,230,264</td>
</tr>
<tr>
<td>September 2026</td>
<td>$5,700</td>
<td>1,617,654</td>
</tr>
</tbody>
</table></div>
<p>The main CI workflow in <code>pydantic/platform</code> ran 4,194 times in May, 6,669 times in June, 11,919 times in July, and 20,659 times through August 30. Growth continued after the move: runner minutes rose from 1,230,264 in August to 1,617,654 in September, while total CI cost fell to $5,700.</p>
<p><img src="https://pydantic.dev/assets/blog/ai-oh-my-ci/ci-execution-minutes.svg" alt="Two charts show pydantic/platform CI growth and actual monthly costs through September 2026. Main CI workflow runs per full UTC week rise from 753 during April 6–12 to 8,082 during September 21–27. Monthly CI cost rises from $3,813 in April to $18,200 in August, then falls to $5,700 in September after the move to RunsOn on September 1. September includes the RunsOn license and all AWS costs." decoding="async"></p>
<p>We weren't delivering slop. We shipped real products, added important tests, improved browser coverage, and ran significantly more automated reviews. AI accelerated all of it. A repository that once merged hundreds of pull requests per month now merges thousands, with bots creating much of that activity and responding to the rest. RunsOn gave us a way to absorb that growth without slowing the team down.</p>
</section><section id="why-runson-section"><h2 id="why-runson" role="presentation"><a href="#why-runson" class="heading-anchor"><button type="button" class="heading-anchor__btn">#</button></a><span role="heading" aria-level="2">Why RunsOn</span></h2>
<p>With RunsOn, GitHub still orchestrates every workflow, while fresh EC2 runners start in our AWS account and disappear when the job finishes. We did not have to replace GitHub's CI control plane or build our own runner platform to control the machines, networking, storage, and cost underneath it.</p>
<p>Once RunsOn was installed in our AWS account and connected to GitHub, ordinary jobs mainly needed a different runner label and the RunsOn setup action. Container builds needed some additional cache and registry changes.</p>
<p>GitHub Actions and managed runner services had let us reach this scale without operating a runner fleet. Above a million runner minutes per month, we wanted more control over which machines we paid for. RunsOn handles the runner lifecycle. We still manage our AWS account, runner catalog, capacity strategy, storage, cache policy, quotas, and telemetry. <a href="https://runs-on.com/blog/runson-break-even/">RunsOn pays for itself at 22 jobs per day</a>, a threshold we were well past.</p>
<p>Today, our catalog ranges from one-core ARM runners to 16-core image builders. Most Python, TypeScript, agentic, and control-plane jobs run on Graviton; x64 remains for container builds and tests that require it. Each preset contains several eligible EC2 families so the Spot allocator has more capacity pools to choose from. RunsOn's <a href="https://runs-on.com/docs/performance/caching/actions/">Magic Cache</a> serves existing <code>actions/cache</code> calls close to the runners, while sticky EBS disks preserve expensive BuildKit state.</p>
<p>We did not make every job Spot. Merge-queue validation, release publishing, deployments, and jobs with expensive restarts use On-Demand instances. Long, interruption-sensitive jobs use capacity-optimized Spot placement. Shorter jobs use price-capacity-optimized placement. The private deployment spans three availability zones, and a circuit breaker temporarily sends new jobs to On-Demand after a burst of interruptions. This sounds complex, but RunsOn does the heavy lifting.</p>
<p>September was our first month on RunsOn. Our total CI cost was $5,700, down from $18,200 in August. That includes the RunsOn license and all AWS costs: compute, EBS, S3 cache storage, and data transfer.</p>
</section><section id="what-we-learned-section"><h2 id="what-we-learned" role="presentation"><a href="#what-we-learned" class="heading-anchor"><button type="button" class="heading-anchor__btn">#</button></a><span role="heading" aria-level="2">What we learned</span></h2>
<p>Three rules mattered more than any individual instance type:</p>
<ul>
<li><strong>Use Spot where retries are cheap.</strong> Keep the merge queue and release paths on On-Demand capacity.</li>
<li><strong>Right-size against the critical path.</strong> The cheapest runner is the one that meets the workload's latency target at the lowest total cost.</li>
<li><strong>Keep cache near the compute.</strong> Retain it only while it is likely to be reused.</li>
</ul>
<p>AI increased the amount we could deliver, and our CI bill grew with it. We did not ask the agents to stop. We changed where their builds and tests ran, then kept tuning the machines, caches, and capacity as the workload grew.</p></section>]]></content:encoded>
</item>
<item>
<title>The code is the graph</title>
<link>https://pydantic.dev/articles/the-code-is-the-graph</link>
<guid isPermaLink="true">https://pydantic.dev/articles/the-code-is-the-graph</guid>
<pubDate>Tue, 13 Oct 2026 09:00:00 GMT</pubDate>
<dc:creator>Samuel Colvin</dc:creator>
<category>Pydantic Monty</category>
<category>Pydantic AI</category>
<description>Graphs are dead, long live graphs. A graph library can be typed, parallel, or snapshotted, but not all three, and every one of them fights the call stack. The graph that works is code, and Monty runs it.</description>
<content:encoded><![CDATA[<!-- cspell:ignore Fateev Montague -->
<section id="tldr-section"><h2 id="tldr" role="presentation"><a href="#tldr" class="heading-anchor"><button type="button" class="heading-anchor__btn">#</button></a><span role="heading" aria-level="2">TL;DR</span></h2>
<p>Graph libraries are a mistake. Your code IS the graph.</p>
<p>Code gives you type safety from type hints, parallel execution from async, and durable execution from Temporal outside the sandbox and Monty inside it.</p>
</section><section id="introduction-section"><h2 id="introduction" role="presentation"><a href="#introduction" class="heading-anchor"><button type="button" class="heading-anchor__btn">#</button></a><span role="heading" aria-level="2">Introduction</span></h2>
<p>There has been a lot of discussion lately of graphs and loops versus prompting as the way to drive agents. Some argue that prompting is over: build graphs and loops instead, let the agents build themselves from there, and graph engineering becomes the default architecture for serious agentic systems within six months.</p>
<p>I agree with half of that. Humans writing code is going away. Developers get a harder and more interesting job instead: formulating the problem. Choose the metrics an agent should optimize and the constraints it has to respect, write the <a href="https://pydantic.dev/docs/ai/evals/evals/">evals</a> that measure them, then make it fast and easy for the agent to iterate. That's worth more than writing the code ever was.</p>
<p>The other half I think is wrong, and I say that as someone who built a graph library. Graphs as most people know them (nodes and edges handed to a library that walks them for you) are a mistake. The only graph that works is code itself.</p>
<p>For a long time I wondered whether that was just a reaction to my strong dislike of LangGraph and its disregard for type safety. I'm now convinced it's not: graphs that implement durability at node boundaries and support parallel node execution are fundamentally incompatible with type safety, but the case against graphs is much stronger than just type safety.</p>
<p>But when agents are defining the graph, and the graph is code, the question becomes how to run the code? That is why we built <a href="https://pydantic.dev/articles/pydantic-monty">Monty</a>, a sandboxed Python interpreter written for exactly this.</p>
<p>Here is what I mean by a graph that is code. <code>reviewer</code> and <code>summarize</code> are sub-agents, each an async function with a typed result, and this is the function that calls them:</p>
<pre><code class="hljs language-python"><span class="hljs-keyword">async</span> <span class="hljs-keyword">def</span> <span class="hljs-title function_">review_comments</span>(<span class="hljs-params">comments: <span class="hljs-built_in">list</span>[<span class="hljs-built_in">str</span>]</span>) -> <span class="hljs-built_in">str</span> | <span class="hljs-literal">None</span>:
    reviews = <span class="hljs-keyword">await</span> asyncio.gather(*(reviewer(task=c) <span class="hljs-keyword">for</span> c <span class="hljs-keyword">in</span> comments))
    issues = [r.issues <span class="hljs-keyword">for</span> r <span class="hljs-keyword">in</span> reviews <span class="hljs-keyword">if</span> r.issues]
    <span class="hljs-keyword">if</span> issues:
        <span class="hljs-keyword">return</span> <span class="hljs-keyword">await</span> summarize(issues)
</code></pre>
<p>Fan out, join, branch. That is a graph, and it's also a Python function: <code>ty</code> checks that <code>summarize</code> accepts <code>issues</code>, the call stack is the run state, and a model can write it in one tool call. This is pure, canonical Python and therefore easy for the agent to write. Monty runs it safely, and can snapshot and resume at every external function call (<code>reviewer</code> and <code>summarize</code> in this case).</p>
</section><section id="every-graph-fights-the-call-stack-section"><h2 id="every-graph-fights-the-call-stack" role="presentation"><a href="#every-graph-fights-the-call-stack" class="heading-anchor"><button type="button" class="heading-anchor__btn">#</button></a><span role="heading" aria-level="2">Every graph fights the call stack</span></h2>
<p>Your program already has state: the values in its variables, where execution has reached, and the calls waiting to return. A graph library adds another representation of that state, which you then have to keep consistent with the code.</p>
<p><code>if</code> is a branch. <code>for</code> is a loop. A function call is an edge, <code>except</code> is the failure edge, a <code>for</code> around a <code>try</code> is a retry, and <code>await asyncio.gather(...)</code> is a fan-out and a join. The call stack records where you are and a stack trace tells you how you got there. It has a debugger, a profiler, a type checker, and every programmer and every model already knows it. The formal name is structured control flow. Everyone else calls it code.</p>
<p>A graph library rebuilds all of that, worse. Nodes are functions you can't call. Edges are registration calls. State is a dict merged by reducers, or a dataclass mutated at moments you don't control, instead of a local variable. And "where is the run right now" is answered by the library's own iterator instead of a trace in your observability tool.</p>
<p>Here's the fan-out example <a href="https://pydantic.dev/docs/ai/graph/builder/">from our own docs</a>, picked deliberately:</p>
<pre><code class="hljs language-python"><span class="hljs-keyword">import</span> asyncio
<span class="hljs-keyword">from</span> dataclasses <span class="hljs-keyword">import</span> dataclass

<span class="hljs-keyword">from</span> pydantic_graph <span class="hljs-keyword">import</span> GraphBuilder, StepContext, reduce_list_append


<span class="hljs-meta">@dataclass</span>
<span class="hljs-keyword">class</span> <span class="hljs-title class_">SimpleState</span>:
    <span class="hljs-keyword">pass</span>


<span class="hljs-keyword">async</span> <span class="hljs-keyword">def</span> <span class="hljs-title function_">main</span>():
    g = GraphBuilder(state_type=SimpleState, output_type=<span class="hljs-built_in">list</span>[<span class="hljs-built_in">int</span>])

<span class="hljs-meta">    @g.step</span>
    <span class="hljs-keyword">async</span> <span class="hljs-keyword">def</span> <span class="hljs-title function_">generate_list</span>(<span class="hljs-params">ctx: StepContext[SimpleState, <span class="hljs-literal">None</span>, <span class="hljs-literal">None</span>]</span>) -> <span class="hljs-built_in">list</span>[<span class="hljs-built_in">int</span>]:
        <span class="hljs-keyword">return</span> [<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>, <span class="hljs-number">5</span>]

<span class="hljs-meta">    @g.step</span>
    <span class="hljs-keyword">async</span> <span class="hljs-keyword">def</span> <span class="hljs-title function_">square</span>(<span class="hljs-params">ctx: StepContext[SimpleState, <span class="hljs-literal">None</span>, <span class="hljs-built_in">int</span>]</span>) -> <span class="hljs-built_in">int</span>:
        <span class="hljs-keyword">return</span> ctx.inputs * ctx.inputs

    collect = g.join(reduce_list_append, initial_factory=<span class="hljs-built_in">list</span>[<span class="hljs-built_in">int</span>])

    g.add(
        g.edge_from(g.start_node).to(generate_list),
        g.edge_from(generate_list).<span class="hljs-built_in">map</span>().to(square),
        g.edge_from(square).to(collect),
        g.edge_from(collect).to(g.end_node),
    )

    graph = g.build()
    result = <span class="hljs-keyword">await</span> graph.run(state=SimpleState())
    <span class="hljs-built_in">print</span>(<span class="hljs-built_in">sorted</span>(result))
    <span class="hljs-comment">#> [1, 4, 9, 16, 25]</span>


asyncio.run(main())
</code></pre>
<p>And the same program:</p>
<pre><code class="hljs language-python"><span class="hljs-keyword">import</span> asyncio


<span class="hljs-keyword">async</span> <span class="hljs-keyword">def</span> <span class="hljs-title function_">square</span>(<span class="hljs-params">n: <span class="hljs-built_in">int</span></span>) -> <span class="hljs-built_in">int</span>:
    <span class="hljs-keyword">return</span> n * n


<span class="hljs-keyword">async</span> <span class="hljs-keyword">def</span> <span class="hljs-title function_">main</span>():
    squares = <span class="hljs-keyword">await</span> asyncio.gather(*(square(n) <span class="hljs-keyword">for</span> n <span class="hljs-keyword">in</span> [<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>, <span class="hljs-number">5</span>]))
    <span class="hljs-built_in">print</span>(<span class="hljs-built_in">sorted</span>(squares))
    <span class="hljs-comment">#> [1, 4, 9, 16, 25]</span>


asyncio.run(main())
</code></pre>
<p>The second one is typed with nothing added, you can put a <code>breakpoint()</code> in it, and the fan-out is one line. A human reads it in seconds and so does a model. The first one is the kind of thing I was proud of last year.</p>
<p>The diagram is still useful, it's the thing you draw <em>about</em> the code, which is why <a href="https://pydantic.dev/docs/ai/graph/graph/">pydantic-graph</a> renders Mermaid.</p>
<p>For agents it's worse, because the control flow an agent needs is rarely known before the run. That argument is right about this part: the unit of work is a loop with a check in it, designed around the task. A fixed graph wired up by a human in advance is a prompt with extra steps.</p>
</section><section id="typed-snapshotted-parallel-pick-two-section"><h2 id="typed-snapshotted-parallel-pick-two" role="presentation"><a href="#typed-snapshotted-parallel-pick-two" class="heading-anchor"><button type="button" class="heading-anchor__btn">#</button></a><span role="heading" aria-level="2">Typed, snapshotted, parallel: pick two</span></h2>
<p>There is a CAP theorem for graphs. Anyone building a graph agent wants three things:</p>
<ol>
<li>type safety, so the checker catches node A handing node B something it can't take;</li>
<li>parallel execution, so you can fan out and join;</li>
<li>snapshots of the graph state, so a crashed run resumes from the last node instead of starting over.</li>
</ol>
<p>I haven't found a graph API that gives all three, and after trying to build one I don't think it can be done.</p>
<p>Typed means a node reads and writes the state as an ordinary object, and the edge out of a node is its return type, so a type checker checks both. Parallel means more than one node in flight at once. Snapshotted means that at a node boundary the whole run is a value you can serialize, and resuming from it gives the same result as never having stopped.</p>
<p>In the original pydantic-graph the snapshot was literally <code>NodeSnapshot(state, next_node)</code>: the state, plus where we are. It was typed and resumable because "where we are" was one node.</p>
<p>Add parallelism and "where we are" becomes a set of in-flight nodes and half-filled joins, while several of those nodes are mutating the one state object. Say one of them makes three updates. When the snapshot is written, how many of the three have happened? Resume from it and the second update runs twice, or never. There is no moment at which the state is a coherent value except a barrier where nothing is in flight, so node boundaries stop being run boundaries. You could snapshot only at barriers, but then a crash inside a step loses the step, and a node that wrote half its changes before the crash has already corrupted the state you were about to save, with no undo, because the writes were in place. Nor can you just re-run the nodes that were in flight. The runner has no idea whether a node touched the outside world, or whether doing it twice is harmless. It sent the email or it didn't, and the graph can't tell.</p>
<p>So to snapshot under parallelism, nodes must stop writing the state. They return a description of a change and the runtime applies it at a commit point. That is the step that costs you the types. Two nodes' changes arrive in no fixed order, so applying them has to be order-independent, which means a merge rule per field, declared outside the node code. The checker can verify the rule's signature. It can't verify the rule is commutative, and it can't verify the state's cross-field invariants hold after two partial updates land. More generally, any join of parallel branches that both touched state needs a semantic merge, and no type system checks a semantic merge. Joining outputs is fine, <code>gather</code> returns a typed tuple. Joining state is the problem.</p>
<p>Each side of the triangle is a real system.</p>
<p><strong>Parallel and snapshotted, so the merge leaves the type system.</strong> That's LangGraph. Nodes return updates instead of mutating state, and a checkpoint is written <a href="https://docs.langchain.com/oss/python/langgraph/persistence">after every super-step</a>. When two nodes in the same step write the same key, a reducer declared in an <code>Annotated</code> type hint merges the writes, and without one <a href="https://docs.langchain.com/oss/python/langgraph/errors/INVALID_CONCURRENT_GRAPH_UPDATE">the graph raises</a>. It works. The state can be typed, and so can the reducer's signature, but the merge itself is out of reach. A node's write used to be a statement a type checker could read; now it's data.</p>
<p><strong>Typed and snapshotted, so sequential.</strong> That was the original pydantic-graph, where <code>FullStatePersistence</code> saved the state and the one next node, and only one node ever ran at a time.</p>
<p><strong>Typed and parallel, so no snapshots.</strong> That's pydantic-graph today. We looked for a long time for an API that stayed typed and could still be snapshotted, and every version either turned into reducer annotations or needed more generics than anyone would put up with. So <code>pydantic_graph.persistence</code> <a href="https://pydantic.dev/docs/ai/graph/builder/#persistence-and-resumability">was removed in V2</a> and durability went to engines built for it. As David Montague, who designed the graph builder API, <a href="https://github.com/pydantic/pydantic-ai/issues/530#issuecomment-3504609992">put it</a>: "durable execution is the practical solution to most practical end-user challenges". What's left is a typed state machine with no durability and no snapshots of its own. Those come from Temporal replaying the code around it, and the graph machinery is, if anything, one more thing that has to replay deterministically.</p>
<p>Temporal escapes the triangle by never snapshotting application state at all. It records the result of each activity as it completes and re-runs your code to rebuild the state, so "how many of the three updates had happened" is answered by running the code again. An activity interrupted mid-flight may run twice, and the activity boundary is where you, not the runner, declare what touches the outside world and whether it's safe to retry.</p>
<p>Code dissolves the whole thing. In code the join of state is something you write, in the language: <code>a, b = await gather(fa(), fb())</code>, then the line that combines them. The merge is typed and ordered because you wrote it, and durability comes from an engine replaying that code. The graph library's problem was that it tried to do the merge for you, generically, and that's the part that can't be typed.</p>
<p>Monty is how the same answer works inside the sandbox, where there is no Temporal. The interpreter holds no operating system resources: no sockets, no file descriptors, no threads. Every parallel branch of the script is a host function the sandbox is waiting on, so at the moment it pauses, everything in flight is outside the interpreter and the interpreter itself, heap and call stack included, is a coherent value a few kilobytes long. That is the barrier the graph libraries couldn't find, and code gets it for free, because the only state is local variables and the only places anything crosses the boundary are the calls you wrote. A <code>gather</code> over three sub-agents pauses as one snapshot with three pending calls, and you resume it, in another process if you like, by handing back their results. The host function is still where you decide what touches the outside world and whether running it twice is safe, exactly like an activity. The join is a line of Python, so it is typed, and the state is the interpreter, so it snapshots.</p>
</section><section id="long-live-graphs-section"><h2 id="long-live-graphs" role="presentation"><a href="#long-live-graphs" class="heading-anchor"><button type="button" class="heading-anchor__btn">#</button></a><span role="heading" aria-level="2">Long live graphs</span></h2>
<p>Prime Intellect <a href="https://www.primeintellect.ai/blog/prime-agent-rust">rewrote Prime Agent from TypeScript to Rust</a> this month. More than 2,000 agents did the work over two weeks, and the result starts roughly 14x faster. The orchestration: a root agent sorted the work into a topological order of tasks and wrote no product code. Each task went through a planner, an implementer, a reviewer, and a verifier, and a failed review or verification sent the task back to the implementer. They describe it as a factory of finite state machines. Look at the shape of it: a <code>for</code> over tasks, and inside each one a <code>while</code> with a <code>try</code>.</p>
<p>The question is what the agent writes that loop in, and how you run it. If a model is going to write Python that calls your sub-agents and your tools, you need to execute it without a human reading it first, and without handing over your filesystem and your network. That's Monty's job: the only way out of the sandbox is a function the host registered. There is no container to start and no network call, so the graph can be rewritten on every turn.</p>
<p>This is already how <a href="https://pydantic.dev/docs/ai/harness/dynamic-workflow/">Pydantic AI Harness</a> does multi-agent coordination. Each sub-agent is an async function. The orchestrator gets one tool, <code>run_workflow</code>, and writes the choreography:</p>
<pre><code class="hljs language-python"><span class="hljs-keyword">import</span> asyncio

reports = <span class="hljs-keyword">await</span> asyncio.gather(
    reviewer(task=<span class="hljs-string">"Review auth.py for bugs:\n&#x3C;file contents>"</span>),
    reviewer(task=<span class="hljs-string">"Review parser.py for bugs:\n&#x3C;file contents>"</span>),
)
<span class="hljs-keyword">await</span> summarizer(task=<span class="hljs-string">"Summarize these review findings:\n"</span> + <span class="hljs-string">"\n\n"</span>.join(reports))
</code></pre>
<p>Retries and voting are the same Python as everywhere else: a <code>for</code> around a <code>try</code>, a list comprehension over the results. Only the last value returns to the model's context. The script is type-checked against the sub-agent signatures first, so a misspelled function or a wrong-typed argument is rejected before any sub-agent runs.</p>
<p>The graph you want to look at is the one the run actually took, not the one someone drew before it. Sub-agents are Pydantic AI agents, so each run and model call is an OpenTelemetry span in the orchestrator's trace, in <a href="https://pydantic.dev/docs/logfire/integrations/llms/pydanticai/">Logfire</a> or any other backend. The fan-out, the join and every retry show up nested the way the code was written, which is why agent observability needs no graph visualizer: the trace is the drawing.</p>
<p>Durability is the same answer as before. <a href="https://pydantic.dev/docs/ai/harness/dynamic-workflow/#running-inside-a-temporal-workflow">Attach Temporal</a> (or any <a href="https://pydantic.dev/docs/ai/capabilities/durable_execution/overview/">other durable execution engine</a>) to the orchestrator and to the sub-agents whose model calls should be activities, and the script the model wrote is replayed against the recorded sub-agent results. The script itself doesn't change.</p>
</section><section id="keep-drawing-graphs-section"><h2 id="keep-drawing-graphs" role="presentation"><a href="#keep-drawing-graphs" class="heading-anchor"><button type="button" class="heading-anchor__btn">#</button></a><span role="heading" aria-level="2">Keep drawing graphs</span></h2>
<p>Draw graphs. Put them in design docs, render them from code, use them to explain a run after the fact. Do not execute them. The runtime for a graph already exists, it's the one your language ships with, and when the author of the graph is a model, give it <a href="https://pydantic.dev/docs/monty/get-started/">Monty</a> rather than a library of nodes. Michael Pfaffenberger measured what that buys in <a href="https://pydantic.dev/articles/why-code-mode-is-the-future">code mode vs tool calling across 5,276 graded runs</a>.</p>
<p>The human side of this, formulating the problem and setting up feedback, like evals that score every run, so the model's randomness can only push in the direction you want, is my talk at <a href="https://fastapiconf.com/speakers/#samuel-colvin">FastAPI Conf</a> in Amsterdam on October 28.</p></section>]]></content:encoded>
</item>
<item>
<title>Announcement: Pydantic v2.14 Release</title>
<link>https://pydantic.dev/articles/pydantic-v2-14-release</link>
<guid isPermaLink="true">https://pydantic.dev/articles/pydantic-v2-14-release</guid>
<pubDate>Thu, 08 Oct 2026 00:00:00 GMT</pubDate>
<dc:creator>Victorien Plot</dc:creator>
<category>Pydantic Validation</category>
<category>Release</category>
<category>New Features</category>
<category>Announcements</category>
<description>Pydantic v2.14 adds Python 3.15 support, with lazy imports and TypeForm, stabilizes the MISSING sentinel, and speeds up schema generation.</description>
<content:encoded><![CDATA[<!-- cspell:ignore jaideeppyne -->
<p><a href="https://github.com/pydantic/pydantic/releases/tag/v2.14.0">Pydantic v2.14</a> was released on October 8th.
You can install it now from <a href="https://pypi.org/project/pydantic/">PyPI</a>:</p>
<pre><code class="hljs language-bash">pip install --upgrade pydantic
</code></pre>
<p>This release features the work of 13 external contributors and provides various new features, performance improvements, and bug fixes.
Several minor changes (considered non-breaking changes according to our <a href="https://pydantic.dev/docs/validation/latest/get-started/version-policy/#pydantic-v2">versioning policy</a>)
are also included in this release. Make sure to look into them before upgrading.</p>
<p>This release drops support for Python 3.9 and adds support for Python 3.15.</p>
<p>Highlights include:</p>
<ul>
<li><a href="https://pydantic.dev/articles/pydantic-v2-14-release#stabilized-missing-sentinel">Stabilized <code>MISSING</code> sentinel</a></li>
<li><a href="https://pydantic.dev/articles/pydantic-v2-14-release#support-for-lazy-imports">Support for lazy imports</a></li>
<li><a href="https://pydantic.dev/articles/pydantic-v2-14-release#support-for-typeform">Support for <code>TypeForm</code></a></li>
</ul>
<p>You can see the full changelog on <a href="https://github.com/pydantic/pydantic/releases/tag/v2.14.0">GitHub</a>.</p>
<section id="quick-reference-section"><h2 id="quick-reference" role="presentation"><a href="#quick-reference" class="heading-anchor"><button type="button" class="heading-anchor__btn">#</button></a><span role="heading" aria-level="2">Quick Reference</span></h2>
<ul>
<li><a href="https://pydantic.dev/articles/pydantic-v2-14-release#new-features">New Features</a></li>
<li><a href="https://pydantic.dev/articles/pydantic-v2-14-release#changes">Changes</a></li>
<li><a href="https://pydantic.dev/articles/pydantic-v2-14-release#performance">Performance</a></li>
</ul>
</section><section id="new-features-section"><h2 id="new-features" role="presentation"><a href="#new-features" class="heading-anchor"><button type="button" class="heading-anchor__btn">#</button></a><span role="heading" aria-level="2">New Features</span></h2>
<p>Pydantic 2.14 officially supports Python 3.15, including most of the new features it introduces. These are covered first.</p>
<section id="stabilized-missing-sentinel-section"><h3 id="stabilized-missing-sentinel" role="presentation"><a href="#stabilized-missing-sentinel" class="heading-anchor"><button type="button" class="heading-anchor__btn">#</button></a><span role="heading" aria-level="3">Stabilized <code>MISSING</code> sentinel</span></h3>
<p>The <a href="https://pydantic.dev/docs/validation/dev/concepts/types/#missing-sentinel"><code>MISSING</code></a> sentinel, added as an experimental feature in 2.12,
is now stabilized and part of the main Pydantic API.</p>
<p><code>MISSING</code> is a singleton indicating that a field value was not provided during validation. During serialization, any field with <code>MISSING</code> as a value is excluded from the output.</p>
<pre><code class="hljs language-python"><span class="hljs-keyword">from</span> pydantic <span class="hljs-keyword">import</span> MISSING, BaseModel


<span class="hljs-keyword">class</span> <span class="hljs-title class_">Configuration</span>(<span class="hljs-title class_ inherited__">BaseModel</span>):
    timeout: <span class="hljs-built_in">int</span> | <span class="hljs-literal">None</span> | MISSING = MISSING


<span class="hljs-comment"># configuration defaults, stored somewhere else:</span>
defaults = {<span class="hljs-string">'timeout'</span>: <span class="hljs-number">200</span>}

conf = Configuration()

<span class="hljs-comment"># `timeout` is excluded from the serialization output:</span>
conf.model_dump()
<span class="hljs-comment">#> {}</span>

<span class="hljs-comment"># The `MISSING` value doesn't appear in the JSON Schema:</span>
Configuration.model_json_schema()[<span class="hljs-string">'properties'</span>][<span class="hljs-string">'timeout'</span>]
<span class="hljs-comment">#> {'anyOf': [{'type': 'integer'}, {'type': 'null'}], 'title': 'Timeout'}</span>

<span class="hljs-comment"># `is` can be used to discriminate between the sentinel and other values:</span>
timeout = conf.timeout <span class="hljs-keyword">if</span> conf.timeout <span class="hljs-keyword">is</span> <span class="hljs-keyword">not</span> MISSING <span class="hljs-keyword">else</span> defaults[<span class="hljs-string">'timeout'</span>]
</code></pre>
<aside class="callout callout-note"><div class="callout-indicator"><svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="2" aria-hidden="true"><path d="M12 8h.01M12 12v4"></path><circle cx="12" cy="12" r="10"></circle></svg><div class="callout-title">Note</div></div><div class="callout-content"><p>Static type checkers support <code>MISSING</code> starting from <a href="https://github.com/microsoft/pyright/releases/tag/1.1.414">pyright 1.1.414</a>
and <a href="https://mypy-lang.blogspot.com/2026/10/mypy-24-released.html">Mypy 2.4</a>.</p></div></aside>
<p>PR reference: <a href="https://github.com/pydantic/pydantic/pull/13782">#13782</a>.</p>
</section><section id="support-for-lazy-imports-section"><h3 id="support-for-lazy-imports" role="presentation"><a href="#support-for-lazy-imports" class="heading-anchor"><button type="button" class="heading-anchor__btn">#</button></a><span role="heading" aria-level="3">Support for lazy imports</span></h3>
<p><a href="https://docs.python.org/3.15/reference/simple_stmts.html#lazy">Lazy imports</a> were introduced by <a href="https://peps.python.org/pep-0810/">PEP 810</a> in Python 3.15.</p>
<p>Lazy imports let models in separate modules reference each other without running into cyclic imports:</p>
<p><code>a.py</code>:</p>
<pre><code class="hljs language-python">lazy <span class="hljs-keyword">from</span> .b <span class="hljs-keyword">import</span> B

<span class="hljs-keyword">from</span> pydantic <span class="hljs-keyword">import</span> BaseModel


<span class="hljs-keyword">class</span> <span class="hljs-title class_">A</span>(<span class="hljs-title class_ inherited__">BaseModel</span>):
    b: B | <span class="hljs-literal">None</span> = <span class="hljs-literal">None</span>
</code></pre>
<p><code>b.py</code>:</p>
<pre><code class="hljs language-python">lazy <span class="hljs-keyword">from</span> .a <span class="hljs-keyword">import</span> A

<span class="hljs-keyword">from</span> pydantic <span class="hljs-keyword">import</span> BaseModel


<span class="hljs-keyword">class</span> <span class="hljs-title class_">B</span>(<span class="hljs-title class_ inherited__">BaseModel</span>):
    a: A | <span class="hljs-literal">None</span> = <span class="hljs-literal">None</span>
</code></pre>
<p>See <a href="https://pydantic.dev/docs/validation/dev/concepts/forward_annotations/#cyclic-imports">the documentation</a> for more details.</p>
<p>PR reference: <a href="https://github.com/pydantic/pydantic/pull/13776">#13776</a>.</p>
</section><section id="support-for-typeform-section"><h3 id="support-for-typeform" role="presentation"><a href="#support-for-typeform" class="heading-anchor"><button type="button" class="heading-anchor__btn">#</button></a><span role="heading" aria-level="3">Support for <code>TypeForm</code></span></h3>
<p><a href="https://docs.python.org/3.15/library/typing.html#typing.TypeForm"><code>typing.TypeForm</code></a> was introduced by <a href="https://peps.python.org/pep-0747/">PEP 747</a> in Python 3.15, and is supported by
major static type checkers.</p>
<p>Pydantic now uses <code>TypeForm</code> in a number of places, in particular with <a href="https://pydantic.dev/docs/validation/latest/concepts/type_adapter/"><code>TypeAdapter</code></a>:</p>
<pre><code class="hljs language-python"><span class="hljs-keyword">from</span> typing <span class="hljs-keyword">import</span> reveal_type

<span class="hljs-keyword">from</span> pydantic <span class="hljs-keyword">import</span> TypeAdapter

ta = TypeAdapter(<span class="hljs-built_in">int</span> | <span class="hljs-built_in">str</span>)

validated = ta.validate_python(<span class="hljs-number">1</span>)

reveal_type(validated)
<span class="hljs-comment"># In &#x3C;= 2.13: Unknown</span>
<span class="hljs-comment"># In >= 2.14: int | str</span>
</code></pre>
<p>Type checkers now infer the correct type for any type form passed to Pydantic (<code>x | y</code> unions, <code>Annotated[...]</code> forms, etc.), not just classes.</p>
<aside class="callout callout-note"><div class="callout-indicator"><svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="2" aria-hidden="true"><path d="M12 8h.01M12 12v4"></path><circle cx="12" cy="12" r="10"></circle></svg><div class="callout-title">Note</div></div><div class="callout-content"><p>Static type checkers support <code>TypeForm</code> starting from <a href="https://github.com/microsoft/pyright/releases/tag/1.1.412">pyright 1.1.412</a>
and <a href="https://mypy-lang.blogspot.com/2026/07/mypy-22-released.html">Mypy 2.2</a>.</p></div></aside>
<p>PR reference: <a href="https://github.com/pydantic/pydantic/pull/13459">#13459</a>.</p>
</section><section id="support-for-frozendict-section"><h3 id="support-for-frozendict" role="presentation"><a href="#support-for-frozendict" class="heading-anchor"><button type="button" class="heading-anchor__btn">#</button></a><span role="heading" aria-level="3">Support for <code>frozendict</code></span></h3>
<p>The <a href="https://docs.python.org/3.15/builtins/stdtypes.html#frozendict"><code>frozendict</code></a> type was introduced by <a href="https://peps.python.org/pep-0814/">PEP 814</a> in Python 3.15. Pydantic supports it,
and it validates and serializes like a regular <code>dict</code>. See <a href="https://pydantic.dev/docs/validation/dev/api/pydantic/standard_library_types/#frozen-dictionaries">the documentation</a>
for more details.</p>
<p>PR reference: <a href="https://github.com/pydantic/pydantic/pull/13634">#13634</a>.</p>
</section><section id="__namespace__-argument-for-create_model-section"><h3 id="__namespace__-argument-for-create_model" role="presentation"><a href="#__namespace__-argument-for-create_model" class="heading-anchor"><button type="button" class="heading-anchor__btn">#</button></a><span role="heading" aria-level="3"><code>__namespace__</code> argument for <code>create_model()</code></span></h3>
<p><a href="https://pydantic.dev/docs/validation/dev/concepts/models/#dynamic-model-creation"><code>create_model()</code></a> now accepts a <code>__namespace__</code> argument,
to add any attribute to the class namespace of the created model, such as validators, methods or computed fields:</p>
<pre><code class="hljs language-python"><span class="hljs-keyword">from</span> pydantic <span class="hljs-keyword">import</span> computed_field, create_model


<span class="hljs-keyword">def</span> <span class="hljs-title function_">full_name</span>(<span class="hljs-params">self</span>) -> <span class="hljs-built_in">str</span>:
    <span class="hljs-keyword">return</span> <span class="hljs-string">f'<span class="hljs-subst">{self.first_name}</span> <span class="hljs-subst">{self.last_name}</span>'</span>


UserModel = create_model(
    <span class="hljs-string">'UserModel'</span>,
    first_name=<span class="hljs-built_in">str</span>,
    last_name=<span class="hljs-built_in">str</span>,
    __namespace__={<span class="hljs-string">'full_name'</span>: computed_field(<span class="hljs-built_in">property</span>(full_name))},
)

UserModel(first_name=<span class="hljs-string">'John'</span>, last_name=<span class="hljs-string">'Doe'</span>).model_dump()
<span class="hljs-comment">#> {'first_name': 'John', 'last_name': 'Doe', 'full_name': 'John Doe'}</span>
</code></pre>
<p>The existing <code>__validators__</code> argument is limited to validators. It is now recommended to use <code>__namespace__</code> instead, as <code>__validators__</code> will be deprecated in v3.</p>
<p>PR reference: <a href="https://github.com/pydantic/pydantic/pull/13895">#13895</a>.</p>
</section><section id="new-core-schema-types-section"><h3 id="new-core-schema-types" role="presentation"><a href="#new-core-schema-types" class="heading-anchor"><button type="button" class="heading-anchor__btn">#</button></a><span role="heading" aria-level="3">New core schema types</span></h3>
<p>Several supported types now have their own <a href="https://pydantic.dev/docs/validation/latest/internals/architecture/#communicating-between-pydantic-and-pydantic-core-the-core-schema">core schema</a>,
meaning they are natively validated/serialized by the <code>pydantic-core</code> Rust component. Previously, Pydantic defined custom
Python validators for them, which were slower and didn't support constraints.</p>
<p>The following types were migrated:</p>
<ul>
<li><a href="https://docs.python.org/3/library/fractions.html#fractions.Fraction"><code>fractions.Fraction</code></a> in <a href="https://github.com/pydantic/pydantic/pull/13339">#13339</a>. <a href="https://docs.python.org/3/builtins/exceptions.html#ZeroDivisionError"><code>ZeroDivisionError</code></a>s during validation are now properly handled.</li>
<li><a href="https://docs.python.org/3/library/collections.html#namedtuple-factory-function-for-tuples-with-named-fields">Named tuples</a> in <a href="https://github.com/pydantic/pydantic/pull/13505">#13505</a>. This fixes a number of issues related to validation.</li>
<li><a href="https://docs.python.org/3/library/collections.html#collections.deque"><code>collections.deque</code></a> in <a href="https://github.com/pydantic/pydantic/pull/13757">#13757</a>.</li>
<li><a href="https://docs.python.org/3/library/collections.html#collections.OrderedDict"><code>collections.OrderedDict</code></a> in <a href="https://github.com/pydantic/pydantic/pull/13796">#13796</a>.</li>
<li><a href="https://docs.python.org/3/library/collections.html#collections.Counter"><code>collections.Counter</code></a> in <a href="https://github.com/pydantic/pydantic/pull/13824">#13824</a>.</li>
</ul>
</section></section><section id="changes-section"><h2 id="changes" role="presentation"><a href="#changes" class="heading-anchor"><button type="button" class="heading-anchor__btn">#</button></a><span role="heading" aria-level="2">Changes</span></h2>
<p>This release contains some minor changes that may affect existing code. Make sure to go through them before upgrading.</p>
<section id="json-schema-changes-section"><h3 id="json-schema-changes" role="presentation"><a href="#json-schema-changes" class="heading-anchor"><button type="button" class="heading-anchor__btn">#</button></a><span role="heading" aria-level="3">JSON Schema changes</span></h3>
<p>This release introduces a number of JSON Schema changes that may affect your generated model schemas.</p>
<h4 id="decimal-pattern"><code>Decimal</code> pattern</h4>
<p>In 2.12, <a href="https://github.com/pydantic/pydantic/pull/11987">#11987</a> added regex patterns in the JSON Schema for <a href="https://docs.python.org/3/library/decimal.html#decimal.Decimal"><code>Decimal</code></a> types. This caused a number of issues, as some users define validation contracts based on the generated schema.</p>
<p>For this reason, the pattern is no longer included by default. A
<a href="https://pydantic.dev/docs/validation/dev/concepts/json_schema/#customizing-the-json-schema-generation-process">custom <code>GenerateJsonSchema</code> subclass</a>
can be defined to enable the pattern again (see <a href="https://pydantic.dev/docs/validation/dev/api/pydantic/standard_library_types/#decimals">the documentation</a> for more details).</p>
<p>PR reference: <a href="https://github.com/pydantic/pydantic/pull/13672">#13672</a>.</p>
<h4 id="typeadapter-config"><code>TypeAdapter</code> config</h4>
<p>The configuration of the <code>TypeAdapter</code> is now used when generating the JSON Schema:</p>
<pre><code class="hljs language-python"><span class="hljs-keyword">from</span> pydantic <span class="hljs-keyword">import</span> ConfigDict, TypeAdapter

ta = TypeAdapter(<span class="hljs-built_in">list</span>[<span class="hljs-built_in">bytes</span>], config=ConfigDict(ser_json_bytes=<span class="hljs-string">'base64'</span>))
ta.json_schema()
<span class="hljs-comment">#> {'type': 'array', 'items': {'type': 'string', 'format': 'base64url'}}</span>
</code></pre>
<p>PR reference: <a href="https://github.com/pydantic/pydantic/pull/13676">#13676</a>.</p>
<h4 id="other-json-schema-changes">Other JSON Schema changes</h4>
<p>These changes are mostly bug fixes that make the JSON Schema more consistent with the validation/serialization behavior:</p>
<ul>
<li>Don't apply serialization temporal formats to validation JSON Schemas in <a href="https://github.com/pydantic/pydantic/pull/13711">#13711</a>.</li>
<li>Reflect <code>str_min_length</code> and <code>str_max_length</code> config in the JSON Schema in <a href="https://github.com/pydantic/pydantic/pull/13714">#13714</a>.</li>
<li>Use the field name in validation JSON Schemas when <code>validate_by_alias</code> is <code>False</code> in <a href="https://github.com/pydantic/pydantic/pull/13717">#13717</a>.</li>
<li>Fix config propagation of stdlib dataclasses and <code>TypedDict</code>s in JSON Schema in <a href="https://github.com/pydantic/pydantic/pull/13891">#13891</a>.</li>
<li>Don't apply <code>ser_json_timedelta</code> to all datetime types in serialization inference in <a href="https://github.com/pydantic/pydantic/pull/13892">#13892</a>.</li>
<li>Encode JSON Schema defaults with a consistent configuration in <a href="https://github.com/pydantic/pydantic/pull/13893">#13893</a>.</li>
</ul>
</section><section id="model_config-is-no-longer-mutated-section"><h3 id="model_config-is-no-longer-mutated" role="presentation"><a href="#model_config-is-no-longer-mutated" class="heading-anchor"><button type="button" class="heading-anchor__btn">#</button></a><span role="heading" aria-level="3"><code>model_config</code> is no longer mutated</span></h3>
<p>Prior to 2.14, the <a href="https://pydantic.dev/docs/validation/dev/api/pydantic/base_model/#pydantic.BaseModel.model_config"><code>model_config</code></a> attribute could
be mutated by Pydantic, e.g. to populate values from deprecated settings. This is no longer the case: <code>model_config</code> will always reflect what was
set by the user (merged with the configuration of parent classes):</p>
<pre><code class="hljs language-python"><span class="hljs-keyword">from</span> pydantic <span class="hljs-keyword">import</span> BaseModel


<span class="hljs-keyword">class</span> <span class="hljs-title class_">Base</span>(<span class="hljs-title class_ inherited__">BaseModel</span>):
    model_config = {<span class="hljs-string">'title'</span>: <span class="hljs-string">'MyBase'</span>}


<span class="hljs-keyword">class</span> <span class="hljs-title class_">Model</span>(<span class="hljs-title class_ inherited__">Base</span>):
    model_config = {<span class="hljs-string">'populate_by_name'</span>: <span class="hljs-literal">True</span>}


Model.model_config
<span class="hljs-comment">#> In &#x3C;= 2.13: {'title': 'MyBase', 'populate_by_name': True, 'validate_by_alias': True, 'validate_by_name': True}</span>
<span class="hljs-comment">#> In >= 2.14: {'title': 'MyBase', 'populate_by_name': True}</span>
</code></pre>
<p>PR reference: <a href="https://github.com/pydantic/pydantic/pull/13825">#13825</a>.</p>
</section><section id="model-signature-with-validate_by_aliasfalse-section"><h3 id="model-signature-with-validate_by_aliasfalse" role="presentation"><a href="#model-signature-with-validate_by_aliasfalse" class="heading-anchor"><button type="button" class="heading-anchor__btn">#</button></a><span role="heading" aria-level="3">Model signature with <code>validate_by_alias=False</code></span></h3>
<p>When <a href="https://pydantic.dev/docs/validation/latest/api/pydantic/config/#pydantic.config.ConfigDict.validate_by_alias"><code>validate_by_alias</code></a> is set to <code>False</code>,
the generated <code>__signature__</code> of models and Pydantic dataclasses now uses the field name instead of the alias, matching what validation actually accepts:</p>
<pre><code class="hljs language-python"><span class="hljs-keyword">import</span> inspect

<span class="hljs-keyword">from</span> pydantic <span class="hljs-keyword">import</span> BaseModel, ConfigDict, Field


<span class="hljs-keyword">class</span> <span class="hljs-title class_">Model</span>(<span class="hljs-title class_ inherited__">BaseModel</span>):
    model_config = ConfigDict(validate_by_alias=<span class="hljs-literal">False</span>, validate_by_name=<span class="hljs-literal">True</span>)

    my_field: <span class="hljs-built_in">int</span> = Field(alias=<span class="hljs-string">'myAlias'</span>)


inspect.signature(Model)
<span class="hljs-comment">#> In &#x3C;= 2.13: (*, myAlias: int) -> None</span>
<span class="hljs-comment">#> In >= 2.14: (*, my_field: int) -> None</span>
</code></pre>
<p>Contributed by <a href="https://github.com/jaideeppyne">@jaideeppyne</a>. PR reference: <a href="https://github.com/pydantic/pydantic/pull/13730">#13730</a>.</p>
</section><section id="multiple_of-constraint-section"><h3 id="multiple_of-constraint" role="presentation"><a href="#multiple_of-constraint" class="heading-anchor"><button type="button" class="heading-anchor__btn">#</button></a><span role="heading" aria-level="3"><code>multiple_of</code> constraint</span></h3>
<p>Using a non-positive value for <code>multiple_of</code> now raises an error when the model is defined. Previously, an unhandled runtime exception was raised during validation.</p>
<p>PR reference: <a href="https://github.com/pydantic/pydantic/pull/13862">#13862</a>.</p>
</section><section id="numeric-constraints-in-the-pipeline-api-section"><h3 id="numeric-constraints-in-the-pipeline-api" role="presentation"><a href="#numeric-constraints-in-the-pipeline-api" class="heading-anchor"><button type="button" class="heading-anchor__btn">#</button></a><span role="heading" aria-level="3">Numeric constraints in the pipeline API</span></h3>
<p>In the experimental <a href="https://pydantic.dev/docs/validation/latest/concepts/experimental/#pipeline-api">pipeline API</a>, numeric constraints
(<code>gt()</code>, <code>ge()</code>, <code>lt()</code>, <code>le()</code> and <code>multiple_of()</code>) are now always applied natively by <code>pydantic-core</code> on numeric types. Previously, some of them were
applied as Python validators, e.g. when chaining several constraints or when the constraint value didn't match the validated type. As a result,
these constraints are now included in the JSON Schema, and validation errors are the same as for regular fields:</p>
<pre><code class="hljs language-python"><span class="hljs-keyword">from</span> typing <span class="hljs-keyword">import</span> Annotated

<span class="hljs-keyword">from</span> pydantic <span class="hljs-keyword">import</span> TypeAdapter
<span class="hljs-keyword">from</span> pydantic.experimental.pipeline <span class="hljs-keyword">import</span> validate_as

ta = TypeAdapter(Annotated[<span class="hljs-built_in">int</span>, validate_as(<span class="hljs-built_in">int</span>).ge(<span class="hljs-number">1</span>).le(<span class="hljs-number">100</span>)])

ta.json_schema()
<span class="hljs-comment">#> In &#x3C;= 2.13: {'minimum': 1, 'type': 'integer'}</span>
<span class="hljs-comment">#> In >= 2.14: {'maximum': 100, 'minimum': 1, 'type': 'integer'}</span>

ta.validate_python(<span class="hljs-number">200</span>)
<span class="hljs-string">"""
In &#x3C;= 2.13:
  Value error, Expected &#x3C;= 100 [type=value_error, input_value=200, input_type=int]
In >= 2.14:
  Input should be less than or equal to 100 [type=less_than_equal, input_value=200, input_type=int]
"""</span>
</code></pre>
<p>PR reference: <a href="https://github.com/pydantic/pydantic/pull/13516">#13516</a>.</p>
</section><section id="invalid-index_key-in-wrap-serializers-section"><h3 id="invalid-index_key-in-wrap-serializers" role="presentation"><a href="#invalid-index_key-in-wrap-serializers" class="heading-anchor"><button type="button" class="heading-anchor__btn">#</button></a><span role="heading" aria-level="3">Invalid <code>index_key</code> in wrap serializers</span></h3>
<p>The handler of <a href="https://pydantic.dev/docs/validation/latest/concepts/serialization/#model-wrap-serializer">wrap serializers</a> takes an optional
second <code>index_key</code> argument, which must be an integer or a string. A previous docstring example wrongly passed the <code>info</code> argument instead,
which went unnoticed unless <code>include</code> or <code>exclude</code> was used. Such invalid values now raise an explicit error:</p>
<pre><code class="hljs language-python"><span class="hljs-keyword">from</span> pydantic <span class="hljs-keyword">import</span> BaseModel, model_serializer


<span class="hljs-keyword">class</span> <span class="hljs-title class_">Model</span>(<span class="hljs-title class_ inherited__">BaseModel</span>):
    a: <span class="hljs-built_in">int</span>

<span class="hljs-meta">    @model_serializer(<span class="hljs-params">mode=<span class="hljs-string">'wrap'</span></span>)</span>
    <span class="hljs-keyword">def</span> <span class="hljs-title function_">ser_model</span>(<span class="hljs-params">self, handler, info</span>):
        <span class="hljs-keyword">return</span> handler(self, info)  <span class="hljs-comment"># should be `handler(self)`</span>


Model(a=<span class="hljs-number">1</span>).model_dump()
<span class="hljs-string">"""
In &#x3C;= 2.13:
  {'a': 1}
In >= 2.14:
  PydanticSerializationError: Error calling function `ser_model`: TypeError: 'index_key' is expected to be an integer or a string, got 'SerializationInfo(...)'
"""</span>
</code></pre>
<p>If you copied this pattern, remove the second argument when calling the handler.</p>
<p>PR reference: <a href="https://github.com/pydantic/pydantic/pull/13506">#13506</a>.</p>
</section></section><section id="performance-section"><h2 id="performance" role="presentation"><a href="#performance" class="heading-anchor"><button type="button" class="heading-anchor__btn">#</button></a><span role="heading" aria-level="2">Performance</span></h2>
<p>2.14 includes several optimizations to schema generation. Most of them individually reduce model build time by 5–20% on our benchmarks, which adds up at import time for applications that define many models:</p>
<ul>
<li>Optimize type lookup logic in core schema generation in <a href="https://github.com/pydantic/pydantic/pull/13573">#13573</a>.</li>
<li>Refactor type references logic in <a href="https://github.com/pydantic/pydantic/pull/13643">#13643</a>.</li>
<li>Move schema gathering logic to <code>pydantic-core</code> in <a href="https://github.com/pydantic/pydantic/pull/13725">#13725</a>.</li>
<li>Improve performance of <code>FieldInfo</code> construction in <a href="https://github.com/pydantic/pydantic/pull/13726">#13726</a>.</li>
<li>Improve performance of <code>GenerateSchema.generate_schema()</code> dispatching in <a href="https://github.com/pydantic/pydantic/pull/13614">#13614</a>.</li>
<li>Avoid exponential core schema traversal in <code>gather_schemas_for_cleaning()</code> in <a href="https://github.com/pydantic/pydantic/pull/13523">#13523</a>.</li>
<li>Introduce micro-optimizations for model class building in <a href="https://github.com/pydantic/pydantic/pull/13540">#13540</a>.</li>
</ul>
<hr>
<p>Ready to try the new features? Upgrade now with <code>pip install --upgrade pydantic</code> or <code>uv add --upgrade pydantic</code> and check out the <a href="https://github.com/pydantic/pydantic/releases/tag/v2.14.0">full release notes</a>. Have questions or feedback? Join the conversation on our community <a href="https://pydantic.dev/docs/logfire/join-slack/">Slack</a>.</p></section>]]></content:encoded>
</item>
<item>
<title>Would you deploy an agent you don&apos;t control?</title>
<link>https://pydantic.dev/articles/pydantic-ai-vs-claude-agent-sdk</link>
<guid isPermaLink="true">https://pydantic.dev/articles/pydantic-ai-vs-claude-agent-sdk</guid>
<pubDate>Mon, 05 Oct 2026 09:00:00 GMT</pubDate>
<dc:creator>Aditya Vardhan</dc:creator>
<category>Pydantic AI</category>
<category>Python</category>
<description>Claude Agent SDK puts Claude Code inside your application. If your product is not a coding agent, that convenience comes with architectural decisions you did not make.</description>
<content:encoded><![CDATA[<p>I have spent my career believing that software should be explicit.</p>
<p>Explicit dependencies. Minimal privileges. Observable behavior. The usual sane software practices. We do not write every line we deploy, but we should understand where our application ends and somebody else's decisions begin.</p>
<p>Agents should not get a pass on that.</p>
<p>So what do you take responsibility for when you build an application with Claude Agent SDK? Which decisions are yours, which belong to Claude Code, and how much control do you have when those decisions no longer fit your application?</p>
<p>Claude Agent SDK, <a href="https://code.claude.com/docs/en/agent-sdk/migration-guide">formerly the Claude Code SDK</a>, wraps Claude Code. That is useful if you are building a coding agent. But I keep seeing it used for applications that have nothing to do with code.</p>
<p>Claude Code is a good coding agent. If your product is not a coding agent, why are you shipping one with it?</p>
<p><img src="https://pydantic.dev/assets/blog/pydantic-ai-vs-claude-agent-sdk/claude-code-python-sdk.jpg" alt="Please sir, can I have a Python SDK? Best I can do is Claude Code in a subprocess." decoding="async"></p>
<p>With my terrible meme game out of the way, let us look at what the SDK brings into your application, and what you have to own once it is there.</p>
<section id="the-contract-is-bigger-than-the-api-section"><h2 id="the-contract-is-bigger-than-the-api" role="presentation"><a href="#the-contract-is-bigger-than-the-api" class="heading-anchor"><button type="button" class="heading-anchor__btn">#</button></a><span role="heading" aria-level="2">The contract is bigger than the API</span></h2>
<p>Every application depends on code its maintainers did not write. Control does not mean authorship. There is still a contract we expect an SDK to honor. We pin dependencies, review upgrades, and expect breaking changes to be visible.</p>
<p>Agents make that contract more complicated than a public API.</p>
<p>Imagine we changed <a href="https://pydantic.dev/docs/ai/">Pydantic AI</a>'s retry prompt to something absurd. The imports would still work. The types would still check. Nothing in the public API would be broken, but deployed agents could behave differently.</p>
<p>Was it an API breaking change? No. Was it the reason your application broke? Absolutely.</p>
<p>We need to be more deliberate with agents. Their prompts, tools, permissions, control loops, and failure behavior are not incidental implementation details. They decide what the model sees, what it can do, and what happens next.</p>
<p>If those decisions are hidden inside another product, that product owns a meaningful part of your application's behavior.</p>
</section><section id="a-coding-agent-harness-dressed-up-as-an-sdk-section"><h2 id="a-coding-agent-harness-dressed-up-as-an-sdk" role="presentation"><a href="#a-coding-agent-harness-dressed-up-as-an-sdk" class="heading-anchor"><button type="button" class="heading-anchor__btn">#</button></a><span role="heading" aria-level="2">A coding-agent harness dressed up as an SDK</span></h2>
<p><code>pip install claude-agent-sdk</code> sounds like installing a Python client for Claude.</p>
<p>It installs a Python client and a bundled Claude Code executable. Each session starts Claude Code as a <a href="https://code.claude.com/docs/en/agent-sdk/hosting#the-subprocess-model">subprocess</a>. Its shell, file tools, skills, plugins, permissions, settings, session files, and agent loop come with it.</p>
<p>Those choices make sense for Claude Code. It needs to inspect repositories, edit files, run commands, recover from failures, and follow project instructions.</p>
<p>They are choices made for a coding agent.</p>
<p>Most of them have a switch. You can deny tools, add hooks, <a href="https://code.claude.com/docs/en/agent-sdk/modifying-system-prompts#how-system-prompts-work">replace the system prompt</a>, provide your own MCP tools, and <a href="https://code.claude.com/docs/en/agent-sdk/hosting">pass <code>setting_sources=[]</code> and <code>CLAUDE_CODE_DISABLE_AUTO_MEMORY=1</code></a> so a session stops loading the project's <code>.claude/</code> settings and memory. But you are still configuring Claude Code rather than building the runtime your application needs. If your users are not asking for a coding agent, why start with one and spend your time taking it apart?</p>
<p>If running that subprocess is the part you do not want, Anthropic also offers <a href="https://platform.claude.com/docs/en/managed-agents/overview">Managed Agents</a>, which hosts the agent loop for you, while tools run in Anthropic's cloud sandbox or one you host. The loop is still Anthropic's.</p>
</section><section id="the-impact-on-your-application-section"><h2 id="the-impact-on-your-application" role="presentation"><a href="#the-impact-on-your-application" class="heading-anchor"><button type="button" class="heading-anchor__btn">#</button></a><span role="heading" aria-level="2">The impact on your application</span></h2>
<p>Claude Agent SDK pins a Claude Code version, so a locked deployment will not change overnight. But <a href="https://github.com/anthropics/claude-agent-sdk-python#release-workflow">upgrading the SDK can replace the bundled Claude Code binary</a>.</p>
<p>Anthropic says Claude Code upgrades <a href="https://code.claude.com/docs/en/prompt-caching#upgrading-claude-code">usually change the system prompt or tool definitions</a>. The <a href="https://code.claude.com/docs/en/settings">system prompt is not published</a> as part of the SDK's contract.</p>
<p>Your prompt can stay the same. Your model can stay the same. Your code can stay the same. The agent you deployed can still change, and the reason does not appear in your code review.</p>
<p>That has a practical cost. Your team has to understand Claude Code's assumptions, constrain capabilities the application does not need, and investigate behavior controlled by a runtime built for a different job.</p>
<p>The problem is not that Claude Code is opinionated. A good coding agent should be opinionated. The problem is adopting all of those opinions when you did not set out to ship a coding agent.</p>
</section><section id="pydantic-ai-grows-with-your-application-section"><h2 id="pydantic-ai-grows-with-your-application" role="presentation"><a href="#pydantic-ai-grows-with-your-application" class="heading-anchor"><button type="button" class="heading-anchor__btn">#</button></a><span role="heading" aria-level="2">Pydantic AI grows with your application</span></h2>
<p>Pydantic AI starts with the application, not a prebuilt harness. You choose the model, from <a href="https://pydantic.dev/docs/ai/models/overview/">any provider Pydantic AI supports</a>, along with the instructions, tools, dependencies, output types, and capabilities.</p>
<pre><code class="hljs language-python"><span class="hljs-keyword">from</span> pydantic <span class="hljs-keyword">import</span> BaseModel
<span class="hljs-keyword">from</span> pydantic_ai <span class="hljs-keyword">import</span> Agent


<span class="hljs-keyword">class</span> <span class="hljs-title class_">SupportReply</span>(<span class="hljs-title class_ inherited__">BaseModel</span>):
    answer: <span class="hljs-built_in">str</span>
    needs_human: <span class="hljs-built_in">bool</span>


agent = Agent(<span class="hljs-string">"anthropic:claude-sonnet-4-6"</span>, output_type=SupportReply)
</code></pre>
<p>Start with one model call. Add typed tools when you need them. Add dependency injection, structured outputs, human approval, durable execution, multiple agents, or an explicit graph as the application grows.</p>
<p>If the application eventually needs filesystem access, a shell, planning, memory, or subagents, <a href="https://pydantic.dev/docs/ai/harness/">Pydantic AI Harness</a> has them as capabilities you add one at a time.</p>
<p>It also has whole agents to start from. <a href="https://pydantic.dev/docs/ai/harness/coder/"><code>Coder</code></a> is a complete coding agent: file tools, a shell, repository instructions, delegation, and context management. <a href="https://pydantic.dev/docs/ai/harness/researcher/"><code>Researcher</code></a> answers questions from the web with cited sources. Both are built from the same capabilities, so they come apart the way they went together. Start from one and remove what you do not need, or skip both and build your own.</p>
<pre><code class="hljs language-python"><span class="hljs-keyword">from</span> pydantic_ai <span class="hljs-keyword">import</span> Agent
<span class="hljs-keyword">from</span> pydantic_ai.capabilities <span class="hljs-keyword">import</span> LocalWorkspace
<span class="hljs-keyword">from</span> pydantic_ai_harness <span class="hljs-keyword">import</span> Coder

agent = Agent(<span class="hljs-string">"anthropic:claude-sonnet-4-6"</span>, capabilities=[LocalWorkspace(<span class="hljs-string">"."</span>), Coder()])
</code></pre>
<p>The same agent can also run in CI. <a href="https://pydantic.dev/docs/ai/harness/gh-aw/">Run your own Pydantic AI agent as a GitHub Agentic Workflow</a> triggers it on issues, pull requests, or a schedule, the job a vendor's GitHub Action does for its own agent. Here it is your agent, with your instructions, your tools, and whichever model you pick.</p>
<p>You do not have to replace the small agent when the application becomes more ambitious, and you do not have to begin with somebody else's entire workstation. We would rather you spent your time building your application than working around decisions we made for a different one.</p>
</section><section id="give-it-somewhere-to-work-section"><h2 id="give-it-somewhere-to-work" role="presentation"><a href="#give-it-somewhere-to-work" class="heading-anchor"><button type="button" class="heading-anchor__btn">#</button></a><span role="heading" aria-level="2">Give it somewhere to work</span></h2>
<p><code>LocalWorkspace(".")</code> runs the agent's commands on your machine, as you. That is fine for your own repository. It is not where you want to run code a user handed you.</p>
<p>To move the work somewhere isolated, swap the <a href="https://pydantic.dev/docs/ai/core-concepts/workspace/">workspace</a> and keep the rest:</p>
<pre><code class="hljs language-python"><span class="hljs-keyword">from</span> pydantic_ai_harness.modal_sandbox <span class="hljs-keyword">import</span> ModalSandbox

agent = Agent(<span class="hljs-string">"anthropic:claude-sonnet-4-6"</span>, capabilities=[ModalSandbox(), Coder()])
</code></pre>
<p><code>Coder</code>'s file and shell tools now run in a <a href="https://pydantic.dev/docs/ai/harness/modal-sandbox/">Modal</a> sandbox. <a href="https://pydantic.dev/docs/ai/harness/e2b-sandbox/"><code>E2BSandbox()</code></a> and <a href="https://pydantic.dev/docs/ai/harness/sprites-sandbox/"><code>SpritesSandbox()</code></a> drop into the same slot. Tools you write yourself reach the environment through <code>ctx.workspace</code>, so a tool you tested on your laptop runs in the sandbox unchanged.</p>
<p>The agent itself stays in your application. Only its commands and file edits move. With Claude Agent SDK, Anthropic's advice is to <a href="https://code.claude.com/docs/en/agent-sdk/hosting#container-based-sandboxing">run the SDK inside a sandboxed container</a>, which puts the whole agent in there with them.</p>
<p>A sandbox keeps running after the run ends, so <a href="https://pydantic.dev/docs/ai/core-concepts/workspace/#cleaning-up">delete it</a> when you are done.</p>
</section><section id="see-what-your-agent-actually-did-section"><h2 id="see-what-your-agent-actually-did" role="presentation"><a href="#see-what-your-agent-actually-did" class="heading-anchor"><button type="button" class="heading-anchor__btn">#</button></a><span role="heading" aria-level="2">See what your agent actually did</span></h2>
<p>Owning the agent only helps if you can see it run. Call <code>logfire.configure()</code> and <code>logfire.instrument_pydantic_ai()</code>, and <a href="https://pydantic.dev/logfire">Pydantic Logfire</a> records every model request, tool call, and retry, including the exact prompt the model received.</p>
<p>That also answers the upgrade problem from earlier. Keep a set of cases in <a href="https://pydantic.dev/docs/ai/evals/evals/">Pydantic Evals</a>, run it before and after you bump a dependency or change a prompt, and a change in behavior shows up in a report you read during review.</p>
</section><section id="choose-the-thing-you-intend-to-ship-section"><h2 id="choose-the-thing-you-intend-to-ship" role="presentation"><a href="#choose-the-thing-you-intend-to-ship" class="heading-anchor"><button type="button" class="heading-anchor__btn">#</button></a><span role="heading" aria-level="2">Choose the thing you intend to ship</span></h2>
<p>If you are building a coding agent and want Claude Code's behavior, Claude Agent SDK is the direct choice. Its shell, filesystem, project instructions, skills, permissions, and coding loop are the product you want.</p>
<div class="overflow-x-auto table-wrapper" tabindex="0"><table>
<thead>
<tr>
<th></th>
<th>Claude Agent SDK</th>
<th>Pydantic AI</th>
</tr>
</thead>
<tbody>
<tr>
<td>What you install</td>
<td>A Python client and a bundled Claude Code executable</td>
<td>A Python library</td>
</tr>
<tr>
<td>Agent loop</td>
<td>Claude Code's, in a subprocess</td>
<td>Pydantic AI's, in your process</td>
</tr>
<tr>
<td>System prompt</td>
<td>Yours or Claude Code's, plus reminders Claude Code adds</td>
<td>The instructions you write</td>
</tr>
<tr>
<td>Default tools</td>
<td>Shell, file tools, skills, and plugins</td>
<td>None until you add them</td>
</tr>
<tr>
<td>Where tools run</td>
<td>Wherever you run the SDK process</td>
<td>Your machine, or a Modal, E2B, or Sprites sandbox</td>
</tr>
<tr>
<td>Models</td>
<td>Claude</td>
<td>Any supported provider</td>
</tr>
<tr>
<td>Coding agent</td>
<td>Claude Code</td>
<td><code>Coder</code> from Pydantic AI Harness</td>
</tr>
<tr>
<td>Fits best</td>
<td>A coding product built on Claude Code's behavior</td>
<td>An application that defines its own agent</td>
</tr>
</tbody>
</table></div>
<p>If you are not building a coding agent, do not reach for a coding-agent harness just because it is packaged as an SDK.</p>
<p>Use Pydantic AI when you want your application to define the agent and grow without giving up control of it.</p>
<hr>
<p><em>We reviewed <code>claude-agent-sdk==0.2.152</code> and its bundled Claude Code <code>2.1.259</code> on September 4, 2026, and checked the Pydantic AI examples against commit <code>06ba88fd</code> on October 1, 2026.</em></p></section>]]></content:encoded>
</item>
<item>
<title>Building production agents: the observability layer</title>
<link>https://pydantic.dev/articles/agent-observability-layer</link>
<guid isPermaLink="true">https://pydantic.dev/articles/agent-observability-layer</guid>
<pubDate>Thu, 01 Oct 2026 09:00:00 GMT</pubDate>
<dc:creator>Antoni Kozelski</dc:creator>
<category>Pydantic Logfire</category>
<category>Vstorm</category>
<description>Agents are still software, but traditional monitoring can&apos;t see what they actually do. A practitioner&apos;s case for treating observability as a first-class layer, and how we do it with Logfire.</description>
<content:encoded><![CDATA[<p><em>This piece is a guest post from Vstorm.</em></p>
<p>A while back, one of our agents handed a customer a wrong answer with total confidence. No exception. No failed test. The logs were clean. It took the better part of a morning to work out what had happened: the model had called the right tool with the wrong argument three steps upstream, then reasoned smoothly on top of the bad result all the way to a fluent, plausible, incorrect conclusion.</p>
<p>That morning is the whole argument for this post. Agents are still software, so the fix isn't a new philosophy. It's the same engineering discipline pointed at a harder target: making a non-deterministic system observable enough that you can read what it did instead of guessing. That layer is <strong>AI agent observability</strong>, and if you're shipping agents to production, it's not optional.</p>
<section id="the-failure-mode-traditional-monitoring-cant-see-section"><h2 id="the-failure-mode-traditional-monitoring-cant-see" role="presentation"><a href="#the-failure-mode-traditional-monitoring-cant-see" class="heading-anchor"><button type="button" class="heading-anchor__btn">#</button></a><span role="heading" aria-level="2">The failure mode traditional monitoring can't see</span></h2>
<p>Your existing stack assumes deterministic code paths. An HTTP handler that returns the same response for the same input is easy to monitor. Agents break that assumption. The <a href="https://mastra.ai/articles/ai-agent-observability">same query can produce a different tool-call sequence</a>, different intermediate reasoning, and a different final output on consecutive runs.</p>
<p>Worse, agents fail without tripping any alarm. Infinite loops, wrong tool selection, context abandonment, and quality that degrades over a long reasoning chain <a href="https://blaxel.ai/blog/ai-observability">rarely throw an error</a>. The exception you're used to catching is replaced by a hallucination that looks completely confident.</p>
<p>Two consequences follow. The unit of debugging moves from the request to the session: isolated traces mean nothing until <a href="https://vercel.com/i/ai-agent-observability">shared identifiers connect them</a> into one readable execution graph. And cost and latency now compound step by step, so without per-step <strong>LLM cost tracking</strong> you find out what an agent costs when the invoice arrives.</p>
</section><section id="how-teams-cope-today-and-why-it-doesnt-hold-section"><h2 id="how-teams-cope-today-and-why-it-doesnt-hold" role="presentation"><a href="#how-teams-cope-today-and-why-it-doesnt-hold" class="heading-anchor"><button type="button" class="heading-anchor__btn">#</button></a><span role="heading" aria-level="2">How teams cope today, and why it doesn't hold</span></h2>
<p>Most teams reach for what they already have. It half-works, which is the dangerous part.</p>
<p>The first instinct is to point traditional APM at the problem. Conventional request monitoring captures latency and error rates, but without an AI/agent integration it lacks the vocabulary for tokens, prompts, tool calls, or eval results, so it's blind to the signals that actually matter. The second instinct is print statements and log spelunking, fine for a demo and hopeless once you're past a few hundred runs a day. The third is an LLM-only tool that traces prompts and completions.</p>
<p>That last one gets closest and still misses by default. What separates an agent from a chat completion is the loop of calling tools, observing results, and iterating. An LLM-focused integration may capture model and tool spans automatically, while database and other application work requires application-level instrumentation.</p>
</section><section id="what-the-ai-agent-observability-layer-must-capture-section"><h2 id="what-the-ai-agent-observability-layer-must-capture" role="presentation"><a href="#what-the-ai-agent-observability-layer-must-capture" class="heading-anchor"><button type="button" class="heading-anchor__btn">#</button></a><span role="heading" aria-level="2">What the AI agent observability layer must capture</span></h2>
<p>Before naming a tool, it's worth being precise about the target. A useful observability layer for agents has to capture five things:</p>
<ul>
<li><strong>The agentic loop as spans.</strong> Plan, call tool, observe, iterate, each as its own step with a duration and an error surface.</li>
<li><strong>One correlated, full-stack trace.</strong> The LLM call, the tool execution, the database query, and the business logic on a single timeline, so you can tell whether the fault is in the AI or the backend.</li>
<li><strong>Per-step cost and latency.</strong> Token usage and spend attached to each step, not summed at the end.</li>
<li><strong>Session correlation.</strong> Parent and child spans across multi-agent handoffs, so an orchestrator and its workers read as one graph.</li>
<li><strong>A portable standard underneath.</strong> Instrumentation built on OpenTelemetry, so you avoid lock-in. OpenTelemetry has <a href="https://opentelemetry.io/blog/2026/genai-observability/">merged semantic conventions for LLM workloads</a>, which gives <strong>OpenTelemetry agent tracing</strong> standard definitions to build on.</li>
</ul>
<p>Here's the same idea as a coverage map. One tool having more logos isn't the interesting part. These signals belong on one timeline rather than stitched across four.</p>
<div class="overflow-x-auto table-wrapper" tabindex="0"><table>
<thead>
<tr>
<th>Area</th>
<th>Traditional tool</th>
<th>Pydantic Logfire</th>
</tr>
</thead>
<tbody>
<tr>
<td>API monitoring</td>
<td>Sentry / Datadog</td>
<td>Yes</td>
</tr>
<tr>
<td>Database queries</td>
<td>Datadog</td>
<td>Yes</td>
</tr>
<tr>
<td>Redis / cache</td>
<td>Datadog</td>
<td>Yes</td>
</tr>
<tr>
<td>Background tasks</td>
<td>Datadog</td>
<td>Yes</td>
</tr>
<tr>
<td>LLM calls (OpenAI, Anthropic)</td>
<td>LangSmith</td>
<td>Yes</td>
</tr>
<tr>
<td>AI agents (LangChain, Pydantic AI)</td>
<td>LangSmith</td>
<td>Yes</td>
</tr>
<tr>
<td>System metrics</td>
<td>Datadog</td>
<td>Yes</td>
</tr>
</tbody>
</table></div>
</section><section id="doing-it-with-pydantic-logfire-section"><h2 id="doing-it-with-pydantic-logfire" role="presentation"><a href="#doing-it-with-pydantic-logfire" class="heading-anchor"><button type="button" class="heading-anchor__btn">#</button></a><span role="heading" aria-level="2">Doing it with Pydantic Logfire</span></h2>
<p>Logfire is an AI-native observability platform from the Pydantic team, built as an <a href="https://github.com/pydantic/logfire">opinionated wrapper around OpenTelemetry</a>. The part that matters for adoption is that it doesn't ask for a rewrite. You initialize it and instrument your agent at the entry point, without touching your agent code:</p>
<pre><code class="hljs language-python"><span class="hljs-keyword">import</span> logfire

logfire.configure()
logfire.instrument_pydantic_ai()
</code></pre>
<p>From there, a few things come for free. You get conversation replay, tool-call inspection, and token and cost breakdowns, because Logfire automatically detects the <a href="https://pydantic.dev/docs/logfire/integrations/agent-frameworks/support-matrix/#native-otel-genai">GenAI semantic conventions</a> in the spans. That covers the per-step <strong>LLM cost tracking</strong> from the section above without custom work.</p>
<p>The full-stack angle is the real differentiator. When you're debugging an agent you're really asking three questions: was it the model, the tool, or the backend? An LLM-only tool can only answer the middle one. Because Logfire traces the whole stack, <a href="https://pydantic.dev/docs/logfire/get-started/">all three land on the same trace</a>.</p>
<p>Two more things I've come to rely on. Logfire exposes your observability data over <a href="https://pydantic.dev/docs/logfire/reference/sql/">SQL</a> (PostgreSQL-compatible) and ships an <a href="https://pydantic.dev/docs/logfire/guides/mcp-server/">MCP server</a>, so a coding agent can query production directly and ask questions nobody built a dashboard for. And it integrates with <a href="https://pydantic.dev/docs/ai/evals/evals/">pydantic-evals</a>, so the traces you capture in production become the datasets you evaluate against. That closes the loop from incident to test.</p>
<p><img src="https://pydantic.dev/assets/blog/agent-observability-layer/production-to-evaluation-flywheel.png" alt="Production to evaluation flywheel: 1. Production agent execution, instrumented via logfire.instrument_pydantic_ai(). 2. Full-stack OpenTelemetry tracing, capturing spans, tool calls and LLM costs. 3. SQL and MCP data export, querying production incidents via PostgreSQL SQL or the MCP server. 4. pydantic-evals testing harness, converting captured traces into evaluation test suites, which feeds back into production agent execution." decoding="async"></p>
</section><section id="what-changes-when-observability-is-a-first-class-layer-section"><h2 id="what-changes-when-observability-is-a-first-class-layer" role="presentation"><a href="#what-changes-when-observability-is-a-first-class-layer" class="heading-anchor"><button type="button" class="heading-anchor__btn">#</button></a><span role="heading" aria-level="2">What changes when observability is a first-class layer</span></h2>
<p>When this layer is in place from day one rather than bolted on after an outage, three things change.</p>
<p>Debugging stops being archaeology. You read a trace and find where the chain diverged, instead of re-running the agent and hoping it misbehaves the same way twice. Cost stops being a surprise, because per-step spend is a number you watch. And production stops being a black box: every captured trace is a candidate test case, so the system gets measurably better instead of anecdotally better. Because this rides on open primitives, anything built on Pydantic AI inherits it. Pydantic Deep Agents, an open-source deep-agent harness (full disclosure, it comes from my team at Vstorm), lights up with the very same one-line setup.</p>
<p>None of this is exotic. It's tracing, metrics, and evals, the same primitives we've always used, applied to a system that happens to think out loud. Agent observability isn't an add-on. It's <a href="https://agentuity.com/ai-agent-observability">a prerequisite for running agents in production responsibly</a>. Or, to borrow the house line: AI, it's still just engineering.</p>
<hr>
<section id="want-to-see-these-primitives-in-a-real-agent-harness-section"><h3 id="want-to-see-these-primitives-in-a-real-agent-harness" role="presentation"><a href="#want-to-see-these-primitives-in-a-real-agent-harness" class="heading-anchor"><button type="button" class="heading-anchor__btn">#</button></a><span role="heading" aria-level="3">Want to see these primitives in a real agent harness?</span></h3>
<p><strong>Pydantic Deep Agents</strong> is an open-source, self-hosted agent harness built on Pydantic AI: planning, sandboxed execution, sub-agent teams, and skills, on any model. Instrument it with Logfire and you get the trace view from this article for free.</p>
<p><a href="https://github.com/vstorm-co/pydantic-deepagents?utm_source=pydantic&#x26;utm_medium=partnership&#x26;utm_campaign=agent-observability-layer"><strong>github.com/vstorm-co/pydantic-deepagents</strong></a></p></section></section>]]></content:encoded>
</item>
<item>
<title>Debugging production from your editor with the Logfire MCP server</title>
<link>https://pydantic.dev/articles/debugging-production-with-logfire-mcp-and-cursor</link>
<guid isPermaLink="true">https://pydantic.dev/articles/debugging-production-with-logfire-mcp-and-cursor</guid>
<pubDate>Wed, 30 Sep 2026 09:00:00 GMT</pubDate>
<dc:creator>Laís Carvalho</dc:creator>
<category>Pydantic Logfire</category>
<category>MCP</category>
<description>Connect Pydantic Logfire&apos;s MCP server to Cursor, Claude Code, or Codex and let your coding agent query real production traces, then build the dashboard and the alert that catch the next one.</description>
<content:encoded><![CDATA[<p>The bug report says checkout is failing. Cursor is open on the file you suspect, and <a href="https://pydantic.dev/logfire">Pydantic Logfire</a> is open in another window on the trace that proves you suspect the wrong file. In between is you, moving stack traces from one to the other by hand and dropping most of the context along the way.</p>
<p>Your coding agent has read every line of your repository. It has never seen a single request your users made. So it guesses, and the guesses are plausible, and you spend the afternoon establishing which one was wrong.</p>
<p><a href="https://www.linkedin.com/in/marcelotryle/">Marcelo Trylesinski</a> and <a href="https://www.linkedin.com/in/summerscope/">Laura Summers</a> ran <a href="https://pydantic.dev/events/ask-your-traces">a live session</a> on this recently, showing how to use Logfire MCP to help with bug investigations.</p>
<section id="what-is-the-logfire-mcp-server-section"><h2 id="what-is-the-logfire-mcp-server" role="presentation"><a href="#what-is-the-logfire-mcp-server" class="heading-anchor"><button type="button" class="heading-anchor__btn">#</button></a><span role="heading" aria-level="2">What is the Logfire MCP server?</span></h2>
<p>The <a href="https://pydantic.dev/docs/logfire/guides/mcp-server/">Logfire MCP server</a> is a hosted Model Context Protocol server that exposes your OpenTelemetry traces, logs, and metrics to any MCP client. It runs at <code>https://logfire-us.pydantic.dev/mcp</code> for US projects and <code>https://logfire-eu.pydantic.dev/mcp</code> for EU projects (the different Logfire instances) and it authenticates over OAuth in the browser or with a Logfire API key as a bearer token.</p>
<p>It exposes 51 tools across queries, dashboards, alerts, notification channels, issues, and feature-flag variables. One of them does nearly all the work: Marcelo, who helped build it, puts <code>query_run</code> at over 99% of all calls, because Pydantic Logfire stores spans as SQL, which makes investigations much easier since agents are very good at writing SQL.</p>
</section><section id="how-do-you-set-up-the-logfire-mcp-server-section"><h2 id="how-do-you-set-up-the-logfire-mcp-server" role="presentation"><a href="#how-do-you-set-up-the-logfire-mcp-server" class="heading-anchor"><button type="button" class="heading-anchor__btn">#</button></a><span role="heading" aria-level="2">How do you set up the Logfire MCP server?</span></h2>
<p>There are three routes in, all will take you under a minute. Pick the row that matches your editor.</p>
<div class="overflow-x-auto table-wrapper" tabindex="0"><table>
<thead>
<tr>
<th>Client</th>
<th>Route in</th>
</tr>
</thead>
<tbody>
<tr>
<td>Claude Code</td>
<td><code>/plugins</code>, then install <code>logfire</code> from the official marketplace</td>
</tr>
<tr>
<td>Codex</td>
<td>Install <a href="https://chatgpt.com/plugins/plugin_asdk_app_6a9a83e37cc4819188896feeab8966ea">Logfire from the OpenAI plugin marketplace</a>, or add it from the CLI</td>
</tr>
<tr>
<td>Cursor and everything else</td>
<td>The remote server URL in your MCP config</td>
</tr>
</tbody>
</table></div>
<p>If you use Claude Code: run <code>/plugins</code>, find <code>logfire</code>, install, authenticate in the browser. You get the MCP server plus <a href="https://pydantic.dev/articles/pydantic-ai-logfire-claude-code-skills">skills</a>, for querying, instrumenting, and navigating the Logfire UI.</p>
<p>Codex users get the same content from the <a href="https://chatgpt.com/plugins/plugin_asdk_app_6a9a83e37cc4819188896feeab8966ea">Logfire plugin on the OpenAI marketplace</a>. Open the listing, install it, and log in. The CLI route reaches the same plugin through the published <code>pydantic/skills</code> marketplace:</p>
<pre><code class="hljs language-bash">codex plugin marketplace add pydantic/skills --ref main
codex plugin add logfire@pydantic-skills
codex mcp login logfire
</code></pre>
<p>Start a new Codex conversation afterward so the MCP tools load.</p>
<p>Everywhere else, point at the remote server directly. There is no token to paste into a file you might later commit. For Cursor, that is <code>.cursor/mcp.json</code> in your project root:</p>
<pre><code class="hljs language-json"><span class="hljs-punctuation">{</span>
	<span class="hljs-attr">"mcpServers"</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">{</span>
		<span class="hljs-attr">"logfire"</span><span class="hljs-punctuation">:</span> <span class="hljs-punctuation">{</span>
			<span class="hljs-attr">"url"</span><span class="hljs-punctuation">:</span> <span class="hljs-string">"https://logfire-us.pydantic.dev/mcp"</span>
		<span class="hljs-punctuation">}</span>
	<span class="hljs-punctuation">}</span>
<span class="hljs-punctuation">}</span>
</code></pre>
<p>Use <code>https://logfire-eu.pydantic.dev/mcp</code> if your project lives in the EU region, or your own URL if you self-host. In Claude Code without the plugin it is two commands:</p>
<pre><code class="hljs language-bash">claude mcp add --transport http logfire https://logfire-us.pydantic.dev/mcp
claude mcp login logfire
</code></pre>
<p>For CI, a container, or anywhere without a browser, authenticate with a Logfire API key as a bearer token. <a href="https://pydantic.dev/docs/logfire/instrument/typescript/reference/cli/#read-tokens">Read scope</a> covers everything up to the section on writing.</p>
<p>Then verify. A question to start can be: "can you check whether I have data in Logfire?" You want a project name and a row count back. In the demo video, Claude went further unprompted and ran a query grouping records by service with an exception count, because it could see which tools it had.</p>
</section><section id="why-does-the-logfire-mcp-server-use-sql-section"><h2 id="why-does-the-logfire-mcp-server-use-sql" role="presentation"><a href="#why-does-the-logfire-mcp-server-use-sql" class="heading-anchor"><button type="button" class="heading-anchor__btn">#</button></a><span role="heading" aria-level="2">Why does the Logfire MCP server use SQL?</span></h2>
<p>Logfire uses SQL because models write SQL better than they navigate bespoke query APIs. Logfire is built on OpenTelemetry and stores spans in a queryable <code>records</code> table, so there is no filter DSL for an agent to learn and no dropdown vocabulary to guess at.</p>
<p>That design decision is why <code>query_run</code> carries over 99% of traffic, and why it has its own eval suite across several models and coding agents. The tool description instructs the agent to fetch the SQL schema reference first if it does not already hold one, so schema grounding happens without you configuring anything. Hallucinated column names cause most failed observability queries, and this is the fix.</p>
<p>A first pass at a failing endpoint looks like this:</p>
<pre><code class="hljs language-sql"><span class="hljs-keyword">SELECT</span> start_timestamp,
       http_route,
       http_response_status_code,
       exception_type,
       exception_message,
       trace_id
<span class="hljs-keyword">FROM</span> records
<span class="hljs-keyword">WHERE</span> is_exception
  <span class="hljs-keyword">AND</span> http_route <span class="hljs-operator">=</span> <span class="hljs-string">'/api/chat'</span>
<span class="hljs-keyword">ORDER</span> <span class="hljs-keyword">BY</span> start_timestamp <span class="hljs-keyword">DESC</span>
LIMIT <span class="hljs-number">20</span>
</code></pre>
<p>You will rarely write that yourself, but you should be able to read it. Marcelo's take is that he does not worry about the SQL and mostly asks the agent to explain the query back.</p>
<p>Some caveats: Logfire's dialect is the DataFusion flavor, and models sometimes reach for a function from a dialect they have seen more of, like ClickHouse. And on a project with a lot of spans, an agent left alone will happily request a two-month window when it needed the last hour.</p>
<p>The latter scenario has a check layer to help: when the query planner can see a query will run long, it fails fast with a tool error. The agent reads the error as output, narrows the window or adds a filter, and calls it again. That retry happens constantly, and it is mostly invisible to the user.</p>
</section><section id="what-does-a-debugging-session-look-like-section"><h2 id="what-does-a-debugging-session-look-like" role="presentation"><a href="#what-does-a-debugging-session-look-like" class="heading-anchor"><button type="button" class="heading-anchor__btn">#</button></a><span role="heading" aria-level="2">What does a debugging session look like?</span></h2>
<p>The demo app was a forum where LLM agents argue with each other, instrumented with Logfire and seeded with real exceptions. The sequence ran in six steps.</p>
<ol>
<li><strong>Find the problem.</strong> The opening question was just whether there was data. The answer came back with exceptions already surfaced, including a <code>ZeroDivisionError</code>.</li>
<li><strong>Fix it.</strong> "Investigate and fix the zero division error." The agent queried for the exception, got the stack trace and the exact line from the span, opened the file, added the guard, and removed the now unreachable handler.</li>
<li><strong>Ask something a stack trace cannot answer.</strong> Laura asked which agent in the forum was most verbose. The answer came back as the historian, which surprised no one <em>who has met a historian</em>.</li>
<li><strong>Make the one-off durable.</strong> "Create a dashboard showing verbosity of the agents over time." It built one measuring average visible output tokens per agent turn, and added panel descriptions on request.</li>
<li><strong>Add the alert.</strong> Rather than specifying it, Marcelo asked for a suggestion: "I've had a lot of 500s lately, can you suggest an alert for it?" The agent proposed a query filtered by service and route on 5xx status with a count threshold above 20 requests, and created it.</li>
<li><strong>Close the loop.</strong> Asked for a notification channel pointing at an ngrok tunnel, the agent created the webhook channel too. The receiver on the far end was wired to spawn a coding agent on the alert payload with read-only tools. Claude configured an alert that pages Claude.</li>
</ol>
</section><section id="what-can-you-ask-beyond-errors-section"><h2 id="what-can-you-ask-beyond-errors" role="presentation"><a href="#what-can-you-ask-beyond-errors" class="heading-anchor"><button type="button" class="heading-anchor__btn">#</button></a><span role="heading" aria-level="2">What can you ask beyond errors?</span></h2>
<p>Some of the questions you can answer with the Logfire MCP are the ones you would not build a dashboard panel for: token counts per route, whether a code path fired at all. Nobody should build a chart to answer a question they plan to ask once.</p>
<p>Latency by model and operation, for when a provider quietly degrades:</p>
<pre><code class="hljs language-sql"><span class="hljs-keyword">SELECT</span> attributes<span class="hljs-operator">-</span><span class="hljs-operator">>></span><span class="hljs-string">'gen_ai.request.model'</span> <span class="hljs-keyword">AS</span> model,
       attributes<span class="hljs-operator">-</span><span class="hljs-operator">>></span><span class="hljs-string">'gen_ai.operation.name'</span> <span class="hljs-keyword">AS</span> operation,
       <span class="hljs-built_in">count</span>(<span class="hljs-operator">*</span>) <span class="hljs-keyword">AS</span> spans,
       <span class="hljs-built_in">avg</span>(duration) <span class="hljs-keyword">AS</span> avg_duration
<span class="hljs-keyword">FROM</span> records
<span class="hljs-keyword">WHERE</span> attributes<span class="hljs-operator">-</span><span class="hljs-operator">>></span><span class="hljs-string">'gen_ai.request.model'</span> <span class="hljs-keyword">IS</span> <span class="hljs-keyword">NOT</span> <span class="hljs-keyword">NULL</span>
<span class="hljs-keyword">GROUP</span> <span class="hljs-keyword">BY</span> model, operation
<span class="hljs-keyword">ORDER</span> <span class="hljs-keyword">BY</span> avg_duration <span class="hljs-keyword">DESC</span>
</code></pre>
<p>Anything under <code>gen_ai.*</code> slices the same way, so token counts, providers, tool names, and model reasoning sit in the same table as your HTTP spans. If it renders in a span in the Logfire UI, your agent can query it. Reasoning traces included.</p>
<p>The other habit worth forming is asking whether a code path is firing at all. It sounds too simple to be useful. It catches the deployment that merged green, passed CI, and does nothing.</p>
</section><section id="can-the-logfire-mcp-server-write-as-well-as-read-section"><h2 id="can-the-logfire-mcp-server-write-as-well-as-read" role="presentation"><a href="#can-the-logfire-mcp-server-write-as-well-as-read" class="heading-anchor"><button type="button" class="heading-anchor__btn">#</button></a><span role="heading" aria-level="2">Can the Logfire MCP server write as well as read?</span></h2>
<p>Yes, the tool surface has read and write capabilities. An agent with the right write scopes can create and modify five kinds of object, and triage a sixth:</p>
<ul>
<li><strong>Dashboards</strong>, including panels, variables, and layout groups</li>
<li><strong>Alerts</strong>, with their queries, thresholds, and evaluation windows</li>
<li><strong>Notification channels</strong>, webhook and Opsgenie</li>
<li><strong>Managed feature-flag variables</strong>, including versions, labels, and rollout</li>
<li><strong>Notification schedules</strong></li>
<li><strong>Issue states</strong>, which it changes on existing issues rather than opening new ones</li>
</ul>
<p>When you fix an incident you know exactly which signal would have caught it, and that knowledge has a half-life of about a day. Creating the alert before the signal is lost is what improves system resilience. It's the you-of-today preventing the issues of tomorrow.</p>
<p>Two caveats on credentials. An agent deletes a dashboard as fluently as it builds one, so grant write scopes only when the session needs them. And a read token is not the harmless one: traces and logs carry user-controlled content, model payloads, and tool arguments, which an agent can surface to the wrong place or read as instructions. Scope and protect both.</p>
</section><section id="when-should-the-agent-write-python-instead-section"><h2 id="when-should-the-agent-write-python-instead" role="presentation"><a href="#when-should-the-agent-write-python-instead" class="heading-anchor"><button type="button" class="heading-anchor__btn">#</button></a><span role="heading" aria-level="2">When should the agent write Python instead?</span></h2>
<p>Reach for the <code>exec</code> tool when a task needs more than about three chained queries. Six sequential tool calls means six round trips, each returning JSON the model must read before choosing the next, all accumulating in context.</p>
<p>Logfire's code-execution endpoint exists for this. It is a separate MCP server from the 51-tool one, with three tools in total. <code>exec</code> takes Python and runs it server-side in <a href="https://pydantic.dev/articles/pydantic-monty">Monty</a>, with every one of those 51 tools wrapped as a function inside the sandbox, <code>help</code> lets the agent discover what those functions are, and <code>results</code> retrieves output from earlier runs. Only the printed summary crosses the wire. Fetch the alert, pull metrics and traces and deploys with <code>asyncio.gather</code>, correlate them, print four lines. Intermediate data never touches your context window.</p>
<p>The savings are large. Anthropic has reported reductions from 150,000 tokens to 2,000 in comparable setups, a 98.7% cut, and Cloudflare found a full MCP implementation of their 2,500-endpoint API would have consumed 1.17 million tokens before the first user message. Jiri wrote up our version in <a href="https://pydantic.dev/articles/your-agent-would-rather-write-code">Your agent would rather write code</a>. His conclusion: it wins decisively on multistep composition, and plain tool calls stay faster for a single lookup.</p>
</section><section id="where-does-the-logfire-mcp-server-stop-helping-section"><h2 id="where-does-the-logfire-mcp-server-stop-helping" role="presentation"><a href="#where-does-the-logfire-mcp-server-stop-helping" class="heading-anchor"><button type="button" class="heading-anchor__btn">#</button></a><span role="heading" aria-level="2">Where does the Logfire MCP server stop helping?</span></h2>
<p>The Logfire MCP server localizes bugs that appear in a trace, and it does not find bugs that only appear as a pattern across files. Four limits worth knowing:</p>
<p><strong>A trace pointing at a line is the best case.</strong> The agent is excellent when evidence localizes to one file, as the zero division fix did. It is much weaker at "this same missing cleanup exists in nine components", because nothing in a single trace tells it to look for the pattern.</p>
<p><strong>Shipping the fix is not evidence the fix worked.</strong> The agent knows the code changed. It has no idea what production did afterward. Query the traces again a day later and compare intended against actual. AutonomyAI automated this, and it is where their 12 silent no-op deployments came from.</p>
<p><strong>Ask clarifying questions.</strong> Laura's take is to tell the agent a query smells and ask it to explain itself, or to ask an alert query which conditions would make it fire and which would not. A long query full of nested CTEs usually means the model overcomplicated something.</p>
<p><strong>Grounding raises the floor.</strong> The model will argue based on info from real spans, but it will still draw confident conclusions from queries that quietly excluded half the traffic.</p>
</section><section id="which-teams-use-the-logfire-mcp-server-in-production-section"><h2 id="which-teams-use-the-logfire-mcp-server-in-production" role="presentation"><a href="#which-teams-use-the-logfire-mcp-server-in-production" class="heading-anchor"><button type="button" class="heading-anchor__btn">#</button></a><span role="heading" aria-level="2">Which teams use the Logfire MCP server in production?</span></h2>
<p>Dosu and AutonomyAI both run the Logfire MCP server as their primary debugging surface. Dosu reports the time saved; AutonomyAI reports the regressions caught.</p>
<p><a href="https://pydantic.dev/case-studies/dosu">Dosu</a> runs 54 agents across more than 697,000 production runs and does most debugging inside the coding agent rather than the Logfire UI. Some traces run past 25 minutes, which is a lot of tool calls to scroll through by hand. Across one 14-day period the team worked through 193 production traces this way before the MCP server changed the workflow.</p>
<blockquote>
<p>"Being able to ask questions right within our coding agent and get cited metrics back has been invaluable. It's rare that I have to really dig into Logfire unless it's a really gnarly problem."</p>
<p>— Taylor Dolezal, Head of OSS at Dosu</p>
</blockquote>
<p>Dosu puts the cut in debugging time at 90%, with time to root cause falling from about an hour to a few minutes, and credits the Logfire agents dashboard with surfacing prompt-caching bugs worth over $30,000 a year.</p>
<p><a href="https://pydantic.dev/case-studies/autonomyai">AutonomyAI</a> pointed their own agents at it. Their agents query Logfire while building to check what a code path did, and again in the days after a change merges. Over five weeks that post-merge pass ran across 105 merged PRs, surfaced 65 issues from real traffic, and caught 12 deployments that merged clean and were silently doing nothing. Logfire ingested over 35 million spans in three weeks, and runs about 3.5x cheaper than the Datadog deployment it sits alongside.</p>
<blockquote>
<p>"Most of our engineers and our internal systems now use the Logfire MCP for basically everything. We barely open the Logfire UI, just because we are so happy with MCP."</p>
<p>— Tammuz Dubnov, co-founder and CTO at AutonomyAI</p>
</blockquote>
</section><section id="how-to-get-started-section"><h2 id="how-to-get-started" role="presentation"><a href="#how-to-get-started" class="heading-anchor"><button type="button" class="heading-anchor__btn">#</button></a><span role="heading" aria-level="2">How to get started?</span></h2>
<p>Install the plugin or add the URL, authenticate, and ask your agent what broke in production this week. If you are not sending traces yet, the <a href="https://pydantic.dev/docs/logfire/">Logfire docs</a> cover Python, JavaScript, Rust, and anything else that speaks OpenTelemetry. The free tier is plenty to answer the question.</p>
<p>Your coding agent already knows your code by heart. Give it the part your code cannot tell it.</p>
</section><section id="frequently-asked-questions-section"><h2 id="frequently-asked-questions" role="presentation"><a href="#frequently-asked-questions" class="heading-anchor"><button type="button" class="heading-anchor__btn">#</button></a><span role="heading" aria-level="2">Frequently asked questions</span></h2>
<p><strong>What is the Logfire MCP server?</strong>
The Logfire MCP server is a hosted Model Context Protocol server that exposes Pydantic Logfire's OpenTelemetry traces, logs, and metrics to an MCP client such as Cursor, Claude Code, or Codex. It lets a coding agent query production data in SQL and return answers with trace IDs attached, without anyone opening the Logfire UI.</p>
<p><strong>How do I connect Logfire MCP to Cursor?</strong>
Add the remote server to <code>.cursor/mcp.json</code> in your project root with the URL <code>https://logfire-us.pydantic.dev/mcp</code>, or <code>https://logfire-eu.pydantic.dev/mcp</code> for EU projects. Cursor prompts for browser authentication the first time it calls a tool. Nothing needs installing locally.</p>
<p><strong>Does the Logfire MCP server work with Claude Code and Codex?</strong>
Yes. Claude Code has an official marketplace plugin, installed by running <code>/plugins</code> and selecting <code>logfire</code>, which bundles the MCP server with skills for querying, instrumenting, and navigating Logfire. Codex installs the same content from the <a href="https://chatgpt.com/plugins/plugin_asdk_app_6a9a83e37cc4819188896feeab8966ea">Logfire plugin on the OpenAI marketplace</a>, or from the CLI by adding the <code>pydantic/skills</code> marketplace, running <code>codex plugin add logfire@pydantic-skills</code>, then <code>codex mcp login logfire</code>.</p>
<p><strong>Can an AI agent write SQL against production traces reliably?</strong>
Mostly, with two known failure modes. Models sometimes use functions from other SQL dialects, since Logfire uses the DataFusion flavor, and they sometimes request time windows far wider than needed. The <code>query_run</code> tool description instructs the agent to fetch the schema reference before querying, and Logfire fails long-running queries fast so the agent retries with a narrower one.</p>
<p><strong>Can the Logfire MCP server create dashboards and alerts?</strong>
Yes. Beyond querying, it creates and edits dashboards, alerts, notification channels, notification schedules, and managed feature-flag variables, and it moves existing issues between states. This lets a debugging session end with permanent monitoring rather than a one-off answer. Scope credentials carefully in both directions: an agent deletes a dashboard as easily as it creates one, and read access alone exposes whatever user content your traces carry.</p>
<p><strong>How much time does the Logfire MCP server save?</strong>
Dosu reports a 90% reduction in debugging time, with time to root cause dropping from roughly an hour to a few minutes across 54 agents and more than 697,000 production runs. AutonomyAI's post-merge review surfaced 65 issues and caught 12 silently failed deployments over five weeks.</p>
<p><strong>Does Logfire require Python or Pydantic AI?</strong>
No. Logfire is built on OpenTelemetry and ingests traces from any stack that emits OTel data, including JavaScript, Rust, and Go. Pydantic AI ships with built-in Logfire instrumentation, which makes setup a single step, but it is not a requirement.</p></section>]]></content:encoded>
</item>
</channel>
</rss>