Skip to content

Self-evolving Context Database for AI Agents. Unify Agent Memory, Knowledge RAG and Skills.

feat(vikingbot): self-evolving agent memory with experience injection (#2007)

yangxinxin-7dcac2669859d
diff --git a/bot/vikingbot/agent/loop.py b/bot/vikingbot/agent/loop.py
index 5801874c9..be8da484f 100644
--- a/bot/vikingbot/agent/loop.py
+++ b/bot/vikingbot/agent/loop.py
@@ -290,6 +290,7 @@ class AgentLoop:
"completion_tokens": 0,
"total_tokens": 0,
}
+ write_exp_injected = False
while iteration < self.max_iterations:
iteration += 1
@@ -325,6 +326,33 @@ class AgentLoop:
)
if response.has_tool_calls:
+ # Inject experience memory before write-related tool calls (once per session)
+ if not write_exp_injected:
+ _ov_cfg = load_config().ov_server
+ _write_tools = set(_ov_cfg.exp_write_tools)
+ if any(tc.name in _write_tools for tc in response.tool_calls):
+ write_exp_injected = True
+ try:
+ # Build query from last 3 user messages
+ _user_msgs = [
+ m["content"] for m in messages
+ if m.get("role") == "user" and isinstance(m.get("content"), str)
+ ]
+ _query = "\n".join(_user_msgs[-3:])
+ workspace_id = self.sandbox_manager.to_workspace_id(session_key) if self.sandbox_manager else "shared"
+ _exp = await self.context.memory.get_viking_experience_context(
+ query=_query, workspace_id=workspace_id
+ )
+ logger.info(f"[WRITE_EXP]: write tool detected, exp_found={bool(_exp)}, query={_query[:50]}")
+ if _exp:
+ messages.append({
+ "role": "user",
+ "content": f"## Relevant Agent Experience\n{_exp}",
+ })
+ continue
+ except Exception as _e:
+ logger.warning(f"[WRITE_EXP]: failed to load experience: {_e}")
+
final_reasoning_content = response.reasoning_content
args_list = [tc.arguments for tc in response.tool_calls]
tool_call_dicts = [
diff --git a/bot/vikingbot/agent/memory.py b/bot/vikingbot/agent/memory.py
index 4fbf7bb0d..745a4801a 100644
--- a/bot/vikingbot/agent/memory.py
+++ b/bot/vikingbot/agent/memory.py
@@ -199,6 +199,34 @@ class MemoryStore:
except Exception as e:
logger.warning(f"Error closing VikingClient: {e}")
+ async def get_viking_experience_context(self, query: str, workspace_id: str) -> str:
+ """用当前任务 query 检索 experience 记忆,注入到 system prompt。"""
+ client = None
+ try:
+ client = await self._create_client(workspace_id)
+ if not client:
+ return ""
+ experiences = await client.search_experiences(query, limit=5)
+ logger.info(f"[READ_EXPERIENCE_MEMORY]: found {len(experiences)} experiences, query={query[:50]}")
+ for i, exp in enumerate(experiences):
+ uri = exp.get("uri", "") if isinstance(exp, dict) else getattr(exp, "uri", "")
+ score = exp.get("score", 0) if isinstance(exp, dict) else getattr(exp, "score", 0)
+ logger.info(f" {i},{uri},{score}")
+ if not experiences:
+ return ""
+ return await self._parse_viking_memory(
+ experiences, client, min_score=0.3, max_chars=2000
+ )
+ except Exception as e:
+ logger.error(f"[READ_EXPERIENCE_MEMORY]: error. {e}")
+ return ""
+ finally:
+ if client:
+ try:
+ await client.close()
+ except Exception:
+ pass
+
async def get_viking_user_profile(self, workspace_id: str, user_id: str) -> str:
client = None
try:
@@ -237,7 +265,6 @@ class MemoryStore:
return ""
async def fetch_profile(user_id: str) -> tuple[str, str]:
- """Fetch a single user profile."""
try:
start_time = time.time()
profile = await client.read_user_profile(user_id)
@@ -251,11 +278,9 @@ class MemoryStore:
logger.error(f"[READ_USER_PROFILE]: user_id={user_id}, error. {e}")
return (user_id, "")
- # Fetch all profiles concurrently
tasks = [fetch_profile(user_id) for user_id in user_ids]
results = await asyncio.gather(*tasks, return_exceptions=True)
- # Build the result string
parts = []
for result in results:
if isinstance(result, Exception):
@@ -273,4 +298,4 @@ class MemoryStore:
try:
await client.close()
except Exception as e:
- logger.warning(f"Error closing VikingClient: {e}")
\ No newline at end of file
+ logger.warning(f"Error closing VikingClient: {e}")
diff --git a/bot/vikingbot/agent/subagent.py b/bot/vikingbot/agent/subagent.py
index 81818129d..ed2faf044 100644
--- a/bot/vikingbot/agent/subagent.py
+++ b/bot/vikingbot/agent/subagent.py
@@ -92,11 +92,29 @@ class SubagentManager:
config=self.config,
)
+ # Search experience memory relevant to this subtask
+ task_content = task
+ try:
+ from vikingbot.agent.memory import MemoryStore
+ memory_store = MemoryStore(self.workspace)
+ workspace_id = (
+ self.sandbox_manager.to_workspace_id(session_key)
+ if self.sandbox_manager
+ else "shared"
+ )
+ exp_memory = await memory_store.get_viking_experience_context(
+ query=task, workspace_id=workspace_id
+ )
+ if exp_memory:
+ task_content = f"## Agent Experience (relevant to this task)\n{exp_memory}\n\n---\n\n{task}"
+ except Exception as e:
+ logger.warning(f"Subagent [{task_id}] failed to load experience memory: {e}")
+
# Build messages with subagent-specific prompt
system_prompt = self._build_subagent_prompt(task)
messages: list[dict[str, Any]] = [
{"role": "system", "content": system_prompt},
- {"role": "user", "content": task},
+ {"role": "user", "content": task_content},
]
# Run agent loop (limited iterations)
diff --git a/bot/vikingbot/config/schema.py b/bot/vikingbot/config/schema.py
index b23a8739a..19e7db3e6 100644
--- a/bot/vikingbot/config/schema.py
+++ b/bot/vikingbot/config/schema.py
@@ -516,6 +516,7 @@ class OpenVikingConfig(BaseModel):
account_id: str = "default"
admin_user_id: str = "default"
agent_id: str = ""
+ exp_write_tools: list[str] = Field(default_factory=lambda: ["write_file", "edit_file"])
@field_validator("api_key_type", mode="before")
@classmethod
diff --git a/bot/vikingbot/hooks/builtins/openviking_hooks.py b/bot/vikingbot/hooks/builtins/openviking_hooks.py
index 895eba87d..6f0ae13ab 100644
--- a/bot/vikingbot/hooks/builtins/openviking_hooks.py
+++ b/bot/vikingbot/hooks/builtins/openviking_hooks.py
@@ -99,19 +99,28 @@ class OpenVikingPostCallHook(Hook):
async def _get_client(self, workspace_id: str) -> VikingClient:
return await get_global_client(workspace_id)
- async def _read_skill_memory(self, workspace_id: str, skill_name: str) -> str:
- ov_client = await self._get_client(workspace_id)
- config = load_config()
- openviking_config = config.ov_server
- if not skill_name:
+ async def _search_skill_experiences(self, workspace_id: str, query: str) -> str:
+ """用 skill 描述检索 experience 记忆,只检索 experiences 目录。"""
+ if not query:
return ""
try:
- skill_owner_user_id = None if openviking_config.mode == "local" else openviking_config.admin_user_id
- skill_memory_uri = ov_client._skill_memory_uri(skill_name, skill_owner_user_id)
- content = await ov_client.read_content(skill_memory_uri, level="read")
- return f"\n\n---\n## Skill Memory\n{content}" if content else ""
+ ov_client = await self._get_client(workspace_id)
+ experiences = await ov_client.search_experiences(query, limit=3)
+ logger.info(f"[SKILL_EXP]: found {len(experiences)} experiences, query={query[:50]}")
+ if not experiences:
+ return ""
+ parts = []
+ for exp in experiences:
+ uri = exp.get("uri", "") if isinstance(exp, dict) else getattr(exp, "uri", "")
+ score = exp.get("score", 0) if isinstance(exp, dict) else getattr(exp, "score", 0)
+ if score < 0.3:
+ continue
+ content = await ov_client.read_content(uri, level="read")
+ if content:
+ parts.append(content)
+ return "\n\n---\n".join(parts) if parts else ""
except Exception as e:
- logger.warning(f"Failed to read skill memory for {skill_name}: {e}")
+ logger.warning(f"Failed to search experiences for skill: {e}")
return ""
async def execute(self, context: HookContext, tool_name, params, result) -> Any:
@@ -120,15 +129,12 @@ class OpenVikingPostCallHook(Hook):
match = re.search(r"^---\s*\nname:\s*(.+?)\s*\n", result, re.MULTILINE)
if match:
skill_name = match.group(1).strip()
- # logger.debug(f"skill_name={skill_name}")
-
- agent_space_name = context.workspace_id
- # logger.debug(f"agent_space_name={agent_space_name}")
+ desc_match = re.search(r"^description:\s*(.+)$", result, re.MULTILINE)
+ skill_query = desc_match.group(1).strip() if desc_match else skill_name
- skill_memory = await self._read_skill_memory(agent_space_name, skill_name)
- # logger.debug(f"skill_memory={skill_memory}")
- if skill_memory:
- result = f"{result}{skill_memory}"
+ exp_memory = await self._search_skill_experiences(context.workspace_id, skill_query)
+ if exp_memory:
+ result = f"{result}\n\n---\n## Related Experiences\n{exp_memory}"
return {"tool_name": tool_name, "params": params, "result": result}
diff --git a/bot/vikingbot/openviking_mount/ov_server.py b/bot/vikingbot/openviking_mount/ov_server.py
index b350eb5c7..b51fd29ae 100644
--- a/bot/vikingbot/openviking_mount/ov_server.py
+++ b/bot/vikingbot/openviking_mount/ov_server.py
@@ -1,5 +1,4 @@
import asyncio
-import hashlib
import time
from typing import Any, Dict, List, Optional
@@ -199,6 +198,7 @@ class VikingClient:
def should_sender_fanout(self) -> bool:
return self._is_root_key_mode()
+
async def find(self, query: str, target_uri: Optional[str] = None):
"""搜索资源"""
if target_uri:
@@ -365,7 +365,7 @@ class VikingClient:
async def search_memory(
self, query: str, user_ids: str | list[str], agent_user_id: str, limit: int = 10
) -> dict[str, list[Any]]:
- """通过上下文消息,检索viking 的user、Agent memory。"""
+ """通过上下文消息,检索viking 的user memory(agent memory 已关闭自动检索)。"""
await self._load_namespace_policy()
def _extract_memories(result: Any) -> list[Any]:
@@ -383,7 +383,6 @@ class VikingClient:
user_ids = [user_ids]
all_user_memories = []
- all_agent_memories = []
for user_id in user_ids:
effective_user_id = self._effective_user_id(user_id)
@@ -400,19 +399,14 @@ class VikingClient:
)
all_user_memories.extend(_extract_memories(user_memory))
- effective_agent_user_id = self._effective_user_id(agent_user_id)
- uri_agent_memory = self._agent_memory_target_uri(effective_agent_user_id)
- agent_memory = await self.client.find(
- query=query,
- target_uri=uri_agent_memory,
- limit=limit,
- )
- all_agent_memories.extend(_extract_memories(agent_memory))
+ return {"user_memory": all_user_memories, "agent_memory": []}
- return {
- "user_memory": all_user_memories,
- "agent_memory": all_agent_memories,
- }
+ async def search_experiences(self, query: str, limit: int = 5) -> list[Any]:
+ """用 query 检索 agent experience 记忆。"""
+ effective_agent_id = self.openviking_config.agent_id or "default"
+ exp_uri = f"viking://agent/{effective_agent_id}/memories/experiences/"
+ result = await self.search(query=query, target_uri=exp_uri, limit=limit)
+ return result.get("memories", [])
async def grep(
self,