> ## 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.

# Stream Code Output

> Receive stdout, stderr and results incrementally while code is still running

`POST /v1/agents/runtime/{runtime_id}/code/run?stream=true`

Runs code and delivers its output as it is produced instead of only when execution
finishes. Output is streamed as Server-Sent Events.

This is not a replay of buffered output at the end: the guest interpreter's `stdout` and
`stderr` are line-buffered and forwarded live through the execution plane, so a loop that
prints once a second produces one event a second. Long running jobs stay observable, and
an agent can act on partial output without waiting for the process to exit.

<CodeGroup>
  ```python Python theme={"theme":{"light":"github-light","dark":"github-dark"}}
  from gravixlayer import GravixLayer

  client = GravixLayer()  # defaults to cloud="aws", region="us-east-1"
  sandbox = client.runtime.create()  # defaults to template="base-small"

  code = """
  import time
  for i in range(5):
      print(f"step {i}", flush=True)
      time.sleep(1)
  42
  """

  # Passing any on_* callback switches run_code into streaming mode.
  result = sandbox.run_code(
      code,
      on_stdout=lambda chunk: print(chunk, end=""),
      on_stderr=lambda chunk: print(chunk, end=""),
      on_result=lambda res: print("result:", res.text),
      on_error=lambda err: print("error:", err.name, err.value),
  )

  print(result.success)
  sandbox.kill()
  ```

  ```typescript TypeScript theme={"theme":{"light":"github-light","dark":"github-dark"}}
  import { GravixLayer } from 'gravixlayer';

  const client = new GravixLayer(); // defaults to cloud="aws", region="us-east-1"
  const sandbox = await client.runtime.create(); // defaults to template="base-small"

  const code = `
  import time
  for i in range(5):
      print(f"step {i}", flush=True)
      time.sleep(1)
  42
  `;

  // Any on* callback switches runCode into streaming mode.
  const result = await sandbox.runCode(code, {
    onStdout: (chunk) => process.stdout.write(chunk),
    onStderr: (chunk) => process.stderr.write(chunk),
    onResult: (res) => console.log('result:', res.text),
    onError: (err) => console.log('error:', err.name, err.value),
  });

  console.log(result.success);
  await sandbox.kill();
  ```

  ```bash CLI theme={"theme":{"light":"github-light","dark":"github-dark"}}
  gravixlayer runtime run "$RT" --file script.py --stream
  ```

  ```bash cURL theme={"theme":{"light":"github-light","dark":"github-dark"}}
  curl -N -X POST "https://api.gravixlayer.ai/v1/agents/runtime/$RT/code/run?stream=true" \
    -H "Authorization: Bearer $GRAVIXLAYER_API_KEY" \
    -H "Content-Type: application/json" \
    -d '{"code": "for i in range(5):\n    print(i, flush=True)", "language": "python"}'
  ```
</CodeGroup>

## Parameters

The request body is identical to [Run Code](/documentation/agentruntime/code-execution/run-python).
Streaming is selected with the `stream=true` query parameter.

| Parameter     | Type    | Required | Description                                                         |
| ------------- | ------- | -------- | ------------------------------------------------------------------- |
| `code`        | string  | Yes      | Code to execute                                                     |
| `language`    | string  | No       | `python` (default), `javascript`, and the other supported languages |
| `context_id`  | string  | No       | Execution context to run in, for state that persists across calls   |
| `environment` | object  | No       | Extra environment variables                                         |
| `timeout`     | integer | No       | Maximum execution time in seconds                                   |

## Events

Each SSE frame carries one JSON object with a `type` field.

| `type`   | Payload                               | Meaning                                                   |
| -------- | ------------------------------------- | --------------------------------------------------------- |
| `start`  | `context_id`                          | Execution has been accepted and the kernel is running     |
| `stdout` | `text`                                | An incremental chunk of standard output                   |
| `stderr` | `text`                                | An incremental chunk of standard error                    |
| `result` | `result`                              | A rich result object (see below)                          |
| `error`  | `error`                               | Execution raised; carries `name`, `value` and `traceback` |
| `end`    | `status`, `duration_ms`, `context_id` | Execution finished                                        |

<Note>
  Streamed code output uses the field name `text`, while streamed **command** output uses
  `data`. They are separate endpoints with separate wire contracts.
</Note>

A `result` payload carries whichever representations the kernel produced:

| Field                | Type   | Description               |
| -------------------- | ------ | ------------------------- |
| `text`               | string | Plain text representation |
| `html`               | string | HTML representation       |
| `json`               | object | JSON representation       |
| `png`, `jpeg`, `svg` | string | Base64 encoded image data |
| `markdown`           | string | Markdown representation   |
| `chart`              | object | Structured chart data     |

```
data: {"type":"start","context_id":"ctx-91ab"}

data: {"type":"stdout","text":"step 0\n"}

data: {"type":"stdout","text":"step 1\n"}

data: {"type":"result","result":{"text":"42"}}

data: {"type":"end","status":"completed","duration_ms":5031,"context_id":"ctx-91ab"}
```

## Errors

When the executed code raises, an `error` frame is emitted before `end`:

```
data: {"type":"error","error":{"name":"ZeroDivisionError","value":"division by zero","traceback":["Traceback (most recent call last):","  File \"<stdin>\", line 1, in <module>","ZeroDivisionError: division by zero"]}}
```

The SDK surfaces this through `on_error` and on the returned `CodeRunResponse`. The CLI
prints the traceback and exits non-zero.

## Choosing streaming

Streaming and buffered execution return the same result shape, so switching is safe. Prefer
streaming when:

* The code runs long enough that intermediate output is useful.
* You want to stop early based on partial output.
* You are relaying progress to a user or to another agent.

Prefer the buffered call when you only need the final value and want one round trip.
