> 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
Content-Type: application/json

会話に入力を送信し、エージェントが完了するか、クライアントツールの結果待ちになるまで待機します。`background`をtrueに設定すると、サーバーがターンを受け付けた時点でエンドポイントは202を返します。その後、`Last-Event-ID`を`stream_cursor`に設定してターンのイベントをストリーミングします。このエンドポイントはアルファ版であり、変更される可能性があります。

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

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

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

## Response

### 200

成功レスポンス。

- `turn_id` (string, required)
- `status` (enum, required)
  - Allowed values: `in_progress`, `completed`, `requires_action`, `failed`, `timed_out`
- `output` (list of TextOutputItem, optional)
- `error` (AgentOutputError, optional)
- `required_actions` (list of ClientToolCallRequiredAction, optional) — エージェントが待機しているアクション。続行するには、各`client_tool_call`に対し、`input`内の`client_tool_result`項目で応答してください。
- `stream_cursor` (string, optional) — このターンのイベントストリームを再開するためのトークン。ターンの進行中に存在し、Last-Event-IDとして渡すとターンのイベントをストリーミングできます。

## Errors

### 422 Conversations Send Message Request Unprocessable Entity Error

検証エラー

- `detail` (list of ValidationError, optional)

## Types

### SendConversationMessageRequestInputItem

- `type`: `client_tool_result`
  - `is_error` (boolean, required)
  - `result` (string, required)
  - `tool_call_id` (string, required) — この結果に対応するツール呼び出しのID。
  - `error_type` (enum, optional) — 失敗理由の任意のカテゴリ。設定すると、`is_error`はtrueとして扱われます。`user_rejected`は特別扱いされ、ツールが呼び出されなかったものとしてマークされます。
    - Allowed values: `user_rejected`, `external_server`, `external_client`, `customer_auth`, `client_timeout`, `unknown`
- `type`: `contextual_update`
  - `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`
  - `content` (list of UserMessageInputItemContentItem, required) — メッセージのパート。テキストパートは最大1つ、ファイルパートは最大5つです。

### TextOutputItem

- `role` ("agent", required)
- `text` (string, required)
- `type` ("text", optional)
- `id` (string, optional)
- `created_at_unix_ms` (integer, optional)

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

### ValidationError

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

### UserMessageInputItemContentItem

- `type`: `file`
  - `source` (FileContentPartSource, required)
- `type`: `text`
  - `text` (string, required)

### ValidationErrorLocItem

- string
- integer

### FileContentPartSource

- `type`: `base64`
  - `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`
  - `file_id` (string, required) — この会話について `POST /v1/convai/conversations/{conversation_id}/files` が返したID。

## Examples

**Request**

```json
{
  "input": [
    {
      "type": "client_tool_result",
      "is_error": true,
      "result": "result",
      "tool_call_id": "tool_call_id"
    }
  ]
}
```

**Response**

```json
{
  "turn_id": "turn_id",
  "status": "in_progress",
  "output": [
    {
      "role": "agent",
      "text": "text",
      "type": "text",
      "id": "id",
      "created_at_unix_ms": 1
    }
  ],
  "error": {
    "type": "type",
    "code": "code",
    "message": "message"
  },
  "required_actions": [
    {
      "tool_call_id": "tool_call_id",
      "tool_name": "tool_name",
      "parameters": {
        "key": "value"
      },
      "type": "client_tool_call"
    }
  ],
  "stream_cursor": "stream_cursor"
}
```

**SDK Code**

```python
import requests

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

payload = { "input": [
        {
            "type": "client_tool_result",
            "is_error": True,
            "result": "result",
            "tool_call_id": "tool_call_id"
        }
    ] }
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';
const options = {
  method: 'POST',
  headers: {'Content-Type': 'application/json'},
  body: '{"input":[{"type":"client_tool_result","is_error":true,"result":"result","tool_call_id":"tool_call_id"}]}'
};

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"

	payload := strings.NewReader("{\n  \"input\": [\n    {\n      \"type\": \"client_tool_result\",\n      \"is_error\": true,\n      \"result\": \"result\",\n      \"tool_call_id\": \"tool_call_id\"\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")

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      \"type\": \"client_tool_result\",\n      \"is_error\": true,\n      \"result\": \"result\",\n      \"tool_call_id\": \"tool_call_id\"\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")
  .header("Content-Type", "application/json")
  .body("{\n  \"input\": [\n    {\n      \"type\": \"client_tool_result\",\n      \"is_error\": true,\n      \"result\": \"result\",\n      \"tool_call_id\": \"tool_call_id\"\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', [
  'body' => '{
  "input": [
    {
      "type": "client_tool_result",
      "is_error": true,
      "result": "result",
      "tool_call_id": "tool_call_id"
    }
  ]
}',
  '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");
var request = new RestRequest(Method.POST);
request.AddHeader("Content-Type", "application/json");
request.AddParameter("application/json", "{\n  \"input\": [\n    {\n      \"type\": \"client_tool_result\",\n      \"is_error\": true,\n      \"result\": \"result\",\n      \"tool_call_id\": \"tool_call_id\"\n    }\n  ]\n}", ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
```

```swift
import Foundation

let headers = ["Content-Type": "application/json"]
let parameters = ["input": [
    [
      "type": "client_tool_result",
      "is_error": true,
      "result": "result",
      "tool_call_id": "tool_call_id"
    ]
  ]] 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")! 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()
```