giqua commited on
Commit
c0d4b53
·
verified ·
1 Parent(s): 81917a3

Implementation multimodal agent with tools

Browse files
Files changed (5) hide show
  1. agent.py +139 -0
  2. app.py +50 -25
  3. requirements.txt +14 -1
  4. tools.py +412 -0
  5. utils.py +12 -0
agent.py ADDED
@@ -0,0 +1,139 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ from langchain_core.messages import HumanMessage
3
+ from langchain_core.runnables.config import RunnableConfig
4
+ from langgraph.checkpoint.memory import MemorySaver
5
+ from langchain.globals import set_debug
6
+ from langchain.globals import set_verbose
7
+ from langgraph.prebuilt import create_react_agent
8
+ from langgraph.prebuilt import ToolNode
9
+ from langgraph.prebuilt.chat_agent_executor import AgentState
10
+
11
+ from smolagents import DuckDuckGoSearchTool
12
+ from smolagents import PythonInterpreterTool
13
+ from tools import analyze_audio
14
+ from tools import analyze_excel
15
+ from tools import analyze_image
16
+ from tools import analyze_video
17
+ from tools import download_file_for_task
18
+ from tools import read_file_contents
19
+ from tools import search_arxiv
20
+ from tools import search_tavily
21
+ from tools import search_wikipedia
22
+ from tools import SmolagentToolWrapper
23
+ from tools import tavily_extract_tool
24
+ from utils import get_llm
25
+
26
+
27
+ GOOGLE_API_KEY = os.getenv("GOOGLE_API_KEY", "")
28
+ if not GOOGLE_API_KEY:
29
+ raise ValueError("GOOGLE_API_KEY environment variable is not set.")
30
+
31
+ AGENT_MODEL_NAME = os.getenv("AGENT_MODEL_NAME", "gemini-2.0-flash")
32
+
33
+ DEFAULT_GAIA_AGENT_PROMPT = """
34
+ You are an intelligent AI assistant that is able to solve complex, real-world tasks.
35
+ Abide by the following principles:
36
+ - Think step-by-step.
37
+ - Be concise. The final answer *must* stricly match the required format with nothing else. Your answer should be a number or as few words as possible or a comma separated list of numbers and/or strings. Do not abbreviate, do not use units or complete sentences. If returning a number, don't use commas, measurement units or currency symbols.
38
+ - Use tools. If a question involves external information, structured data, images, or audio, call the appropriate tool to retrieve or process it. Please pass the question verbatim when calling a tool.
39
+ - No guessing. If you don't know, say you don't know. Always exhaust your list of tools.
40
+ - Use code if necessary. For calculations, parsing, or transformations, generate Python code and execute it.
41
+ - Never submit logic leading up to your answer - just the answer. Don't use complete sentences.
42
+ - Please include the descriptive terms in your solution as indicated in the question.
43
+ - Always return the answer to the question prefixed with 'FINAL ANSWER: '"
44
+ - If the question ask to count something, return only the number of items, don't add any words.
45
+ - If the question ask to list something, return only the list of items, don't add any words.
46
+ - If the question ask to sort something, return only the sorted list of items, don't add any words.
47
+ Examples
48
+ QUESTION: How much is a hamburger in USD? ANSWER: 4.99
49
+ QUESTION: Put fresh fruit, apple, and fresh apple in alphabetical order. ANSWER: apple, fresh apple, fresh fruit
50
+ QUESTION: What city is known as the 'Gateway to the West'? ANSWER: Saint Louis
51
+ QUESTION: How many faces are there on Mount Rushmore? ANSWER: 4
52
+ QUESTION: How would you respond to 'Is it hot or cold?'? ANSWER: Hot
53
+ QUESTION: What pages did the first chapter of the book have? ANSWER: 1, 2, 3
54
+ QUESTION: Who sang the song 'I Will Always Love You'? ANSWER: Whitney Houston
55
+ """
56
+
57
+ set_debug(True)
58
+ set_verbose(True)
59
+
60
+
61
+ class State(AgentState):
62
+ task_id: str
63
+ question: str
64
+ file_name: str
65
+
66
+
67
+ class MultiModalAgent:
68
+ def __init__(self, model_name: str | None = None):
69
+ if model_name is None:
70
+ model_name = AGENT_MODEL_NAME
71
+ llm = self._get_llm(model_name)
72
+ tools = self._get_tools()
73
+ self.agent = create_react_agent(
74
+ llm,
75
+ tools=tools,
76
+ state_schema=State,
77
+ state_modifier=DEFAULT_GAIA_AGENT_PROMPT,
78
+ checkpointer = MemorySaver()
79
+ )
80
+
81
+ def _get_llm(self, model_name: str):
82
+ return get_llm(
83
+ llm_provider_api_key=GOOGLE_API_KEY,
84
+ model_name=model_name,
85
+ )
86
+
87
+ def _get_tools(self):
88
+ tools = [
89
+ SmolagentToolWrapper(DuckDuckGoSearchTool()),
90
+ SmolagentToolWrapper(PythonInterpreterTool()),
91
+ download_file_for_task,
92
+ read_file_contents,
93
+ analyze_audio,
94
+ analyze_image,
95
+ analyze_excel,
96
+ analyze_video,
97
+ search_arxiv,
98
+ search_tavily,
99
+ search_wikipedia,
100
+ tavily_extract_tool,
101
+ ]
102
+ return ToolNode(tools)
103
+
104
+ async def __call__(
105
+ self, task_id: str, question: str, file_name: str | None = None
106
+ ) -> str:
107
+
108
+ config = RunnableConfig(
109
+ recursion_limit=64,
110
+ configurable={ "thread_id": task_id }
111
+ )
112
+
113
+ if not file_name:
114
+ file_name = "None - no file present"
115
+
116
+ message = HumanMessage(
117
+ content=
118
+ [
119
+ {
120
+ "type": "text",
121
+ "text": f"Task Id: {task_id}, Question: {question}, Filename: {file_name}. If a filename is present (and is not 'None'), download the file for the task that's referenced in the question. If there isn't a filename present, please use tools where applicable."
122
+ }
123
+ ]
124
+ )
125
+
126
+ answer = await self.agent.ainvoke(
127
+ {
128
+ "messages": [message],
129
+ "question": question,
130
+ "task_id": task_id,
131
+ "file_name": file_name
132
+ }, config)
133
+
134
+ final_answer = answer['messages'][-1].content
135
+ if "FINAL ANSWER: " in final_answer:
136
+ return final_answer.split("FINAL ANSWER: ", 1)[1].strip()
137
+ else:
138
+ return final_answer
139
+
app.py CHANGED
@@ -1,23 +1,34 @@
 
1
  import os
2
  import gradio as gr
3
  import requests
4
- import inspect
5
  import pandas as pd
 
6
 
7
  # (Keep Constants as is)
8
  # --- Constants ---
9
  DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
10
 
11
- # --- Basic Agent Definition ---
12
- # ----- THIS IS WERE YOU CAN BUILD WHAT YOU WANT ------
13
- class BasicAgent:
14
- def __init__(self):
15
- print("BasicAgent initialized.")
16
- def __call__(self, question: str) -> str:
17
- print(f"Agent received question (first 50 chars): {question[:50]}...")
18
- fixed_answer = "This is a default answer."
19
- print(f"Agent returning fixed answer: {fixed_answer}")
20
- return fixed_answer
 
 
 
 
 
 
 
 
 
 
21
 
22
  def run_and_submit_all( profile: gr.OAuthProfile | None):
23
  """
@@ -40,7 +51,7 @@ def run_and_submit_all( profile: gr.OAuthProfile | None):
40
 
41
  # 1. Instantiate Agent ( modify this part to create your agent)
42
  try:
43
- agent = BasicAgent()
44
  except Exception as e:
45
  print(f"Error instantiating agent: {e}")
46
  return f"Error initializing agent: {e}", None
@@ -69,23 +80,37 @@ def run_and_submit_all( profile: gr.OAuthProfile | None):
69
  print(f"An unexpected error occurred fetching questions: {e}")
70
  return f"An unexpected error occurred fetching questions: {e}", None
71
 
 
 
 
 
 
 
 
 
72
  # 3. Run your Agent
73
  results_log = []
74
  answers_payload = []
75
  print(f"Running agent on {len(questions_data)} questions...")
76
- for item in questions_data:
77
- task_id = item.get("task_id")
78
- question_text = item.get("question")
79
- if not task_id or question_text is None:
80
- print(f"Skipping item with missing task_id or question: {item}")
81
- continue
82
- try:
83
- submitted_answer = agent(question_text)
84
- answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
85
- results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})
86
- except Exception as e:
87
- print(f"Error running agent on task {task_id}: {e}")
88
- results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": f"AGENT ERROR: {e}"})
 
 
 
 
 
 
89
 
90
  if not answers_payload:
91
  print("Agent did not produce any answers to submit.")
 
1
+ import asyncio
2
  import os
3
  import gradio as gr
4
  import requests
 
5
  import pandas as pd
6
+ from agent import MultiModalAgent
7
 
8
  # (Keep Constants as is)
9
  # --- Constants ---
10
  DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
11
 
12
+ async def run_agent(
13
+ agt: MultiModalAgent,
14
+ item: dict
15
+ ) -> str | None:
16
+ task_id = item.get("task_id")
17
+ question_text = item.get("question")
18
+ file_name = item.get("file_name", None)
19
+
20
+ if not task_id or question_text is None:
21
+ print(f"Skipping item with missing task_id or question: {item}")
22
+ return None
23
+
24
+ submitted_answer = await agt(task_id, question_text, file_name)
25
+
26
+ return {
27
+ "task_id": task_id,
28
+ "question": question_text,
29
+ "submitted_answer": submitted_answer
30
+ }
31
+
32
 
33
  def run_and_submit_all( profile: gr.OAuthProfile | None):
34
  """
 
51
 
52
  # 1. Instantiate Agent ( modify this part to create your agent)
53
  try:
54
+ agent = MultiModalAgent()
55
  except Exception as e:
56
  print(f"Error instantiating agent: {e}")
57
  return f"Error initializing agent: {e}", None
 
80
  print(f"An unexpected error occurred fetching questions: {e}")
81
  return f"An unexpected error occurred fetching questions: {e}", None
82
 
83
+ try:
84
+ #see if there is a loop already running. If there is, reuse it.
85
+ loop = asyncio.get_running_loop()
86
+ except RuntimeError:
87
+ # Create new event loop if one is not running
88
+ loop = asyncio.new_event_loop()
89
+ asyncio.set_event_loop(loop)
90
+
91
  # 3. Run your Agent
92
  results_log = []
93
  answers_payload = []
94
  print(f"Running agent on {len(questions_data)} questions...")
95
+
96
+ try:
97
+ results = loop.run_until_complete(
98
+ asyncio.gather(*(run_agent(agent, item) for item in questions_data))
99
+ )
100
+ answers_payload = [{key: value for key, value in item.items() if key != "question"}
101
+ for item in results]
102
+
103
+ for item in results:
104
+ results_log.append(
105
+ {
106
+ "Task ID": item['task_id'],
107
+ "Question": item['question'],
108
+ "Submitted Answer": item['submitted_answer']
109
+ }
110
+ )
111
+ finally:
112
+ # Clean up
113
+ loop.close()
114
 
115
  if not answers_payload:
116
  print("Agent did not produce any answers to submit.")
requirements.txt CHANGED
@@ -1,2 +1,15 @@
 
 
 
1
  gradio
2
- requests
 
 
 
 
 
 
 
 
 
 
 
1
+ asyncer
2
+ anyio
3
+ arxiv
4
  gradio
5
+ httpx
6
+ requests
7
+ langgraph
8
+ langchain-google-genai
9
+ langchain-community
10
+ langchain-tavily
11
+ openpyxl
12
+ smolagents
13
+ tavily-python
14
+ wikipedia-api
15
+ wikipedia
tools.py ADDED
@@ -0,0 +1,412 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import dotenv
3
+ import pandas as pd
4
+ import tempfile
5
+ import typing
6
+
7
+ from base64 import b64encode
8
+ from io import StringIO
9
+
10
+ import httpx
11
+
12
+ from anyio import Path
13
+ from asyncer import asyncify
14
+ from langchain_community.document_loaders import ArxivLoader
15
+ from langchain_community.document_loaders import WikipediaLoader
16
+ from langchain_core.messages import HumanMessage
17
+ from langchain_tavily import TavilyExtract
18
+ from langchain_tavily import TavilySearch
19
+ from langgraph.prebuilt import create_react_agent
20
+ from langgraph.prebuilt import InjectedState
21
+ from langchain.tools import BaseTool
22
+ from langchain.tools import tool
23
+ from pydantic import Field
24
+ from typing_extensions import Annotated
25
+
26
+ from utils import get_llm
27
+
28
+ dotenv.load_dotenv()
29
+ GOOGLE_API_KEY = os.getenv("GOOGLE_API_KEY", "")
30
+ if not GOOGLE_API_KEY:
31
+ raise ValueError("GOOGLE_API_KEY environment variable is not set.")
32
+
33
+ AGENT_MODEL_NAME = os.getenv("AGENT_MODEL_NAME", "gemini-2.0-flash")
34
+
35
+ DEFAULT_AGENT_PROMPT = """
36
+ You are a intelligent AI assistant that is able to solve complex, real-world
37
+ tasks. You are able to analyze images, videos, and excel files.
38
+ Abide by the following principles:
39
+ - Think step-by-step.
40
+ - Be concise. The final answer *must* stricly match the required format with nothing else. Your answer should be a number or as few words as possible or a comma separated list of numbers and/or strings. Do not abbreviate, do not use units or complete sentences. If returning a number, don't use commas, measurement units or currency symbols.
41
+ - No guessing. If you don't know, say you don't know.
42
+ - Please include the descriptive terms in your solution as indicated in the question.
43
+ - Always return the answer to the question prefixed with 'FINAL ANSWER: '"
44
+ Examples:
45
+ QUESTION: How much is a hamburger in USD? ANSWER: 4.99
46
+ QUESTION: Put fresh fruit, apple, and fresh apple in alphabetical order. ANSWER: apple, fresh apple, fresh fruit
47
+ QUESTION: What city is known as the 'Gateway to the West'? ANSWER: Saint Louis
48
+ QUESTION: How many faces are there on Mount Rushmore? ANSWER: 4
49
+ QUESTION: How would you respond to 'Is it hot or cold?'? ANSWER: Hot
50
+ QUESTION: What pages did the first chapter of the book have? ANSWER: 1, 2, 3
51
+ """
52
+
53
+
54
+ class SmolagentToolWrapper(BaseTool):
55
+ """Smol wrapper to allow Langchain/Graph to leverage smolagents tools"""
56
+
57
+ wrapped_tool: object = Field(description="Smolagents tool (wrapped)")
58
+
59
+ def __init__(self, tool):
60
+ super().__init__(
61
+ name=tool.name,
62
+ description=tool.description,
63
+ return_direct=False,
64
+ wrapped_tool=tool,
65
+ )
66
+
67
+ def _run(self, query: str) -> str:
68
+ try:
69
+ return self.wrapped_tool(query)
70
+ except Exception as e:
71
+ return f"Error using SmolagentToolWrapper: {str(e)}"
72
+
73
+ def _arun(self, *args: typing.Any, **kwargs: typing.Any) -> typing.Any:
74
+ """Async version of the tool"""
75
+ return asyncify(self._run, cancellable=True)(*args, **kwargs)
76
+
77
+
78
+ tavily_extract_tool = TavilyExtract()
79
+
80
+
81
+ @tool("search-tavily-tool", parse_docstring=True)
82
+ async def search_tavily(
83
+ query: str,
84
+ state: Annotated[dict, InjectedState],
85
+ included_domains: list[str] = None,
86
+ max_results: int = 5,
87
+ ) -> dict[str, str]:
88
+ """
89
+ Search the web using Tavily API with optional domain filtering.
90
+
91
+ This function performs a search using the Tavily search engine and returns formatted results.
92
+ You can specify domains to include in the search results for more targeted information.
93
+
94
+ Args:
95
+ query (str): The search query to search the web for
96
+ included_domains (list[str], optional): List of domains to include in search results
97
+ (e.g., ["wikipedia.org", "cnn.com"]). Defaults to None.
98
+ max_results (int, optional): Maximum number of results to return. Defaults to 5.
99
+
100
+ Returns:
101
+ dict[str, str]: A dictionary with key 'tavily_results' containing formatted search results.
102
+ Each result includes document source, page information, and content.
103
+
104
+ Example:
105
+ results = await search_tavily("How many albums did Michael Jackson produce", included_domains=[], topic="general")
106
+ # Returns filtered results about Michael Jackson
107
+ """
108
+ # Configure Tavily search with provided parameters
109
+ tavily_search_tool = TavilySearch(
110
+ max_results=max_results,
111
+ topic="general",
112
+ include_domains=included_domains if included_domains else None,
113
+ search_depth="advanced",
114
+ include_answer="advanced",
115
+ )
116
+
117
+ # Execute search
118
+ search_docs = await tavily_search_tool.arun(state["question"])
119
+
120
+ # Format results
121
+ formatted_search_docs = "\n\n---\n\n".join(
122
+ [
123
+ f'<Document source="{doc.get("url", "No URL")}"/>{doc.get("title", "No Title")}\n{doc.get("content", "")}\n</Document>'
124
+ for doc in search_docs.get("results", [])
125
+ ]
126
+ )
127
+
128
+ results = {"tavily_results": formatted_search_docs}
129
+
130
+ answer = search_docs.get("answer", None)
131
+
132
+ if answer:
133
+ results["tavily_answer"] = answer
134
+
135
+ return results
136
+
137
+
138
+ @tool("search-arxiv-tool", parse_docstring=True)
139
+ async def search_arxiv(query: str, max_num_result: int = 5) -> dict[str, str]:
140
+ """
141
+ Search arXiv for academic papers matching the provided query.
142
+ This function queries the arXiv database for scholarly articles related to the
143
+ search query and returns a formatted collection of the results.
144
+
145
+ Args:
146
+ query (str): The search query to find relevant academic papers.
147
+ max_num_result (int, optional): Maximum number of results to return. Defaults to 5.
148
+
149
+ Returns:
150
+ dict[str, str]: A dictionary with key 'arxiv_results' containing formatted search results.
151
+ Each result includes document source, page information, and content.
152
+
153
+ Example:
154
+ results = await search_arxiv("quantum computing", 3)
155
+ # Returns dictionary with up to 3 formatted arXiv papers about quantum computing
156
+ """
157
+ search_docs = await ArxivLoader(query=query, load_max_docs=max_num_result).aload()
158
+ formatted_search_docs = "\n\n---\n\n".join(
159
+ [
160
+ f'<Document source="{doc.metadata["source"]}" page="{doc.metadata.get("page", "")}"/>\n{doc.page_content}\n</Document>'
161
+ for doc in search_docs
162
+ ]
163
+ )
164
+ return {"arvix_results": formatted_search_docs}
165
+
166
+
167
+ @tool("search-wikipedia-tool", parse_docstring=True)
168
+ async def search_wikipedia(query: str, max_num_result: int = 5) -> dict[str, str]:
169
+ """
170
+ Search Wikipedia for articles matching the provided query.
171
+ This function queries the Wikipedia database for articles related to the
172
+ search term and returns a formatted collection of the results.
173
+
174
+ Args:
175
+ query (str): The search query to find relevant Wikipedia articles.
176
+ max_num_result (int, optional): Maximum number of results to return. Defaults to 5.
177
+
178
+ Returns:
179
+ dict[str, str]: A dictionary with key 'wikipedia_results' containing formatted search results.
180
+ Each result includes document source, page information, and content.
181
+
182
+ Example:
183
+ results = await search_wikipedia("neural networks", 3)
184
+ # Returns dictionary with up to 3 formatted Wikipedia articles about neural networks
185
+ """
186
+ search_docs = await WikipediaLoader(
187
+ query=query,
188
+ load_max_docs=max_num_result,
189
+ load_all_available_meta=True,
190
+ doc_content_chars_max=128000,
191
+ ).aload()
192
+
193
+ print(search_docs)
194
+
195
+ formatted_search_docs = "\n\n---\n\n".join(
196
+ [
197
+ f'<Document source="{doc.metadata["source"]}" page="{doc.metadata.get("page", "")}"/>\n{doc.page_content}\n</Document>'
198
+ for doc in search_docs
199
+ ]
200
+ )
201
+ return {"wikipedia_results": formatted_search_docs}
202
+
203
+
204
+ @tool("download-file-for-task-tool", parse_docstring=True)
205
+ async def download_file_for_task(task_id: str, filename: str | None = None) -> str:
206
+ """
207
+ Download a file for task_id, save to a temporary file, and return path
208
+
209
+ Args:
210
+ task_id: The task id file to download
211
+ filename: Optional filename (will be generated if not provided)
212
+
213
+ Returns:
214
+ String path to the downloaded file
215
+ """
216
+ if filename is None:
217
+ filename = task_id
218
+
219
+ temp_dir = Path(tempfile.gettempdir())
220
+ filepath = temp_dir / filename
221
+
222
+ url = f"https://agents-course-unit4-scoring.hf.space/files/{task_id}"
223
+ async with httpx.AsyncClient() as client:
224
+ async with client.stream("GET", url) as response:
225
+ response.raise_for_status()
226
+ async with await filepath.open("wb") as f:
227
+ async for chunk in response.aiter_bytes(chunk_size=4096):
228
+ await f.write(chunk)
229
+
230
+ return str(filepath)
231
+
232
+
233
+ @tool("read-file-contents-tool", parse_docstring=True)
234
+ async def read_file_contents(file_path: str) -> str:
235
+ """
236
+ Read a file and return its contents
237
+
238
+ Args:
239
+ file_path: String path to file to read
240
+
241
+ Returns:
242
+ Contents of the file at file_path
243
+ """
244
+ path = Path(file_path)
245
+ return await path.read_text()
246
+
247
+
248
+ @tool("analyze-image-tool", parse_docstring=True)
249
+ async def analyze_image(state: Annotated[dict, InjectedState], image_path: str) -> str:
250
+ """
251
+ Analyze the image at image_path
252
+
253
+ Args:
254
+ image_path: String path where the image file is located on disk
255
+
256
+ Returns:
257
+ Answer to the question about the image file
258
+ """
259
+ path = Path(image_path)
260
+ async with await path.open("rb") as rb:
261
+ img_base64 = b64encode(await rb.read()).decode("utf-8")
262
+
263
+ llm = get_llm(
264
+ llm_provider_api_key=GOOGLE_API_KEY,
265
+ model_name=AGENT_MODEL_NAME,
266
+ )
267
+
268
+ file_agent = create_react_agent(
269
+ llm,
270
+ tools=[],
271
+ state_modifier=DEFAULT_AGENT_PROMPT,
272
+ )
273
+
274
+ message = HumanMessage(
275
+ content=[
276
+ {"type": "text", "text": state["question"]},
277
+ {
278
+ "type": "image",
279
+ "source_type": "base64",
280
+ "mime_type": "image/png",
281
+ "data": img_base64,
282
+ },
283
+ ]
284
+ )
285
+
286
+ messages = await file_agent.ainvoke({"messages": [message]})
287
+ return messages["messages"][-1].content
288
+
289
+
290
+ @tool("analyze-excel-tool", parse_docstring=True)
291
+ async def analyze_excel(state: Annotated[dict, InjectedState], excel_path: str) -> str:
292
+ """
293
+ Analyze the excel file at excel_path
294
+
295
+ Args:
296
+ excel_path: String path where the excel file is located on disk
297
+
298
+ Returns:
299
+ Answer to the question about the excel file
300
+ """
301
+
302
+ df = pd.read_excel(excel_path)
303
+
304
+ csv_buffer = StringIO()
305
+ df.to_csv(csv_buffer, index=False)
306
+
307
+ csv_contents = csv_buffer.getvalue()
308
+ csv_contents_bytes = csv_contents.encode("utf-8")
309
+ csv_contents_base64 = b64encode(csv_contents_bytes).decode("utf-8")
310
+
311
+ llm = get_llm(
312
+ llm_provider_api_key=GOOGLE_API_KEY,
313
+ model_name=AGENT_MODEL_NAME,
314
+ )
315
+
316
+ file_agent = create_react_agent(
317
+ llm,
318
+ tools=[],
319
+ state_modifier=DEFAULT_AGENT_PROMPT,
320
+ )
321
+
322
+ message = HumanMessage(
323
+ content=[
324
+ {"type": "text", "text": state["question"]},
325
+ {
326
+ "type": "file",
327
+ "source_type": "base64",
328
+ "mime_type": "text/csv",
329
+ "data": csv_contents_base64,
330
+ },
331
+ ],
332
+ )
333
+
334
+ messages = await file_agent.ainvoke({"messages": [message]})
335
+ return messages["messages"][-1].content
336
+
337
+
338
+ @tool("analyze-audio-tool", parse_docstring=True)
339
+ async def analyze_audio(state: Annotated[dict, InjectedState], audio_path: str) -> str:
340
+ """
341
+ Analyze the audio at audio_path
342
+
343
+ Args:
344
+ audio_path: String path where the audio file is located on disk
345
+
346
+ Returns:
347
+ Answer to the question about the audio file
348
+ """
349
+ audio_mime_type = "audio/mpeg"
350
+
351
+ path = Path(audio_path)
352
+
353
+ async with await path.open("rb") as rb:
354
+ encoded_audio = b64encode(await rb.read()).decode("utf-8")
355
+
356
+ llm = get_llm(
357
+ llm_provider_api_key=GOOGLE_API_KEY,
358
+ model_name=AGENT_MODEL_NAME,
359
+ )
360
+
361
+ file_agent = create_react_agent(
362
+ llm,
363
+ tools=[],
364
+ state_modifier=DEFAULT_AGENT_PROMPT,
365
+ )
366
+
367
+ message = HumanMessage(
368
+ content=[
369
+ {"type": "text", "text": state["question"]},
370
+ {"type": "media", "data": encoded_audio, "mime_type": audio_mime_type},
371
+ ],
372
+ )
373
+
374
+ messages = await file_agent.ainvoke({"messages": [message]})
375
+ return messages["messages"][-1].content
376
+
377
+
378
+ @tool("analyze-video-tool", parse_docstring=True)
379
+ async def analyze_video(state: Annotated[dict, InjectedState], video_url: str) -> str:
380
+ """
381
+ Analyze the video at video_url
382
+
383
+ Args:
384
+ video_url: URL where the video is located
385
+
386
+ Returns:
387
+ Answer to the question about the video url
388
+ """
389
+ llm = get_llm(
390
+ llm_provider_api_key=GOOGLE_API_KEY,
391
+ model_name=AGENT_MODEL_NAME,
392
+ )
393
+
394
+ file_agent = create_react_agent(
395
+ llm,
396
+ tools=[],
397
+ state_modifier=DEFAULT_AGENT_PROMPT,
398
+ )
399
+
400
+ message = HumanMessage(
401
+ content=[
402
+ {"type": "text", "text": state["question"]},
403
+ {
404
+ "type": "media",
405
+ "mime_type": "video/mp4",
406
+ "file_uri": video_url,
407
+ },
408
+ ],
409
+ )
410
+
411
+ messages = await file_agent.ainvoke({"messages": [message]})
412
+ return messages["messages"][-1].content
utils.py ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from langchain_google_genai import ChatGoogleGenerativeAI
2
+
3
+
4
+ def get_llm(
5
+ llm_provider_api_key: str,
6
+ model_name: str = "gemini-2.0-flash",
7
+ ):
8
+ return ChatGoogleGenerativeAI(
9
+ google_api_key=llm_provider_api_key,
10
+ temperature=0.7,
11
+ max_retries=5,
12
+ model=model_name)