CMCloudMesh
源码解读

用 OpenViking 给 Python Agent 加记忆:完整实战指南

REST API 封装 + AgentMemory 类 + 对话循环实战代码,支持本地/S3/内存三种后端

以主仓为事实源 历史文章保留原貌

OpenViking 源码解读系列

1. 问题:Agent 为何需要记忆系统?

一个没有记忆的 Agent 长这样:

while True:
    user_input = input("> ")
    response = call_llm(user_input)  # 每次都是全新的对话
    print(response)

用户说"我叫张三",下一轮问"我叫啥",Agent 回答不上来。

加记忆的朴素解法——往列表 append:

history = []
while True:
    user_input = input("> ")
    history.append({"role": "user", "content": user_input})
    response = call_llm(history)
    history.append({"role": "assistant", "content": response})
    print(response)

这个方案有三个致命问题:

问题说明
会话丢失重启后 history 全部清空
内容膨胀对话历史无限增长,LLM context 爆炸
无法检索想找"上次聊的某个项目",只能全量塞进 Prompt

OpenViking 解决的是这三个问题:持久化 + 自动去重 + 语义检索。

2. OpenViking 是什么?

OpenViking(字节跳动火山引擎开源)是 AI Agent 的上下文数据库,核心设计:

架构概览

Python Agent → HTTP REST API → OpenViking Server(REST 服务,默认端口 1933)→ 内容寻址存储(本地磁盘 / S3 / SQLite / 内存,四种后端)

重要前提

OpenViking 是 REST API 服务,不是 Python 库。需要先启动服务(Docker 或二进制),再用 HTTP 调用。不是 pip install openviking 就能用。

3. 3行启动 OpenViking

# 拉取镜像
docker pull openviking/openviking

# 启动服务(本地 1933 端口)
docker run -d -p 1933:1933 \
  --name openviking \
  openviking/openviking

# 验证服务
curl http://127.0.0.1:1933/health
# 返回 {"status": "ok"}

生产环境如果要持久化存储:

docker run -d -p 1933:1933 \
  -v /data/openviking:/data/openviking \
  --name openviking \
  openviking/openviking

4. AgentMemory 类:完整封装

"""
agent_memory.py - 用 OpenViking 给 Python Agent 加记忆
依赖:pip install httpx
"""

import os, uuid, httpx


class AgentMemory:
    """OpenViking 记忆层封装。通过 REST API 与 OpenViking 服务通信。"""

    def __init__(self, account="default", user="default",
                 endpoint="http://127.0.0.1:1933", api_key="",
                 session_id=None):
        self.endpoint = endpoint.rstrip("/")
        self.account = account
        self.user = user
        self.api_key = api_key
        self.session_id = session_id or str(uuid.uuid4())
        self._client = httpx.Client(timeout=30.0)

    def _headers(self):
        h = {"Content-Type": "application/json",
             "X-OpenViking-Account": self.account, "X-OpenViking-User": self.user}
        if self.api_key: h["X-API-Key"] = self.api_key
        return h

    def _url(self, path):
        return f"{self.endpoint}{path}"

    def is_available(self):
        try:
            return self._client.get(self._url("/health"), timeout=3.0).status_code == 200
        except Exception:
            return False

    def remember(self, role, content):
        """写入一条记忆到当前会话。commit 时自动提取为结构化记忆。"""
        resp = self._client.post(
            self._url(f"/api/v1/sessions/{self.session_id}/messages"),
            json={"role": role, "content": content[:4000]},
            headers=self._headers())
        resp.raise_for_status()
        msg_id = resp.json().get("result", {}).get("id", "")
        print(f"[记忆] {role}: {content[:40]}... → {msg_id[:8]}")
        return msg_id

    def search(self, query, top_k=5):
        """语义搜索记忆,返回相关结果列表。"""
        resp = self._client.post(
            self._url("/api/v1/search/find"),
            json={"query": query, "top_k": top_k},
            headers=self._headers())
        resp.raise_for_status()
        result = resp.json().get("result", {})
        items = []
        for ctx_type in ("memories", "resources", "skills"):
            for item in result.get(ctx_type, []):
                items.append({
                    "uri": item.get("uri", ""),
                    "type": ctx_type.rstrip("s"),
                    "score": round(item.get("score", 0), 3),
                    "abstract": item.get("abstract", ""),
                })
        return items

    def browse(self, path="viking://", action="list"):
        endpoint_map = {"tree": "/api/v1/fs/tree",
                        "list": "/api/v1/fs/ls", "stat": "/api/v1/fs/stat"}
        resp = self._client.get(
            self._url(endpoint_map.get(action, "/api/v1/fs/ls")),
            params={"uri": path}, headers=self._headers())
        resp.raise_for_status()
        result = resp.json().get("result", {})
        if action in ("list", "tree") and isinstance(result, list):
            return [{"name": e.get("rel_path", e.get("name", "")),
                     "uri": e.get("uri", ""),
                     "type": "dir" if e.get("isDir") else "file",
                     "abstract": e.get("abstract", "")} for e in result[:50]]
        return result

    def commit(self):
        """提交会话,触发 OpenViking 自动提取 6 类记忆。"""
        resp = self._client.post(
            self._url(f"/api/v1/sessions/{self.session_id}/commit"),
            headers=self._headers())
        ok = resp.status_code == 200
        if ok: print(f"[提交] 会话 {self.session_id[:8]} 已提交")
        return ok

    def build_context(self, query, max_results=5):
        """根据 query 搜索相关记忆,拼成 LLM 可用的上下文字符串。"""
        results = self.search(query, top_k=max_results)
        if not results: return ""
        return "\n".join([f"[{r['type']}] {r['abstract']}" for r in results])

    def close(self):
        self.commit()
        self._client.close()

5. Agent 对话循环

class Agent:
    """带有 OpenViking 记忆的对话 Agent。"""

    def __init__(self, account="default", user="default",
                 endpoint="http://127.0.0.1:1933"):
        self.memory = AgentMemory(account, user, endpoint)
        if not self.memory.is_available():
            print("[警告] OpenViking 服务不可达")

    def chat(self, user_input, call_llm_fn=None):
        # 1. 检索相关记忆作为上下文
        context = self.memory.build_context(user_input)

        # 2. 组装 Prompt
        if context:
            system_prompt = f"参考以下记忆回答:\n{context}\n\n如果记忆不相关,正常回答。"
        else:
            system_prompt = "你是有帮助的 AI 助手。"
        prompt = f"{system_prompt}\n\n用户:{user_input}"

        # 3. 调用 LLM(生产环境替换 call_llm_fn)
        response = call_llm_fn(prompt) if call_llm_fn else "[模拟响应]"

        # 4. 写入记忆
        self.memory.remember("user", user_input)
        self.memory.remember("assistant", response)
        return response

    def close(self):
        self.memory.close()

生产环境替换 LLM(以 OpenAI为例):

import openai

def real_llm(prompt):
    resp = openai.ChatCompletion.create(
        model="gpt-4",
        messages=[{"role": "user", "content": prompt}])
    return resp.choices[0].message.content

agent = Agent()
response = agent.chat("你好,我叫张三", call_llm_fn=real_llm)
print(response)  # 能记住"张三"

6. 完整对话循环(可直接运行)

# agent_demo.py
import os
from agent_memory import Agent, AgentMemory

ENDPOINT = os.environ.get("OPENVIKING_ENDPOINT", "http://127.0.0.1:1933")
ACCOUNT = os.environ.get("OPENVIKING_ACCOUNT", "user_001")

agent = Agent(account=ACCOUNT, endpoint=ENDPOINT)

if not agent.memory.is_available():
    print(f"[错误] 无法连接 OpenViking: {ENDPOINT}")
    print("启动: docker run -d -p 1933:1933 openviking/openviking")
    exit(1)

print("=" * 50)
print("OpenViking Agent 记忆系统 - 输入 exit 退出")
print("=" * 50)

while True:
    user_input = input("\n> ").strip()
    if user_input.lower() == "exit":
        agent.close()
        print("会话已提交,记忆已保存。")
        break
    if user_input.lower().startswith("search:"):
        results = agent.memory.search(user_input[7:].strip())
        for r in results:
            print(f"  [{r['score']}] {r['abstract'][:80]}")
        continue
    if user_input.lower() == "browse":
        for e in agent.memory.browse():
            print(f"  {'📁' if e['type']=='dir' else '📄'} {e['name']}")
        continue
    response = agent.chat(user_input)
    print(response)

运行效果:

> 你好,我叫张三,是一名 AI 工程师
[记忆] user: 你好,我叫张三,是一名... → msg_id: a1b2c3d4
[记忆] assistant: 你好张三!很高兴认识... → msg_id: e5f6g7h8
你好张三!很高兴认识你,AI 工程师。有什么我可以帮你的吗?

> search: 张三
[记忆] user: 你好,我叫张三,是一名... → msg_id: a1b2c3d4
  [0.92] 你好,我叫张三,是一名 AI 工程师 (memories)

> 我叫什么名字?
[记忆] user: 我叫什么名字? → msg_id: i9j0k1l2
[记忆] assistant: 你叫张三,是一名 AI 工程师。 → msg_id: m3n4o5p6
你叫张三,是一名 AI 工程师。

> exit
[提交] 会话 user_001-xxx 已提交
会话已提交,记忆已保存。

7. 多后端切换

OpenViking 支持四种存储后端,Python 端只需改配置:

后端配置方式适用场景
本地磁盘默认,data-dir 配置开发调试、单机使用
S3/TOSS3 bucket + AK/SK多机器共享、正式环境
SQLite数据库文件路径需要 SQL 查询能力
内存纯内存测试、嵌入式

切换到 S3:

docker run -d -p 1933:1933 \
  -e OPENVIKING_STORAGE=s3 \
  -e OPENVIKING_S3_BUCKET=my-agent-memories \
  -e OPENVIKING_S3_REGION=us-east-1 \
  -e OPENVIKING_AWS_ACCESS_KEY_ID=AKIAxxx \
  -e OPENVIKING_AWS_SECRET_ACCESS_KEY=*** \
  openviking/openviking

多台机器的 Agent 读写同一 bucket,记忆天然共享。

8. 核心优势总结

传统方案(List append)OpenViking 方案
重启后记忆丢失持久化存储,会话间继承
内容无限膨胀内容寻址,相同内容不重复存储
全量塞进 Prompt语义检索,只取相关内容
手动去重SHA-1 OID 自动去重
无版本历史Git 版本控制,可追溯
单机独享S3 后端多机共享

9. 下一步


📅2026-07-15 · 🏷️ OpenViking, AI Agent, Python · ⏱️ 约 15 分钟