Learning resourcesReviewed · Pydantic

Pydantic AI Harness: IPython Code Mode

This guide teaches Python developers to give local AI assistants a persistent Python workspace, but generated code runs with the user's permissions and is not sandboxed. It covers installation, tool integration, retained variables, execution limits and kernel management.

Researched 24 Nov 2026

In short.

This guide explains IPython Code Mode for developers building local AI assistants, with the main catch that generated code can access the host's files, network and credentials. The capability exposes one run_code tool backed by a persistent IPython kernel, allowing ordinary Python packages and registered agent tools to work together. The page documents setup, output handling, timeouts and kernel lifecycle, while explaining the absence of sandboxing and durable execution. Installation success, runtime reliability, performance and operating costs are not independently established.

Researched and written by an AI model and checked by a second AI model. How it works

Covers the complete documentation page at [https://pydantic.dev/docs/ai/harness/ipython-code-mode/index.md], including security and version notices, setup, examples, tool selection and dispatch, outputs, errors, kernel lifecycle, observability and the API reference. Linked pages, source files, issue discussions and licence documents are excluded. No code was executed; installation, runtime behavior, performance, security effectiveness and production suitability remain unverified.

The overview

identity

The resource is Pydantic AI Harness's documentation for IPythonCodeMode and IPythonKernel. It explains how to add Python execution to a Pydantic AI agent and includes installation commands, examples, operational warnings and an API reference. The source page is [https://pydantic.dev/docs/ai/harness/ipython-code-mode/index.md].

IPythonCodeMode is the agent capability that supplies run_code. IPythonKernel manages the separate Python process and can retain its variables across multiple agent runs when explicitly shared.

assessment

The guide is useful when an assistant needs installed Python libraries, reusable intermediate data and several tool calls composed in one script. It provides enough detail to understand both basic integration and operational constraints.

Its central trade-off is host access. Generated Python inherits the running user's permissions, including access to credentials and subprocesses. The documentation warns against processing untrusted prompts, documents or web pages unless the whole agent is isolated in a suitably restricted container or virtual machine. Running locally alone does not provide that isolation.

users

The intended audience is developers building local data-analysis or coding assistants with Pydantic AI. Beginners get a small integration example; experienced developers get details about tool dispatch, shared kernels, failure recovery and platform differences.

Following the examples requires familiarity with Python environments, agent configuration and function registration. Developers building web-facing or shared services should pay particular attention to the isolation warning and the page's comparison with Monty-based Code Mode.

capabilities

The kernel offers full CPython and packages installed in its Python environment. Variables, imports, functions and loaded data persist between run_code calls. Supported IPython features include magics, shell escapes and top-level await.

The final expression can return structured data, a textual representation or an image. Displayed images can also reach the model. Printed output combines standard output, standard error and textual displays in order, with a 10 MiB cap per call.

A tool selector can expose all eligible tools, named tools, tools matching a predicate or tools matching metadata. Unselected tools remain ordinary agent tools, and some framework control and code-execution tools always remain native.

Using it

requirements

The documented installation uses the ipython extra of pydantic-ai-harness, which supplies jupyter-client and ipykernel. The examples assume a configured Pydantic AI agent and model. Provider authentication instructions and a complete Python compatibility matrix are not supplied.

The default python3 kernelspec launches the kernel with the agent's Python interpreter. Another installed IPython kernelspec can select a different environment. Packages used by generated code must be available in that environment; the sales example uses pandas.

The agent communicates with its kernel over Unix sockets where available. On Windows, the page describes local TCP connections without transport encryption and warns that other users on the machine can connect and read code and output.

mechanism

IPythonCodeMode places eligible agent tools behind run_code and defines them in the kernel as synchronous functions with keyword-only parameters. Each function call travels through Jupyter's stdin channel back to Pydantic AI for execution. Calls run one at a time.

These calls retain argument validation, capability hooks and approval or deferral handlers. Those controls apply to registered tool calls; generated Python still has the host access described in the security warning. Tool-call approvals therefore do not establish containment of arbitrary Python.

Tool failures raise ToolCallError inside the kernel and can be caught by generated code. Nested calls and returns are recorded in run_code metadata. Core instrumentation records run_code and its nested tool calls; the capability emits no separate spans.

setup

The page gives two installation commands: pip install "pydantic-ai-harness[ipython]" or uv add "pydantic-ai-harness[ipython]". Integration then consists of adding IPythonCodeMode() to the Agent capabilities and registering tools as usual, such as with @agent.tool_plain.

By default, each agent run starts its kernel on the first run_code call and shuts it down when the run ends. A run that never calls run_code starts no kernel.

To retain state across runs, create an IPythonKernel and pass it through IPythonCodeMode(kernel=...). Manage its lifetime with an async context manager or shutdown(). Configuration includes the kernelspec name, working directory and a startup timeout that defaults to 60 seconds.

example

The sales example registers get_sales(region), then illustrates generated code calling it for north and south regions, creating pandas DataFrames and calculating mean percentage changes. The imported pandas module and both DataFrames remain available in the next code call.

The sample tool returns the same two fixed monthly totals for every region, so it does not establish a regional difference. The generated script is explicitly illustrative. Execution success and analytical correctness are not established by the example.

A second example shares an IPythonKernel across runs so an assistant can load a CSV into a variable and later plot it. The example also passes conversation history to the subsequent agent run.

Assessment & evidence

limitations

There is no built-in sandbox or documented memory cap. The default timeout is 60 seconds per run_code call and excludes time spent in tool calls. A timeout first interrupts Python; code that keeps running for another five seconds causes kernel shutdown and loss of state.

The default maximum is 100 nested tool calls per run_code call. Nested calls also count toward the agent run's tool_calls_limit, together with run_code itself. Code exceptions consume the default allowance of three retries, while state created before an ordinary exception remains available.

Durable execution with Temporal, DBOS or Prefect is unsupported and fails before code execution. Eager execution, speculative execution and dynamic_catalog are also unsupported. A shared kernel executes one cell at a time and is tied to the event loop that started it.

The page warns of a Python 3.14 printing-and-interruption bug that can force kernel shutdown and discard state. It identifies Python 3.11 through 3.13 as unaffected and says Python 3.15 fixes the bug. These version-specific statements have not been independently verified.

reasoning

The practical fit follows from two documented properties: access to ordinary Python packages and retained in-memory state. Together, they can support analysis that reuses loaded data across several assistant steps. This is an architectural benefit, not a measured speed or accuracy improvement.

Persistent state also introduces a recovery boundary: crashes and forced shutdowns erase it, and sharing one kernel serializes execution. Retaining a namespace does not provide durable recovery.

The decisive deployment question is whether the agent's effective permissions are acceptable for every input it may encounter. Registered tool validation cannot be treated as a complete security boundary when code can access the host directly.

alternatives

The page's named alternative is Monty-based Code Mode at [https://pydantic.dev/docs/ai/harness/code-mode/]. Its comparison describes a restricted Python subset, time and memory limits, controlled filesystem and network access, concurrent asynchronous tool calls and support for durable execution.

The documentation recommends that alternative for production and web-facing agents. IPython Code Mode offers full CPython and installed packages, with the corresponding responsibility to control host access.

These comparisons come from the IPython Code Mode page. The linked alternative's documentation, implementation and runtime behavior have not been assessed here.

evidence

The evidence is the complete documentation page at [https://pydantic.dev/docs/ai/harness/ipython-code-mode/index.md], including its safety warnings, installation instructions, examples, comparison table and API reference. Linked documentation, repository files and issue discussions are outside the available evidence.

The page provides implementation descriptions and illustrative snippets. It does not supply independent installation results, benchmarks, security-audit findings or production reliability measurements. Runtime behavior remains unverified.

Access & freshness

costs

The page supplies no package pricing, model-provider rates or end-to-end operating costs. Whether a particular deployment incurs licence, model, hosting or other charges is unknown from this evidence.

Memory consumption, execution throughput and any savings from combining tool calls into scripts are not measured. No supported cost estimate or performance comparison can be derived from the examples.

rights

The page links to implementation source at [https://github.com/pydantic/pydantic-ai/tree/main/src/pydantic_ai_harness/pydantic_ai_harness/ipython_code_mode/]. It does not include licence text or establish commercial-use, modification or redistribution terms for the code or documentation.

The repository's licence, dependency licences and any applicable model-provider terms remain unknown within this page's evidence. A source link alone does not establish redistribution permission.

freshness

The documentation snapshot was captured at 2026-11-24T01:50:38.696Z. Its source revision is sha256:13f5053bd0a85df925255eff5a40a5d67fdade2a7284f4a3487820cdf2269a54, and its content checksum is 643d5d26a2197c7fbf8bf694fd79679b62ed55735e5b5e58dc9075ebb6bf1357. The capture timestamp does not establish a publication or package-release date.

The page warns that Pydantic AI Harness APIs may change between minor releases while on 0.x versions, with deprecation warnings and release-note migration guidance. It does not identify an exact package release for the documented behavior, so compatibility with a particular installed version is unknown.

actions

First decide whether full Python access is necessary and what files, network destinations and credentials the agent actually needs. Before processing untrusted prompts, documents or web pages, follow the documentation's requirement to isolate the whole agent in a container or virtual machine with only the required access.

For an appropriate environment, install the ipython extra, add the capability to a small agent and register a limited set of tools. Decide explicitly whether state should end with each run or persist through an owned IPythonKernel.

Before relying on the integration, verify the chosen package version, provider configuration, applicable terms and costs. Check tool approvals, timeout recovery, state loss and platform-specific transport behavior in the intended environment. These checks remain outstanding.

Evidence for this report

selected-page.txtselected · checked 2026-11-24