DriptoBhattacharyya Claude Opus 4.8 commited on
Commit
0a9b8d0
·
1 Parent(s): 323f3b4

Harden agent: survive Groq tool_use_failed, enforce per-question timeout

Browse files

research node retries malformed tool calls then bails to evidence; agent wrapper bounds each question with QUESTION_TIMEOUT via a per-call executor; judge retries cut to 1 to reduce Groq rate-limit stalls; add progress logging.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

Files changed (3) hide show
  1. gaia_agent/agent.py +31 -9
  2. gaia_agent/config.py +1 -1
  3. gaia_agent/nodes.py +25 -3
gaia_agent/agent.py CHANGED
@@ -2,6 +2,10 @@
2
 
3
  from __future__ import annotations
4
 
 
 
 
 
5
  from gaia_agent.config import get_settings
6
  from gaia_agent.graph import graph
7
 
@@ -18,15 +22,33 @@ class GaiaAgent:
18
  self._settings = get_settings()
19
  print("GaiaAgent initialised (LangGraph + Groq).")
20
 
 
 
 
 
 
 
 
21
  def __call__(self, question: str, task_id: str = "") -> str:
22
- """Run the graph on one question and return the bare answer string."""
 
 
 
 
 
 
 
 
23
  try:
24
- result = self._graph.invoke(
25
- {"question": question, "task_id": task_id},
26
- config={"recursion_limit": self._settings.recursion_limit},
27
- )
28
- answer = (result.get("final_answer") or "").strip()
29
- return answer or "Unable to determine an answer."
30
  except Exception as exc: # noqa: BLE001
31
- print(f"GaiaAgent error on task {task_id}: {exc}")
32
- return "Unable to determine an answer."
 
 
 
 
 
2
 
3
  from __future__ import annotations
4
 
5
+ import time
6
+ from concurrent.futures import ThreadPoolExecutor
7
+ from concurrent.futures import TimeoutError as FutureTimeout
8
+
9
  from gaia_agent.config import get_settings
10
  from gaia_agent.graph import graph
11
 
 
22
  self._settings = get_settings()
23
  print("GaiaAgent initialised (LangGraph + Groq).")
24
 
25
+ def _run(self, question: str, task_id: str) -> str:
26
+ result = self._graph.invoke(
27
+ {"question": question, "task_id": task_id},
28
+ config={"recursion_limit": self._settings.recursion_limit},
29
+ )
30
+ return (result.get("final_answer") or "").strip()
31
+
32
  def __call__(self, question: str, task_id: str = "") -> str:
33
+ """Run the graph on one question, bounded by QUESTION_TIMEOUT seconds.
34
+
35
+ A fresh single-worker executor per call means a timed-out question's thread
36
+ is abandoned (daemon) rather than blocking the next question.
37
+ """
38
+ start = time.time()
39
+ print(f"[GaiaAgent] task {task_id}: {question[:70]}...")
40
+ pool = ThreadPoolExecutor(max_workers=1)
41
+ future = pool.submit(self._run, question, task_id)
42
  try:
43
+ answer = future.result(timeout=self._settings.question_timeout)
44
+ except FutureTimeout:
45
+ print(f"[GaiaAgent] task {task_id} timed out after "
46
+ f"{self._settings.question_timeout}s; returning best-effort.")
47
+ answer = ""
 
48
  except Exception as exc: # noqa: BLE001
49
+ print(f"[GaiaAgent] task {task_id} error: {exc}")
50
+ answer = ""
51
+ finally:
52
+ pool.shutdown(wait=False)
53
+ print(f"[GaiaAgent] task {task_id} done in {time.time() - start:.0f}s -> {answer!r}")
54
+ return answer or "Unable to determine an answer."
gaia_agent/config.py CHANGED
@@ -29,7 +29,7 @@ class Settings(BaseSettings):
29
 
30
  # --- API + control knobs ---
31
  gaia_api_url: str = "https://agents-course-unit4-scoring.hf.space"
32
- max_judge_retries: int = 2
33
  recursion_limit: int = 40
34
  question_timeout: int = 180
35
 
 
29
 
30
  # --- API + control knobs ---
31
  gaia_api_url: str = "https://agents-course-unit4-scoring.hf.space"
32
+ max_judge_retries: int = 1
33
  recursion_limit: int = 40
34
  question_timeout: int = 180
35
 
gaia_agent/nodes.py CHANGED
@@ -6,7 +6,7 @@ Flow: planner -> [ingest_file] -> research <-> tools -> evidence -> solver
6
 
7
  from __future__ import annotations
8
 
9
- from langchain_core.messages import HumanMessage, SystemMessage
10
 
11
  from gaia_agent.config import get_settings
12
  from gaia_agent.llm import get_text_llm
@@ -99,6 +99,28 @@ def ingest_file(state: GraphState) -> dict:
99
  # --------------------------------------------------------------------------- #
100
 
101
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
102
  def research(state: GraphState) -> dict:
103
  """Run one step of the research tool-calling loop."""
104
  llm = get_text_llm().bind_tools(RESEARCH_TOOLS)
@@ -115,9 +137,9 @@ def research(state: GraphState) -> dict:
115
  "needed to answer precisely. Call tools as needed; stop when confident."
116
  ),
117
  ]
118
- ai = llm.invoke(seed)
119
  return {"messages": seed + [ai]}
120
- ai = llm.invoke(state["messages"])
121
  return {"messages": [ai]}
122
 
123
 
 
6
 
7
  from __future__ import annotations
8
 
9
+ from langchain_core.messages import AIMessage, HumanMessage, SystemMessage
10
 
11
  from gaia_agent.config import get_settings
12
  from gaia_agent.llm import get_text_llm
 
99
  # --------------------------------------------------------------------------- #
100
 
101
 
102
+ def _invoke_with_tools(llm, msgs: list):
103
+ """Invoke a tool-bound LLM, tolerating Groq's occasional malformed tool calls.
104
+
105
+ Groq's llama models sometimes emit ``<function=name{...}>`` text instead of a
106
+ proper tool call, which the API rejects with a 400 ``tool_use_failed``. We retry
107
+ once with a corrective nudge, then fall back to a tool-less AIMessage so the graph
108
+ proceeds to the evidence step instead of failing the whole question.
109
+ """
110
+ try:
111
+ return llm.invoke(msgs)
112
+ except Exception: # noqa: BLE001
113
+ nudge = SystemMessage(
114
+ "Call tools ONLY via the native function-calling interface. Never write "
115
+ "<function=...> tags or tool calls inside message content. If you do not "
116
+ "need a tool, answer in plain text."
117
+ )
118
+ try:
119
+ return llm.invoke(msgs + [nudge])
120
+ except Exception: # noqa: BLE001
121
+ return AIMessage(content="(tool calling unavailable; proceeding with context)")
122
+
123
+
124
  def research(state: GraphState) -> dict:
125
  """Run one step of the research tool-calling loop."""
126
  llm = get_text_llm().bind_tools(RESEARCH_TOOLS)
 
137
  "needed to answer precisely. Call tools as needed; stop when confident."
138
  ),
139
  ]
140
+ ai = _invoke_with_tools(llm, seed)
141
  return {"messages": seed + [ai]}
142
+ ai = _invoke_with_tools(llm, state["messages"])
143
  return {"messages": [ai]}
144
 
145