ptoloudis commited on
Commit
3f71280
·
verified ·
1 Parent(s): ee0a78f

Delete agent.py

Browse files
Files changed (1) hide show
  1. agent.py +0 -371
agent.py DELETED
@@ -1,371 +0,0 @@
1
- """LangGraph agent that answers GAIA benchmark questions (Hugging Face Agents Course, Unit 4).
2
-
3
- The agent is a LangGraph ReAct-style graph: an LLM served through the Hugging Face
4
- Inference API, bound to a toolset (web/Wikipedia/arXiv search, arithmetic, GAIA
5
- task-file download, and CSV/Excel analysis). Structure and prompt are adapted from
6
- https://huggingface.co/spaces/fisherman611/gaia-agent, trimmed to tools that need no
7
- extra paid API keys and no arbitrary code execution. See
8
- https://huggingface.co/learn/agents-course/unit4/hands-on for the assignment.
9
- """
10
-
11
- import os
12
- import re
13
- import tempfile
14
- import uuid
15
- from pathlib import Path
16
- from typing import Optional
17
- from urllib.parse import urlparse
18
-
19
- import pandas as pd
20
- import requests
21
- from langchain_community.document_loaders import ArxivLoader, WikipediaLoader
22
- from langchain_community.tools import DuckDuckGoSearchRun
23
- from langchain_core.messages import HumanMessage, SystemMessage
24
- from langchain_core.tools import tool
25
- from langchain_huggingface import ChatHuggingFace, HuggingFaceEndpoint
26
- from langgraph.graph import START, MessagesState, StateGraph
27
- from langgraph.prebuilt import ToolNode, tools_condition
28
-
29
- DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
30
-
31
- # "huggingface" (default, needs only HF_TOKEN) or "anthropic" (needs ANTHROPIC_API_KEY,
32
- # paid - https://console.anthropic.com). Anthropic's native tool calling is more reliable
33
- # than the HF router's per-provider variance, at the cost of no free tier.
34
- LLM_PROVIDER = os.getenv("LLM_PROVIDER", "huggingface")
35
-
36
- # Any HF Inference API model that supports tool calling works here. Override via the
37
- # HF_AGENT_MODEL env var without touching code. Qwen3-14B gives noticeably better reasoning
38
- # than the 8B model it replaced (meta-llama/Llama-3.1-8B-Instruct) for a modest bite out of
39
- # the free tier's tiny $0.10/month Inference Provider credit allowance - on the "nscale"
40
- # provider below, a full ~20-question GAIA run costs only a few cents. Drop back to
41
- # Llama-3.1-8B-Instruct (paired with the "deepinfra" provider) if you need more runs per
42
- # month out of the free allowance, or go bigger (e.g. meta-llama/Llama-3.3-70B-Instruct on
43
- # "together") once you have paid credits.
44
- HF_MODEL_REPO_ID = os.getenv("HF_AGENT_MODEL", "Qwen/Qwen3-14B")
45
-
46
- # Left unset ("auto"), the HF router picks whichever provider is cheapest/fastest for the
47
- # model, and some of those don't support the `tools` param at all (HTTP 422
48
- # UNSUPPORTED_OPENAI_PARAMS). Pin one that reliably supports tool calling; override via
49
- # HF_AGENT_PROVIDER if it doesn't happen to host HF_AGENT_MODEL.
50
- HF_MODEL_PROVIDER = os.getenv("HF_AGENT_PROVIDER", "nscale")
51
-
52
- # Cheapest current Claude model - a good fit for an agent that makes many tool-calling
53
- # round trips per question. Override via ANTHROPIC_MODEL (e.g. "claude-sonnet-5" for
54
- # stronger reasoning on harder questions, at higher cost).
55
- ANTHROPIC_MODEL = os.getenv("ANTHROPIC_MODEL", "claude-haiku-4-5")
56
-
57
- with open(Path(__file__).parent / "system_prompt.txt", "r", encoding="utf-8") as f:
58
- SYSTEM_PROMPT = f.read()
59
-
60
- _FINAL_ANSWER_RE = re.compile(r"final answer\s*:\s*", re.IGNORECASE)
61
-
62
-
63
- ### =============== SEARCH TOOLS =============== ###
64
-
65
-
66
- @tool
67
- def web_search(query: str) -> str:
68
- """Search the web (DuckDuckGo) for a query and return a few results.
69
-
70
- Args:
71
- query: The search query.
72
- """
73
- return DuckDuckGoSearchRun().invoke(query)
74
-
75
-
76
- @tool
77
- def wiki_search(query: str) -> str:
78
- """Search Wikipedia for a query and return up to 2 results.
79
-
80
- Args:
81
- query: The search query.
82
- """
83
- docs = WikipediaLoader(query=query, load_max_docs=2).load()
84
- return "\n\n---\n\n".join(
85
- f'<Document source="{d.metadata.get("source", "")}"/>\n{d.page_content}\n</Document>'
86
- for d in docs
87
- )
88
-
89
-
90
- @tool
91
- def arxiv_search(query: str) -> str:
92
- """Search arXiv for a query and return up to 2 results (abstracts truncated).
93
-
94
- Args:
95
- query: The search query.
96
- """
97
- docs = ArxivLoader(query=query, load_max_docs=2).load()
98
- return "\n\n---\n\n".join(
99
- f'<Document source="{d.metadata.get("source", "")}"/>\n{d.page_content[:1000]}\n</Document>'
100
- for d in docs
101
- )
102
-
103
-
104
- ### =============== MATH TOOLS =============== ###
105
-
106
-
107
- @tool
108
- def add(a: float, b: float) -> float:
109
- """Add two numbers.
110
-
111
- Args:
112
- a: the first number
113
- b: the second number
114
- """
115
- return a + b
116
-
117
-
118
- @tool
119
- def subtract(a: float, b: float) -> float:
120
- """Subtract two numbers.
121
-
122
- Args:
123
- a: the first number
124
- b: the second number
125
- """
126
- return a - b
127
-
128
-
129
- @tool
130
- def multiply(a: float, b: float) -> float:
131
- """Multiply two numbers.
132
-
133
- Args:
134
- a: the first number
135
- b: the second number
136
- """
137
- return a * b
138
-
139
-
140
- @tool
141
- def divide(a: float, b: float) -> float:
142
- """Divide two numbers.
143
-
144
- Args:
145
- a: the numerator
146
- b: the denominator
147
- """
148
- if b == 0:
149
- raise ValueError("Cannot divide by zero.")
150
- return a / b
151
-
152
-
153
- @tool
154
- def modulus(a: int, b: int) -> int:
155
- """Get the remainder of a divided by b.
156
-
157
- Args:
158
- a: the first number
159
- b: the second number
160
- """
161
- return a % b
162
-
163
-
164
- @tool
165
- def power(a: float, b: float) -> float:
166
- """Raise a to the power of b.
167
-
168
- Args:
169
- a: the base
170
- b: the exponent
171
- """
172
- return a**b
173
-
174
-
175
- @tool
176
- def square_root(a: float) -> float:
177
- """Get the square root of a non-negative number.
178
-
179
- Args:
180
- a: the number to get the square root of
181
- """
182
- if a < 0:
183
- raise ValueError("Cannot take the square root of a negative number.")
184
- return a**0.5
185
-
186
-
187
- ### =============== FILE TOOLS =============== ###
188
-
189
-
190
- @tool
191
- def download_task_file(task_id: str) -> str:
192
- """Download the file attached to a GAIA task (if any) and return its text content.
193
-
194
- Only useful when the question references an attached file. Pass the task's task_id.
195
- Returns decoded text (truncated to 4000 characters) for text-like files, or a short
196
- description (content type and size) for files that can't be decoded as text.
197
- """
198
- try:
199
- response = requests.get(f"{DEFAULT_API_URL}/files/{task_id}", timeout=30)
200
- response.raise_for_status()
201
- except requests.exceptions.RequestException as e:
202
- return f"Error downloading file for task {task_id}: {e}"
203
-
204
- try:
205
- return response.content.decode("utf-8")[:4000]
206
- except UnicodeDecodeError:
207
- content_type = response.headers.get("content-type", "unknown")
208
- return (
209
- f"File for task {task_id} is binary (content-type: {content_type}, "
210
- f"{len(response.content)} bytes) and cannot be read as text."
211
- )
212
-
213
-
214
- @tool
215
- def download_file_from_url(url: str, filename: Optional[str] = None) -> str:
216
- """Download a file from a URL to a temporary path, for later analysis.
217
-
218
- Args:
219
- url: the URL of the file to download.
220
- filename: optional filename to save as; a random one is used if omitted.
221
- """
222
- try:
223
- if not filename:
224
- filename = os.path.basename(urlparse(url).path) or f"downloaded_{uuid.uuid4().hex[:8]}"
225
- filepath = os.path.join(tempfile.gettempdir(), filename)
226
- response = requests.get(url, stream=True, timeout=30)
227
- response.raise_for_status()
228
- with open(filepath, "wb") as f:
229
- for chunk in response.iter_content(chunk_size=8192):
230
- f.write(chunk)
231
- return f"File downloaded to {filepath}."
232
- except Exception as e:
233
- return f"Error downloading file: {e}"
234
-
235
-
236
- @tool
237
- def analyze_csv_file(file_path: str) -> str:
238
- """Load a CSV file and return its shape, columns, and summary statistics.
239
-
240
- Args:
241
- file_path: path to the CSV file (e.g. from download_file_from_url).
242
- """
243
- try:
244
- df = pd.read_csv(file_path)
245
- return (
246
- f"{len(df)} rows, {len(df.columns)} columns.\n"
247
- f"Columns: {', '.join(df.columns)}\n\n"
248
- f"Summary statistics:\n{df.describe(include='all')}"
249
- )
250
- except Exception as e:
251
- return f"Error analyzing CSV file: {e}"
252
-
253
-
254
- @tool
255
- def analyze_excel_file(file_path: str) -> str:
256
- """Load an Excel file and return its shape, columns, and summary statistics.
257
-
258
- Args:
259
- file_path: path to the .xlsx/.xls file (e.g. from download_file_from_url).
260
- """
261
- try:
262
- df = pd.read_excel(file_path)
263
- return (
264
- f"{len(df)} rows, {len(df.columns)} columns.\n"
265
- f"Columns: {', '.join(df.columns)}\n\n"
266
- f"Summary statistics:\n{df.describe(include='all')}"
267
- )
268
- except Exception as e:
269
- return f"Error analyzing Excel file: {e}"
270
-
271
-
272
- def _build_tools():
273
- return [
274
- web_search,
275
- wiki_search,
276
- arxiv_search,
277
- add,
278
- subtract,
279
- multiply,
280
- divide,
281
- modulus,
282
- power,
283
- square_root,
284
- download_task_file,
285
- download_file_from_url,
286
- analyze_csv_file,
287
- analyze_excel_file,
288
- ]
289
-
290
-
291
- def _build_llm():
292
- if LLM_PROVIDER == "anthropic":
293
- from langchain_anthropic import ChatAnthropic
294
-
295
- return ChatAnthropic(
296
- model=ANTHROPIC_MODEL,
297
- api_key=os.getenv("ANTHROPIC_API_KEY"),
298
- temperature=0,
299
- max_tokens=1024,
300
- )
301
- if LLM_PROVIDER == "huggingface":
302
- endpoint = HuggingFaceEndpoint(
303
- repo_id=HF_MODEL_REPO_ID,
304
- provider=HF_MODEL_PROVIDER,
305
- huggingfacehub_api_token=os.getenv("HF_TOKEN"),
306
- temperature=0,
307
- max_new_tokens=1024,
308
- )
309
- return ChatHuggingFace(llm=endpoint)
310
- raise ValueError(f"Unknown LLM_PROVIDER: {LLM_PROVIDER!r}. Use 'huggingface' or 'anthropic'.")
311
-
312
-
313
- def build_graph():
314
- """Build the compiled LangGraph agent graph."""
315
- tools = _build_tools()
316
- llm_with_tools = _build_llm().bind_tools(tools)
317
-
318
- def assistant(state: MessagesState):
319
- return {"messages": [llm_with_tools.invoke(state["messages"])]}
320
-
321
- builder = StateGraph(MessagesState)
322
- builder.add_node("assistant", assistant)
323
- builder.add_node("tools", ToolNode(tools))
324
- builder.add_edge(START, "assistant")
325
- builder.add_conditional_edges("assistant", tools_condition)
326
- builder.add_edge("tools", "assistant")
327
-
328
- return builder.compile()
329
-
330
-
331
- def _extract_final_answer(text: str) -> str:
332
- match = _FINAL_ANSWER_RE.search(text)
333
- answer = text[match.end():] if match else text
334
- answer = answer.strip()
335
- if len(answer) >= 2 and answer[0] == answer[-1] and answer[0] in "\"'":
336
- answer = answer[1:-1].strip()
337
- return answer
338
-
339
-
340
- class GaiaAgent:
341
- """A LangGraph ReAct agent (HF Inference API LLM + tools) for GAIA questions."""
342
-
343
- def __init__(self):
344
- self._graph = build_graph()
345
- print("GaiaAgent initialized.")
346
-
347
- def __call__(self, question: str, task_id: Optional[str] = None) -> str:
348
- print(f"Agent received question (first 80 chars): {question[:80]}...")
349
-
350
- user_content = question
351
- if task_id:
352
- user_content += (
353
- f"\n\n(task_id: {task_id} - use download_task_file if a file is attached)"
354
- )
355
-
356
- try:
357
- result = self._graph.invoke(
358
- {
359
- "messages": [
360
- SystemMessage(content=SYSTEM_PROMPT),
361
- HumanMessage(content=user_content),
362
- ]
363
- }
364
- )
365
- answer = _extract_final_answer(result["messages"][-1].content)
366
- except Exception as e:
367
- print(f"Agent error: {e}")
368
- answer = f"AGENT ERROR: {e}"
369
-
370
- print(f"Agent returning answer (first 80 chars): {answer[:80]}...")
371
- return answer