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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import json
|
| 3 |
+
import torch
|
| 4 |
+
import base64
|
| 5 |
+
import requests
|
| 6 |
+
import mimetypes
|
| 7 |
+
import pygraphviz
|
| 8 |
+
from PIL import Image
|
| 9 |
+
from tavily import TavilyClient
|
| 10 |
+
from langchain_core.tools import tool
|
| 11 |
+
from langchain.chat_models import ChatOpenAI
|
| 12 |
+
from langchain_core.pydantic_v1 import BaseModel
|
| 13 |
+
from langgraph.graph import StateGraph, START, END
|
| 14 |
+
from langchain_experimental.utilities import PythonREPL
|
| 15 |
+
from langchain_core.messages import SystemMessage, HumanMessage
|
| 16 |
+
from typing import TypedDict, List, Dict, Any, Optional, Annotated
|
| 17 |
+
from transformers import Blip2Processor, Blip2ForConditionalGeneration
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
# ===== PLAN NODE PROMPT =====
|
| 22 |
+
PLAN_PROMPT = """
|
| 23 |
+
You are the GAIA Strategic Planner.
|
| 24 |
+
Input is a single JSON object with:
|
| 25 |
+
• question: string
|
| 26 |
+
• files: empty or array of objects, each with:
|
| 27 |
+
– file_path: string (URL or local path)
|
| 28 |
+
– file_type: one of ["image","text","pdf"]
|
| 29 |
+
• level: integer (1,2,3)
|
| 30 |
+
|
| 31 |
+
Your ONLY output must be a valid JSON array of step objects.
|
| 32 |
+
Each step object must be:
|
| 33 |
+
{
|
| 34 |
+
"tool": "<tool_name>",
|
| 35 |
+
"args": { … }
|
| 36 |
+
}
|
| 37 |
+
|
| 38 |
+
**Available tools & when to use them**
|
| 39 |
+
1. **vision_caption**
|
| 40 |
+
– Use if any file_type == "image" to extract visual information.
|
| 41 |
+
|
| 42 |
+
2. **pdf_parser**
|
| 43 |
+
– Use if any file_type == "pdf" or "text" to extract document contents.
|
| 44 |
+
|
| 45 |
+
3. **browser_search(query, max_results)**
|
| 46 |
+
– Factual lookup after you have text or image insights.
|
| 47 |
+
• Level 1: max_results=3
|
| 48 |
+
• Level 2: max_results=5 + cross‑validation searches
|
| 49 |
+
• Level 3: max_results=7 + specialized follow‑ups
|
| 50 |
+
|
| 51 |
+
4. **python_repl_tool(code)**
|
| 52 |
+
– For arithmetic, date math, or any required unit conversions.
|
| 53 |
+
|
| 54 |
+
**Sequencing rules**
|
| 55 |
+
- If you have an image **and** the question needs ingredients or labels:
|
| 56 |
+
1) vision_caption → get labels
|
| 57 |
+
2) browser_search on each label → gather details
|
| 58 |
+
3) python_repl_tool for any numeric aggregation
|
| 59 |
+
|
| 60 |
+
- If you have a PDF/text file **and** the question refers to its contents:
|
| 61 |
+
1) pdf_parser → extract raw text
|
| 62 |
+
2) browser_search on key terms or data points
|
| 63 |
+
3) python_repl_tool for calculations
|
| 64 |
+
|
| 65 |
+
- If both image and PDF/text are present, interleave:
|
| 66 |
+
vision_caption → pdf_parser → browser_search → python_repl_tool
|
| 67 |
+
|
| 68 |
+
**Multi‑entity handling**
|
| 69 |
+
- If question mentions >1 entity (e.g., two cities), generate separate browser_search steps for each.
|
| 70 |
+
|
| 71 |
+
DO NOT output anything else (no explanations, no markdown).
|
| 72 |
+
If no tools apply or you’re uncertain, output `[]`.
|
| 73 |
+
|
| 74 |
+
Example output:
|
| 75 |
+
```json
|
| 76 |
+
[
|
| 77 |
+
{ "tool": "vision_caption", "args": {"image_path":"chart.png"} },
|
| 78 |
+
{ "tool": "pdf_parser", "args": {"file_path":"data.pdf"} },
|
| 79 |
+
{ "tool": "browser_search", "args": {"query":"population of CityA","max_results":5} },
|
| 80 |
+
{ "tool": "python_repl_tool", "args": {"code":"print(30+49)"} }
|
| 81 |
+
]
|
| 82 |
+
|
| 83 |
+
---
|
| 84 |
+
|
| 85 |
+
### How to integrate this into your agent
|
| 86 |
+
|
| 87 |
+
1. **Planner Node**
|
| 88 |
+
- Feed it the above `PLAN_PROMPT` plus your JSON payload
|
| 89 |
+
- Parse its JSON array into `state["plan"]`
|
| 90 |
+
|
| 91 |
+
2. **Executor Node**
|
| 92 |
+
- Loop over `state["plan"]`, dispatching to `vision_caption`, `pdf_parser`, `browser_search`, or `python_repl_tool` as specified
|
| 93 |
+
|
| 94 |
+
3. **Content Accumulation**
|
| 95 |
+
- Collect each tool’s output into `state["tool_results"]` in sequence, so later tools (or your synthesizer) can see the combined context
|
| 96 |
+
|
| 97 |
+
4. **Synthesizer Node**
|
| 98 |
+
- Consume `state["tool_results"]` and generate the final GAIA‑format answer, pulling in facts, captions, and computed values
|
| 99 |
+
|
| 100 |
+
---
|
| 101 |
+
|
| 102 |
+
### Example Flow for a Mixed‑Modal Question
|
| 103 |
+
|
| 104 |
+
> **Question**: “From the attached recipe PDF, list each ingredient’s cost, then compute the total cost.”
|
| 105 |
+
|
| 106 |
+
- **files** includes one PDF
|
| 107 |
+
- **level** = 2
|
| 108 |
+
|
| 109 |
+
**Planner emits**:
|
| 110 |
+
```json
|
| 111 |
+
[
|
| 112 |
+
{ "tool":"pdf_parser", "args":{"file_path":"recipe.pdf"} },
|
| 113 |
+
{ "tool":"browser_search", "args":{"query":"cost of flour per kg","max_results":5} },
|
| 114 |
+
{ "tool":"browser_search", "args":{"query":"cost of sugar per kg","max_results":5} },
|
| 115 |
+
{ "tool":"python_repl_tool", "args":{"code":"print(2*1.5 + 3*0.8)"} }
|
| 116 |
+
]
|
| 117 |
+
"""
|
| 118 |
+
|
| 119 |
+
# ===== RESEARCH PLAN NODE PROMPT =====
|
| 120 |
+
RESEARCH_PROMPT = """**GAIA Query Optimizer**
|
| 121 |
+
Generate 1-3 search queries for factual data retrieval. Follow these rules:
|
| 122 |
+
|
| 123 |
+
**Query Requirements:**
|
| 124 |
+
1. Temporal specificity: Always include timeframe if relevant
|
| 125 |
+
2. Geographic precision: Add country/region when ambiguous
|
| 126 |
+
3. Source targeting: "site:*.gov" for official statistics
|
| 127 |
+
4. Exclusion list: -forum -blog -reddit
|
| 128 |
+
|
| 129 |
+
**Formatting Rules:**
|
| 130 |
+
- Use exact measurement units from question
|
| 131 |
+
- Maintain original terminology (don't paraphrase)
|
| 132 |
+
- Prioritize keywords over natural language
|
| 133 |
+
|
| 134 |
+
**Examples:**
|
| 135 |
+
Good: "France GDP 2020 in USD World Bank data"
|
| 136 |
+
Bad: "What was France's economy size last year?"
|
| 137 |
+
|
| 138 |
+
**Output Schema:**
|
| 139 |
+
```yaml
|
| 140 |
+
queries: list[str] # Ordered by priority, max 3 queries
|
| 141 |
+
"""
|
| 142 |
+
|
| 143 |
+
BROWSE_PROMPT = """
|
| 144 |
+
You are the GAIA Web Query Planner.
|
| 145 |
+
Given:
|
| 146 |
+
• task: a GAIA question requiring factual lookup
|
| 147 |
+
• content: a list of any snippets or context already gathered (may be empty)
|
| 148 |
+
|
| 149 |
+
Your job is to propose 2–3 concise search queries that will help answer the task.
|
| 150 |
+
Output **only** a JSON object matching this schema:
|
| 151 |
+
```json
|
| 152 |
+
{ "queries": ["first query", "second query", …] }
|
| 153 |
+
Do not include any other text or explanations.
|
| 154 |
+
"""
|
| 155 |
+
|
| 156 |
+
|
| 157 |
+
SYNTHESIZE_PROMPT = """
|
| 158 |
+
You are a highly precise assistant for the GAIA benchmark.
|
| 159 |
+
You have access to:
|
| 160 |
+
- The user’s question
|
| 161 |
+
- A list of “tool outputs” containing facts or computations
|
| 162 |
+
|
| 163 |
+
Your job:
|
| 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 |
+
|
| 175 |
+
|
| 176 |
+
|
| 177 |
+
DeepSeek_API_KEY= os.environ["DeepSeek_API_KEY"]
|
| 178 |
+
GPT_4o_API_KEY = os.environ["GPT_4o_API_KEY"]
|
| 179 |
+
TAVILY_API_KEY = os.environ["TAVILY_API_KEY"]
|
| 180 |
+
Pixtral12B_API = os.environ["Pixtral12B_API"]
|
| 181 |
+
API_URL = "https://openrouter.ai/api/v1/chat/completions"
|
| 182 |
+
|
| 183 |
+
model = ChatOpenAI(base_url="https://openrouter.ai/api/v1", temperature=0)
|
| 184 |
+
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
|
| 429 |
+
import torch
|
| 430 |
+
import base64
|
| 431 |
+
import requests
|
| 432 |
+
import mimetypes
|
| 433 |
+
import pygraphviz
|
| 434 |
+
from PIL import Image
|
| 435 |
+
from tavily import TavilyClient
|
| 436 |
+
from langchain_core.tools import tool
|
| 437 |
+
from langchain.chat_models import ChatOpenAI
|
| 438 |
+
from langchain_core.pydantic_v1 import BaseModel
|
| 439 |
+
from langgraph.graph import StateGraph, START, END
|
| 440 |
+
from langchain_experimental.utilities import PythonREPL
|
| 441 |
+
from langchain_core.messages import SystemMessage, HumanMessage
|
| 442 |
+
from typing import TypedDict, List, Dict, Any, Optional, Annotated
|
| 443 |
+
from transformers import Blip2Processor, Blip2ForConditionalGeneration
|
| 444 |
+
|
| 445 |
+
|
| 446 |
+
DeepSeek_API_KEY= os.environ["DeepSeek_API_KEY"]
|
| 447 |
+
GPT_4o_API_KEY = os.environ["GPT_4o_API_KEY"]
|
| 448 |
+
TAVILY_API_KEY = os.environ["TAVILY_API_KEY"]
|
| 449 |
+
Pixtral12B_API = os.environ["Pixtral12B_API"]
|
| 450 |
+
API_URL = "https://openrouter.ai/api/v1/chat/completions"
|
| 451 |
+
|
| 452 |
+
model = ChatOpenAI(base_url="https://openrouter.ai/api/v1", temperature=0)
|
| 453 |
+
tavily = TavilyClient(api_key=TAVILY_API_KEY)
|
| 454 |
+
|
| 455 |
+
|
| 456 |
+
|
| 457 |
+
# === 1. AGENT STATE ===
|
| 458 |
+
|
| 459 |
+
class GaiaAgentState(TypedDict):
|
| 460 |
+
task_id: int
|
| 461 |
+
question: str
|
| 462 |
+
files: List[str]
|
| 463 |
+
level: int
|
| 464 |
+
plan: List[Dict[str, Any]]
|
| 465 |
+
tool_results: List[Any]
|
| 466 |
+
final_answer: str
|
| 467 |
+
|
| 468 |
+
# === 2. TOOL STUBS ===
|
| 469 |
+
|
| 470 |
+
python_repl = PythonREPL()
|
| 471 |
+
@tool
|
| 472 |
+
def python_repl_tool(code: str) -> str:
|
| 473 |
+
"""
|
| 474 |
+
Execute Python code; return printed output.
|
| 475 |
+
"""
|
| 476 |
+
return python_repl.run(code)
|
| 477 |
+
|
| 478 |
+
@tool
|
| 479 |
+
def browser_search(query: str, max_results: int = 3) -> List[str]:
|
| 480 |
+
"""
|
| 481 |
+
Search the web for `query`, return top‐k text snippets.
|
| 482 |
+
TODO: implement with SerpAPI or HF browser.
|
| 483 |
+
"""
|
| 484 |
+
resp = model.invoke([
|
| 485 |
+
SystemMessage(content=BROWSE_PROMPT),
|
| 486 |
+
HumanMessage(content=json.dumps({"task": query}))
|
| 487 |
+
])
|
| 488 |
+
raw = resp.content.strip()
|
| 489 |
+
try:
|
| 490 |
+
queries = json.loads(raw)["queries"]
|
| 491 |
+
except Exception:
|
| 492 |
+
# fallback: just use the raw task as a single query
|
| 493 |
+
queries = [query]
|
| 494 |
+
|
| 495 |
+
#go through the queries we generted and search for them in Tavily
|
| 496 |
+
content = []
|
| 497 |
+
for q in queries:
|
| 498 |
+
response = tavily.search(query=q, max_results=max_results)
|
| 499 |
+
#append the new content to the old contetnt and return it
|
| 500 |
+
for r in response['results']:
|
| 501 |
+
content.append(r['content'])
|
| 502 |
+
return content
|
| 503 |
+
|
| 504 |
+
|
| 505 |
+
|
| 506 |
+
# === 1. Initialize the BLIP‑2 model & processor once ===
|
| 507 |
+
# You can choose a smaller or larger BLIP‑2 variant as needed.
|
| 508 |
+
MODEL_NAME = "Salesforce/blip2-opt-2.7b"
|
| 509 |
+
MODEL_NAME = "Salesforce/blip2-flan-t5-xl" # much smaller, still strong
|
| 510 |
+
|
| 511 |
+
processor = Blip2Processor.from_pretrained(MODEL_NAME)
|
| 512 |
+
model_blip2 = Blip2ForConditionalGeneration.from_pretrained(MODEL_NAME).to("cuda" if torch.cuda.is_available() else "cpu")
|
| 513 |
+
|
| 514 |
+
|
| 515 |
+
# === 2. The vision_caption tool ===
|
| 516 |
+
def encode_image_to_base64(image_path):
|
| 517 |
+
with open(image_path, "rb") as image_file:
|
| 518 |
+
return base64.b64encode(image_file.read()).decode('utf-8')
|
| 519 |
+
|
| 520 |
+
|
| 521 |
+
@tool
|
| 522 |
+
def vision_caption_via_api(image_path: str, max_length: Optional[int] = 64) -> str:
|
| 523 |
+
"""
|
| 524 |
+
Generate a natural‑language caption for the image at `image_path`.
|
| 525 |
+
|
| 526 |
+
Args:
|
| 527 |
+
image_path: Local filesystem path (or URL fetched locally) to an image file.
|
| 528 |
+
max_length: Maximum number of tokens in the generated caption (default: 64).
|
| 529 |
+
|
| 530 |
+
Returns:
|
| 531 |
+
A concise, human‑readable caption describing the image content.
|
| 532 |
+
"""
|
| 533 |
+
headers = {
|
| 534 |
+
"Authorization": f"Bearer {os.getenv('Pixtral12B_API')}",
|
| 535 |
+
"Content-Type": "application/json"
|
| 536 |
+
}
|
| 537 |
+
|
| 538 |
+
# Read and encode the image
|
| 539 |
+
base64_image = encode_image_to_base64(image_path)
|
| 540 |
+
|
| 541 |
+
messages = [
|
| 542 |
+
{
|
| 543 |
+
"role": "user",
|
| 544 |
+
"content": [
|
| 545 |
+
{
|
| 546 |
+
"type": "text",
|
| 547 |
+
"text": "What's in this image?"
|
| 548 |
+
},
|
| 549 |
+
{
|
| 550 |
+
"type": "image_url",
|
| 551 |
+
"image_url": {
|
| 552 |
+
"url": f"data:image/jpeg;base64,{base64_image}"
|
| 553 |
+
}
|
| 554 |
+
}
|
| 555 |
+
]
|
| 556 |
+
}
|
| 557 |
+
]
|
| 558 |
+
|
| 559 |
+
payload = {
|
| 560 |
+
"model": "google/gemini-2.0-flash-001",
|
| 561 |
+
"messages": messages
|
| 562 |
+
}
|
| 563 |
+
|
| 564 |
+
response = requests.post(url, headers=headers, json=payload)
|
| 565 |
+
response.raise_for_status()
|
| 566 |
+
|
| 567 |
+
# The HF endpoint returns JSON like {"generated_text": "...caption..."}
|
| 568 |
+
result = response.json()
|
| 569 |
+
# Some endpoints return a list of dicts, e.g. [{"generated_text": "..."}]
|
| 570 |
+
if isinstance(result, list) and "generated_text" in result[0]:
|
| 571 |
+
return result[0]["generated_text"]
|
| 572 |
+
elif "generated_text" in result:
|
| 573 |
+
return result["generated_text"]
|
| 574 |
+
else:
|
| 575 |
+
# fallback: return raw text
|
| 576 |
+
return str(result)
|
| 577 |
+
|
| 578 |
+
|
| 579 |
+
|
| 580 |
+
python_repl = PythonREPL()
|
| 581 |
+
@tool
|
| 582 |
+
def python_repl_tool(code: str) -> str:
|
| 583 |
+
"""
|
| 584 |
+
Execute Python code; return printed output.
|
| 585 |
+
"""
|
| 586 |
+
return python_repl.run(code)
|
| 587 |
+
|
| 588 |
+
@tool
|
| 589 |
+
def pdf_parser(file_path: str) -> str:
|
| 590 |
+
"""
|
| 591 |
+
Sends a PDF or a text file to OpenRouter’s chat API and returns the model’s answer.
|
| 592 |
+
"""
|
| 593 |
+
b64 = base64.b64encode(open(file_path,"rb").read()).decode()
|
| 594 |
+
payload = {
|
| 595 |
+
"model": "gpt-4o-mini",
|
| 596 |
+
"messages": [
|
| 597 |
+
{"role":"system","content":"You are a GAIA‑style document assistant."},
|
| 598 |
+
{"role":"user","content":[
|
| 599 |
+
{"type":"file","file":{"filename":os.path.basename(file_path),"file_data":f"data:application/pdf;base64,{b64}"}}
|
| 600 |
+
]}
|
| 601 |
+
]
|
| 602 |
+
}
|
| 603 |
+
headers = {"Authorization":f"Bearer {os.getenv('GPT_4o_API_KEY')}"}
|
| 604 |
+
res = requests.post(API_URL, json=payload, headers=headers)
|
| 605 |
+
res.raise_for_status()
|
| 606 |
+
content = res.json()["choices"][0]["message"]["content"]
|
| 607 |
+
# Extract FINAL ANSWER:
|
| 608 |
+
for line in content.splitlines():
|
| 609 |
+
if line.startswith("FINAL ANSWER:"):
|
| 610 |
+
return line.split(":",1)[1].strip()
|
| 611 |
+
return content
|
| 612 |
+
|
| 613 |
+
# Build a simple name→function map for execution
|
| 614 |
+
TOOLS: Dict[str, Any] = {
|
| 615 |
+
"browser_search": browser_search,
|
| 616 |
+
"vision_caption": vision_caption_via_api,
|
| 617 |
+
"pdf_parser": pdf_parser,
|
| 618 |
+
"python_repl_tool": python_repl_tool,
|
| 619 |
+
}
|
| 620 |
+
|
| 621 |
+
|
| 622 |
+
# === 3. NODES ===
|
| 623 |
+
def planner_node(state: GaiaAgentState) -> dict:
|
| 624 |
+
# Build metadata for each file
|
| 625 |
+
files_metadata = []
|
| 626 |
+
for f_path in state['files']:
|
| 627 |
+
mime, _ = mimetypes.guess_type(f_path)
|
| 628 |
+
kind = "image" if mime and mime.startswith("image/") else "text"
|
| 629 |
+
files_metadata.append({
|
| 630 |
+
"file_path": f_path,
|
| 631 |
+
"file_type": kind
|
| 632 |
+
})
|
| 633 |
+
|
| 634 |
+
human_content = json.dumps({
|
| 635 |
+
"question": state['question'],
|
| 636 |
+
"files": files_metadata,
|
| 637 |
+
"level": state['level']
|
| 638 |
+
})
|
| 639 |
+
|
| 640 |
+
messages = [
|
| 641 |
+
SystemMessage(content=PLAN_PROMPT),
|
| 642 |
+
HumanMessage(content=human_content)
|
| 643 |
+
]
|
| 644 |
+
response = model.invoke(messages)
|
| 645 |
+
plan = json.loads(response.content)
|
| 646 |
+
return {"plan": plan}
|
| 647 |
+
|
| 648 |
+
|
| 649 |
+
def tool_executor(state: GaiaAgentState) -> dict:
|
| 650 |
+
tool_results = []
|
| 651 |
+
for step in state['plan']:
|
| 652 |
+
tool_obj = TOOLS[step["tool"]]
|
| 653 |
+
out = tool_obj.run(tool_input=step["args"])
|
| 654 |
+
tool_results.append(out)
|
| 655 |
+
return {'tool_results': out}
|
| 656 |
+
|
| 657 |
+
|
| 658 |
+
# ===== 2. The node implementation =====
|
| 659 |
+
def synthesizer(state: GaiaAgentState) -> dict:
|
| 660 |
+
|
| 661 |
+
# Format tool outputs as bullet points
|
| 662 |
+
snippet_text = "\n".join(f"- {s}" for s in state["tool_results"])
|
| 663 |
+
|
| 664 |
+
human_payload = f"""
|
| 665 |
+
Question: {state['question']}
|
| 666 |
+
|
| 667 |
+
Tool outputs:
|
| 668 |
+
{snippet_text}
|
| 669 |
+
|
| 670 |
+
Using the above, answer the question.
|
| 671 |
+
"""
|
| 672 |
+
messages = [
|
| 673 |
+
SystemMessage(content=SYNTHESIZE_PROMPT),
|
| 674 |
+
HumanMessage(content=human_payload.strip())
|
| 675 |
+
]
|
| 676 |
+
|
| 677 |
+
# Invoke your chat model (replace with your actual model instance)
|
| 678 |
+
response = model.invoke(messages)
|
| 679 |
+
text = response.content.strip()
|
| 680 |
+
|
| 681 |
+
# Extract the line starting with FINAL ANSWER:
|
| 682 |
+
final = None
|
| 683 |
+
for line in text.splitlines():
|
| 684 |
+
if line.startswith("FINAL ANSWER:"):
|
| 685 |
+
final = line[len("FINAL ANSWER:"):].strip()
|
| 686 |
+
break
|
| 687 |
+
if final is None:
|
| 688 |
+
# Fallback: last non-empty line
|
| 689 |
+
final = text.splitlines()[-1].strip()
|
| 690 |
+
|
| 691 |
+
return {"final_answer": final}
|
| 692 |
+
|
| 693 |
+
|
| 694 |
+
|
| 695 |
+
# === 4. BUILD & COMPILE GRAPH ===
|
| 696 |
+
|
| 697 |
+
builder = StateGraph(GaiaAgentState)
|
| 698 |
+
|
| 699 |
+
builder.add_node("planner", planner_node)
|
| 700 |
+
builder.add_node("execute", tool_executor)
|
| 701 |
+
builder.add_node("synthesize", synthesizer)
|
| 702 |
+
|
| 703 |
+
builder.add_edge(START, "planner")
|
| 704 |
+
builder.add_edge("planner", "execute")
|
| 705 |
+
builder.add_edge("execute", "synthesize")
|
| 706 |
+
builder.add_edge("synthesize", END)
|
| 707 |
+
|
| 708 |
+
graph = builder.compile()
|
| 709 |
+
|
| 710 |
+
# === 5. RUN EXAMPLE ===
|
| 711 |
+
# Example dev payload (in practice, fetch from /random-question)
|
| 712 |
+
|
| 713 |
+
# test
|
| 714 |
+
if __name__ == "__main__":
|
| 715 |
+
question = "When was a picture of St. Thomas Aquinas first added to the Wikipedia page on the Principle of double effect?"
|
| 716 |
+
# Build the graph
|
| 717 |
+
# Run the graph
|
| 718 |
+
messages = [HumanMessage(content=question)]
|
| 719 |
+
messages = graph.invoke({"messages": messages})
|
| 720 |
+
for m in messages["messages"]:
|
| 721 |
+
m.pretty_print()
|
| 722 |
+
|