José Ángel González commited on
Commit
31d215e
·
1 Parent(s): 5a10929

first submission

Browse files
.gitattributes copy ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ *.7z filter=lfs diff=lfs merge=lfs -text
2
+ *.arrow filter=lfs diff=lfs merge=lfs -text
3
+ *.bin filter=lfs diff=lfs merge=lfs -text
4
+ *.bz2 filter=lfs diff=lfs merge=lfs -text
5
+ *.ckpt filter=lfs diff=lfs merge=lfs -text
6
+ *.ftz filter=lfs diff=lfs merge=lfs -text
7
+ *.gz filter=lfs diff=lfs merge=lfs -text
8
+ *.h5 filter=lfs diff=lfs merge=lfs -text
9
+ *.joblib filter=lfs diff=lfs merge=lfs -text
10
+ *.lfs.* filter=lfs diff=lfs merge=lfs -text
11
+ *.mlmodel filter=lfs diff=lfs merge=lfs -text
12
+ *.model filter=lfs diff=lfs merge=lfs -text
13
+ *.msgpack filter=lfs diff=lfs merge=lfs -text
14
+ *.npy filter=lfs diff=lfs merge=lfs -text
15
+ *.npz filter=lfs diff=lfs merge=lfs -text
16
+ *.onnx filter=lfs diff=lfs merge=lfs -text
17
+ *.ot filter=lfs diff=lfs merge=lfs -text
18
+ *.parquet filter=lfs diff=lfs merge=lfs -text
19
+ *.pb filter=lfs diff=lfs merge=lfs -text
20
+ *.pickle filter=lfs diff=lfs merge=lfs -text
21
+ *.pkl filter=lfs diff=lfs merge=lfs -text
22
+ *.pt filter=lfs diff=lfs merge=lfs -text
23
+ *.pth filter=lfs diff=lfs merge=lfs -text
24
+ *.rar filter=lfs diff=lfs merge=lfs -text
25
+ *.safetensors filter=lfs diff=lfs merge=lfs -text
26
+ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
27
+ *.tar.* filter=lfs diff=lfs merge=lfs -text
28
+ *.tar filter=lfs diff=lfs merge=lfs -text
29
+ *.tflite filter=lfs diff=lfs merge=lfs -text
30
+ *.tgz filter=lfs diff=lfs merge=lfs -text
31
+ *.wasm filter=lfs diff=lfs merge=lfs -text
32
+ *.xz filter=lfs diff=lfs merge=lfs -text
33
+ *.zip filter=lfs diff=lfs merge=lfs -text
34
+ *.zst filter=lfs diff=lfs merge=lfs -text
35
+ *tfevents* filter=lfs diff=lfs merge=lfs -text
README.md CHANGED
@@ -1,14 +1,13 @@
1
  ---
2
- title: SmolAgentsCourse
3
- emoji: 📉
4
  colorFrom: indigo
5
- colorTo: yellow
6
  sdk: gradio
7
- sdk_version: 5.27.0
8
  app_file: app.py
9
  pinned: false
10
- license: apache-2.0
11
- short_description: Course submissions
 
12
  ---
13
-
14
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
1
  ---
2
+ title: Template Final Assignment
3
+ emoji: 🕵🏻‍♂️
4
  colorFrom: indigo
5
+ colorTo: indigo
6
  sdk: gradio
7
+ sdk_version: 5.25.2
8
  app_file: app.py
9
  pinned: false
10
+ hf_oauth: true
11
+ # optional, default duration is 8 hours/480 minutes. Max duration is 30 days/43200 minutes.
12
+ hf_oauth_expiration_minutes: 480
13
  ---
 
 
agents/__init__.py ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ from .llm_only import LLMOnly
2
+ from .react_agent import ReactAgent
agents/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (225 Bytes). View file
 
agents/__pycache__/llm_only.cpython-310.pyc ADDED
Binary file (1.87 kB). View file
 
agents/llm_only.py ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from openai import OpenAI
2
+ from pydantic import BaseModel
3
+
4
+ MODEL = "gpt-4o"
5
+ SYSTEM_PROMPT = "You are a general AI assistant. I will ask you a question. Report your thoughts, and write your final answer. 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."
6
+
7
+ class OutputSchema(BaseModel):
8
+ thoughts: str
9
+ final_answer: str
10
+
11
+ class LLMOnly:
12
+ def __init__(self):
13
+ self.client = OpenAI()
14
+
15
+ def __call__(self, question: str) -> str:
16
+ response = self.client.beta.chat.completions.parse(
17
+ model=MODEL,
18
+ messages=[
19
+ {"role": "system", "content": SYSTEM_PROMPT},
20
+ {"role": "user", "content": question}
21
+ ],
22
+ response_format=OutputSchema
23
+ )
24
+ answer = response.choices[0].message.parsed
25
+ return answer
agents/react_agent.py ADDED
@@ -0,0 +1,163 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ React-Agent based solution for the smolagents course.
3
+
4
+ Based on two pillars:
5
+
6
+ 1) Avoid unnecessary logic inside the agent's react flow. Why we have to let the LLM to decide how to load/parse
7
+ specific files if we can do that beforehand and we can prepare it accordingly? Less prone to errors, shorter
8
+ reasoning paths, and more accurate.
9
+
10
+ 2) Stronger LLMs are all you need. GPT-4o does not work very well with the system prompt of smolagents,
11
+ but GPT-4.5 yes! The sentence of "or your mom will die" in the steered system prompt is just for GPT-4o to work :)
12
+
13
+ """
14
+
15
+ from smolagents import (
16
+ OpenAIServerModel,
17
+ CodeAgent,
18
+ DuckDuckGoSearchTool,
19
+ PythonInterpreterTool,
20
+ Tool
21
+ )
22
+ from PIL import Image
23
+ import requests
24
+ from io import BytesIO
25
+ import os
26
+ from pathlib import Path
27
+ import pandas as pd
28
+
29
+
30
+ # Utils
31
+ def parse_image(content: bytes) -> Image:
32
+ return Image.open(BytesIO(content)).convert("RGB")
33
+
34
+
35
+ def parse_excel(content: bytes) -> str:
36
+ return pd.read_excel(BytesIO(content)).to_markdown(index=False)
37
+
38
+
39
+ def parse_text(content: str) -> str:
40
+ return content
41
+
42
+ def parse_mp3(content: bytes) -> str:
43
+ speech_to_text = Tool.from_space(
44
+ "maguid28/TranscriptTool",
45
+ name="transcription_tool",
46
+ description="Transcribe speech to text"
47
+ )
48
+ with open("audio.mp3", "wb") as fw:
49
+ fw.write(content)
50
+ return speech_to_text("audio.mp3")
51
+
52
+ def download(task_id: str) -> bytes:
53
+ response = requests.get(FILE_URL.format(task_id=task_id))
54
+ return response.content
55
+
56
+
57
+ def get_type_and_parser(file_name: str) -> dict:
58
+ path = Path(file_name)
59
+ return EXTENSIONS[path.suffix]
60
+
61
+
62
+ # Configs
63
+ EXTENSIONS = {
64
+ ".png": {"type": "image", "parser": parse_image},
65
+ ".jpg": {"type": "image", "parser": parse_image},
66
+ ".jpeg": {"type": "image", "parser": parse_image},
67
+ ".xlsx": {"type": "document", "parser": parse_excel},
68
+ ".txt": {"type": "document", "parser": parse_text},
69
+ ".py": {"type": "document", "parser": parse_text},
70
+ ".mp3": {"type": "audio", "parser": parse_mp3},
71
+ }
72
+ DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
73
+ FILE_URL = f"{DEFAULT_API_URL}/files/{{task_id}}"
74
+
75
+ # Tools
76
+ TOOLS = [DuckDuckGoSearchTool(), PythonInterpreterTool()]
77
+ AUTHORIZED_IMPORTS = [
78
+ "geopandas",
79
+ "plotly",
80
+ "shapely",
81
+ "json",
82
+ "pandas",
83
+ "numpy",
84
+ "datetime",
85
+ ]
86
+
87
+
88
+ class ReactAgent:
89
+ def __init__(self):
90
+ model = OpenAIServerModel(
91
+ model_id="gpt-4o",
92
+ api_key=os.environ["OPENAI_API_KEY"],
93
+ temperature=0,
94
+ )
95
+ self.agent = CodeAgent(
96
+ model=model,
97
+ tools=TOOLS,
98
+ additional_authorized_imports=AUTHORIZED_IMPORTS,
99
+ max_steps=20,
100
+ verbosity_level=2,
101
+ )
102
+ self.steer_system_prompt()
103
+
104
+ def __call__(self, question: dict) -> str:
105
+ file_name = question.get("file_name")
106
+
107
+ if file_name:
108
+ content = download(question["task_id"])
109
+ file_info = get_type_and_parser(file_name)
110
+ parsed_content = file_info["parser"](content)
111
+ user_question = question["question"]
112
+ if file_info["type"] == "image":
113
+ parsed_content.save("image.png")
114
+ return self.agent.run(user_question, images=[parsed_content])
115
+
116
+ user_question = (
117
+ f"{user_question}\n"
118
+ f"Here is the content of the file you have to consider to answer the question:\n"
119
+ f"{parsed_content}"
120
+ )
121
+ return self.agent.run(user_question)
122
+
123
+ return self.agent.run(question)
124
+
125
+ def steer_system_prompt(self):
126
+ prev_system_prompt = self.agent.system_prompt
127
+ prompt_prefix = prev_system_prompt.split("Now Begin!")[0].strip()
128
+ gaia_answer_rules = """\n\nYour 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."""
129
+ gaia_answer_rules = """It is crucial that you wrap your final answer in the ```code``` block by using the `final_answer` tool or your mom will die."""
130
+ system_prompt = prompt_prefix + gaia_answer_rules + "\n\nNow Begin!"
131
+ self.agent.system_prompt = system_prompt
132
+
133
+ if __name__ == "__main__":
134
+ question1 = {
135
+ "task_id": "7bd855d8-463d-4ed5-93ca-5fe35145f733",
136
+ "question": "The attached Excel file contains the sales of menu items for a local fast-food chain. What were the total sales that the chain made from food (not including drinks)? Express your answer in USD with two decimal places.",
137
+ "Level": "1",
138
+ "file_name": "7bd855d8-463d-4ed5-93ca-5fe35145f733.xlsx",
139
+ }
140
+
141
+ question2 = {
142
+ "task_id": "cca530fc-4052-43b2-b130-b30968d8aa44",
143
+ "question": "Review the chess position provided in the image. It is black's turn. Provide the correct next move for black which guarantees a win. Please provide your response in algebraic notation.",
144
+ "Level": "1",
145
+ "file_name": "cca530fc-4052-43b2-b130-b30968d8aa44.png",
146
+ }
147
+
148
+ question3 = {
149
+ "task_id": "f918266a-b3e0-4914-865d-4faa564f1aef",
150
+ "question": "What is the final numeric output from the attached Python code?",
151
+ "Level": "1",
152
+ "file_name": "f918266a-b3e0-4914-865d-4faa564f1aef.py",
153
+ }
154
+
155
+ question4 = {
156
+ "task_id": "99c9cc74-fdc8-46c6-8f8d-3ce2d3bfeea3",
157
+ "question": 'Hi, I\'m making a pie but I could use some help with my shopping list. I have everything I need for the crust, but I\'m not sure about the filling. I got the recipe from my friend Aditi, but she left it as a voice memo and the speaker on my phone is buzzing so I can\'t quite make out what she\'s saying. Could you please listen to the recipe and list all of the ingredients that my friend described? I only want the ingredients for the filling, as I have everything I need to make my favorite pie crust. I\'ve attached the recipe as Strawberry pie.mp3.\n\nIn your response, please only list the ingredients, not any measurements. So if the recipe calls for "a pinch of salt" or "two cups of ripe strawberries" the ingredients on the list would be "salt" and "ripe strawberries".\n\nPlease format your response as a comma separated list of ingredients. Also, please alphabetize the ingredients.',
158
+ "Level": "1",
159
+ "file_name": "99c9cc74-fdc8-46c6-8f8d-3ce2d3bfeea3.mp3",
160
+ }
161
+
162
+ agent = ReactAgent()
163
+ response = agent(question4)
app.py ADDED
@@ -0,0 +1,186 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import gradio as gr
3
+ import requests
4
+ import inspect
5
+ import pandas as pd
6
+ from agents import ReactAgent
7
+
8
+ # (Keep Constants as is)
9
+ # --- Constants ---
10
+ DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
11
+
12
+
13
+ def run_and_submit_all(profile: gr.OAuthProfile | None):
14
+ """
15
+ Fetches all questions, runs the BasicAgent on them, submits all answers,
16
+ and displays the results.
17
+ """
18
+ # --- Determine HF Space Runtime URL and Repo URL ---
19
+ space_id = os.getenv("SPACE_ID") # Get the SPACE_ID for sending link to the code
20
+
21
+ if profile:
22
+ username= f"{profile.username}"
23
+ print(f"User logged in: {username}")
24
+ else:
25
+ print("User not logged in.")
26
+ return "Please Login to Hugging Face with the button.", None
27
+
28
+ api_url = DEFAULT_API_URL
29
+ questions_url = f"{api_url}/questions"
30
+ submit_url = f"{api_url}/submit"
31
+
32
+ # 1. Instantiate Agent ( modify this part to create your agent)
33
+ try:
34
+ agent = ReactAgent()
35
+ except Exception as e:
36
+ print(f"Error instantiating agent: {e}")
37
+ return f"Error initializing agent: {e}", None
38
+ # 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)
39
+ agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
40
+ print(agent_code)
41
+
42
+ # 2. Fetch Questions
43
+ print(f"Fetching questions from: {questions_url}")
44
+ try:
45
+ response = requests.get(questions_url, timeout=15)
46
+ response.raise_for_status()
47
+ questions_data = response.json()
48
+ if not questions_data:
49
+ print("Fetched questions list is empty.")
50
+ return "Fetched questions list is empty or invalid format.", None
51
+ print(f"Fetched {len(questions_data)} questions.")
52
+ except requests.exceptions.RequestException as e:
53
+ print(f"Error fetching questions: {e}")
54
+ return f"Error fetching questions: {e}", None
55
+ except requests.exceptions.JSONDecodeError as e:
56
+ print(f"Error decoding JSON response from questions endpoint: {e}")
57
+ print(f"Response text: {response.text[:500]}")
58
+ return f"Error decoding server response for questions: {e}", None
59
+ except Exception as e:
60
+ print(f"An unexpected error occurred fetching questions: {e}")
61
+ return f"An unexpected error occurred fetching questions: {e}", None
62
+
63
+ # 3. Run your Agent
64
+ results_log = []
65
+ answers_payload = []
66
+ print(f"Running agent on {len(questions_data)} questions...")
67
+ for item in questions_data:
68
+ task_id = item.get("task_id")
69
+ question_text = item.get("question")
70
+ if not task_id or question_text is None:
71
+ print(f"Skipping item with missing task_id or question: {item}")
72
+ continue
73
+ try:
74
+ submitted_answer = agent(item)
75
+ answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
76
+ results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})
77
+ except Exception as e:
78
+ print(f"Error running agent on task {task_id}: {e}")
79
+ results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": f"AGENT ERROR: {e}"})
80
+
81
+ if not answers_payload:
82
+ print("Agent did not produce any answers to submit.")
83
+ return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)
84
+
85
+ # 4. Prepare Submission
86
+ submission_data = {"username": username.strip(), "agent_code": agent_code, "answers": answers_payload}
87
+ status_update = f"Agent finished. Submitting {len(answers_payload)} answers for user '{username}'..."
88
+ print(status_update)
89
+
90
+ # 5. Submit
91
+ print(f"Submitting {len(answers_payload)} answers to: {submit_url}")
92
+ try:
93
+ response = requests.post(submit_url, json=submission_data, timeout=60)
94
+ response.raise_for_status()
95
+ result_data = response.json()
96
+ final_status = (
97
+ f"Submission Successful!\n"
98
+ f"User: {result_data.get('username')}\n"
99
+ f"Overall Score: {result_data.get('score', 'N/A')}% "
100
+ f"({result_data.get('correct_count', '?')}/{result_data.get('total_attempted', '?')} correct)\n"
101
+ f"Message: {result_data.get('message', 'No message received.')}"
102
+ )
103
+ print("Submission successful.")
104
+ results_df = pd.DataFrame(results_log)
105
+ return final_status, results_df
106
+ except requests.exceptions.HTTPError as e:
107
+ error_detail = f"Server responded with status {e.response.status_code}."
108
+ try:
109
+ error_json = e.response.json()
110
+ error_detail += f" Detail: {error_json.get('detail', e.response.text)}"
111
+ except requests.exceptions.JSONDecodeError:
112
+ error_detail += f" Response: {e.response.text[:500]}"
113
+ status_message = f"Submission Failed: {error_detail}"
114
+ print(status_message)
115
+ results_df = pd.DataFrame(results_log)
116
+ return status_message, results_df
117
+ except requests.exceptions.Timeout:
118
+ status_message = "Submission Failed: The request timed out."
119
+ print(status_message)
120
+ results_df = pd.DataFrame(results_log)
121
+ return status_message, results_df
122
+ except requests.exceptions.RequestException as e:
123
+ status_message = f"Submission Failed: Network error - {e}"
124
+ print(status_message)
125
+ results_df = pd.DataFrame(results_log)
126
+ return status_message, results_df
127
+ except Exception as e:
128
+ status_message = f"An unexpected error occurred during submission: {e}"
129
+ print(status_message)
130
+ results_df = pd.DataFrame(results_log)
131
+ return status_message, results_df
132
+
133
+ # --- Build Gradio Interface using Blocks ---
134
+ with gr.Blocks() as demo:
135
+ gr.Markdown("# Basic Agent Evaluation Runner")
136
+ gr.Markdown(
137
+ """
138
+ **Instructions:**
139
+
140
+ 1. Please clone this space, then modify the code to define your agent's logic, the tools, the necessary packages, etc ...
141
+ 2. Log in to your Hugging Face account using the button below. This uses your HF username for submission.
142
+ 3. Click 'Run Evaluation & Submit All Answers' to fetch questions, run your agent, submit answers, and see the score.
143
+
144
+ ---
145
+ **Disclaimers:**
146
+ 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).
147
+ 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.
148
+ """
149
+ )
150
+
151
+ gr.LoginButton()
152
+
153
+ run_button = gr.Button("Run Evaluation & Submit All Answers")
154
+
155
+ status_output = gr.Textbox(label="Run Status / Submission Result", lines=5, interactive=False)
156
+ # Removed max_rows=10 from DataFrame constructor
157
+ results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True)
158
+
159
+ run_button.click(
160
+ fn=run_and_submit_all,
161
+ outputs=[status_output, results_table]
162
+ )
163
+
164
+ if __name__ == "__main__":
165
+ print("\n" + "-"*30 + " App Starting " + "-"*30)
166
+ # Check for SPACE_HOST and SPACE_ID at startup for information
167
+ space_host_startup = os.getenv("SPACE_HOST")
168
+ space_id_startup = os.getenv("SPACE_ID") # Get SPACE_ID at startup
169
+
170
+ if space_host_startup:
171
+ print(f"✅ SPACE_HOST found: {space_host_startup}")
172
+ print(f" Runtime URL should be: https://{space_host_startup}.hf.space")
173
+ else:
174
+ print("ℹ️ SPACE_HOST environment variable not found (running locally?).")
175
+
176
+ if space_id_startup: # Print repo URLs if SPACE_ID is found
177
+ print(f"✅ SPACE_ID found: {space_id_startup}")
178
+ print(f" Repo URL: https://huggingface.co/spaces/{space_id_startup}")
179
+ print(f" Repo Tree URL: https://huggingface.co/spaces/{space_id_startup}/tree/main")
180
+ else:
181
+ print("ℹ️ SPACE_ID environment variable not found (running locally?). Repo URL cannot be determined.")
182
+
183
+ print("-"*(60 + len(" App Starting ")) + "\n")
184
+
185
+ print("Launching Gradio Interface for Basic Agent Evaluation...")
186
+ demo.launch(debug=True, share=False)
requirements.txt ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ gradio
2
+ requests
3
+ langgraph
4
+ openai
5
+ langchain-openai
6
+ langchain-community
7
+ langchain-experimental
8
+ duckduckgo-search
9
+ langchain
10
+ pydantic
11
+ smolagents
12
+ pandas
13
+ openpyxl
14
+ tabulate