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

# エージェント実行（ストリーミング）

> SSE ストリーミングでエージェントを実行し、リアルタイムに応答を受け取る API

# エージェント実行（ストリーミング）

Server-Sent Events (SSE) を使ってエージェントを実行し、応答をリアルタイムにストリーミングで受け取ります。エージェントがテキストを生成するたびに `delta` イベントが送信されます。

<Note>
  長時間の調査タスクや、リアルタイムで応答を表示したい UI アプリケーションに最適です。完了まで待つだけなら [エージェント実行（非ストリーミング）](/ja/api-reference/execute-agent) も使えます。
</Note>

## 新規実行

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

### ヘッダー

| ヘッダー            | 必須 | 説明                             |
| --------------- | -- | ------------------------------ |
| `Authorization` | はい | `Bearer snorbe_...` 形式の API キー |
| `Content-Type`  | はい | `application/json`             |
| `Accept`        | はい | `text/event-stream`            |

### リクエストボディ

```json theme={null}
{
  "modelName": "gpt-5-mini-2025-08-07",
  "inputText": "AIエージェントの最新論文を調べて",
  "promptKey": "chat-routing",
  "locale": "ja",
  "fileUrls": [],
  "mentions": [],
  "maxBrowsingSteps": 5,
  "extendedContextEnabled": false
}
```

### パラメータ

| パラメータ                    | 型           | 必須  | 説明                                                                                                                                                                                       |
| ------------------------ | ----------- | --- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `modelName`              | `string`    | はい  | 使用するモデル名                                                                                                                                                                                 |
| `inputText`              | `string`    | はい  | エージェントへの入力テキスト                                                                                                                                                                           |
| `promptKey`              | `string`    | はい  | プロンプトキー（通常は `"chat-routing"`）                                                                                                                                                            |
| `locale`                 | `string`    | はい  | `"ja"` または `"en"`                                                                                                                                                                        |
| `fileUrls`               | `string[]`  | いいえ | 添付ファイル URL（最大10件）。デフォルト: `[]`                                                                                                                                                            |
| `agentId`                | `string`    | いいえ | エージェント ID。省略時はデフォルトエージェント                                                                                                                                                                |
| `mentions`               | `Mention[]` | いいえ | @メンション（エンティティ・AgentRun・ソース・**他 Agent** の参照）。デフォルト: `[]`。`type: "agent"` を含めると呼び出し先が `mentionAgent` で他 Agent に委譲できる（詳細は [/agent/run](/ja/api-reference/execute-agent#agent-間メンション委譲) を参照） |
| `maxBrowsingSteps`       | `number`    | いいえ | ブラウジングの最大ステップ数（1-100）                                                                                                                                                                    |
| `maxChainSteps`          | `number`    | いいえ | Agent 間メンション連鎖の最大深さ（1-50、デフォルト 10）                                                                                                                                                       |
| `maxRetries`             | `number`    | いいえ | リトライ回数（0-5）                                                                                                                                                                              |
| `retryDelayMs`           | `number`    | いいえ | リトライ間隔（ms、0-10000）                                                                                                                                                                       |
| `includeOthersEntities`  | `boolean`   | いいえ | 他ユーザーのエンティティも RAG 検索対象にする。デフォルト: `true`                                                                                                                                                  |
| `extendedContextEnabled` | `boolean`   | いいえ | 拡張コンテキスト（モデル最大トークンの 80% を使用）。デフォルト: `false`                                                                                                                                              |
| `matrixEditContext`      | `object`    | いいえ | マトリクス編集コンテキスト（`sourceRunId` + `selection`）                                                                                                                                               |
| `matrixContinueContext`  | `object`    | いいえ | マトリクス継続コンテキスト（`sourceRunId`）                                                                                                                                                             |
| `matrixSelectionContent` | `string`    | いいえ | マトリクス選択 XML（`<matrix_selection>` 形式）                                                                                                                                                     |

### Mention オブジェクト

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

| フィールド   | 型        | 説明                                                                  |
| ------- | -------- | ------------------------------------------------------------------- |
| `id`    | `string` | 参照先の ID（エンティティ・AgentRun・ソース）                                        |
| `type`  | `string` | `"entity"` / `"agent-run"` / `"public-source"` / `"private-source"` |
| `label` | `string` | 表示名                                                                 |

## レジューム（既存実行の再開）

HITL（Human-in-the-Loop）によるプラン確認やレポート確認の後に、実行を再開する場合に使用します。

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

### リクエストボディ

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

### パラメータ

| パラメータ                    | 型         | 必須  | 説明                             |
| ------------------------ | --------- | --- | ------------------------------ |
| `modelName`              | `string`  | はい  | 使用するモデル名                       |
| `extendedContextEnabled` | `boolean` | いいえ | 拡張コンテキストを有効にするか。デフォルト: `false` |

## SSE イベント形式

各イベントは `data: {JSON}\n\n` 形式で送信されます。

### config イベント

ストリーム開始時に1回送信されます。

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

### delta イベント

エージェントがテキストを生成するたびに送信されます。

```
data: {"type":"delta","payload":{"runId":"clxyz...","deltaText":"生成されたテキスト","responseText":"これまでの全テキスト","stepIndex":0,"modelId":"gpt-5-mini-2025-08-07","provider":"openai"}}
```

### step イベント

各実行ステップの完了時に送信されます。

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

### browse イベント

browse ツールが選ばれた場合は、ブラウザ操作の進行状況が送信されます。

```
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":"クリック","screenshot":"..."}}
data: {"type":"browse-ask-human","payload":{"runId":"clxyz...","status":"pending","question":"どのメニューを開きますか？"}}
data: {"type":"browse-final","payload":{"runId":"clxyz...","result":"取得した情報..."}}
data: {"type":"browse-end","payload":{"runId":"clxyz..."}}
```

`browse-ask-human` を受け取ったら、`browse-start.payload.websocketInfo.session_id` を `sessionId` として `/browser/answer-question` に回答します。plan/report/matrix と違い、回答後に `/agent/run/stream/{runId}` を呼ぶ必要はありません。

### complete イベント

エージェント実行が完了した時に送信されます。ストリームの最後のイベントです。

```
data: {"type":"complete","payload":{"runId":"clxyz...","text":"最終応答テキスト","finishReason":"stop","status":"completed","model":{"id":"gpt-5-mini-2025-08-07","provider":"openai"}}}
```

### error イベント

エラーが発生した時に送信されます。

```
data: {"type":"error","payload":{"message":"エラーメッセージ"}}
```

### 追加の内部イベント

SSE ストリームはエージェントの**内部処理をすべて** 逐次配信します。上記の基本イベント
（`config` / `delta` / `step` / `browse-*` / `complete` / `error`）に加えて、以下も流れます:

| カテゴリ         | イベント種別                                                                                                                                                                |
| ------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| プラン（HITL）    | `plan`・`plan-draft-delta`・`plan-draft-complete`・`plan-confirmed`・`plan-rejected`                                                                                      |
| レポート構造（HITL） | `report-structure-draft-delta`・`report-structure-draft-complete`・`report_structure_confirmed`・`report_structure_rejected`                                             |
| マトリクス（HITL）  | `matrix-structure-draft-delta`・`matrix-structure-draft-complete`・`matrix-data-preview`・`matrix-data-updated`・`matrix_structure_confirmed`・`matrix_structure_rejected` |
| ソース要約        | `source-summary-start`・`source-summary-delta`・`source-summary-item`・`source-summary-complete`                                                                         |
| グラフ抽出        | `graph-start`・`graph`・`graph-extraction-entity-delta`                                                                                                                 |

<Note>
  **ストリームが切断された場合の回収**: SSE で途中まで受信したイベント列は
  `agentRun.process` として DB に永続化されます。後から
  [`GET /turn/list`](/ja/api-reference/list-turns) を叩くと、`turns[].agentRun.process`
  から同じイベント列を取得できます。参照したソースは
  `turns[].agentRun.publicSourceAgentRuns` / `privateSourceAgentRuns` に入っています。
</Note>

## 使用例

<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": "AIエージェントの最新論文を調べて",
      "promptKey": "chat-routing",
      "locale": "ja"
    }'
  ```

  ```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": "AIエージェントの最新論文を調べて",
          "promptKey": "chat-routing",
          "locale": "ja",
      },
      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: "AIエージェントの最新論文を調べて",
      promptKey: "chat-routing",
      locale: "ja",
    }),
  });

  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>

## レジュームの使用例

```bash theme={null}
# HITL 確認後に実行を再開
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"}'
```

## エラーレスポンス

ストリーム開始前にエラーが発生した場合は、SSE ではなく通常の JSON レスポンスが返ります。

| HTTP ステータス | 説明                                    |
| ---------- | ------------------------------------- |
| 401        | API キーが無効                             |
| 400        | バリデーションエラー                            |
| 404        | 指定された `runId` のエージェント実行が存在しない（レジューム時） |
