mralamdari commited on
Commit
482279f
·
verified ·
1 Parent(s): 6bcbd05

Update agent.py

Browse files
Files changed (1) hide show
  1. agent.py +237 -348
agent.py CHANGED
@@ -1,131 +1,8 @@
1
- # ===== PLAN NODE PROMPT =====
2
- PLAN_PROMPT = """
3
- You are the GAIA Strategic Planner.
4
- Input is a single JSON object with:
5
- • question: string
6
- • files: empty or array of objects, each with:
7
- – file_path: string (URL or local path)
8
- – file_type: one of ["image","text","pdf"]
9
- • level: integer (1,2,3)
10
-
11
- Your ONLY output must be a valid JSON array of step objects.
12
- Each step object must be:
13
- {
14
- "tool": "<tool_name>",
15
- "args": { … }
16
- }
17
-
18
- **Available tools & when to use them**
19
- 1. **vision_caption**
20
- – Use if any file_type == "image" to extract visual information.
21
-
22
- 2. **pdf_parser**
23
- – Use if any file_type == "pdf" or "text" to extract document contents.
24
-
25
- 3. **browser_search(query, max_results)**
26
- – Factual lookup after you have text or image insights.
27
- • Level 1: max_results=3
28
- • Level 2: max_results=5 + cross‑validation searches
29
- • Level 3: max_results=7 + specialized follow‑ups
30
-
31
- 4. **python_repl_tool(code)**
32
- – For arithmetic, date math, or any required unit conversions.
33
-
34
- **Sequencing rules**
35
- - If you have an image **and** the question needs ingredients or labels:
36
- 1) vision_caption → get labels
37
- 2) browser_search on each label → gather details
38
- 3) python_repl_tool for any numeric aggregation
39
-
40
- - If you have a PDF/text file **and** the question refers to its contents:
41
- 1) pdf_parser → extract raw text
42
- 2) browser_search on key terms or data points
43
- 3) python_repl_tool for calculations
44
-
45
- - If both image and PDF/text are present, interleave:
46
- vision_caption → pdf_parser → browser_search → python_repl_tool
47
-
48
- **Multi‑entity handling**
49
- - If question mentions >1 entity (e.g., two cities), generate separate browser_search steps for each.
50
-
51
- DO NOT output anything else (no explanations, no markdown).
52
- If no tools apply or you’re uncertain, output `[]`.
53
-
54
- Example output:
55
- ```json
56
- [
57
- { "tool": "vision_caption", "args": {"image_path":"chart.png"} },
58
- { "tool": "pdf_parser", "args": {"file_path":"data.pdf"} },
59
- { "tool": "browser_search", "args": {"query":"population of CityA","max_results":5} },
60
- { "tool": "python_repl_tool", "args": {"code":"print(30+49)"} }
61
- ]
62
-
63
- ---
64
-
65
- ### How to integrate this into your agent
66
-
67
- 1. **Planner Node**
68
- - Feed it the above `PLAN_PROMPT` plus your JSON payload
69
- - Parse its JSON array into `state["plan"]`
70
-
71
- 2. **Executor Node**
72
- - Loop over `state["plan"]`, dispatching to `vision_caption`, `pdf_parser`, `browser_search`, or `python_repl_tool` as specified
73
-
74
- 3. **Content Accumulation**
75
- - Collect each tool’s output into `state["tool_results"]` in sequence, so later tools (or your synthesizer) can see the combined context
76
-
77
- 4. **Synthesizer Node**
78
- - Consume `state["tool_results"]` and generate the final GAIA‑format answer, pulling in facts, captions, and computed values
79
-
80
- ---
81
-
82
- ### Example Flow for a Mixed‑Modal Question
83
-
84
- > **Question**: “From the attached recipe PDF, list each ingredient’s cost, then compute the total cost.”
85
-
86
- - **files** includes one PDF
87
- - **level** = 2
88
-
89
- **Planner emits**:
90
- ```json
91
- [
92
- { "tool":"pdf_parser", "args":{"file_path":"recipe.pdf"} },
93
- { "tool":"browser_search", "args":{"query":"cost of flour per kg","max_results":5} },
94
- { "tool":"browser_search", "args":{"query":"cost of sugar per kg","max_results":5} },
95
- { "tool":"python_repl_tool", "args":{"code":"print(2*1.5 + 3*0.8)"} }
96
- ]
97
- """
98
-
99
- # ===== RESEARCH PLAN NODE PROMPT =====
100
- RESEARCH_PROMPT = """**GAIA Query Optimizer**
101
- Generate 1-3 search queries for factual data retrieval. Follow these rules:
102
-
103
- **Query Requirements:**
104
- 1. Temporal specificity: Always include timeframe if relevant
105
- 2. Geographic precision: Add country/region when ambiguous
106
- 3. Source targeting: "site:*.gov" for official statistics
107
- 4. Exclusion list: -forum -blog -reddit
108
-
109
- **Formatting Rules:**
110
- - Use exact measurement units from question
111
- - Maintain original terminology (don't paraphrase)
112
- - Prioritize keywords over natural language
113
-
114
- **Examples:**
115
- Good: "France GDP 2020 in USD World Bank data"
116
- Bad: "What was France's economy size last year?"
117
-
118
- **Output Schema:**
119
- ```yaml
120
- queries: list[str] # Ordered by priority, max 3 queries
121
- """
122
-
123
  BROWSE_PROMPT = """
124
  You are the GAIA Web Query Planner.
125
  Given:
126
  • task: a GAIA question requiring factual lookup
127
  • content: a list of any snippets or context already gathered (may be empty)
128
-
129
  Your job is to propose 2–3 concise search queries that will help answer the task.
130
  Output **only** a JSON object matching this schema:
131
  ```json
@@ -134,85 +11,54 @@ Do not include any other text or explanations.
134
  """
135
 
136
 
137
- SYNTHESIZE_PROMPT = """
138
- You are a highly precise assistant for the GAIA benchmark.
139
- You have access to:
140
- - The user’s question
141
- - A list of “tool outputs” containing facts or computations
142
-
143
- 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.
144
- """
145
-
146
 
147
- import os
148
- import json
149
- import torch
150
- import base64
151
- import requests
152
- import mimetypes
153
- from PIL import Image
154
- from langchain_core.tools import tool
155
- from dataclasses import dataclass, field
156
- # from langchain.chat_models import ChatOpenAI
157
- # from langchain_community.chat_models import ChatOpenAI
158
- # from langchain.chat_models import ChatOpenAI
159
- # from langchain_core.pydantic_v1 import BaseModel
160
- # from langchain_community.chat_models import ChatOpenAI
161
- # Or, if you’ve installed langchain-openai:
162
- # from langchain_openai import ChatOpenAI
163
- from pydantic import BaseModel
164
- from langchain_openai import ChatOpenAI
165
- from langgraph.graph import StateGraph, START, END
166
- from langchain_experimental.utilities import PythonREPL
167
- from langchain_core.messages import SystemMessage, HumanMessage
168
- from typing import TypedDict, List, Dict, Any, Optional, Annotated
169
- from transformers import Blip2Processor, Blip2ForConditionalGeneration
170
-
171
- from tavily import TavilyClient
172
-
173
- GPT_4o_API_KEY = os.environ["DeepSeek_API_KEY"]
174
  # GPT_4o_API_KEY = os.environ["GPT_4o_API_KEY"]
175
  TAVILY_API_KEY = os.environ["TAVILY_API_KEY"]
176
  Pixtral12B_API = os.environ["Pixtral12B_API"]
177
 
178
-
179
  API_URL = "https://openrouter.ai/api/v1/chat/completions"
180
-
181
- model = ChatOpenAI(openai_api_key=GPT_4o_API_KEY,
182
- base_url="https://openrouter.ai/api/v1",
183
- # model_name="gpt-4o",
184
- temperature=0)
185
  tavily = TavilyClient(api_key=TAVILY_API_KEY)
186
 
187
 
188
- # === 1. AGENT STATE ===
189
- @dataclass
190
- class GaiaAgentState:
191
- raw_payload: Dict[str, Any]
192
- question: str = ""
193
- files: List[str] = field(default_factory=list)
194
- level: int = 1
195
- # downstream nodes can write into these:
196
- plan: List[Dict[str,Any]] = field(default_factory=list)
197
- tool_results: List[Any] = field(default_factory=list)
198
- final_answer: str = ""
199
 
200
- # === 2. TOOL STUBS ===
201
-
202
- python_repl = PythonREPL()
203
  @tool
204
- def python_repl_tool(code: str) -> str:
205
  """
206
- Execute Python code; return printed output.
 
 
 
 
 
 
207
  """
208
- return python_repl.run(code)
 
209
 
210
  @tool
211
- def browser_search(query: str, max_results: int = 3) -> List[str]:
212
  """
213
- Search the web for `query`, return top‐k text snippets.
214
- TODO: implement with SerpAPI or HF browser.
 
 
 
 
 
 
215
  """
 
 
 
 
 
216
  resp = model.invoke([
217
  SystemMessage(content=BROWSE_PROMPT),
218
  HumanMessage(content=json.dumps({"task": query}))
@@ -227,11 +73,27 @@ def browser_search(query: str, max_results: int = 3) -> List[str]:
227
  #go through the queries we generted and search for them in Tavily
228
  content = []
229
  for q in queries:
230
- response = tavily.search(query=q, max_results=max_results)
231
  #append the new content to the old contetnt and return it
232
- for r in response['results']:
233
- content.append(r['content'])
234
- return content
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
235
 
236
 
237
 
@@ -239,19 +101,12 @@ def browser_search(query: str, max_results: int = 3) -> List[str]:
239
  # You can choose a smaller or larger BLIP‑2 variant as needed.
240
  MODEL_NAME = "Salesforce/blip2-opt-2.7b"
241
  MODEL_NAME = "Salesforce/blip2-flan-t5-xl" # much smaller, still strong
242
-
243
  processor = Blip2Processor.from_pretrained(MODEL_NAME)
244
  model_blip2 = Blip2ForConditionalGeneration.from_pretrained(MODEL_NAME).to("cuda" if torch.cuda.is_available() else "cpu")
245
 
246
 
247
- # === 2. The vision_caption tool ===
248
- def encode_image_to_base64(image_path):
249
- with open(image_path, "rb") as image_file:
250
- return base64.b64encode(image_file.read()).decode('utf-8')
251
-
252
-
253
  @tool
254
- def vision_caption_via_api(image_path: str, max_length: Optional[int] = 64) -> str:
255
  """
256
  Generate a natural‑language caption for the image at `image_path`.
257
  Args:
@@ -266,7 +121,8 @@ def vision_caption_via_api(image_path: str, max_length: Optional[int] = 64) -> s
266
  }
267
 
268
  # Read and encode the image
269
- base64_image = encode_image_to_base64(image_path)
 
270
 
271
  messages = [
272
  {
@@ -307,18 +163,110 @@ def vision_caption_via_api(image_path: str, max_length: Optional[int] = 64) -> s
307
 
308
 
309
 
310
- python_repl = PythonREPL()
311
  @tool
312
- def python_repl_tool(code: str) -> str:
313
  """
314
- Execute Python code; return printed output.
 
 
 
 
315
  """
316
- return python_repl.run(code)
 
 
 
 
 
 
 
 
 
 
317
 
318
  @tool
319
- def pdf_parser(file_path: str) -> str:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
320
  """
321
  Sends a PDF or a text file to OpenRouter’s chat API and returns the model’s answer.
 
 
 
 
 
322
  """
323
  b64 = base64.b64encode(open(file_path,"rb").read()).decode()
324
  payload = {
@@ -340,154 +288,95 @@ def pdf_parser(file_path: str) -> str:
340
  return line.split(":",1)[1].strip()
341
  return content
342
 
343
- # Build a simple name→function map for execution
344
- TOOLS: Dict[str, Any] = {
345
- "browser_search": browser_search,
346
- "vision_caption": vision_caption_via_api,
347
- "pdf_parser": pdf_parser,
348
- "python_repl_tool": python_repl_tool,
349
- }
350
-
351
-
352
- # === 3. NODES ===
353
- def planner_node(state: GaiaAgentState) -> dict:
354
- # Build metadata for each file
355
- files_metadata = []
356
- # print(55555555555555,state.files)
357
- for f_path in state.files:
358
- # for f_path in state.files:
359
- mime, _ = mimetypes.guess_type(f_path)
360
- kind = "image" if mime and mime.startswith("image/") else "text"
361
- files_metadata.append({
362
- "file_path": f_path,
363
- "file_type": kind
364
- })
365
-
366
- human_content = json.dumps({
367
- "question": state.question,
368
- "files": files_metadata,
369
- "level": state.level
370
- })
371
-
372
- messages = [
373
- SystemMessage(content=PLAN_PROMPT),
374
- HumanMessage(content=human_content)
375
- ]
376
- response = model.invoke(messages)
377
- plan = json.loads(response.content)
378
- return {"plan": plan}
379
-
380
-
381
- def tool_executor(state: GaiaAgentState) -> dict:
382
- tool_results = []
383
- for step in state.plan:
384
- tool_obj = TOOLS[step["tool"]]
385
- out = tool_obj.run(tool_input=step["args"])
386
- tool_results.append(out)
387
- return {'tool_results': tool_results}
388
-
389
-
390
- # ===== 2. The node implementation =====
391
- def synthesizer(state: GaiaAgentState) -> dict:
392
-
393
- # Format tool outputs as bullet points
394
- snippet_text = "\n".join(f"- {s}" for s in state.tool_results)
395
-
396
- human_payload = f"""
397
- Question: {state.question}
398
- Tool outputs:
399
- {snippet_text}
400
- Using the above, answer the question.
401
- """
402
- messages = [
403
- SystemMessage(content=SYNTHESIZE_PROMPT),
404
- HumanMessage(content=human_payload.strip())
405
- ]
406
-
407
- # Invoke your chat model (replace with your actual model instance)
408
- response = model.invoke(messages)
409
- text = response.content.strip()
410
-
411
- # Extract the line starting with FINAL ANSWER:
412
- final = None
413
- for line in text.splitlines():
414
- if line.startswith("FINAL ANSWER:"):
415
- final = line[len("FINAL ANSWER:"):].strip()
416
- break
417
- if final is None:
418
- # Fallback: last non-empty line
419
- final = text.splitlines()[-1].strip()
420
-
421
- return {"final_answer": final}
422
-
423
-
424
-
425
-
426
-
427
- # 2) Input‑parser node: unpacks raw_payload→working state
428
- def input_parser(state: GaiaAgentState) -> dict:
429
- return {
430
- "question": state.raw_payload["question"],
431
- "files": state.raw_payload.get("files", []),
432
- "level": state.raw_payload.get("level", 1),
433
- }
434
-
435
-
436
-
437
-
438
- class EsiAgent:
439
- def __init__(self):
440
- # 1. Build & compile your graph
441
- builder = StateGraph(GaiaAgentState)
442
 
443
- builder.add_node("parse", input_parser)
444
- builder.add_node("planner", planner_node)
445
- builder.add_node("execute", tool_executor)
446
- builder.add_node("synthesize", synthesizer)
447
 
448
- builder.add_edge(START, "parse")
449
- builder.add_edge("parse", "planner")
450
- builder.add_edge("planner", "execute")
451
- builder.add_edge("execute", "synthesize")
452
- builder.add_edge("synthesize", END)
453
- self.graph = builder.compile()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
454
 
455
 
456
 
457
- def run(self, question: str, files=None, level: int = 1) -> str:
458
- """
459
- question: the user’s question string
460
- files: optional list of file paths/URLs (default empty list)
461
- level: GAIA difficulty (1,2,3)
462
- """
463
-
464
- payload = {
465
- "task_id": None,
466
- "question": question,
467
- "files": [],
468
- "level": 1
469
- }
470
- state = GaiaAgentState(raw_payload=payload)
471
- final_state = self.graph.invoke(state)
472
- print(final_state)
473
- # 4) Pull out the final answer
474
- return final_state['final_answer']
475
- # Optional: allow running agent.py directly for quick tests
476
  if __name__ == "__main__":
477
- agent = EsiAgent()
478
- q = "When was a picture of St. Thomas Aquinas first added to the Wikipedia page on the Principle of double effect?"
479
- print("→", agent.run(q))
480
-
481
-
482
-
483
-
484
- # # test
485
- # if __name__ == "__main__":
486
- # question = "When was a picture of St. Thomas Aquinas first added to the Wikipedia page on the Principle of double effect?"
487
- # # Build the graph
488
- # # Run the graph
489
- # messages = [HumanMessage(content=question)]
490
- # messages = graph.invoke({"messages": messages})
491
- # for m in messages["messages"]:
492
- # m.pretty_print()
493
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  BROWSE_PROMPT = """
2
  You are the GAIA Web Query Planner.
3
  Given:
4
  • task: a GAIA question requiring factual lookup
5
  • content: a list of any snippets or context already gathered (may be empty)
 
6
  Your job is to propose 2–3 concise search queries that will help answer the task.
7
  Output **only** a JSON object matching this schema:
8
  ```json
 
11
  """
12
 
13
 
14
+ SYSTEM_PROMT = """You are a helpful assistant tasked with answering questions using a set of tools.
15
+ Now, I will ask you a question. Report your thoughts, and finish your answer with the following template:
16
+ FINAL ANSWER: [YOUR FINAL ANSWER].
17
+ 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 rules above for each element (number or string), ensure there is exactly one space after each comma.
18
+ Your answer should only start with "FINAL ANSWER: ", then follows with the answer. """
 
 
 
 
19
 
20
+ GPT_4o_API_KEY = os.environ["META_LLAMA_4_MAVERICK"]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
21
  # GPT_4o_API_KEY = os.environ["GPT_4o_API_KEY"]
22
  TAVILY_API_KEY = os.environ["TAVILY_API_KEY"]
23
  Pixtral12B_API = os.environ["Pixtral12B_API"]
24
 
 
25
  API_URL = "https://openrouter.ai/api/v1/chat/completions"
 
 
 
 
 
26
  tavily = TavilyClient(api_key=TAVILY_API_KEY)
27
 
28
 
 
 
 
 
 
 
 
 
 
 
 
29
 
30
+ # === TOOL STUBS ===
 
 
31
  @tool
32
+ def python_repl_tool(query: str) -> str:
33
  """
34
+ Execute Python query like calculations; return printed output.
35
+
36
+ Args:
37
+ query: The calculation formula.
38
+
39
+ Returns:
40
+ The result of the code exacuation
41
  """
42
+ python_repl = PythonREPL()
43
+ return python_repl.run(query)
44
 
45
  @tool
46
+ def web_search_with_LLM(query: str) -> List[str]:
47
  """
48
+ Use the LLM model to learn more about the query then
49
+ Search the web for `query`, return top‐3 text snippets.
50
+
51
+ Args:
52
+ query: The search query.
53
+
54
+ Returns:
55
+ A concise details about the query from internet.
56
  """
57
+ model = ChatOpenAI(openai_api_key=GPT_4o_API_KEY,
58
+ base_url="https://openrouter.ai/api/v1",
59
+ # model_name="gpt-4o",
60
+ temperature=0,
61
+ max_tokens=512)
62
  resp = model.invoke([
63
  SystemMessage(content=BROWSE_PROMPT),
64
  HumanMessage(content=json.dumps({"task": query}))
 
73
  #go through the queries we generted and search for them in Tavily
74
  content = []
75
  for q in queries:
76
+ response = tavily.search(query=q, max_results=3)
77
  #append the new content to the old contetnt and return it
78
+ for doc in response['results']:
79
+ print(doc.keys())
80
+ content.append(f'<Document source="{doc["url"]}" confidence score="{doc["score"]}"/>\n{doc["content"]}\n</Document>')
81
+ return {"web_results": content}
82
+
83
+
84
+ @tool
85
+ def web_search(query: str) -> str:
86
+ """Search Tavily for a query and return maximum 3 results.
87
+ Args:
88
+ query: The search query.
89
+ Returns:
90
+ A concise details about the query from internet."""
91
+ # search_docs = TavilySearchResults(max_results=3).invoke(query=query)
92
+ response = tavily.search(query=query, max_results=3)
93
+ content = []
94
+ for doc in response['results']:
95
+ content.append(f'<Document source="{doc["url"]}" confidence score="{doc["score"]}"/>\n{doc["content"]}\n</Document>')
96
+ return {"web_results": formatted_search_docs}
97
 
98
 
99
 
 
101
  # You can choose a smaller or larger BLIP‑2 variant as needed.
102
  MODEL_NAME = "Salesforce/blip2-opt-2.7b"
103
  MODEL_NAME = "Salesforce/blip2-flan-t5-xl" # much smaller, still strong
 
104
  processor = Blip2Processor.from_pretrained(MODEL_NAME)
105
  model_blip2 = Blip2ForConditionalGeneration.from_pretrained(MODEL_NAME).to("cuda" if torch.cuda.is_available() else "cpu")
106
 
107
 
 
 
 
 
 
 
108
  @tool
109
+ def vision_caption_with_LLM(image_path: str, max_length: Optional[int] = 64) -> str:
110
  """
111
  Generate a natural‑language caption for the image at `image_path`.
112
  Args:
 
121
  }
122
 
123
  # Read and encode the image
124
+ with open(image_path, "rb") as image_file:
125
+ base64_image = base64.b64encode(image_file.read()).decode('utf-8')
126
 
127
  messages = [
128
  {
 
163
 
164
 
165
 
 
166
  @tool
167
+ def vision_caption(image_path: str) -> str:
168
  """
169
+ Extract text from an image using OCR library pytesseract (if available).
170
+ Args:
171
+ image_path (str): the path to the image file.
172
+ Returns:
173
+ A concise, human‑readable caption describing the image content.
174
  """
175
+ try:
176
+ # Open the image
177
+ image = Image.open(image_path)
178
+
179
+ # Extract text from the image
180
+ text = pytesseract.image_to_string(image)
181
+
182
+ return f"Extracted text from image:\n\n{text}"
183
+ except Exception as e:
184
+ return f"Error extracting text from image: {str(e)}"
185
+
186
 
187
  @tool
188
+ def wiki_search(query: str) -> str:
189
+ """Search Wikipedia for a query and return maximum 2 results.
190
+
191
+ Args:
192
+ query: The search query.
193
+ Returns:
194
+ Search results about the query from the Wikipedia website
195
+ """
196
+ search_docs = WikipediaLoader(query=query, load_max_docs=2).load()
197
+ formatted_search_docs = "\n\n---\n\n".join(
198
+ [
199
+ f'<Document source="{doc.metadata["source"]}" page="{doc.metadata.get("page", "")}"/>\n{doc.page_content}\n</Document>'
200
+ for doc in search_docs
201
+ ])
202
+ return {"wiki_results": formatted_search_docs}
203
+
204
+
205
+ @tool
206
+ def arvix_search(query: str) -> str:
207
+ """Search Arxiv for a query and return maximum 3 result.
208
+
209
+ Args:
210
+ query: The search query.
211
+ Returns:
212
+ Search results about the query from the Arxiv website
213
+ """
214
+ search_docs = ArxivLoader(query=query, load_max_docs=3).load()
215
+ formatted_search_docs = "\n\n---\n\n".join(
216
+ [
217
+ f'<Document source="{doc.metadata["source"]}" page="{doc.metadata.get("page", "")}"/>\n{doc.page_content[:1000]}\n</Document>'
218
+ for doc in search_docs
219
+ ])
220
+ return {"arvix_results": formatted_search_docs}
221
+
222
+
223
+
224
+ @tool
225
+ def download_file_from_url(url: str, filename: Optional[str] = None) -> str:
226
+ """
227
+ Download a file from a URL and save it to a temporary location.
228
+ Args:
229
+ url (str): the URL of the file to download.
230
+ filename (str, optional): the name of the file. If not provided, a random name file will be created.
231
+ Returns:
232
+ Nothing
233
+ """
234
+ try:
235
+ # Parse URL to get filename if not provided
236
+ if not filename:
237
+ path = urlparse(url).path
238
+ filename = os.path.basename(path)
239
+ if not filename:
240
+ filename = f"downloaded_{uuid.uuid4().hex[:8]}"
241
+
242
+ # Create temporary file
243
+ temp_dir = tempfile.gettempdir()
244
+ filepath = os.path.join(temp_dir, filename)
245
+
246
+ # Download the file
247
+ response = requests.get(url, stream=True)
248
+ response.raise_for_status()
249
+
250
+ # Save the file
251
+ with open(filepath, "wb") as f:
252
+ for chunk in response.iter_content(chunk_size=8192):
253
+ f.write(chunk)
254
+
255
+ return f"File downloaded to {filepath}. You can read this file to process its contents."
256
+ except Exception as e:
257
+ return f"Error downloading file: {str(e)}"
258
+
259
+
260
+
261
+ @tool
262
+ def file_reader_with_LLM(file_path: str) -> str:
263
  """
264
  Sends a PDF or a text file to OpenRouter’s chat API and returns the model’s answer.
265
+
266
+ Args:
267
+ file_path (str): the path to the CSV file.
268
+ Returns:
269
+ The conetent inside the PDF/Text file
270
  """
271
  b64 = base64.b64encode(open(file_path,"rb").read()).decode()
272
  payload = {
 
288
  return line.split(":",1)[1].strip()
289
  return content
290
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
291
 
 
 
 
 
292
 
293
+ @tool
294
+ def file_reader(file_path: str) -> str:
295
+ """
296
+ Analyze a text file using pandas and answer a question about it.
297
+ The file can be any of excel, csv, tsv, xls, json, txt or log.
298
+ Args:
299
+ file_path (str): the path to the CSV file.
300
+ Returns:
301
+ The conetent inside the PDF/Text file
302
+ """
303
+ try:
304
+ _, ext = os.path.splitext(file_path.lower())
305
+ if ext in {".csv", ".tsv"}:
306
+ sep = "\t" if ext == ".tsv" else ","
307
+ data = pd.read_csv(file_path, sep=sep)
308
+ if ext in {".xls", ".xlsx"}:
309
+ data = pd.read_excel(file_path)
310
+ if ext == ".json":
311
+ data = pd.read_json(file_path)
312
+ if ext in {".txt", ".log"}:
313
+ with open(file_path, "r", encoding="utf-8") as f:
314
+ data = f.read()
315
+
316
+ # Run various analyses based on the query
317
+ result = f"text file loaded with {len(data)} rows and {len(data.columns)} columns.\n"
318
+ result += f"Columns: {', '.join(data.columns)}\n\n"+\
319
+ "Summary statistics:\n" + str(data.describe())
320
+ # Add summary statistics
321
+ return result
322
+
323
+ except Exception as e:
324
+ return f"Error analyzing text file: {str(e)}"
325
+
326
+
327
+ tools = [python_repl_tool,
328
+ web_search_with_LLM,
329
+ web_search,
330
+ vision_caption,
331
+ vision_caption_with_LLM,
332
+ arvix_search,
333
+ wiki_search,
334
+ download_file_from_url,
335
+ file_reader_with_LLM,
336
+ file_reader]
337
+
338
+ # Build graph function
339
+ def EsiAgent(provider: str = "groq"):
340
+ """Build the graph"""
341
+
342
+ llm = ChatOpenAI(openai_api_key=GPT_4o_API_KEY,
343
+ base_url="https://openrouter.ai/api/v1",
344
+ # model_name="gpt-4o",
345
+ # model_name="gpt-3.5-turbo",
346
+ temperature=0,
347
+ max_tokens=256)
348
+ # Bind tools to LLM
349
+ llm_with_tools = llm.bind_tools(tools)
350
+
351
+ # System message
352
+ sys_msg = SystemMessage(content=SYSTEM_PROMT)
353
+
354
+ def assistant(state: MessagesState):
355
+ """Assistant node"""
356
+ msgs = [llm_with_tools.invoke(state["messages"])]
357
+ if not any(isinstance(m, SystemMessage) for m in msgs):
358
+ msgs = [sys_msg] + msgs
359
+ return {"messages": msgs}
360
+
361
+ builder = StateGraph(MessagesState)
362
+ builder.add_node("assistant", assistant)
363
+ builder.add_node("tools", ToolNode(tools))
364
+ builder.add_edge(START, "assistant")
365
+ builder.add_conditional_edges(
366
+ "assistant",
367
+ tools_condition,
368
+ )
369
+ builder.add_edge("tools", "assistant")
370
+
371
+ # Compile graph
372
+ return builder.compile()
373
 
374
 
375
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
376
  if __name__ == "__main__":
377
+ # question = "Where is the capital of the Iran?"
378
+ graph = EsiAgent(provider="groq")
379
+ messages = [HumanMessage(content=question)]
380
+ messages = graph.invoke({"messages": messages})
381
+ for m in messages["messages"]:
382
+ m.pretty_print()