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

# Execute Agent (Streaming)

> Execute an agent with SSE streaming for real-time responses

# Execute Agent (Streaming)

Execute a research agent using Server-Sent Events (SSE) to receive responses in real time. As the agent generates text, `delta` events are streamed to the client.

<Note>
  Ideal for long-running research tasks and UI applications that display responses in real time. For simple fire-and-forget use cases, see [Execute Agent (Non-Streaming)](/en/api-reference/execute-agent).
</Note>

## New Execution

```
POST /api/v1/agent/run/stream
```

### Headers

| Header          | Required | Description                           |
| --------------- | -------- | ------------------------------------- |
| `Authorization` | Yes      | API key in `Bearer snorbe_...` format |
| `Content-Type`  | Yes      | `application/json`                    |
| `Accept`        | Yes      | `text/event-stream`                   |

### Request Body

```json theme={null}
{
  "modelName": "gpt-5-mini-2025-08-07",
  "inputText": "Research the latest AI agent papers",
  "promptKey": "chat-routing",
  "locale": "en",
  "fileUrls": [],
  "mentions": [],
  "maxBrowsingSteps": 5,
  "extendedContextEnabled": false
}
```

### Parameters

| Parameter                | Type        | Required | Description                                                                                                                                                                                                                                                         |
| ------------------------ | ----------- | -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `modelName`              | `string`    | Yes      | Model name                                                                                                                                                                                                                                                          |
| `inputText`              | `string`    | Yes      | Input text for the agent                                                                                                                                                                                                                                            |
| `promptKey`              | `string`    | Yes      | Prompt key (typically `"chat-routing"`)                                                                                                                                                                                                                             |
| `locale`                 | `string`    | Yes      | `"ja"` or `"en"`                                                                                                                                                                                                                                                    |
| `fileUrls`               | `string[]`  | No       | Attached file URLs (max 10). Default: `[]`                                                                                                                                                                                                                          |
| `agentId`                | `string`    | No       | Agent ID. Defaults to the default agent                                                                                                                                                                                                                             |
| `mentions`               | `Mention[]` | No       | @mention references (entities, agent runs, sources, **other Agents**). Default: `[]`. Including `type: "agent"` lets the target Agent delegate via `mentionAgent` mid-run (see [/agent/run](/en/api-reference/execute-agent#agent-to-agent-delegation) for details) |
| `maxBrowsingSteps`       | `number`    | No       | Max browsing steps (1-100)                                                                                                                                                                                                                                          |
| `maxChainSteps`          | `number`    | No       | Maximum depth of Agent-to-Agent mention chains (1-50, default 10)                                                                                                                                                                                                   |
| `maxRetries`             | `number`    | No       | Retry count (0-5)                                                                                                                                                                                                                                                   |
| `retryDelayMs`           | `number`    | No       | Retry delay in ms (0-10000)                                                                                                                                                                                                                                         |
| `includeOthersEntities`  | `boolean`   | No       | Include other users' entities in RAG search. Default: `true`                                                                                                                                                                                                        |
| `extendedContextEnabled` | `boolean`   | No       | Extended context (uses 80% of model max tokens). Default: `false`                                                                                                                                                                                                   |
| `matrixEditContext`      | `object`    | No       | Matrix edit context (`sourceRunId` + `selection`)                                                                                                                                                                                                                   |
| `matrixContinueContext`  | `object`    | No       | Matrix continue context (`sourceRunId`)                                                                                                                                                                                                                             |
| `matrixSelectionContent` | `string`    | No       | Matrix selection XML (`<matrix_selection>` format)                                                                                                                                                                                                                  |

### Mention Object

```json theme={null}
{
  "id": "entity_abc123",
  "type": "entity",
  "label": "GPT-5"
}
```

| Field   | Type     | Description                                                         |
| ------- | -------- | ------------------------------------------------------------------- |
| `id`    | `string` | ID of the referenced item (entity, agent run, or source)            |
| `type`  | `string` | `"entity"` / `"agent-run"` / `"public-source"` / `"private-source"` |
| `label` | `string` | Display name                                                        |

## Resume (Restart Existing Run)

Resume execution after a HITL (Human-in-the-Loop) pause, such as plan or report confirmation.

```
POST /api/v1/agent/run/stream/{runId}
```

### Request Body

```json theme={null}
{
  "modelName": "gpt-5-mini-2025-08-07",
  "extendedContextEnabled": false
}
```

### Parameters

| Parameter                | Type      | Required | Description                               |
| ------------------------ | --------- | -------- | ----------------------------------------- |
| `modelName`              | `string`  | Yes      | Model name                                |
| `extendedContextEnabled` | `boolean` | No       | Enable extended context. Default: `false` |

## SSE Event Format

Each event is sent as `data: {JSON}\n\n`.

### config event

Sent once at the start of the stream.

```
data: {"type":"config","payload":{"runId":"clxyz...","modelName":"gpt-5-mini-2025-08-07","locale":"en","inputText":"..."}}
```

### delta event

Sent each time the agent generates text.

```
data: {"type":"delta","payload":{"runId":"clxyz...","deltaText":"Generated text","responseText":"Full text so far","stepIndex":0,"modelId":"gpt-5-mini-2025-08-07","provider":"openai"}}
```

### step event

Sent when an execution step completes.

```
data: {"type":"step","payload":{"runId":"clxyz...","stepIndex":0,"status":"complete","finishReason":"stop","usage":{"inputTokens":1234,"outputTokens":567}}}
```

### browse events

When the browse tool is selected, browser automation progress is streamed as events.

```
data: {"type":"browse-start","payload":{"runId":"clxyz...","websocketInfo":{"session_id":"browser-session-id","user_id":"user-id","ws_url":"wss://...","token":"..."}}}
data: {"type":"browse-step","payload":{"runId":"clxyz...","stepIndex":1,"action":"click","screenshot":"..."}}
data: {"type":"browse-ask-human","payload":{"runId":"clxyz...","status":"pending","question":"Which menu should I open?"}}
data: {"type":"browse-final","payload":{"runId":"clxyz...","result":"Collected information..."}}
data: {"type":"browse-end","payload":{"runId":"clxyz..."}}
```

When you receive `browse-ask-human`, answer through `/browser/answer-question` using `browse-start.payload.websocketInfo.session_id` as `sessionId`. Unlike plan/report/matrix reviews, you do not call `/agent/run/stream/{runId}` after answering a browser question.

### complete event

Sent when the agent finishes. This is the final event in the stream.

```
data: {"type":"complete","payload":{"runId":"clxyz...","text":"Final response text","finishReason":"stop","status":"completed","model":{"id":"gpt-5-mini-2025-08-07","provider":"openai"}}}
```

### error event

Sent when an error occurs.

```
data: {"type":"error","payload":{"message":"Error message"}}
```

### Additional internal events

The SSE stream emits **every internal event** as the agent progresses. In addition to
the basic events above (`config` / `delta` / `step` / `browse-*` / `complete` / `error`),
the following are also streamed:

| Category                | Event types                                                                                                                                                                |
| ----------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Plan (HITL)             | `plan`, `plan-draft-delta`, `plan-draft-complete`, `plan-confirmed`, `plan-rejected`                                                                                       |
| Report structure (HITL) | `report-structure-draft-delta`, `report-structure-draft-complete`, `report_structure_confirmed`, `report_structure_rejected`                                               |
| Matrix (HITL)           | `matrix-structure-draft-delta`, `matrix-structure-draft-complete`, `matrix-data-preview`, `matrix-data-updated`, `matrix_structure_confirmed`, `matrix_structure_rejected` |
| Source summarization    | `source-summary-start`, `source-summary-delta`, `source-summary-item`, `source-summary-complete`                                                                           |
| Graph extraction        | `graph-start`, `graph`, `graph-extraction-entity-delta`                                                                                                                    |

<Note>
  **Recovering a dropped stream**: every event sent over SSE is also persisted as
  `agentRun.process` in the database. If your SSE connection drops, call
  [`GET /turn/list`](/en/api-reference/list-turns) — `turns[].agentRun.process`
  returns the same event timeline, and referenced sources are available in
  `turns[].agentRun.publicSourceAgentRuns` / `privateSourceAgentRuns`.
</Note>

## Examples

<CodeGroup>
  ```bash cURL theme={null}
  curl -N -X POST "https://app.snorbe.deskrex.ai/api/v1/agent/run/stream" \
    -H "Authorization: Bearer snorbe_your_api_key_here" \
    -H "Accept: text/event-stream" \
    -H "Content-Type: application/json" \
    -d '{
      "modelName": "gpt-5-mini-2025-08-07",
      "inputText": "Research the latest AI agent papers",
      "promptKey": "chat-routing",
      "locale": "en"
    }'
  ```

  ```python Python theme={null}
  import requests
  import json

  resp = requests.post(
      "https://app.snorbe.deskrex.ai/api/v1/agent/run/stream",
      headers={
          "Authorization": "Bearer snorbe_your_api_key_here",
          "Accept": "text/event-stream",
          "Content-Type": "application/json",
      },
      json={
          "modelName": "gpt-5-mini-2025-08-07",
          "inputText": "Research the latest AI agent papers",
          "promptKey": "chat-routing",
          "locale": "en",
      },
      stream=True,
      timeout=300,
  )

  for line in resp.iter_lines(decode_unicode=True):
      if line.startswith("data: "):
          event = json.loads(line[6:])
          event_type = event["type"]
          if event_type == "delta":
              print(event["payload"]["deltaText"], end="", flush=True)
          elif event_type == "complete":
              print(f"\n\nRun ID: {event['payload']['runId']}")
          elif event_type == "error":
              print(f"\nError: {event['payload']['message']}")
  ```

  ```typescript TypeScript theme={null}
  const resp = await fetch("https://app.snorbe.deskrex.ai/api/v1/agent/run/stream", {
    method: "POST",
    headers: {
      Authorization: "Bearer snorbe_your_api_key_here",
      Accept: "text/event-stream",
      "Content-Type": "application/json",
    },
    body: JSON.stringify({
      modelName: "gpt-5-mini-2025-08-07",
      inputText: "Research the latest AI agent papers",
      promptKey: "chat-routing",
      locale: "en",
    }),
  });

  const reader = resp.body!.getReader();
  const decoder = new TextDecoder();
  let buffer = "";

  while (true) {
    const { done, value } = await reader.read();
    if (done) break;
    buffer += decoder.decode(value, { stream: true });

    const lines = buffer.split("\n\n");
    buffer = lines.pop() ?? "";

    for (const line of lines) {
      if (line.startsWith("data: ")) {
        const event = JSON.parse(line.slice(6));
        if (event.type === "delta") {
          process.stdout.write(event.payload.deltaText);
        } else if (event.type === "complete") {
          console.log(`\nRun ID: ${event.payload.runId}`);
        } else if (event.type === "error") {
          console.error(`Error: ${event.payload.message}`);
        }
      }
    }
  }
  ```
</CodeGroup>

## Resume Example

```bash theme={null}
# Resume after HITL confirmation
curl -N -X POST "https://app.snorbe.deskrex.ai/api/v1/agent/run/stream/clxxx123" \
  -H "Authorization: Bearer snorbe_your_api_key_here" \
  -H "Accept: text/event-stream" \
  -H "Content-Type: application/json" \
  -d '{"modelName":"gpt-5-mini-2025-08-07"}'
```

## Error Responses

If an error occurs before the stream starts, a regular JSON response is returned instead of SSE.

| HTTP Status | Description                                             |
| ----------- | ------------------------------------------------------- |
| 401         | Invalid API key                                         |
| 400         | Validation error                                        |
| 404         | Agent run not found for the given `runId` (resume only) |
