> ## 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_service.json post /completion-messages
openapi: 3.0.1
info:
  title: Dify 服务 API
  description: 用于 Dify 应用与知识库的 REST API。应用类接口使用应用 API 密钥认证，知识库类接口使用知识库 API 密钥认证。
  version: 1.0.0
servers:
  - url: https://{api_base_url}
    description: Dify 服务 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: 与管理标注直接回复相关的操作。
  - name: 人工介入
    description: 暂停等待人工输入的工作流恢复操作。
  - name: 工作流运行
    description: 用于执行和管理工作流的操作。
  - name: 文本生成消息
    description: 文本生成相关操作。
  - name: 知识库
    description: 用于管理知识库的操作，包括创建、配置和检索。
  - name: 文档
    description: 用于在知识库中创建、更新和管理文档的操作。
  - name: 分段
    description: 用于管理分段和子分段的操作。
  - name: 元数据
    description: 用于管理知识库元数据字段和文档元数据值的操作。
  - name: 标签
    description: 用于管理知识库标签和标签绑定的操作。
  - name: 模型
    description: 用于获取可用模型的操作。
  - name: 知识流水线
    description: 用于管理和运行知识流水线的操作，包括数据源插件和流水线执行。
paths:
  /completion-messages:
    post:
      tags:
        - 文本生成消息
      summary: 发送消息
      description: |-
        **适用于**：文本生成应用。

        向文本生成型应用发送请求。
      operationId: createCompletionMessage
      requestBody:
        description: 创建文本生成消息的请求体。
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/CompletionRequest'
            examples:
              streaming_example:
                summary: 请求示例 - 流式模式
                value:
                  inputs:
                    city: San Francisco
                  query: Translate 'hello' to Spanish.
                  response_mode: streaming
                  user: abc-123
                  files:
                    - type: image
                      transfer_method: remote_url
                      url: https://cloud.dify.ai/logo/logo-site.png
              blocking_example:
                summary: 请求示例 - 阻塞模式
                value:
                  inputs:
                    city: New York
                  query: 'Summarize the following text: ...'
                  response_mode: blocking
                  user: def-456
      responses:
        '200':
          description: >-
            请求成功。内容类型和结构取决于请求中的 `response_mode` 参数。


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

            - 如果 `response_mode` 为 `streaming`，返回 `text/event-stream` 和
            `ChunkCompletionEvent` 对象流。
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/CompletionResponse'
              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
                    mode: completion
                    answer: Hello World!...
                    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
                    created_at: 1705407629
            text/event-stream:
              schema:
                type: string
                description: >-
                  服务器发送事件 (SSE) 流。每个事件是一个以 `data: ` 为前缀的 JSON 对象，以两个换行符终止。


                  **SSE 解析指南：**每个事件是一行以 `data: ` 为前缀的 JSON 对象，以 `\n\n` 终止。解析
                  JSON 前先去除 `data: ` 前缀。JSON 内的 `event` 字段决定事件类型。当收到终止事件（如
                  `message_end` 或 `error`）时流结束。忽略 `ping` 事件（每 10
                  秒发送一次以保持连接活跃）。注意即使流中出现错误事件，HTTP 状态码仍为 `200`。
              examples:
                streamingResponse:
                  summary: 响应示例 - 流式模式
                  value: >+
                    data: {"event": "message", "task_id":
                    "900bbd43-dc0b-4383-a372-aa6e6c414227", "message_id":
                    "5ad4cb98-f0c7-4085-b384-88c403be6290", "answer": " I",
                    "created_at": 1679586595}


                    data: {"event": "message", "task_id":
                    "900bbd43-dc0b-4383-a372-aa6e6c414227", "message_id":
                    "5ad4cb98-f0c7-4085-b384-88c403be6290", "answer": "'m",
                    "created_at": 1679586595}


                    data: {"event": "message_end", "task_id":
                    "900bbd43-dc0b-4383-a372-aa6e6c414227", "id":
                    "5e52ce04-874b-4d27-9045-b3bc80def685", "message_id":
                    "5ad4cb98-f0c7-4085-b384-88c403be6290", "metadata":
                    {"usage": {"prompt_tokens": 1033, "prompt_unit_price":
                    "0.001", "prompt_price_unit": "0.001", "prompt_price":
                    "0.0010330", "completion_tokens": 135,
                    "completion_unit_price": "0.002", "completion_price_unit":
                    "0.001", "completion_price": "0.0002700", "total_tokens":
                    1168, "total_price": "0.0013030", "currency": "USD",
                    "latency": 1.381760165997548}}}

        '400':
          description: |-
            - `app_unavailable` : 应用不可用或配置错误。
            - `provider_not_initialize` : 未找到有效的模型供应商凭据。
            - `provider_quota_exceeded` : 模型供应商配额已用尽。
            - `model_currently_not_support` : 当前模型不可用。
            - `completion_request_error` : 文本生成失败。
            - `invalid_param` : 缺少必需参数或参数无效。
          content:
            application/json:
              examples:
                app_unavailable:
                  summary: app_unavailable
                  value:
                    status: 400
                    code: app_unavailable
                    message: App unavailable, please check your app configurations.
                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.
                invalid_param:
                  summary: invalid_param
                  value:
                    status: 400
                    code: invalid_param
                    message: Arg user must be provided.
        '429':
          description: '`too_many_requests` : 该应用的并发请求过多。'
          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. The current
                      maximum concurrent requests allowed for
                      5b3d4f2a-1c9e-4a7b-8f6d-2e0c9a1b3d4f is 10.
        '500':
          description: '`internal_server_error` : 内部服务器错误。'
          content:
            application/json:
              examples:
                internal_server_error:
                  summary: internal_server_error
                  value:
                    status: 500
                    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.
components:
  schemas:
    CompletionRequest:
      type: object
      required:
        - inputs
        - user
      properties:
        inputs:
          type: object
          description: >-
            允许输入应用定义的各种变量值。包含键值对，每个键对应一个特定变量，每个值为该变量的具体值。请参阅
            [获取应用参数](/zh/api-reference/applications/get-app-parameters) 响应中的
            `user_input_form` 字段，以了解应用所需的变量名称和类型。
          additionalProperties: true
        query:
          type: string
          default: ''
          description: 要处理的输入文本。这是一个旧版参数；在较新的应用中，查询内容应通过 `inputs` 对象传递。
        response_mode:
          type: string
          enum:
            - streaming
            - blocking
          description: >-
            响应返回模式。`streaming`（推荐）使用 SSE。`blocking`
            等待完成后返回（长时间处理可能会被中断）。Cloudflare 超时为 `100 s`。省略时默认为阻塞模式。
        user:
          type: string
          description: 用户标识符，在应用内唯一。此标识符限定数据访问范围——消息和文件仅在使用相同 `user` 值查询时可见。
        files:
          type: array
          items:
            $ref: '#/components/schemas/InputFileObject'
          description: >-
            用于多模态理解的文件列表，包括图片、文档、音频和视频。要附加本地文件，请先通过
            [上传文件](/zh/api-reference/files/upload-file) 上传，然后将返回的 `id` 作为
            `upload_file_id`，并设置 `transfer_method: local_file`。
    CompletionResponse:
      type: object
      properties:
        event:
          type: string
          description: 事件类型，固定为 `message`。
        task_id:
          type: string
          format: uuid
          description: >-
            用于请求追踪和
            [停止响应](/zh/api-reference/completion-messages/stop-completion-message-generation)
            API 的任务 ID。
        id:
          type: string
          format: uuid
          description: 该响应事件的唯一 ID。
        message_id:
          type: string
          format: uuid
          description: 唯一的消息 ID。调用反馈或推荐问题接口时，将此值作为 `message_id` 参数使用。
        mode:
          type: string
          description: 应用模式，固定为 `completion`。
        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 纪元秒）。
    InputFileObject:
      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: >-
            已上传文件 ID，通过 [上传文件](/zh/api-reference/files/upload-file) API 预先上传获取（当
            `transfer_method` 为 `local_file` 时使用）。
      anyOf:
        - properties:
            transfer_method:
              enum:
                - remote_url
            url:
              type: string
              format: url
          required:
            - url
          not:
            required:
              - upload_file_id
        - properties:
            transfer_method:
              enum:
                - local_file
            upload_file_id:
              type: string
          required:
            - upload_file_id
          not:
            required:
              - url
    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 泄漏导致严重后果。**缺少或无效的 API Key 会返回 HTTP
        `401`，错误码为 `unauthorized`。

````