Shivangsinha commited on
Commit
693dcc6
·
verified ·
1 Parent(s): 22a337a

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +49 -95
app.py CHANGED
@@ -6,7 +6,7 @@ import inspect
6
  import pandas as pd
7
  from smolagents import (
8
  ToolCallingAgent,
9
- OpenAIServerModel,
10
  DuckDuckGoSearchTool,
11
  WikipediaSearchTool,
12
  PythonInterpreterTool,
@@ -29,110 +29,87 @@ def get_current_date_time() -> str:
29
  class BasicAgent:
30
  def __init__(self):
31
  print("BasicAgent initialized.")
32
- sambanova_api_key = os.getenv("SAMBANOVA_API_KEY")
33
- self.model = OpenAIServerModel(
34
- model_id="Meta-Llama-3.3-70B-Instruct",
35
- api_base="https://api.sambanova.ai/v1",
36
- api_key=sambanova_api_key,
 
37
  )
38
- tools = [
39
  DuckDuckGoSearchTool(),
40
  WikipediaSearchTool(),
41
  PythonInterpreterTool(),
42
  get_current_date_time,
43
  ]
44
- self.tools = tools
 
 
 
 
 
45
 
46
  def __call__(self, question: str) -> str:
47
- print(f"Agent received question (first 50 chars): {question[:50]}")
48
- # Retry up to 3 times with backoff on rate limit errors
49
- for attempt in range(3):
50
- try:
51
- agent = ToolCallingAgent(
52
- tools=self.tools,
53
- model=self.model,
54
- max_steps=8,
55
- )
56
- answer = agent.run(question)
57
- print(f"Agent answer: {str(answer)[:100]}")
58
- return str(answer)
59
- except Exception as e:
60
- err = str(e)
61
- if "429" in err or "rate_limit" in err.lower() or "rate limit" in err.lower():
62
- wait = 60 * (attempt + 1)
63
- print(f"Rate limit hit, waiting {wait}s before retry {attempt+1}/3...")
64
- time.sleep(wait)
65
- else:
66
- print(f"Agent error: {e}")
67
- return f"Error: {e}"
68
- return "Error: Rate limit exceeded after retries"
69
 
70
 
71
- # --- run_and_submit_all function (Keep as is) ---
72
  def run_and_submit_all(profile: gr.OAuthProfile | None):
73
  space_id = os.getenv("SPACE_ID")
74
-
75
  if profile:
76
  username = f"{profile.username}"
77
  print(f"User logged in: {username}")
78
  else:
79
  print("User not logged in.")
80
  return "Please Login to Hugging Face with the button.", None
81
-
82
  api_url = DEFAULT_API_URL
83
  questions_url = f"{api_url}/questions"
84
  submit_url = f"{api_url}/submit"
85
-
86
  try:
87
  agent = BasicAgent()
88
  except Exception as e:
89
  print(f"Error instantiating agent: {e}")
90
  return f"Error initializing agent: {e}", None
91
-
92
  agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
93
- print(agent_code)
94
-
95
  print(f"Fetching questions from: {questions_url}")
96
  try:
97
  response = requests.get(questions_url, timeout=15)
98
  response.raise_for_status()
99
  questions_data = response.json()
100
  if not questions_data:
101
- print("Fetched questions list is empty.")
102
- return "Fetched questions list is empty or invalid format.", None
103
- print(f"Fetched {len(questions_data)} questions.")
104
  except Exception as e:
105
  print(f"Error fetching questions: {e}")
106
  return f"Error fetching questions: {e}", None
107
-
108
  results_log = []
109
  answers_payload = []
110
  print(f"Running agent on {len(questions_data)} questions...")
111
- for item in questions_data:
112
  task_id = item.get("task_id")
113
  question_text = item.get("question")
114
- if not task_id or question_text is None:
115
- print(f"Skipping item with missing task_id or question: {item}")
116
  continue
117
  try:
118
  submitted_answer = agent(question_text)
119
  answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
120
  results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})
121
  except Exception as e:
122
- print(f"Error running agent on task {task_id}: {e}")
123
- results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": f"AGENT ERROR: {e}"})
124
- # Pause between questions to avoid per-minute rate limits
125
- time.sleep(3)
126
-
127
  if not answers_payload:
128
- print("Agent did not produce any answers to submit.")
129
- return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)
130
-
131
  submission_data = {"username": username.strip(), "agent_code": agent_code, "answers": answers_payload}
132
- status_update = f"Agent finished. Submitting {len(answers_payload)} answers for user '{username}'..."
133
- print(status_update)
134
-
135
- print(f"Submitting {len(answers_payload)} answers to: {submit_url}")
136
  try:
137
  response = requests.post(submit_url, json=submission_data, timeout=60)
138
  response.raise_for_status()
@@ -140,60 +117,37 @@ def run_and_submit_all(profile: gr.OAuthProfile | None):
140
  final_status = (
141
  f"Submission Successful!\n"
142
  f"User: {result_data.get('username')}\n"
143
- f"Overall Score: {result_data.get('score', 'N/A')} "
144
- f"({result_data.get('correct_count', '?')}/{result_data.get('total_attempted', '?')} correct)\n"
145
- f"Message: {result_data.get('message', 'No message received.')}"
146
  )
147
- print("Submission successful.")
148
- results_df = pd.DataFrame(results_log)
149
- return final_status, results_df
150
  except Exception as e:
151
- status_message = f"Submission Failed: {e}"
152
- print(status_message)
153
- results_df = pd.DataFrame(results_log)
154
- return status_message, results_df
155
 
156
 
157
- # --- Build Gradio Interface using Blocks ---
158
  with gr.Blocks() as demo:
159
  gr.Markdown("# Basic Agent Evaluation Runner")
160
  gr.Markdown(
161
  """
162
- **Instructions:**
163
- 1. Please clone this space, then modify the code to define your agent's logic, the tools, the necessary packages, etc ...
164
- 2. Log in to your Hugging Face account using the button below. This uses your HF username for submission.
165
- 3. Click 'Run Evaluation & Submit All Answers' to fetch questions, run your agent, submit answers, and see the score.
166
- ---
167
- **Disclaimers:**
168
- Once clicking on the "submit button, it can take quite some time ( this is the time for the agent to go through all the questions).
169
- This space provides a basic setup and is intentionally sub-optimal to encourage you to develop your own, more robust solution. For instance for the delay process of the submit button, a solution could be to cache the answers and submit in a seperate action or even to answer the questions in async.
170
- """
171
  )
172
  gr.LoginButton()
173
  run_button = gr.Button("Run Evaluation & Submit All Answers")
174
  status_output = gr.Textbox(label="Run Status / Submission Result", lines=5, interactive=False)
175
- # Removed max_rows=10 from DataFrame constructor
176
  results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True)
177
  run_button.click(
178
  fn=run_and_submit_all,
179
  outputs=[status_output, results_table]
180
  )
 
181
  if __name__ == "__main__":
182
- print("\n" + "-" * 30 + " App Starting " + "-" * 30)
183
- # Check for SPACE_HOST and SPACE_ID at startup for information
184
- space_host_startup = os.getenv("SPACE_HOST")
185
- space_id_startup = os.getenv("SPACE_ID") # Get SPACE_ID at startup
186
- if space_host_startup:
187
- print(f"\u2705 SPACE_HOST found: {space_host_startup}")
188
- print(f" Runtime URL should be: https://{space_host_startup}.hf.space")
189
- else:
190
- print("\u2139\ufe0f SPACE_HOST environment variable not found (running locally?).")
191
- if space_id_startup: # Print repo URLs if SPACE_ID is found
192
- print(f"\u2705 SPACE_ID found: {space_id_startup}")
193
- print(f" Repo URL: https://huggingface.co/spaces/{space_id_startup}")
194
- print(f" Repo Tree URL: https://huggingface.co/spaces/{space_id_startup}/tree/main")
195
- else:
196
- print("\u2139\ufe0f SPACE_ID environment variable not found (running locally?). Repo URL cannot be determined.")
197
- print("-" * (60 + len(" App Starting ")) + "\n")
198
- print("Launching Gradio Interface for Basic Agent Evaluation...")
199
- demo.launch(debug=True, share=False)
 
6
  import pandas as pd
7
  from smolagents import (
8
  ToolCallingAgent,
9
+ LiteLLMModel,
10
  DuckDuckGoSearchTool,
11
  WikipediaSearchTool,
12
  PythonInterpreterTool,
 
29
  class BasicAgent:
30
  def __init__(self):
31
  print("BasicAgent initialized.")
32
+ groq_api_key = os.getenv("GROQ_API_KEY")
33
+ if not groq_api_key:
34
+ raise ValueError("GROQ_API_KEY environment variable not set")
35
+ self.model = LiteLLMModel(
36
+ model_id="groq/llama-3.3-70b-versatile",
37
+ api_key=groq_api_key,
38
  )
39
+ self.tools = [
40
  DuckDuckGoSearchTool(),
41
  WikipediaSearchTool(),
42
  PythonInterpreterTool(),
43
  get_current_date_time,
44
  ]
45
+ self.agent = ToolCallingAgent(
46
+ tools=self.tools,
47
+ model=self.model,
48
+ max_steps=6,
49
+ )
50
+ print("BasicAgent ready with Groq Llama-3.3-70B.")
51
 
52
  def __call__(self, question: str) -> str:
53
+ print(f"Agent received question: {question[:80]}...")
54
+ try:
55
+ answer = self.agent.run(question)
56
+ print(f"Agent answer: {str(answer)[:200]}")
57
+ return str(answer)
58
+ except Exception as e:
59
+ print(f"Agent error: {e}")
60
+ return f"Error: {str(e)}"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
61
 
62
 
63
+ # --- The rest of the code (keep as-is) ---
64
  def run_and_submit_all(profile: gr.OAuthProfile | None):
65
  space_id = os.getenv("SPACE_ID")
 
66
  if profile:
67
  username = f"{profile.username}"
68
  print(f"User logged in: {username}")
69
  else:
70
  print("User not logged in.")
71
  return "Please Login to Hugging Face with the button.", None
 
72
  api_url = DEFAULT_API_URL
73
  questions_url = f"{api_url}/questions"
74
  submit_url = f"{api_url}/submit"
 
75
  try:
76
  agent = BasicAgent()
77
  except Exception as e:
78
  print(f"Error instantiating agent: {e}")
79
  return f"Error initializing agent: {e}", None
 
80
  agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
81
+ print(f"Agent code: {agent_code}")
 
82
  print(f"Fetching questions from: {questions_url}")
83
  try:
84
  response = requests.get(questions_url, timeout=15)
85
  response.raise_for_status()
86
  questions_data = response.json()
87
  if not questions_data:
88
+ print("No questions.")
89
+ return "No questions.", None
 
90
  except Exception as e:
91
  print(f"Error fetching questions: {e}")
92
  return f"Error fetching questions: {e}", None
 
93
  results_log = []
94
  answers_payload = []
95
  print(f"Running agent on {len(questions_data)} questions...")
96
+ for i, item in enumerate(questions_data):
97
  task_id = item.get("task_id")
98
  question_text = item.get("question")
99
+ if not task_id or not question_text:
 
100
  continue
101
  try:
102
  submitted_answer = agent(question_text)
103
  answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
104
  results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})
105
  except Exception as e:
106
+ print(f"Error on task {task_id}: {e}")
107
+ results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": f"ERROR: {e}"})
108
+ time.sleep(1)
 
 
109
  if not answers_payload:
110
+ return "No answers.", pd.DataFrame(results_log)
 
 
111
  submission_data = {"username": username.strip(), "agent_code": agent_code, "answers": answers_payload}
112
+ print(f"Submitting {len(answers_payload)} answers...")
 
 
 
113
  try:
114
  response = requests.post(submit_url, json=submission_data, timeout=60)
115
  response.raise_for_status()
 
117
  final_status = (
118
  f"Submission Successful!\n"
119
  f"User: {result_data.get('username')}\n"
120
+ f"Score: {result_data.get('score')}%\n"
121
+ f"Correct: {result_data.get('correct_count')}/{result_data.get('total_attempted')}\n"
122
+ f"Message: {result_data.get('message')}"
123
  )
124
+ print(final_status)
125
+ return final_status, pd.DataFrame(results_log)
 
126
  except Exception as e:
127
+ print(f"Submission error: {e}")
128
+ return f"Submission failed: {e}", pd.DataFrame(results_log)
 
 
129
 
130
 
131
+ # --- Build Gradio UI ---
132
  with gr.Blocks() as demo:
133
  gr.Markdown("# Basic Agent Evaluation Runner")
134
  gr.Markdown(
135
  """
136
+ **Instructions:**
137
+ 1. Clone this space and set `GROQ_API_KEY` in your Space secrets.
138
+ 2. Log in with your Hugging Face account below.
139
+ 3. Click 'Run Evaluation & Submit' to start.
140
+ """
 
 
 
 
141
  )
142
  gr.LoginButton()
143
  run_button = gr.Button("Run Evaluation & Submit All Answers")
144
  status_output = gr.Textbox(label="Run Status / Submission Result", lines=5, interactive=False)
 
145
  results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True)
146
  run_button.click(
147
  fn=run_and_submit_all,
148
  outputs=[status_output, results_table]
149
  )
150
+
151
  if __name__ == "__main__":
152
+ print("Starting Gradio app...")
153
+ demo.launch(debug=True, share=False)