チャットメッセージを送信
対象アプリ:Chatflow、Agent、チャットボット、レガシー Agent。
チャットアプリにメッセージを送信し、アシスタントの応答を返します。ストリーミングレスポンスのイベントはアプリタイプによって異なります。
1 min read
post/chat-messages
Request example
curl --request POST \
--url https://api.dify.ai/v1/chat-messages \
--header 'Authorization: Bearer <token>' \
--header 'Content-Type: application/json' \
--data '{
"conversation_id": "45701982-8118-4bc5-8e9b-64562b4555f2",
"inputs": {},
"query": "What are the specs of the iPhone 13 Pro Max?",
"response_mode": "blocking",
"user": "abc-123"
}'import requests
url = "https://api.dify.ai/v1/chat-messages"
headers = {
"Authorization": "Bearer <token>",
"Content-Type": "application/json",
}
payload = {
"conversation_id": "45701982-8118-4bc5-8e9b-64562b4555f2",
"inputs": {},
"query": "What are the specs of the iPhone 13 Pro Max?",
"response_mode": "blocking",
"user": "abc-123"
}
response = requests.request("POST", url, headers=headers, json=payload)
print(response.text)const response = await fetch('https://api.dify.ai/v1/chat-messages', {
method: 'POST',
headers: {
'Authorization': 'Bearer <token>',
'Content-Type': 'application/json'
},
body: JSON.stringify({
"conversation_id": "45701982-8118-4bc5-8e9b-64562b4555f2",
"inputs": {},
"query": "What are the specs of the iPhone 13 Pro Max?",
"response_mode": "blocking",
"user": "abc-123"
})
});
const data = await response.json();
console.log(data);<?php
$curl = curl_init();
curl_setopt_array($curl, [
CURLOPT_URL => 'https://api.dify.ai/v1/chat-messages',
CURLOPT_RETURNTRANSFER => true,
CURLOPT_CUSTOMREQUEST => 'POST',
CURLOPT_POSTFIELDS => '{
"conversation_id": "45701982-8118-4bc5-8e9b-64562b4555f2",
"inputs": {},
"query": "What are the specs of the iPhone 13 Pro Max?",
"response_mode": "blocking",
"user": "abc-123"
}',
CURLOPT_HTTPHEADER => [
'Authorization: Bearer <token>',
'Content-Type: application/json',
],
]);
$response = curl_exec($curl);
curl_close($curl);
echo $response;package main
import (
"fmt"
"io"
"net/http"
"strings"
)
func main() {
url := "https://api.dify.ai/v1/chat-messages"
payload := strings.NewReader("{\n \"conversation_id\": \"45701982-8118-4bc5-8e9b-64562b4555f2\",\n \"inputs\": {},\n \"query\": \"What are the specs of the iPhone 13 Pro Max?\",\n \"response_mode\": \"blocking\",\n \"user\": \"abc-123\"\n}")
req, _ := http.NewRequest("POST", url, payload)
req.Header.Add("Authorization", "Bearer <token>")
req.Header.Add("Content-Type", "application/json")
res, _ := http.DefaultClient.Do(req)
defer res.Body.Close()
body, _ := io.ReadAll(res.Body)
fmt.Println(string(body))
}HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create("https://api.dify.ai/v1/chat-messages"))
.header("Authorization", "Bearer <token>")
.header("Content-Type", "application/json")
.method("POST", HttpRequest.BodyPublishers.ofString("{\n \"conversation_id\": \"45701982-8118-4bc5-8e9b-64562b4555f2\",\n \"inputs\": {},\n \"query\": \"What are the specs of the iPhone 13 Pro Max?\",\n \"response_mode\": \"blocking\",\n \"user\": \"abc-123\"\n}"))
.build();
HttpResponse<String> response = HttpClient.newHttpClient()
.send(request, HttpResponse.BodyHandlers.ofString());
System.out.println(response.body());require 'uri'
require 'net/http'
url = URI('https://api.dify.ai/v1/chat-messages')
http = Net::HTTP.new(url.host, url.port)
http.use_ssl = url.scheme == 'https'
request = Net::HTTP::Post.new(url)
request['Authorization'] = 'Bearer <token>'
request['Content-Type'] = 'application/json'
request.body = '{
"conversation_id": "45701982-8118-4bc5-8e9b-64562b4555f2",
"inputs": {},
"query": "What are the specs of the iPhone 13 Pro Max?",
"response_mode": "blocking",
"user": "abc-123"
}'
response = http.request(request)
puts response.read_bodyResponse
{
"answer": "iPhone 13 Pro Max specs are listed here:...",
"conversation_id": "45701982-8118-4bc5-8e9b-64562b4555f2",
"created_at": 1705407629,
"event": "message",
"id": "b01a39de-3480-4f3e-9f1e-4841a80f8e5e",
"message_id": "9da23599-e713-473b-982c-4328d4f5c78a",
"metadata": {
"retriever_resources": [
{
"content": "\"Model\",\"Release Date\",\"Display Size\",\"Resolution\",\"Processor\",\"RAM\",\"Storage\",\"Camera\",\"Battery\",\"Operating System\" \"iPhone 13 Pro Max\",\"September 24, 2021\",\"6.7 inch\",\"1284 x 2778\",\"Hexa-core (2x3.23 GHz Avalanche + 4x1.82 GHz Blizzard)\",\"6 GB\",\"128, 256, 512 GB, 1TB\",\"12 MP\",\"4352 mAh\",\"iOS 15\"",
"dataset_id": "101b4c97-fc2e-463c-90b1-5261a4cdcafb",
"dataset_name": "iPhone",
"document_id": "8dd1ad74-0b5f-4175-b735-7d98bbbb4e00",
"document_name": "iPhone List",
"position": 1,
"score": 0.98457545,
"segment_id": "ed599c7f-2766-4294-9d1d-e5235a61270a"
}
],
"usage": {
"completion_price": "0.0002560",
"completion_price_unit": "0.001",
"completion_tokens": 128,
"completion_unit_price": "0.002",
"currency": "USD",
"latency": 0.7682376249867957,
"prompt_price": "0.0010330",
"prompt_price_unit": "0.001",
"prompt_tokens": 1033,
"prompt_unit_price": "0.001",
"total_price": "0.0012890",
"total_tokens": 1161
}
},
"mode": "chat",
"task_id": "c3800678-a077-43df-a102-53f23ed20b88"
}event: ping
data: {"event": "workflow_started", "task_id": "c3800678-a077-43df-a102-53f23ed20b88", "message_id": "2e4f6a8b-1c3d-5e7f-9a0b-2c4d6e8f0a1b", "conversation_id": "9d3a2f1b-6c7d-4e8f-a0b1-c2d3e4f5a6b7", "created_at": 1705407629, "workflow_run_id": "fb47b2e6-5e43-4f90-be01-d5c5a088d156", "data": {"id": "fb47b2e6-5e43-4f90-be01-d5c5a088d156", "workflow_id": "7c3e33d4-2a8b-4e5f-9b1a-d3c6e8f12345", "inputs": {"draft": "Hello"}, "created_at": 1705407629, "reason": "initial"}}
data: {"event": "human_input_required", "task_id": "c3800678-a077-43df-a102-53f23ed20b88", "message_id": "2e4f6a8b-1c3d-5e7f-9a0b-2c4d6e8f0a1b", "conversation_id": "9d3a2f1b-6c7d-4e8f-a0b1-c2d3e4f5a6b7", "created_at": 1705407629, "workflow_run_id": "fb47b2e6-5e43-4f90-be01-d5c5a088d156", "data": {"form_id": "a1b2c3d4-e5f6-7890-abcd-ef1234567890", "form_token": "tok_abc123", "node_id": "approval_node", "node_title": "Approval", "form_content": "ドラフトを確認してください。", "inputs": [{"type": "paragraph", "output_variable_name": "comment", "default": null}], "actions": [{"id": "approve", "title": "承認", "button_style": "primary"}], "display_in_ui": false, "resolved_default_values": {"comment": ""}, "expiration_time": 1705494029}}
data: {"event": "workflow_paused", "task_id": "c3800678-a077-43df-a102-53f23ed20b88", "message_id": "2e4f6a8b-1c3d-5e7f-9a0b-2c4d6e8f0a1b", "conversation_id": "9d3a2f1b-6c7d-4e8f-a0b1-c2d3e4f5a6b7", "created_at": 1705407629, "workflow_run_id": "fb47b2e6-5e43-4f90-be01-d5c5a088d156", "data": {"workflow_run_id": "fb47b2e6-5e43-4f90-be01-d5c5a088d156", "paused_nodes": ["approval_node"], "outputs": {}, "reasons": [{"TYPE": "human_input_required", "form_id": "a1b2c3d4-e5f6-7890-abcd-ef1234567890", "form_content": "ドラフトを確認してください。", "inputs": [{"type": "paragraph", "output_variable_name": "comment", "default": null}], "actions": [{"id": "approve", "title": "承認", "button_style": "primary"}], "node_id": "approval_node", "node_title": "Approval", "resolved_default_values": {"comment": ""}, "form_token": "tok_abc123", "expiration_time": 1705494029}], "status": "paused", "created_at": 1705407629, "elapsed_time": 0.5, "total_tokens": 0, "total_steps": 1}}data: {"event": "agent_thought", "id": "agent_thought_id_1", "task_id": "task123", "message_id": "msg123", "conversation_id": "conv123", "position": 1, "thought": "Thinking about calling a tool...", "tool": "dalle3", "tool_input": "{\"dalle3\": {\"prompt\": \"a cute cat\"}}", "created_at": 1705395332}
data: {"event": "message_file", "task_id": "task123", "message_id": "msg123", "conversation_id": "conv123", "id": "file_id_1", "type": "image", "belongs_to": "assistant", "url": "https://example.com/cat.png", "created_at": 1705395332}
data: {"event": "agent_message", "task_id": "task123", "message_id": "msg123", "conversation_id": "conv123", "answer": "Here is the image: ", "created_at": 1705395333}
data: {"event": "message_end", "task_id":"task123", "message_id": "msg123", "conversation_id": "conv123", "metadata": {"usage": {"total_tokens": 50, "latency": 2.5}}}data: {"event": "message", "task_id": "mock_task_id", "message_id": "5ad4cb98-f0c7-4085-b384-88c403be6290", "conversation_id": "45701982-8118-4bc5-8e9b-64562b4555f2", "answer": " I", "created_at": 1679586595}
data: {"event": "message_end", "task_id": "mock_task_id", "message_id": "5ad4cb98-f0c7-4085-b384-88c403be6290", "conversation_id": "45701982-8118-4bc5-8e9b-64562b4555f2", "created_at": 1679586595, "metadata": {"usage": {"total_tokens": 10, "latency": 1.0}}}event: ping
data: {"event": "workflow_started", "task_id": "task123", "workflow_run_id": "wfr_abc123", "message_id": "msg123", "conversation_id": "conv123", "created_at": 1705395332, "data": {"id": "wfr_abc123", "workflow_id": "wf_def456", "inputs": {"city": "San Francisco"}, "created_at": 1705395332}}
data: {"event": "node_started", "task_id": "task123", "workflow_run_id": "wfr_abc123", "message_id": "msg123", "conversation_id": "conv123", "created_at": 1705395332, "data": {"id": "ne_001", "node_id": "node_llm_1", "node_type": "llm", "title": "LLM", "index": 1, "created_at": 1705395332}}
data: {"event": "reasoning_chunk", "task_id": "task123", "message_id": "msg123", "conversation_id": "conv123", "created_at": 1705395333, "data": {"message_id": "msg123", "reasoning": "The user greeted me, so", "node_id": "node_llm_1", "is_final": false}}
data: {"event": "reasoning_chunk", "task_id": "task123", "message_id": "msg123", "conversation_id": "conv123", "created_at": 1705395333, "data": {"message_id": "msg123", "reasoning": "", "node_id": "node_llm_1", "is_final": true}}
data: {"event": "message", "task_id": "task123", "message_id": "msg123", "conversation_id": "conv123", "answer": " I", "created_at": 1705395333}
data: {"event": "node_finished", "task_id": "task123", "workflow_run_id": "wfr_abc123", "message_id": "msg123", "conversation_id": "conv123", "created_at": 1705395334, "data": {"id": "ne_001", "node_id": "node_llm_1", "node_type": "llm", "title": "LLM", "index": 1, "status": "succeeded", "elapsed_time": 1.5, "created_at": 1705395332, "finished_at": 1705395334}}
data: {"event": "message_end", "task_id": "task123", "message_id": "msg123", "conversation_id": "conv123", "created_at": 1705395334, "metadata": {"usage": {"total_tokens": 50, "latency": 2.5}}}
data: {"event": "workflow_finished", "task_id": "task123", "workflow_run_id": "wfr_abc123", "message_id": "msg123", "conversation_id": "conv123", "created_at": 1705395335, "data": {"id": "wfr_abc123", "workflow_id": "wf_def456", "status": "succeeded", "elapsed_time": 2.5, "total_tokens": 50, "total_steps": 2, "created_at": 1705395332, "finished_at": 1705395335}}{
"code": "app_unavailable",
"message": "App unavailable, please check your app configurations.",
"status": 400
}{
"code": "completion_request_error",
"message": "Completion request failed.",
"status": 400
}{
"code": "conversation_completed",
"message": "The conversation has ended. Please start a new conversation.",
"status": 400
}{
"code": "bad_request",
"message": "Cannot use draft workflow version. Workflow ID: a1b2c3d4-5678-90ab-cdef-1234567890ab. ",
"status": 400
}{
"code": "model_currently_not_support",
"message": "Dify Hosted OpenAI trial currently not support the GPT-4 model.",
"status": 400
}{
"code": "invalid_param",
"message": "Agent App has no bound Agent",
"status": 400
}{
"code": "agent_not_published",
"message": "Agent has not been published. Please publish the Agent before using the API.",
"status": 400
}{
"code": "bad_request",
"message": "Agent App only supports streaming response mode.",
"status": 400
}{
"code": "not_chat_app",
"message": "Please check if your app mode matches the right API route.",
"status": 400
}{
"code": "provider_not_initialize",
"message": "No valid model provider credentials found. Please go to Settings -> Model Provider to complete your provider credentials.",
"status": 400
}{
"code": "provider_quota_exceeded",
"message": "Your quota for Dify Hosted OpenAI has been exhausted. Please go to Settings -> Model Provider to complete your own provider credentials.",
"status": 400
}{
"code": "bad_request",
"message": "Invalid workflow_id format: 'not-a-valid-id'. ",
"status": 400
}{
"code": "workflow_version_execution_not_allowed",
"message": "Workflow version execution is not available on your current plan. Please upgrade to a paid plan.",
"status": 403
}{
"code": "not_found",
"message": "Conversation Not Exists.",
"status": 404
}{
"code": "not_found",
"message": "Workflow not found with id: a1b2c3d4-5678-90ab-cdef-1234567890ab",
"status": 404
}{
"code": "rate_limit_error",
"message": "Workflow execution quota limit reached for tenant 8f1e2a90-3b7c-4d55-9a01-6c2f4e8b1d33",
"status": 429
}{
"code": "too_many_requests",
"message": "Too many requests. Please try again later.",
"status": 429
}{
"code": "internal_server_error",
"message": "The server encountered an internal error and was unable to complete your request. Either the server is overloaded or there is an error in the application.",
"status": 500
}post/chat-messages
Authorization
すべてのリクエストは API キーで認証します:Authorization: Bearer {API_KEY}。アプリのエンドポイントにはアプリの API キーを、ナレッジのエンドポイントにはナレッジベースの API キーを使用します(Dify API クイックスタート)。
キーはサーバーサイドで保管し、クライアントコードには決して埋め込まないでください。キーが欠落または無効なリクエストは HTTP 401(unauthorized)で失敗します。
Body
application/jsonDefault: true
継続する会話の ID です。省略するか空文字列を渡すと新しい会話を開始します。レスポンスで
conversation_id が返されるので、次のメッセージで渡します。以前の会話を再開するには、その ID を 会話一覧を取得 から取得します。メッセージに添付するファイルです。ローカルファイルの場合は、まず ファイルをアップロード でアップロードし、返された
id を upload_file_id として transfer_method: local_file で参照します。Agent アプリはファイル参照を受け付けますが、その内容は処理しません。Show child attributesHide child attributes
転送方法です。ファイル URL の場合は
remote_url、アップロードファイルの場合は local_file です。Options:
remote_urllocal_fileファイル URL(
transfer_method が remote_url の場合は必須)です。アプリの入力変数の値を、変数名をキーとして指定します。期待される名前と型は、アプリケーションのパラメータ情報を取得 の
user_input_form フィールドで確認できます。ユーザーのメッセージです。
レスポンスの返却モードです。省略した場合はブロッキングになります。
streaming(推奨):応答は Server-Sent Events として届きます。blocking:生成の完了後に返します。長時間の生成は中断されるおそれがあります。Dify Cloud では、応答がタイムアウト内に届かないと、エッジプロキシが接続を終了する場合があります。- レガシー Agent と Agent アプリは
streamingのみに対応します。blockingのリクエストは 400 で失敗します。
Options:
streamingblockingエンドユーザーの識別子。アプリ側で定義し、アプリ内で一意にします。会話、メッセージ、ファイルは、同じ
user を持つリクエストにのみ表示されます。エンドユーザーの識別 を参照してください。Chatflow アプリでのみ使用できます。 実行する公開済みワークフローバージョンの ID を指定します。指定しない場合、最新の公開バージョンが使用されます。Dify Cloud では、バージョンの指定には有料プランが必要です。
Responses
リクエスト成功。コンテンツタイプと構造はリクエストの response_mode パラメータに依存します。
response_modeがblockingの場合、application/jsonでChatCompletionResponseオブジェクトを返します。response_modeがstreamingの場合、text/event-streamでサーバー送信イベントのストリームを返します。
完全なレスポンスコンテンツ。
会話 ID。
メッセージ作成タイムスタンプ(Unix エポック秒)。
イベントタイプ。
message に固定されています。このレスポンスイベントの一意 ID です。
一意のメッセージ ID です。フィードバックや推奨質問のエンドポイントを呼び出す際に
message_id パラメータとして使用します。使用量と検索リソースを含むメタデータ。
Show child attributesHide child attributes
使用された検索リソースのリスト。
Show child attributesHide child attributes
リソースからのコンテンツスニペット。
作成タイムスタンプ(Unix エポック秒)。
データソースのタイプ。
ナレッジベース ID。
ナレッジベース名。
ドキュメント ID。
ドキュメント名。
このチャンクがヒットした回数。
検索リソースの一意の ID。
インデックスノードのハッシュ。
このリソースが属するメッセージの ID。
リスト内のリソースの位置。
リソースの関連性スコア。
ドキュメント内の特定のチャンクの ID。
ドキュメント内のチャンクの位置。
チャンクコンテンツの要約。
チャンクの単語数。
モデルの使用情報です。
Show child attributesHide child attributes
補完トークンの合計価格。
補完トークンの価格単位。
補完のトークン数。
補完トークンあたりの単価。
課金通貨。
レイテンシ(秒)。
プロンプトトークンの合計価格。
プロンプトトークンの価格単位。
プロンプト内のトークン数。
プロンプトトークンあたりの単価。
すべてのトークンの合計価格。
使用されたトークンの合計数。
アプリモード。
chat はチャットボットアプリ、agent-chat はレガシー Agent アプリ、advanced-chat は Chatflow アプリです。リクエスト追跡およびレスポンス停止 API 用のタスク ID です。