STARX33 commited on
Commit
fe3a5b5
·
verified ·
1 Parent(s): 5e043c7

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +45 -40
app.py CHANGED
@@ -1,33 +1,40 @@
1
  import os
2
  import gradio as gr
3
  import requests
4
- import inspect
5
- import pandas as pd
 
6
  from smolagents import CodeAgent, HfApiModel
 
 
7
 
8
  # === Constants ===
9
  DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
10
 
11
- # === BasicAgent using built-in smolagents tools ===
12
  class BasicAgent:
13
  def __init__(self):
14
- model = HfApiModel(model_id="Qwen/Qwen2.5-Coder-32B-Instruct")
 
 
15
 
16
  self.agent = CodeAgent(
17
  model=model,
18
- tools=[], # Leave empty, base tools are added below
19
- add_base_tools=True, # Enables DuckDuckGoSearchTool + Vision tools
 
 
20
  max_steps=6,
21
- name="CertificationAgent",
22
- description="Agent using built-in smolagents tools for search and vision tasks"
23
  )
24
- print("✅ BasicAgent initialized with built-in tools (search + vision).")
25
 
26
  def __call__(self, question: str) -> str:
27
  return self.agent.run(question)
28
 
29
 
30
- # === Evaluation Logic (Do Not Modify) ===
31
  def run_and_submit_all(profile: gr.OAuthProfile | None):
32
  space_id = os.getenv("SPACE_ID")
33
 
@@ -38,6 +45,7 @@ def run_and_submit_all(profile: gr.OAuthProfile | None):
38
  print("User not logged in.")
39
  return "Please Login to Hugging Face with the button.", None
40
 
 
41
  api_url = DEFAULT_API_URL
42
  questions_url = f"{api_url}/questions"
43
  submit_url = f"{api_url}/submit"
@@ -45,50 +53,48 @@ def run_and_submit_all(profile: gr.OAuthProfile | None):
45
  try:
46
  agent = BasicAgent()
47
  except Exception as e:
48
- print(f"Error instantiating agent: {e}")
49
  return f"Error initializing agent: {e}", None
50
 
51
- agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
52
- print(agent_code)
53
-
54
- print(f"Fetching questions from: {questions_url}")
55
  try:
56
  response = requests.get(questions_url, timeout=15)
57
  response.raise_for_status()
58
  questions_data = response.json()
59
  if not questions_data:
60
- print("Fetched questions list is empty.")
61
  return "Fetched questions list is empty or invalid format.", None
62
- print(f"Fetched {len(questions_data)} questions.")
63
- except requests.exceptions.RequestException as e:
64
- print(f"Error fetching questions: {e}")
65
- return f"Error fetching questions: {e}", None
66
- except requests.exceptions.JSONDecodeError as e:
67
- print(f"Error decoding JSON response: {e}")
68
- return f"Error decoding server response: {e}", None
69
  except Exception as e:
70
- print(f"Unexpected error fetching questions: {e}")
71
- return f"Unexpected error fetching questions: {e}", None
72
 
73
  results_log = []
74
  answers_payload = []
 
75
  for item in questions_data:
76
  task_id = item.get("task_id")
77
  question_text = item.get("question")
78
- if not task_id or question_text is None:
79
  continue
80
  try:
81
  submitted_answer = agent(question_text)
82
  answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
83
- results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})
 
 
 
 
84
  except Exception as e:
85
- results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": f"AGENT ERROR: {e}"})
 
 
 
 
86
 
87
  if not answers_payload:
88
  return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)
89
 
90
- submission_data = {"username": username.strip(), "agent_code": agent_code, "answers": answers_payload}
91
- print(f"Submitting {len(answers_payload)} answers to: {submit_url}")
 
 
 
92
 
93
  try:
94
  response = requests.post(submit_url, json=submission_data, timeout=60)
@@ -106,7 +112,7 @@ def run_and_submit_all(profile: gr.OAuthProfile | None):
106
  return f"Submission Failed: {e}", pd.DataFrame(results_log)
107
 
108
 
109
- # === Gradio UI (Do Not Modify) ===
110
  with gr.Blocks() as demo:
111
  gr.Markdown("# Basic Agent Evaluation Runner")
112
  gr.Markdown("""
@@ -125,14 +131,13 @@ with gr.Blocks() as demo:
125
 
126
  if __name__ == "__main__":
127
  print("\n" + "-"*30 + " App Starting " + "-"*30)
128
- space_host_startup = os.getenv("SPACE_HOST")
129
- space_id_startup = os.getenv("SPACE_ID")
130
- if space_host_startup:
131
- print(f"✅ SPACE_HOST found: {space_host_startup}")
132
- print(f" Runtime URL: https://{space_host_startup}.hf.space")
133
- if space_id_startup:
134
- print(f"✅ SPACE_ID found: {space_id_startup}")
135
- print(f" Repo URL: https://huggingface.co/spaces/{space_id_startup}")
136
- print(f" Tree URL: https://huggingface.co/spaces/{space_id_startup}/tree/main")
137
  print("Launching Gradio Interface...")
138
  demo.launch(debug=True, share=False)
 
1
  import os
2
  import gradio as gr
3
  import requests
4
+ import pandas as pd # Required for result table formatting
5
+
6
+ # === Hugging Face SmolAgents imports ===
7
  from smolagents import CodeAgent, HfApiModel
8
+ from smolagents.tools.web_search import DuckDuckGoSearchTool
9
+ from smolagents.tools.vision import ImageCaptionTool
10
 
11
  # === Constants ===
12
  DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
13
 
14
+ # === Agent Definition with 2 Tools ===
15
  class BasicAgent:
16
  def __init__(self):
17
+ model = HfApiModel(
18
+ model_id="Qwen/Qwen2.5-Coder-32B-Instruct"
19
+ )
20
 
21
  self.agent = CodeAgent(
22
  model=model,
23
+ tools=[
24
+ DuckDuckGoSearchTool(),
25
+ ImageCaptionTool()
26
+ ],
27
  max_steps=6,
28
+ name="EvalAgent",
29
+ description="Agent using DuckDuckGoSearchTool and ImageCaptionTool for HF certification"
30
  )
31
+ print("✅ BasicAgent initialized with 2 certified tools.")
32
 
33
  def __call__(self, question: str) -> str:
34
  return self.agent.run(question)
35
 
36
 
37
+ # === Evaluation Logic (Unmodified) ===
38
  def run_and_submit_all(profile: gr.OAuthProfile | None):
39
  space_id = os.getenv("SPACE_ID")
40
 
 
45
  print("User not logged in.")
46
  return "Please Login to Hugging Face with the button.", None
47
 
48
+ agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
49
  api_url = DEFAULT_API_URL
50
  questions_url = f"{api_url}/questions"
51
  submit_url = f"{api_url}/submit"
 
53
  try:
54
  agent = BasicAgent()
55
  except Exception as e:
 
56
  return f"Error initializing agent: {e}", None
57
 
 
 
 
 
58
  try:
59
  response = requests.get(questions_url, timeout=15)
60
  response.raise_for_status()
61
  questions_data = response.json()
62
  if not questions_data:
 
63
  return "Fetched questions list is empty or invalid format.", None
 
 
 
 
 
 
 
64
  except Exception as e:
65
+ return f"Error fetching questions: {e}", None
 
66
 
67
  results_log = []
68
  answers_payload = []
69
+
70
  for item in questions_data:
71
  task_id = item.get("task_id")
72
  question_text = item.get("question")
73
+ if not task_id or not question_text:
74
  continue
75
  try:
76
  submitted_answer = agent(question_text)
77
  answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
78
+ results_log.append({
79
+ "Task ID": task_id,
80
+ "Question": question_text,
81
+ "Submitted Answer": submitted_answer
82
+ })
83
  except Exception as e:
84
+ results_log.append({
85
+ "Task ID": task_id,
86
+ "Question": question_text,
87
+ "Submitted Answer": f"AGENT ERROR: {e}"
88
+ })
89
 
90
  if not answers_payload:
91
  return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)
92
 
93
+ submission_data = {
94
+ "username": username.strip(),
95
+ "agent_code": agent_code,
96
+ "answers": answers_payload
97
+ }
98
 
99
  try:
100
  response = requests.post(submit_url, json=submission_data, timeout=60)
 
112
  return f"Submission Failed: {e}", pd.DataFrame(results_log)
113
 
114
 
115
+ # === Gradio UI (Unmodified) ===
116
  with gr.Blocks() as demo:
117
  gr.Markdown("# Basic Agent Evaluation Runner")
118
  gr.Markdown("""
 
131
 
132
  if __name__ == "__main__":
133
  print("\n" + "-"*30 + " App Starting " + "-"*30)
134
+ space_host = os.getenv("SPACE_HOST")
135
+ space_id = os.getenv("SPACE_ID")
136
+ if space_host:
137
+ print(f"✅ SPACE_HOST found: {space_host}")
138
+ print(f" Runtime URL: https://{space_host}.hf.space")
139
+ if space_id:
140
+ print(f"✅ SPACE_ID found: {space_id}")
141
+ print(f" Repo URL: https://huggingface.co/spaces/{space_id}")
 
142
  print("Launching Gradio Interface...")
143
  demo.launch(debug=True, share=False)