RozzaCreat commited on
Commit
e283efe
·
verified ·
1 Parent(s): 7986740

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +83 -31
app.py CHANGED
@@ -1,18 +1,8 @@
1
- additional_authorized_imports=["pandas", "numpy", "datetime", "re", "json", "math"]
2
-
3
  import os
4
  import gradio as gr
5
  import requests
6
- import inspect
7
  import pandas as pd
8
- from smolagents import CodeAgent, DuckDuckGoSearchTool, InferenceClientModel, WikipediaSearchTool
9
-
10
 
11
- # (Keep Constants as is)
12
- # --- Constants ---
13
- DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
14
-
15
- import os
16
  from smolagents import (
17
  CodeAgent,
18
  DuckDuckGoSearchTool,
@@ -20,20 +10,7 @@ from smolagents import (
20
  WikipediaSearchTool,
21
  )
22
 
23
- SYSTEM_HINT = (
24
- "Answer with ONLY the final answer — no explanation, no units unless asked, "
25
- "no leading articles. If it's a number, write digits. "
26
- "If it's a list, comma-separated."
27
- )
28
-
29
-
30
- import os
31
- from smolagents import (
32
- CodeAgent,
33
- DuckDuckGoSearchTool,
34
- InferenceClientModel,
35
- WikipediaSearchTool,
36
- )
37
 
38
  GAIA_SYSTEM_PROMPT = """You are a general AI assistant. I will ask you a question. Report your thoughts, and finish your answer with the following template:
39
  FINAL ANSWER: [YOUR FINAL ANSWER].
@@ -45,11 +22,13 @@ If you are asked for a comma separated list, apply the above rules depending on
45
 
46
  class BasicAgent:
47
  def __init__(self):
 
 
48
  self.agent = CodeAgent(
49
  tools=[DuckDuckGoSearchTool(), WikipediaSearchTool()],
50
  model=InferenceClientModel(
51
  model_id="Qwen/Qwen2.5-Coder-32B-Instruct",
52
- token=os.getenv("HF_TOKEN"),
53
  ),
54
  max_steps=12,
55
  additional_authorized_imports=["pandas", "numpy", "datetime", "re", "json", "math"],
@@ -58,15 +37,88 @@ class BasicAgent:
58
  def __call__(self, question: str) -> str:
59
  try:
60
  raw = str(self.agent.run(f"{GAIA_SYSTEM_PROMPT}\n\nQuestion: {question}"))
 
61
  if "FINAL ANSWER:" in raw:
62
- answer = raw.split("FINAL ANSWER:")[-1].strip()
63
- answer = answer.rstrip(".").strip()
64
- return answer
65
  return raw.strip()
66
  except Exception as e:
67
- print(f"Agent failed: {e}")
68
- return "unable to answer"
69
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
70
 
71
 
72
  def run_and_submit_all( profile: gr.OAuthProfile | None):
 
 
 
1
  import os
2
  import gradio as gr
3
  import requests
 
4
  import pandas as pd
 
 
5
 
 
 
 
 
 
6
  from smolagents import (
7
  CodeAgent,
8
  DuckDuckGoSearchTool,
 
10
  WikipediaSearchTool,
11
  )
12
 
13
+ DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
 
 
 
 
 
 
 
 
 
 
 
 
 
14
 
15
  GAIA_SYSTEM_PROMPT = """You are a general AI assistant. I will ask you a question. Report your thoughts, and finish your answer with the following template:
16
  FINAL ANSWER: [YOUR FINAL ANSWER].
 
22
 
23
  class BasicAgent:
24
  def __init__(self):
25
+ token = os.getenv("HF_TOKEN")
26
+ print(f"[BasicAgent] HF_TOKEN loaded: {bool(token)}, length: {len(token) if token else 0}")
27
  self.agent = CodeAgent(
28
  tools=[DuckDuckGoSearchTool(), WikipediaSearchTool()],
29
  model=InferenceClientModel(
30
  model_id="Qwen/Qwen2.5-Coder-32B-Instruct",
31
+ token=token,
32
  ),
33
  max_steps=12,
34
  additional_authorized_imports=["pandas", "numpy", "datetime", "re", "json", "math"],
 
37
  def __call__(self, question: str) -> str:
38
  try:
39
  raw = str(self.agent.run(f"{GAIA_SYSTEM_PROMPT}\n\nQuestion: {question}"))
40
+ print(f"[Agent raw output, first 300 chars]: {raw[:300]}")
41
  if "FINAL ANSWER:" in raw:
42
+ return raw.split("FINAL ANSWER:")[-1].strip().rstrip(".").strip()
 
 
43
  return raw.strip()
44
  except Exception as e:
45
+ err = f"ERR: {type(e).__name__}: {str(e)[:200]}"
46
+ print(f"[Agent exception]: {err}")
47
+ return err
48
+
49
+
50
+ def run_and_submit_all(profile: gr.OAuthProfile | None):
51
+ space_id = os.getenv("SPACE_ID")
52
+
53
+ if profile:
54
+ username = f"{profile.username}"
55
+ print(f"User logged in: {username}")
56
+ else:
57
+ return "Please Login to Hugging Face with the button.", None
58
+
59
+ api_url = DEFAULT_API_URL
60
+ questions_url = f"{api_url}/questions"
61
+ submit_url = f"{api_url}/submit"
62
+
63
+ try:
64
+ agent = BasicAgent()
65
+ except Exception as e:
66
+ return f"Error initializing agent: {e}", None
67
+
68
+ agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
69
+
70
+ try:
71
+ response = requests.get(questions_url, timeout=15)
72
+ response.raise_for_status()
73
+ questions_data = response.json()
74
+ if not questions_data:
75
+ return "Fetched questions list is empty or invalid format.", None
76
+ except Exception as e:
77
+ return f"Error fetching questions: {e}", None
78
+
79
+ results_log = []
80
+ answers_payload = []
81
+ for item in questions_data:
82
+ task_id = item.get("task_id")
83
+ question_text = item.get("question")
84
+ if not task_id or question_text is None:
85
+ continue
86
+ submitted_answer = agent(question_text)
87
+ answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
88
+ results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})
89
+
90
+ if not answers_payload:
91
+ return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)
92
+
93
+ submission_data = {"username": username.strip(), "agent_code": agent_code, "answers": answers_payload}
94
+
95
+ try:
96
+ response = requests.post(submit_url, json=submission_data, timeout=60)
97
+ response.raise_for_status()
98
+ result_data = response.json()
99
+ final_status = (
100
+ f"Submission Successful!\n"
101
+ f"User: {result_data.get('username')}\n"
102
+ f"Overall Score: {result_data.get('score', 'N/A')}% "
103
+ f"({result_data.get('correct_count', '?')}/{result_data.get('total_attempted', '?')} correct)\n"
104
+ f"Message: {result_data.get('message', 'No message received.')}"
105
+ )
106
+ return final_status, pd.DataFrame(results_log)
107
+ except Exception as e:
108
+ return f"Submission Failed: {e}", pd.DataFrame(results_log)
109
+
110
+
111
+ with gr.Blocks() as demo:
112
+ gr.Markdown("# Basic Agent Evaluation Runner")
113
+ gr.LoginButton()
114
+ run_button = gr.Button("Run Evaluation & Submit All Answers")
115
+ status_output = gr.Textbox(label="Run Status / Submission Result", lines=5, interactive=False)
116
+ results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True)
117
+ run_button.click(fn=run_and_submit_all, outputs=[status_output, results_table])
118
+
119
+
120
+ if __name__ == "__main__":
121
+ demo.launch(debug=True, share=False)
122
 
123
 
124
  def run_and_submit_all( profile: gr.OAuthProfile | None):