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

# 创建查询令牌

> 为 [运行查询](/zh/api-reference/queries/run-query) 签发查询令牌，并返回需随令牌一起发送的请求体。详见 [查询知识库](/zh/api-reference/guides/knowledge-base#query-the-knowledge-base)。



## OpenAPI

````yaml /zh/api-reference/openapi_service.json post /knowledge-fs/spaces/{knowledge_base_id}/queries/admission
openapi: 3.0.1
info:
  description: 用于 Dify 应用与知识库的 REST API。应用类接口使用应用 API 密钥认证，知识库类接口使用知识库 API 密钥认证。
  title: Dify 服务 API
  version: 1.0.0
servers:
  - description: Dify 服务 API 的基础 URL。自部署时，替换为你的 API 基础 URL。
    url: https://{api_base_url}
    variables:
      api_base_url:
        default: api.dify.ai/v1
        description: API 基础 URL 的主机与路径，不含 `https://` 前缀。
security:
  - ApiKeyAuth: []
tags:
  - 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: 用于管理和运行知识流水线的操作，包括数据源插件和流水线执行。
    name: 知识流水线
  - description: 向知识库提问，并流式返回回答。
    name: 查询
  - description: 查看一次查询检索到了什么，以及原因。
    name: 查询记录
  - description: 在后台运行研究问题，并获取其结果。
    name: 研究任务
  - description: 读取知识库中的文档及其文件、修订版本和分段，并用元数据标注文档。
    name: 文档与分段
  - description: 跟踪、取消或重试索引，并列出知识库的后台任务。
    name: 索引任务
  - description: 跟踪文档文件、一批文件或数据源的删除，直到完成。
    name: 删除作业
  - description: 管理为知识库提供内容的数据源，以及它们的定时同步设置和连接。
    name: 数据源
  - description: 立即同步数据源，导入网站页面或提供商条目，并跟踪、取消或重试运行。
    name: 数据源同步与导入
  - description: 读取和更改知识库的模型与检索设置，并跟踪更改触发的迁移。
    name: 设置
paths:
  /knowledge-fs/spaces/{knowledge_base_id}/queries/admission:
    post:
      tags:
        - Queries
      summary: 创建查询令牌
      description: >-
        为 [运行查询](/zh/api-reference/queries/run-query) 签发查询令牌，并返回需随令牌一起发送的请求体。详见
        [查询知识库](/zh/api-reference/guides/knowledge-base#query-the-knowledge-base)。
      operationId: createQueryToken
      parameters:
        - description: >-
            知识库 ID：即知识库 **API 访问** 对话框中所示服务 API
            端点的最后一段（`…/knowledge-fs/spaces/<knowledge base ID>`），也是地址栏中
            `/datasets/new/` 之后的那一段。
          in: path
          name: knowledge_base_id
          required: true
          schema:
            format: uuid
            type: string
      requestBody:
        content:
          application/json:
            examples:
              request:
                summary: 请求示例 - 新会话
                value:
                  mode: fast
                  query: What changed in the refund policy this quarter?
              request_session:
                summary: 请求示例 - 带会话 ID
                value:
                  activeDocumentIds: []
                  activeEntityIds: []
                  mode: fast
                  query: What is the refund window for monthly plans?
                  sessionId: a1b2c3d4-e5f6-4a7b-8c9d-0e1f2a3b4c5d
            schema:
              additionalProperties: false
              description: 需提供非空白的 `query`。
              properties:
                activeDocumentIds:
                  description: 这些 ID 不会对检索到的内容进行筛选或排序。留空即可。
                  items:
                    type: string
                  maxItems: 100
                  type: array
                activeEntityIds:
                  description: 这些 ID 不会对检索到的内容进行筛选或排序。留空即可。
                  items:
                    type: string
                  maxItems: 100
                  type: array
                mode:
                  description: >-
                    检索深度：`fast`、`deep` 或 `research`（参见
                    [检索深度](/zh/cloud/use-dify/knowledge-base/retrieval-settings#retrieval-depth)）。省略（或传
                    `null`）时使用知识库的默认深度，即
                    [获取知识库设置](/zh/api-reference/settings/get-knowledge-base-settings)
                    中的 `retrieval.default_mode`。
                  enum:
                    - fast
                    - deep
                    - research
                    - null
                  nullable: true
                  type: string
                query:
                  description: 要查询的问题。不能为空白，且不超过 16,384 个 UTF-8 字节。
                  maxLength: 16000
                  nullable: false
                  pattern: \S
                  type: string
                sessionId:
                  description: >-
                    查询会话 ID，格式为
                    UUID。省略则开启新会话。[运行查询](/zh/api-reference/queries/run-query) 会在
                    `x-session-id` 响应头中返回会话 ID。


                    一个会话保存最近 20 次查询，但不会把它们带入之后的回答。30 分钟内没有查询，会话即过期。


                    传入已过期或未知的 ID 时，会以该 ID 开启一个新会话，因此你自行生成的 UUID 始终可以用作该会话的 ID。
                  nullable: true
                  type: string
              required:
                - query
              type: object
        description: |-
          包含未知字段时返回 `400`。

          标记为 nullable 的可选字段，传 `null` 等同于省略。
        required: true
      responses:
        '200':
          content:
            application/json:
              examples:
                success:
                  summary: 响应示例 - 新会话
                  value:
                    expires_at: '2026-09-06T08:31:07Z'
                    operation_id: createQuery
                    request:
                      activeDocumentIds: []
                      activeEntityIds: []
                      knowledgeSpaceId: 8d2c6a1e-5b3f-4c7d-9e01-2a3b4c5d6e7f
                      mode: fast
                      query: What changed in the refund policy this quarter?
                    token: >-
                      eyJhbGciOiJSUzI1NiIsImtpZCI6Imtmcy0yMDI2LTA5In0.eyJpc3MiOiJkaWZ5LWNvbnRyb2wtcGxhbmUiLCJhdWQiOiJrbm93bGVkZ2UtZnMiLCJzdWIiOiJkaWZ5LWRhdGFzZXQtYXBpLWtleTo3YjRjOWUyMS0zZDVmLTRhNmItOGM3ZC05ZTBmMWEyYjNjNGQiLCJhY3Rpb24iOiJxdWVyaWVzLmNyZWF0ZSIsInRyYWNlX2lkIjoiM2YxZTlhN2MtMmI0ZC00ZTZmLThhOTAtMWIyYzNkNGU1ZjYwIiwiZXhwIjoxNzg4NjgzNDY3fQ.V2s9Rm5xR2ZUZ0J2M2Q5aW1KU3hqUXJsV1pKcGtnQUFCZUtGMQ
                    trace_id: 3f1e9a7c-2b4d-4e6f-8a90-1b2c3d4e5f60
                    url: https://api.example.com/v1/knowledge-fs/query-stream
                success_session:
                  summary: 响应示例 - 带会话 ID
                  value:
                    expires_at: '2026-09-06T08:33:52Z'
                    operation_id: createQuery
                    request:
                      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
                    token: >-
                      eyJhbGciOiJSUzI1NiIsImtpZCI6Imtmcy0yMDI2LTA5In0.eyJpc3MiOiJkaWZ5LWNvbnRyb2wtcGxhbmUiLCJhdWQiOiJrbm93bGVkZ2UtZnMiLCJzdWIiOiJkaWZ5LWRhdGFzZXQtYXBpLWtleTo3YjRjOWUyMS0zZDVmLTRhNmItOGM3ZC05ZTBmMWEyYjNjNGQiLCJhY3Rpb24iOiJxdWVyaWVzLmNyZWF0ZSIsInRyYWNlX2lkIjoiN2Q0YTFjOGUtNWY2MC00YjIzLTlhN2QtOGUwZjFhMmIzYzRkIiwiZXhwIjoxNzg4NjgzNjMyfQ.TnBHc0xxUjBkWWJ4M2VBaW1KU3hqUXJsV1pKcGtnQUFCZUtGMg
                    trace_id: 7d4a1c8e-5f60-4b23-9a7d-8e0f1a2b3c4d
                    url: https://api.example.com/v1/knowledge-fs/query-stream
              schema:
                properties:
                  expires_at:
                    description: 令牌的过期时间，为 UTC 时区的 ISO 8601 时间戳。最晚为签发后 60 秒，部署方可缩短这一有效期。
                    type: string
                  operation_id:
                    description: 始终为 `createQuery`，即该令牌适用的操作。调用方可忽略此字段。
                    type: string
                  request:
                    description: '[运行查询](/zh/api-reference/queries/run-query) 的请求体，需原样发送。'
                    properties:
                      activeDocumentIds:
                        description: 文档 ID，与请求中发送的一致。省略时为 `[]`。
                        items:
                          type: string
                        type: array
                      activeEntityIds:
                        description: 实体 ID，与请求中发送的一致。省略时为 `[]`。
                        items:
                          type: string
                        type: array
                      knowledgeSpaceId:
                        description: >-
                          知识库的内部 ID，并非路径中的知识库 ID。它已绑定到令牌中，请求体中的
                          `knowledgeSpaceId`
                          与令牌不匹配时，[运行查询](/zh/api-reference/queries/run-query)
                          会拒绝该请求。
                        type: string
                      mode:
                        description: 检索深度，与请求中发送的一致。省略时为 `null`。
                        nullable: true
                        type: string
                      query:
                        description: 请求中的问题。请求包含图片引用时可能为 `null`。
                        maxLength: 16000
                        nullable: true
                        pattern: \S
                        type: string
                      sessionId:
                        description: 会话 ID，与请求中发送的一致。省略时不返回。
                        nullable: true
                        type: string
                    type: object
                  token:
                    description: >-
                      用于对该知识库调用 [运行查询](/zh/api-reference/queries/run-query)
                      的查询令牌，在 `expires_at` 之前有效。以 `Authorization: Bearer
                      <token>` 的形式发送。


                      每次调用都要创建新令牌，重试也不例外。


                      令牌是签名的 JWT。`X-Trace-ID` 请求头的值直接从本响应的 `trace_id` 读取，无需解码令牌。
                    type: string
                  trace_id:
                    description: >-
                      调用 [运行查询](/zh/api-reference/queries/run-query) 时作为
                      `X-Trace-ID` 请求头发送的值，与令牌中的 `trace_id` 声明相同。它不是查询记录 ID。
                    type: string
                  url:
                    description: >-
                      [运行查询](/zh/api-reference/queries/run-query) 的请求地址。部署设置了
                      `SERVICE_API_URL` 时为绝对 URL；否则为路径
                      `/v1/knowledge-fs/query-stream`，其中已包含 `/v1`
                      前缀。这种情况下，基于端点的协议和主机解析该路径，不要基于端点的路径解析。
                    type: string
                type: object
          description: 查询令牌已签发。
        '400':
          content:
            application/json:
              examples:
                knowledge_fs_invalid_request:
                  summary: knowledge_fs_invalid_request
                  value:
                    code: knowledge_fs_invalid_request
                    message: Agent Knowledge Base request is invalid.
                    status: 400
                    violations:
                      - field:
                          - query
                        type: string_too_long
          description: '- `knowledge_fs_invalid_request`：请求未通过校验。`violations` 列出每个出错的字段。'
        '401':
          content:
            application/json:
              examples:
                knowledge_fs_invalid_credential:
                  summary: knowledge_fs_invalid_credential
                  value:
                    code: knowledge_fs_invalid_credential
                    message: Invalid Agent Knowledge Base service credential.
                    status: 401
                unauthorized_1:
                  summary: unauthorized (header missing)
                  value:
                    code: unauthorized
                    message: >-
                      Authorization header must be provided and start with
                      'Bearer'
                    status: 401
                unauthorized_2:
                  summary: unauthorized (key unknown)
                  value:
                    code: unauthorized
                    message: Access token is invalid
                    status: 401
          description: >-
            - `unauthorized`：缺少 `Authorization` 请求头，或密钥无法识别、不是知识库 API 密钥。

            - `knowledge_fs_invalid_credential`：密钥有效，但其所属工作空间中没有此 ID
            的知识库，或该密钥未关联任何工作空间。
        '403':
          content:
            application/json:
              examples:
                forbidden:
                  summary: forbidden (rate limit)
                  value:
                    code: forbidden
                    message: >-
                      Sorry, you have reached the knowledge base request rate
                      limit of your subscription.
                    status: 403
                knowledge_fs_access_denied:
                  summary: knowledge_fs_access_denied
                  value:
                    code: knowledge_fs_access_denied
                    message: Agent Knowledge Base operation is not allowed.
                    status: 403
          description: >-
            - `knowledge_fs_access_denied`：该密钥的访问范围限定为其他知识库、此知识库已关闭 **API
            访问**，或知识库未处于活动状态。

            - `knowledge_fs_access_denied`：签发令牌期间，该密钥对此知识库的访问权限被撤销。

            - `forbidden`：在 Dify Cloud
            上，工作空间已达到其订阅套餐的知识库请求频率限制。所有调用都计入，读取操作也不例外。
        '404':
          content:
            application/json:
              examples:
                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: '- `not_found`：当前部署已关闭 Agent 知识库功能。'
        '503':
          content:
            application/json:
              examples:
                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: >-
            - `knowledge_fs_operation_unavailable`：此工作空间尚未配置 Agent
            知识库功能、当前部署不提供此操作，或在请求鉴权期间该密钥对此知识库的访问权限发生了变化。重新获取令牌。

            -
            `knowledge_fs_operation_unavailable`：该知识库由经典知识库升级而来，仍在禁用原先已禁用或已归档的文档。稍后重试。
components:
  securitySchemes:
    ApiKeyAuth:
      bearerFormat: API_KEY
      description: >-
        每个请求都通过 API Key 认证：`Authorization: Bearer {API_KEY}`。应用接口使用应用 API
        Key，知识库接口使用知识库 API Key（[快速开始](/zh/api-reference/guides/get-started)）。


        API Key 应保存在服务端，切勿嵌入客户端代码。缺失或无效的 Key 会返回 HTTP `401`（`unauthorized`）。
      scheme: bearer
      type: http

````

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