WaelDahech commited on
Commit
8318d74
·
1 Parent(s): 18b9371

add openai req

Browse files
Files changed (1) hide show
  1. app.py +239 -43
app.py CHANGED
@@ -1,59 +1,49 @@
1
- from smolagents import CodeAgent,DuckDuckGoSearchTool, InferenceClientModel,load_tool,tool
2
- import datetime
3
  import requests
4
- import pytz
5
- import yaml
6
- from tools.final_answer import FinalAnswerTool
7
-
8
- from smolagents import Tool
9
-
10
- from Gradio_UI import GradioUI
11
 
12
- # Below is an example of a tool that does nothing. Amaze us with your creativity !
 
 
13
 
14
- final_answer = FinalAnswerTool()
15
 
 
 
16
 
17
- system_promot = """
18
- You are a helpful assistant tasked with answering questions using a set of tools.
19
- Now, I will ask you a question. Report your thoughts, and finish your answer with the following template:
20
- FINAL ANSWER: [YOUR FINAL ANSWER].
21
- YOUR FINAL ANSWER should be a number OR as few words as possible OR a comma separated list of numbers and/or strings. If you are asked for a number, don't use comma to write your number neither use units such as $ or percent sign unless specified otherwise. If you are asked for a string, don't use articles, neither abbreviations (e.g. for cities), and write the digits in plain text unless specified otherwise. If you are asked for a comma separated list, apply the above rules depending of whether the element to be put in the list is a number or a string.
22
- Your answer should only start with "FINAL ANSWER: ", then follows with the answer.
23
- """
24
 
25
- # Import tool from Hub
 
26
 
27
  with open("prompts.yaml", 'r') as stream:
28
  prompt_templates = yaml.safe_load(stream)
 
 
29
 
 
 
30
 
 
 
31
 
32
- # === Tool Definitions ===
33
-
34
-
35
- TOOL_REGISTRY = [
36
- Tool(name="wikipedia_search", entry_point="mytools.wikipedia_search.call"),
37
- Tool(name="youtube_transcript", entry_point="mytools.youtube_transcript.call"),
38
- Tool(name="video_frame_analyzer", entry_point="mytools.video_frame_analyzer.call"),
39
- Tool(name="string_manipulator", entry_point="mytools.string_manipulator.call"),
40
- Tool(name="vision_chess_engine", entry_point="mytools.vision_chess_engine.call"),
41
- Tool(name="table_parser", entry_point="mytools.table_parser.call"),
42
- Tool(name="libretext_fetcher", entry_point="mytools.libretext_fetcher.call"),
43
- Tool(name="audio_transcriber", entry_point="mytools.audio_transcriber.call"),
44
- Tool(name="botanical_classifier", entry_point="mytools.botanical_classifier.call"),
45
- Tool(name="imdb_lookup", entry_point="mytools.imdb_lookup.call"),
46
- Tool(name="excel_reader", entry_point="mytools.excel_reader.call"),
47
- Tool(name="competition_db", entry_point="mytools.competition_db.call"),
48
- Tool(name="japanese_baseball_api", entry_point="mytools.japanese_baseball_api.call"),
49
- ]
50
 
 
 
51
 
52
- model_id = "Qwen/Qwen2.5-Coder-32B-Instruct"
53
-
54
- agent = CodeAgent(
55
- model= InferenceClientModel(model_id=model_id),
56
- tools=[final_answer, *TOOL_REGISTRY], ## add your tools here (don't remove final answer)
57
  max_steps=6,
58
  verbosity_level=1,
59
  grammar=None,
@@ -62,6 +52,212 @@ agent = CodeAgent(
62
  description=None,
63
  prompt_templates=prompt_templates
64
  )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
65
 
 
66
 
67
- GradioUI(agent).launch(share=False)
 
 
1
+ import os
2
+ import gradio as gr
3
  import requests
4
+ import inspect
5
+ import pandas as pd
 
 
 
 
 
6
 
7
+ # (Keep Constants as is)
8
+ # --- Constants ---
9
+ DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
10
 
11
+ from my_tools import tools_list
12
 
13
+ from smolagents import Tool
14
+ from smolagents import CodeAgent,DuckDuckGoSearchTool, InferenceClientModel,load_tool,tool
15
 
16
+ # --- Basic Agent Definition ---
17
+ import yaml
18
+ #with open("prompts.yaml", 'r') as stream:
19
+ # prompt_templates = yaml.safe_load(stream)
 
 
 
20
 
21
+ import os
22
+ from dotenv import load_dotenv
23
 
24
  with open("prompts.yaml", 'r') as stream:
25
  prompt_templates = yaml.safe_load(stream)
26
+ # 1) load your .env (skip if you set it in the shell)
27
+ load_dotenv()
28
 
29
+ # 2) grab the key
30
+ openai_api_key = os.getenv("OPENAI_API_KEY")
31
 
32
+ # 3) build the Smolagents model
33
+ from smolagents import OpenAIServerModel
34
 
35
+ model = OpenAIServerModel(
36
+ model_id="gpt-4.1", # or "gpt-3.5-turbo", etc.
37
+ api_base="https://api.openai.com/v1", # OpenAI’s standard endpoint
38
+ api_key=openai_api_key # your secret key
39
+ ) # :contentReference[oaicite:1]{index=1}
 
 
 
 
 
 
 
 
 
 
 
 
 
40
 
41
+ # 4) create a CodeAgent powered by that model
42
+ from smolagents import CodeAgent, DuckDuckGoSearchTool
43
 
44
+ OpenAIAgent = CodeAgent(
45
+ tools=[DuckDuckGoSearchTool()], # any tools you want
46
+ model=model,
 
 
47
  max_steps=6,
48
  verbosity_level=1,
49
  grammar=None,
 
52
  description=None,
53
  prompt_templates=prompt_templates
54
  )
55
+ # you can allow extra imports if needed:
56
+ # additional_authorized_imports=["requests", "bs4"],
57
+
58
+ MyAgent = CodeAgent(
59
+ model= InferenceClientModel(model_id="Qwen/Qwen2.5-Coder-32B-Instruct"),
60
+ tools=[],
61
+ max_steps=6,
62
+ verbosity_level=1,
63
+ grammar=None,
64
+ planning_interval=None,
65
+ name=None,
66
+ description=None,
67
+ prompt_templates=None
68
+ )
69
+
70
+ class BasicAgent:
71
+ def __init__(self):
72
+ print("BasicAgent initialized.")
73
+ def __call__(self, question: str) -> str:
74
+ print(f"Agent received question (first 50 chars): {question[:50]}...")
75
+ fixed_answer = "This is a default answer."
76
+ print(f"Agent returning fixed answer: {fixed_answer}")
77
+ return fixed_answer
78
+
79
+ # ----- THIS IS WERE YOU CAN BUILD WHAT YOU WANT ------
80
+ class BasicAgent:
81
+ def __init__(self):
82
+ print("BasicAgent initialized.")
83
+ def __call__(self, question: str) -> str:
84
+ print(f"Agent received question (first 50 chars): {question[:50]}...")
85
+ fixed_answer = "This is a default answer."
86
+ print(f"Agent returning fixed answer: {fixed_answer}")
87
+ return fixed_answer
88
+
89
+ def run_and_submit_all( profile: gr.OAuthProfile | None):
90
+ """
91
+ Fetches all questions, runs the BasicAgent on them, submits all answers,
92
+ and displays the results.
93
+ """
94
+ # --- Determine HF Space Runtime URL and Repo URL ---
95
+ space_id = os.getenv("SPACE_ID") # Get the SPACE_ID for sending link to the code
96
+
97
+ if profile:
98
+ username= f"{profile.username}"
99
+ print(f"User logged in: {username}")
100
+ else:
101
+ print("User not logged in.")
102
+ return "Please Login to Hugging Face with the button.", None
103
+
104
+ api_url = DEFAULT_API_URL
105
+ questions_url = f"{api_url}/questions"
106
+ submit_url = f"{api_url}/submit"
107
+
108
+ # 1. Instantiate Agent ( modify this part to create your agent)
109
+ try:
110
+ agent = OpenAIAgent()
111
+ except Exception as e:
112
+ print(f"Error instantiating agent: {e}")
113
+ return f"Error initializing agent: {e}", None
114
+ # In the case of an app running as a hugging Face space, this link points toward your codebase ( usefull for others so please keep it public)
115
+ agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
116
+ print(agent_code)
117
+
118
+ # 2. Fetch Questions
119
+ print(f"Fetching questions from: {questions_url}")
120
+ try:
121
+ response = requests.get(questions_url, timeout=15)
122
+ response.raise_for_status()
123
+ questions_data = response.json()
124
+ if not questions_data:
125
+ print("Fetched questions list is empty.")
126
+ return "Fetched questions list is empty or invalid format.", None
127
+ print(f"Fetched {len(questions_data)} questions.")
128
+ except requests.exceptions.RequestException as e:
129
+ print(f"Error fetching questions: {e}")
130
+ return f"Error fetching questions: {e}", None
131
+ except requests.exceptions.JSONDecodeError as e:
132
+ print(f"Error decoding JSON response from questions endpoint: {e}")
133
+ print(f"Response text: {response.text[:500]}")
134
+ return f"Error decoding server response for questions: {e}", None
135
+ except Exception as e:
136
+ print(f"An unexpected error occurred fetching questions: {e}")
137
+ return f"An unexpected error occurred fetching questions: {e}", None
138
+
139
+ # 3. Run your Agent
140
+ results_log = []
141
+ answers_payload = []
142
+ print(f"Running agent on {len(questions_data)} questions...")
143
+ for item in questions_data:
144
+ task_id = item.get("task_id")
145
+ question_text = item.get("question")
146
+ if not task_id or question_text is None:
147
+ print(f"Skipping item with missing task_id or question: {item}")
148
+ continue
149
+ try:
150
+ submitted_answer = agent(question_text)
151
+ answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
152
+ results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})
153
+ except Exception as e:
154
+ print(f"Error running agent on task {task_id}: {e}")
155
+ results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": f"AGENT ERROR: {e}"})
156
+
157
+ if not answers_payload:
158
+ print("Agent did not produce any answers to submit.")
159
+ return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)
160
+
161
+ # 4. Prepare Submission
162
+ submission_data = {"username": username.strip(), "agent_code": agent_code, "answers": answers_payload}
163
+ status_update = f"Agent finished. Submitting {len(answers_payload)} answers for user '{username}'..."
164
+ print(status_update)
165
+
166
+ # 5. Submit
167
+ print(f"Submitting {len(answers_payload)} answers to: {submit_url}")
168
+ try:
169
+ response = requests.post(submit_url, json=submission_data, timeout=60)
170
+ response.raise_for_status()
171
+ result_data = response.json()
172
+ final_status = (
173
+ f"Submission Successful!\n"
174
+ f"User: {result_data.get('username')}\n"
175
+ f"Overall Score: {result_data.get('score', 'N/A')}% "
176
+ f"({result_data.get('correct_count', '?')}/{result_data.get('total_attempted', '?')} correct)\n"
177
+ f"Message: {result_data.get('message', 'No message received.')}"
178
+ )
179
+ print("Submission successful.")
180
+ results_df = pd.DataFrame(results_log)
181
+ return final_status, results_df
182
+ except requests.exceptions.HTTPError as e:
183
+ error_detail = f"Server responded with status {e.response.status_code}."
184
+ try:
185
+ error_json = e.response.json()
186
+ error_detail += f" Detail: {error_json.get('detail', e.response.text)}"
187
+ except requests.exceptions.JSONDecodeError:
188
+ error_detail += f" Response: {e.response.text[:500]}"
189
+ status_message = f"Submission Failed: {error_detail}"
190
+ print(status_message)
191
+ results_df = pd.DataFrame(results_log)
192
+ return status_message, results_df
193
+ except requests.exceptions.Timeout:
194
+ status_message = "Submission Failed: The request timed out."
195
+ print(status_message)
196
+ results_df = pd.DataFrame(results_log)
197
+ return status_message, results_df
198
+ except requests.exceptions.RequestException as e:
199
+ status_message = f"Submission Failed: Network error - {e}"
200
+ print(status_message)
201
+ results_df = pd.DataFrame(results_log)
202
+ return status_message, results_df
203
+ except Exception as e:
204
+ status_message = f"An unexpected error occurred during submission: {e}"
205
+ print(status_message)
206
+ results_df = pd.DataFrame(results_log)
207
+ return status_message, results_df
208
+
209
+
210
+ # --- Build Gradio Interface using Blocks ---
211
+ with gr.Blocks() as demo:
212
+ gr.Markdown("# Basic Agent Evaluation Runner")
213
+ gr.Markdown(
214
+ """
215
+ **Instructions:**
216
+
217
+ 1. Please clone this space, then modify the code to define your agent's logic, the tools, the necessary packages, etc ...
218
+ 2. Log in to your Hugging Face account using the button below. This uses your HF username for submission.
219
+ 3. Click 'Run Evaluation & Submit All Answers' to fetch questions, run your agent, submit answers, and see the score.
220
+
221
+ ---
222
+ **Disclaimers:**
223
+ 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).
224
+ 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.
225
+ """
226
+ )
227
+
228
+ gr.LoginButton()
229
+
230
+ run_button = gr.Button("Run Evaluation & Submit All Answers")
231
+
232
+ status_output = gr.Textbox(label="Run Status / Submission Result", lines=5, interactive=False)
233
+ # Removed max_rows=10 from DataFrame constructor
234
+ results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True)
235
+
236
+ run_button.click(
237
+ fn=run_and_submit_all,
238
+ outputs=[status_output, results_table]
239
+ )
240
+
241
+ if __name__ == "__main__":
242
+ print("\n" + "-"*30 + " App Starting " + "-"*30)
243
+ # Check for SPACE_HOST and SPACE_ID at startup for information
244
+ space_host_startup = os.getenv("SPACE_HOST")
245
+ space_id_startup = os.getenv("SPACE_ID") # Get SPACE_ID at startup
246
+
247
+ if space_host_startup:
248
+ print(f"✅ SPACE_HOST found: {space_host_startup}")
249
+ print(f" Runtime URL should be: https://{space_host_startup}.hf.space")
250
+ else:
251
+ print("ℹ️ SPACE_HOST environment variable not found (running locally?).")
252
+
253
+ if space_id_startup: # Print repo URLs if SPACE_ID is found
254
+ print(f"✅ SPACE_ID found: {space_id_startup}")
255
+ print(f" Repo URL: https://huggingface.co/spaces/{space_id_startup}")
256
+ print(f" Repo Tree URL: https://huggingface.co/spaces/{space_id_startup}/tree/main")
257
+ else:
258
+ print("ℹ️ SPACE_ID environment variable not found (running locally?). Repo URL cannot be determined.")
259
 
260
+ print("-"*(60 + len(" App Starting ")) + "\n")
261
 
262
+ print("Launching Gradio Interface for Basic Agent Evaluation...")
263
+ demo.launch(debug=True, share=False)