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

# 使用 Milvus 存储

`milvus` 后端把知识片段的 embedding 写入 Milvus collection，既可连接 Milvus 或 Zilliz Cloud，也可使用本地 Milvus Lite 文件。该后端从 VeADK 1.0.3 开始提供。

## 依赖

```bash lines theme={null}
pip install "veadk-python[extensions]"
```

## 使用 Milvus Lite

本地验证时，可以把 `DATABASE_MILVUS_URI` 指向 Milvus Lite 数据文件，并配置 embedding 模型：

```bash lines theme={null}
export DATABASE_MILVUS_URI="./data/product_docs.db"
export MODEL_EMBEDDING_API_KEY="your-ark-api-key"
```

首次运行会创建数据文件；再次使用相同文件和 collection 名称时，可以检索已写入的内容。

## 使用示例

```python lines theme={null}
from veadk import Agent
from veadk.knowledgebase import KnowledgeBase

kb = KnowledgeBase(
    backend="milvus",
    index="product_docs",
    backend_config={
        "index": "product_docs",
        "milvus_config": {
            "uri": "https://milvus.example.com",
            "token": "填入 Milvus Token",
            "db_name": "default",
        },
    },
)
kb.add_from_directory("./docs")

agent = Agent(knowledgebase=kb)
```

## 参数

| 参数 | 类型 | 默认值 | 说明 |
| - | - | - | - |
| `index` | `str` | 无 | Milvus collection 名称。必须以字母或下划线开头，只能包含字母、数字和下划线，最长 255 个字符。 |
| `milvus_config` | `MilvusConfig` | 从 `DATABASE_MILVUS_*` 读取 | Milvus 连接与 collection 配置。 |
| `embedding_config` | `EmbeddingModelConfig` | 从 `MODEL_EMBEDDING_*` 读取 | 用于生成知识片段向量的 embedding 模型配置。 |

### Milvus 配置

| 配置项 | 环境变量 | 类型 | 默认值 | 说明 |
| - | - | - | - | - |
| `uri` | `DATABASE_MILVUS_URI` | `str` | `""` | 远程 Milvus URI 或 Milvus Lite 本地文件路径，必填。 |
| `token` | `DATABASE_MILVUS_TOKEN` | `str` | `""` | Milvus Token；优先于用户名和密码。 |
| `user` | `DATABASE_MILVUS_USER` | `str` | `""` | 用户名，与 `password` 配合使用。 |
| `password` | `DATABASE_MILVUS_PASSWORD` | `str` | `""` | 密码。 |
| `db_name` | `DATABASE_MILVUS_DB_NAME` | `str` | `default` | 数据库名称。 |
| `overwrite` | `DATABASE_MILVUS_OVERWRITE` | `bool` | `false` | 初始化时是否覆盖同名 collection。 |
| `timeout` | `DATABASE_MILVUS_TIMEOUT` | `float \| None` | `None` | 请求超时秒数。 |
| `output_fields` | `DATABASE_MILVUS_OUTPUT_FIELDS` | `list[str] \| str` | 空 | 需要随检索结果返回的字段；环境变量可使用逗号分隔或 JSON 数组。 |

<Warning>
  启用 `overwrite` 可能清除同名 collection 中的现有数据。仅在确认可以重建知识库时使用。
</Warning>
