页面简介
Let a Pydantic AI agent call its tools from one sandboxed Python script (programmatic tool calling) instead of one model round-trip per tool call.
正文摘录
Code Mode Code Mode lets the model call your tools from one sandboxed Python program instead of a model turn per dependent batch of tool calls. CodeMode puts them behind a run_code tool: the model writes code that calls them as functions, with loops, conditionals, variables, and asyncio.gather, and the Monty sandbox runs it. Source While Pydantic AI Harness is on 0.x releases, the API may change between minor releases; when it does, deprecation warnings and release-note migration guidance tell you (or your agent) exactly how to upgrade. See the version policy. flowchart LR accTitle: Code Mode: one program instead of a tool call per step accDescr: The model sends one run_code program to CodeMode, which runs it in the Monty sandbox. The program calls list_items on your tools and gets 10 ids, then calls get_item 10 times in parallel and gets 10 full items. It filters them in Python, so the 10 items stay in the sandbox and only the 3 matching names go back to the model. model(["model"]) cap["CodeMode()<br/>Monty sandbox<br/>filters in Python"]:::capability tools["your tools"] model -->|"run_code,<br/>one program"| cap cap -->|"list_items, then<br/>get_item x 10<br/>in parallel"| tools tools -->|"10 ids, then<br/>10 full items"| cap cap -->|"only the 3<br/>matching names"| model classDef capability stroke:#E520E9,stroke-width:2px classDef external stroke:#0E9C86,stroke-width:2px classDef blocked stroke:#E5533D,stroke-width:2px,stroke-dasharray:4 3 The problem Standard tool calling often needs a model turn per dependent batch of tool calls: fetching 10 items and then processing them can take many turns, adding latency, cost, and context, and every intermediate result grows the history. The solution CodeMode wraps eligible tools into a single run_code tool and dispatches each call its code makes through Pydantic AI to the host tool. Standard tool callingCode modeDependent tool batches across model turnsMany dependent calls in one run_codeParallel only when the model emits a batchParallelism expressed in PythonNo local computationFilter, transform, aggregate in codeLarge conversation historyCompact, with fewer messages Durable execution integrations can record nested calls for deterministic replay. Code Mode or IPython Code Mode IPython Code Mode offers the same run_code tool on a persistent IPython kernel instead of Monty. Pick by where the agent runs: Code ModeIPython Code ModeBuilt forProduction and web-facing agentsLocal agents you trust to do whatever the code asksSafe in a webserverYesNo, unless the agent runs in a sandboxPythonThe Monty subset, with time and memory limitsFull CPython, with any installed packageFilesystem and networkOnly through mount, os_access, and toolsUnrestricted, with the agent process’s permissionsStatePer run, plus an optional repl_storeA kernel per run, or one IPythonKernel kept across runs Installation Install the codemode extra for the Monty sandbox (code-mode is an alias): pip uv Terminalpip install "pydantic-ai-harness[codemode]" Usage Add CodeMode() to capabilities and register tools as usual; eligible tools become callable inside run_code: from pydantic_ai import Agent from pydantic_ai_harness import CodeMode agent = Agent('anthropic:claude-sonnet-5-5', capabilities=[CodeMode()]) @agent.tool_plain def get_weather(city: str) -> dict: """Get current weather for a city.""" return {'city': city, 'temp_f': 72, 'condition': 'sunny'} result = agent.run_sync("What's the weather in Paris and Tokyo, in Celsius?") print(result.output) The model then writes one run_code snippet like this (exact code varies), running both lookups in parallel: import asyncio paris, tokyo = await asyncio.gather( get_weather(city='Paris'), get_weather(city='Tokyo'), ) paris_c = round((paris['temp_f'] - 32) * 5 / 9, 1) tokyo_c = round((tokyo['temp_f'] - 32) * 5 / 9, 1) {'paris': paris_c, 'tokyo': tokyo_c} Selective tool sandboxing tools is a Pydantic AI ToolSelector: matching tools become callables inside run_code, and the rest stay regular tool calls. The default, tools='all', sandboxes every eligible regular tool. from pydantic_ai_harness import CodeMode # By name: only these tools are available inside run_code CodeMode(tools=['search', 'fetch']) # By predicate: (ctx, tool_def) -> bool | Awaitable[bool] CodeMode(tools=lambda ctx, td: td.name != 'dangerous_tool') # By metadata: combine with SetToolMetadata or a toolset's .with_metadata() CodeMode(tools={'code_mode': True}) These tools stay regular tool calls: Framework control tools and native fallbacks. Deferred tools the model hasn’t discovered yet. requires_approval=True and external tools, under the default tools='all'. Other code-execution tools, such as Shell’s run_command and start_command (so the model never quotes shell inside Python) and CapabilityCreation’s author_capability (its argument is a whole module). Their other tools, such as read_file, are folded in. To fold a code-execution tool anyway, set FOLD_INTO_CODE_MODE (from pydantic_ai_harness.code_mode) to True in its metadata, for example from prepare_tools. It keeps its code_arg_name, so instrumentation and other capabilities still treat it as code. Metadata-based selection Metadata lets the decision travel with a shared toolset: its author tags tools safe to call from generated code, and each agent opts in with CodeMode(tools={...}). A tool matches when its ToolDefinition.metadata contains all the selector’s key-value pairs, extra keys allowed and nested dictionaries matched by deep inclusion: from pydantic_ai import Agent from pydantic_ai.toolsets import FunctionToolset from pydantic_ai_harness import CodeMode def search(query: str) -> str: """Search the web.""" return f'results for {query}' def fetch(url: str) -> str: """Fetch a URL.""" return f'contents of {url}' search_tools = FunctionToolset(tools=[search, fetch]).with_metadata(code_mode=True) agent = Agent( 'anthropic:claude-sonnet-5-5', toolsets=[search_tools], capabilities=[CodeMode(tools={'code_mode': True})], ) search and fetch leave the model-facing tool list and become functions inside run_code; untagged tools stay regular tool calls. Tool Search interaction Tools or whole toolsets marked defer_loading=True (Tool Search) stay out of run_code until discovered. Once the model discovers a tool, or loads the deferred capability that owns it, CodeMode folds it into run_code if the tools selector matches it. Under tools='all', a discovered requires_approval=True or external tool stays native. With the default dynamic_catalog=True, the signatures of sandboxed tools live in the instructions, not in run_code’s description. Each discovery appends to them (on_change='append') and sends the model a short note naming the new functions, so earlier messages stay as sent and the prompt cache survives. A deferred tool that run_code will take over isn’t declared to the model until found, and is then callable only from run_code. The catalog puts tool definitions, including MCP-supplied names, descriptions, and schemas, into the instructions. The model already receives tool definitions with the same authority, so this grants nothing new; connect only MCP servers you trust. Two setups still move the cached prefix on discovery, as with dynamic_catalog=False: A callable tools selector that answers differently for a tool before and after it’s revealed. The 'bm25' and 'regex' strategies, which have no local search_tools: only the provider’s native search finds deferred tools, so a tool that run_code will take over is declared natively first. If the tools selector sandboxes some deferred tools and keeps others native, the local search_tools finds both by keyword matching (or your strategy callable) instead of the provider’s native tool search. Another toolset with id code_mode that contributes instructions clashes with the catalog and makes the run raise a UserError; rename it. dynamic_catalog=False, the default in earlier releases, keeps the catalog in run_code’s description: from pydantic_ai_harness import CodeMode CodeMode(dynamic_catalog=False) Each discovery then grows that description and invalidates the prompt cache from that point on; turns without a discovery stay cache-warm. Deferred tools are declared to the provider’s native tool search where there is one. To keep a Tool Search corpus fully native (not callable from run_code), exclude the tools a native tool manages: from pydantic_ai_harness import CodeMode CodeMode(tools=lambda ctx, td: td.with_native is None) Return values The snippet’s last expression is its return value, so no print() is needed. An assignment returns nothing, so put the name on the last line: result = await get_weather(city='Paris') result Use print() for supplementary logging; printed text is returned alongside the result: ScenarioReturnNon-None final expression with no print outputLast expression valueFinal assignment or None result with no print output{}Print output with no final expression or a None result{'output': '<printed text>'}Print output with a plain, non-None final expression{'output': '<printed text>', 'result': <last expression>}Multimodal final expression with no print outputReturned natively for model processingPrint output with a multimodal final expressionList with printed text followed by native multimodal content When a nested tool returns a ToolReturn, the snippet gets its return_value. Its content, such as a screenshot, never enters the sandbox: it goes to the model with the run_code result, in call order, as for a direct tool call. A nested tool that raises ToolFailed the snippet doesn’t catch ends run_code with a failed tool result instead of a retry, as for a direct call, and doesn’t spend run_code’s retries. The result is the tool’s message, after any printed output and followed by a summary of the other nested calls, if the snippet made any. A hook on the nested tool receives the tool’s exception; the ToolFailed that run_code raises is a new one carrying the extra text, with the tool’s exception as