ChockqOteewy commited on
Commit
5bb8fe1
·
verified ·
1 Parent(s): 2f5add3

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +69 -101
app.py CHANGED
@@ -2,128 +2,96 @@ import os
2
  import gradio as gr
3
  import requests
4
  import pandas as pd
5
-
6
- from smolagents.models import InferenceClientModel
7
- from smolagents.agents import ToolCallingAgent
8
- from smolagents.tools import DuckDuckGoSearchTool, WebSearchTool, WikipediaSearchTool
9
 
10
  DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
11
 
12
- def create_agent():
13
- model = InferenceClientModel(repo_id="HuggingFaceH4/zephyr-7b-beta")
14
- wiki_tool = WikipediaSearchTool()
15
- duck_tool = DuckDuckGoSearchTool()
16
- web_tool = WebSearchTool()
17
- agent = ToolCallingAgent(
18
- tools=[wiki_tool, duck_tool, web_tool],
19
- model=model
20
- )
21
- return agent
22
 
23
- def run_and_submit_all(profile: gr.OAuthProfile | None):
24
- space_id = os.getenv("SPACE_ID")
25
- if profile:
26
- username = f"{profile.username}"
27
- else:
28
- return "Please Login to Hugging Face with the button.", None
 
 
29
 
30
- api_url = DEFAULT_API_URL
31
- questions_url = f"{api_url}/questions"
32
- submit_url = f"{api_url}/submit"
 
33
 
 
34
  try:
35
- agent = create_agent()
 
 
 
36
  except Exception as e:
37
- return f"Error initializing agent: {e}", None
38
 
39
- agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
 
 
 
 
 
 
 
 
 
40
 
 
 
 
 
 
 
 
 
41
  try:
42
- response = requests.get(questions_url, timeout=15)
43
- response.raise_for_status()
44
- questions_data = response.json()
45
- if not questions_data:
46
- return "Fetched questions list is empty or invalid format.", None
47
  except Exception as e:
48
- return f"Error fetching questions: {e}", None
 
 
 
49
 
50
- results_log = []
51
- answers_payload = []
52
  for item in questions_data:
53
  task_id = item.get("task_id")
54
  question_text = item.get("question")
55
- if not task_id or question_text is None:
56
- continue
57
- try:
58
- submitted_answer = agent(question_text)
59
- answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
60
- results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})
61
- except Exception as e:
62
- results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": f"(Agent error: {e})"})
63
-
64
- if not answers_payload:
65
- return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)
66
-
67
- submission_data = {
68
- "username": username.strip(),
69
- "agent_code": agent_code,
70
- "answers": answers_payload
71
- }
72
 
73
- try:
74
- response = requests.post(submit_url, json=submission_data, timeout=60)
75
- response.raise_for_status()
76
- result_data = response.json()
77
- final_status = (
78
- f"Submission Successful!\n"
79
- f"User: {result_data.get('username')}\n"
80
- f"Overall Score: {result_data.get('score', 'N/A')}% "
81
- f"({result_data.get('correct_count', '?')}/{result_data.get('total_attempted', '?')} correct)\n"
82
- f"Message: {result_data.get('message', 'No message received.')}"
83
- )
84
- results_df = pd.DataFrame(results_log)
85
- return final_status, results_df
86
- except Exception as e:
87
- status_message = f"Submission Failed: {e}"
88
- results_df = pd.DataFrame(results_log)
89
- return status_message, results_df
90
 
91
- with gr.Blocks() as demo:
92
- gr.Markdown("# SmolAgent Evaluation Runner")
93
- gr.Markdown(
94
- """
95
- **Instructions:**
96
- - Clone and modify this space to improve your agent logic as you see fit.
97
- - Log in to your Hugging Face account with the button below.
98
- - Click 'Run Evaluation & Submit All Answers' to begin.
99
- Disclaimer: Submission may take a while depending on the number of questions and agent speed.
100
- """
101
  )
 
 
 
 
 
102
  gr.LoginButton()
103
  run_button = gr.Button("Run Evaluation & Submit All Answers")
104
- status_output = gr.Textbox(label="Run Status / Submission Result", lines=5, interactive=False)
105
- results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True)
106
 
107
- run_button.click(
108
- fn=run_and_submit_all,
109
- outputs=[status_output, results_table]
110
- )
111
 
112
  if __name__ == "__main__":
113
- print("\n" + "-"*30 + " App Starting " + "-"*30)
114
- space_host_startup = os.getenv("SPACE_HOST")
115
- space_id_startup = os.getenv("SPACE_ID")
116
- if space_host_startup:
117
- print(f"✅ SPACE_HOST found: {space_host_startup}")
118
- print(f" Runtime URL should be: https://{space_host_startup}.hf.space")
119
- else:
120
- print("ℹ️ SPACE_HOST not found (running locally?)")
121
- if space_id_startup:
122
- print(f"✅ SPACE_ID found: {space_id_startup}")
123
- print(f" Repo URL: https://huggingface.co/spaces/{space_id_startup}")
124
- print(f" Repo Tree URL: https://huggingface.co/spaces/{space_id_startup}/tree/main")
125
- else:
126
- print("ℹ️ SPACE_ID not found")
127
- print("-"*(60 + len(" App Starting ")) + "\n")
128
- print("Launching Gradio Interface for SmolAgent Evaluation...")
129
- demo.launch(debug=True, share=False)
 
2
  import gradio as gr
3
  import requests
4
  import pandas as pd
5
+ from huggingface_hub import InferenceClient
6
+ from duckduckgo_search import DDGS
7
+ from datasets import load_dataset
 
8
 
9
  DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
10
 
11
+ # Hugging Face Token (set in environment)
12
+ HF_TOKEN = os.environ.get("HF_TOKEN")
13
+ deepseek_model = "deepseek-ai/DeepSeek-R1"
14
+ hf_client = InferenceClient(model=deepseek_model, token=HF_TOKEN)
 
 
 
 
 
 
15
 
16
+ # Load Wikipedia dataset (small subset for efficient retrieval)
17
+ wiki_dataset = load_dataset("wikipedia", "20220301.en", split="train[:10000]")
18
+
19
+ def search_wikipedia(question):
20
+ results = wiki_dataset.filter(lambda x: question.lower() in x["text"].lower())
21
+ if len(results):
22
+ return results[0]["text"][:1000] # limit to first 1000 chars
23
+ return "No relevant information found on Wikipedia."
24
 
25
+ def duckduckgo_search(query):
26
+ with DDGS() as ddgs:
27
+ results = [r["body"] for r in ddgs.text(query, max_results=3)]
28
+ return "\n".join(results) if results else "No results found."
29
 
30
+ def ask_deepseek(prompt, max_tokens=512):
31
  try:
32
+ response = hf_client.text_generation(
33
+ prompt, max_new_tokens=max_tokens, temperature=0.2, repetition_penalty=1.1
34
+ )
35
+ return response
36
  except Exception as e:
37
+ return f"DeepSeek Error: {e}"
38
 
39
+ class SmartAgent:
40
+ def __call__(self, question: str) -> str:
41
+ q_lower = question.lower()
42
+ if any(term in q_lower for term in ["current", "latest", "2024", "2025", "recent", "live", "today", "now"]):
43
+ return duckduckgo_search(question)
44
+ deepseek_response = ask_deepseek(question)
45
+ if "DeepSeek Error" not in deepseek_response and deepseek_response.strip():
46
+ return deepseek_response
47
+ # fallback to Wikipedia if DeepSeek fails
48
+ return search_wikipedia(question)
49
 
50
+ def run_and_submit_all(profile: gr.OAuthProfile | None):
51
+ if not profile:
52
+ return "Please Login to Hugging Face with the button.", None
53
+ username = profile.username
54
+ questions_url = f"{DEFAULT_API_URL}/questions"
55
+ submit_url = f"{DEFAULT_API_URL}/submit"
56
+ agent_code = f"https://huggingface.co/spaces/{os.getenv('SPACE_ID')}/tree/main"
57
+
58
  try:
59
+ agent = SmartAgent()
 
 
 
 
60
  except Exception as e:
61
+ return f"Agent Error: {e}", None
62
+
63
+ questions_data = requests.get(questions_url).json()
64
+ results_log, answers_payload = [], []
65
 
 
 
66
  for item in questions_data:
67
  task_id = item.get("task_id")
68
  question_text = item.get("question")
69
+ if task_id and question_text:
70
+ answer = agent(question_text)
71
+ answers_payload.append({"task_id": task_id, "submitted_answer": answer})
72
+ results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": answer})
 
 
 
 
 
 
 
 
 
 
 
 
 
73
 
74
+ submission_data = {"username": username, "agent_code": agent_code, "answers": answers_payload}
75
+ response = requests.post(submit_url, json=submission_data).json()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
76
 
77
+ final_status = (
78
+ f"Submission Successful!\n"
79
+ f"User: {response.get('username')}\n"
80
+ f"Overall Score: {response.get('score', 'N/A')}%\n"
81
+ f"({response.get('correct_count', '?')}/{response.get('total_attempted', '?')} correct)\n"
82
+ f"Message: {response.get('message', 'No message received.')}"
 
 
 
 
83
  )
84
+
85
+ return final_status, pd.DataFrame(results_log)
86
+
87
+ with gr.Blocks() as demo:
88
+ gr.Markdown("# Smart Agent Evaluation Runner")
89
  gr.LoginButton()
90
  run_button = gr.Button("Run Evaluation & Submit All Answers")
91
+ status_output = gr.Textbox(label="Run Status", lines=5, interactive=False)
92
+ results_table = gr.DataFrame(label="Questions and Answers")
93
 
94
+ run_button.click(run_and_submit_all, outputs=[status_output, results_table])
 
 
 
95
 
96
  if __name__ == "__main__":
97
+ demo.launch(debug=True)