at1300 commited on
Commit
6aba340
·
verified ·
1 Parent(s): 7efbf2b

switch to deepseek with managed agent

Browse files
Files changed (1) hide show
  1. app.py +105 -17
app.py CHANGED
@@ -5,45 +5,100 @@ import inspect
5
  import pandas as pd
6
  import yaml
7
 
8
- from smolagents import CodeAgent, WebSearchTool, InferenceClientModel, DuckDuckGoSearchTool, Tool
9
- from tools import visit_webpage
10
 
11
  # (Keep Constants as is)
12
  # --- Constants ---
13
  DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
14
 
15
- # --- Basic Agent Definition ---
16
  # ----- THIS IS WERE YOU CAN BUILD WHAT YOU WANT ------
17
- class BasicAgent:
 
18
  def __init__(self):
19
- websearchtool = WebSearchTool()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
20
  #search_tool = DuckDuckGoSearchTool()
21
- model = InferenceClientModel()
22
- # TODO: add additional tools and or subagents (e.g. OpenAI image recognition)
23
 
24
- answer_facts = ""
 
 
 
 
 
 
 
 
 
 
 
25
  with open("prompts.yaml", 'r') as stream:
26
  prompt_templates = yaml.safe_load(stream)
27
 
28
  self.master_agent = CodeAgent(
29
- tools=[websearchtool, visit_webpage],
 
30
  model=model,
31
  add_base_tools=True,
32
- planning_interval=3,
33
- max_steps=10,
34
  prompt_templates=prompt_templates,
 
 
 
 
 
 
 
 
 
35
  )
36
- print("BasicAgent initialized.")
37
 
38
- def __call__(self, question: str) -> str:
 
39
  print(f"Agent received question (first 50 chars): {question[:50]}...")
 
40
  agent_answer = self.master_agent.run(question)
41
  print(f"Agent answer: {agent_answer}")
42
  return agent_answer
43
 
44
  def run_and_submit_all( profile: gr.OAuthProfile | None):
45
  """
46
- Fetches all questions, runs the BasicAgent on them, submits all answers,
47
  and displays the results.
48
  """
49
  # --- Determine HF Space Runtime URL and Repo URL ---
@@ -63,7 +118,7 @@ def run_and_submit_all( profile: gr.OAuthProfile | None):
63
 
64
  # 1. Instantiate Agent ( modify this part to create your agent)
65
  try:
66
- agent = BasicAgent()
67
  except Exception as e:
68
  print(f"Error instantiating agent: {e}")
69
  return f"Error initializing agent: {e}", None
@@ -96,9 +151,42 @@ def run_and_submit_all( profile: gr.OAuthProfile | None):
96
  results_log = []
97
  answers_payload = []
98
  print(f"Running agent on {len(questions_data)} questions...")
 
 
 
 
 
99
  for item in questions_data:
100
  task_id = item.get("task_id")
101
  question_text = item.get("question")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
102
  if not task_id or question_text is None:
103
  print(f"Skipping item with missing task_id or question: {item}")
104
  continue
@@ -165,7 +253,7 @@ def run_and_submit_all( profile: gr.OAuthProfile | None):
165
 
166
  # --- Build Gradio Interface using Blocks ---
167
  with gr.Blocks() as demo:
168
- gr.Markdown("# Basic Agent Evaluation Runner")
169
  gr.Markdown(
170
  """
171
  **Instructions:**
@@ -215,5 +303,5 @@ if __name__ == "__main__":
215
 
216
  print("-"*(60 + len(" App Starting ")) + "\n")
217
 
218
- print("Launching Gradio Interface for Basic Agent Evaluation...")
219
  demo.launch(debug=True, share=False)
 
5
  import pandas as pd
6
  import yaml
7
 
8
+ from smolagents import CodeAgent, WebSearchTool, InferenceClientModel, DuckDuckGoSearchTool, Tool, VisitWebpageTool
9
+ from tools import visit_webpage, transcribe_audio, analyze_video
10
 
11
  # (Keep Constants as is)
12
  # --- Constants ---
13
  DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
14
 
15
+ # --- Agent Definition ---
16
  # ----- THIS IS WERE YOU CAN BUILD WHAT YOU WANT ------
17
+ class coder_agent:
18
+ """Coder agent that is running the Qwen2.5 coder model and can generate and execute python code. It can import the pandas library for """
19
  def __init__(self):
20
+ model = InferenceClientModel(model_id="Qwen/Qwen2.5-Coder-32B-Instruct")
21
+
22
+ web_agent = CodeAgent(
23
+ model=model,
24
+ tools=[
25
+ #visit_webpage,
26
+ VisitWebpageTool(),
27
+ WebSearchTool()
28
+ ],
29
+ name="web_agent",
30
+ description="Browses the web to find information",
31
+ verbosity_level=0,
32
+ max_steps=10,
33
+ additional_authorized_imports=[
34
+ "geopandas",
35
+ "plotly",
36
+ "shapely",
37
+ "json",
38
+ "pandas",
39
+ "numpy",
40
+ ],
41
+ )
42
+
43
+ def __call__(self, prompt: str) -> str:
44
+
45
+
46
+ #class vision_agent:
47
+ # """This vision agent is able to be passed base64-encoded image data and will use the OpenAI gpt-4o model to decode it and identify objects within. It will return a textual description of the image."""
48
+
49
+
50
+ class MasterAgent:
51
+ def __init__(self):
52
+ #websearchtool = WebSearchTool()
53
  #search_tool = DuckDuckGoSearchTool()
54
+ model=InferenceClientModel("deepseek-ai/DeepSeek-R1", max_tokens=8096),
 
55
 
56
+ try:
57
+ coder_agent = coder_agent()
58
+ except Exception as e:
59
+ print(f"Error instantiating agent: {e}")
60
+ return f"Error initializing agent: {e}", None
61
+
62
+ try:
63
+ vision_agent = vision_agent()
64
+ except Exception as e:
65
+ print(f"Error instantiating agent: {e}")
66
+ return f"Error initializing agent: {e}", None
67
+
68
  with open("prompts.yaml", 'r') as stream:
69
  prompt_templates = yaml.safe_load(stream)
70
 
71
  self.master_agent = CodeAgent(
72
+ tools=[VisitWebpageTool(),
73
+ WebSearchTool()],
74
  model=model,
75
  add_base_tools=True,
76
+ planning_interval=5,
77
+ max_steps=15,
78
  prompt_templates=prompt_templates,
79
+ managed_agents=[coder_agent],
80
+ additional_authorized_imports=[
81
+ "geopandas",
82
+ "plotly",
83
+ "shapely",
84
+ "json",
85
+ "pandas",
86
+ "numpy",
87
+ ],
88
  )
89
+ print("MasterAgent initialized.")
90
 
91
+ def __call__(self, question: str, attached_file: str) -> str:
92
+ """"""
93
  print(f"Agent received question (first 50 chars): {question[:50]}...")
94
+ #TODO Handle the file, some will need to be accessed locally, some can just be passed as public URLs
95
  agent_answer = self.master_agent.run(question)
96
  print(f"Agent answer: {agent_answer}")
97
  return agent_answer
98
 
99
  def run_and_submit_all( profile: gr.OAuthProfile | None):
100
  """
101
+ Fetches all questions, runs the MasterAgent on them, submits all answers,
102
  and displays the results.
103
  """
104
  # --- Determine HF Space Runtime URL and Repo URL ---
 
118
 
119
  # 1. Instantiate Agent ( modify this part to create your agent)
120
  try:
121
+ agent = MasterAgent()
122
  except Exception as e:
123
  print(f"Error instantiating agent: {e}")
124
  return f"Error initializing agent: {e}", None
 
151
  results_log = []
152
  answers_payload = []
153
  print(f"Running agent on {len(questions_data)} questions...")
154
+
155
+ cache_dir = "file_cache"
156
+ if not os.path.exists(cache_dir):
157
+ os.makedirs(cache_dir)
158
+
159
  for item in questions_data:
160
  task_id = item.get("task_id")
161
  question_text = item.get("question")
162
+ attached_file = item.get("file_name")
163
+ if attached_file != "":
164
+ local_file_path = os.path.join(cache_dir, attached_file)
165
+ if not os.path.exists(local_file_path):
166
+ file_name_no_ext = os.path.splitext(attached_file)[0] # e.g., 'document' from 'document.pdf'
167
+ download_url = f"{questions_url}/files/{file_name_no_ext}"
168
+
169
+ try:
170
+ print(f"Downloading from {download_url}")
171
+ response = requests.get(download_url, stream=True)
172
+ response.raise_for_status() # Raises an HTTPError for bad responses
173
+ with open(local_file_path, 'wb') as f:
174
+ for chunk in response.iter_content(chunk_size=8192):
175
+ if chunk:
176
+ f.write(chunk)
177
+ print(f"File downloaded and cached: {local_file_path}")
178
+ return local_file_path
179
+
180
+ except requests.exceptions.HTTPError as e:
181
+ print(f"HTTP error downloading {download_url}: {e}")
182
+ return None
183
+ except requests.exceptions.RequestException as e:
184
+ print(f"Error downloading {download_url}: {e}")
185
+ return None
186
+ except OSError as e:
187
+ print(f"Error saving file to {local_file_path}: {e}")
188
+ return None
189
+
190
  if not task_id or question_text is None:
191
  print(f"Skipping item with missing task_id or question: {item}")
192
  continue
 
253
 
254
  # --- Build Gradio Interface using Blocks ---
255
  with gr.Blocks() as demo:
256
+ gr.Markdown("# Agent Evaluation Runner")
257
  gr.Markdown(
258
  """
259
  **Instructions:**
 
303
 
304
  print("-"*(60 + len(" App Starting ")) + "\n")
305
 
306
+ print("Launching Gradio Interface for Agent Evaluation...")
307
  demo.launch(debug=True, share=False)