Update agent.py
Browse files
agent.py
CHANGED
@@ -1,6 +1,12 @@
|
|
1 |
import os
|
2 |
import requests
|
|
|
3 |
from openai import OpenAI
|
|
|
|
|
|
|
|
|
|
|
4 |
|
5 |
class GaiaAgent:
|
6 |
def __init__(self):
|
@@ -9,42 +15,52 @@ class GaiaAgent:
|
|
9 |
"You are a top-tier research assistant for the GAIA benchmark. "
|
10 |
"You analyze documents, reason step by step, and always provide a single, concise, and correct answer. "
|
11 |
"If a file is provided, extract all relevant information. Use only information from the question and file. "
|
12 |
-
"
|
13 |
)
|
14 |
self.api_url = "https://agents-course-unit4-scoring.hf.space"
|
15 |
|
16 |
-
def
|
17 |
try:
|
18 |
url = f"{self.api_url}/files/{task_id}"
|
19 |
-
|
20 |
-
|
21 |
-
|
22 |
-
|
23 |
-
if any(t in content_type for t in ["text", "csv", "json"]):
|
24 |
-
return response.text[:6000] # Allow more context for better answers
|
25 |
-
elif "application/pdf" in content_type:
|
26 |
-
return "[PDF file detected. Use a PDF parser to extract text.]"
|
27 |
-
else:
|
28 |
-
return f"[Unsupported file type: {content_type}]"
|
29 |
except Exception as e:
|
30 |
-
return
|
31 |
|
32 |
-
def
|
33 |
-
|
34 |
-
|
35 |
-
|
36 |
-
|
37 |
-
|
38 |
|
39 |
-
|
40 |
-
|
41 |
-
|
42 |
-
|
43 |
-
|
44 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
45 |
|
|
|
46 |
response = self.client.chat.completions.create(
|
47 |
-
model="gpt-4o",
|
48 |
messages=[
|
49 |
{"role": "system", "content": self.instructions},
|
50 |
{"role": "user", "content": prompt}
|
@@ -52,5 +68,56 @@ class GaiaAgent:
|
|
52 |
temperature=0.0,
|
53 |
max_tokens=1024,
|
54 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
55 |
|
56 |
-
|
|
|
|
1 |
import os
|
2 |
import requests
|
3 |
+
import mimetypes
|
4 |
from openai import OpenAI
|
5 |
+
from duckduckgo_search import DDGS
|
6 |
+
from PIL import Image
|
7 |
+
import pytesseract
|
8 |
+
import io
|
9 |
+
import openpyxl
|
10 |
|
11 |
class GaiaAgent:
|
12 |
def __init__(self):
|
|
|
15 |
"You are a top-tier research assistant for the GAIA benchmark. "
|
16 |
"You analyze documents, reason step by step, and always provide a single, concise, and correct answer. "
|
17 |
"If a file is provided, extract all relevant information. Use only information from the question and file. "
|
18 |
+
"Always output only 'Final Answer: <answer>' as the last line, no explanation after."
|
19 |
)
|
20 |
self.api_url = "https://agents-course-unit4-scoring.hf.space"
|
21 |
|
22 |
+
def fetch_file(self, task_id: str):
|
23 |
try:
|
24 |
url = f"{self.api_url}/files/{task_id}"
|
25 |
+
resp = requests.get(url, timeout=15)
|
26 |
+
resp.raise_for_status()
|
27 |
+
content_type = resp.headers.get("Content-Type", "")
|
28 |
+
return resp.content, content_type
|
|
|
|
|
|
|
|
|
|
|
|
|
29 |
except Exception as e:
|
30 |
+
return None, None
|
31 |
|
32 |
+
def ocr_image(self, img_bytes):
|
33 |
+
try:
|
34 |
+
img = Image.open(io.BytesIO(img_bytes))
|
35 |
+
return pytesseract.image_to_string(img)
|
36 |
+
except Exception as e:
|
37 |
+
return "[ERROR: Unable to OCR image]"
|
38 |
|
39 |
+
def read_excel(self, file_bytes):
|
40 |
+
try:
|
41 |
+
wb = openpyxl.load_workbook(io.BytesIO(file_bytes), data_only=True)
|
42 |
+
sheet = wb.active
|
43 |
+
rows = list(sheet.iter_rows(values_only=True))
|
44 |
+
text = "\n".join(["\t".join(str(cell) if cell is not None else "" for cell in row) for row in rows])
|
45 |
+
return text
|
46 |
+
except Exception as e:
|
47 |
+
return "[ERROR: Unable to read Excel file]"
|
48 |
+
|
49 |
+
def web_search(self, query, max_results=3):
|
50 |
+
try:
|
51 |
+
ddgs = DDGS()
|
52 |
+
results = ddgs.text(query)
|
53 |
+
summaries = []
|
54 |
+
for i, r in enumerate(results):
|
55 |
+
if i >= max_results: break
|
56 |
+
summaries.append(f"{r['title']}: {r['body']}")
|
57 |
+
return "\n".join(summaries)
|
58 |
+
except Exception as e:
|
59 |
+
return f"[ERROR: Web search failed: {e}]"
|
60 |
|
61 |
+
def call_llm(self, prompt):
|
62 |
response = self.client.chat.completions.create(
|
63 |
+
model="gpt-4o",
|
64 |
messages=[
|
65 |
{"role": "system", "content": self.instructions},
|
66 |
{"role": "user", "content": prompt}
|
|
|
68 |
temperature=0.0,
|
69 |
max_tokens=1024,
|
70 |
)
|
71 |
+
return response.choices[0].message.content.strip()
|
72 |
+
|
73 |
+
def parse_final_answer(self, text):
|
74 |
+
for line in reversed(text.splitlines()):
|
75 |
+
if "Final Answer:" in line:
|
76 |
+
return line.replace("Final Answer:", "").strip()
|
77 |
+
# fallback
|
78 |
+
return text.strip()
|
79 |
+
|
80 |
+
def __call__(self, question: str, task_id: str = None) -> str:
|
81 |
+
file_context = ""
|
82 |
+
file_text = ""
|
83 |
+
file_type = None
|
84 |
+
|
85 |
+
# Step 1: Download and process file if provided
|
86 |
+
if task_id:
|
87 |
+
file_bytes, content_type = self.fetch_file(task_id)
|
88 |
+
if not file_bytes or not content_type:
|
89 |
+
file_context = "[ERROR: Could not download file]"
|
90 |
+
elif "image" in content_type:
|
91 |
+
file_text = self.ocr_image(file_bytes)
|
92 |
+
file_context = f"Extracted text from image:\n{file_text}\n"
|
93 |
+
elif "spreadsheet" in content_type or "excel" in content_type or task_id.endswith(".xlsx"):
|
94 |
+
file_text = self.read_excel(file_bytes)
|
95 |
+
file_context = f"Extracted text from Excel:\n{file_text}\n"
|
96 |
+
elif "text" in content_type or "csv" in content_type or "json" in content_type:
|
97 |
+
file_text = file_bytes.decode(errors="ignore")[:6000]
|
98 |
+
file_context = f"File content:\n{file_text}\n"
|
99 |
+
else:
|
100 |
+
file_context = "[Unsupported or unknown file type]\n"
|
101 |
+
|
102 |
+
# Step 2: Use web search for open-domain/factual questions
|
103 |
+
# Basic heuristics: if the question is about a person, place, number, award, year, etc., try a search
|
104 |
+
search_needed = False
|
105 |
+
search_keywords = ["who", "what", "when", "where", "name", "number", "how many", "first", "last", "award", "recipient"]
|
106 |
+
if any(kw in question.lower() for kw in search_keywords):
|
107 |
+
search_results = self.web_search(question)
|
108 |
+
if search_results and "ERROR" not in search_results:
|
109 |
+
file_context += f"\nHere are relevant web search results:\n{search_results}\n"
|
110 |
+
search_needed = True
|
111 |
+
|
112 |
+
# Step 3: Build LLM prompt
|
113 |
+
prompt = (
|
114 |
+
f"{self.instructions}\n\n"
|
115 |
+
f"{file_context}"
|
116 |
+
f"Question: {question}\n"
|
117 |
+
"Show your reasoning step by step, then provide the final answer as 'Final Answer: <answer>'."
|
118 |
+
)
|
119 |
+
llm_response = self.call_llm(prompt)
|
120 |
+
answer = self.parse_final_answer(llm_response)
|
121 |
|
122 |
+
# Step 4: Enforce strict output: only final answer, no extra lines
|
123 |
+
return answer
|