OpenViking 学习教程

OpenViking 学习教程

一、环境准备

1.1 前置知识

学习 OpenViking 前,建议掌握以下知识:

知识领域 要求程度 说明
Python 中级 理解异步编程、类、模块
AI Agent 概念 基础 理解 Agent、Context、Memory
向量检索 基础 了解 Embedding、向量数据库
CLI 操作 基础 熟悉命令行操作

1.2 环境要求

# 系统要求
- Python 3.10+
- Go 1.22+ (可选,用于构建 AGFS 组件)
- C++ 编译器: GCC 9+ 或 Clang 11+ (可选)
- 操作系统: Linux, macOS, Windows

# 网络要求
- 稳定的网络连接 (下载依赖和访问模型服务)

1.3 安装步骤

Python 包安装

# 安装 OpenViking
pip install openviking --upgrade --force-reinstall

# 安装 VikingBot (可选,带 Agent 框架)
pip install "openviking[bot]"

Rust CLI 安装 (可选)

# 通过脚本安装
curl -fsSL https://raw.githubusercontent.com/volcengine/OpenViking/main/crates/ov_cli/install.sh | bash

# 或从源码构建
cargo install --git https://github.com/volcengine/OpenViking ov_cli

1.4 验证安装

# 检查 Python 包
python -c "import openviking; print('OpenViking 安装成功')"

# 检查 CLI (如果安装了)
ov --version

二、快速开始

2.1 配置文件创建

创建配置文件 ~/.openviking/ov.conf:

mkdir -p ~/.openviking

使用 OpenAI 的配置示例

{
  "storage": {
    "workspace": "/home/your-name/openviking_workspace"
  },
  "log": {
    "level": "INFO",
    "output": "stdout"
  },
  "embedding": {
    "dense": {
      "api_base": "https://api.openai.com/v1",
      "api_key": "your-openai-api-key",
      "provider": "openai",
      "dimension": 3072,
      "model": "text-embedding-3-large"
    },
    "max_concurrent": 10
  },
  "vlm": {
    "api_base": "https://api.openai.com/v1",
    "api_key": "your-openai-api-key",
    "provider": "openai",
    "model": "gpt-4o",
    "max_concurrent": 100
  }
}

使用火山引擎豆包的配置示例

{
  "storage": {
    "workspace": "/home/your-name/openviking_workspace"
  },
  "log": {
    "level": "INFO",
    "output": "stdout"
  },
  "embedding": {
    "dense": {
      "api_base": "https://ark.cn-beijing.volces.com/api/v3",
      "api_key": "your-volcengine-api-key",
      "provider": "volcengine",
      "dimension": 1024,
      "model": "doubao-embedding-vision-250615"
    },
    "max_concurrent": 10
  },
  "vlm": {
    "api_base": "https://ark.cn-beijing.volces.com/api/v3",
    "api_key": "your-volcengine-api-key",
    "provider": "volcengine",
    "model": "doubao-seed-2-0-pro-260215",
    "max_concurrent": 100
  }
}

使用 Ollama 本地模型的配置示例

{
  "storage": {
    "workspace": "/home/your-name/openviking_workspace"
  },
  "log": {
    "level": "INFO",
    "output": "stdout"
  },
  "embedding": {
    "dense": {
      "api_base": "http://localhost:11434",
      "provider": "ollama",
      "model": "nomic-embed-text"
    }
  },
  "vlm": {
    "api_base": "http://localhost:11434",
    "provider": "litellm",
    "model": "ollama/llama3.1"
  }
}

2.2 设置环境变量

# Linux/macOS
export OPENVIKING_CONFIG_FILE=~/.openviking/ov.conf

# Windows PowerShell
$env:OPENVIKING_CONFIG_FILE = "$HOME/.openviking/ov.conf"

2.3 Hello World: 第一个示例

# Step 1: 启动服务器
openviking-server

# 或后台运行
nohup openviking-server > /data/log/openviking.log 2>&1 &

# Step 2: 检查状态
ov status

# Step 3: 添加资源 (GitHub 仓库)
ov add-resource https://github.com/volcengine/OpenViking --wait

# Step 4: 查看资源列表
ov ls viking://resources/

# Step 5: 查看目录树结构
ov tree viking://resources/volcengine/OpenViking -L 2

# Step 6: 语义搜索
ov find "what is openviking"

# Step 7: 内容搜索
ov grep "openviking" --uri viking://resources/volcengine/OpenViking/docs/zh

三、核心概念

3.1 概念图谱

┌─────────────────────────────────────────────────────────────────┐
│                    OpenViking 核心概念                           │
├─────────────────────────────────────────────────────────────────┤
│                                                                 │
│  ┌─────────────────────────────────────────────────────────┐   │
│  │                  Viking URI 协议                         │   │
│  │   viking:// - 统一的资源标识协议                          │   │
│  └─────────────────────────────────────────────────────────┘   │
│                              │                                  │
│              ┌───────────────┼───────────────┐                  │
│              ▼               ▼               ▼                  │
│  ┌───────────────┐ ┌───────────────┐ ┌───────────────┐          │
│  │   resources   │ │     user      │ │    agent      │          │
│  │    资源区     │ │    用户区     │ │   Agent 区    │          │
│  └───────────────┘ └───────────────┘ └───────────────┘          │
│              │               │               │                  │
│              └───────────────┼───────────────┘                  │
│                              ▼                                  │
│  ┌─────────────────────────────────────────────────────────┐   │
│  │               L0/L1/L2 分层加载                          │   │
│  │   Abstract → Overview → Details                          │   │
│  └─────────────────────────────────────────────────────────┘   │
│                              │                                  │
│                              ▼                                  │
│  ┌─────────────────────────────────────────────────────────┐   │
│  │               目录递归检索 + 可视化轨迹                    │   │
│  └─────────────────────────────────────────────────────────┘   │
│                                                                 │
└─────────────────────────────────────────────────────────────────┘

3.2 核心概念详解

Viking URI 协议

定义: 统一的资源标识协议,所有上下文都有唯一的 viking:// URI

viking://
├── resources/                    # 资源: 外部知识
│   ├── github/
│   │   └── org/
│   │       └── repo/
│   │           ├── docs/
│   │           └── src/
│   └── web/
│       └── example.com/
│           └── page.html
│
├── user/                         # 用户: 个人相关
│   └── memories/
│       ├── preferences/
│       │   ├── writing_style
│       │   └── coding_habits
│       └── history/
│
└── agent/                        # Agent: 自身相关
    ├── skills/
    │   ├── search_code
    │   └── analyze_data
    ├── memories/
    │   └── task_experience
    └── instructions/
        └── coding_guidelines

三大上下文类型:

类型 URI 前缀 用途 示例
Resources viking://resources/ 外部知识资源 文档、代码库、网页
User viking://user/ 用户相关记忆 偏好、习惯、历史
Agent viking://agent/ Agent 自身知识 技能、任务记忆、指令

L0/L1/L2 分层加载

┌─────────────────────────────────────────────────────────────┐
│                    分层上下文加载                            │
├─────────────────────────────────────────────────────────────┤
│                                                             │
│  L0 - Abstract (~100 tokens)                                │
│  ├── 一句话摘要                                              │
│  ├── 用于快速相关性检查                                      │
│  └── 决定是否需要进一步加载                                  │
│                                                             │
│  L1 - Overview (~2,000 tokens)                              │
│  ├── 核心信息和使用场景                                      │
│  ├── 用于 Agent 规划阶段                                     │
│  └── 理解结构和关键点                                        │
│                                                             │
│  L2 - Details (完整内容)                                     │
│  ├── 原始完整数据                                            │
│  ├── 用于深度阅读                                            │
│  └── 仅在绝对必要时加载                                      │
│                                                             │
└─────────────────────────────────────────────────────────────┘

文件系统映射:

viking://resources/my_project/
├── .abstract          # L0 层文件
├── .overview          # L1 层文件
├── docs/
│   ├── .abstract
│   ├── .overview
│   └── api.md         # L2 层 (原始文件)
└── src/
    ├── .abstract
    ├── .overview
    └── main.py

目录递归检索

检索策略: "先锁定高分目录,再精细探索内容"

Step 1: 意图分析
        └── 将查询分解为多个检索条件

Step 2: 初始定位
        └── 向量检索快速定位高分目录

Step 3: 精细探索
        └── 在目录内二次检索

Step 4: 递归下钻
        └── 子目录递归检索

Step 5: 结果聚合
        └── 返回最相关上下文

检索流程图:

查询: "如何配置 OpenViking"
        │
        ▼
┌───────────────┐
│   意图分析    │ ──→ ["配置", "OpenViking", "安装设置"]
└───────────────┘
        │
        ▼
┌───────────────┐
│  向量检索     │ ──→ 定位到 viking://resources/OpenViking/docs/
└───────────────┘
        │
        ▼
┌───────────────┐
│ 目录内检索    │ ──→ 发现 installation/ 子目录
└───────────────┘
        │
        ▼
┌───────────────┐
│  递归下钻     │ ──→ 找到 configuration.md
└───────────────┘
        │
        ▼
    返回结果

3.3 术语表

术语 英文 定义
Context Database Context Database 专为 AI Agent 设计的上下文数据库
Viking URI Viking URI 统一资源标识协议 (viking://)
Resources Resources 外部知识资源 (文档、代码等)
User Memories User Memories 用户相关记忆 (偏好、习惯)
Agent Skills Agent Skills Agent 可复用的技能
L0/L1/L2 Context Layers 三层上下文结构
Abstract Abstract L0 层,一句话摘要
Overview Overview L1 层,概览内容
Details Details L2 层,完整内容

四、CLI 命令详解

4.1 服务器命令

# 启动服务器
openviking-server

# 后台启动
nohup openviking-server > /var/log/openviking.log 2>&1 &

# 启动服务器并启用 Bot 功能
openviking-server --with-bot

# 指定配置文件
openviking-server --config /path/to/ov.conf

# 指定端口
openviking-server --port 1933

4.2 资源管理命令

添加资源

# 添加 GitHub 仓库
ov add-resource https://github.com/volcengine/OpenViking

# 添加并等待处理完成
ov add-resource https://github.com/user/repo --wait

# 添加网页
ov add-resource https://example.com/docs

# 添加本地文件
ov add-resource /path/to/local/file.md

# 添加本地目录
ov add-resource /path/to/project/

查看资源

# 列出所有资源
ov ls viking://resources/

# 列出特定目录
ov ls viking://resources/github/

# 树形显示
ov tree viking://resources/ -L 3

# 显示详细信息
ov ls -la viking://resources/

4.3 检索命令

语义搜索 (find)

# 语义搜索
ov find "如何配置 OpenViking"

# 限制结果数量
ov find "API 文档" --limit 10

# 指定搜索范围
ov find "安装步骤" --uri viking://resources/docs/

内容搜索 (grep)

# 内容搜索
ov grep "embedding"

# 指定目录
ov grep "配置" --uri viking://resources/docs/

# 使用正则表达式
ov grep "api.*key"

# 显示上下文
ov grep "context" -C 3

4.4 状态和调试命令

# 检查服务器状态
ov status

# 查看配置
ov config show

# 查看日志
ov logs --tail 100

# 查看检索轨迹
ov trace <query-id>

4.5 VikingBot 命令

# 启动交互式聊天
ov chat

# 指定模型
ov chat --model gpt-4o

# 查看聊天历史
ov chat --history

五、Python SDK 使用

5.1 基本使用

from openviking import OpenVikingClient

# 创建客户端
client = OpenVikingClient(
    url="http://localhost:1933",
    timeout=60.0
)

# 检查状态
status = client.status()
print(f"Server status: {status}")

5.2 资源管理

# 添加资源
result = client.add_resource(
    uri="https://github.com/volcengine/OpenViking",
    wait=True  # 等待处理完成
)
print(f"Resource added: {result}")

# 列出资源
resources = client.list_resources("viking://resources/")
for resource in resources:
    print(f"- {resource.uri}")

# 删除资源
client.delete_resource("viking://resources/github/user/repo")

5.3 语义搜索

# 语义搜索
results = client.find(
    query="如何配置 OpenViking",
    limit=10
)

for result in results:
    print(f"URI: {result.uri}")
    print(f"Score: {result.score}")
    print(f"Content: {result.content[:200]}...")
    print("---")

5.4 上下文获取

# 获取 L0 层 (摘要)
abstract = client.get_context(
    uri="viking://resources/docs/guide.md",
    layer="L0"
)

# 获取 L1 层 (概览)
overview = client.get_context(
    uri="viking://resources/docs/guide.md",
    layer="L1"
)

# 获取 L2 层 (完整内容)
details = client.get_context(
    uri="viking://resources/docs/guide.md",
    layer="L2"
)

5.5 用户记忆管理

# 添加用户记忆
client.add_memory(
    user_id="user123",
    memory_type="preference",
    content="用户喜欢使用 Python 进行数据分析",
    tags=["coding", "python"]
)

# 获取用户记忆
memories = client.get_memories(
    user_id="user123",
    memory_type="preference"
)

for memory in memories:
    print(f"- {memory.content}")

5.6 Agent 技能管理

# 注册技能
client.register_skill(
    skill_id="search_code",
    description="在代码库中搜索特定功能",
    parameters={
        "query": {"type": "string", "description": "搜索关键词"},
        "language": {"type": "string", "description": "编程语言"}
    }
)

# 获取技能列表
skills = client.list_skills()
for skill in skills:
    print(f"- {skill.skill_id}: {skill.description}")

六、实战案例

6.1 案例 1: 构建项目知识库

from openviking import OpenVikingClient

client = OpenVikingClient()

# 1. 添加项目文档
client.add_resource("https://github.com/myorg/myproject", wait=True)

# 2. 添加 API 文档
client.add_resource("https://docs.myproject.com/api", wait=True)

# 3. 添加内部 Wiki
client.add_resource("https://wiki.company.com/myproject", wait=True)

# 4. 搜索示例
def search_project_knowledge(query: str) -> str:
    """搜索项目知识库"""
    results = client.find(query, limit=3)

    context = []
    for r in results:
        context.append(f"来源: {r.uri}\n内容: {r.content}")

    return "\n\n---\n\n".join(context)

# 使用
answer = search_project_knowledge("如何处理用户认证?")
print(answer)

6.2 案例 2: AI Agent 长期记忆

from openviking import OpenVikingClient
from datetime import datetime

class AgentMemory:
    """AI Agent 长期记忆系统"""

    def __init__(self, agent_id: str):
        self.client = OpenVikingClient()
        self.agent_id = agent_id

    def save_task_experience(self, task: str, result: str, learnings: str):
        """保存任务经验"""
        memory_uri = f"viking://agent/{self.agent_id}/memories/tasks/{datetime.now().strftime('%Y%m%d_%H%M%S')}"

        content = f"""
# 任务: {task}

## 执行结果
{result}

## 经验总结
{learnings}

## 时间
{datetime.now().isoformat()}
"""
        self.client.write_context(memory_uri, content)
        print(f"任务经验已保存: {memory_uri}")

    def recall_experience(self, query: str) -> str:
        """回忆相关经验"""
        results = self.client.find(
            query=query,
            uri_prefix=f"viking://agent/{self.agent_id}/memories/"
        )
        return results

    def update_skill(self, skill_name: str, usage_notes: str):
        """更新技能使用笔记"""
        skill_uri = f"viking://agent/{self.agent_id}/skills/{skill_name}"

        existing = self.client.get_context(skill_uri, layer="L2")
        updated = f"{existing}\n\n## 新增笔记\n{usage_notes}"

        self.client.write_context(skill_uri, updated)

# 使用
memory = AgentMemory("my-assistant")

# 保存任务经验
memory.save_task_experience(
    task="修复登录 Bug",
    result="成功修复",
    learnings="注意检查 token 过期时间"
)

# 回忆经验
experience = memory.recall_experience("登录相关问题")

6.3 案例 3: 用户个性化系统

from openviking import OpenVikingClient
import json

class UserPersonalization:
    """用户个性化系统"""

    def __init__(self):
        self.client = OpenVikingClient()

    def learn_preference(self, user_id: str, preference_type: str, value: str):
        """学习用户偏好"""
        uri = f"viking://user/{user_id}/preferences/{preference_type}"
        self.client.write_context(uri, value)
        print(f"已记录偏好: {preference_type} = {value}")

    def get_preferences(self, user_id: str) -> dict:
        """获取用户所有偏好"""
        preferences = {}
        pref_dir = f"viking://user/{user_id}/preferences/"

        resources = self.client.list_resources(pref_dir)
        for r in resources:
            pref_name = r.uri.split("/")[-1]
            pref_value = self.client.get_context(r.uri, layer="L0")
            preferences[pref_name] = pref_value

        return preferences

    def personalize_response(self, user_id: str, response: str) -> str:
        """根据用户偏好个性化响应"""
        prefs = self.get_preferences(user_id)

        # 应用偏好
        if prefs.get("tone") == "formal":
            response = self._make_formal(response)
        elif prefs.get("tone") == "casual":
            response = self._make_casual(response)

        if prefs.get("language") == "zh":
            response = self._translate_to_chinese(response)

        return response

    def _make_formal(self, text: str) -> str:
        # 实现正式语气转换
        return text

    def _make_casual(self, text: str) -> str:
        # 实现随意语气转换
        return text

    def _translate_to_chinese(self, text: str) -> str:
        # 实现翻译
        return text

# 使用
personalizer = UserPersonalization()

# 学习用户偏好
personalizer.learn_preference("user123", "tone", "casual")
personalizer.learn_preference("user123", "language", "zh")
personalizer.learn_preference("user123", "code_style", "pythonic")

# 获取偏好
prefs = personalizer.get_preferences("user123")
print(prefs)

6.4 案例 4: OpenClaw 集成

# OpenClaw Memory Plugin 集成示例

from openclaw import Agent
from openviking import OpenVikingClient

class OpenVikingMemoryPlugin:
    """OpenViking Memory Plugin for OpenClaw"""

    def __init__(self, openviking_url: str = "http://localhost:1933"):
        self.client = OpenVikingClient(url=openviking_url)

    def get_context_for_agent(self, query: str, user_id: str = None) -> str:
        """为 Agent 获取上下文"""
        context_parts = []

        # 1. 搜索资源
        resources = self.client.find(query, limit=5)
        if resources:
            context_parts.append("## 相关知识\n")
            for r in resources:
                context_parts.append(f"- {r.content[:500]}")

        # 2. 获取用户偏好
        if user_id:
            prefs = self.client.list_resources(
                f"viking://user/{user_id}/preferences/"
            )
            if prefs:
                context_parts.append("\n## 用户偏好\n")
                for p in prefs:
                    pref_value = self.client.get_context(p.uri, layer="L0")
                    context_parts.append(f"- {p.uri.split('/')[-1]}: {pref_value}")

        return "\n".join(context_parts)

    def save_conversation(self, user_id: str, messages: list):
        """保存对话记录"""
        # 自动提取重要信息并保存
        conversation_summary = self._summarize_conversation(messages)

        # 保存到用户记忆
        self.client.add_memory(
            user_id=user_id,
            memory_type="conversation",
            content=conversation_summary
        )

    def _summarize_conversation(self, messages: list) -> str:
        """总结对话"""
        # 实现对话摘要逻辑
        return "\n".join([f"{m['role']}: {m['content'][:100]}" for m in messages])

# 使用
plugin = OpenVikingMemoryPlugin()

# 在 OpenClaw Agent 中使用
agent = Agent(memory_plugin=plugin)

七、进阶主题

7.1 自定义检索策略

from openviking import OpenVikingClient
from openviking.retrieval import RetrievalStrategy

class CustomRetrievalStrategy(RetrievalStrategy):
    """自定义检索策略"""

    def __init__(self, client: OpenVikingClient):
        self.client = client

    def retrieve(self, query: str, **kwargs):
        """自定义检索逻辑"""
        # 1. 意图分析
        intents = self._analyze_intent(query)

        # 2. 多路检索
        results = []
        for intent in intents:
            intent_results = self.client.find(intent, limit=5)
            results.extend(intent_results)

        # 3. 去重和排序
        results = self._deduplicate(results)
        results = self._rank(results, query)

        return results[:kwargs.get("limit", 10)]

    def _analyze_intent(self, query: str) -> list:
        """分析查询意图"""
        # 实现意图分析
        return [query]

    def _deduplicate(self, results: list) -> list:
        """去重"""
        seen = set()
        unique = []
        for r in results:
            if r.uri not in seen:
                seen.add(r.uri)
                unique.append(r)
        return unique

    def _rank(self, results: list, query: str) -> list:
        """重新排序"""
        # 实现自定义排序逻辑
        return sorted(results, key=lambda x: x.score, reverse=True)

7.2 会话自动管理

from openviking import OpenVikingClient
from openviking.session import SessionManager

class AutoSessionManager:
    """自动会话管理器"""

    def __init__(self, agent_id: str, user_id: str):
        self.client = OpenVikingClient()
        self.agent_id = agent_id
        self.user_id = user_id
        self.session_messages = []

    def add_message(self, role: str, content: str):
        """添加消息"""
        self.session_messages.append({
            "role": role,
            "content": content,
            "timestamp": datetime.now().isoformat()
        })

    def end_session(self):
        """结束会话,自动提取记忆"""
        # 1. 提取用户偏好
        self._extract_user_preferences()

        # 2. 提取任务经验
        self._extract_task_experience()

        # 3. 更新 Agent 技能
        self._update_agent_skills()

        # 4. 清理会话
        self.session_messages = []

    def _extract_user_preferences(self):
        """提取用户偏好"""
        # 分析对话,提取用户偏好
        preferences = self._analyze_preferences(self.session_messages)

        for pref_type, pref_value in preferences.items():
            uri = f"viking://user/{self.user_id}/preferences/{pref_type}"
            self.client.write_context(uri, pref_value)

    def _extract_task_experience(self):
        """提取任务经验"""
        # 分析任务执行情况
        experiences = self._analyze_tasks(self.session_messages)

        for exp in experiences:
            uri = f"viking://agent/{self.agent_id}/memories/tasks/{datetime.now().strftime('%Y%m%d_%H%M%S')}"
            self.client.write_context(uri, exp)

    def _update_agent_skills(self):
        """更新 Agent 技能"""
        # 分析技能使用情况
        skill_updates = self._analyze_skill_usage(self.session_messages)

        for skill_name, notes in skill_updates.items():
            uri = f"viking://agent/{self.agent_id}/skills/{skill_name}/notes"
            existing = self.client.get_context(uri, layer="L2")
            updated = f"{existing}\n\n{notes}" if existing else notes
            self.client.write_context(uri, updated)

    def _analyze_preferences(self, messages: list) -> dict:
        """分析用户偏好"""
        # 实现偏好分析逻辑
        return {}

    def _analyze_tasks(self, messages: list) -> list:
        """分析任务经验"""
        # 实现任务分析逻辑
        return []

    def _analyze_skill_usage(self, messages: list) -> dict:
        """分析技能使用"""
        # 实现技能分析逻辑
        return {}

7.3 性能优化

from openviking import OpenVikingClient
import asyncio
from functools import lru_cache

class OptimizedOpenVikingClient:
    """性能优化的 OpenViking 客户端"""

    def __init__(self, url: str = "http://localhost:1933"):
        self.client = OpenVikingClient(url=url)
        self._cache = {}

    @lru_cache(maxsize=1000)
    def get_abstract(self, uri: str) -> str:
        """获取摘要 (带缓存)"""
        return self.client.get_context(uri, layer="L0")

    async def batch_find(self, queries: list) -> list:
        """批量异步搜索"""
        tasks = [self._async_find(q) for q in queries]
        return await asyncio.gather(*tasks)

    async def _async_find(self, query: str) -> list:
        """异步搜索"""
        loop = asyncio.get_event_loop()
        return await loop.run_in_executor(
            None,
            lambda: self.client.find(query)
        )

    def preload_context(self, uris: list):
        """预加载上下文"""
        for uri in uris:
            if uri not in self._cache:
                self._cache[uri] = {
                    "L0": self.client.get_context(uri, layer="L0"),
                    "L1": self.client.get_context(uri, layer="L1")
                }

    def get_cached_context(self, uri: str, layer: str = "L0"):
        """获取缓存的上下文"""
        if uri in self._cache:
            return self._cache[uri].get(layer)
        return self.client.get_context(uri, layer=layer)

八、常见问题

Q1: 如何选择 L0/L1/L2 层级?

A: 根据使用场景选择:

场景 推荐层级 原因
快速筛选 L0 只需一句话摘要
理解概要 L1 获取核心信息
深度分析 L2 需要完整内容
Agent 规划 L1 平衡信息和效率

Q2: 如何处理大量资源?

A: 使用分层管理:

# 1. 分类存储
client.add_resource("https://github.com/org/backend", tags=["backend"])
client.add_resource("https://github.com/org/frontend", tags=["frontend"])

# 2. 按需加载
results = client.find("API 设计", tags=["backend"])

# 3. 使用 L0 快速筛选
for r in results:
    abstract = client.get_context(r.uri, layer="L0")
    if is_relevant(abstract):
        # 再加载 L1/L2
        details = client.get_context(r.uri, layer="L2")

Q3: 如何调试检索问题?

A: 使用可视化检索轨迹:

# 启用详细日志
import logging
logging.basicConfig(level=logging.DEBUG)

# 查看检索轨迹
results = client.find("查询内容", trace=True)
for r in results:
    print(f"URI: {r.uri}")
    print(f"Score: {r.score}")
    print(f"Trace: {r.trace}")  # 检索路径

Q4: 如何与其他框架集成?

A: OpenViking 提供多种集成方式:

# LangChain 集成
from langchain.retrievers import OpenVikingRetriever

retriever = OpenVikingRetriever(
    openviking_url="http://localhost:1933"
)
docs = retriever.get_relevant_documents("查询")

# LlamaIndex 集成
from llama_index import OpenVikingReader

reader = OpenVikingReader(url="http://localhost:1933")
documents = reader.load_data("viking://resources/")

Q5: 如何部署到生产环境?

A: 推荐使用云服务器:

# 1. 使用 systemd 管理服务
sudo cat > /etc/systemd/system/openviking.service << EOF
[Unit]
Description=OpenViking Server
After=network.target

[Service]
Type=simple
User=openviking
WorkingDirectory=/opt/openviking
ExecStart=/usr/local/bin/openviking-server
Restart=always

[Install]
WantedBy=multi-user.target
EOF

sudo systemctl enable openviking
sudo systemctl start openviking

# 2. 配置 Nginx 反向代理
# 3. 设置监控和日志

九、参考资料

9.1 官方资源

9.2 相关项目

9.3 社区

  • 📱 飞书群: 扫码加入
  • 💬 微信群: 添加助手
  • 🎮 Discord: 加入服务器
  • 🐦 X (Twitter): 关注官方

9.4 学习路径

┌─────────────────────────────────────────────────────────────────┐
│                    OpenViking 学习路径                           │
├─────────────────────────────────────────────────────────────────┤
│                                                                 │
│  Week 1: 基础                                                   │
│  ├── 理解上下文管理挑战                                          │
│  ├── 安装和配置 OpenViking                                      │
│  └── 掌握基本 CLI 命令                                          │
│                                                                 │
│  Week 2: 核心概念                                               │
│  ├── 理解 Viking URI 协议                                        │
│  ├── 掌握 L0/L1/L2 分层                                         │
│  └── 理解目录递归检索                                            │
│                                                                 │
│  Week 3: 实践                                                   │
│  ├── Python SDK 使用                                            │
│  ├── 构建知识库                                                  │
│  └── 实现用户个性化                                              │
│                                                                 │
│  Week 4: 进阶                                                   │
│  ├── 与 AI Agent 框架集成                                       │
│  ├── 自定义检索策略                                              │
│  └── 生产环境部署                                                │
│                                                                 │
└─────────────────────────────────────────────────────────────────┘

十、总结

通过本教程,你学会了:

  1. 核心概念: Viking URI、L0/L1/L2 分层、目录递归检索
  2. 安装配置: Python 包安装、配置文件、环境变量
  3. CLI 使用: 资源管理、语义搜索、内容搜索
  4. Python SDK: 资源管理、检索、记忆管理
  5. 实战案例: 知识库构建、Agent 记忆、用户个性化
  6. 进阶主题: 自定义检索、会话管理、性能优化

下一步行动: - [ ] 安装 OpenViking 并运行第一个示例 - [ ] 构建你的第一个知识库 - [ ] 为你的 AI Agent 添加长期记忆 - [ ] 与 OpenClaw 或其他框架集成

Happy Coding! 🚀