> ## Documentation Index
> Fetch the complete documentation index at: https://docs.dify.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# 发送对话消息

> 向应用发送请求。



## OpenAPI

````yaml /zh/api-reference/openapi_chat.json post /chat-messages
openapi: 3.0.1
info:
  title: 对话型应用 API
  description: 对话型应用支持会话持久化，允许将之前的聊天记录作为上下文进行回复。适用于聊天机器人、客服 AI 等场景。
  version: 1.0.0
servers:
  - url: https://{api_base_url}
    description: 对话型应用 API 的基础 URL。自部署时，替换为你的 API 基础 URL。
    variables:
      api_base_url:
        default: api.dify.ai/v1
        description: API 基础 URL 的主机与路径，不含 `https://` 前缀。
security:
  - ApiKeyAuth: []
tags:
  - name: 对话消息
    description: 与聊天消息和交互相关的操作。
  - name: 文件操作
    description: 文件上传和预览操作。
  - name: 终端用户
    description: 终端用户信息相关操作。
  - name: 消息反馈
    description: 用户反馈操作。
  - name: 会话管理
    description: 与管理会话相关的操作。
  - name: 语音与文字转换
    description: 文字转语音和语音转文字操作。
  - name: 应用配置
    description: 获取应用设置和信息的操作。
  - name: 标注管理
    description: 与管理标注直接回复相关的操作。
paths:
  /chat-messages:
    post:
      tags:
        - 对话消息
      summary: 发送对话消息
      description: 向应用发送请求。
      operationId: sendBasicChatMessageCn
      requestBody:
        description: 发送对话消息的请求体。
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/ChatRequest'
            examples:
              streaming_example:
                summary: 请求示例 - 流式模式
                value:
                  inputs:
                    city: San Francisco
                  query: What are the specs of the iPhone 13 Pro Max?
                  response_mode: streaming
                  conversation_id: ''
                  user: abc-123
                  files:
                    - type: image
                      transfer_method: remote_url
                      url: https://cloud.dify.ai/logo/logo-site.png
              blocking_example:
                summary: 请求示例 - 阻塞模式
                value:
                  inputs: {}
                  query: What are the specs of the iPhone 13 Pro Max?
                  response_mode: blocking
                  conversation_id: 45701982-8118-4bc5-8e9b-64562b4555f2
                  user: abc-123
      responses:
        '200':
          description: >-
            请求成功。内容类型和结构取决于请求中的 `response_mode` 参数。


            - 如果 `response_mode` 为 `blocking`，返回 `application/json` 和
            `ChatCompletionResponse` 对象。

            - 如果 `response_mode` 为 `streaming`，返回 `text/event-stream` 和服务器发送事件流。
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ChatCompletionResponse'
              examples:
                blockingResponse:
                  summary: 响应示例 - 阻塞模式
                  value:
                    event: message
                    task_id: c3800678-a077-43df-a102-53f23ed20b88
                    id: b01a39de-3480-4f3e-9f1e-4841a80f8e5e
                    message_id: 9da23599-e713-473b-982c-4328d4f5c78a
                    conversation_id: 45701982-8118-4bc5-8e9b-64562b4555f2
                    mode: chat
                    answer: iPhone 13 Pro Max specs are listed here:...
                    metadata:
                      usage:
                        prompt_tokens: 1033
                        prompt_unit_price: '0.001'
                        prompt_price_unit: '0.001'
                        prompt_price: '0.0010330'
                        completion_tokens: 128
                        completion_unit_price: '0.002'
                        completion_price_unit: '0.001'
                        completion_price: '0.0002560'
                        total_tokens: 1161
                        total_price: '0.0012890'
                        currency: USD
                        latency: 0.7682376249867957
                      retriever_resources:
                        - position: 1
                          dataset_id: 101b4c97-fc2e-463c-90b1-5261a4cdcafb
                          dataset_name: iPhone
                          document_id: 8dd1ad74-0b5f-4175-b735-7d98bbbb4e00
                          document_name: iPhone List
                          segment_id: ed599c7f-2766-4294-9d1d-e5235a61270a
                          score: 0.98457545
                          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"
                    created_at: 1705407629
            text/event-stream:
              schema:
                type: string
                description: >-
                  服务器发送事件 (SSE) 流。


                  **解析**：每个事件是一行以 `data: ` 为前缀的 JSON 对象，以 `\n\n` 终止。解析 JSON 前先去除
                  `data: ` 前缀，再读取 `event` 字段确定事件类型。忽略 `ping` 事件，它以 `event: ping`
                  行的形式（无 `data:` 载荷）每 10 秒发送一次以保持连接活跃。


                  **流生命周期**：回复以 `message` 事件（聊天助手应用）或 `agent_thought` 与
                  `agent_message` 事件（Agent 应用）的形式流式返回，并以 `message_end`
                  结束。开启文本转语音（TTS）自动播放时，`tts_message` 事件会穿插其间，`tts_message_end`
                  成为最后一个事件。


                  **事件**：除 `ping` 外，每个事件都包含 `conversation_id`、`message_id` 和
                  `created_at`（Unix 纪元秒）；除 `error` 外，其余事件还包含 `task_id`。


                  **回复事件**


                  | 事件 | 应用 | 触发时机 | 关键字段 |

                  |:---|:---|:---|:---|

                  | `message` | 聊天助手 | 每个回答片段（按顺序拼接） | `answer` |

                  | `agent_message` | Agent | 每个回答片段（按顺序拼接） | `answer` |

                  | `agent_thought` | Agent | 每个推理或工具调用步骤 |
                  `position`、`thought`、`tool`、`tool_input`（JSON）、`observation`、`message_files`
                  |

                  | `message_replace` | 聊天助手、Agent | 内容审核替换已生成的回答 | `answer` |

                  | `message_file` | 聊天助手、Agent | 助手返回文件 |
                  `type`、`belongs_to`、`url` |

                  | `message_end` | 聊天助手、Agent | 回答完成 |
                  `metadata`（`usage`、`retriever_resources`） |

                  | `tts_message`、`tts_message_end` | 聊天助手、Agent | 音频片段/结束，开启
                  TTS 自动播放时 | `audio` |


                  **传输事件**


                  | 事件 | 应用 | 触发时机 | 关键字段 |

                  |:---|:---|:---|:---|

                  | `error` | 聊天助手、Agent | 失败导致流结束；HTTP 仍为 `200` | `status`（如
                  `400`）、`code`（如 `invalid_param`）、`message` |

                  | `ping` | 聊天助手、Agent | 每 10 秒保持连接 | 无 |
              examples:
                streamingResponseBasic:
                  summary: Response Example - Streaming (Basic)
                  value: >-
                    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", "metadata":
                    {"usage": {"total_tokens": 10, "latency": 1.0}}}
                streamingResponseAgent:
                  summary: Response Example - Streaming (Agent)
                  value: >-
                    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}}}
        '400':
          description: |-
            - `app_unavailable` : 应用不可用或配置错误。
            - `not_chat_app` : App mode does not match the API route.
            - `conversation_completed` : The conversation has ended.
            - `provider_not_initialize` : 未找到有效的模型提供商凭据。
            - `provider_quota_exceeded` : 模型提供商配额已用尽。
            - `model_currently_not_support` : 当前模型不可用。
            - `completion_request_error` : 文本生成失败。
          content:
            application/json:
              examples:
                app_unavailable:
                  summary: app_unavailable
                  value:
                    status: 400
                    code: app_unavailable
                    message: App unavailable, please check your app configurations.
                not_chat_app:
                  summary: not_chat_app
                  value:
                    status: 400
                    code: not_chat_app
                    message: Please check if your app mode matches the right API route.
                conversation_completed:
                  summary: conversation_completed
                  value:
                    status: 400
                    code: conversation_completed
                    message: >-
                      The conversation has ended. Please start a new
                      conversation.
                provider_not_initialize:
                  summary: provider_not_initialize
                  value:
                    status: 400
                    code: provider_not_initialize
                    message: >-
                      No valid model provider credentials found. Please go to
                      Settings -> Model Provider to complete your provider
                      credentials.
                provider_quota_exceeded:
                  summary: provider_quota_exceeded
                  value:
                    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.
                model_currently_not_support:
                  summary: model_currently_not_support
                  value:
                    status: 400
                    code: model_currently_not_support
                    message: >-
                      Dify Hosted OpenAI trial currently not support the GPT-4
                      model.
                completion_request_error:
                  summary: completion_request_error
                  value:
                    status: 400
                    code: completion_request_error
                    message: Completion request failed.
        '404':
          description: '`not_found` : 会话不存在。'
          content:
            application/json:
              examples:
                conversation_not_exists:
                  summary: not_found
                  value:
                    status: 404
                    code: not_found
                    message: Conversation Not Exists.
        '429':
          description: |-
            - `too_many_requests` : 该应用的并发请求过多。
            - `rate_limit_error` : 上游模型提供商的速率限制已超出。
          content:
            application/json:
              examples:
                too_many_requests:
                  summary: too_many_requests
                  value:
                    status: 429
                    code: too_many_requests
                    message: Too many requests. Please try again later.
                rate_limit_error:
                  summary: rate_limit_error
                  value:
                    status: 429
                    code: rate_limit_error
                    message: Rate Limit Error
        '500':
          description: '`internal_server_error` : 内部服务器错误。'
          content:
            application/json:
              examples:
                internal_server_error:
                  summary: internal_server_error
                  value:
                    status: 500
                    code: internal_server_error
                    message: Internal server error.
components:
  schemas:
    ChatRequest:
      type: object
      required:
        - inputs
        - query
        - user
      properties:
        query:
          type: string
          description: 用户输入/问题内容。
        inputs:
          type: object
          description: >-
            允许输入应用定义的各种变量值。包含键值对。请参阅 [获取应用参数](/api-reference/应用配置/获取应用参数) 响应中的
            `user_input_form` 字段，以了解应用所需的变量名称和类型。
          additionalProperties: true
        response_mode:
          type: string
          enum:
            - streaming
            - blocking
          description: >-
            响应返回模式。`streaming`（推荐）使用 SSE。`blocking` 在完成后返回（长时间处理可能中断；Agent
            助手模式不支持此选项）。Cloudflare 超时时间为 `100 s`。未指定时默认为阻塞模式。
        user:
          type: string
          description: 用户标识符，在应用内唯一。此标识符用于限定数据访问范围——会话、消息和文件仅在使用相同的 `user` 值查询时可见。
        conversation_id:
          type: string
          description: >-
            用于继续会话的会话 ID。传入上一条消息的 `conversation_id`。要开始新会话，请省略此字段或传入空字符串。响应会返回一个
            `conversation_id`——在后续消息中传入该值即可继续该会话。
        files:
          type: array
          description: >-
            用于多模态理解的文件列表，包括图片、文档、音频和视频。要附加本地文件，请先通过
            [上传文件](/api-reference/文件操作/上传文件) 上传，然后将返回的 `id` 作为
            `upload_file_id`，并设置 `transfer_method: local_file`。
          items:
            type: object
            required:
              - type
              - transfer_method
            properties:
              type:
                type: string
                enum:
                  - image
                  - document
                  - audio
                  - video
                  - custom
                description: 文件类型。
              transfer_method:
                type: string
                enum:
                  - remote_url
                  - local_file
                description: 传输方式：文件 URL 使用 `remote_url`，上传文件使用 `local_file`。
              url:
                type: string
                format: url
                description: 文件 URL（当 `transfer_method` 为 `remote_url` 时必填）。
              upload_file_id:
                type: string
                description: >-
                  通过 [上传文件](/api-reference/文件操作/上传文件) API 获取的已上传文件 ID（当
                  `transfer_method` 为 `local_file` 时必填）。
        auto_generate_name:
          type: boolean
          description: >-
            自动生成会话标题。如果为 `false`，请使用 [重命名会话](/api-reference/会话管理/重命名会话) API 并设置
            `auto_generate: true` 来异步生成标题。
          default: true
    ChatCompletionResponse:
      type: object
      properties:
        event:
          type: string
          description: 事件类型，固定为 `message`。
        task_id:
          type: string
          format: uuid
          description: 用于请求追踪和停止响应 API 的任务 ID。
        id:
          type: string
          format: uuid
          description: 该响应事件的唯一 ID。
        message_id:
          type: string
          format: uuid
          description: 唯一的消息 ID。调用反馈或推荐问题接口时，将此值作为 `message_id` 参数使用。
        conversation_id:
          type: string
          format: uuid
          description: 会话 ID。
        mode:
          type: string
          description: 应用模式。`chat` 表示聊天助手应用，`agent-chat` 表示 Agent 应用。
        answer:
          type: string
          description: 完整的响应内容。
        metadata:
          type: object
          description: 包含用量和检索资源的元数据。
          properties:
            usage:
              $ref: '#/components/schemas/Usage'
            retriever_resources:
              type: array
              description: 使用的检索资源列表。
              items:
                $ref: '#/components/schemas/RetrieverResource'
        created_at:
          type: integer
          format: int64
          description: 消息创建时间戳（Unix 纪元秒）。
    Usage:
      type: object
      description: 模型使用信息。
      properties:
        prompt_tokens:
          type: integer
          description: 提示词中的令牌数。
        prompt_unit_price:
          type: string
          format: decimal
          description: 每个提示词令牌的单价。
        prompt_price_unit:
          type: string
          format: decimal
          description: 提示词令牌的价格单位。
        prompt_price:
          type: string
          format: decimal
          description: 提示词令牌的总价。
        completion_tokens:
          type: integer
          description: 补全内容中的令牌数。
        completion_unit_price:
          type: string
          format: decimal
          description: 每个补全令牌的单价。
        completion_price_unit:
          type: string
          format: decimal
          description: 补全令牌的价格单位。
        completion_price:
          type: string
          format: decimal
          description: 补全令牌的总价。
        total_tokens:
          type: integer
          description: 使用的令牌总数。
        total_price:
          type: string
          format: decimal
          description: 所有令牌的总价。
        currency:
          type: string
          description: 计价货币。
        latency:
          type: number
          format: double
          description: 延迟时间（秒）。
    RetrieverResource:
      type: object
      description: 检索资源的引用和归属信息。
      properties:
        id:
          type: string
          format: uuid
          description: 检索资源的唯一 ID。
        message_id:
          type: string
          format: uuid
          description: 该资源所属消息的 ID。
        position:
          type: integer
          description: 资源在列表中的位置。
        dataset_id:
          type: string
          format: uuid
          description: 知识库 ID。
        dataset_name:
          type: string
          description: 知识库名称。
        document_id:
          type: string
          format: uuid
          description: 文档 ID。
        document_name:
          type: string
          description: 文档名称。
        data_source_type:
          type: string
          description: 数据源类型。
        segment_id:
          type: string
          format: uuid
          description: 文档中特定块的 ID。
        score:
          type: number
          format: float
          description: 资源的相关性评分。
        hit_count:
          type: integer
          description: 该块被命中的次数。
        word_count:
          type: integer
          description: 块的字数。
        segment_position:
          type: integer
          description: 块在文档中的位置。
        index_node_hash:
          type: string
          description: 索引节点的哈希值。
        content:
          type: string
          description: 资源的内容片段。
        summary:
          type: string
          nullable: true
          description: 块内容的摘要。
        created_at:
          type: integer
          format: int64
          description: 创建时间戳（Unix 纪元秒）。
  securitySchemes:
    ApiKeyAuth:
      type: http
      scheme: bearer
      bearerFormat: API_KEY
      description: >-
        API Key 认证。对于所有 API 请求，请在 `Authorization` HTTP 头中包含您的 API Key，并加上
        `Bearer ` 前缀。示例：`Authorization: Bearer {API_KEY}`。**强烈建议将 API Key
        存储在服务端，不要在客户端共享或存储，以避免 API Key 泄漏导致严重后果。**

````