ignatiev commited on
Commit
7e9feed
·
1 Parent(s): 17e7acf

fix: add multi modal inputs

Browse files
Files changed (3) hide show
  1. agents/web_search_tool.py +27 -0
  2. app.py +89 -12
  3. requirements.txt +3 -1
agents/web_search_tool.py CHANGED
@@ -1,6 +1,7 @@
1
  import os
2
  import requests
3
  from smolagents import tool
 
4
 
5
  @tool
6
  def search_in_google(query: str) -> str:
@@ -28,3 +29,29 @@ def search_in_google(query: str) -> str:
28
  processed_results.append(f"Title: {title}\nLink: {link}\nSnippet: {snippet}\n")
29
 
30
  return "\n".join(processed_results)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  import os
2
  import requests
3
  from smolagents import tool
4
+ import arxiv
5
 
6
  @tool
7
  def search_in_google(query: str) -> str:
 
29
  processed_results.append(f"Title: {title}\nLink: {link}\nSnippet: {snippet}\n")
30
 
31
  return "\n".join(processed_results)
32
+
33
+ @tool
34
+ def search_in_arxiv(query: str) -> str:
35
+ """
36
+ Perform a search in arXiv for research articles using the provided query and return the first result.
37
+
38
+ Args:
39
+ query (str): The search query to perform a web search on arXiv.
40
+ """
41
+
42
+ search = arxiv.Search(
43
+ query=query,
44
+ max_results=10,
45
+ sort_by=arxiv.SortCriterion.SubmittedDate,
46
+ sort_order=arxiv.SortOrder.Descending,
47
+ )
48
+
49
+ results = list(search.results())
50
+
51
+ processed_results = []
52
+
53
+ # Display metadata and summaries
54
+ for doc in results:
55
+ processed_results.append(f"Title: {doc.title}\nSummary: {doc.summary}\nLink: {doc.entry_id}\n")
56
+
57
+ return "\n".join(processed_results)
app.py CHANGED
@@ -3,6 +3,8 @@ import gradio as gr
3
  import requests
4
  import json
5
  import tempfile
 
 
6
 
7
  from smolagents import (
8
  ToolCallingAgent,
@@ -11,7 +13,7 @@ from smolagents import (
11
  VisitWebpageTool,
12
  OpenAIServerModel,
13
  )
14
- from agents.web_search_tool import search_in_google
15
 
16
  import pandas as pd
17
 
@@ -26,6 +28,8 @@ class BasicAgent:
26
  def __init__(self):
27
  print("BasicAgent initialized.")
28
  HF_TOKEN = os.getenv("HF_TOKEN")
 
 
29
 
30
  self._manager_model = OpenAIServerModel(
31
  model_id="gpt-4o",
@@ -44,24 +48,37 @@ class BasicAgent:
44
  )
45
 
46
  self._web_search_agent = ToolCallingAgent(
47
- tools=[search_in_google, VisitWebpageTool()],
48
  name="web_search_and_knowledge_expert_agent",
49
- description="An agent who answers questions with recent information from Internet and web search.",
 
 
 
 
 
 
 
 
 
50
  model=self._web_search_model,
51
  max_steps=5,
52
  )
53
 
54
  self._coder_expert_agent = CodeAgent(
55
- tools=[],
56
  name="coder_expert_agent",
57
  description=(
58
  "An agent who can provide precise answers by generating and executing Python code."
59
- "This agent allowed:"
60
  "\n"
61
  "- call public API with requests module"
62
  "\n"
63
  "- get YouTube video transcripts with youtube_transcript_api module, only is subtitles are available"
64
  "\n"
 
 
 
 
65
  ),
66
  additional_authorized_imports=[
67
  "json",
@@ -81,6 +98,8 @@ class BasicAgent:
81
  "queue",
82
  "bs4",
83
  "pandas",
 
 
84
  ],
85
  model=self._coder_model,
86
  max_steps=5,
@@ -92,25 +111,77 @@ class BasicAgent:
92
  description=(
93
  "An agent who can provide answers on questions by planning and delegating concrete tasks to more specific agents."
94
  "Follow principles:"
 
 
 
95
  "\n"
96
  "- Plan all needed steps which need extractions from external resources in priority, so all following steps have needed information."
97
  "\n"
98
- "- Skip tasks and questions with obligation to recognize video, audio, or image content. Answer with 'Not possible yet'."
99
  "\n"
100
  "- Skip tasks and questions with obligation to verify information manually. Answer with 'Not possible yet'."
101
  ),
102
  model=self._manager_model,
103
  add_base_tools=True,
104
- max_steps=15,
105
  managed_agents=[self._web_search_agent, self._coder_expert_agent],
106
  )
107
 
108
- def __call__(self, question: str, file_name: str) -> str:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
109
  print(f"Agent received question (first 50 chars): {question[:50]}...")
 
 
 
 
 
 
 
 
 
110
 
111
  answer = self._expert_agent.run(
112
- f"Respond precisely to the question by planning and delegating concrete tasks to available specific agents. User question: {question}. If file_name is provided, open it and use it to answer the question.",
113
- additional_args={"user_question": question, "file_name": file_name},
114
  )
115
 
116
  return answer
@@ -186,12 +257,18 @@ def run_and_submit_all( profile: gr.OAuthProfile | None):
186
  for item in questions_data:
187
  task_id = item.get("task_id")
188
  question_text = item.get("question")
189
- file_name = temp_dir + "/" + item.get("file_name")
 
 
 
 
 
 
190
  if not task_id or question_text is None:
191
  print(f"Skipping item with missing task_id or question: {item}")
192
  continue
193
  try:
194
- submitted_answer = agent(question_text, file_name)
195
  answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
196
  results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})
197
  except Exception as e:
 
3
  import requests
4
  import json
5
  import tempfile
6
+ import base64
7
+ from openai import OpenAI
8
 
9
  from smolagents import (
10
  ToolCallingAgent,
 
13
  VisitWebpageTool,
14
  OpenAIServerModel,
15
  )
16
+ from agents.web_search_tool import search_in_google, search_in_arxiv
17
 
18
  import pandas as pd
19
 
 
28
  def __init__(self):
29
  print("BasicAgent initialized.")
30
  HF_TOKEN = os.getenv("HF_TOKEN")
31
+
32
+ self._open_ai_client = OpenAI(api_key=os.environ.get("OPENAI_API_KEY"))
33
 
34
  self._manager_model = OpenAIServerModel(
35
  model_id="gpt-4o",
 
48
  )
49
 
50
  self._web_search_agent = ToolCallingAgent(
51
+ tools=[search_in_google, search_in_arxiv, VisitWebpageTool()],
52
  name="web_search_and_knowledge_expert_agent",
53
+ description=(
54
+ "An agent who answers questions with recent information from Internet and web search. This agent uses Llama-3.3-70B model and allows:"
55
+ "\n"
56
+ "- Search in Web with Google Custom Search API"
57
+ "\n"
58
+ "- Visit Webpage and extract information from it"
59
+ "\n"
60
+ "- skip any solutions which could require manual steps or downloading files and return 'Not possible yet'"
61
+ "\n"
62
+ ),
63
  model=self._web_search_model,
64
  max_steps=5,
65
  )
66
 
67
  self._coder_expert_agent = CodeAgent(
68
+ tools=[VisitWebpageTool()],
69
  name="coder_expert_agent",
70
  description=(
71
  "An agent who can provide precise answers by generating and executing Python code."
72
+ "This agent uses Qwen2.5-Coder-32B model and allows:"
73
  "\n"
74
  "- call public API with requests module"
75
  "\n"
76
  "- get YouTube video transcripts with youtube_transcript_api module, only is subtitles are available"
77
  "\n"
78
+ "- use pandas module to process tabular data"
79
+ "\n"
80
+ "- skip any solutions which could require manual steps or downloading files and return 'Not possible yet'"
81
+ "\n"
82
  ),
83
  additional_authorized_imports=[
84
  "json",
 
98
  "queue",
99
  "bs4",
100
  "pandas",
101
+ "base64",
102
+ "io",
103
  ],
104
  model=self._coder_model,
105
  max_steps=5,
 
111
  description=(
112
  "An agent who can provide answers on questions by planning and delegating concrete tasks to more specific agents."
113
  "Follow principles:"
114
+ "- IMPORTANT: Provide short and concrete final answer to the question."
115
+ "\n"
116
+ "- Provide to managed agents precise, clear and enhanced instructions with plan and examples how problem could be solved."
117
  "\n"
118
  "- Plan all needed steps which need extractions from external resources in priority, so all following steps have needed information."
119
  "\n"
120
+ "- Skip tasks and questions with obligation to download video, audio, or image content. Answer with 'Not possible yet'."
121
  "\n"
122
  "- Skip tasks and questions with obligation to verify information manually. Answer with 'Not possible yet'."
123
  ),
124
  model=self._manager_model,
125
  add_base_tools=True,
126
+ max_steps=10,
127
  managed_agents=[self._web_search_agent, self._coder_expert_agent],
128
  )
129
 
130
+ def _describe_audio(self, question, audio_content_base64: str) -> str:
131
+ response = self._open_ai_client.chat.completions.create(
132
+ model="gpt-4o-audio-preview",
133
+ messages=[
134
+ {"role": "system", "content": f"You are a helpful assistant that responds in Markdown. Help me recognize the audio file to help user to answer the question {question}."},
135
+ {"role": "user", "content": [
136
+ {"type": "text", "text": "This is an audio file."},
137
+ {"type": "input_audio",
138
+
139
+ "input_audio": {
140
+ "data": audio_content_base64,
141
+ "format": "mp3"
142
+ }
143
+ }
144
+ ]}
145
+ ],
146
+ )
147
+
148
+ return response.choices[0].message.content
149
+
150
+ def _describe_image(self, question, image_content_base64: str) -> str:
151
+ response = self._open_ai_client.chat.completions.create(
152
+ model="gpt-4o-mini",
153
+ messages=[
154
+ {"role": "system", "content": f"You are a helpful assistant that responds in Markdown. Help me recognize the image file to help user to answer the question {question}."},
155
+ {"role": "user", "content": [
156
+ {"type": "text", "text": "This is an image file."},
157
+ {"type": "input_image",
158
+
159
+ "input_image": {
160
+ "data": image_content_base64,
161
+ "format": "png"
162
+ }
163
+ }
164
+ ]}
165
+ ],
166
+ )
167
+
168
+ return response.choices[0].message.content
169
+
170
+ def __call__(self, question: str, file_name: str, file_content_base64: str) -> str:
171
  print(f"Agent received question (first 50 chars): {question[:50]}...")
172
+
173
+ additional_prompt_info = ""
174
+
175
+ if file_name.endswith(".mp3"):
176
+ additional_prompt_info = f"file_name: {file_name}, transcription: {self._describe_audio(file_content_base64)}"
177
+
178
+ if file_name.endswith(".png"):
179
+ additional_prompt_info = f"file_name: {file_name}, image description: {self._describe_image(file_content_base64)}"
180
+
181
 
182
  answer = self._expert_agent.run(
183
+ f"Respond precisely to the question by planning and delegating concrete tasks to available specific agents. User question: {question}. file_name and file_context are provided when user attached files to the question. {additional_prompt_info}",
184
+ additional_args={"user_question": question, "file_name": file_name, "file_content_base64": file_content_base64},
185
  )
186
 
187
  return answer
 
257
  for item in questions_data:
258
  task_id = item.get("task_id")
259
  question_text = item.get("question")
260
+ file_name = ""
261
+ if item.get("file_name"):
262
+ file_name = temp_dir + "/" + item.get("file_name")
263
+ # Read the file content and encode it in base64
264
+ with open(file_name, "rb") as f:
265
+ file_content = f.read()
266
+ file_content_base64 = base64.b64encode(file_content).decode('utf-8')
267
  if not task_id or question_text is None:
268
  print(f"Skipping item with missing task_id or question: {item}")
269
  continue
270
  try:
271
+ submitted_answer = agent(question_text, file_name, file_content_base64)
272
  answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
273
  results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})
274
  except Exception as e:
requirements.txt CHANGED
@@ -5,4 +5,6 @@ markdownify==1.1.0
5
  openai==1.78.0
6
  youtube-transcript-api==1.0.3
7
  pandas==2.2.3
8
- duckduckgo_search==8.0.1
 
 
 
5
  openai==1.78.0
6
  youtube-transcript-api==1.0.3
7
  pandas==2.2.3
8
+ duckduckgo_search==8.0.1
9
+ arxiv==2.2.0
10
+ xlrd==2.0.1