Self-evolving Context Database for AI Agents. Unify Agent Memory, Knowledge RAG and Skills.
Python agent-contextagent-memoryagent-pluginsagentic-ragcontext-databasedsh-pluginknowledge-basememorymemory-managementself-evolvingvector-database
docs: Add basic usage example and Chinese documentation for examples (#979)
冰水泡枸杞2cc3761ee771
diff --git a/examples/basic-usage/README.md b/examples/basic-usage/README.mdnew file mode 100644index 000000000..018165893--- /dev/null+++ b/examples/basic-usage/README.md@@ -0,0 +1,301 @@+# Basic Usage Example: Getting Started with OpenViking Python SDK++This example demonstrates the core features of OpenViking using the Python SDK. It covers the essential operations for building AI Agent applications with persistent context management.++## What You'll Learn++- **Initializing OpenViking**: Embedded mode vs HTTP client mode+- **Adding Resources**: URLs, files, and directories+- **Browsing the Virtual Filesystem**: Using `ls`, `tree`, `glob`+- **Semantic Search**: Finding relevant context with `find` and `search`+- **Tiered Context Loading**: Using L0 (abstract), L1 (overview), L2 (full content)+- **Session Management**: Storing and recalling conversation memories++## Prerequisites++1. **Python 3.10+**+2. **OpenViking installed**:+ ```bash+ pip install openviking --upgrade+ ```+3. **Configuration file** at `~/.openviking/ov.conf` (see [Configuration](#configuration) below)++## Quick Start++### 1. Run the Example Script++```bash+# Clone the repository+git clone https://github.com/volcengine/OpenViking.git+cd OpenViking/examples/basic-usage++# Run the basic usage example+python basic_usage.py+```++### 2. Expected Output++```+=== OpenViking Basic Usage Example ===++1. Initializing OpenViking...+ Status: healthy++2. Adding a resource (URL)...+ Root URI: viking://resources/raw.githubusercontent.com/volcengine/OpenViking/refs/heads/main/README.md+ Files indexed: 1++3. Browsing the virtual filesystem...+ viking://resources/raw.githubusercontent.com/volcengine/OpenViking/refs/heads/main/+ └── README.md++4. Waiting for semantic processing...++5. Tiered Context Loading:+ L0 (Abstract): OpenViking is an open-source Context Database designed specifically for AI Agents...++ L1 (Overview):+ [Contains key points and usage scenarios]++6. Semantic Search:+ Query: "what is openviking"+ Results:+ - viking://resources/.../README.md (score: 0.8523)++7. Content search (grep):+ Pattern: "Agent"+ Found 15 matches++8. Closing OpenViking...+ Done!+```++## Code Walkthrough++### Initialization++OpenViking supports two modes:++**Embedded Mode** (default for local development):+```python+import openviking as ov++client = ov.OpenViking(path="./data")+client.initialize()+```++**HTTP Client Mode** (connect to remote server):+```python+import openviking as ov++client = ov.SyncHTTPClient(url="http://localhost:1933")+```++### Adding Resources++Add URLs, local files, or directories:++```python+# Add a URL+result = client.add_resource(+ path="https://example.com/documentation",+ wait=True # Wait for semantic processing+)++# Add a local file+result = client.add_resource(+ path="/path/to/your/document.pdf"+)++# Add a directory (repository)+result = client.add_resource(+ path="/path/to/your/project",+ instruction="This is a Python web application"+)+```++### Browsing the Filesystem++OpenViking uses a virtual filesystem paradigm with `viking://` URIs:++```python+# List directory contents+files = client.ls("viking://resources/")++# Show directory tree+tree = client.tree("viking://resources/my-project", level_limit=3)++# Find files by pattern+matches = client.glob("**/*.md", uri="viking://resources/my-project")+```++### Semantic Search++Find context using natural language queries:++```python+# Quick semantic search+results = client.find(+ query="how to handle API authentication",+ target_uri="viking://resources/my-project",+ limit=5+)++# Advanced search with intent analysis+results = client.search(+ query="database connection configuration and error handling",+ target_uri="viking://resources/",+ limit=10+)+```++### Tiered Context Loading++OpenViking processes content into three layers for efficient retrieval:++```python+uri = "viking://resources/my-project/docs/api.md"++# L0: Quick abstract (~100 tokens)+abstract = client.abstract(uri)++# L1: Overview with key points (~2k tokens)+overview = client.overview(uri)++# L2: Full content+content = client.read(uri)+```++### Session Management++Store conversation memories for long-term recall:++```python+# Create a session+session_info = client.create_session()+session_id = session_info["session_id"]++# Add conversation messages+client.add_message(session_id, "user", "I prefer TypeScript over JavaScript")+client.add_message(session_id, "assistant", "Noted! I'll use TypeScript in your projects.")++# Commit session to extract long-term memories+client.commit_session(session_id)++# Later, recall relevant memories+memories = client.find(+ query="user programming preferences",+ target_uri="viking://user/memories/"+)+```++## Configuration++Create `~/.openviking/ov.conf` with your model provider settings:++```json+{+ "storage": {+ "workspace": "~/.openviking/data"+ },+ "embedding": {+ "dense": {+ "provider": "openai",+ "api_key": "your-api-key",+ "model": "text-embedding-3-large",+ "dimension": 3072+ }+ },+ "vlm": {+ "provider": "openai",+ "api_key": "your-api-key",+ "model": "gpt-4o"+ }+}+```++> **Tip**: You can also use Volcengine (Doubao), Azure OpenAI, or LiteLLM (supports Anthropic, DeepSeek, Gemini, etc.). See the main README for provider-specific configuration.++## Use Cases++### Building a Documentation-Aware Agent++```python+import openviking as ov++class DocumentationAgent:+ def __init__(self):+ self.ov = ov.OpenViking(path="./data")+ self.ov.initialize()++ def ingest_docs(self, doc_path: str):+ """Add documentation to the knowledge base."""+ self.ov.add_resource(doc_path, wait=True)++ def answer(self, question: str) -> str:+ """Find relevant documentation and answer."""+ results = self.ov.find(question, limit=3)++ context = []+ for r in results.resources:+ content = self.ov.read(r.uri)+ context.append(content)++ # Use context with your LLM to generate answer+ return context++# Usage+agent = DocumentationAgent()+agent.ingest_docs("https://docs.python.org/3/")+agent.ingest_docs("/path/to/your/project/docs")+```++### Creating a Memory-Aware Assistant++```python+import openviking as ov++class MemoryAssistant:+ def __init__(self, user_id: str):+ self.ov = ov.SyncHTTPClient(url="http://localhost:1933")+ self.user_id = user_id+ self.session_id = None++ def start_conversation(self):+ """Start a new conversation session."""+ session = self.ov.create_session()+ self.session_id = session["session_id"]++ def remember(self, user_input: str, assistant_response: str):+ """Store conversation turn."""+ self.ov.add_message(self.session_id, "user", user_input)+ self.ov.add_message(self.session_id, "assistant", assistant_response)++ def recall(self, query: str) -> list:+ """Recall relevant memories."""+ return self.ov.find(query, target_uri="viking://user/memories/")++ def end_conversation(self):+ """Extract long-term memories from session."""+ self.ov.commit_session(self.session_id)+```++## Next Steps++- **[OpenClaw Plugin](../openclaw-plugin/)**: Integrate with OpenClaw AI assistant+- **[Claude Memory Plugin](../claude-memory-plugin/)**: Use with Claude Code+- **[OpenCode Memory Plugin](../opencode-memory-plugin/)**: Integrate with OpenCode+- **[Skills Examples](../skills/)**: CLI-based search and management skills++## Troubleshooting++| Issue | Solution |+|-------|----------|+| `ImportError: pyagfs not found` | Run: `pip install -e third_party/agfs/agfs-sdk/python` from source |+| `Connection refused` | Ensure OpenViking server is running: `openviking-server` |+| `API key error` | Check your `~/.openviking/ov.conf` configuration |+| `Slow semantic processing` | Wait for `wait_processed()` or use `add_resource(..., wait=True)` |++## License++Apache License 2.0\ No newline at end of filediff --git a/examples/basic-usage/README_CN.md b/examples/basic-usage/README_CN.mdnew file mode 100644index 000000000..717ffa5e8--- /dev/null+++ b/examples/basic-usage/README_CN.md@@ -0,0 +1,301 @@+# 基础使用示例:OpenViking Python SDK 快速入门++本示例演示如何使用 Python SDK 操作 OpenViking 的核心功能,涵盖构建 AI 智能体应用所需的基本操作。++## 你将学到什么++- **初始化 OpenViking**:嵌入式模式与 HTTP 客户端模式+- **添加资源**:URL、文件和目录+- **浏览虚拟文件系统**:使用 `ls`、`tree`、`glob`+- **语义搜索**:使用 `find` 和 `search` 查找相关上下文+- **分层上下文加载**:L0(摘要)、L1(概览)、L2(完整内容)+- **会话管理**:存储和召回对话记忆++## 前置条件++1. **Python 3.10+**+2. **安装 OpenViking**:+ ```bash+ pip install openviking --upgrade+ ```+3. **配置文件** 位于 `~/.openviking/ov.conf`(见下方[配置说明](#配置说明))++## 快速开始++### 1. 运行示例脚本++```bash+# 克隆仓库+git clone https://github.com/volcengine/OpenViking.git+cd OpenViking/examples/basic-usage++# 运行基础使用示例+python basic_usage.py+```++### 2. 预期输出++```+=== OpenViking 基础使用示例 ===++1. 初始化 OpenViking...+ 状态: healthy++2. 添加资源 (URL)...+ 根 URI: viking://resources/raw.githubusercontent.com/volcengine/OpenViking/refs/heads/main/README.md+ 已索引文件: 1++3. 浏览虚拟文件系统...+ viking://resources/raw.githubusercontent.com/volcengine/OpenViking/refs/heads/main/+ └── README.md++4. 等待语义处理...++5. 分层上下文加载:+ L0 (摘要): OpenViking 是专为 AI 智能体设计的开源上下文数据库...++ L1 (概览):+ [包含核心要点和使用场景]++6. 语义搜索:+ 查询: "what is openviking"+ 结果:+ - viking://resources/.../README.md (得分: 0.8523)++7. 内容搜索 (grep):+ 模式: "Agent"+ 找到 15 处匹配++8. 关闭 OpenViking...+ 完成!+```++## 代码详解++### 初始化++OpenViking 支持两种模式:++**嵌入式模式**(本地开发默认):+```python+import openviking as ov++client = ov.OpenViking(path="./data")+client.initialize()+```++**HTTP 客户端模式**(连接远程服务器):+```python+import openviking as ov++client = ov.SyncHTTPClient(url="http://localhost:1933")+```++### 添加资源++添加 URL、本地文件或目录:++```python+# 添加 URL+result = client.add_resource(+ path="https://example.com/documentation",+ wait=True # 等待语义处理完成+)++# 添加本地文件+result = client.add_resource(+ path="/path/to/your/document.pdf"+)++# 添加目录(代码仓库)+result = client.add_resource(+ path="/path/to/your/project",+ instruction="这是一个 Python Web 应用"+)+```++### 浏览文件系统++OpenViking 使用 `viking://` URI 的虚拟文件系统范式:++```python+# 列出目录内容+files = client.ls("viking://resources/")++# 显示目录树+tree = client.tree("viking://resources/my-project", level_limit=3)++# 按模式查找文件+matches = client.glob("**/*.md", uri="viking://resources/my-project")+```++### 语义搜索++使用自然语言查询查找上下文:++```python+# 快速语义搜索+results = client.find(+ query="如何处理 API 认证",+ target_uri="viking://resources/my-project",+ limit=5+)++# 高级搜索(带意图分析)+results = client.search(+ query="数据库连接配置和错误处理",+ target_uri="viking://resources/",+ limit=10+)+```++### 分层上下文加载++OpenViking 将内容处理为三个层次,实现高效检索:++```python+uri = "viking://resources/my-project/docs/api.md"++# L0: 快速摘要(约 100 tokens)+abstract = client.abstract(uri)++# L1: 概览(约 2k tokens,包含核心要点)+overview = client.overview(uri)++# L2: 完整内容+content = client.read(uri)+```++### 会话管理++存储对话记忆以实现长期召回:++```python+# 创建会话+session_info = client.create_session()+session_id = session_info["session_id"]++# 添加对话消息+client.add_message(session_id, "user", "我更喜欢 TypeScript 而不是 JavaScript")+client.add_message(session_id, "assistant", "好的!我会在你的项目中使用 TypeScript。")++# 提交会话以提取长期记忆+client.commit_session(session_id)++# 之后召回相关记忆+memories = client.find(+ query="用户编程偏好",+ target_uri="viking://user/memories/"+)+```++## 配置说明++创建 `~/.openviking/ov.conf` 配置文件:++```json+{+ "storage": {+ "workspace": "~/.openviking/data"+ },+ "embedding": {+ "dense": {+ "provider": "openai",+ "api_key": "your-api-key",+ "model": "text-embedding-3-large",+ "dimension": 3072+ }+ },+ "vlm": {+ "provider": "openai",+ "api_key": "your-api-key",+ "model": "gpt-4o"+ }+}+```++> **提示**:你也可以使用火山引擎(豆包)、Azure OpenAI 或 LiteLLM(支持 Anthropic、DeepSeek、Gemini 等)。详见主 README 的提供商配置说明。++## 应用场景++### 构建文档感知智能体++```python+import openviking as ov++class DocumentationAgent:+ def __init__(self):+ self.ov = ov.OpenViking(path="./data")+ self.ov.initialize()++ def ingest_docs(self, doc_path: str):+ """将文档添加到知识库"""+ self.ov.add_resource(doc_path, wait=True)++ def answer(self, question: str) -> str:+ """查找相关文档并回答"""+ results = self.ov.find(question, limit=3)++ context = []+ for r in results.resources:+ content = self.ov.read(r.uri)+ context.append(content)++ # 使用上下文和 LLM 生成回答+ return context++# 使用+agent = DocumentationAgent()+agent.ingest_docs("https://docs.python.org/3/")+agent.ingest_docs("/path/to/your/project/docs")+```++### 创建记忆感知助手++```python+import openviking as ov++class MemoryAssistant:+ def __init__(self, user_id: str):+ self.ov = ov.SyncHTTPClient(url="http://localhost:1933")+ self.user_id = user_id+ self.session_id = None++ def start_conversation(self):+ """开始新的对话会话"""+ session = self.ov.create_session()+ self.session_id = session["session_id"]++ def remember(self, user_input: str, assistant_response: str):+ """存储对话轮次"""+ self.ov.add_message(self.session_id, "user", user_input)+ self.ov.add_message(self.session_id, "assistant", assistant_response)++ def recall(self, query: str) -> list:+ """召回相关记忆"""+ return self.ov.find(query, target_uri="viking://user/memories/")++ def end_conversation(self):+ """从会话中提取长期记忆"""+ self.ov.commit_session(self.session_id)+```++## 下一步++- **[OpenClaw 插件](../openclaw-plugin/)**:与 OpenClaw AI 助手集成+- **[Claude 记忆插件](../claude-memory-plugin/)**:在 Claude Code 中使用+- **[OpenCode 记忆插件](../opencode-memory-plugin/)**:与 OpenCode 集成+- **[技能示例](../skills/)**:基于 CLI 的搜索和管理技能++## 常见问题++| 问题 | 解决方案 |+|------|---------|+| `ImportError: pyagfs not found` | 从源码运行:`pip install -e third_party/agfs/agfs-sdk/python` |+| `Connection refused` | 确保 OpenViking 服务器正在运行:`openviking-server` |+| `API key error` | 检查 `~/.openviking/ov.conf` 配置 |+| `语义处理缓慢` | 等待 `wait_processed()` 或使用 `add_resource(..., wait=True)` |++## 许可证++Apache License 2.0\ No newline at end of filediff --git a/examples/basic-usage/basic_usage.py b/examples/basic-usage/basic_usage.pynew file mode 100644index 000000000..98df833b0--- /dev/null+++ b/examples/basic-usage/basic_usage.py@@ -0,0 +1,296 @@+#!/usr/bin/env python3+"""+OpenViking Basic Usage Example++This script demonstrates the core features of OpenViking:+1. Initialization (embedded mode and HTTP client mode)+2. Adding resources (URLs, files, directories)+3. Browsing the virtual filesystem+4. Semantic search and retrieval+5. Tiered context loading (L0/L1/L2)+6. Session management for memory++Requirements:+- pip install openviking --upgrade+- Configuration file at ~/.openviking/ov.conf+"""++import os+import sys+import time++# Add parent directory to path for local development+sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))+++def main():+ print("=" * 60)+ print("OpenViking Basic Usage Example")+ print("=" * 60)+ print()++ # ============================================================+ # 1. Initialization+ # ============================================================+ print("1. Initializing OpenViking...")+ print("-" * 40)++ try:+ import openviking as ov+ except ImportError as e:+ print(f" Error: Failed to import openviking: {e}")+ print(" Please install: pip install openviking --upgrade")+ sys.exit(1)++ # Embedded mode (local development)+ # Option A: Embedded mode with local path+ client = ov.OpenViking(path="./data")++ # Option B: HTTP client mode (connect to remote server)+ # client = ov.SyncHTTPClient(url="http://localhost:1933")++ try:+ client.initialize()+ print(" Client initialized successfully")++ # Check health status+ if client.is_healthy():+ print(" Status: healthy")+ else:+ print(" Warning: Some components may not be healthy")++ except Exception as e:+ print(f" Error during initialization: {e}")+ print(" Make sure you have configured ~/.openviking/ov.conf")+ sys.exit(1)++ print()++ # ============================================================+ # 2. Adding Resources+ # ============================================================+ print("2. Adding a resource (URL)...")+ print("-" * 40)++ try:+ # Add a URL resource+ result = client.add_resource(+ path="https://raw.githubusercontent.com/volcengine/OpenViking/refs/heads/main/README.md",+ wait=False # Non-blocking, process in background+ )++ root_uri = result.get("root_uri", "")+ print(f" Root URI: {root_uri}")++ # Get the file count+ files = client.ls(root_uri)+ print(f" Files indexed: {len(files)}")++ except Exception as e:+ print(f" Error adding resource: {e}")+ root_uri = ""++ print()++ # ============================================================+ # 3. Browsing the Virtual Filesystem+ # ============================================================+ print("3. Browsing the virtual filesystem...")+ print("-" * 40)++ if root_uri:+ try:+ # List directory contents+ print(f" Directory listing:")+ files = client.ls(root_uri, simple=True)+ for f in files[:5]: # Show first 5 files+ print(f" - {f}")++ # Show tree structure+ print(f"\n Tree view:")+ tree = client.tree(root_uri, level_limit=2)+ print_tree(tree, indent=" ")++ except Exception as e:+ print(f" Error browsing filesystem: {e}")++ print()++ # ============================================================+ # 4. Waiting for Semantic Processing+ # ============================================================+ print("4. Waiting for semantic processing...")+ print("-" * 40)++ try:+ # Wait for all async operations to complete+ status = client.wait_processed(timeout=60)+ print(f" Processing complete: {status}")+ except Exception as e:+ print(f" Note: {e}")+ print(" Continuing without waiting...")++ print()++ # ============================================================+ # 5. Tiered Context Loading+ # ============================================================+ print("5. Tiered Context Loading (L0/L1/L2):")+ print("-" * 40)++ if root_uri:+ try:+ # L0: Abstract (quick summary ~100 tokens)+ print(" L0 (Abstract):")+ abstract = client.abstract(root_uri)+ if abstract:+ # Show first 200 characters+ preview = abstract[:200] + "..." if len(abstract) > 200 else abstract+ print(f" {preview}")+ else:+ print(" (Not available yet)")++ print()++ # L1: Overview (key points ~2k tokens)+ print(" L1 (Overview):")+ overview = client.overview(root_uri)+ if overview:+ preview = overview[:300] + "..." if len(overview) > 300 else overview+ print(f" {preview}")+ else:+ print(" (Not available yet)")++ print()++ # L2: Full content (read first 500 chars)+ print(" L2 (Full content - first 500 chars):")+ content = client.read(root_uri)+ if content:+ preview = content[:500] + "..." if len(content) > 500 else content+ print(f" {preview}")+ else:+ print(" (Not available)")++ except Exception as e:+ print(f" Error loading context: {e}")++ print()++ # ============================================================+ # 6. Semantic Search+ # ============================================================+ print("6. Semantic Search:")+ print("-" * 40)++ if root_uri:+ try:+ query = "what is openviking"+ print(f" Query: '{query}'")+ print(" Results:")++ results = client.find(+ query=query,+ target_uri=root_uri,+ limit=5+ )++ if hasattr(results, 'resources') and results.resources:+ for r in results.resources:+ print(f" - {r.uri}")+ print(f" Score: {r.score:.4f}")+ else:+ print(" No results found")++ except Exception as e:+ print(f" Error during search: {e}")++ print()++ # ============================================================+ # 7. Content Search (grep)+ # ============================================================+ print("7. Content search (grep):")+ print("-" * 40)++ if root_uri:+ try:+ pattern = "Agent"+ print(f" Pattern: '{pattern}'")++ result = client.grep(root_uri, pattern, case_insensitive=True)++ matches = result.get("matches", [])+ print(f" Found {len(matches)} matches")++ # Show first 3 matches+ for match in matches[:3]:+ print(f" - {match.get('uri', 'N/A')}: {match.get('count', 0)} occurrences")++ except Exception as e:+ print(f" Error during grep: {e}")++ print()++ # ============================================================+ # 8. Session Management (Optional Demo)+ # ============================================================+ print("8. Session Management (Demo):")+ print("-" * 40)++ try:+ # Create a new session+ session_info = client.create_session()+ session_id = session_info.get("session_id", "")+ print(f" Created session: {session_id}")++ # Add a conversation turn+ client.add_message(session_id, "user", "I prefer Python for data science projects")+ client.add_message(session_id, "assistant", "Understood! I'll use Python for your data science work.")++ print(" Added conversation turn")++ # Note: In a real application, you would commit the session at the end+ # to extract long-term memories. Here we just demonstrate the API.+ # client.commit_session(session_id)++ print(" (Session would be committed at conversation end)")++ except Exception as e:+ print(f" Note: Session demo skipped - {e}")++ print()++ # ============================================================+ # 9. Cleanup+ # ============================================================+ print("8. Closing OpenViking...")+ print("-" * 40)++ client.close()+ print(" Done!")+ print()+ print("=" * 60)+ print("Example completed successfully!")+ print("=" * 60)+++def print_tree(tree: dict, indent: str = ""):+ """Helper function to print tree structure."""+ if not tree:+ return++ name = tree.get("name", "?")+ children = tree.get("children", [])++ print(f"{indent}{name}/")++ for child in children[:5]: # Limit to first 5 children+ if child.get("is_dir"):+ print_tree(child, indent + " ")+ else:+ print(f"{indent} {child.get('name', '?')}")+++if __name__ == "__main__":+ main()\ No newline at end of filediff --git a/examples/claude-memory-plugin/README_CN.md b/examples/claude-memory-plugin/README_CN.mdnew file mode 100644index 000000000..5966497c2--- /dev/null+++ b/examples/claude-memory-plugin/README_CN.md@@ -0,0 +1,99 @@+# OpenViking Claude 记忆插件(方案 B)++基于 **OpenViking Session 记忆** 的 Claude Code 记忆插件。++- 在 Claude 会话期间累积会话数据(`Stop` 钩子)。+- 在 `SessionEnd` 时,插件调用 `session.commit()` 触发 OpenViking 记忆提取。+- 记忆召回由 `memory-recall` 技能处理。++## 此版本的设计选择++- 模式:**自动切换**+ - 优先尝试 HTTP 模式(从 `./ov.conf` 的 `server.host` + `server.port` 读取,健康检查 `/health`)+ - 如果服务器不可达,则回退到嵌入式本地模式+- 配置:**严格**+ - 必须在项目根目录有 `./ov.conf` 文件+- 插件状态目录:`./.openviking/memory/`++## 目录结构++```text+examples/claude-memory-plugin/+├── .claude-plugin/+│ └── plugin.json+├── hooks/+│ ├── hooks.json+│ ├── common.sh+│ ├── session-start.sh+│ ├── user-prompt-submit.sh+│ ├── stop.sh+│ └── session-end.sh+├── scripts/+│ ├── ov_memory.py+│ └── run_e2e_claude_session.sh+└── skills/+ └── memory-recall/+ └── SKILL.md+```++## 钩子行为++- `SessionStart`+ - 验证 `./ov.conf`+ - 自动检测后端模式(http/local)+ - 创建新的 OpenViking 会话并持久化插件状态+- `UserPromptSubmit`+ - 添加轻量级提示,表明记忆可用+- `Stop`(异步)+ - 解析最后一条对话记录+ - 总结本轮对话(当可用时使用 `claude -p --model haiku`;回退到本地总结)+ - 将用户和助手总结追加到 OpenViking 会话+ - 按最后一条用户消息 UUID 去重+- `SessionEnd`+ - 提交 OpenViking 会话以提取长期记忆++## 技能行为++`memory-recall` 运行桥接命令:++```bash+python3 .../ov_memory.py recall --query "<query>" --top-k 5+```++它搜索以下位置:++- `viking://user/memories/`+- `viking://agent/memories/`++然后返回简洁的、带来源链接的记忆摘要。++## 一键端到端测试++使用源配置运行真实的 Claude 无头会话端到端测试:++```bash+cd /Users/quemingjian/.codex/worktrees/6e45/OpenViking+bash /Users/quemingjian/.codex/worktrees/6e45/OpenViking/examples/claude-memory-plugin/scripts/run_e2e_claude_session.sh+```++自定义源配置和提示:++```bash+bash /Users/quemingjian/.codex/worktrees/6e45/OpenViking/examples/claude-memory-plugin/scripts/run_e2e_claude_session.sh \+ /Users/quemingjian/Source/OpenViking/ov.conf \+ "请只回复: CUSTOM_E2E_TOKEN"+```++脚本执行内容:++- 在 `/tmp` 下创建 Python 3.11 虚拟环境(一次性安装依赖)。+- 从源配置生成临时项目 `./ov.conf`,并注入 HTTP 服务器字段。+- 启动 OpenViking HTTP 服务器,使用此插件运行真实的 `claude -p` 会话,然后触发确定性的 Stop + SessionEnd 验证。+- 验证 `session_state.json`、`ingested_turns >= 1` 以及会话归档文件创建。+- 完成后恢复原始 `./ov.conf`。++## 注意事项++- 此 MVP 不修改 OpenViking 核心。+- 如果缺少 `./ov.conf`,钩子会安全降级并在 systemMessage 中报告状态。+- 状态文件:`./.openviking/memory/session_state.json`\ No newline at end of filediff --git a/examples/k8s-helm/README_CN.md b/examples/k8s-helm/README_CN.mdnew file mode 100644index 000000000..b3c7db600--- /dev/null+++ b/examples/k8s-helm/README_CN.md@@ -0,0 +1,272 @@+# OpenViking Helm Chart++此 Helm Chart 用于在 Kubernetes 上部署 OpenViking,提供可扩展、生产就绪的 RAG(检索增强生成)和语义搜索服务。++## 概述++[OpenViking](https://github.com/volcengine/OpenViking) 是一个开源的 RAG 和语义搜索引擎,作为上下文数据库 MCP(Model Context Protocol)服务器运行。此 Helm Chart 支持在 Kubernetes 集群上轻松部署,兼容主流云服务商。++## 前置条件++- Kubernetes 1.24++- Helm 3.8++- 有效的火山引擎 API Key(用于 embedding 和 VLM 服务)++## 安装++### 添加 Helm 仓库(发布后可用)++```bash+helm repo add openviking https://volcengine.github.io/openviking+helm repo update+```++### 从本地 Chart 安装++```bash+# 克隆仓库+git clone https://github.com/volcengine/OpenViking.git+cd OpenViking/deploy/helm++# 使用默认值安装+helm install openviking ./openviking++# 使用自定义值安装+helm install openviking ./openviking -f my-values.yaml+```++### 快速开始++```bash+# GCP 部署+helm install openviking ./openviking \+ --set cloudProvider=gcp \+ --set openviking.config.embedding.dense.api_key=YOUR_API_KEY++# AWS 部署+helm install openviking ./openviking \+ --set cloudProvider=aws \+ --set openviking.config.embedding.dense.api_key=YOUR_API_KEY+```++## 配置++### 云服务商支持++此 Chart 支持为主流云服务商自动配置 LoadBalancer 注解:++| 云服务商 | 配置值 |+|----------|--------|+| Google Cloud Platform | `cloudProvider: gcp` |+| Amazon Web Services | `cloudProvider: aws` |+| 其他/通用 | `cloudProvider: ""`(默认) |++### 关键配置选项++| 参数 | 说明 | 默认值 |+|------|------|--------|+| `cloudProvider` | 云服务商,用于 LoadBalancer 注解 | `""` |+| `replicaCount` | 副本数量 | `1` |+| `image.repository` | 容器镜像仓库 | `ghcr.io/astral-sh/uv` |+| `image.tag` | 容器镜像标签 | `python3.12-bookworm` |+| `service.type` | Kubernetes 服务类型 | `LoadBalancer` |+| `service.port` | 服务端口 | `1933` |+| `openviking.config.server.api_key` | 认证 API Key | `null` |+| `openviking.config.embedding.dense.api_key` | 火山引擎 API Key | `null` |++### OpenViking 配置++`ov.conf` 中的所有 OpenViking 配置选项都在 `openviking.config` 下可用。完整默认配置请参见 `values.yaml`。++### Embedding 配置++Embedding 服务需要火山引擎 API Key:++```yaml+openviking:+ config:+ embedding:+ dense:+ api_key: "your-api-key-here"+ api_base: "https://ark.cn-beijing.volces.com/api/v3"+ model: "doubao-embedding-vision-250615"+```++### VLM 配置++视觉语言模型支持:++```yaml+openviking:+ config:+ vlm:+ api_key: "your-api-key-here"+ api_base: "https://ark.cn-beijing.volces.com/api/v3"+ model: "doubao-seed-2-0-pro-260215"+```++## 存储++### 默认(emptyDir)++默认情况下,Chart 使用 `emptyDir` 卷进行数据存储。这适用于开发和测试,但 Pod 重启后**数据将丢失**。++### 持久化存储(可选)++使用 PVC 启用持久化存储:++```yaml+openviking:+ dataVolume:+ enabled: true+ usePVC: true+ size: 50Gi+ storageClassName: standard+ accessModes:+ - ReadWriteOnce+```++## 安全++### API Key 认证++启用 API Key 认证以保护 OpenViking 服务器:++```yaml+openviking:+ config:+ server:+ api_key: "your-secure-api-key"+ cors_origins:+ - "https://your-domain.com"+```++### 密钥管理++生产环境建议使用 Kubernetes Secrets 或外部密钥管理:++```bash+# 从字面值创建 Secret+kubectl create secret generic openviking-config \+ --from-literal=ov.conf='{"server":{"api_key":"secret"}}'++# 或挂载现有 Secret+helm install openviking ./openviking \+ --set existingSecret=openviking-config+```++## 自动扩缩容++为生产工作负载启用 Horizontal Pod Autoscaler:++```yaml+autoscaling:+ enabled: true+ minReplicas: 2+ maxReplicas: 10+ targetCPUUtilizationPercentage: 80+ targetMemoryUtilizationPercentage: 80+```++## 资源限制++默认资源配置:++```yaml+resources:+ limits:+ cpu: 2000m+ memory: 4Gi+ requests:+ cpu: 500m+ memory: 1Gi+```++根据工作负载需求调整。++## 使用示例++### 使用 CLI 连接++```bash+# 获取 LoadBalancer IP+export OPENVIKING_IP=$(kubectl get svc openviking -o jsonpath='{.status.loadBalancer.ingress[0].ip}')++# 创建 CLI 配置+cat > ~/.openviking/ovcli.conf <<EOF+{+ "url": "http://$OPENVIKING_IP:1933",+ "api_key": null,+ "output": "table"+}+EOF++# 测试连接+openviking health+```++### Python 客户端++```python+import openviking as ov++# 获取服务端点+# kubectl get svc openviking++client = ov.OpenViking(url="http://<load-balancer-ip>:1933", api_key="your-key")+client.initialize()++# 添加资源+client.add_resource(path="./document.pdf")+client.wait_processed()++# 搜索+results = client.find("your search query")+print(results)++client.close()+```++## 故障排除++### Pod 启动失败++检查 Pod 日志:+```bash+kubectl logs -l app.kubernetes.io/name=openviking+```++### 健康检查失败++验证配置:+```bash+kubectl get secret openviking-config -o jsonpath='{.data.ov\.conf}' | base64 -d+```++### LoadBalancer 未获取 IP++等待云服务商分配负载均衡器:+```bash+kubectl get svc openviking -w+```++检查 `values.yaml` 中云服务商特定的注解。++## 卸载++```bash+helm uninstall openviking+```++删除持久化数据(如果启用了 PVC):+```bash+kubectl delete pvc openviking-data+```++## 贡献++欢迎贡献!请参见 [OpenViking 仓库](https://github.com/volcengine/OpenViking) 的贡献指南。++## 许可证++此 Helm Chart 采用 Apache License 2.0 许可证,与 OpenViking 项目许可证一致。\ No newline at end of filediff --git a/examples/mcp-query/README_CN.md b/examples/mcp-query/README_CN.mdnew file mode 100644index 000000000..df24af359--- /dev/null+++ b/examples/mcp-query/README_CN.md@@ -0,0 +1,66 @@+# OpenViking MCP Server++MCP(Model Context Protocol)HTTP 服务器,将 OpenViking RAG 能力作为工具暴露。++## 工具++| 工具 | 说明 |+|------|------|+| `query` | 完整 RAG 流程 — 搜索 + LLM 答案生成 |+| `search` | 仅语义搜索,返回匹配文档 |+| `add_resource` | 添加文件、目录或 URL 到数据库 |++## 快速开始++```bash+# 设置配置+cp ov.conf.example ov.conf+# 编辑 ov.conf,填入你的 API Key++# 安装依赖+uv sync++# 启动服务器(端口 2033 的可流式 HTTP)+uv run server.py+```++服务器将在 `http://127.0.0.1:2033/mcp` 可用。++## 从 Claude 连接++```bash+# 在 Claude CLI 中添加 MCP 服务器+claude mcp add --transport http openviking http://localhost:2033/mcp+```++或添加到 `.mcp.json`:++```json+{+ "mcpServers": {+ "openviking": {+ "type": "http",+ "url": "http://localhost:2033/mcp"+ }+ }+}+```++## 选项++```+uv run server.py [OPTIONS]++ --config PATH 配置文件路径(默认:./ov.conf,环境变量:OV_CONFIG)+ --data PATH 数据目录路径(默认:./data,环境变量:OV_DATA)+ --host HOST 绑定地址(默认:127.0.0.1)+ --port PORT 监听端口(默认:2033,环境变量:OV_PORT)+ --transport TYPE streamable-http | stdio(默认:streamable-http)+```++## 使用 MCP Inspector 测试++```bash+npx @modelcontextprotocol/inspector+# 连接到 http://localhost:2033/mcp+```\ No newline at end of file