Python

Python#

The assistant can execute Python code blocks.

It uses IPython to do so, and persists the IPython instance between calls to give a REPL-like experience.

Configuration:
GPTME_IPYTHON_TIMEOUT: Seconds a code block may run before it is

interrupted (default 600, 0 disables). Processes the block started are killed too, and time.sleep is interruptible while a block runs; other blocking calls (e.g. a socket read) only stop once they return.

GPTME_IPYTHON_BACKEND controls which execution backend is used for Python cells (default auto):

  • auto: use the kernel backend when a project environment is detected (a .venv directory, an active VIRTUAL_ENV, or a uv.lock / [tool.uv] project marker) and the kernel extra is installed. Falls back to in-process when no environment or kernel dependencies are found.

  • kernel: always use the kernel backend.

  • inprocess: always use the in-process backend.

The kernel backend runs cells in a separate Jupyter kernel process, enabling reliable SIGINT interrupts and project-environment isolation (%pip install goes to the project venv, not gptme’s).

Instructions

Use this tool to execute Python code in an interactive IPython session.
It responds with the execution output and final result.

### When to use the python tool

Use `python` for computation, structured data, and file-processing automation.
Prefer it over the shell for pure computation or when you need persistent
state or Python libraries.

Examples

Result of the last expression will be returned

User
What is 2 + 2?
Assistant
ipython
2 + 2
System
Executed code block.
`result
4
`

Write a function and call it

User
compute fib 10
Assistant
To compute the 10th Fibonacci number, we can run the following code:
ipython
def fib(n):
    if n <= 1:
        return n
    return fib(n - 1) + fib(n - 2)
fib(10)
System
Executed code block.
`result
55
`
exception gptme.tools.python.CellTimeout

Raised in a cell’s thread when it exceeds GPTME_IPYTHON_TIMEOUT.

class gptme.tools.python.TeeIO
__init__(original_stream)
get_captured() → str

Return buffered output, appending a truncation marker if writes were dropped.

write(s)

Write string to file.

Returns the number of characters written, which is always equal to the length of the string.

gptme.tools.python.execute_python(code: str | None, args: list[str] | None, kwargs: dict[str, str] | None) → Generator[Message, None, None]

Executes a python codeblock and returns the output.

gptme.tools.python.get_installed_python_libraries() → list[str]

Check if a select list of Python libraries are installed.

gptme.tools.python.register_function(func: T, *, tool_name: str | None = None) → T

Register a function for IPython and optionally record its owning tool.