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

# 向量存储

> 向量存储 — PostgreSQL pgvector、用户级 Embedding 配置

Zeus 使用 **PostgreSQL pgvector** 作为向量存储引擎，通过 `langchain-postgres` 的 `PGVector` 封装，同时为 Knowledge Base（RAG 检索）和 Memory（长期记忆）提供统一的向量存储服务。

***

## 存储架构

```mermaid theme={null}
graph TD
    subgraph Callers["调用方"]
        rag["RAGService<br/>知识库检索"]
        doc["DocumentService<br/>文档入库"]
        mem["MemoryService<br/>记忆存储/检索"]
    end

    subgraph VectorStore["VectorStore (单例)"]
        factory["create_embeddings(user_id)<br/>用户级 Embedding 工厂"]
        instance["PGVector<br/>collection: knowledge / memory"]
    end

    subgraph PG["PostgreSQL"]
        pgvector["pgvector 扩展<br/>向量索引 + 余弦相似度"]
        metadata["元数据过滤<br/>user_id, knowledge_base_id, ..."]
    end

    rag --> VectorStore
    doc --> VectorStore
    mem --> VectorStore
    VectorStore --> PG
```

### Collection 设计

| Collection  | 用途      | 过滤字段                                                         |
| ----------- | ------- | ------------------------------------------------------------ |
| `knowledge` | 知识库文档分块 | `user_id`, `knowledge_base_id`, `document_id`, `chunk_index` |
| `memory`    | 用户长期记忆  | `user_id`, `scope`, `project_id`, `session_id`               |

每个 collection 通过 `VectorStore.get_instance(collection_name, embeddings)` 获取，同一 collection + embeddings 组合共享单例。

***

## Embedding 配置

Zeus 支持 **用户级别** 的 Embedding 配置，不同用户可使用不同的 Embedding 模型。配置按以下优先级查找：

```mermaid theme={null}
graph TD
    start["create_embeddings(user_id)"] --> user_check{"用户数据库配置?"}
    user_check -->|"有"| user_config["使用用户配置的<br/>API Key / Base URL / Model"]
    user_check -->|"无"| env_check{"环境变量配置?"}
    env_check -->|"有"| env_config["使用环境变量<br/>OPENAI_API_KEY / OPENAI_BASE_URL"]
    env_check -->|"无"| system_check{"Next.js API 系统默认?"}
    system_check -->|"有"| system_config["使用系统默认配置"]
    system_check -->|"无"| fail["返回 None<br/>(向量功能不可用)"]

    user_config --> embeddings["OpenAIEmbeddings 实例"]
    env_config --> embeddings
    system_config --> embeddings
```

### 优先级

| 优先级    | 来源      | 获取方式                                                                                  |
| ------ | ------- | ------------------------------------------------------------------------------------- |
| 1 (最高) | 用户数据库配置 | `GET /api/config/embedding`（X-User-Id header），取 `isDefault=true` 且 `enabled=true` 的配置 |
| 2      | 环境变量    | `OPENAI_API_KEY` + `OPENAI_BASE_URL` + `EMBEDDING_MODEL`                              |
| 3      | 系统默认    | Next.js API 的 system embedding 配置                                                     |

### 支持的模型

任何兼容 OpenAI Embeddings API 格式的模型均可使用：

| 模型                       | 说明                    |
| ------------------------ | --------------------- |
| `text-embedding-3-small` | OpenAI 默认，1536 维，性价比高 |
| `text-embedding-3-large` | OpenAI 高精度，3072 维     |
| BGE 系列                   | 通过兼容 API 使用           |
| Jina Embeddings          | 通过兼容 API 使用           |
| 自部署模型                    | 通过自定义 `base_url` 接入   |

***

## 核心操作

### 写入

```python theme={null}
# 文档处理时写入
docs_to_add = [
    LCDocument(
        page_content="分块内容...",
        metadata={
            "user_id": "user_123",
            "knowledge_base_id": "kb_456",
            "document_id": "doc_789",
            "chunk_index": 0,
            "source": "example.pdf",
            "page": 1,
            "created_at": "2025-01-01T00:00:00",
        }
    )
]
chunk_ids = vectorstore.add_documents(docs_to_add)
```

### 检索

```python theme={null}
# 向量相似度搜索 + 元数据过滤
results = vectorstore.similarity_search_with_score(
    query="如何配置 Zeus?",
    k=5,
    filter={
        "user_id": "user_123",
        "knowledge_base_id": "kb_456",
    },
)
```

### 删除

```python theme={null}
# 删除文档的所有分块
vectorstore.delete(filter={"document_id": "doc_789"})

# 删除知识库的所有数据
vectorstore.delete(filter={"knowledge_base_id": "kb_456"})
```
