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

# Run Query

> Runs the query that [Create Query Token](/en/api-reference/queries/create-query-token) issued a token for and streams the answer as Server-Sent Events. The credential is the query token, not the knowledge base API key. The token is checked when the request is accepted.

For the two-call flow and how to read the stream, see [Query the Knowledge Base](/en/api-reference/guides/knowledge-base#query-the-knowledge-base).

For which errors to retry and what the error details mean, see [Handle Errors](/en/api-reference/guides/knowledge-base#handle-errors).

A successful query saves its query record before sending `answer.done`. Repeating the call runs the query again.



## OpenAPI

````yaml /en/api-reference/openapi_service.json post /knowledge-fs/query-stream
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:
  /knowledge-fs/query-stream:
    post:
      tags:
        - Queries
      summary: Run Query
      description: >-
        Runs the query that [Create Query
        Token](/en/api-reference/queries/create-query-token) issued a token for
        and streams the answer as Server-Sent Events. The credential is the
        query token, not the knowledge base API key. The token is checked when
        the request is accepted.


        For the two-call flow and how to read the stream, see [Query the
        Knowledge
        Base](/en/api-reference/guides/knowledge-base#query-the-knowledge-base).


        For which errors to retry and what the error details mean, see [Handle
        Errors](/en/api-reference/guides/knowledge-base#handle-errors).


        A successful query saves its query record before sending `answer.done`.
        Repeating the call runs the query again.
      operationId: runQuery
      parameters:
        - description: >-
            The `trace_id` from the [Create Query
            Token](/en/api-reference/queries/create-query-token) response, the
            same value as the token's `trace_id` claim. A value that does not
            match the token is rejected with `403`. See [Query the Knowledge
            Base](/en/api-reference/guides/knowledge-base#query-the-knowledge-base).
          in: header
          name: X-Trace-ID
          required: true
          schema:
            type: string
      requestBody:
        content:
          application/json:
            examples:
              request:
                summary: Request Example - New session
                value:
                  activeDocumentIds: []
                  activeEntityIds: []
                  knowledgeSpaceId: 8d2c6a1e-5b3f-4c7d-9e01-2a3b4c5d6e7f
                  mode: fast
                  query: What changed in the refund policy this quarter?
              request_session:
                summary: Request Example - With a session ID
                value:
                  activeDocumentIds: []
                  activeEntityIds: []
                  knowledgeSpaceId: 8d2c6a1e-5b3f-4c7d-9e01-2a3b4c5d6e7f
                  mode: fast
                  query: What is the refund window for monthly plans?
                  sessionId: a1b2c3d4-e5f6-4a7b-8c9d-0e1f2a3b4c5d
            schema:
              additionalProperties: false
              description: Provide a nonblank `query`.
              properties:
                activeDocumentIds:
                  description: >-
                    Copied from the returned `request` object. These IDs do not
                    filter or rank retrieved content.
                  items:
                    format: uuid
                    type: string
                  maxItems: 100
                  type: array
                activeEntityIds:
                  description: >-
                    Copied from the returned `request` object. These IDs do not
                    filter or rank retrieved content.
                  items:
                    maxLength: 200
                    minLength: 1
                    type: string
                  maxItems: 100
                  type: array
                knowledgeSpaceId:
                  description: >-
                    Internal ID of the knowledge base, copied from the `request`
                    object of [Create Query
                    Token](/en/api-reference/queries/create-query-token). Must
                    match the token. A mismatch is rejected with `403`.
                  format: uuid
                  minLength: 1
                  type: string
                mode:
                  description: >-
                    Retrieval depth, copied from the `request` object of [Create
                    Query Token](/en/api-reference/queries/create-query-token).
                    `null` is accepted and means the knowledge base's default
                    depth.
                  enum:
                    - fast
                    - deep
                    - research
                    - null
                  nullable: true
                  type: string
                query:
                  description: >-
                    The question. Use a nonblank query. Also limited to 16,384
                    UTF-8 bytes.
                  maxLength: 16000
                  nullable: false
                  pattern: \S
                  type: string
                sessionId:
                  description: >-
                    Session ID, copied from the `request` object of [Create
                    Query Token](/en/api-reference/queries/create-query-token).
                  format: uuid
                  nullable: true
                  type: string
              required:
                - knowledgeSpaceId
                - query
              type: object
        description: >-
          Send the `request` object from [Create Query
          Token](/en/api-reference/queries/create-query-token) unchanged.
          Unknown fields answer `400`.


          Optional fields marked nullable treat `null` as omitted.


          The normalized request must fit within 65,536 UTF-8 bytes. Exceeding
          this budget answers `413`. See [Request Size
          Limits](/en/api-reference/guides/knowledge-base#request-size-limits).
        required: true
      responses:
        '200':
          content:
            text/event-stream:
              schema:
                description: >-
                  Each frame has an `event:` line naming the event and a `data:`
                  line holding one JSON object. Dispatch on the `event:` line;
                  the JSON carries no `event` field.


                  Set your client's read timeout to allow for your slowest
                  retrieval mode. The API has no read timeout of its own and
                  sends no keep-alive events. For work that must survive a
                  client timeout, use [Create Research
                  Task](/en/api-reference/research-tasks/create-research-task).


                  See [Query the Knowledge
                  Base](/en/api-reference/guides/knowledge-base#query-the-knowledge-base)
                  for the streaming flow.


                  **Events**


                  - `answer.delta`: one piece of the answer.
                    - `delta`: the text to append.
                    - `traceId`: the query record ID.
                  - `answer.done`: the answer is complete and its query record
                  is saved.
                    - `finishReason`: `retrieval-evidence` when chunks were found, `no-retrieval-evidence` when nothing matched.
                    - `metadata`: an open map. It carries `mode` and `evidenceBundle` at `fast`, `deep`, and `research` depth, `citations` with `retrieval-evidence`, and other keys the run produced. `evidenceBundle.items` holds the retrieved chunks with their text and scores.

                      To inspect them later, call [List Query Chunks](/en/api-reference/query-records/list-query-chunks). It returns them page by page and marks chunks whose document has since been deleted.
                    - `traceId`: the query record ID.
                  - `answer.error`: the query failed after the stream opened.
                    - `code`: the failure, one of:
                      - `RETRIEVAL_EXECUTION_LEASE_LOST`: the knowledge base entered deletion, or the run expired. Run the query again.
                      - `KNOWLEDGE_FS_UNAVAILABLE`: any other failure while generating the answer or saving the query record.
                    - `error`: the message.
                    - `failure`: error details: `category`, `code`, `message`, `retryPolicy`, `stage`, `traceId`, and optionally `action`.
                      - `stage`: always `query_generation`.
                    - `traceId`: the query record ID.

                  **`citations`**


                  One entry per retrieved chunk that supports the answer:


                  - `nodeId`: the chunk ID.

                  - `label`: `node:<nodeId>`.

                  - `documentAssetId`: the document file the chunk came from.

                  - `sectionPath`: the outline path.

                  - `pageNumber`: page number, starting at 1, when the source
                  provides page information. Omitted otherwise.

                  - `projectionIds`: IDs of the search indexes that contributed
                  to this match. Use `documentAssetId` to identify the source
                  file.

                  - `sources`: which searches found the chunk: `dense`, `fts`,
                  `pageindex`, or `visual`.


                  An image citation can include
                  `multimodalCandidate.assetRef.analysisUnavailable.reason`.
                  When present, image analysis was skipped because of a resource
                  limit or an image-processing failure. Related text can still
                  contribute to the result.


                  `evidenceBundle.items[].citations[]` may also carry
                  `startOffset` and `endOffset`. These are zero-based UTF-8 byte
                  offsets into the parsed document text, with an inclusive start
                  and exclusive end. Use the returned chunk text to display a
                  citation; do not slice the original file at these offsets.


                  **Closing sequence by outcome**


                  - Success: zero or more `answer.delta`, then one
                  `answer.done`, then the stream closes.

                  - Failure: `answer.error` in place of `answer.done`, then the
                  stream closes. Pieces already delivered may precede it, and
                  the HTTP status stays `200`. Treat it as final and start a new
                  query to try again.

                  - Client disconnect. The run is canceled and the stream ends.


                  **Answer content**: at `fast` and `deep`, one `answer.delta`
                  carries a digest of the retrieved chunks (`Retrieval evidence
                  answer:` followed by numbered section paths and their text).
                  At `research`, the synthesized answer streams as one or more
                  pieces. When nothing matched, the single piece is `I could not
                  find evidence for that query in the indexed retrieval
                  projections.` and `finishReason` is `no-retrieval-evidence`.


                  Answers are capped at 2,000 characters at every depth.
                  Reaching that length does not tell you whether the answer was
                  truncated.


                  A successful run:


                  ```text

                  event: answer.delta

                  data: {"delta":"Retrieval evidence answer:\n1. Policies /
                  Refunds: Refund window extended from 14 to 30 days for annual
                  plans.","traceId":"6c1f0b2e-9d3a-4f5b-8c7d-0e1f2a3b4c5d"}


                  event: answer.done

                  data:
                  {"finishReason":"retrieval-evidence","metadata":{"mode":"fast","generator":"hybrid-query","topScore":0.83,"citations":[{"documentAssetId":"b3f4c8d2-6a1e-4f7b-9c0d-2e3f4a5b6c7d","label":"node:9f2e6b41-7c3d-4a58-b0e9-1d2c3f4a5b6e","nodeId":"9f2e6b41-7c3d-4a58-b0e9-1d2c3f4a5b6e","pageNumber":4,"projectionIds":["c7a0d5b2-3e14-4f89-a6b7-0c1d2e3f4a5b"],"sectionPath":["Policies","Refunds"],"sources":["dense","fts"]}],"evidenceBundle":{"createdAt":"2026-09-06T08:31:12Z","id":"e4b2f7a0-1c3d-4e58-9f6a-0b1c2d3e4f5a","items":[{"citations":[{"documentAssetId":"b3f4c8d2-6a1e-4f7b-9c0d-2e3f4a5b6c7d","documentVersion":1,"pageNumber":4,"sectionPath":["Policies","Refunds"]}],"conflicts":[],"freshness":{"status":"fresh"},"metadata":{},"nodeId":"9f2e6b41-7c3d-4a58-b0e9-1d2c3f4a5b6e","score":0.83,"scores":{"final":0.83,"retrieval":0.71},"text":"Refund
                  window extended from 14 to 30 days for annual
                  plans."}],"missingEvidence":[],"query":"What changed in the
                  refund policy this
                  quarter?","state":"answerable","traceId":"6c1f0b2e-9d3a-4f5b-8c7d-0e1f2a3b4c5d"}},"traceId":"6c1f0b2e-9d3a-4f5b-8c7d-0e1f2a3b4c5d"}


                  ```


                  Failure after the stream opened:


                  ```text

                  event: answer.error

                  data: {"code":"KNOWLEDGE_FS_UNAVAILABLE","error":"Agent
                  Knowledge Base is temporarily unavailable. Try again
                  later.","failure":{"action":"retry","category":"dependency","code":"KNOWLEDGE_FS_UNAVAILABLE","message":"Agent
                  Knowledge Base is temporarily unavailable. Try again
                  later.","retryPolicy":"manual","stage":"query_generation","traceId":"6c1f0b2e-9d3a-4f5b-8c7d-0e1f2a3b4c5d"},"traceId":"6c1f0b2e-9d3a-4f5b-8c7d-0e1f2a3b4c5d"}


                  ```
                type: string
          description: >-
            The stream opened. Events follow as `text/event-stream`, whatever
            `Accept` the request sends. Before the stream opens, handle failures
            as HTTP errors. After it opens, handle an `answer.error` event as
            failure even though the HTTP status is `200`.
          headers:
            x-query-run-id:
              description: >-
                Query record ID (UUID). Use it with [Get Query
                Record](/en/api-reference/query-records/get-query-record). The
                same value is the `traceId` in every event, and the `id` of the
                record in [List Query
                Records](/en/api-reference/query-records/list-query-records). A
                failure before the stream opens carries no run ID.
              schema:
                type: string
            x-session-id:
              description: >-
                The query session ID (UUID): the `sessionId` you sent, or the
                new session started for this query. Send it as `sessionId` on a
                later [Create Query
                Token](/en/api-reference/queries/create-query-token) to reuse
                the session.
              schema:
                type: string
        '400':
          content:
            application/json:
              examples:
                KNOWLEDGE_FS_INVALID_REQUEST:
                  summary: KNOWLEDGE_FS_INVALID_REQUEST
                  value:
                    code: KNOWLEDGE_FS_INVALID_REQUEST
                    error: The Agent Knowledge Base request is invalid.
                    failure:
                      category: validation
                      code: KNOWLEDGE_FS_INVALID_REQUEST
                      message: The Agent Knowledge Base request is invalid.
                      retryPolicy: never
                      traceId: 3f1e9a7c-2b4d-4e6f-8a90-1b2c3d4e5f60
                RETRIEVAL_PROFILE_SCORE_THRESHOLD_REQUIRES_RERANK:
                  summary: RETRIEVAL_PROFILE_SCORE_THRESHOLD_REQUIRES_RERANK
                  value:
                    code: RETRIEVAL_PROFILE_SCORE_THRESHOLD_REQUIRES_RERANK
                    error: The Agent Knowledge Base request is invalid.
                    failure:
                      category: validation
                      code: KNOWLEDGE_FS_INVALID_REQUEST
                      message: The Agent Knowledge Base request is invalid.
                      retryPolicy: never
                      traceId: 3f1e9a7c-2b4d-4e6f-8a90-1b2c3d4e5f60
                    mode: fast
                knowledge_fs_invalid_request:
                  summary: knowledge_fs_invalid_request (X-Trace-ID)
                  value:
                    code: knowledge_fs_invalid_request
                    message: Agent Knowledge Base request is invalid.
                    status: 400
                knowledge_fs_invalid_request_body:
                  summary: knowledge_fs_invalid_request (body validation)
                  value:
                    code: knowledge_fs_invalid_request
                    message: Agent Knowledge Base request is invalid.
                    status: 400
                    violations:
                      - field:
                          - knowledgeSpaceId
                        type: missing
          description: >-
            Standard error body, raised by Dify:


            - `knowledge_fs_invalid_request`: `X-Trace-ID` is missing, longer
            than 255 bytes, or contains a NUL, CR, or LF character. This body
            carries no field detail.

            - `knowledge_fs_invalid_request`: the body carries an unknown key,
            is missing `knowledgeSpaceId`, or breaks a [Create Query
            Token](/en/api-reference/queries/create-query-token) rule.
            `violations` names each failing field.


            Raised while running the query (`error`, `code`, and error details
            in `failure`):


            - `KNOWLEDGE_FS_INVALID_REQUEST`: the body failed the service's own
            checks: `sessionId` or an `activeDocumentIds` entry is not a UUID,
            or an `activeEntityIds` entry is outside 1 to 200 characters. The
            body can also carry `violations`, each with `code` and `path`.

            - `RETRIEVAL_PROFILE_SCORE_THRESHOLD_REQUIRES_RERANK`: the resolved
            depth is `fast` or `deep`, and the knowledge base's retrieval
            settings enable a score threshold but have `rerank.enabled: false`.
            Check the rerank model configuration under **Settings** >
            **Retrieval** in Dify. The body also carries `mode`.
        '401':
          content:
            application/json:
              examples:
                KNOWLEDGE_FS_ACCESS_DENIED:
                  summary: KNOWLEDGE_FS_ACCESS_DENIED
                  value:
                    code: KNOWLEDGE_FS_ACCESS_DENIED
                    error: >-
                      You do not have permission to perform this Agent Knowledge
                      Base operation.
                    failure:
                      action: contact_admin
                      category: authorization
                      code: KNOWLEDGE_FS_ACCESS_DENIED
                      message: >-
                        You do not have permission to perform this Agent
                        Knowledge Base operation.
                      retryPolicy: never
                      traceId: 3f1e9a7c-2b4d-4e6f-8a90-1b2c3d4e5f60
                knowledge_fs_invalid_credential:
                  summary: knowledge_fs_invalid_credential
                  value:
                    code: knowledge_fs_invalid_credential
                    message: Invalid Agent Knowledge Base service credential.
                    status: 401
          description: >-
            Standard error body, raised by Dify:


            - `knowledge_fs_invalid_credential`: the `Authorization` header is
            missing, is not `Bearer <token>`, or the token is empty, longer than
            16 KiB, or contains whitespace.


            Raised while running the query:


            - `KNOWLEDGE_FS_ACCESS_DENIED`: the token has expired, or its
            signature, issuer, or audience does not verify. Create a new token
            and call again.
        '403':
          content:
            application/json:
              examples:
                KNOWLEDGE_FS_ACCESS_DENIED:
                  summary: KNOWLEDGE_FS_ACCESS_DENIED
                  value:
                    code: KNOWLEDGE_FS_ACCESS_DENIED
                    error: >-
                      You do not have permission to perform this Agent Knowledge
                      Base operation.
                    failure:
                      action: contact_admin
                      category: authorization
                      code: KNOWLEDGE_FS_ACCESS_DENIED
                      message: >-
                        You do not have permission to perform this Agent
                        Knowledge Base operation.
                      retryPolicy: never
                      traceId: 3f1e9a7c-2b4d-4e6f-8a90-1b2c3d4e5f60
          description: >-
            Raised while running the query:


            - `KNOWLEDGE_FS_ACCESS_DENIED`: `X-Trace-ID` does not equal the
            token's `trace_id` claim, the body's `knowledgeSpaceId` does not
            match the token, or the token was issued for another operation.
        '404':
          content:
            application/json:
              examples:
                KNOWLEDGE_FS_NOT_FOUND:
                  summary: KNOWLEDGE_FS_NOT_FOUND
                  value:
                    code: KNOWLEDGE_FS_NOT_FOUND
                    error: The requested Agent Knowledge Base resource was not found.
                    failure:
                      category: not_found
                      code: KNOWLEDGE_FS_NOT_FOUND
                      message: >-
                        The requested Agent Knowledge Base resource was not
                        found.
                      retryPolicy: never
                      traceId: 3f1e9a7c-2b4d-4e6f-8a90-1b2c3d4e5f60
                QUERY_IMAGE_NOT_FOUND:
                  summary: QUERY_IMAGE_NOT_FOUND
                  value:
                    code: QUERY_IMAGE_NOT_FOUND
                    error: The requested Agent Knowledge Base resource was not found.
                    failure:
                      category: not_found
                      code: KNOWLEDGE_FS_NOT_FOUND
                      message: >-
                        The requested Agent Knowledge Base resource was not
                        found.
                      retryPolicy: never
                      traceId: 3f1e9a7c-2b4d-4e6f-8a90-1b2c3d4e5f60
                not_found:
                  summary: not_found (feature off)
                  value:
                    code: not_found
                    message: >-
                      The requested URL was not found on the server. If you
                      entered the URL manually please check your spelling and
                      try again.
                    status: 404
          description: >-
            Standard error body, raised by Dify:


            - `not_found`: the Agent Knowledge Base feature is turned off on
            this deployment. On this route the check runs after the token,
            `X-Trace-ID`, and body checks.


            Raised while running the query:


            - `KNOWLEDGE_FS_NOT_FOUND`: the knowledge base no longer exists, for
            example because it was deleted after the token was issued. A
            `knowledgeSpaceId` that does not match the token answers `403`.

            - `QUERY_IMAGE_NOT_FOUND`: a referenced query image is missing or
            unavailable to the caller.
        '409':
          content:
            application/json:
              examples:
                RETRIEVAL_DELETION_IN_PROGRESS:
                  summary: RETRIEVAL_DELETION_IN_PROGRESS
                  value:
                    code: RETRIEVAL_DELETION_IN_PROGRESS
                    error: >-
                      This Agent Knowledge Base is being deleted and cannot be
                      searched.
                    failure:
                      category: conflict
                      code: RETRIEVAL_DELETION_IN_PROGRESS
                      message: >-
                        This Agent Knowledge Base is being deleted and cannot be
                        searched.
                      retryPolicy: never
                      traceId: 3f1e9a7c-2b4d-4e6f-8a90-1b2c3d4e5f60
                RETRIEVAL_EXECUTION_LEASE_LOST:
                  summary: RETRIEVAL_EXECUTION_LEASE_LOST
                  value:
                    code: RETRIEVAL_EXECUTION_LEASE_LOST
                    error: >-
                      The retrieval execution expired before it could finish.
                      Run the query again.
                    failure:
                      action: retry
                      category: conflict
                      code: RETRIEVAL_EXECUTION_LEASE_LOST
                      message: >-
                        The retrieval execution expired before it could finish.
                        Run the query again.
                      retryPolicy: manual
                      traceId: 3f1e9a7c-2b4d-4e6f-8a90-1b2c3d4e5f60
          description: >-
            Raised while running the query:


            - `RETRIEVAL_DELETION_IN_PROGRESS`: the knowledge base is being
            deleted, so queries are refused.

            - `RETRIEVAL_EXECUTION_LEASE_LOST`: the run was canceled before the
            stream opened, because deletion started or the run expired. Run the
            query again.
        '413':
          content:
            application/json:
              examples:
                knowledge_fs_request_too_large:
                  summary: knowledge_fs_request_too_large
                  value:
                    code: knowledge_fs_request_too_large
                    message: Agent Knowledge Base request is too large.
                    status: 413
          description: >-
            Standard error body, raised by Dify:


            - `knowledge_fs_request_too_large`: the request, once Dify adds its
            defaults, exceeds 65,536 UTF-8 bytes. See [Request Size
            Limits](/en/api-reference/guides/knowledge-base#request-size-limits).
        '500':
          content:
            application/json:
              examples:
                KNOWLEDGE_FS_INTERNAL_ERROR:
                  summary: KNOWLEDGE_FS_INTERNAL_ERROR
                  value:
                    code: KNOWLEDGE_FS_INTERNAL_ERROR
                    error: >-
                      Agent Knowledge Base could not complete the operation. Try
                      again, or contact an administrator with the error
                      reference.
                    failure:
                      action: contact_admin
                      category: internal
                      code: KNOWLEDGE_FS_INTERNAL_ERROR
                      message: >-
                        Agent Knowledge Base could not complete the operation.
                        Try again, or contact an administrator with the error
                        reference.
                      retryPolicy: manual
                      traceId: 3f1e9a7c-2b4d-4e6f-8a90-1b2c3d4e5f60
          description: >-
            Raised while running the query:


            - `KNOWLEDGE_FS_INTERNAL_ERROR`: the query failed unexpectedly
            before the stream opened. Retry after a pause with a fresh query
            token.
        '502':
          content:
            application/json:
              examples:
                knowledge_fs_upstream_unavailable:
                  summary: knowledge_fs_upstream_unavailable
                  value:
                    code: knowledge_fs_upstream_unavailable
                    message: Agent Knowledge Base is unavailable.
                    status: 502
          description: >-
            Standard error body, raised by Dify:


            - `knowledge_fs_upstream_unavailable`: no response came back in
            time, or the response was in a form the API cannot relay (a
            compressed body, a success that is not an event stream, or an error
            that is not JSON). After a pause, start again with a fresh query
            token and its returned request. This starts another run; it does not
            resume a lost stream.
        '503':
          content:
            application/json:
              examples:
                KNOWLEDGE_FS_UNAVAILABLE:
                  summary: KNOWLEDGE_FS_UNAVAILABLE
                  value:
                    code: KNOWLEDGE_FS_UNAVAILABLE
                    error: >-
                      Agent Knowledge Base is temporarily unavailable. Try again
                      later.
                    failure:
                      action: retry
                      category: dependency
                      code: KNOWLEDGE_FS_UNAVAILABLE
                      message: >-
                        Agent Knowledge Base is temporarily unavailable. Try
                        again later.
                      retryPolicy: manual
                      traceId: 3f1e9a7c-2b4d-4e6f-8a90-1b2c3d4e5f60
                knowledge_fs_operation_unavailable:
                  summary: knowledge_fs_operation_unavailable
                  value:
                    code: knowledge_fs_operation_unavailable
                    message: Agent Knowledge Base operation is not available.
                    status: 503
          description: >-
            Standard error body, raised by Dify:


            - `knowledge_fs_operation_unavailable`: Run Query is not available
            on this deployment.


            Raised while running the query:


            - `KNOWLEDGE_FS_UNAVAILABLE`: the knowledge base is not ready to
            answer at the resolved depth: no published content yet, no active
            embedding model, or a search index still being built. Check
            `capabilities` in [Get Knowledge Base
            Settings](/en/api-reference/settings/get-knowledge-base-settings)
            and try again later.

            - `TIDB_FTS_POSTINGS_NOT_READY`: the keyword search index is still
            being prepared. The body also carries `runState`. Try again later.
      security:
        - QueryToken: []
components:
  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
    QueryToken:
      bearerFormat: JWT
      description: >-
        The query token returned by [Create Query
        Token](/en/api-reference/queries/create-query-token), sent as
        `Authorization: Bearer {token}`. Use it before the returned `expires_at`
        time, at most 60 seconds after issue. It authorizes only Run Query on
        that knowledge base.


        Send `X-Trace-ID` on the same request, with the `trace_id` that Create
        Query Token returned.
      scheme: bearer
      type: http

````

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