> This is a page from the ElevenLabs documentation. For an index of the documentation, fetch https://elevenlabs.io/docs/llms.txt.

# 会話メッセージをストリーミング送信

POST https://api.elevenlabs.io/v1/convai/conversations/{conversation_id}/messages/stream
Content-Type: application/json

会話に入力を送信し、リクエストのイベントをServer-Sent Eventsとしてストリーミングします。最後のイベントは`stream_ended`で、ターンの結果が含まれます。このエンドポイントはアルファ版であり、変更される可能性があります。

Reference: https://elevenlabs.io/docs/api-reference/conversations/send-message-stream

## Servers

- `https://api.elevenlabs.io` (Production, default)
- `https://api.us.elevenlabs.io` (Production US)
- `https://api.eu.residency.elevenlabs.io` (Production EU)
- `https://api.in.residency.elevenlabs.io` (Production India)
- `https://api.sg.residency.elevenlabs.io` (Production Singapore)

## Request

### Path parameters

- `conversation_id` (string, required) — 会話ID

### Body (application/json)

This endpoint expects a SendConversationMessageStreamRequest.

- `input` (list of SendConversationMessageStreamRequestInputItems, required) — 新しいターンを開始する1件の`user_message`、または待機中のターンの`required_actions`に応答してターンを続行する`client_tool_result`項目のいずれかです。含まれていない呼び出しは保留のままになります。クライアントツールの待機にはタイムアウトがありません。呼び出しが保留中の場合、`user_message`は拒否されます。`user_message`には、`context_id`ごとに最大1件の`contextual_update`項目を含められます。保留中のすべての呼び出しに応答する`client_tool_result`項目には、`end`更新を含められます。

## Response

### 200

Server-Sent Events。各イベントには、ストリームカーソルが`id`、イベントタイプが`event`、ストリームエンベロープが`data`として含まれます。

- Streaming response of `StreamEnvelope`.
- `conversation_id` (string, required)
- `turn_id` (string, required)
- `created_at_unix_ms` (integer, required)
- `event` (StreamEnvelopeEvent, required)

## Errors

### 422 Unprocessable Entity Error

検証エラー

- `detail` (list of ValidationError, optional)

## Types

### SendConversationMessageStreamRequestInputItems

- `type`: `client_tool_result` (ClientToolResultItem)
  - `is_error` (boolean, required)
  - `result` (string, required)
  - `tool_call_id` (string, required) — この結果に対応するツール呼び出しのID。
  - `error_type` (enum, optional, nullable) — 失敗理由の任意のカテゴリ。設定すると、`is_error`はtrueとして扱われます。`user_rejected`は特別扱いされ、ツールが呼び出されなかったものとしてマークされます。
    - Allowed values: `user_rejected`, `external_server`, `external_client`, `customer_auth`, `client_timeout`, `unknown`
- `type`: `contextual_update` (ContextualUpdateInputItem)
  - `context_id` (string, required) — 更新内容の説明。エージェントに表示されるのは、各 `context_id` の最新の更新のみです。
  - `text` (string, required) — 顧客の現在の状態など、ユーザーが記述していないエージェント向けのコンテキスト。
  - `placement` (enum, optional, default: in_place) — `in_place`：更新はイベントのように送信された位置に残ります。`end`：更新は現在の状態として、最新のメッセージまたはツール結果の後に送信されます。
    - Allowed values: `in_place`, `end`
- `type`: `user_message` (UserMessageInputItem)
  - `content` (list of UserMessageInputItemContentItems, required) — メッセージのパート。テキストパートは最大1つ、ファイルパートは最大5つです。

### StreamEnvelopeEvent

- `type`: `agent_chat_response_part` (AgentChatResponsePartClientEvent)
  - `text_response_part` (AgentChatResponsePartClientEventData, required)
- `type`: `agent_reasoning_response_part` (AgentReasoningResponsePartClientEvent)
  - `reasoning_response_part` (AgentReasoningResponsePartClientEventData, required)
- `type`: `agent_response` (AgentResponseClientEvent)
  - `agent_response_event` (AgentResponseClientEventData, required)
- `type`: `agent_tool_request` (AgentToolRequestStreamedEvent)
  - `agent_tool_request` (AgentToolRequestClientEventData, required)
- `type`: `agent_tool_response` (AgentToolResponseStreamedEvent)
  - `agent_tool_response` (AgentToolResponseClientEventData, required)
- `type`: `client_tool_call` (ClientToolCallEvent)
  - `client_tool_call` (ClientToolCallClientEventData, required)
- `type`: `stream_ended` (StreamEndedEvent)
  - `stream_ended_event` (StreamEndedData, required)

### ValidationError

- `loc` (list of ValidationErrorLocItems, required)
- `msg` (string, required)
- `type` (string, required)

### UserMessageInputItemContentItems

- `type`: `file` (FileContentPart)
  - `source` (UserMessageInputItemContentItemsDiscriminatorMappingFileSource, required)
- `type`: `text` (TextContentPart)
  - `text` (string, required)

### AgentChatResponsePartClientEventData

- `text` (string, required)
- `type` (enum, required)
  - Allowed values: `start`, `delta`, `stop`
- `event_id` (integer, required)
- `response_id` (string, required)

### AgentReasoningResponsePartClientEventData

- `text` (string, required)
- `type` (enum, required)
  - Allowed values: `start`, `delta`, `stop`
- `event_id` (integer, required)

### AgentResponseClientEventData

- `agent_response` (string, required)
- `event_id` (integer, required)
- `response_id` (string, required)
- `in_response_to_ids` (list of string, optional)
- `response_type` (enum, optional, default: text)
  - Allowed values: `text`, `voice`
- `attachments` (list of AgentResponseAttachment, optional)

### AgentToolRequestClientEventData

- `tool_name` (string, required)
- `tool_call_id` (string, required)
- `tool_type` (string, required)
- `event_id` (integer, required)
- `expects_response` (boolean, required)
- `disable_interruptions` (boolean, required)
- `response_timeout_secs` (integer, required)
- `execution_mode` (string, required)

### AgentToolResponseClientEventData

- `tool_name` (string, required)
- `tool_call_id` (string, required)
- `tool_type` (string, required)
- `is_error` (boolean, required)
- `event_id` (integer, required)
- `is_called` (boolean, required)
- `status` (enum, required) — 実行フラグから算出されたツール呼び出しステータス。
  - Allowed values: `success`, `error`, `blocked`, `skipped`
- `is_blocked` (boolean, optional, default: false)

### ClientToolCallClientEventData

- `tool_name` (string, required)
- `tool_call_id` (string, required)
- `parameters` (map from string to any, required)
- `event_id` (integer, required)
- `expects_response` (boolean, required) — サーバーがClientToolResultレスポンスを待機するかどうか。

### StreamEndedData

- `status` (enum, required)
  - Allowed values: `in_progress`, `completed`, `requires_action`, `failed`, `timed_out`
- `error` (AgentOutputError, optional, nullable)
- `required_actions` (list of ClientToolCallRequiredAction, optional) — エージェントが待機しているアクション。続行するには、各`client_tool_call`に対し、`input`内の`client_tool_result`項目で応答してください。

### ValidationErrorLocItems

- string
- integer

### UserMessageInputItemContentItemsDiscriminatorMappingFileSource

- `type`: `base64` (Base64FileSource)
  - `data` (string, required) — base64でエンコードされたファイルの内容。
  - `filename` (string, required) — 拡張子を含むファイル名。
  - `media_type` (enum, required)
    - Allowed values: `image/png`, `image/jpeg`, `image/gif`, `image/webp`, `application/pdf`, `text/plain`
- `type`: `file_id` (FileIdSource)
  - `file_id` (string, required) — この会話について `POST /v1/convai/conversations/{conversation_id}/files` が返したID。

### AgentResponseAttachment

- `url` (string, required)
- `name` (string, required)
- `mime_type` (string, optional, nullable)

### AgentOutputError

- `type` (string, required)
- `code` (string, required)
- `message` (string, required)

### ClientToolCallRequiredAction

- `tool_call_id` (string, required)
- `tool_name` (string, required)
- `parameters` (map from string to any, required)
- `type` ("client_tool_call", optional, default: client_tool_call)

## Examples

**Request**

```json
{
  "input": [
    {
      "content": [
        {
          "text": "string",
          "type": "string"
        }
      ],
      "type": "string"
    }
  ]
}
```

**SDK Code**

```python
import requests

url = "https://api.elevenlabs.io/v1/convai/conversations/conversation_id/messages/stream"

payload = { "input": [
        {
            "content": [
                {
                    "text": "string",
                    "type": "string"
                }
            ],
            "type": "string"
        }
    ] }
headers = {"Content-Type": "application/json"}

response = requests.post(url, json=payload, headers=headers)

print(response.json())
```

```javascript
const url = 'https://api.elevenlabs.io/v1/convai/conversations/conversation_id/messages/stream';
const options = {
  method: 'POST',
  headers: {'Content-Type': 'application/json'},
  body: '{"input":[{"content":[{"text":"string","type":"string"}],"type":"string"}]}'
};

try {
  const response = await fetch(url, options);
  const data = await response.json();
  console.log(data);
} catch (error) {
  console.error(error);
}
```

```go
package main

import (
	"fmt"
	"strings"
	"net/http"
	"io"
)

func main() {

	url := "https://api.elevenlabs.io/v1/convai/conversations/conversation_id/messages/stream"

	payload := strings.NewReader("{\n  \"input\": [\n    {\n      \"content\": [\n        {\n          \"text\": \"string\",\n          \"type\": \"string\"\n        }\n      ],\n      \"type\": \"string\"\n    }\n  ]\n}")

	req, _ := http.NewRequest("POST", url, payload)

	req.Header.Add("Content-Type", "application/json")

	res, _ := http.DefaultClient.Do(req)

	defer res.Body.Close()
	body, _ := io.ReadAll(res.Body)

	fmt.Println(res)
	fmt.Println(string(body))

}
```

```ruby
require 'uri'
require 'net/http'

url = URI("https://api.elevenlabs.io/v1/convai/conversations/conversation_id/messages/stream")

http = Net::HTTP.new(url.host, url.port)
http.use_ssl = true

request = Net::HTTP::Post.new(url)
request["Content-Type"] = 'application/json'
request.body = "{\n  \"input\": [\n    {\n      \"content\": [\n        {\n          \"text\": \"string\",\n          \"type\": \"string\"\n        }\n      ],\n      \"type\": \"string\"\n    }\n  ]\n}"

response = http.request(request)
puts response.read_body
```

```java
import com.mashape.unirest.http.HttpResponse;
import com.mashape.unirest.http.Unirest;

HttpResponse<String> response = Unirest.post("https://api.elevenlabs.io/v1/convai/conversations/conversation_id/messages/stream")
  .header("Content-Type", "application/json")
  .body("{\n  \"input\": [\n    {\n      \"content\": [\n        {\n          \"text\": \"string\",\n          \"type\": \"string\"\n        }\n      ],\n      \"type\": \"string\"\n    }\n  ]\n}")
  .asString();
```

```php
<?php
require_once('vendor/autoload.php');

$client = new \GuzzleHttp\Client();

$response = $client->request('POST', 'https://api.elevenlabs.io/v1/convai/conversations/conversation_id/messages/stream', [
  'body' => '{
  "input": [
    {
      "content": [
        {
          "text": "string",
          "type": "string"
        }
      ],
      "type": "string"
    }
  ]
}',
  'headers' => [
    'Content-Type' => 'application/json',
  ],
]);

echo $response->getBody();
```

```csharp
using RestSharp;

var client = new RestClient("https://api.elevenlabs.io/v1/convai/conversations/conversation_id/messages/stream");
var request = new RestRequest(Method.POST);
request.AddHeader("Content-Type", "application/json");
request.AddParameter("application/json", "{\n  \"input\": [\n    {\n      \"content\": [\n        {\n          \"text\": \"string\",\n          \"type\": \"string\"\n        }\n      ],\n      \"type\": \"string\"\n    }\n  ]\n}", ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
```

```swift
import Foundation

let headers = ["Content-Type": "application/json"]
let parameters = ["input": [
    [
      "content": [
        [
          "text": "string",
          "type": "string"
        ]
      ],
      "type": "string"
    ]
  ]] as [String : Any]

let postData = JSONSerialization.data(withJSONObject: parameters, options: [])

let request = NSMutableURLRequest(url: NSURL(string: "https://api.elevenlabs.io/v1/convai/conversations/conversation_id/messages/stream")! as URL,
                                        cachePolicy: .useProtocolCachePolicy,
                                    timeoutInterval: 10.0)
request.httpMethod = "POST"
request.allHTTPHeaderFields = headers
request.httpBody = postData as Data

let session = URLSession.shared
let dataTask = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) -> Void in
  if (error != nil) {
    print(error as Any)
  } else {
    let httpResponse = response as? HTTPURLResponse
    print(httpResponse)
  }
})

dataTask.resume()
```