Skip to content

Building AI agents, atomically

fix(example/deep-research): address PR review findings

KennyVaneetveldefaf7592652f1
diff --git a/atomic-examples/deep-research/deep_research/agents/decider_agent.py b/atomic-examples/deep-research/deep_research/agents/decider_agent.py
index b45ad0c..8452376 100644
--- a/atomic-examples/deep-research/deep_research/agents/decider_agent.py
+++ b/atomic-examples/deep-research/deep_research/agents/decider_agent.py
@@ -24,7 +24,7 @@ from deep_research.config import ChatConfig
class DeciderInput(BaseIOSchema):
"""Input schema for the DeciderAgent."""
- user_message: str = Field(..., description="The user's latest question or follow-up.")
+ user_message: str = Field(..., min_length=1, description="The user's latest question or follow-up.")
class DeciderOutput(BaseIOSchema):
@@ -32,6 +32,7 @@ class DeciderOutput(BaseIOSchema):
reasoning: str = Field(
...,
+ min_length=1,
description="One short paragraph: what's already in the state, what's missing, and why that tips the decision.",
)
needs_research: bool = Field(
@@ -47,7 +48,7 @@ decider_agent = AtomicAgent[DeciderInput, DeciderOutput](
AgentConfig(
client=instructor.from_openai(openai.OpenAI(api_key=ChatConfig.api_key)),
model=ChatConfig.model,
- model_api_parameters={"reasoning_effort": ChatConfig.reasoning_effort, "temperature": 0.1},
+ model_api_parameters={"reasoning_effort": ChatConfig.reasoning_effort},
system_prompt_generator=SystemPromptGenerator(
background=[
"You are a routing agent. Given the user's latest message and the current ResearchState "
diff --git a/atomic-examples/deep-research/deep_research/agents/planner_agent.py b/atomic-examples/deep-research/deep_research/agents/planner_agent.py
index 01bb3b1..6dab2a9 100644
--- a/atomic-examples/deep-research/deep_research/agents/planner_agent.py
+++ b/atomic-examples/deep-research/deep_research/agents/planner_agent.py
@@ -1,13 +1,12 @@
"""
PlannerAgent — decomposes a research question into durable sub-topics.
-Sub-topics are the *breadth* axis of the pipeline. They are decided once
-by the planner and stay fixed; only the queries *within* a sub-topic
-iterate as we learn more. Keeping the plan small and durable makes the
-final report easy to organise section-by-section.
-
-The planner runs before any state exists, so it takes only the raw
-question and does not register any context providers.
+Sub-topics are the *breadth* axis of the pipeline. On the first turn
+the planner produces the whole plan. In chat mode, follow-up turns that
+need new research re-invoke the planner with the same state visible via
+``ResearchStateProvider``; the planner is expected to propose new
+sub-topics that extend coverage rather than duplicate what's already
+been researched.
"""
import instructor
@@ -75,6 +74,8 @@ planner_agent = AtomicAgent[PlannerInput, PlannerOutput](
"Sub-topic names must be short (2–6 words).",
"Initial queries must read like search-engine input, not natural-language sentences.",
"Do not duplicate sub-topics or queries across the plan.",
+ "If the research state already contains learnings on some angle, "
+ "propose sub-topics that fill different gaps instead of revisiting covered ground.",
],
),
)
diff --git a/atomic-examples/deep-research/deep_research/agents/qa_agent.py b/atomic-examples/deep-research/deep_research/agents/qa_agent.py
index 171535a..503f40b 100644
--- a/atomic-examples/deep-research/deep_research/agents/qa_agent.py
+++ b/atomic-examples/deep-research/deep_research/agents/qa_agent.py
@@ -26,7 +26,7 @@ from deep_research.config import ChatConfig
class QAInput(BaseIOSchema):
"""Input schema for the QAAgent."""
- question: str = Field(..., description="The user's question or follow-up.")
+ question: str = Field(..., min_length=1, description="The user's question or follow-up.")
class QAOutput(BaseIOSchema):
@@ -34,6 +34,7 @@ class QAOutput(BaseIOSchema):
answer: str = Field(
...,
+ min_length=1,
description=(
"Markdown-formatted answer. Every factual sentence must end with a [Sn] citation marker "
"referencing a source from the research state."
@@ -41,6 +42,8 @@ class QAOutput(BaseIOSchema):
)
follow_up_questions: list[str] = Field(
...,
+ min_length=2,
+ max_length=3,
description="2–3 natural follow-up questions the user might want to ask next.",
)
@@ -62,10 +65,12 @@ qa_agent = AtomicAgent[QAInput, QAOutput](
"Suggest 2–3 follow-up questions that naturally extend the conversation.",
],
output_instructions=[
+ "Every factual sentence must end with one or more [Sn] citation markers.",
+ "Drop any sentence you cannot cite from the state — do not invent or infer claims.",
"Only cite source IDs that actually exist in the research state.",
- "If you cannot answer from the state, say so briefly rather than inventing claims.",
+ "If the state doesn't support an answer at all, say so briefly rather than producing uncited prose.",
"Keep the answer tight — a few short paragraphs, not a full report.",
- "Follow-up questions should be self-contained and phrased as the user would ask them.",
+ "Return 2–3 self-contained follow-up questions, phrased as the user would ask them.",
],
),
)
diff --git a/atomic-examples/deep-research/deep_research/main.py b/atomic-examples/deep-research/deep_research/main.py
index 6bca600..856b11d 100644
--- a/atomic-examples/deep-research/deep_research/main.py
+++ b/atomic-examples/deep-research/deep_research/main.py
@@ -41,6 +41,14 @@ from deep_research.tools.webpage_scraper import (
WebpageScraperToolInputSchema,
)
+# Rich renders unicode liberally (→, bullets, box-drawing). On Windows the
+# default stdout/stderr encoding is cp1252, so piping or redirecting output
+# crashes on any non-cp1252 character. Reconfigure to utf-8 with a safe
+# fallback so the example runs anywhere.
+for _stream in (sys.stdout, sys.stderr):
+ if hasattr(_stream, "reconfigure"):
+ _stream.reconfigure(encoding="utf-8", errors="replace")
+
console = Console()
# How many new sub-topics a follow-up research pass may add. Kept small so
@@ -255,11 +263,19 @@ def answer_from_state(question: str, state: ResearchState) -> None:
def research_follow_up(question: str, state: ResearchState, search: SearXNGSearchTool, scraper: WebpageScraperTool) -> None:
- """Follow-up that needs new material: plan a few new sub-topics scoped to the follow-up, research them, then QA."""
+ """Follow-up that needs new material: plan up to ``FOLLOW_UP_SUB_TOPICS`` new sub-topics, research them, then QA.
+
+ The planner sees the existing ``ResearchState`` via its context provider
+ and is expected to propose only angles not yet covered. If it returns
+ zero new sub-topics we print a visible warning so the user knows the
+ QA answer rests on existing material, not new research.
+ """
state.question = question # the planner / providers read the live question
console.rule("[bold cyan]Extending research")
new_sub_topics = plan_research(state, num_sub_topics=FOLLOW_UP_SUB_TOPICS)
+ if not new_sub_topics:
+ console.print("[yellow]Planner returned no new sub-topics — answering from existing state.[/yellow]")
for sub_topic in new_sub_topics:
research_sub_topic(sub_topic, state, search, scraper)
@@ -268,6 +284,10 @@ def research_follow_up(question: str, state: ResearchState, search: SearXNGSearc
def handle_follow_up(user_message: str, state: ResearchState, search: SearXNGSearchTool, scraper: WebpageScraperTool) -> None:
"""Route a single follow-up turn through decider → either research+QA or QA alone."""
+ if state.agent_calls >= ResearchBudget.hard_call_cap:
+ console.print("[red]Hard call cap reached — cannot process follow-up.[/red]")
+ return
+
decision = decider_agent.run(DeciderInput(user_message=user_message))
state.agent_calls += 1
@@ -299,23 +319,54 @@ def chat_loop() -> None:
first_turn = True
while True:
prompt = "[bold blue]Your question:[/bold blue] " if first_turn else "[bold blue]Follow-up:[/bold blue] "
- user_message = console.input("\n" + prompt).strip()
+ try:
+ user_message = console.input("\n" + prompt).strip()
+ except (KeyboardInterrupt, EOFError):
+ # Clean exit on Ctrl+C / Ctrl+D instead of a Rich traceback.
+ console.print("\n[bold]Goodbye.[/bold]")
+ return
+
if not user_message:
continue
if user_message.lower() in ("/exit", "/quit"):
console.print("\n[bold]Goodbye.[/bold]")
return
- if first_turn:
- run_initial_pipeline(user_message, state, search, scraper)
- first_turn = False
- else:
- handle_follow_up(user_message, state, search, scraper)
+ # Keep the REPL alive on turn-level failures (malformed structured
+ # output, transient tool errors, etc.) instead of dropping the user's
+ # accumulated ResearchState.
+ try:
+ if first_turn:
+ run_initial_pipeline(user_message, state, search, scraper)
+ first_turn = False
+ else:
+ handle_follow_up(user_message, state, search, scraper)
+ except KeyboardInterrupt:
+ _safe_print("Interrupted — returning to prompt.", style="yellow")
+ except Exception as exc:
+ _safe_print(f"Turn failed: {exc.__class__.__name__}: {exc}", style="red")
+ _safe_print("Accumulated research state is preserved; try a different question.", style="dim")
# --- Internals ---------------------------------------------------------------
+def _safe_print(message: str, style: str = "") -> None:
+ """Print an error/status message without risking a recursive Rich failure.
+
+ The chat loop's error handler must not itself raise — if Rich's own render
+ path is what failed (e.g. a Windows encoding error), falling back to a
+ plain builtin ``print`` keeps the REPL alive.
+ """
+ try:
+ console.print(f"\n[{style}]{message}[/{style}]" if style else f"\n{message}")
+ except Exception:
+ try:
+ print(f"\n{message}", flush=True)
+ except Exception:
+ pass
+
+
def _build_tools() -> tuple[SearXNGSearchTool, WebpageScraperTool]:
search = SearXNGSearchTool(
SearXNGSearchToolConfig(