Jump to content

Connect SuperML | Leeroopedia MCP: Equip your AI agents with best practices, code verification, and debugging knowledge. Powered by Leeroo — building Organizational Superintelligence. Contact us at founders@leeroo.com.

Implementation:Openai Openai agents python CodeInterpreterTool Pattern

From Leeroopedia
Knowledge Sources
Domains Code Execution, Hosted Tools, Mathematical Computation
Last Updated 2026-02-11 00:00 GMT

Overview

Demonstrates using the CodeInterpreterTool hosted tool with streaming to execute Python code in a sandboxed container and capture both the generated code and its output.

Description

The CodeInterpreterTool pattern integrates OpenAI's hosted code interpreter capability into an agent, allowing it to write and execute Python code to solve computational problems. The tool runs in an auto-provisioned container ("container": {"type": "auto"}), meaning the platform handles sandbox lifecycle management automatically.

The example creates an agent that uses code interpreter to solve a math problem. It runs in streaming mode via Runner.run_streamed() and iterates over stream_events() to capture real-time output. The event filtering logic checks for run_item_stream_event events, then inspects the raw item for code_interpreter_call type to extract the generated Python code. A helper function _get_field handles both dictionary-style and attribute-style access patterns on the raw item objects, providing robustness across different response formats.

The streaming approach is particularly useful for code interpreter use cases because it allows the application to display the generated code to the user as it is produced, before the execution result is available. This provides transparency into the agent's problem-solving process.

Usage

Use this pattern when agents need to perform calculations, data analysis, or any task that benefits from executing Python code. It is ideal for mathematical problem solving, data transformation, statistical analysis, or generating visualizations where the agent needs a runtime environment to produce accurate results.

Code Reference

Source Location

Signature

CodeInterpreterTool(
    tool_config={"type": "code_interpreter", "container": {"type": "auto"}}
)

Import

from agents import Agent, CodeInterpreterTool, Runner, trace

I/O Contract

Inputs

Name Type Required Description
tool_config.type str Yes Must be "code_interpreter"
tool_config.container.type str Yes Container provisioning mode; "auto" for platform-managed containers
input str Yes The user query describing the computation or problem to solve

Outputs

Name Type Description
result.final_output str The agent's final text response containing the computed answer
stream event (code_interpreter_call) str The Python code generated and executed by the code interpreter
stream event (run_item_stream_event) StreamEvent Individual streaming events including tool call items and message output items

Usage Examples

Streaming Code Interpreter for Math

import asyncio
from collections.abc import Mapping
from typing import Any
from agents import Agent, CodeInterpreterTool, Runner, trace

def _get_field(obj: Any, key: str) -> Any:
    if isinstance(obj, Mapping):
        return obj.get(key)
    return getattr(obj, key, None)

async def main():
    agent = Agent(
        name="Code interpreter",
        model="gpt-5.2",
        instructions="You love doing math.",
        tools=[
            CodeInterpreterTool(
                tool_config={"type": "code_interpreter", "container": {"type": "auto"}},
            )
        ],
    )

    with trace("Code interpreter example"):
        result = Runner.run_streamed(agent, "What is the square root of 273 * 312821 plus 1782?")
        async for event in result.stream_events():
            if event.type != "run_item_stream_event":
                continue
            item = event.item
            if item.type == "tool_call_item":
                raw_call = item.raw_item
                if _get_field(raw_call, "type") == "code_interpreter_call":
                    code = _get_field(raw_call, "code")
                    if isinstance(code, str):
                        print(f"Code interpreter code:\n{code}\n")
                        continue
            print(f"Other event: {event.item.type}")
        print(f"Final output: {result.final_output}")

asyncio.run(main())

Related Pages

Page Connections

Double-click a node to navigate. Hold to expand connections.
Principle
Implementation
Heuristic
Environment