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
feat(tau2/vikingbot): config-driven experience recall + per-domain isolation (#2380)
yangxinxin-7936624c24bef
diff --git a/benchmark/tau2/llm/scripts/run_memory_v2_eval.py b/benchmark/tau2/llm/scripts/run_memory_v2_eval.pyindex 6cb3488b1..900181e57 100644--- a/benchmark/tau2/llm/scripts/run_memory_v2_eval.py+++ b/benchmark/tau2/llm/scripts/run_memory_v2_eval.py@@ -427,7 +427,7 @@ def _client(args: argparse.Namespace):client = ov.SyncHTTPClient(url=args.openviking_url,- api_key="",+ api_key=None,user=args.openviking_user,agent_id=args.openviking_agent_id,account=args.openviking_account,diff --git a/benchmark/tau2/vikingbot/README.md b/benchmark/tau2/vikingbot/README.mdindex d9d573c67..1ba38708b 100644--- a/benchmark/tau2/vikingbot/README.md+++ b/benchmark/tau2/vikingbot/README.md@@ -26,10 +26,17 @@ The pipeline is: **run tasks → evaluate reward → commit train trajectories t## Install & Config-One step sets up everything. `setup_env.sh` creates a fresh `.venv` at the OpenViking repo-root, clones tau2-bench into `./tau2-bench` (external dependency, gitignored), installs-openviking + vikingbot (`pip install -e .`, which also runs the Cargo build) and tau2-bench,-installs smolagents, then activates the venv and exports the runtime env vars:+> **Prerequisite — Python 3.12 or 3.13.** tau2-bench requires `>=3.12,<3.14`. `setup_env.sh`+> builds the venv with `python3 -m venv`, so `python3` must resolve to 3.12/3.13. If your+> `python3` is older (e.g. 3.11), pre-create the venv with a matching interpreter *before*+> sourcing — `python3.13 -m venv .venv` — otherwise the tau2-bench install step fails with+> `ERROR: Package 'tau2' requires a different Python`.++One step sets up everything. `setup_env.sh` creates a `.venv` at the OpenViking repo root+(if one isn't already present), clones tau2-bench into `./tau2-bench` (external dependency,+gitignored), installs openviking + vikingbot with the **`[bot]` extra**+(`pip install -e .[bot]`, which also runs the Cargo build) plus tau2-bench (`[gym]` extra) and+smolagents, then activates the venv and exports the runtime env vars:```bashsource benchmark/tau2/vikingbot/setup_env.sh # first run: install, then activate + export@@ -37,7 +44,8 @@ source benchmark/tau2/vikingbot/setup_env.sh --reinstall # rebuild the .venv fr```Safe to `source` in every new shell: the install phase runs only when the venv is missing;-later sources just activate and re-export.+later sources just activate and re-export. (`--reinstall` rebuilds with `python3 -m venv`, so+the same 3.12/3.13 requirement applies.)It exports `PYTHONPATH` for `openviking` + `bot/vikingbot`, `TAU2_DATA_ROOT`(defaults to `./tau2-bench/data/tau2`), `OPENVIKING_CONFIG_FILE`, and the user-simulator LLM@@ -142,14 +150,14 @@ python scripts/commit_trajectory_to_memory.py \## How the runner adapts VikingBot for tau2-There are **two layers** of adaptation:+Adaptation happens in two places:-1. **Runner-level** (this folder only, no core edits) — swap the agent's tool set over to the tau2- environment tools, gate OpenViking memory by epoch (cold start vs. memory-augmented), and commit- train trajectories between epochs. Detailed below.-2. **Core `bot/vikingbot`** edits — required for per-domain workspace isolation and for reading- *agent* (experience) memory instead of *user* memory. See- [Core `bot/vikingbot` changes for tau2](#core-botvikingbot-changes-for-tau2) below.+1. **Runner-level** (this folder only) — swap the agent's tool set over to the tau2 environment+ tools, gate OpenViking memory by epoch (cold start vs. memory-augmented), and commit train+ trajectories between epochs. Detailed below.+2. **`ov.conf` flags** — three OpenViking config flags switch VikingBot core into the+ experience-memory recall mode tau2 needs. **No core code edits required.** See+ [Required `ov.conf` flags for tau2](#required-ovconf-flags-for-tau2) below.### Runner-level adaptations:@@ -168,142 +176,82 @@ There are **two layers** of adaptation:(optionally only failed ones, via `--only-wrong`) into OpenViking memory between epochs.-### Core `bot/vikingbot` changes for tau2--Two behaviours in the VikingBot core-(`bot/vikingbot`) had to be changed for tau2:--1. **Per-domain workspace isolation via `agent_id`**- By default VikingBot do not support agent id- isolation in local mode. In order to easily test in local, changes are made so that each tau2 domain (airline, retail, …) read/write its own OpenViking namespace so experiences learned on one domain don't leak into another.-2. **Read *agent* (experience) memory at system-prompt build time**- By default VikingBot retrieves *user* memory when assembling the system message. For tau2 self-improvement we want to isolate the effect of the agent's own accumulated **experience** agent memory instead.---### Change 1 — `agent_id` isolation in `VikingClient` (`openviking_mount/ov_server.py`)--In `local` mode the client used to hardcode `agent_id = "default"` for every caller, so all-domains shared one namespace. It now reads the incoming `agent_id` and only falls back to-`"default"` when the id is a normal session key (which contains `__`, e.g. `cli__default`):--```diff- if openviking_config.mode == "local":-- self.client = ov.AsyncHTTPClient(url=openviking_config.server_url)-- self.agent_id = "default"-+ if agent_id is None or "__" in agent_id:-+ self.client = ov.AsyncHTTPClient(url=openviking_config.server_url)-+ self.agent_id = "default"-+ else:-+ self.client = ov.AsyncHTTPClient(-+ url=openviking_config.server_url,-+ agent_id=agent_id,-+ )-+ self.agent_id = agent_id- self.account_id = "default"- self.user_id = "default"- self.admin_user_id = "default"- return-```+### Required `ov.conf` flags for tau2++Two VikingBot behaviours need to change for tau2 self-improvement:++1. **Per-domain workspace isolation** — each tau2 domain (airline, retail, …) must read and+ write its own OpenViking namespace so experiences learned on one domain don't leak into+ another.+2. **Recall *agent experience* instead of *user* memory** — by default VikingBot pulls user+ memory into every turn. For tau2 we want the agent's own accumulated **experience** memory,+ pulled once per task, with a larger character budget per experience.++Both are now controlled by config — set these three flags in the `bot.ov_server` section of the+`ov.conf` pointed to by `OPENVIKING_CONFIG_FILE`:-(The `agent_id is None` guard is needed because `agent_id` defaults to `None`, and `"__" in None`-would raise `TypeError`.)--`search_experiences` then resolves the experience URI from this per-instance `agent_id` (a clean-domain id like `airline_v1` contains a single `_`), instead of always using the global config-`agent_id`:--```diff- 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"-+ if self.agent_id and "_" in self.agent_id:-+ effective_agent_id = self.agent_id- 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", [])+```jsonc+{+ "bot": {+ "ov_server": {+ "recall_exp_first_round_only": true, // skip per-turn user/agent recall; inject exp once on the first user turn+ "exp_recall_limit": 2, // fetch 2 experiences per task (default: 5)+ "exp_recall_max_chars": 10000 // character budget for the injected experience block (default: 2000)+ }+ }+}```+What each flag does:++- **`recall_exp_first_round_only`** — when `true`, `ContextBuilder._build_user_memory` skips the+ default `get_viking_memory_context` (user + agent memory, every turn) and instead calls+ `get_viking_experience_context` once, on the first user-turn of the session. The runner only+ ever sends one user turn per task, so this becomes "fetch experience once per task."+- **`exp_recall_limit`** — how many experiences to retrieve. tau2 prefers **fewer but longer**+ (2) over many shallow hits (5).+- **`exp_recall_max_chars`** — total character budget for the formatted experience block. Bumped+ to **10000** so each of the 2 experiences gets room for full context (default 2000 truncates).++Workspace isolation does not need a config flag: it follows automatically from `--agent-id`+plumbing, described below.+-#### How `agent_id` flows from the runner into the core+#### How `--agent-id` flows from the runner into the core-The domain id is threaded all the way down into the OpenViking client:+The `--agent-id airline_v0` you pass on the command line is threaded all the way down into the+OpenViking client, and resolves to `viking://agent/airline_v0/memories/experiences/`:```-run_full_test.sh AGENT_ID=${DOMAIN}_v1 # e.g. airline_v1, retail_v1- └─ run_tau2_domain.sh --agent-id airline_v1+run_full_test.sh AGENT_ID=${DOMAIN}_v0 # e.g. airline_v0, retail_v0+ └─ run_tau2_domain.sh --agent-id airline_v0└─ vikingbot_tau2_runner.py- build_messages(..., memory_users=agent_id) # memory_users == "airline_v1"+ build_messages(..., agent_id=agent_id) # explicit agent_id param└─ context.py _build_user_memory- workspace_id = memory_users # workspace_id == "airline_v1"- └─ memory.py get_viking_experience_context(query, workspace_id)- └─ _create_client(workspace_id)- └─ VikingClient.create(agent_id=workspace_id)- └─ ov_server.py VikingClient.__init__ / search_experiences- viking://agent/airline_v1/memories/experiences/+ exp_workspace_id = agent_id or _get_workspace_id(session_key)+ └─ memory.py get_viking_experience_context(query, exp_workspace_id)+ └─ VikingClient.create(agent_id=exp_workspace_id)+ └─ ov_server.py VikingClient.__init__ / search_experiences+ viking://agent/airline_v0/memories/experiences/```-So `--agent-id airline_v1` ⇒ the agent reads/writes `viking://agent/airline_v1/...`, giving each-domain an isolated workspace.--### Change 2 — system prompt reads *agent experience* memory (`agent/context.py`)--`_build_user_memory` (called by `build_messages` when assembling the system prompt) used to call-`get_viking_memory_context`, which retrieves **user** memory. For tau2 it now binds `workspace_id`-to the passed-in `memory_users` (the domain `agent_id`) and calls `get_viking_experience_context`-to retrieve the agent's **experience** memory:--```diff-- # Viking agent memory (only if ov tools are enabled)- if ov_tools_enable:- start = _time.time()- # Use provided memory_users or fall back to [sender_id]- search_user_ids = memory_users if memory_users else [sender_id]-- viking_memory = await self.memory.get_viking_memory_context(-- current_message=current_message,-- workspace_id=workspace_id,-- sender_id=sender_id,-- user_ids=search_user_ids,-- )-+ workspace_id = memory_users-+-+ viking_memory = await self.memory.get_viking_experience_context(-+ query=current_message,-+ workspace_id=workspace_id,-+ )- logger.info(f"viking_memory={viking_memory}")- cost = round(_time.time() - start, 2)- logger.info(-- f"[READ_USER_MEMORY]: cost {cost}s, memory={viking_memory[:50] if viking_memory else 'None'}"-+ f"[READ_AGENT_MEMORY]: cost {cost}s, memory={viking_memory[:50] if viking_memory else 'None'}"- )- if viking_memory:- self.latest_relevant_memories = viking_memory-- parts.append(f"## openviking_search(query=[user_query])\n{viking_memory}")-+ parts.append(f"## openviking_search(query=[user_query])\n ## Agent Experience (relevant to this task)\n {viking_memory}")- else:- self.latest_relevant_memories = None-```--The key line is `workspace_id = memory_users`: the runner passes the domain id as `memory_users`,-and it becomes the `agent_id` used to open the (isolated) OpenViking client downstream.+Isolation holds in **both** `local` and `remote` `bot.ov_server.mode` (no patching required):-### Change 3 — supporting edits in `agent/memory.py`+- `VikingClient.__init__` — in `remote` mode (root api-key, account/user auth) the incoming+ `agent_id` is *always* threaded into the HTTP client, so per-domain isolation already holds.+ In `local` mode (no auth, account/user fixed to `default`) the client used to hardcode+ `agent_id="default"` — collapsing every domain into one namespace — and now opens against the+ given `agent_id` whenever it isn't a session key (contains no `__`), giving local runs the same+ isolation as remote.+- `search_experiences` — in both modes, prefers the per-instance `self.agent_id` (a non-session+ id, e.g. `airline_v0`) over the global `openviking_config.agent_id`.-`get_viking_experience_context` is the experience-retrieval path that Change 2 now calls.--Retrieval limits in `get_viking_experience_context` were also tuned for tau2 (fewer experiences,-more characters per experience):+So `--agent-id airline_v0` ⇒ the agent reads/writes `viking://agent/airline_v0/...`, giving each+domain an isolated workspace.-```diff-- experiences = await client.search_experiences(query, limit=5)-+ experiences = await client.search_experiences(query, limit=2)- ...- return await self._parse_viking_memory(-- experiences, client, min_score=0.3, max_chars=2000-+ experiences, client, min_score=0.3, max_chars=10000- )-```+> Verified end-to-end in both modes: after committing a trajectory under `airline_v0`, the+> experience is recalled **only** when querying with `--agent-id airline_v0`, and never leaks to+> a different agent id (a control id with nothing written returns zero hits).---diff --git a/benchmark/tau2/vikingbot/scripts/vikingbot_tau2_runner.py b/benchmark/tau2/vikingbot/scripts/vikingbot_tau2_runner.pyindex 39aa9de41..3f17985df 100644--- a/benchmark/tau2/vikingbot/scripts/vikingbot_tau2_runner.py+++ b/benchmark/tau2/vikingbot/scripts/vikingbot_tau2_runner.py@@ -149,7 +149,7 @@ async def _run_agent(ov_tools_enable=keep_default_tools,media=None,profile_user_list=[],- memory_users=agent_id,+ agent_id=agent_id,)if system_prompt:messages.insert(1, {"role": "system", "content": system_prompt})diff --git a/bot/vikingbot/agent/context.py b/bot/vikingbot/agent/context.pyindex db81ad92f..13c45a49f 100644--- a/bot/vikingbot/agent/context.py+++ b/bot/vikingbot/agent/context.py@@ -12,6 +12,7 @@ from loguru import loggerfrom vikingbot.agent.memory import MemoryStorefrom vikingbot.agent.skills import SkillsLoader+from vikingbot.config.loader import load_configfrom vikingbot.config.schema import SessionKeyfrom vikingbot.sandbox import SandboxManagerfrom vikingbot.utils.helpers import ensure_non_empty_assistant_content@@ -167,6 +168,8 @@ Skills with available="false" need dependencies installed first - you can try insender_id: str,memory_users: list[str] | None = None,ov_tools_enable: bool = True,+ is_first_round: bool = True,+ agent_id: str | None = None,) -> str:"""Build the system prompt from bootstrap files, memory, and skills.@@ -198,25 +201,48 @@ Skills with available="false" need dependencies installed first - you can try in# Viking agent memory (only if ov tools are enabled)if ov_tools_enable:- start = _time.time()- # Use provided memory_users or fall back to [sender_id]- search_user_ids = memory_users if memory_users else [sender_id]- viking_memory = await self.memory.get_viking_memory_context(- current_message=current_message,- workspace_id=workspace_id,- sender_id=sender_id,- user_ids=search_user_ids,- )- logger.info(f"viking_memory={viking_memory}")- cost = round(_time.time() - start, 2)- logger.info(- f"[READ_USER_MEMORY]: cost {cost}s, memory={viking_memory[:50] if viking_memory else 'None'}"- )- if viking_memory:- self.latest_relevant_memories = viking_memory- parts.append(f"## openviking_search(query=[user_query])\n{viking_memory}")- else:+ exp_first_round_only = load_config().ov_server.recall_exp_first_round_only++ if exp_first_round_only:+ # Alt mode: skip per-turn user+agent recall; inject exp once per session.+ # When the caller provides an explicit agent_id (e.g. tau2 runner passing+ # a per-domain id like "airline_v0"), use it as the experience workspace+ # so retrieval targets viking://agent/<agent_id>/memories/experiences/.+ exp_workspace_id = agent_id or workspace_idself.latest_relevant_memories = None+ if is_first_round:+ start = _time.time()+ exp_memory = await self.memory.get_viking_experience_context(+ query=current_message, workspace_id=exp_workspace_id+ )+ cost = round(_time.time() - start, 2)+ logger.info(+ f"[READ_EXP_FIRST_ROUND]: cost {cost}s, "+ f"exp={exp_memory[:50] if exp_memory else 'None'}"+ )+ if exp_memory:+ self.latest_relevant_memories = exp_memory+ parts.append(f"## Relevant Agent Experience\n{exp_memory}")+ else:+ start = _time.time()+ # Use provided memory_users or fall back to [sender_id]+ search_user_ids = memory_users if memory_users else [sender_id]+ viking_memory = await self.memory.get_viking_memory_context(+ current_message=current_message,+ workspace_id=workspace_id,+ sender_id=sender_id,+ user_ids=search_user_ids,+ )+ logger.info(f"viking_memory={viking_memory}")+ cost = round(_time.time() - start, 2)+ logger.info(+ f"[READ_USER_MEMORY]: cost {cost}s, memory={viking_memory[:50] if viking_memory else 'None'}"+ )+ if viking_memory:+ self.latest_relevant_memories = viking_memory+ parts.append(f"## openviking_search(query=[user_query])\n{viking_memory}")+ else:+ self.latest_relevant_memories = Noneparts.append("Reply in the same language as the user's query, ignoring the language of the reference materials. User's query:"@@ -288,6 +314,7 @@ IMPORTANT:ov_tools_enable: bool = True,profile_user_list: list[str] | None = None,memory_users: list[str] | None = None,+ agent_id: str | None = None,) -> list[dict[str, Any]]:"""Build the complete message list for an LLM call.@@ -324,6 +351,8 @@ IMPORTANT:self._sender_id,memory_users,ov_tools_enable=ov_tools_enable,+ is_first_round=not history,+ agent_id=agent_id,)messages.append({"role": "user", "content": user_info})diff --git a/bot/vikingbot/agent/memory.py b/bot/vikingbot/agent/memory.pyindex 6c1074581..78c18f911 100644--- a/bot/vikingbot/agent/memory.py+++ b/bot/vikingbot/agent/memory.py@@ -194,8 +194,9 @@ class MemoryStore:"""用当前任务 query 检索 experience 记忆,注入到 system prompt。"""client = Nonetry:+ ov_cfg = load_config().ov_serverclient = await VikingClient.create(agent_id=workspace_id)- experiences = await client.search_experiences(query, limit=5)+ experiences = await client.search_experiences(query, limit=ov_cfg.exp_recall_limit)logger.info(f"[READ_EXPERIENCE_MEMORY]: found {len(experiences)} experiences, query={query[:50]}")@@ -206,7 +207,7 @@ class MemoryStore:if not experiences:return ""return await self._parse_viking_memory(- experiences, client, min_score=0.3, max_chars=2000+ experiences, client, min_score=0.3, max_chars=ov_cfg.exp_recall_max_chars)except Exception as e:logger.error(f"[READ_EXPERIENCE_MEMORY]: error. {e}")diff --git a/bot/vikingbot/config/schema.py b/bot/vikingbot/config/schema.pyindex 19f972931..7843e31e0 100644--- a/bot/vikingbot/config/schema.py+++ b/bot/vikingbot/config/schema.py@@ -521,6 +521,18 @@ class OpenVikingConfig(BaseModel):admin_user_id: str = "default"agent_id: str = ""exp_write_tools: list[str] = Field(default_factory=lambda: ["write_file", "edit_file"])+ # When True, switch auto-recall mode: skip the per-turn user+agent memory retrieval+ # entirely, and instead retrieve experience memory once per session (on the first+ # user-turn build of _build_user_memory) and inject it into that user message.+ # When False, keep the default behavior (user+agent memory retrieved every turn).+ # NOTE: in True mode no memory is injected on later turns of a multi-turn session, so+ # it suits single-turn / per-task runners (e.g. tau2) rather than long conversations.+ recall_exp_first_round_only: bool = False+ # How many experience memories to fetch per call to get_viking_experience_context.+ exp_recall_limit: int = 5+ # Total character budget for the injected experience block. Memories beyond this+ # budget are degraded to link-only (uri + score) instead of being dropped.+ exp_recall_max_chars: int = 2000@field_validator("api_key_type", mode="before")@classmethoddiff --git a/bot/vikingbot/openviking_mount/ov_server.py b/bot/vikingbot/openviking_mount/ov_server.pyindex 051ffbd55..a20adb11e 100644--- a/bot/vikingbot/openviking_mount/ov_server.py+++ b/bot/vikingbot/openviking_mount/ov_server.py@@ -11,6 +11,16 @@ from vikingbot.openviking_mount.user_apikey_manager import UserApiKeyManagerviking_resource_prefix = "viking://resources/"+def _is_session_key(agent_id: Optional[str]) -> bool:+ """Whether agent_id is a session key rather than a standalone agent workspace.++ Session keys (e.g. "cli__default__<uuid>") contain "__"; a per-domain id such as+ the tau2 domain "airline_v0" does not, and is treated as an isolated agent+ namespace instead of the shared "default" one.+ """+ return agent_id is not None and "__" in agent_id++class VikingClient:def __init__(self, agent_id: Optional[str] = None):config = load_config()@@ -32,8 +42,18 @@ class VikingClient:self._namespace_policy_loaded = Falseif openviking_config.mode == "local":- self.client = ov.AsyncHTTPClient(url=openviking_config.server_url)- self.agent_id = "default"+ # Session keys fall back to the shared "default" namespace; a standalone+ # per-domain id (e.g. "airline_v0") is treated as an isolated agent workspace+ # and threaded into the HTTP client so storage is scoped per id.+ if agent_id is None or _is_session_key(agent_id):+ self.client = ov.AsyncHTTPClient(url=openviking_config.server_url)+ self.agent_id = "default"+ else:+ self.client = ov.AsyncHTTPClient(+ url=openviking_config.server_url,+ agent_id=agent_id,+ )+ self.agent_id = agent_idself.account_id = "default"self.user_id = "default"self.admin_user_id = "default"@@ -439,6 +459,10 @@ class VikingClient: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"+ # A per-instance, non-session agent_id overrides the global config so each domain+ # reads from its own experience namespace.+ if self.agent_id and not _is_session_key(self.agent_id):+ effective_agent_id = self.agent_idexp_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", [])