# OpenViking 深度集成文档 ## 概述 ZCLAW 桌面端已集成 OpenViking 记忆系统,支持三种运行模式: 1. **本地服务器模式**:自动管理本地 OpenViking 服务器(隐私优先,数据完全本地) 2. **远程模式**:连接到运行中的远程 OpenViking 服务器 3. **本地存储模式**:使用 localStorage 作为回退(无需外部依赖) **推荐**:对于注重隐私的用户,使用本地服务器模式,所有数据存储在 `~/.openviking/`。 ## OpenViking 架构说明 OpenViking 采用客户端-服务器架构: ``` ┌─────────────────────────────────────────────────────────────────┐ │ OpenViking 架构 │ │ │ │ ┌─────────────────┐ HTTP API ┌─────────────────┐ │ │ │ ov CLI │ ◄──────────────────► │ openviking- │ │ │ │ (Rust) │ │ server (Python) │ │ │ └─────────────────┘ └────────┬────────┘ │ │ │ │ │ ┌────────▼────────┐ │ │ │ SQLite + Vector │ │ │ │ ~/.openviking/ │ │ │ └─────────────────┘ │ └─────────────────────────────────────────────────────────────────┘ ``` **重要**:CLI 不能独立运行,必须与服务器配合使用。 ## ZCLAW 集成架构(本地模式) ``` ┌─────────────────────────────────────────────────────────────────┐ │ ZCLAW Desktop (Tauri + React) │ │ │ │ ┌────────────────────────────────────────────────────────────┐ │ │ │ React UI Layer │ │ │ │ ┌──────────────┐ ┌────────────────┐ │ │ │ │ │ MemoryPanel │ │ContextBuilder │ │ │ │ │ └──────┬───────┘ └───────┬────────┘ │ │ │ └─────────┼─────────────────┼─────────────────────────────────┘ │ │ │ │ │ │ ┌─────────▼─────────────────▼─────────────────────────────────┐ │ │ │ TypeScript Integration Layer │ │ │ │ ┌─────────────────┐ ┌──────────────────────────────────┐ │ │ │ │ │ VikingAdapter │ │ viking-server-manager │ │ │ │ │ │ (local mode) │ │ (auto-start local server) │ │ │ │ │ └────────┬────────┘ └──────────────────────────────────┘ │ │ │ └───────────┼──────────────────────────────────────────────────┘ │ │ │ │ │ ┌───────────▼──────────────────────────────────────────────────┐ │ │ │ Tauri Command Layer │ │ │ │ ┌──────────────────────────────────────────────────────────┐│ │ │ │ │ viking_server_start/stop/status/restart ││ │ │ │ │ (Rust: manages openviking-server process) ││ │ │ │ └──────────────────────────────────────────────────────────┘│ │ │ └──────────────────────────┬───────────────────────────────────┘ │ │ │ │ │ ┌──────────────────────────▼───────────────────────────────────┐ │ │ │ Storage Layer (LOCAL DATA ONLY) │ │ │ │ ┌──────────────────────────────────────────────────────────┐│ │ │ │ │ OpenViking Server (Python) ││ │ │ │ │ http://127.0.0.1:1933 ││ │ │ │ │ Data: ~/.openviking/ ││ │ │ │ │ - SQLite database ││ │ │ │ │ - Vector embeddings ││ │ │ │ │ - Configuration ││ │ │ │ └──────────────────────────────────────────────────────────┘│ │ │ └──────────────────────────────────────────────────────────────┘ │ └─────────────────────────────────────────────────────────────────┘ ``` ## 隐私保证 **本地模式下**: - ✅ 所有数据存储在 `~/.openviking/` 目录 - ✅ 服务器只监听 `127.0.0.1`(本地回环) - ✅ 无任何数据上传到远程服务器 - ✅ 向量嵌入通过 doubao API 生成(可选配置本地模型) ## 文件结构 ### Rust 后端 (`desktop/src-tauri/src/`) | 文件 | 功能 | |------|------| | `viking_commands.rs` | Tauri 命令封装,调用 OpenViking CLI | | `memory/mod.rs` | 记忆模块入口 | | `memory/extractor.rs` | LLM 驱动的会话记忆提取 | | `memory/context_builder.rs` | L0/L1/L2 分层上下文构建 | | `llm/mod.rs` | 多提供商 LLM 客户端 (doubao/OpenAI/Anthropic) | ### TypeScript 前端 (`desktop/src/lib/`) | 文件 | 功能 | |------|------| | `viking-adapter.ts` | 多模式适配器 (local/sidecar/remote) | | `viking-server-manager.ts` | 本地服务器管理(启动/停止/状态) | | `viking-client.ts` | OpenViking HTTP API 客户端 | | `viking-local.ts` | Tauri sidecar 客户端 | | `viking-memory-adapter.ts` | VikingAdapter → MemoryManager 桥接 | | `context-builder.ts` | 聊天上下文构建器 | ### Rust 后端 (`desktop/src-tauri/src/`) | 文件 | 功能 | |------|------| | `viking_server.rs` | **本地服务器管理** (启动/停止/状态检查) | | `viking_commands.rs` | Tauri 命令封装(调用 OpenViking CLI) | ### 二进制文件 (`desktop/src-tauri/binaries/`) | 文件 | 说明 | |------|------| | `ov-x86_64-pc-windows-msvc.exe` | Windows mock 二进制 (开发用) | | `README.md` | 获取真实二进制的说明 | ## L0/L1/L2 分层上下文加载 为了优化 Token 消耗,上下文构建采用三层加载策略: | 层级 | 名称 | Token 预算 | 策略 | |------|------|-----------|------| | L0 | Quick Scan | ~500 | 快速向量搜索,返回概览 | | L1 | Standard | ~2000 | 加载相关项的详细内容 | | L2 | Deep | ~3000 | 加载最相关项的完整内容 | ``` L0: find(query, limit=50) → 返回 URI + score + overview ↓ L1: read(uri, level=L1) → 返回详细内容 (score >= 0.5) ↓ L2: read(uri, level=L2) → 返回完整内容 (top 3) ``` ## LLM 记忆提取 会话结束后,LLM 自动分析并提取记忆: ```rust pub enum ExtractionCategory { UserPreference, // 用户偏好 UserFact, // 用户事实 AgentLesson, // Agent 经验教训 AgentPattern, // Agent 任务模式 Task, // 任务信息 } ``` ### 支持的 LLM 提供商 | 提供商 | Endpoint | 默认模型 | |--------|----------|----------| | doubao | https://ark.cn-beijing.volces.com/api/v3 | doubao-pro-32k | | openai | https://api.openai.com/v1 | gpt-4o | | anthropic | https://api.anthropic.com/v1 | claude-sonnet-4-20250514 | ## 使用方式 ### 1. 本地服务器模式 (推荐,隐私优先) ```typescript import { getVikingAdapter } from './lib/viking-adapter'; import { getVikingServerManager } from './lib/viking-server-manager'; // 获取服务器管理器 const serverManager = getVikingServerManager(); // 确保本地服务器运行 await serverManager.ensureRunning(); // 使用适配器(自动检测本地服务器) const viking = getVikingAdapter({ mode: 'auto' }); await viking.buildEnhancedContext(userMessage, agentId); // 检查服务器状态 const status = await serverManager.getStatus(); console.log(`Server running: ${status.running}, port: ${status.port}`); ``` ### 2. 自动模式 (智能检测) ```typescript const viking = getVikingAdapter(); // mode: 'auto' await viking.buildEnhancedContext(userMessage, agentId); ``` 自动检测顺序: 1. 尝试启动本地服务器 (local) 2. 检查 sidecar CLI (sidecar) 3. 连接远程服务器 (remote) 4. 回退到 localStorage ### 3. 强制本地模式 ```typescript const viking = getVikingAdapter({ mode: 'local' }); ``` ### 4. 强制 Sidecar 模式 ```typescript const viking = getVikingAdapter({ mode: 'sidecar' }); ``` ### 5. 使用 MemoryManager 接口 ```typescript import { getVikingMemoryAdapter } from './lib/viking-memory-adapter'; const adapter = getVikingMemoryAdapter({ enabled: true, mode: 'auto', fallbackToLocal: true }); // 使用与 agent-memory.ts 相同的接口 await adapter.save(entry); await adapter.search(query); await adapter.stats(agentId); ``` ## 配置 ### 本地服务器配置 (Tauri 命令) 通过 Rust 后端管理本地 OpenViking 服务器: ```typescript import { invoke } from '@tauri-apps/api/core'; // 获取服务器状态 const status = await invoke('viking_server_status'); // 启动服务器 await invoke('viking_server_start', { config: { port: 1933, dataDir: '', // 使用默认 ~/.openviking/workspace configFile: '' // 使用默认 ~/.openviking/ov.conf } }); // 停止服务器 await invoke('viking_server_stop'); // 重启服务器 await invoke('viking_server_restart'); ``` ### Tauri Sidecar 配置 (`tauri.conf.json`) 仅在 sidecar 模式下需要: ```json { "bundle": { "externalBin": ["binaries/ov"] } } ``` ### 环境变量 | 变量 | 说明 | |------|------| | `ZCLAW_VIKING_BIN` | OpenViking CLI 二进制路径 (sidecar 模式) | | `ZCLAW_VIKING_SERVER_BIN` | OpenViking 服务器二进制路径 (本地模式) | | `VIKING_SERVER_URL` | 远程服务器地址 (远程模式) | | `OPENVIKING_CONFIG_FILE` | OpenViking 配置文件路径 | ## 安装 OpenViking (本地模式) ### 系统要求 | 组件 | 要求 | 说明 | |------|------|------| | Python | 3.10 - 3.12 | ⚠️ Python 3.13+ 可能没有预编译 wheel | | Go | 1.22+ | 可选,用于从源码构建 AGFS 组件 | | C++ 编译器 | GCC 9+ / Clang 11+ / MSVC | 可选,从源码构建时需要 | ### ⚠️ Windows 安装注意事项 **如果使用 Python 3.13+**,预编译 wheel 可能不可用。推荐方案: 1. **安装 Python 3.12**(推荐): - 从 [python.org](https://www.python.org/downloads/) 下载 Python 3.12 - 或使用 `py -3.12 -m pip install openviking` 2. **使用 conda 创建 3.12 环境**: ```bash conda create -n openviking python=3.12 conda activate openviking pip install openviking ``` 3. **使用 WSL2 + Linux**: ```bash wsl --install -d Ubuntu # 在 WSL 中 pip install openviking ``` ### 快速安装 (推荐) ZCLAW 会自动管理本地 OpenViking 服务器。你只需要安装 OpenViking Python 包: ```bash # 使用 pip 安装 (Python 3.10-3.12) pip install openviking --upgrade # 验证安装 openviking-server --version ``` ### 安装验证 ```bash # 检查 OpenViking 是否正确安装 python -c "import openviking; print(openviking.__version__)" # 检查服务器命令是否可用 openviking-server --help ``` ### 自动服务器管理 ZCLAW 的 `viking-server-manager.ts` 会自动: 1. 检测本地服务器是否运行 2. 如未运行,自动启动 `openviking-server` 3. 监控服务器健康状态 4. 在应用退出时清理进程 ```typescript import { getVikingServerManager } from './lib/viking-server-manager'; const manager = getVikingServerManager(); // 确保服务器运行(自动启动如果需要) await manager.ensureRunning(); // 获取服务器状态 const status = await manager.getStatus(); // { running: true, port: 1933, pid: 12345, dataDir: '~/.openviking/workspace' } // 获取服务器 URL const url = manager.getServerUrl(); // 'http://127.0.0.1:1933' ``` ### 手动启动服务器 (可选) 如果你希望手动控制服务器: ```bash # 前台运行 openviking-server --host 127.0.0.1 --port 1933 # 后台运行 (Linux/macOS) nohup openviking-server > ~/.openviking/server.log 2>&1 & # 后台运行 (Windows PowerShell) Start-Process -NoNewWindow openviking-server -RedirectStandardOutput "$env:USERPROFILE\.openviking\server.log" ``` ### 配置文件 创建 `~/.openviking/ov.conf`: ```json { "storage": { "workspace": "/home/your-name/openviking_workspace" }, "embedding": { "dense": { "api_base": "https://ark.cn-beijing.volces.com/api/v3", "api_key": "your-api-key", "provider": "volcengine", "dimension": 1024, "model": "doubao-embedding-vision-250615" } }, "vlm": { "api_base": "https://ark.cn-beijing.volces.com/api/v3", "api_key": "your-api-key", "provider": "volcengine", "model": "doubao-seed-2-0-pro-260215" } } ``` 设置环境变量: ```bash # Linux/macOS export OPENVIKING_CONFIG_FILE=~/.openviking/ov.conf # Windows PowerShell $env:OPENVIKING_CONFIG_FILE = "$HOME/.openviking/ov.conf" ``` ## 测试 ### Rust 测试 ```bash cd desktop/src-tauri cargo test ``` 当前测试覆盖: - `test_provider_configs` - LLM 提供商配置 - `test_llm_client_creation` - LLM 客户端创建 - `test_extraction_config_default` - 提取配置默认值 - `test_uri_generation` - URI 生成 - `test_estimate_tokens` - Token 估算 - `test_extract_category` - 分类提取 - `test_context_builder_config_default` - 上下文构建器配置 - `test_status_unavailable_without_cli` - 无 CLI 时的状态 ### TypeScript 测试 ```bash cd desktop pnpm vitest run tests/desktop/memory*.test.ts ``` ## 火山引擎 (Volcengine) 配置 ### 激活 Embedding 模型 **重要**:火山引擎的 Embedding 模型需要在控制台单独激活。 1. **登录火山引擎控制台**: https://console.volcengine.com/ark 2. **激活 Embedding 模型**: - 进入「模型推理」→「模型服务」 - 搜索并激活以下模型之一: - `Doubao-Embedding` (推荐,1024 维) - `Doubao-Embedding-Large` (2048 维) 3. **获取 Endpoint ID**: - 激活后,复制模型的 **Endpoint ID** - 格式类似:`ep-xxxxxxxxxxxx` 4. **更新配置文件**: 使用 Endpoint ID(推荐): ```json { "embedding": { "dense": { "api_base": "https://ark.cn-beijing.volces.com/api/v3", "api_key": "your-api-key", "provider": "volcengine", "model": "ep-xxxxxxxxxxxx", "dimension": 1024 } } } ``` 或使用模型名称(需要在控制台激活): ```json { "embedding": { "dense": { "api_base": "https://ark.cn-beijing.volces.com/api/v3", "api_key": "your-api-key", "provider": "volcengine", "model": "doubao-embedding", "dimension": 1024 } } } ``` ### 常见错误 | 错误 | 原因 | 解决方案 | |------|------|----------| | `ModelNotOpen` | 模型未激活 | 在控制台激活对应的 Embedding 模型 | | `InvalidEndpointOrModel.NotFound` | Endpoint ID 不存在 | 检查 Endpoint ID 是否正确 | | `404 Not Found` | API 路径错误 | 确认 `api_base` 为 `https://ark.cn-beijing.volces.com/api/v3` | ### 测试 Embedding 配置 ```bash # 启动服务器后,测试向量搜索 curl -X POST http://127.0.0.1:1933/api/v1/search/search \ -H "Content-Type: application/json" \ -d '{"query": "test query", "limit": 5}' ``` 成功响应: ```json {"status":"ok","result":[],"error":null} ``` 失败响应(需要激活模型): ```json {"status":"error","error":{"message":"Volcengine embedding failed: ModelNotOpen..."}} ``` ## 故障排除 ### Q: OpenViking CLI not found 确保 `ov-x86_64-pc-windows-msvc.exe` 存在于 `binaries/` 目录,或设置 `ZCLAW_VIKING_BIN` 环境变量。 ### Q: Sidecar 启动失败 检查 Tauri 控制台日志,确认 sidecar 二进制权限正确。 ### Q: 记忆未保存 1. 检查 LLM API 配置 (doubao/OpenAI/Anthropic) 2. 确认 `VIKING_SERVER_URL` 正确 (remote 模式) 3. 检查浏览器控制台的网络请求 ## 迁移路径 从现有 localStorage 实现迁移到 OpenViking: 1. 导出现有记忆:`getMemoryManager().exportToMarkdown(agentId)` 2. 切换到 OpenViking 模式 3. 导入记忆到 OpenViking (通过 CLI 或 API) ## 参考资料 - [OpenViking GitHub](https://github.com/anthropics/openviking) - [ZCLAW_AGENT_INTELLIGENCE_EVOLUTION.md](../docs/ZCLAW_AGENT_INTELLIGENCE_EVOLUTION.md) - [ZCLAW_OPENVIKING_INTEGRATION_PLAN.md](../docs/ZCLAW_OPENVIKING_INTEGRATION_PLAN.md)