ignatiev commited on
Commit
aa8ca9f
·
1 Parent(s): 81917a3

feat: first try

Browse files
Files changed (4) hide show
  1. agents/__init__.py +0 -0
  2. agents/web_search_tool.py +30 -0
  3. app.py +117 -6
  4. requirements.txt +6 -1
agents/__init__.py ADDED
File without changes
agents/web_search_tool.py ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import requests
3
+ from smolagents import tool
4
+
5
+ @tool
6
+ def search_in_google(query: str) -> str:
7
+ """
8
+ Perform a Google search using the provided query and return the first result.
9
+
10
+ Args:
11
+ query (str): The search query to perform a web search on Google.
12
+ """
13
+
14
+ GOOGLE_CUSTOM_SEARCH_API_KEY = os.getenv("GOOGLE_CUSTOM_SEARCH_API_KEY")
15
+ GOOGLE_CUSTOM_SEARCH_SEARCH_ENGINE_ID = os.getenv("GOOGLE_CUSTOM_SEARCH_SEARCH_ENGINE_ID")
16
+
17
+ response = requests.get(f"https://www.googleapis.com/customsearch/v1?key={GOOGLE_CUSTOM_SEARCH_API_KEY}&cx={GOOGLE_CUSTOM_SEARCH_SEARCH_ENGINE_ID}&q={query}")
18
+
19
+ response_json = response.json()
20
+ search_results = response_json.get("items", [])
21
+
22
+ processed_results = []
23
+
24
+ for result in search_results:
25
+ title = result.get("title")
26
+ link = result.get("link")
27
+ snippet = result.get("snippet")
28
+ processed_results.append(f"Title: {title}\nLink: {link}\nSnippet: {snippet}\n")
29
+
30
+ return "\n".join(processed_results)
app.py CHANGED
@@ -1,7 +1,18 @@
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)
@@ -10,14 +21,99 @@ 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
  """
@@ -51,6 +147,7 @@ def run_and_submit_all( profile: gr.OAuthProfile | None):
51
  # 2. Fetch Questions
52
  print(f"Fetching questions from: {questions_url}")
53
  try:
 
54
  response = requests.get(questions_url, timeout=15)
55
  response.raise_for_status()
56
  questions_data = response.json()
@@ -58,6 +155,19 @@ def run_and_submit_all( profile: gr.OAuthProfile | None):
58
  print("Fetched questions list is empty.")
59
  return "Fetched questions list is empty or invalid format.", None
60
  print(f"Fetched {len(questions_data)} questions.")
 
 
 
 
 
 
 
 
 
 
 
 
 
61
  except requests.exceptions.RequestException as e:
62
  print(f"Error fetching questions: {e}")
63
  return f"Error fetching questions: {e}", None
@@ -76,11 +186,12 @@ def run_and_submit_all( profile: gr.OAuthProfile | None):
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:
 
1
  import os
2
  import gradio as gr
3
  import requests
4
+ import json
5
+ import tempfile
6
+
7
+ from smolagents import (
8
+ ToolCallingAgent,
9
+ InferenceClientModel,
10
+ CodeAgent,
11
+ VisitWebpageTool,
12
+ OpenAIServerModel,
13
+ )
14
+ from agents.web_search_tool import search_in_google
15
+
16
  import pandas as pd
17
 
18
  # (Keep Constants as is)
 
21
 
22
  # --- Basic Agent Definition ---
23
  # ----- THIS IS WERE YOU CAN BUILD WHAT YOU WANT ------
24
+
25
  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",
32
+ api_base="https://api.openai.com/v1",
33
+ api_key=os.getenv("OPENAI_API_KEY"),
34
+ )
35
+
36
+ self._coder_model = InferenceClientModel(
37
+ model_id="Qwen/Qwen2.5-Coder-32B-Instruct",
38
+ token=HF_TOKEN,
39
+ )
40
+
41
+ self._web_search_model = InferenceClientModel(
42
+ model_id="meta-llama/Llama-3.3-70B-Instruct",
43
+ token=HF_TOKEN,
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",
68
+ "requests",
69
+ "youtube-transcript-api",
70
+ "collections",
71
+ "datetime",
72
+ "re",
73
+ "stat",
74
+ "time",
75
+ "unicodedata",
76
+ "random",
77
+ "statistics",
78
+ "youtube_transcript_api",
79
+ "itertools",
80
+ "math",
81
+ "queue",
82
+ "bs4",
83
+ "pandas",
84
+ ],
85
+ model=self._coder_model,
86
+ max_steps=5,
87
+ )
88
+
89
+ self._expert_agent = CodeAgent(
90
+ tools=[],
91
+ name="general_expert_agent",
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
117
 
118
  def run_and_submit_all( profile: gr.OAuthProfile | None):
119
  """
 
147
  # 2. Fetch Questions
148
  print(f"Fetching questions from: {questions_url}")
149
  try:
150
+ temp_dir = tempfile.mkdtemp()
151
  response = requests.get(questions_url, timeout=15)
152
  response.raise_for_status()
153
  questions_data = response.json()
 
155
  print("Fetched questions list is empty.")
156
  return "Fetched questions list is empty or invalid format.", None
157
  print(f"Fetched {len(questions_data)} questions.")
158
+
159
+ for item in questions_data:
160
+ task_id = item.get("task_id")
161
+ file_name = item.get("file_name")
162
+ if file_name:
163
+ file_response = requests.get(
164
+ f"{api_url}/files/{task_id}",
165
+ timeout=15,
166
+ )
167
+ # Save file in temporary directory with name in file variable
168
+ with open(temp_dir + "/" + file_name, "wb") as f:
169
+ f.write(file_response.content)
170
+
171
  except requests.exceptions.RequestException as e:
172
  print(f"Error fetching questions: {e}")
173
  return f"Error fetching questions: {e}", 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:
requirements.txt CHANGED
@@ -1,2 +1,7 @@
1
  gradio
2
- requests
 
 
 
 
 
 
1
  gradio
2
+ requests
3
+ smolagents==1.15.0
4
+ markdownify==1.1.0
5
+ openai==1.78.0
6
+ youtube-transcript-api==1.0.3
7
+ pandas==2.2.3