Skip to main content
Lesson 9 of 18 · Mistral Agents: Building Autonomous AI

code_interpreter Tool: Run Python

Lesson 9 of 18 Updated November 2, 2026 Developer
On this page
  1. Run Code in the Mistral Cloud
  2. Create an Agent with Code Interpreter
  3. Trigger an Execution
  4. Response Structure
  5. What the Tool Changes in Practice
  6. Combine with Other Tools
  7. Sandbox Limitations
  8. Key Takeaways

Run Code in the Mistral Cloud

The code_interpreter tool lets your agent write and execute Python code inside a sandboxed container. It’s the ideal choice for calculations, data analysis, chart generation, and code validation. This isn’t just about convenience: an LLM that “calculates” in its head produces a plausible result, not a correct one. By offloading the operation to a real interpreter, you replace token prediction with verifiable execution, giving you code you can review.

Create an Agent with Code Interpreter

The instructions for this agent require it to show the code before executing it, giving you a control point over what actually runs.

from mistralai.client import Mistral
import os

client = Mistral(api_key=os.environ["MISTRAL_API_KEY"])

agent = client.beta.agents.create(
    model="mistral-medium-latest",
    name="Code Agent",
    instructions="""You are a Python programming assistant.
- Use the code interpreter to run code when necessary
- Always show the code before executing it
- Explain results clearly""",
    tools=[{"type": "code_interpreter"}],
    completion_args={"temperature": 0.3, "top_p": 0.95}
)

Trigger an Execution

A simple calculation request is enough to trigger the tool; no special instruction from you is needed.

response = client.beta.conversations.start(
    agent_id=agent.id,
    inputs="Calculate the first 20 Fibonacci numbers."
)

The agent then writes a Python script to calculate the sequence, runs it in the sandbox, and presents the results along with explanations. The twenty values you receive come from actual execution: they will be exact even beyond the point where a model usually starts making mistakes.

Response Structure

You can read this mechanism directly in the returned entries, and your code must distinguish between text and execution results.

for entry in response.outputs:
    if entry.type == "message.output":
        # First response: "I will calculate..." or final result
        print(f"Message: {entry.content}")

    elif entry.type == "tool.execution":
        # Executed code and result
        print(f"Code: {entry.info.code}")
        print(f"Output: {entry.info.code_output}")

The agent starts with a message.output announcing what it’s about to do. Next comes the tool.execution where the code runs: info.code contains the script, and info.code_output holds its output. A second message.output closes the sequence, in which the agent interprets and explains the results. These two fields, info.code and info.code_output, are your audit trail—keep them in your application logs, as they let you replay and challenge any figure produced by the agent.

What the Tool Changes in Practice

Data analysis is the most immediate use case. Provide a series of values and ask for statistics: the mean, median, and standard deviation are calculated, not estimated.

response = client.beta.conversations.start(
    agent_id=agent.id,
    inputs="""Here are the monthly sales (in K€): 
    Jan: 120, Feb: 135, Mar: 142, Apr: 128, May: 155, Jun: 168
    Calculate the mean, median, standard deviation, and trend."""
)

Chart generation naturally extends this capability, since the environment includes plotting libraries.

response = client.beta.conversations.start(
    agent_id=agent.id,
    inputs="Create a bar chart of cloud market shares in Europe: AWS 31%, Azure 25%, GCP 11%, OVH 8%, Others 25%"
)

The agent uses matplotlib to generate the chart. The result is an image file accessible in the response—so make sure your reading code handles this case, or you’ll end up displaying only the accompanying text comment.

Code validation is a third use case, less obvious but valuable. Submit a function and the test cases to cover: the agent doesn’t just reason about the code, it runs it. In the example below, the input "Madam" reveals a flaw that a simple code review would likely miss.

response = client.beta.conversations.start(
    agent_id=agent.id,
    inputs="""Check if this function is correct:
    
def is_palindrome(s):
    return s == s[::-1]

Test it with: "radar", "hello", "kayak", "Madam"
"""
)

Applied mathematics round out the list: solving systems of equations, linear algebra, optimization. Here again, the response relies on a solver, not intuition.

response = client.beta.conversations.start(
    agent_id=agent.id,
    inputs="Solve the system of equations: 2x + 3y = 12, 4x - y = 5"
)

Combine with Other Tools

An agent can have multiple tools enabled simultaneously, and this is often where the real value appears: search brings in fresh data that code transforms into analysis.

agent = client.beta.agents.create(
    model="mistral-large-latest",
    name="Complete Analyst",
    description="Search + Calculation",
    instructions="Search for recent data then analyze it with code.",
    tools=[
        {"type": "web_search"},
        {"type": "code_interpreter"}
    ]
)

response = client.beta.conversations.start(
    agent_id=agent.id,
    inputs="Find the current price of Bitcoin and calculate its percentage change over the last 30 days."
)

The agent automatically chooses which tool to use at each step. In this request, it chains the two: you can’t calculate a change without first getting the values, and you can’t get those values without web access.

Sandbox Limitations

This isolated environment imposes constraints you should know before designing your application. Libraries are limited: standard Python packages are available—numpy, pandas, matplotlib, among others—but not all third-party packages, which rules out your internal dependencies. The code has no network access, so data must reach it via context or another tool, never through an HTTP call written in the script. Execution time is bounded, so long-running processes get interrupted: break up large volumes rather than hoping for a single pass. Finally, there is no persistence between calls; a file created during one execution won’t be found in the next.

Key Takeaways

  • code_interpreter runs Python in a secure sandbox on the Mistral side
  • The response contains the executed code (info.code) and its output (info.code_output)
  • Ideal for calculations, data analysis, and chart generation
  • Can be combined with other tools (web_search, etc.)
  • The sandbox has limitations: no network access, limited libraries, no persistence