From ea2c2054c68f2d80a1b0ff2995778e4e6b182f40 Mon Sep 17 00:00:00 2001 From: cybr-wisp Date: Mon, 12 Oct 2026 20:11:55 -0400 Subject: [PATCH] fix: recover from failed search results on follow-up queries (#265) --- src/sherpa_ai/agents/qa_agent.py | 68 ++++++++++ src/sherpa_ai/policies/react_policy.py | 16 ++- .../unit_tests/agents/test_search_recovery.py | 125 ++++++++++++++++++ .../policies/test_react_recovery.py | 55 ++++++++ .../unit_tests/policies/test_search_retry.py | 89 +++++++++++++ 5 files changed, 352 insertions(+), 1 deletion(-) create mode 100644 src/tests/unit_tests/agents/test_search_recovery.py create mode 100644 src/tests/unit_tests/policies/test_react_recovery.py create mode 100644 src/tests/unit_tests/policies/test_search_retry.py diff --git a/src/sherpa_ai/agents/qa_agent.py b/src/sherpa_ai/agents/qa_agent.py index 8d7cece1c..0e554410d 100644 --- a/src/sherpa_ai/agents/qa_agent.py +++ b/src/sherpa_ai/agents/qa_agent.py @@ -1,3 +1,4 @@ +import re from typing import List, Optional from sherpa_ai.actions import GoogleSearch, SynthesizeOutput @@ -113,6 +114,14 @@ def __init__( version="1.0", ) + action_planner += ( + "\nWhen comparing multiple named subjects, gather evidence for " + "each subject rather than assuming one search covers them all. " + "If an earlier response failed to find a subject, use a fresh " + "targeted search query on a follow-up request. Previous retrieval " + "failures are not proof that the subject cannot be found." + ) + self.description = self.description + "\n\n" + f"Your name is {self.name}." if self.policy is None: @@ -133,6 +142,65 @@ def __init__( self.citation_enabled = True break + def _missing_subject_for_retry(self) -> Optional[str]: + """Find a subject missing from the most recent answer.""" + if self.belief.current_task is None: + return None + + question = self.belief.current_task.content + + for event in reversed(self.belief.events): + if event.event_type != "result": + continue + + answer = event.content or "" + + pattern = ( + r"(?:could not|couldn't|cannot|can't|did not|didn't)" + r" find (?:any )?information (?:about|on) " + r"([A-Za-z][A-Za-z0-9_.+-]*)" + ) + + match = re.search(pattern, answer, re.IGNORECASE) + if match is None: + return None + + subject = match.group(1).rstrip(".,;:!?") + + # Match the complete subject, ignoring capitalization. + words = re.findall(r"[A-Za-z][A-Za-z0-9_.+-]*", question) + if subject.lower() in (word.lower() for word in words): + return subject + + return None + + return None + + async def async_run(self): + """Retry an explicitly missing subject before normal execution.""" + subject = self._missing_subject_for_retry() + + if subject is not None: + actions = await self.belief.async_get_actions() + + if not actions and self.belief.state_machine is None: + actions = self.actions or self.create_actions() + self.belief.set_actions(actions) + + search = next( + (action for action in actions if action.name == "Google Search"), + None, + ) + + if search is not None: + # At most one recovery search per execution. + await self.async_act( + search, + {"query": f"{subject} documentation overview"}, + ) + + return await super().async_run() + def create_actions(self) -> List[BaseAction]: """Create and return the list of actions available to this agent. diff --git a/src/sherpa_ai/policies/react_policy.py b/src/sherpa_ai/policies/react_policy.py index 0883ee052..50ac55e65 100644 --- a/src/sherpa_ai/policies/react_policy.py +++ b/src/sherpa_ai/policies/react_policy.py @@ -122,13 +122,27 @@ def select_action(self, belief: Belief) -> Optional[PolicyOutput]: self.llm.get_num_tokens ) + # A previous unsuccessful retrieval is not evidence that the information + # does not exist. Give the policy the current conversation and explicitly + # permit further retrieval when an earlier query missed an entity. + task_context = belief.get_context(self.llm.get_num_tokens) + recovery_instruction = ( + "Treat previous failed searches and 'not found' answers as " + "inconclusive, not as facts. If the current user request asks for " + "information missing from earlier results, select an available " + "retrieval action with a new, targeted query. For comparisons, " + "retrieve evidence for each missing subject separately; do not " + "repeat an unsupported previous conclusion." + ) + response_format = json.dumps(self.response_format, indent=4) variables = { "role_description": self.role_description, - "output_instruction": self.output_instruction, + "output_instruction": self.output_instruction + "\n\n" + recovery_instruction, "task_description": task_description, "possible_actions": possible_actions, + "task_context": task_context, "history_of_previous_actions": history_of_previous_actions, "response_format": response_format, } diff --git a/src/tests/unit_tests/agents/test_search_recovery.py b/src/tests/unit_tests/agents/test_search_recovery.py new file mode 100644 index 000000000..4d28472a1 --- /dev/null +++ b/src/tests/unit_tests/agents/test_search_recovery.py @@ -0,0 +1,125 @@ +"""Regression tests for Sherpa issue #265.""" + +import asyncio +from unittest.mock import AsyncMock, patch + +from pydantic import Field + +from sherpa_ai.actions.base import BaseAction +from sherpa_ai.agents.base import BaseAgent +from sherpa_ai.agents.qa_agent import QAAgent +from sherpa_ai.config.task_result import TaskResult +from sherpa_ai.events import build_event +from sherpa_ai.memory.belief import Belief + + +class FakeSearch(BaseAction): + """A search action that records queries without using Google.""" + + name: str = "Google Search" + usage: str = "Search the web" + args: dict = {"query": "string"} + queries: list[str] = Field(default_factory=list) + + def execute(self, query: str) -> str: + self.queries.append(query) + return f"Found information about {query}" + + +def make_agent(question, previous_answer): + belief = Belief() + belief.set_current_task(question) + + if previous_answer: + belief.update( + build_event( + "result", + "Sherpa", + content=previous_answer, + ) + ) + + search = FakeSearch(belief=belief) + agent = QAAgent(belief=belief, actions=[search]) + + return agent, search + + +def run_recovery(agent): + # Isolate the recovery preflight from the normal agent loop. + completed = TaskResult(content="done", status="success") + + with patch.object( + BaseAgent, + "async_run", + new_callable=AsyncMock, + return_value=completed, + ) as normal_run: + result = asyncio.run(agent.async_run()) + normal_run.assert_awaited_once() + + return result + + +def test_missing_subject_triggers_new_search(): + agent, search = make_agent( + "Compare with LangChain", + "I couldn't find any information about LangChain.", + ) + + result = run_recovery(agent) + + assert result.status == "success" + assert search.queries == ["LangChain documentation overview"] + + +def test_unrelated_question_does_not_retry(): + agent, search = make_agent( + "Explain Python decorators", + "I couldn't find any information about LangChain.", + ) + + run_recovery(agent) + + assert search.queries == [] + + +def test_successful_previous_answer_does_not_retry(): + agent, search = make_agent( + "Tell me more about LangChain", + "LangChain is a framework for LLM applications.", + ) + + run_recovery(agent) + + assert search.queries == [] + + +def test_recovery_is_limited_to_one_search(): + agent, search = make_agent( + "Compare with LangChain", + "I couldn't find any information about LangChain.", + ) + + run_recovery(agent) + + assert len(search.queries) == 1 + + +def test_latest_answer_takes_priority(): + agent, search = make_agent( + "Tell me more about LangChain", + "I couldn't find any information about LangChain.", + ) + + agent.belief.update( + build_event( + "result", + "Sherpa", + content="LangChain is a framework for LLM applications.", + ) + ) + + run_recovery(agent) + + assert search.queries == [] diff --git a/src/tests/unit_tests/policies/test_react_recovery.py b/src/tests/unit_tests/policies/test_react_recovery.py new file mode 100644 index 000000000..aa343c5be --- /dev/null +++ b/src/tests/unit_tests/policies/test_react_recovery.py @@ -0,0 +1,55 @@ +"""Regression coverage for retrieval recovery (issue #265).""" + +from langchain_core.language_models import FakeListLLM + +from sherpa_ai.actions.empty import EmptyAction +from sherpa_ai.events import build_event +from sherpa_ai.memory.belief import Belief +from sherpa_ai.policies.react_policy import ReactPolicy + + +def test_follow_up_search_keeps_current_context_and_recovery_instruction(): + llm = FakeListLLM( + responses=[ + '{"command": {"name": "Google Search", ' + '"args": {"query": "LangChain framework documentation"}}}' + ] + ) + policy = ReactPolicy( + role_description="Research assistant", + output_instruction="Choose an action", + llm=llm, + ) + belief = Belief() + belief.set_current_task("Compare with LangChain") + belief.update( + build_event( + "result", + "Sherpa", + content="I couldn't find any information about LangChain.", + ) + ) + belief.update_internal( + "action_finish", + "Google Search", + outputs="Earlier query only searched LlamaIndex", + ) + search = EmptyAction(name="Google Search", args={"query": "string"}) + belief.set_actions([search]) + + captured = {} + original = policy.prompt_template.format_prompt + + def capture(*args, **kwargs): + captured.update(kwargs.get("variables", {})) + return original(*args, **kwargs) + + policy.prompt_template.format_prompt = capture + selected = policy.select_action(belief) + + assert selected.action is search + assert selected.args == {"query": "LangChain framework documentation"} + assert "couldn't find any information" in captured["task_context"] + assert "Previous" in captured["output_instruction"] or "previous" in captured["output_instruction"] + assert "targeted query" in captured["output_instruction"] + assert "Compare with LangChain" == captured["task_description"] diff --git a/src/tests/unit_tests/policies/test_search_retry.py b/src/tests/unit_tests/policies/test_search_retry.py new file mode 100644 index 000000000..a0418c218 --- /dev/null +++ b/src/tests/unit_tests/policies/test_search_retry.py @@ -0,0 +1,89 @@ +"""Regression tests for issue #265: recovery after an incomplete search.""" + +from langchain_core.language_models import FakeListLLM +from pydantic import Field +from pydantic import Field + +from sherpa_ai.actions.base import BaseAction +from sherpa_ai.memory.belief import Belief +from sherpa_ai.events import build_event +from sherpa_ai.policies.react_policy import ReactPolicy + + +class FakeSearch(BaseAction): + """Record search queries without calling Google.""" + + name: str = "Google Search" + usage: str = "Search the web for information" + args: dict = {"query": "string"} + queries: list[str] = Field(default_factory=list) + queries: list[str] = Field(default_factory=list) + + def execute(self, query: str) -> str: + # Keep a record of every search the agent makes. + self.queries.append(query) + + if "langchain" in query.lower(): + return "LangChain is a framework for building LLM applications." + + if "llamaindex" in query.lower(): + return "LlamaIndex is a framework for connecting LLMs to data." + + return "No results found." + + +def test_agent_searches_again_after_missing_information(): + # Simulate the action choices made on two consecutive turns. + llm = FakeListLLM( + responses=[ + '{"command": {"name": "Google Search", ' + '"args": {"query": "LlamaIndex"}}}', + '{"command": {"name": "Google Search", ' + '"args": {"query": "LangChain framework documentation"}}}', + ] + ) + + policy = ReactPolicy( + role_description="Research assistant", + output_instruction="Choose the next action", + llm=llm, + ) + + search = FakeSearch() + + belief = Belief() + belief.set_actions([search]) + + # First turn: the agent searches only for LlamaIndex. + belief.set_current_task("Compare LlamaIndex and LangChain") + + first_action = policy.select_action(belief) + first_result = first_action.action.execute(**first_action.args) + + assert "LlamaIndex" in first_result + assert search.queries == ["LlamaIndex"] + + # Save the incomplete answer in conversation history. + belief.update( + build_event( + "result", + "Sherpa", + content=( + "LlamaIndex connects language models to data. " + "I couldn't find information about LangChain." + ), + ) + ) + + # Second turn: the user asks about the missing framework. + belief.set_current_task("Compare with LangChain") + + second_action = policy.select_action(belief) + second_result = second_action.action.execute(**second_action.args) + + # A new search must occur, not a repetition of the failed answer. + assert len(search.queries) == 2 + assert "langchain" in search.queries[1].lower() + assert "LangChain is a framework" in second_result + +