Agentriaで作成したエージェントをAPIとして公開すると、外部サービスからこのAPIエンドポイント(Endpoint)を呼び出してエージェントと対話できます。Agent APIは、チャットルームの作成・照会・削除、非同期チャット、SSE(Server-Sent Events)ストリーミングチャットに対応するREST APIです。
このガイドでは、各エンドポイントの呼び出し方と、対話の文脈を維持しながら実行結果を安全に取得する方法を案内します。
エージェントがAPIとして公開済みである必要があります。まだ公開していない場合は、先に🔗API公開ガイドを完了してください。
公開時に発行されたエンドポイントコード(api_endpoint)とAPIキー(Key)が必要です。
ベースURLと認証方式は、以下のすべてのエンドポイントに共通です。
ベースURL
すべてのリクエストにX-API-KEYヘッダーが必要です。
APIキーが正しくないか権限がない場合、403 Forbiddenが返されます。エンドポイントによって詳細なエラーコードが異なる場合があるため、各ステップのError Responses表もあわせて確認してください。
エージェントとの対話はチャットルーム(Chat Room)単位で管理されます。対話履歴を維持するには、先にチャットルームを作成し、以降のリクエストで同じチャットルームIDを使い続けます。
パラメータ | 型 | 説明 |
|---|
api_endpoint
| string | エージェントコード(公開済みエージェントの一意の識別子) |
ヘッダー | 型 | 必須 | 説明 |
|---|
X-API-KEY
| string | Yes | API アクセストークン |
フィールド | 型 | 必須 | 説明 |
|---|
user_ids
| list[int] | Yes | チャットルームに参加させるユーザーIDのリスト(最初のIDが作成者になる) |
成功すると、200 OKステータスとともに作成されたチャットルームのUUIDを応答として受け取ります。
"e36644fa-0b2e-11f0-b130-143627ec67e9"
"e36644fa-0b2e-11f0-b130-143627ec67e9"
"e36644fa-0b2e-11f0-b130-143627ec67e9"
Status | 説明 |
|---|
400 Bad Request
| user_idsがない、またはリストでない場合
|
403 Forbidden
| APIキーが無効、またはエージェントへのアクセス権限がない場合 |
curl -X POST "{host}/api/agent/my-agent/rooms" \
-H "X-API-KEY: your-api-key" \
-H "Content-Type: application/json" \
-d '{"user_ids": [1]}'curl -X POST "{host}/api/agent/my-agent/rooms" \
-H "X-API-KEY: your-api-key" \
-H "Content-Type: application/json" \
-d '{"user_ids": [1]}'curl -X POST "{host}/api/agent/my-agent/rooms" \
-H "X-API-KEY: your-api-key" \
-H "Content-Type: application/json" \
-d '{"user_ids": [1]}'該当エージェントAPIで作成されたチャットルームの一覧をページング(Paging)形式で照会します。
パラメータ | 型 | 必須 | デフォルト値 | 説明 |
|---|
page_index
| int | No | 0
| ページ番号(0から開始) |
page_size
| int | No | 10
| 1ページあたりの件数(最大100、超過時は100が適用される) |
order_by
| list[string] | No | created_time,desc
| 並び順(例:created_time,desc) |
成功すると、200 OKステータスとともに以下の形式で応答を受け取ります。
{
"data": [
{
"id": "e36644fa-0b2e-11f0-b130-143627ec67e9",
"creator_id": 1,
"properties_json": {},
"created_time": "2026-01-15T10:30:00",
"updated_time": "2026-01-15T10:30:00"
}
],
"page": {
"page_size": 10,
"page_number": 0,
"total_elements": 1,
"total_pages": 1
}
}{
"data": [
{
"id": "e36644fa-0b2e-11f0-b130-143627ec67e9",
"creator_id": 1,
"properties_json": {},
"created_time": "2026-01-15T10:30:00",
"updated_time": "2026-01-15T10:30:00"
}
],
"page": {
"page_size": 10,
"page_number": 0,
"total_elements": 1,
"total_pages": 1
}
}{
"data": [
{
"id": "e36644fa-0b2e-11f0-b130-143627ec67e9",
"creator_id": 1,
"properties_json": {},
"created_time": "2026-01-15T10:30:00",
"updated_time": "2026-01-15T10:30:00"
}
],
"page": {
"page_size": 10,
"page_number": 0,
"total_elements": 1,
"total_pages": 1
}
}Status | 説明 |
|---|
403 Forbidden
| APIキーが無効、またはエージェントへのアクセス権限がない場合 |
curl -X GET "{host}/api/agent/my-agent/rooms?page_index=0&page_size=10" \
-H "X-API-KEY: your-api-key"curl -X GET "{host}/api/agent/my-agent/rooms?page_index=0&page_size=10" \
-H "X-API-KEY: your-api-key"curl -X GET "{host}/api/agent/my-agent/rooms?page_index=0&page_size=10" \
-H "X-API-KEY: your-api-key"特定のチャットルームの詳細情報を照会します。
パラメータ | 型 | 説明 |
|---|
api_endpoint
| string | エージェントコード |
chat_room_id
| UUID | チャットルームID |
成功すると、200 OKステータスとともに以下の形式で応答を受け取ります。participants_jsonで、チャットルームに参加しているユーザーとエージェントの情報を確認できます。
{
"id": "e36644fa-0b2e-11f0-b130-143627ec67e9",
"participants_json": {
"users": {
"1": {
"id": 1,
"type": "USER",
"joined_time": "2026-01-15T10:30:00",
"name": null
}
},
"agents": {
"42": {
"id": 42,
"type": "AGENT",
"joined_time": "2026-01-15T10:30:00",
"name": "My Agent"
}
}
},
"creator_id": 1,
"properties_json": {},
"created_time": "2026-01-15T10:30:00",
"updated_time": "2026-01-15T10:30:00"
}{
"id": "e36644fa-0b2e-11f0-b130-143627ec67e9",
"participants_json": {
"users": {
"1": {
"id": 1,
"type": "USER",
"joined_time": "2026-01-15T10:30:00",
"name": null
}
},
"agents": {
"42": {
"id": 42,
"type": "AGENT",
"joined_time": "2026-01-15T10:30:00",
"name": "My Agent"
}
}
},
"creator_id": 1,
"properties_json": {},
"created_time": "2026-01-15T10:30:00",
"updated_time": "2026-01-15T10:30:00"
}{
"id": "e36644fa-0b2e-11f0-b130-143627ec67e9",
"participants_json": {
"users": {
"1": {
"id": 1,
"type": "USER",
"joined_time": "2026-01-15T10:30:00",
"name": null
}
},
"agents": {
"42": {
"id": 42,
"type": "AGENT",
"joined_time": "2026-01-15T10:30:00",
"name": "My Agent"
}
}
},
"creator_id": 1,
"properties_json": {},
"created_time": "2026-01-15T10:30:00",
"updated_time": "2026-01-15T10:30:00"
}Status | 説明 |
|---|
403 Forbidden
| APIキーが無効、またはチャットルームが存在しない場合 |
curl -X GET "{host}/api/agent/my-agent/rooms/e36644fa-0b2e-11f0-b130-143627ec67e9" \
-H "X-API-KEY: your-api-key"curl -X GET "{host}/api/agent/my-agent/rooms/e36644fa-0b2e-11f0-b130-143627ec67e9" \
-H "X-API-KEY: your-api-key"curl -X GET "{host}/api/agent/my-agent/rooms/e36644fa-0b2e-11f0-b130-143627ec67e9" \
-H "X-API-KEY: your-api-key"成功すると、200 OKステータスとともにtrue(成功)またはfalse(失敗)を応答として受け取ります。
Status | 説明 |
|---|
403 Forbidden
| APIキーが無効、またはエージェントへのアクセス権限がない場合 |
curl -X DELETE "{host}/api/agent/my-agent/rooms/e36644fa-0b2e-11f0-b130-143627ec67e9" \
-H "X-API-KEY: your-api-key"curl -X DELETE "{host}/api/agent/my-agent/rooms/e36644fa-0b2e-11f0-b130-143627ec67e9" \
-H "X-API-KEY: your-api-key"curl -X DELETE "{host}/api/agent/my-agent/rooms/e36644fa-0b2e-11f0-b130-143627ec67e9" \
-H "X-API-KEY: your-api-key"エージェントにメッセージを送信し、request_idを即座に応答として受け取ります。実行結果は、ステータス照会API(ステップ3)またはコールバック(Callback)URLで受け取れます。
パラメータ | 型 | 説明 |
|---|
api_endpoint
| string | エージェントコード |
ヘッダー | 型 | 必須 | 説明 |
|---|
X-API-KEY
| string | Yes | API アクセストークン |
フィールド | 型 | 必須 | 説明 |
|---|
params_json
| string (JSON) | Yes | リクエストパラメータ(下記の構造を参照) |
callback_url
| string | No | 結果をPOSTで受け取るコールバックURL |
debug
| boolean | No | デバッグモード(デフォルト:false) |
external_request_id
| string | No | クライアントが発行する外部リクエスト識別子(最大128文字、^[A-Za-z0-9_\-\.:]+$)。同一エージェント内で一意である必要があります。 |
files
| file[] | No | アップロードするファイルのリスト |
{
"input_message": "こんにちは",
"chat_room_id": "e36644fa-0b2e-11f0-b130-143627ec67e9",
"input_files": [
"<https: example.com="" image1.jpg="">",
"s3://bucket-name/image2.jpg"
]
}<
{
"input_message": "こんにちは",
"chat_room_id": "e36644fa-0b2e-11f0-b130-143627ec67e9",
"input_files": [
"<https: example.com="" image1.jpg="">",
"s3://bucket-name/image2.jpg"
]
}<
{
"input_message": "こんにちは",
"chat_room_id": "e36644fa-0b2e-11f0-b130-143627ec67e9",
"input_files": [
"<https: example.com="" image1.jpg="">",
"s3://bucket-name/image2.jpg"
]
}<
フィールド | 型 | 必須 | 説明 |
|---|
input_message
| string | No | テキストメッセージ |
chat_room_id
| string (UUID) | No | 既存のチャットルームID(指定しない場合は新規作成される) |
input_files
| list[string] | No | ファイルURLのリスト(HTTP URLまたはS3 URI) |
chat_room_idを指定しない場合、リクエストごとに新しいチャットルームが自動的に作成されることがあります。対話の文脈を継続するには、ステップ1で作成した(または前回の応答で受け取った)チャットルームIDを毎回同じ値で渡す必要があります。
external_request_idは、クライアントがリクエスト送信前に自ら発行する識別子で、2つの役割があります。1つ目は、同じexternal_request_idで再リクエストされた場合、サーバーが同一リクエストとみなして409 Conflictで拒否するため、ネットワーク再試行などによる重複実行(冪等性、Idempotency)を防げる点です。2つ目は、クライアントがリクエスト送信時点で既にこの識別子を保持しているため、サーバーがレスポンスでrequest_idを返す前から、この値でリクエストを追跡・照会できる点です。
成功すると、200 OKステータスとともにリクエストID(文字列)を応答として受け取ります。
"a1b2c3d4-e5f6-7890-abcd-ef1234567890"
"a1b2c3d4-e5f6-7890-abcd-ef1234567890"
"a1b2c3d4-e5f6-7890-abcd-ef1234567890"
Status | 説明 |
|---|
400 Bad Request
| external_request_idの形式が正しくない場合
|
401 Unauthorized
| 認証に失敗 |
404 Not Found
| エージェントが見つからない |
409 Conflict
| 同一のexternal_request_idが既に登録されている場合 |
500 Internal Server Error
| サーバー内部エラー |
curl -X POST "{host}/api/agent/my-agent/async" \
-H "X-API-KEY: your-api-key" \
-F 'params_json={"input_message": "こんにちは", "chat_room_id": "e36644fa-0b2e-11f0-b130-143627ec67e9"}' \
-F 'debug=false'
curl -X POST "{host}/api/agent/my-agent/async" \
-H "X-API-KEY: your-api-key" \
-F 'params_json={"input_message": "注文処理をお願いします", "chat_room_id": "e36644fa-0b2e-11f0-b130-143627ec67e9"}' \
-F 'callback_url=https://my-service.com/webhook' \
-F 'external_request_id=order-12345'
curl -X POST "{host}/api/agent/my-agent/async" \
-H "X-API-KEY: your-api-key" \
-F 'params_json={"input_message": "この画像を分析してください"}' \
-F 'callback_url=https://my-service.com/webhook' \
-F 'files=@/path/to/image.png'
curl -X POST "{host}/api/agent/my-agent/async" \
-H "X-API-KEY: your-api-key" \
-F 'params_json={"input_message": "こんにちは", "chat_room_id": "e36644fa-0b2e-11f0-b130-143627ec67e9"}' \
-F 'debug=false'
curl -X POST "{host}/api/agent/my-agent/async" \
-H "X-API-KEY: your-api-key" \
-F 'params_json={"input_message": "注文処理をお願いします", "chat_room_id": "e36644fa-0b2e-11f0-b130-143627ec67e9"}' \
-F 'callback_url=https://my-service.com/webhook' \
-F 'external_request_id=order-12345'
curl -X POST "{host}/api/agent/my-agent/async" \
-H "X-API-KEY: your-api-key" \
-F 'params_json={"input_message": "この画像を分析してください"}' \
-F 'callback_url=https://my-service.com/webhook' \
-F 'files=@/path/to/image.png'
curl -X POST "{host}/api/agent/my-agent/async" \
-H "X-API-KEY: your-api-key" \
-F 'params_json={"input_message": "こんにちは", "chat_room_id": "e36644fa-0b2e-11f0-b130-143627ec67e9"}' \
-F 'debug=false'
curl -X POST "{host}/api/agent/my-agent/async" \
-H "X-API-KEY: your-api-key" \
-F 'params_json={"input_message": "注文処理をお願いします", "chat_room_id": "e36644fa-0b2e-11f0-b130-143627ec67e9"}' \
-F 'callback_url=https://my-service.com/webhook' \
-F 'external_request_id=order-12345'
curl -X POST "{host}/api/agent/my-agent/async" \
-H "X-API-KEY: your-api-key" \
-F 'params_json={"input_message": "この画像を分析してください"}' \
-F 'callback_url=https://my-service.com/webhook' \
-F 'files=@/path/to/image.png'非同期チャットリクエストの処理ステータスと結果を照会します。
両方のエンドポイントは同じレスポンスを返します。
パラメータ | 型 | 説明 |
|---|
api_endpoint
| string | エージェントコード |
request_id
| string | 非同期リクエストID(/asyncの応答値) |
成功すると、200 OKステータスとともに以下の形式の結果を応答として受け取ります。
{
"request_id": "a1b2c3d4-e5f6-7890-abcd-ef1234567890",
"external_request_id": null,
"chat_room_id": "e36644fa-0b2e-11f0-b130-143627ec67e9",
"status": "COMPLETED",
"failure_reason": null,
"results": {
"output": "エージェントの応答内容"
},
"artifact_metadata_json": null,
"request_params_json": "{\"method\":\"POST\",\"client\":\"127.0.0.1\",\"params\":[{\"type\":\"text\",\"text\":\"こんにちは\"}]}",
"result_metadata_json": null,
"requested_time": "2026-01-15T10:30:00",
"updated_time": "2026-01-15T10:31:00"
}{
"request_id": "a1b2c3d4-e5f6-7890-abcd-ef1234567890",
"external_request_id": null,
"chat_room_id": "e36644fa-0b2e-11f0-b130-143627ec67e9",
"status": "COMPLETED",
"failure_reason": null,
"results": {
"output": "エージェントの応答内容"
},
"artifact_metadata_json": null,
"request_params_json": "{\"method\":\"POST\",\"client\":\"127.0.0.1\",\"params\":[{\"type\":\"text\",\"text\":\"こんにちは\"}]}",
"result_metadata_json": null,
"requested_time": "2026-01-15T10:30:00",
"updated_time": "2026-01-15T10:31:00"
}{
"request_id": "a1b2c3d4-e5f6-7890-abcd-ef1234567890",
"external_request_id": null,
"chat_room_id": "e36644fa-0b2e-11f0-b130-143627ec67e9",
"status": "COMPLETED",
"failure_reason": null,
"results": {
"output": "エージェントの応答内容"
},
"artifact_metadata_json": null,
"request_params_json": "{\"method\":\"POST\",\"client\":\"127.0.0.1\",\"params\":[{\"type\":\"text\",\"text\":\"こんにちは\"}]}",
"result_metadata_json": null,
"requested_time": "2026-01-15T10:30:00",
"updated_time": "2026-01-15T10:31:00"
}external_request_idは、リクエスト時に外部IDを付与した場合のみ値が入り、それ以外はnullです。
値 | 説明 |
|---|
NONE
| 初期状態(処理待ち) |
PROCESSING
| 処理中 |
COMPLETED
| 完了 |
FAILURE
| 失敗(failure_reasonフィールドに理由を含む) |
CANCELED
| キャンセル済み |
curl -X GET "{host}/api/agent/my-agent/a1b2c3d4-e5f6-7890-abcd-ef1234567890/status" \
-H "X-API-KEY: your-api-key"curl -X GET "{host}/api/agent/my-agent/a1b2c3d4-e5f6-7890-abcd-ef1234567890/status" \
-H "X-API-KEY: your-api-key"curl -X GET "{host}/api/agent/my-agent/a1b2c3d4-e5f6-7890-abcd-ef1234567890/status" \
-H "X-API-KEY: your-api-key"リクエスト時にexternal_request_idを付与していた場合、その値でも同じレスポンスを照会できます。
Status | 説明 |
|---|
400 Bad Request
| external_request_idの形式が正しくない
|
404 Not Found
| 該当の外部IDで登録されたリクエストがない |
curl -X GET "{host}/api/agent/my-agent/external/order-12345/status" \
-H "X-API-KEY: your-api-key"curl -X GET "{host}/api/agent/my-agent/external/order-12345/status" \
-H "X-API-KEY: your-api-key"curl -X GET "{host}/api/agent/my-agent/external/order-12345/status" \
-H "X-API-KEY: your-api-key"エージェントとリアルタイムのストリーミングチャットを行います。SSEを通じてエージェントの応答をリアルタイムで受信します。
ステップ1・ステップ2と同様に、api_endpointパスパラメータとX-API-KEYヘッダーが必要です。
フィールド | 型 | 必須 | 説明 |
|---|
params_json
| string (JSON) | Yes | リクエストパラメータ(ステップ2と同じ構造) |
debug
| boolean | No | デバッグモード(デフォルト:false) |
external_request_id
| string | No | クライアントが発行する外部リクエスト識別子。形式のルールはステップ2と同じです。SSE終了後は、この値でもステータス・結果を照会できます。 |
{
"input_message": "こんにちは",
"chat_room_id": "e36644fa-0b2e-11f0-b130-143627ec67e9",
"input_files": [
"<https: example.com="" image1.jpg="">"
]
}<
{
"input_message": "こんにちは",
"chat_room_id": "e36644fa-0b2e-11f0-b130-143627ec67e9",
"input_files": [
"<https: example.com="" image1.jpg="">"
]
}<
{
"input_message": "こんにちは",
"chat_room_id": "e36644fa-0b2e-11f0-b130-143627ec67e9",
"input_files": [
"<https: example.com="" image1.jpg="">"
]
}<
レスポンスのContent-Typeはtext/event-streamです。
レスポンスヘッダーX-Agent-Request-IdにリクエストIDが含まれます。最初のイベントを受信する前に接続が切れても、この値で再照会できます。これは最初のrequest_idイベントと同じ値です。
注意:X-Request-IdヘッダーはHTTPトレース用の別の値のため、X-Agent-Request-Idと混同しないよう注意してください。
各イベントは、標準のEventSource形式と互換性のない独自定義のSSE行形式で配信されます。空行でイベントが区切られます。
Agent APIのSSEでは、最初のrequest_idメタイベントを除くすべてのイベントが、{"ability_node_id", "ability_node_name", "results"}という形でもう一段階ラップされてシリアライズされます。これは、response/errrorイベントのbodyが結果スキーマそのまま届くAbility APIのSSEとは異なる部分なので、両方のAPIを併せて連携する場合は特に注意してください。
event_type | 発生タイミング | bodyの形 |
|---|
request_id
| ストリーム開始直後(最初、1回) | プレーンな文字列(UUID)。ラップされずそのまま届き、ストリーム消失時の結果再照会用リクエストIDとなる |
node
| 各ノードの実行終了時点(中間イベント、ノード数分繰り返し) | {"ability_node_id":, "ability_node_name":, "results":<ノード実行結果のdict>}
|
response
| エージェントが正常に完了(最終、1回) | {"ability_node_id":0, "ability_node_name":"final_output", "results":}
|
error
| エージェントの失敗または処理エラー(最終、1回) | {"ability_node_id":0, "ability_node_name":"final_output", "results":}
|
最終イベントでは、resultsフィールドの中にAPIResponseSchemaがまるごともう一段階入っている点が重要です(ステップ3のステータス照会レスポンスと同じ構造)。そのため、最終ステータスを判定する際はchunk.statusではなくchunk.results.statusを確認する必要があります。
event_type == "request_id" → メタイベント(ストリーム開始直後に1回、リクエストIDを伝える)
chunk.ability_node_id === 0 → 最終イベント
またはchunk.results.statusがCOMPLETED・FAILUREであれば最終イベント
それ以外(上記のいずれにも該当しない場合) → 中間のノードイベント
ネットワーク切断などで最終イベントを受け取れなかった場合、同じリクエストを再送信するとエージェントが再実行され、対話履歴が重複してしまうため、再照会を使う必要があります。サーバーはストリームの接続状態に関わらず実行を完了し、結果を記録します。
request_idイベント(またはX-Agent-Request-Idヘッダー)で受け取ったリクエストIDで、GET /{api_endpoint}/{request_id}/resultをポーリングします(ステップ3参照)。
external_request_idを付与していた場合は、GET /{api_endpoint}/external/{external_request_id}/resultでも照会できます(ステップ3参照)。
statusがCOMPLETED・FAILURE・CANCELEDになるまでポーリングします。同じexternal_request_idで再送信すると409 Conflictで拒否されるため、外部IDを併用することで誤った重複実行も防げます。
curl -N -X POST "{host}/api/agent/my-agent/sse" \
-H "X-API-KEY: your-api-key" \
-F 'params_json={"input_message":"こんにちは","chat_room_id":"e36644fa-0b2e-11f0-b130-143627ec67e9"}' \
-F 'debug=false'curl -N -X POST "{host}/api/agent/my-agent/sse" \
-H "X-API-KEY: your-api-key" \
-F 'params_json={"input_message":"こんにちは","chat_room_id":"e36644fa-0b2e-11f0-b130-143627ec67e9"}' \
-F 'debug=false'curl -N -X POST "{host}/api/agent/my-agent/sse" \
-H "X-API-KEY: your-api-key" \
-F 'params_json={"input_message":"こんにちは","chat_room_id":"e36644fa-0b2e-11f0-b130-143627ec67e9"}' \
-F 'debug=false'N(-no-buffer)オプションは必須です。付けない場合、チャンクがまとめて届いてしまいます。
const formData = new FormData();
formData.append('params_json', JSON.stringify({
input_message: 'こんにちは',
chat_room_id: 'e36644fa-0b2e-11f0-b130-143627ec67e9'
}));
formData.append('debug', 'false');
const response = await fetch(`${host}/api/agent/my-agent/sse`, {
method: 'POST',
headers: { 'X-API-KEY': 'your-api-key' },
body: formData
});
let requestId = response.headers.get('X-Agent-Request-Id');
const reader = response.body.getReader();
const decoder = new TextDecoder();
let buf = '';
let currentEvent = null;
const chunks = [];
let finalChunk = null;
while (true) {
const { done, value } = await reader.read();
if (done) break;
buf += decoder.decode(value, { stream: true });
let nl;
while ((nl = buf.indexOf('\n')) !== -1) {
const line = buf.slice(0, nl);
buf = buf.slice(nl + 1);
if (line === '') { currentEvent = null; continue; }
if (line.endsWith(':')) { currentEvent = line.slice(0, -1); continue; }
if (currentEvent === 'request_id') { requestId = line; continue; }
let body;
try { body = JSON.parse(line); } catch { continue; }
chunks.push(body);
const status = body.results?.status;
if (body.ability_node_id === 0 || status === 'COMPLETED' || status === 'FAILURE') {
finalChunk = body;
console.log('[final]', status, finalChunk.results.results);
} else {
console.log('[node]', body.ability_node_id, body.ability_node_name, body.results);
}
}
}
if (finalChunk?.results?.status === 'FAILURE') {
console.error('失敗:', finalChunk.results.failure_reason);
}
if (!finalChunk && requestId) {
const res = await fetch(`${host}/api/agent/my-agent/${requestId}/result`, {
headers: { 'X-API-KEY': 'your-api-key' }
});
const result = await res.json();
}const formData = new FormData();
formData.append('params_json', JSON.stringify({
input_message: 'こんにちは',
chat_room_id: 'e36644fa-0b2e-11f0-b130-143627ec67e9'
}));
formData.append('debug', 'false');
const response = await fetch(`${host}/api/agent/my-agent/sse`, {
method: 'POST',
headers: { 'X-API-KEY': 'your-api-key' },
body: formData
});
let requestId = response.headers.get('X-Agent-Request-Id');
const reader = response.body.getReader();
const decoder = new TextDecoder();
let buf = '';
let currentEvent = null;
const chunks = [];
let finalChunk = null;
while (true) {
const { done, value } = await reader.read();
if (done) break;
buf += decoder.decode(value, { stream: true });
let nl;
while ((nl = buf.indexOf('\n')) !== -1) {
const line = buf.slice(0, nl);
buf = buf.slice(nl + 1);
if (line === '') { currentEvent = null; continue; }
if (line.endsWith(':')) { currentEvent = line.slice(0, -1); continue; }
if (currentEvent === 'request_id') { requestId = line; continue; }
let body;
try { body = JSON.parse(line); } catch { continue; }
chunks.push(body);
const status = body.results?.status;
if (body.ability_node_id === 0 || status === 'COMPLETED' || status === 'FAILURE') {
finalChunk = body;
console.log('[final]', status, finalChunk.results.results);
} else {
console.log('[node]', body.ability_node_id, body.ability_node_name, body.results);
}
}
}
if (finalChunk?.results?.status === 'FAILURE') {
console.error('失敗:', finalChunk.results.failure_reason);
}
if (!finalChunk && requestId) {
const res = await fetch(`${host}/api/agent/my-agent/${requestId}/result`, {
headers: { 'X-API-KEY': 'your-api-key' }
});
const result = await res.json();
}const formData = new FormData();
formData.append('params_json', JSON.stringify({
input_message: 'こんにちは',
chat_room_id: 'e36644fa-0b2e-11f0-b130-143627ec67e9'
}));
formData.append('debug', 'false');
const response = await fetch(`${host}/api/agent/my-agent/sse`, {
method: 'POST',
headers: { 'X-API-KEY': 'your-api-key' },
body: formData
});
let requestId = response.headers.get('X-Agent-Request-Id');
const reader = response.body.getReader();
const decoder = new TextDecoder();
let buf = '';
let currentEvent = null;
const chunks = [];
let finalChunk = null;
while (true) {
const { done, value } = await reader.read();
if (done) break;
buf += decoder.decode(value, { stream: true });
let nl;
while ((nl = buf.indexOf('\n')) !== -1) {
const line = buf.slice(0, nl);
buf = buf.slice(nl + 1);
if (line === '') { currentEvent = null; continue; }
if (line.endsWith(':')) { currentEvent = line.slice(0, -1); continue; }
if (currentEvent === 'request_id') { requestId = line; continue; }
let body;
try { body = JSON.parse(line); } catch { continue; }
chunks.push(body);
const status = body.results?.status;
if (body.ability_node_id === 0 || status === 'COMPLETED' || status === 'FAILURE') {
finalChunk = body;
console.log('[final]', status, finalChunk.results.results);
} else {
console.log('[node]', body.ability_node_id, body.ability_node_name, body.results);
}
}
}
if (finalChunk?.results?.status === 'FAILURE') {
console.error('失敗:', finalChunk.results.failure_reason);
}
if (!finalChunk && requestId) {
const res = await fetch(`${host}/api/agent/my-agent/${requestId}/result`, {
headers: { 'X-API-KEY': 'your-api-key' }
});
const result = await res.json();
}参考(Pythonクライアント):httpx.AsyncClient.stream()のaiter_lines()とJSONパースで1行ずつ処理しますが、node: / response: / error:の接頭行はJSONパースエラーとしてスキップすれば構いません。request_idイベントのbody(プレーンなUUID)もJSONではないため同様にスキップされ、既存クライアントのchunks[-1].get("results", {}).get("status") == "FAILURE"のような判定パターンがそのまま動作します。再照会用のIDが必要な場合は、直前の行がrequest_id:かどうかを追跡するか、レスポンスヘッダーX-Agent-Request-Idを使用してください。
用途に応じて、以下の3つのフローのいずれかを選んで使用します。
フロー1:非同期方式(ポーリング)
フロー2:非同期方式(コールバック)
コールバックペイロードの例です。
{
"request_id": "a1b2c3d4-...",
"external_request_id": "order-12345",
"chat_room_id": "e36644fa-...",
"status": "COMPLETED",
"results": { ... },
"failure_reason": null
}
{
"request_id": "a1b2c3d4-...",
"chat_room_id": "e36644fa-...",
"status": "COMPLETED",
"results": { ... },
"failure_reason": null
}
{
"request_id": "a1b2c3d4-...",
"external_request_id": "order-12345",
"chat_room_id": "e36644fa-...",
"status": "COMPLETED",
"results": { ... },
"failure_reason": null
}
{
"request_id": "a1b2c3d4-...",
"chat_room_id": "e36644fa-...",
"status": "COMPLETED",
"results": { ... },
"failure_reason": null
}
{
"request_id": "a1b2c3d4-...",
"external_request_id": "order-12345",
"chat_room_id": "e36644fa-...",
"status": "COMPLETED",
"results": { ... },
"failure_reason": null
}
{
"request_id": "a1b2c3d4-...",
"chat_room_id": "e36644fa-...",
"status": "COMPLETED",
"results": { ... },
"failure_reason": null
}外部IDがないリクエストは、external_request_idキー自体をコールバックペイロードに含めません。既存の方式がそのまま維持されるため、以前の連携コードとも互換性があります。
フロー3:リアルタイムストリーミング方式
参考:chat_room_idを指定しない場合、チャットルームが自動的に作成されることがあります。対話履歴を維持するには、常に同じchat_room_idを使用する必要があります。
Agent APIエンドポイントの使い方を確認しました。
これで、外部サービスからエージェントと直接対話し、実行結果を取得できます。
🔗 API公開 ガイドで、エンドポイントとAPIキーの発行手順を再確認できます。
Agent APIは、外部サービスがAgentriaで作成したエージェントとREST API経由で対話できるようにする機能です。チャットルームの作成・照会・削除、非同期チャット、SSEストリーミングチャットに対応しており、すべてのリクエストはX-API-KEYヘッダーで認証されます。
外部のバックエンドサーバーや別のサービスから、AgentriaのUIを経由せずにエージェントと対話し、応答を受け取りたい場合に使用します。例えば、自社のチャット画面からエージェントを呼び出したい場合や、複数回のやり取りにわたって文脈を維持しながら自動応答を実装したい場合に適しています。
Ability APIが完成したワークフロー(アビリティ)を一度実行して結果を受け取る方式であるのに対し、Agent APIはチャットルーム単位で複数回やり取りしながら文脈を維持する方式です。SSEのレスポンス構造も異なり、Agent APIでは最初のrequest_idイベントを除くすべてのイベントが{ability_node_id, ability_node_name, results}という形でラップされており、最終ステータスはresults.statusを確認する必要があります。
同じchat_room_idを渡し続ける限り、対話の文脈は維持されます。リクエスト時にchat_room_idを指定しないと新しいチャットルームが自動的に作成されることがあるため、対話を継続するには、前回の応答で受け取ったchat_room_idを次回以降のリクエストにも同じ値で渡す必要があります。
サーバーはストリームの接続状態に関わらずエージェントの実行を継続して完了させ、結果を記録します。接続が切れて最終イベントを受け取れなかった場合は、同じリクエストを再送信せず、request_id(またはexternal_request_id)でステータス・結果照会APIをポーリングして結果を取得する必要があります。同じリクエストを再送信すると、エージェントが再実行され、対話履歴が重複することがあります。