Spaces:
Sleeping
Sleeping
Update agent.py
Browse files
agent.py
CHANGED
|
@@ -160,15 +160,7 @@ You have access to:
|
|
| 160 |
- The user’s question
|
| 161 |
- A list of “tool outputs” containing facts or computations
|
| 162 |
|
| 163 |
-
|
| 164 |
-
1. Show your chain of thought, prefixing each reasoning step with `Thought:`
|
| 165 |
-
2. Conclude with exactly one line, starting with `FINAL ANSWER: ` followed by your answer.
|
| 166 |
-
|
| 167 |
-
Formatting rules for the answer only:
|
| 168 |
-
- If numeric, write plain digits (no commas, no percent signs, no units unless asked).
|
| 169 |
-
- If textual, no articles (“the”, “a”), no abbreviations (e.g. “NYC” → “New York City”).
|
| 170 |
-
- If a list, comma‑separate with one space after each comma.
|
| 171 |
-
- Do not include any extra text or punctuation before `FINAL ANSWER:`.
|
| 172 |
"""
|
| 173 |
|
| 174 |
|
|
@@ -185,244 +177,6 @@ tavily = TavilyClient(api_key=TAVILY_API_KEY)
|
|
| 185 |
|
| 186 |
|
| 187 |
|
| 188 |
-
# === 1. AGENT STATE ===
|
| 189 |
-
|
| 190 |
-
class GaiaAgentState(TypedDict):
|
| 191 |
-
task_id: int
|
| 192 |
-
question: str
|
| 193 |
-
files: List[str]
|
| 194 |
-
level: int
|
| 195 |
-
plan: List[Dict[str, Any]]
|
| 196 |
-
tool_results: List[Any]
|
| 197 |
-
final_answer: str
|
| 198 |
-
|
| 199 |
-
# === 2. TOOL STUBS ===
|
| 200 |
-
|
| 201 |
-
python_repl = PythonREPL()
|
| 202 |
-
@tool
|
| 203 |
-
def python_repl_tool(code: str) -> str:
|
| 204 |
-
"""
|
| 205 |
-
Execute Python code; return printed output.
|
| 206 |
-
"""
|
| 207 |
-
return python_repl.run(code)
|
| 208 |
-
|
| 209 |
-
@tool
|
| 210 |
-
def browser_search(query: str, max_results: int = 3) -> List[str]:
|
| 211 |
-
"""
|
| 212 |
-
Search the web for `query`, return top‐k text snippets.
|
| 213 |
-
TODO: implement with SerpAPI or HF browser.
|
| 214 |
-
"""
|
| 215 |
-
resp = model.invoke([
|
| 216 |
-
SystemMessage(content=BROWSE_PROMPT),
|
| 217 |
-
HumanMessage(content=json.dumps({"task": query}))
|
| 218 |
-
])
|
| 219 |
-
raw = resp.content.strip()
|
| 220 |
-
try:
|
| 221 |
-
queries = json.loads(raw)["queries"]
|
| 222 |
-
except Exception:
|
| 223 |
-
# fallback: just use the raw task as a single query
|
| 224 |
-
queries = [query]
|
| 225 |
-
|
| 226 |
-
#go through the queries we generted and search for them in Tavily
|
| 227 |
-
content = []
|
| 228 |
-
for q in queries:
|
| 229 |
-
response = tavily.search(query=q, max_results=max_results)
|
| 230 |
-
#append the new content to the old contetnt and return it
|
| 231 |
-
for r in response['results']:
|
| 232 |
-
content.append(r['content'])
|
| 233 |
-
return content
|
| 234 |
-
|
| 235 |
-
|
| 236 |
-
|
| 237 |
-
# === 1. Initialize the BLIP‑2 model & processor once ===
|
| 238 |
-
# You can choose a smaller or larger BLIP‑2 variant as needed.
|
| 239 |
-
MODEL_NAME = "Salesforce/blip2-opt-2.7b"
|
| 240 |
-
MODEL_NAME = "Salesforce/blip2-flan-t5-xl" # much smaller, still strong
|
| 241 |
-
|
| 242 |
-
processor = Blip2Processor.from_pretrained(MODEL_NAME)
|
| 243 |
-
model_blip2 = Blip2ForConditionalGeneration.from_pretrained(MODEL_NAME).to("cuda" if torch.cuda.is_available() else "cpu")
|
| 244 |
-
|
| 245 |
-
|
| 246 |
-
# === 2. The vision_caption tool ===
|
| 247 |
-
def encode_image_to_base64(image_path):
|
| 248 |
-
with open(image_path, "rb") as image_file:
|
| 249 |
-
return base64.b64encode(image_file.read()).decode('utf-8')
|
| 250 |
-
|
| 251 |
-
|
| 252 |
-
@tool
|
| 253 |
-
def vision_caption_via_api(image_path: str, max_length: Optional[int] = 64) -> str:
|
| 254 |
-
"""
|
| 255 |
-
Generate a natural‑language caption for the image at `image_path`.
|
| 256 |
-
|
| 257 |
-
Args:
|
| 258 |
-
image_path: Local filesystem path (or URL fetched locally) to an image file.
|
| 259 |
-
max_length: Maximum number of tokens in the generated caption (default: 64).
|
| 260 |
-
|
| 261 |
-
Returns:
|
| 262 |
-
A concise, human‑readable caption describing the image content.
|
| 263 |
-
"""
|
| 264 |
-
headers = {
|
| 265 |
-
"Authorization": f"Bearer {os.getenv('Pixtral12B_API')}",
|
| 266 |
-
"Content-Type": "application/json"
|
| 267 |
-
}
|
| 268 |
-
|
| 269 |
-
# Read and encode the image
|
| 270 |
-
base64_image = encode_image_to_base64(image_path)
|
| 271 |
-
|
| 272 |
-
messages = [
|
| 273 |
-
{
|
| 274 |
-
"role": "user",
|
| 275 |
-
"content": [
|
| 276 |
-
{
|
| 277 |
-
"type": "text",
|
| 278 |
-
"text": "What's in this image?"
|
| 279 |
-
},
|
| 280 |
-
{
|
| 281 |
-
"type": "image_url",
|
| 282 |
-
"image_url": {
|
| 283 |
-
"url": f"data:image/jpeg;base64,{base64_image}"
|
| 284 |
-
}
|
| 285 |
-
}
|
| 286 |
-
]
|
| 287 |
-
}
|
| 288 |
-
]
|
| 289 |
-
|
| 290 |
-
payload = {
|
| 291 |
-
"model": "google/gemini-2.0-flash-001",
|
| 292 |
-
"messages": messages
|
| 293 |
-
}
|
| 294 |
-
|
| 295 |
-
response = requests.post(url, headers=headers, json=payload)
|
| 296 |
-
response.raise_for_status()
|
| 297 |
-
|
| 298 |
-
# The HF endpoint returns JSON like {"generated_text": "...caption..."}
|
| 299 |
-
result = response.json()
|
| 300 |
-
# Some endpoints return a list of dicts, e.g. [{"generated_text": "..."}]
|
| 301 |
-
if isinstance(result, list) and "generated_text" in result[0]:
|
| 302 |
-
return result[0]["generated_text"]
|
| 303 |
-
elif "generated_text" in result:
|
| 304 |
-
return result["generated_text"]
|
| 305 |
-
else:
|
| 306 |
-
# fallback: return raw text
|
| 307 |
-
return str(result)
|
| 308 |
-
|
| 309 |
-
|
| 310 |
-
|
| 311 |
-
python_repl = PythonREPL()
|
| 312 |
-
@tool
|
| 313 |
-
def python_repl_tool(code: str) -> str:
|
| 314 |
-
"""
|
| 315 |
-
Execute Python code; return printed output.
|
| 316 |
-
"""
|
| 317 |
-
return python_repl.run(code)
|
| 318 |
-
|
| 319 |
-
@tool
|
| 320 |
-
def pdf_parser(file_path: str) -> str:
|
| 321 |
-
"""
|
| 322 |
-
Sends a PDF or a text file to OpenRouter’s chat API and returns the model’s answer.
|
| 323 |
-
"""
|
| 324 |
-
b64 = base64.b64encode(open(file_path,"rb").read()).decode()
|
| 325 |
-
payload = {
|
| 326 |
-
"model": "gpt-4o-mini",
|
| 327 |
-
"messages": [
|
| 328 |
-
{"role":"system","content":"You are a GAIA‑style document assistant."},
|
| 329 |
-
{"role":"user","content":[
|
| 330 |
-
{"type":"file","file":{"filename":os.path.basename(file_path),"file_data":f"data:application/pdf;base64,{b64}"}}
|
| 331 |
-
]}
|
| 332 |
-
]
|
| 333 |
-
}
|
| 334 |
-
headers = {"Authorization":f"Bearer {os.getenv('GPT_4o_API_KEY')}"}
|
| 335 |
-
res = requests.post(API_URL, json=payload, headers=headers)
|
| 336 |
-
res.raise_for_status()
|
| 337 |
-
content = res.json()["choices"][0]["message"]["content"]
|
| 338 |
-
# Extract FINAL ANSWER:
|
| 339 |
-
for line in content.splitlines():
|
| 340 |
-
if line.startswith("FINAL ANSWER:"):
|
| 341 |
-
return line.split(":",1)[1].strip()
|
| 342 |
-
return content
|
| 343 |
-
|
| 344 |
-
# Build a simple name→function map for execution
|
| 345 |
-
TOOLS: Dict[str, Any] = {
|
| 346 |
-
"browser_search": browser_search,
|
| 347 |
-
"vision_caption": vision_caption_via_api,
|
| 348 |
-
"pdf_parser": pdf_parser,
|
| 349 |
-
"python_repl_tool": python_repl_tool,
|
| 350 |
-
}
|
| 351 |
-
|
| 352 |
-
|
| 353 |
-
# === 3. NODES ===
|
| 354 |
-
def planner_node(state: GaiaAgentState) -> dict:
|
| 355 |
-
# Build metadata for each file
|
| 356 |
-
files_metadata = []
|
| 357 |
-
for f_path in state['files']:
|
| 358 |
-
mime, _ = mimetypes.guess_type(f_path)
|
| 359 |
-
kind = "image" if mime and mime.startswith("image/") else "text"
|
| 360 |
-
files_metadata.append({
|
| 361 |
-
"file_path": f_path,
|
| 362 |
-
"file_type": kind
|
| 363 |
-
})
|
| 364 |
-
|
| 365 |
-
human_content = json.dumps({
|
| 366 |
-
"question": state['question'],
|
| 367 |
-
"files": files_metadata,
|
| 368 |
-
"level": state['level']
|
| 369 |
-
})
|
| 370 |
-
|
| 371 |
-
messages = [
|
| 372 |
-
SystemMessage(content=PLAN_PROMPT),
|
| 373 |
-
HumanMessage(content=human_content)
|
| 374 |
-
]
|
| 375 |
-
response = model.invoke(messages)
|
| 376 |
-
plan = json.loads(response.content)
|
| 377 |
-
return {"plan": plan}
|
| 378 |
-
|
| 379 |
-
|
| 380 |
-
def tool_executor(state: GaiaAgentState) -> dict:
|
| 381 |
-
tool_results = []
|
| 382 |
-
for step in state['plan']:
|
| 383 |
-
tool_obj = TOOLS[step["tool"]]
|
| 384 |
-
out = tool_obj.run(tool_input=step["args"])
|
| 385 |
-
tool_results.append(out)
|
| 386 |
-
return {'tool_results': out}
|
| 387 |
-
|
| 388 |
-
|
| 389 |
-
# ===== 2. The node implementation =====
|
| 390 |
-
def synthesizer(state: GaiaAgentState) -> dict:
|
| 391 |
-
|
| 392 |
-
# Format tool outputs as bullet points
|
| 393 |
-
snippet_text = "\n".join(f"- {s}" for s in state["tool_results"])
|
| 394 |
-
|
| 395 |
-
human_payload = f"""
|
| 396 |
-
Question: {state['question']}
|
| 397 |
-
|
| 398 |
-
Tool outputs:
|
| 399 |
-
{snippet_text}
|
| 400 |
-
|
| 401 |
-
Using the above, answer the question.
|
| 402 |
-
"""
|
| 403 |
-
messages = [
|
| 404 |
-
SystemMessage(content=SYNTHESIZE_PROMPT),
|
| 405 |
-
HumanMessage(content=human_payload.strip())
|
| 406 |
-
]
|
| 407 |
-
|
| 408 |
-
# Invoke your chat model (replace with your actual model instance)
|
| 409 |
-
response = model.invoke(messages)
|
| 410 |
-
text = response.content.strip()
|
| 411 |
-
|
| 412 |
-
# Extract the line starting with FINAL ANSWER:
|
| 413 |
-
final = None
|
| 414 |
-
for line in text.splitlines():
|
| 415 |
-
if line.startswith("FINAL ANSWER:"):
|
| 416 |
-
final = line[len("FINAL ANSWER:"):].strip()
|
| 417 |
-
break
|
| 418 |
-
if final is None:
|
| 419 |
-
# Fallback: last non-empty line
|
| 420 |
-
final = text.splitlines()[-1].strip()
|
| 421 |
-
|
| 422 |
-
return {"final_answer": final}
|
| 423 |
-
|
| 424 |
-
|
| 425 |
-
|
| 426 |
# === 4. BUILD & COMPILE GRAPH ===
|
| 427 |
import os
|
| 428 |
import json
|
|
|
|
| 160 |
- The user’s question
|
| 161 |
- A list of “tool outputs” containing facts or computations
|
| 162 |
|
| 163 |
+
You are a general AI assistant. I will ask you a question. Report your thoughts, and finish your answer with the following template: FINAL ANSWER: [YOUR FINAL ANSWER]. YOUR FINAL ANSWER should be a number OR as few words as possible OR a comma separated list of numbers and/or strings. If you are asked for a number, don't use comma to write your number neither use units such as $ or percent sign unless specified otherwise. If you are asked for a string, don't use articles, neither abbreviations (e.g. for cities), and write the digits in plain text unless specified otherwise. If you are asked for a comma separated list, apply the above rules depending of whether the element to be put in the list is a number or a string.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 164 |
"""
|
| 165 |
|
| 166 |
|
|
|
|
| 177 |
|
| 178 |
|
| 179 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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