> ## Documentation Index
> Fetch the complete documentation index at: https://docs.gravixlayer.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# Run Python

> Execute Python code in agent runtimes

## Basic Execution

```python theme={null}
from gravixlayer import GravixLayer

client = GravixLayer()
runtime = client.runtime.create(template="python-3.14-base-small")

result = runtime.run_code(code="import math\nprint(math.sqrt(81))")
print(result.text)  # 9.0

runtime.kill()
```

## Error Handling

```python theme={null}
from gravixlayer import GravixLayer

client = GravixLayer()
runtime = client.runtime.create(template="python-3.14-base-small")

result = runtime.run_code(code="raise ValueError('example')")

if not result.success and result.error:
    print(result.error.name)       # ValueError
    print(result.error.value)      # example
    print(result.error.traceback)  # Full traceback

runtime.kill()
```

## With Code Context

Preserve variables across multiple `run_code` calls:

```python theme={null}
from gravixlayer import GravixLayer

client = GravixLayer()
runtime = client.runtime.create(template="python-3.14-base-small")

ctx = client.runtime.create_context(runtime.runtime_id)

client.runtime.run_code(runtime.runtime_id, code="x = 42", context_id=ctx.context_id)

result = client.runtime.run_code(runtime.runtime_id, code="print(x + 1)", context_id=ctx.context_id)
print(result.text)  # 43

runtime.kill()
```

## Parameters

| Parameter     | Type    | Required | Description                            |
| ------------- | ------- | -------- | -------------------------------------- |
| `code`        | string  | Yes      | Python source code to execute          |
| `language`    | string  | No       | `"python"` (default) or `"javascript"` |
| `context_id`  | string  | No       | Reuse a persistent code context        |
| `environment` | object  | No       | Per-execution environment variables    |
| `timeout`     | integer | No       | Execution timeout in seconds           |

## Response

| Field     | Type    | Description                                  |
| --------- | ------- | -------------------------------------------- |
| `text`    | string  | Combined stdout output                       |
| `success` | boolean | `True` if no execution error                 |
| `error`   | object  | Error details (`name`, `value`, `traceback`) |
| `results` | list    | Structured execution results                 |
| `logs`    | object  | `stdout` and `stderr` as lists of strings    |
