> ## 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.

# Send Completion Message

> **Available for**: Text Generator apps.

Sends a request to a text-generation app and returns the generated text.



## OpenAPI

````yaml /en/api-reference/openapi_service.json post /completion-messages
openapi: 3.0.1
info:
  description: >-
    REST API for Dify applications and knowledge bases. Application endpoints
    authenticate with an app API key; knowledge endpoints authenticate with a
    dataset API key.
  title: Dify Service API
  version: 1.0.0
servers:
  - description: >-
      Base URL of the Dify Service API. For self-hosted deployments, replace it
      with your own API base URL.
    url: https://{api_base_url}
    variables:
      api_base_url:
        default: api.dify.ai/v1
        description: Host and path of the API base URL, without the `https://` prefix.
security:
  - ApiKeyAuth: []
tags:
  - description: Operations related to chat messages and interactions.
    name: Chat Messages
  - description: File upload and preview operations.
    name: Files
  - description: Operations related to end user information.
    name: End Users
  - description: User feedback operations.
    name: Feedback
  - description: Operations related to managing conversations.
    name: Conversations
  - description: Text-to-Speech and Speech-to-Text operations.
    name: Audio
  - description: Operations to retrieve application settings and information.
    name: Applications
  - description: Operations related to managing annotations for direct replies.
    name: Annotations
  - description: Endpoints for resuming paused workflows that require human input.
    name: Human Input
  - description: Operations for executing and managing workflows.
    name: Workflow Runs
  - description: Operations related to text generation and completion.
    name: Completion Messages
  - description: >-
      Operations for managing knowledge bases, including creation,
      configuration, and retrieval.
    name: Knowledge Bases
  - description: >-
      Operations for creating, updating, and managing documents within a
      knowledge base.
    name: Documents
  - description: Operations for managing document chunks and child chunks.
    name: Chunks
  - description: >-
      Operations for managing knowledge base metadata fields and document
      metadata values.
    name: Metadata
  - description: Operations for managing knowledge base tags and tag bindings.
    name: Tags
  - description: Operations for retrieving available models.
    name: Models
  - description: >-
      Operations for managing and running knowledge pipelines, including
      datasource plugins and pipeline execution.
    name: Knowledge Pipeline
  - description: Ask a knowledge base a question and stream the answer.
    name: Queries
  - description: Inspect what a query retrieved and why.
    name: Query Records
  - description: Run a research question in the background and collect its results.
    name: Research Tasks
  - description: >-
      Read the documents in a knowledge base, their files, revisions, and
      chunks; label documents with metadata.
    name: Documents and Chunks
  - description: >-
      Follow, cancel, or retry indexing, and list the knowledge base's
      background tasks.
    name: Indexing Tasks
  - description: >-
      Follow the deletion of a document file, a batch of files, or a source
      until it finishes.
    name: Deletion Jobs
  - description: >-
      Manage the sources that feed a knowledge base, their sync schedules, and
      their connections.
    name: Sources
  - description: >-
      Sync a source now, import website pages or provider items, and follow,
      cancel, or retry the runs.
    name: Source Syncs and Imports
  - description: >-
      Read and change the knowledge base's models and retrieval settings, and
      follow the migration a change starts.
    name: Settings
paths:
  /completion-messages:
    post:
      tags:
        - Completion Messages
      summary: Send Completion Message
      description: |-
        **Available for**: Text Generator apps.

        Sends a request to a text-generation app and returns the generated text.
      operationId: createCompletionMessage
      requestBody:
        content:
          application/json:
            examples:
              blocking_example:
                summary: Request Example - Blocking mode
                value:
                  inputs:
                    city: New York
                  query: 'Summarize the following text: ...'
                  response_mode: blocking
                  user: def-456
              streaming_example:
                summary: Request Example - Streaming mode
                value:
                  files:
                    - transfer_method: remote_url
                      type: image
                      url: https://cloud.dify.ai/logo/logo-site.png
                  inputs:
                    city: San Francisco
                  query: Translate 'hello' to Spanish.
                  response_mode: streaming
                  user: abc-123
            schema:
              $ref: '#/components/schemas/CompletionRequest'
        description: Request body to create a completion message.
        required: true
      responses:
        '200':
          content:
            application/json:
              examples:
                blockingResponse:
                  summary: Response Example - Blocking mode
                  value:
                    answer: Hello World!...
                    created_at: 1705407629
                    event: message
                    id: b01a39de-3480-4f3e-9f1e-4841a80f8e5e
                    message_id: 9da23599-e713-473b-982c-4328d4f5c78a
                    metadata:
                      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: completion
                    task_id: c3800678-a077-43df-a102-53f23ed20b88
              schema:
                $ref: '#/components/schemas/CompletionResponse'
            text/event-stream:
              examples:
                streamingResponse:
                  summary: Response Example - Streaming mode
                  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}}}

              schema:
                description: >-
                  A stream of Server-Sent Events. Parse it per the [SSE
                  Streaming guide](/en/api-reference/guides/streaming): read
                  `data:` lines, dispatch on the `event` field, skip `ping`
                  (keep-alive every 10 seconds). See `ChunkCompletionEvent` for
                  the event structures.


                  **Stream lifecycle**: the reply streams as `message` chunks
                  and ends with `message_end`. An `error` event ends the stream
                  early; HTTP status stays `200`, so inspect the event payload
                  for details.
                type: string
          description: >-
            Successful response. The content type and structure depend on the
            `response_mode` parameter in the request.


            - If `response_mode` is `blocking`, returns `application/json` with
            a `CompletionResponse` object.

            - If `response_mode` is `streaming`, returns `text/event-stream`
            with a stream of `ChunkCompletionEvent` objects.
        '400':
          content:
            application/json:
              examples:
                app_unavailable:
                  summary: app_unavailable
                  value:
                    code: app_unavailable
                    message: App unavailable, please check your app configurations.
                    status: 400
                completion_request_error:
                  summary: completion_request_error
                  value:
                    code: completion_request_error
                    message: Completion request failed.
                    status: 400
                invalid_param:
                  summary: invalid_param
                  value:
                    code: invalid_param
                    message: Arg user must be provided.
                    status: 400
                model_currently_not_support:
                  summary: model_currently_not_support
                  value:
                    code: model_currently_not_support
                    message: >-
                      Dify Hosted OpenAI trial currently not support the GPT-4
                      model.
                    status: 400
                moderation_rejected:
                  summary: moderation_rejected
                  value:
                    code: moderation_rejected
                    message: Model input was rejected by moderation.
                    status: 400
                provider_not_initialize:
                  summary: provider_not_initialize
                  value:
                    code: provider_not_initialize
                    message: >-
                      No valid model provider credentials found. Please go to
                      Settings -> Model Provider to complete your provider
                      credentials.
                    status: 400
                provider_quota_exceeded:
                  summary: provider_quota_exceeded
                  value:
                    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
          description: >-
            - `app_unavailable` : App unavailable or misconfigured.

            - `provider_not_initialize` : No valid model provider credentials
            found.

            - `provider_quota_exceeded` : Model provider quota exhausted.

            - `model_currently_not_support` : Current model unavailable.

            - `completion_request_error` : Text generation failed.

            - `moderation_rejected` : On Dify Cloud, Dify's own moderation
            rejected the input or output of a model running on AI credits.

            - `invalid_param` : The required `user` field is missing.
        '429':
          content:
            application/json:
              examples:
                too_many_requests:
                  summary: too_many_requests
                  value:
                    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.
                    status: 429
          description: '`too_many_requests` : Too many concurrent requests for this app.'
        '500':
          content:
            application/json:
              examples:
                internal_server_error:
                  summary: internal_server_error
                  value:
                    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
          description: '`internal_server_error` : Internal server error.'
        '503':
          content:
            application/json:
              examples:
                moderation_unavailable:
                  summary: moderation_unavailable
                  value:
                    code: moderation_unavailable
                    message: >-
                      This message can’t be processed right now. Please try
                      again later.
                    status: 503
          description: >-
            - `moderation_unavailable` : The app's content moderation, set to
            Keywords or Custom Endpoint, couldn't complete its check on the
            input or output, for example because the endpoint couldn't be
            reached or returned an invalid response.

            - `moderation_unavailable` : On Dify Cloud, Dify's own moderation
            couldn't complete its check on the input or output of a model
            running on AI credits.

            - `moderation_unavailable` : The app's content moderation is set to
            OpenAI Moderation, and the workspace has no working OpenAI API key
            in Model Provider. On Dify Cloud, this happens only when the app's
            model uses the workspace's own API key.
components:
  schemas:
    CompletionRequest:
      properties:
        files:
          description: >-
            Files to attach to the request. For a local file, first upload it
            via [Upload File](/en/api-reference/files/upload-file), then
            reference the returned `id` as `upload_file_id` with
            `transfer_method: local_file`.
          items:
            $ref: '#/components/schemas/InputFileObject'
          type: array
        inputs:
          additionalProperties: true
          description: >-
            Values for the app's input variables, keyed by variable name. The
            expected names and types come from the `user_input_form` field of
            [Get App
            Parameters](/en/api-reference/applications/get-app-parameters).


            When a file or file-list input is omitted or `null`, the app uses
            the default configured for that input.
          type: object
        query:
          default: ''
          description: >-
            The text to process. Legacy field; newer apps pass this inside
            `inputs` instead.
          type: string
        response_mode:
          description: >-
            Mode of response return. Defaults to blocking when omitted.


            - `streaming` (recommended): the reply arrives as Server-Sent
            Events.

            - `blocking`: returns once generation completes. Long generations
            risk interruption: on Dify Cloud, the edge proxy may end the
            connection if the response doesn't arrive within its timeout.
          enum:
            - streaming
            - blocking
          type: string
        user:
          description: >-
            End-user identifier, defined by your app and unique within it.
            Messages and files are visible only to requests carrying the same
            `user`. See [End User
            Identity](/en/api-reference/guides/end-user-identity).
          type: string
      required:
        - inputs
        - user
      type: object
    CompletionResponse:
      properties:
        answer:
          description: Complete response content.
          type: string
        created_at:
          description: Message creation timestamp (Unix epoch seconds).
          format: int64
          type: integer
        event:
          description: Event type, fixed as `message`.
          type: string
        id:
          description: Unique ID of this response event.
          format: uuid
          type: string
        message_id:
          description: >-
            Unique message ID. Use this as the `message_id` parameter when
            calling feedback or suggested questions endpoints.
          format: uuid
          type: string
        metadata:
          description: Metadata including usage and retriever resources.
          properties:
            retriever_resources:
              description: List of retriever resources used.
              items:
                $ref: '#/components/schemas/RetrieverResource'
              type: array
            usage:
              $ref: '#/components/schemas/Usage'
          type: object
        mode:
          description: App mode, fixed as `completion`.
          type: string
        task_id:
          description: >-
            Task ID for request tracking and the [Stop Completion Message
            Generation](/en/api-reference/completion-messages/stop-completion-message-generation)
            API.
          format: uuid
          type: string
      type: object
    InputFileObject:
      anyOf:
        - not:
            required:
              - upload_file_id
          properties:
            transfer_method:
              enum:
                - remote_url
            url:
              format: url
              type: string
          required:
            - url
        - not:
            required:
              - url
          properties:
            transfer_method:
              enum:
                - local_file
            upload_file_id:
              type: string
          required:
            - upload_file_id
      properties:
        transfer_method:
          description: >-
            Transfer method: `remote_url` for file URL, `local_file` for
            uploaded file.
          enum:
            - remote_url
            - local_file
          type: string
        type:
          description: File type.
          enum:
            - image
            - document
            - audio
            - video
            - custom
          type: string
        upload_file_id:
          description: >-
            Uploaded file ID, obtained by uploading through the [Upload
            File](/en/api-reference/files/upload-file) API in advance (when
            `transfer_method` is `local_file`).
          type: string
        url:
          description: File URL (when `transfer_method` is `remote_url`).
          format: url
          type: string
      required:
        - type
        - transfer_method
      type: object
    RetrieverResource:
      description: Citation and attribution information for a retriever resource.
      properties:
        content:
          description: Content snippet from the resource.
          type: string
        created_at:
          description: Creation timestamp (Unix epoch seconds).
          format: int64
          type: integer
        data_source_type:
          description: Type of the data source.
          type: string
        dataset_id:
          description: ID of the knowledge base.
          format: uuid
          type: string
        dataset_name:
          description: Name of the knowledge base.
          type: string
        doc_metadata:
          description: >-
            Metadata values of the source document, keyed by metadata field
            name. Includes the built-in fields when they are enabled for the
            knowledge base. `null` if the document has no metadata.


            For a record from an external knowledge base, it's filled in
            Chatflow, Chatbot, and Text Generator apps, with the record's
            `metadata` from the external knowledge API plus the `score`,
            `title`, `dataset_id`, and `dataset_name` that Dify adds. In Legacy
            Agent apps it's `null` for external records.
          nullable: true
          type: object
        document_id:
          description: ID of the document.
          format: uuid
          type: string
        document_name:
          description: Name of the document.
          type: string
        files:
          description: >-
            Images in the retrieved chunk that matched the query. Returned only
            by Chatflow apps, and only when the match came from an image; `null`
            otherwise, including when the chunk matched on its text.
          items:
            properties:
              extension:
                description: >-
                  File extension, including the leading dot (for example,
                  `.png`).
                type: string
              id:
                description: ID of the uploaded image file.
                format: uuid
                type: string
              mime_type:
                description: MIME type of the file.
                type: string
              name:
                description: File name.
                type: string
              size:
                description: File size in bytes.
                type: integer
              source_url:
                description: >-
                  Signed preview URL for the image, valid for the time set by
                  the `FILES_ACCESS_TIMEOUT` [environment
                  variable](/en/self-host/deploy/configuration/environments#files_access_timeout)
                  (300 seconds by default).
                type: string
            type: object
          nullable: true
          type: array
        hit_count:
          description: Number of times this chunk was hit.
          type: integer
        id:
          description: Unique ID of the retriever resource.
          format: uuid
          type: string
        index_node_hash:
          description: Hash of the index node.
          type: string
        message_id:
          description: ID of the message this resource belongs to.
          format: uuid
          type: string
        position:
          description: Position of the resource in the list.
          type: integer
        score:
          description: Similarity score of the resource.
          format: float
          type: number
        segment_id:
          description: ID of the specific chunk within the document.
          format: uuid
          type: string
        segment_position:
          description: Position of the chunk within the document.
          type: integer
        summary:
          description: Summary of the chunk content.
          nullable: true
          type: string
        title:
          description: >-
            Title of the external knowledge base record, the same value as
            `document_name`. Returned only for external knowledge base records
            retrieved by Legacy Agent apps; otherwise `null`.
          nullable: true
          type: string
        word_count:
          description: Word count of the chunk.
          type: integer
      type: object
    Usage:
      description: Model usage information.
      properties:
        completion_price:
          description: Total price for completion tokens.
          format: decimal
          type: string
        completion_price_unit:
          description: Price unit for completion tokens.
          format: decimal
          type: string
        completion_tokens:
          description: Number of tokens in the completion.
          type: integer
        completion_unit_price:
          description: Unit price per completion token.
          format: decimal
          type: string
        currency:
          description: Currency for pricing.
          type: string
        latency:
          description: Latency in seconds.
          format: double
          type: number
        prompt_price:
          description: Total price for prompt tokens.
          format: decimal
          type: string
        prompt_price_unit:
          description: Price unit for prompt tokens.
          format: decimal
          type: string
        prompt_tokens:
          description: Number of tokens in the prompt.
          type: integer
        prompt_unit_price:
          description: Unit price per prompt token.
          format: decimal
          type: string
        total_price:
          description: Total price for all tokens.
          format: decimal
          type: string
        total_tokens:
          description: Total number of tokens used.
          type: integer
      type: object
  securitySchemes:
    ApiKeyAuth:
      bearerFormat: API_KEY
      description: >-
        Every request authenticates with an API key: `Authorization: Bearer
        {API_KEY}`. App endpoints take an app API key; knowledge endpoints take
        a knowledge base API key ([Get
        Started](/en/api-reference/guides/get-started)).


        Keep keys server-side; never embed them in client code. Requests with a
        missing or invalid key fail with HTTP `401` (`unauthorized`).
      scheme: bearer
      type: http

````

This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.