发送对话消息
适用于: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
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 时必填)。用户发送的消息。
响应返回模式。省略时默认为阻塞式返回。
streaming(推荐):回复以 Server-Sent Events 形式返回。blocking:生成完成后一次性返回。生成时间较长时有中断风险:在 Dify Cloud 上,如果边缘代理在超时时间内未收到响应,就可能中断连接。- 旧版 Agent 和 Agent 应用仅支持
streaming;使用blocking会返回 400。
Options:
streamingblocking仅适用于 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。