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
fix(bot):Fix bot search tool's result, opt the answer when iteration limit reach (#2810)
DuTaoa9f781c5e191
diff --git a/bot/tests/test_agent_loop_outcome.py b/bot/tests/test_agent_loop_outcome.pyindex 6ff1cbcaf..12f122ec6 100644--- a/bot/tests/test_agent_loop_outcome.py+++ b/bot/tests/test_agent_loop_outcome.py@@ -9,7 +9,7 @@ from vikingbot.bus.events import InboundMessage, OutboundEventTypefrom vikingbot.bus.queue import MessageBusfrom vikingbot.config.schema import Config, SessionKeyfrom vikingbot.heartbeat.service import HEARTBEAT_METADATA_KEY-from vikingbot.providers.base import LLMProvider+from vikingbot.providers.base import LLMProvider, LLMResponse, ToolCallRequestclass _FakeProvider(LLMProvider):@@ -73,6 +73,114 @@ class _FakeOVClient:return {"session_id": session_id, "status": "accepted"}+async def test_agent_loop_makes_final_no_tool_call_when_iteration_limit_reached(+ temp_dir: Path, monkeypatch+):+ monkeypatch.setattr(AgentLoop, "_register_builtin_hooks", lambda self: None)+ monkeypatch.setattr(AgentLoop, "_register_default_tools", lambda self: None)+ monkeypatch.setattr("vikingbot.agent.loop.SubagentManager", _FakeSubagentManager)++ class _OVConfig:+ exp_write_tools = []++ class _LoadedConfig:+ ov_server = _OVConfig()++ monkeypatch.setattr(loop_module, "load_config", lambda: _LoadedConfig())++ class _ToolLimitProvider(LLMProvider):+ def __init__(self):+ super().__init__()+ self.calls = []++ async def chat(self, messages, tools=None, **kwargs):+ self.calls.append(+ {+ "messages": [dict(message) for message in messages],+ "tools": list(tools or []),+ "kwargs": kwargs,+ }+ )+ if len(self.calls) == 1:+ return LLMResponse(+ content=None,+ tool_calls=[+ ToolCallRequest(+ id="call-1",+ name="lookup_fact",+ arguments={"query": "current facts"},+ tokens=3,+ )+ ],+ usage={"prompt_tokens": 10, "completion_tokens": 2, "total_tokens": 12},+ )+ return LLMResponse(+ content="final answer from gathered tool results",+ usage={"prompt_tokens": 7, "completion_tokens": 5, "total_tokens": 12},+ )++ def get_default_model(self) -> str:+ return "fake-model"++ class _ToolRegistry:+ def __init__(self):+ self.execute_calls = []++ def get_definitions(self, **kwargs):+ return [+ {+ "type": "function",+ "function": {+ "name": "lookup_fact",+ "description": "Lookup fact",+ "parameters": {"type": "object", "properties": {}},+ },+ }+ ]++ async def execute(self, tool_name, arguments, **kwargs):+ self.execute_calls.append((tool_name, arguments, kwargs))+ return "tool result: useful context"++ provider = _ToolLimitProvider()+ tools = _ToolRegistry()+ bus = MessageBus()+ config = Config(storage_workspace=str(temp_dir))+ loop = AgentLoop(+ bus=bus,+ provider=provider,+ workspace=temp_dir / "workspace",+ config=config,+ max_iterations=1,+ )+ loop.tools = tools++ session_key = SessionKey(type="cli", channel_id="default", chat_id="session-limit")+ final_content, _reasoning, tools_used, token_usage, iteration = await loop._run_agent_loop(+ messages=[{"role": "user", "content": "please answer with lookup"}],+ session_key=session_key,+ publish_events=False,+ )++ assert final_content == "final answer from gathered tool results"+ assert iteration == 1+ assert len(provider.calls) == 2+ assert provider.calls[0]["tools"]+ assert provider.calls[1]["tools"] == []+ assert provider.calls[1]["messages"][-1]["content"].startswith(+ "Tool-use iteration limit reached."+ )+ assert any(+ message.get("content") == "tool result: useful context"+ for message in provider.calls[1]["messages"]+ )+ assert len(tools.execute_calls) == 1+ assert tools.execute_calls[0][:2] == ("lookup_fact", {"query": "current facts"})+ assert [tool["tool_name"] for tool in tools_used] == ["lookup_fact"]+ assert token_usage == {"prompt_tokens": 17, "completion_tokens": 7, "total_tokens": 24}++@pytest.mark.asyncioasync def test_agent_loop_evaluates_previous_response_outcome_before_new_user_turn(temp_dir: Path, monkeypatch@@ -257,8 +365,10 @@ async def test_agent_loop_build_prompt_history_uses_ov_context_plus_unsynced_tai})- async def fake_get_ov_client(self, session_key, openviking_connection=None):- del session_key, openviking_connection+ async def fake_get_ov_client(+ self, session_key, openviking_connection=None, actor_peer_id=None+ ):+ del session_key, openviking_connection, actor_peer_idreturn fake_ov_clientmonkeypatch.setattr(AgentLoop, "_get_ov_client", fake_get_ov_client)@@ -310,8 +420,10 @@ async def test_agent_loop_build_prompt_history_skips_tail_when_sync_cursor_is_pacontext_payload={"messages": [{"role": "user", "content": "OV user turn"}]})- async def fake_get_ov_client(self, session_key, openviking_connection=None):- del self, session_key, openviking_connection+ async def fake_get_ov_client(+ self, session_key, openviking_connection=None, actor_peer_id=None+ ):+ del self, session_key, openviking_connection, actor_peer_idreturn fake_ov_clientmonkeypatch.setattr(AgentLoop, "_get_ov_client", fake_get_ov_client)@@ -415,14 +527,19 @@ async def test_agent_loop_commits_openviking_before_model_when_pending_tokens_restate["last_synced_local_index"] = len(session.messages) - 1return kwargs- async def fake_get_ov_client(self, session_key, openviking_connection=None):- del self, session_key, openviking_connection+ async def fake_get_ov_client(+ self, session_key, openviking_connection=None, actor_peer_id=None+ ):+ del self, session_key, openviking_connection, actor_peer_idclass _Client:async def get_session_context(self, session_id, token_budget):events.append(("context", session_id, token_budget))return {"messages": []}+ async def close(self):+ return None+return _Client()async def fake_run_agent_loop(self, **kwargs):@@ -515,14 +632,19 @@ async def test_agent_loop_commits_openviking_before_model_when_memory_window_reasession.metadata["openviking"]["last_commit_performed"] = bool(kwargs["force_commit"])return kwargs- async def fake_get_ov_client(self, session_key, openviking_connection=None):- del self, session_key, openviking_connection+ async def fake_get_ov_client(+ self, session_key, openviking_connection=None, actor_peer_id=None+ ):+ del self, session_key, openviking_connection, actor_peer_idclass _Client:async def get_session_context(self, session_id, token_budget):events.append(("context", session_id, token_budget))return {"messages": []}+ async def close(self):+ return None+return _Client()async def fake_run_agent_loop(self, **kwargs):diff --git a/bot/tests/test_openviking_api_key_type.py b/bot/tests/test_openviking_api_key_type.pyindex 0d303653c..0cafa12b4 100644--- a/bot/tests/test_openviking_api_key_type.py+++ b/bot/tests/test_openviking_api_key_type.py@@ -213,6 +213,58 @@ def test_user_key_current_memory_targets_use_current_user_shorthand(monkeypatch)]+async def test_viking_client_search_preserves_serialized_group_results(monkeypatch):+ monkeypatch.setattr(ov_server_module, "load_config", lambda: _make_config("user"))+ client = VikingClient()++ async def _search(query, target_uri=None, limit=10):+ return {+ "memories": [+ {+ "context_type": "memory",+ "uri": "viking://user/default/memories/profile.md",+ "abstract": "profile hit",+ "score": 0.3,+ }+ ],+ "resources": [+ {+ "context_type": "resource",+ "uri": "viking://resources/解释信-杜涛/解释信-杜涛.md",+ "abstract": "resource hit",+ "score": 0.4,+ }+ ],+ "skills": [+ {+ "context_type": "skill",+ "uri": "viking://user/default/skills/planner.md",+ "abstract": "skill hit",+ "score": 0.2,+ }+ ],+ "total": 3,+ }++ monkeypatch.setattr(client.client, "search", _search)++ result = await client.search("解释信", target_uri="", limit=10)++ assert result["total"] == 3+ assert result["query"] == "解释信"+ assert result["target_uri"] == ""+ assert [item["uri"] for item in result["memories"]] == [+ "viking://user/default/memories/profile.md"+ ]+ assert [item["uri"] for item in result["resources"]] == [+ "viking://resources/解释信-杜涛/解释信-杜涛.md"+ ]+ assert [item["uri"] for item in result["skills"]] == [+ "viking://user/default/skills/planner.md"+ ]++def test_ov_server_api_key_mode_ignores_bot_root_key_and_uses_ovcli_user_key(monkeypatch):bot_data = {"root_api_key": "bot-root-key"}ov_data = {"root_api_key": "server-root-key"}@@ -2276,7 +2328,7 @@ async def test_openviking_search_user_key_mode_uses_current_user_namespace(monke@pytest.mark.asyncio-async def test_openviking_search_actor_client_uses_server_default_scope(monkeypatch):+async def test_openviking_search_actor_client_expands_current_peer_scope(monkeypatch):tool = VikingSearchTool()calls = []@@ -2286,6 +2338,14 @@ async def test_openviking_search_actor_client_uses_server_default_scope(monkeypadef should_sender_fanout(self):return True+ def _memory_target_uri(self, _user_id=None):+ return "viking://user/memories/"++ def build_current_memory_target_uris(self, *, peer_ids=None, include_self=True):+ uris = ["viking://user/memories/"] if include_self else []+ uris.extend(f"viking://user/peers/{peer_id}/memories/" for peer_id in peer_ids or [])+ return uris+async def search(self, query, target_uri=None, limit=20, user_id=None):calls.append((target_uri, user_id))return {@@ -2308,7 +2368,15 @@ async def test_openviking_search_actor_client_uses_server_default_scope(monkeyparesult = await tool.execute(tool_context, query="hello")assert "sender-0/memories" in result- assert calls == [("", None), ("close", None)]+ assert calls == [+ ("viking://resources/", None),+ ("viking://user/memories/", None),+ ("viking://user/skills/", None),+ ("viking://user/peers/sender-0/memories/", None),+ ("viking://user/peers/sender-1/memories/", None),+ ("viking://user/peers/sender-2/memories/", None),+ ("close", None),+ ]@pytest.mark.asynciodiff --git a/bot/vikingbot/agent/loop.py b/bot/vikingbot/agent/loop.pyindex e6096a146..a510b6bce 100644--- a/bot/vikingbot/agent/loop.py+++ b/bot/vikingbot/agent/loop.py@@ -680,6 +680,14 @@ class AgentLoop:}write_exp_injected = False+ def accumulate_token_usage(response: Any) -> None:+ if not response.usage:+ return+ cur_token = response.usage+ token_usage["prompt_tokens"] += cur_token.get("prompt_tokens", 0)+ token_usage["completion_tokens"] += cur_token.get("completion_tokens", 0)+ token_usage["total_tokens"] += cur_token.get("total_tokens", 0)+while iteration < self.max_iterations:iteration += 1@@ -702,11 +710,7 @@ class AgentLoop:session_key=session_key,publish_events=publish_events,)- if response.usage:- cur_token = response.usage- token_usage["prompt_tokens"] += cur_token["prompt_tokens"]- token_usage["completion_tokens"] += cur_token["completion_tokens"]- token_usage["total_tokens"] += cur_token["total_tokens"]+ accumulate_token_usage(response)if publish_events and response.reasoning_content and not streamed_reasoning:await self.bus.publish_outbound(@@ -849,7 +853,43 @@ class AgentLoop:if final_content is None or (isinstance(final_content, str) and not final_content.strip()):if iteration >= self.max_iterations:- final_content = f"Reached {self.max_iterations} iterations without completion."+ messages.append(+ {+ "role": "user",+ "content": (+ "Tool-use iteration limit reached. Do not call any more tools. "+ "Answer the user's original request directly using only the "+ "conversation, tool calls, and tool results already available above. "+ "If the gathered information is incomplete, explain the best-known "+ "answer and clearly note what remains uncertain."+ ),+ }+ )+ response, _streamed_content, streamed_reasoning = await self._chat_with_stream_events(+ messages=messages,+ tools=[],+ session_key=session_key,+ publish_events=publish_events,+ )+ accumulate_token_usage(response)+ final_content = response.content+ final_reasoning_content = response.reasoning_content++ if publish_events and response.reasoning_content and not streamed_reasoning:+ await self.bus.publish_outbound(+ OutboundMessage(+ session_key=session_key,+ content=response.reasoning_content,+ event_type=OutboundEventType.REASONING,+ )+ )++ if final_content is None or (isinstance(final_content, str) and not final_content.strip()):+ if iteration >= self.max_iterations:+ final_content = (+ "I reached the tool-use limit before completing every step, and the "+ "available tool results are not enough for a reliable final answer."+ )else:final_content = "I've completed processing but have no response to give."diff --git a/bot/vikingbot/agent/tools/ov_file.py b/bot/vikingbot/agent/tools/ov_file.pyindex 5d467c6bb..b9854d218 100644--- a/bot/vikingbot/agent/tools/ov_file.py+++ b/bot/vikingbot/agent/tools/ov_file.py@@ -426,9 +426,10 @@ class VikingSearchTool(OVFileTool):else:peer_ids = self._memory_peer_ids(tool_context)if not target_uri:- if getattr(client, "actor_peer_id", None):- target_uris = [""]- elif peer_ids:+ actor_peer_id = getattr(client, "actor_peer_id", None)+ if actor_peer_id and not peer_ids:+ peer_ids = [actor_peer_id]+ if actor_peer_id or peer_ids:target_uris = self._dedupe_strings(["viking://resources/",diff --git a/bot/vikingbot/openviking_mount/ov_server.py b/bot/vikingbot/openviking_mount/ov_server.pyindex 77950cc5a..bc48a0da3 100644--- a/bot/vikingbot/openviking_mount/ov_server.py+++ b/bot/vikingbot/openviking_mount/ov_server.py@@ -253,6 +253,38 @@ class VikingClient:"reason": getattr(relation, "reason", ""),}+ def _matched_context_group_to_dicts(self, result: Any, group_name: str) -> List[Dict[str, Any]]:+ if isinstance(result, dict):+ group = result.get(group_name, [])+ else:+ group = getattr(result, group_name, [])++ if not isinstance(group, list):+ return []++ items: List[Dict[str, Any]] = []+ for item in group:+ if isinstance(item, dict):+ items.append(dict(item))+ else:+ items.append(self._matched_context_to_dict(item))+ return items++ def _matched_context_total(+ self,+ result: Any,+ memories: List[Dict[str, Any]],+ resources: List[Dict[str, Any]],+ skills: List[Dict[str, Any]],+ ) -> int:+ if isinstance(result, dict):+ total = result.get("total")+ else:+ total = getattr(result, "total", None)+ if isinstance(total, int):+ return total+ return len(memories) + len(resources) + len(skills)+def _is_root_key_mode(self) -> bool:return (self.auth_mode == "trusted"@@ -616,18 +648,15 @@ class VikingClient:if should_close:await client.close()- # 将 FindResult 对象转换为 JSON map+ # 将 FindResult 对象或已序列化的 JSON map 统一转换为 JSON map+ memories = self._matched_context_group_to_dicts(result, "memories")+ resources = self._matched_context_group_to_dicts(result, "resources")+ skills = self._matched_context_group_to_dicts(result, "skills")return {- "memories": [self._matched_context_to_dict(m) for m in result.memories]- if hasattr(result, "memories")- else [],- "resources": [self._matched_context_to_dict(r) for r in result.resources]- if hasattr(result, "resources")- else [],- "skills": [self._matched_context_to_dict(s) for s in result.skills]- if hasattr(result, "skills")- else [],- "total": getattr(result, "total", len(getattr(result, "resources", []))),+ "memories": memories,+ "resources": resources,+ "skills": skills,+ "total": self._matched_context_total(result, memories, resources, skills),"query": query,"target_uri": target_uri,}