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

# 外部知识库 API

## 端点

```
POST <your-endpoint>/retrieval
```

## 请求头

该 API 用于连接团队内独立维护的知识库，如需了解更多操作指引，请参考阅读 [连接外部知识库](/zh/3.7.x/use/knowledge-base/connect-external-knowledge-base)。你可以在 HTTP 请求头的 `Authorization` 字段中使用 `API-Key` 来验证权限。身份验证逻辑由您在检索 API 中定义，如下所示：

```
Authorization: Bearer {API_KEY}
```

## 请求体元素

请求接受以下 JSON 格式的数据。

| 属性                  | 是否必需 | 类型  | 描述       | 示例值         |
| ------------------- | ---- | --- | -------- | ----------- |
| knowledge\_id       | 是    | 字符串 | 知识库唯一 ID | AAA-BBB-CCC |
| query               | 是    | 字符串 | 用户的查询    | Dify 是什么？   |
| retrieval\_setting  | 是    | 对象  | 知识检索参数   | 见下文         |
| metadata\_condition | 否    | 对象  | 原数组筛选    | 见下文         |

`retrieval_setting` 属性是一个包含以下键的对象：

| 属性               | 是否必需 | 类型  | 描述                    | 示例值 |
| ---------------- | ---- | --- | --------------------- | --- |
| top\_k           | 是    | 整数  | 检索结果的最大数量             | 5   |
| score\_threshold | 是    | 浮点数 | 结果与查询相关性的分数限制，范围：0\~1 | 0.5 |

`metadata_condition` 属性是一个包含以下键的对象：

| 属性                | 是否必需 | 类型     | 描述                              | 示例值 |
| ----------------- | ---- | ------ | ------------------------------- | --- |
| logical\_operator | 否    | 字符串    | 逻辑操作符，取值为 `and` 或 `or`，默认 `and` | and |
| conditions        | 是    | 数组（对象） | 条件列表                            | 见下文 |

`conditions` 数组中的每个对象包含以下键：

| 属性                   | 是否必需 | 类型      | 描述                                                   | 示例值                   |
| -------------------- | ---- | ------- | ---------------------------------------------------- | --------------------- |
| name                 | 是    | 数组（字符串） | 需要筛选的 metadata 名称                                    | `["category", "tag"]` |
| comparison\_operator | 是    | 字符串     | 比较操作符                                                | `contains`            |
| value                | 否    | 字符串     | 对比值，当操作符为 `empty`、`not empty`、`null`、`not null` 时可省略 | `"AI"`                |

支持的 `comparison_operator` 操作符：

* `contains`：包含某个值
* `not contains`：不包含某个值
* `start with`：以某个值开头
* `end with`：以某个值结尾
* `is`：等于某个值
* `is not`：不等于某个值
* `empty`：为空
* `not empty`：不为空
* `=`：等于
* `≠`：不等于
* `>`：大于
* `<`：小于
* `≥`：大于等于
* `≤`：小于等于
* `before`：在某个日期之前
* `after`：在某个日期之后

## 请求语法

```json theme={null}
POST <your-endpoint>/retrieval HTTP/1.1
-- 请求头
Content-Type: application/json
Authorization: Bearer your-api-key
-- 数据
{
    "knowledge_id": "your-knowledge-id",
    "query": "你的问题",
    "retrieval_setting":{
        "top_k": 2,
        "score_threshold": 0.5
    }
}
```

## 响应元素

如果操作成功，服务将返回 HTTP 200 响应。服务以 JSON 格式返回以下数据。

| 属性      | 是否必需 | 类型   | 描述          | 示例值 |
| ------- | ---- | ---- | ----------- | --- |
| records | 是    | 对象列表 | 从知识库查询的记录列表 | 见下文 |

`records` 属性是一个包含以下键的对象列表：

| 属性       | 是否必需 | 类型   | 描述                  | 示例值                  |
| -------- | ---- | ---- | ------------------- | -------------------- |
| content  | 是    | 字符串  | 包含知识库中数据源的文本块       | Dify：GenAI 应用程序的创新引擎 |
| score    | 是    | 浮点数  | 结果与查询的相关性分数，范围：0\~1 | 0.5                  |
| title    | 是    | 字符串  | 文档标题                | Dify 简介              |
| metadata | 否    | json | 包含数据源中文档的元数据属性及其值   | 见示例                  |

## 响应语法

```json theme={null}
HTTP/1.1 200
Content-type: application/json
{
    "records": [{
                    "metadata": {
                            "path": "s3://dify/knowledge.txt",
                            "description": "dify 知识文档"
                    },
                    "score": 0.98,
                    "title": "knowledge.txt",
                    "content": "这是外部知识的文档。"
            },
            {
                    "metadata": {
                            "path": "s3://dify/introduce.txt",
                            "description": "dify 介绍"
                    },
                    "score": 0.66,
                    "title": "introduce.txt",
                    "content": "GenAI 应用程序的创新引擎"
            }
    ]
}
```

## 错误

如果操作失败，服务将返回以下错误信息（JSON 格式）：

| 属性          | 是否必需 | 类型  | 描述       | 示例值                                              |
| ----------- | ---- | --- | -------- | ------------------------------------------------ |
| error\_code | 是    | 整数  | 错误代码     | 1001                                             |
| error\_msg  | 是    | 字符串 | API 异常描述 | 无效的 Authorization 头格式。预期格式为 `Bearer <api-key>`'。 |

`error_code` 属性有以下类型：

| 代码   | 描述                    |
| ---- | --------------------- |
| 1001 | 无效的 Authorization 头格式 |
| 1002 | 授权失败                  |
| 2001 | 知识库不存在                |

### HTTP 状态码

**AccessDeniedException**
由于缺少访问权限，请求被拒绝。请检查您的权限并重试。
HTTP 状态码：403

**InternalServerException**
发生内部服务器错误。请重试您的请求。
HTTP 状态码：500

## 开发示例

你可以通过以下视频了解如何开发外部知识库插件 —— 以 Llamacloud 为例。

<iframe src="https://www.youtube.com/embed/FaOzKZRS-2E" width="100%" height="315" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowFullScreen />

如需了解功能原理，请参考插件 [GitHub 地址](https://github.com/langgenius/dify-official-plugins/tree/main/extensions/llamacloud)。

<CardGroup cols="2">
  <Card title="编辑此页面" icon="pen-to-square" href="https://github.com/langgenius/dify-docs-mintlify/edit/main/zh-hans/guides/knowledge-base/api-documentation/external-knowledge-api-documentation.mdx">
    通过直接提交修改来帮助改进文档内容
  </Card>

  <Card title="提交问题" icon="github" href="https://github.com/langgenius/dify-docs-mintlify/issues/new?title=文档问题%3A%20nal-knowledge-api-documentat&body=%23%23%20问题描述%0A%3C%21--%20请简要描述您发现的问题%20--%3E%0A%0A%23%23%20页面链接%0Ahttps%3A%2F%2Fgithub.com%2Flanggenius%2Fdify-docs-mintlify%2Fblob%2Fmain%2Fzh-hans/guides/knowledge-base/api-documentation%2Fexternal-knowledge-api-documentation.mdx%0A%0A%23%23%20建议修改%0A%3C%21--%20如果有具体的修改建议，请在此说明%20--%3E%0A%0A%3C%21--%20感谢您对文档质量的关注！%20--%3E">
    发现错误或有改进建议？请提交问题反馈
  </Card>
</CardGroup>
