Spaces:
Sleeping
Sleeping
Sivaraj
commited on
Commit
·
a6fe20b
1
Parent(s):
81917a3
Initial Commit
Browse files- .gitignore +6 -0
- README.md +1 -1
- agent.py +45 -0
- app.py +51 -39
- requirements.txt +3 -1
- src/config/__init__.py +7 -0
- src/config/model.py +7 -0
- tool.py +24 -0
.gitignore
ADDED
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Ignore Python cache files
|
2 |
+
*.pyc
|
3 |
+
__pycache__
|
4 |
+
|
5 |
+
.venv
|
6 |
+
.env
|
README.md
CHANGED
@@ -4,7 +4,7 @@ emoji: 🕵🏻♂️
|
|
4 |
colorFrom: indigo
|
5 |
colorTo: indigo
|
6 |
sdk: gradio
|
7 |
-
sdk_version: 5.
|
8 |
app_file: app.py
|
9 |
pinned: false
|
10 |
hf_oauth: true
|
|
|
4 |
colorFrom: indigo
|
5 |
colorTo: indigo
|
6 |
sdk: gradio
|
7 |
+
sdk_version: 5.34.0
|
8 |
app_file: app.py
|
9 |
pinned: false
|
10 |
hf_oauth: true
|
agent.py
ADDED
@@ -0,0 +1,45 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from smolagents import (
|
2 |
+
ToolCallingAgent,
|
3 |
+
PromptTemplates,
|
4 |
+
PlanningPromptTemplate,
|
5 |
+
ManagedAgentPromptTemplate,
|
6 |
+
FinalAnswerPromptTemplate,
|
7 |
+
)
|
8 |
+
|
9 |
+
from tool import addition_tool
|
10 |
+
from src.config.model import openai_model
|
11 |
+
|
12 |
+
|
13 |
+
# --- Basic Agent Definition ---
|
14 |
+
# ----- THIS IS WERE YOU CAN BUILD WHAT YOU WANT ------
|
15 |
+
class BaseAgent:
|
16 |
+
def __init__(self):
|
17 |
+
print("BaseAgent initialized.")
|
18 |
+
self.agent = ToolCallingAgent(
|
19 |
+
model=openai_model,
|
20 |
+
tools=[
|
21 |
+
addition_tool,
|
22 |
+
],
|
23 |
+
verbosity_level=2,
|
24 |
+
prompt_templates=PromptTemplates(
|
25 |
+
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: FINAL ANSWER: [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.",
|
26 |
+
# planning=PlanningPromptTemplate(
|
27 |
+
# initial_plan="",
|
28 |
+
# update_plan_pre_messages="",
|
29 |
+
# update_plan_post_messages="",
|
30 |
+
# ),
|
31 |
+
# managed_agent=ManagedAgentPromptTemplate(
|
32 |
+
# task="",
|
33 |
+
# report="",
|
34 |
+
# ),
|
35 |
+
# final_answer=FinalAnswerPromptTemplate(
|
36 |
+
# pre_messages="", post_messages=""
|
37 |
+
# ),
|
38 |
+
),
|
39 |
+
)
|
40 |
+
|
41 |
+
def run(self, question: str) -> str:
|
42 |
+
print(f"Agent received question (first 50 chars): {question[:50]}...")
|
43 |
+
response = self.agent.run(question)
|
44 |
+
print(f"Agent returning response: {response}")
|
45 |
+
return response.replace("FINAL ANSWER:", "").strip()
|
app.py
CHANGED
@@ -3,32 +3,23 @@ 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 |
-
|
12 |
-
|
13 |
-
class BasicAgent:
|
14 |
-
def __init__(self):
|
15 |
-
print("BasicAgent initialized.")
|
16 |
-
def __call__(self, question: str) -> str:
|
17 |
-
print(f"Agent received question (first 50 chars): {question[:50]}...")
|
18 |
-
fixed_answer = "This is a default answer."
|
19 |
-
print(f"Agent returning fixed answer: {fixed_answer}")
|
20 |
-
return fixed_answer
|
21 |
-
|
22 |
-
def run_and_submit_all( profile: gr.OAuthProfile | None):
|
23 |
"""
|
24 |
Fetches all questions, runs the BasicAgent on them, submits all answers,
|
25 |
and displays the results.
|
26 |
"""
|
27 |
# --- Determine HF Space Runtime URL and Repo URL ---
|
28 |
-
space_id = os.getenv("SPACE_ID")
|
29 |
|
30 |
if profile:
|
31 |
-
username= f"{profile.username}"
|
32 |
print(f"User logged in: {username}")
|
33 |
else:
|
34 |
print("User not logged in.")
|
@@ -40,7 +31,7 @@ def run_and_submit_all( profile: gr.OAuthProfile | None):
|
|
40 |
|
41 |
# 1. Instantiate Agent ( modify this part to create your agent)
|
42 |
try:
|
43 |
-
|
44 |
except Exception as e:
|
45 |
print(f"Error instantiating agent: {e}")
|
46 |
return f"Error initializing agent: {e}", None
|
@@ -55,16 +46,16 @@ def run_and_submit_all( profile: gr.OAuthProfile | None):
|
|
55 |
response.raise_for_status()
|
56 |
questions_data = response.json()
|
57 |
if not questions_data:
|
58 |
-
|
59 |
-
|
60 |
print(f"Fetched {len(questions_data)} questions.")
|
61 |
except requests.exceptions.RequestException as e:
|
62 |
print(f"Error fetching questions: {e}")
|
63 |
return f"Error fetching questions: {e}", None
|
64 |
except requests.exceptions.JSONDecodeError as e:
|
65 |
-
|
66 |
-
|
67 |
-
|
68 |
except Exception as e:
|
69 |
print(f"An unexpected error occurred fetching questions: {e}")
|
70 |
return f"An unexpected error occurred fetching questions: {e}", None
|
@@ -80,19 +71,37 @@ def run_and_submit_all( profile: gr.OAuthProfile | None):
|
|
80 |
print(f"Skipping item with missing task_id or question: {item}")
|
81 |
continue
|
82 |
try:
|
83 |
-
submitted_answer =
|
84 |
-
answers_payload.append(
|
85 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
86 |
except Exception as e:
|
87 |
-
|
88 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
89 |
|
90 |
if not answers_payload:
|
91 |
print("Agent did not produce any answers to submit.")
|
92 |
return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)
|
93 |
|
94 |
-
# 4. Prepare Submission
|
95 |
-
submission_data = {
|
|
|
|
|
|
|
|
|
96 |
status_update = f"Agent finished. Submitting {len(answers_payload)} answers for user '{username}'..."
|
97 |
print(status_update)
|
98 |
|
@@ -162,20 +171,19 @@ with gr.Blocks() as demo:
|
|
162 |
|
163 |
run_button = gr.Button("Run Evaluation & Submit All Answers")
|
164 |
|
165 |
-
status_output = gr.Textbox(
|
|
|
|
|
166 |
# Removed max_rows=10 from DataFrame constructor
|
167 |
results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True)
|
168 |
|
169 |
-
run_button.click(
|
170 |
-
fn=run_and_submit_all,
|
171 |
-
outputs=[status_output, results_table]
|
172 |
-
)
|
173 |
|
174 |
if __name__ == "__main__":
|
175 |
-
print("\n" + "-"*30 + " App Starting " + "-"*30)
|
176 |
# Check for SPACE_HOST and SPACE_ID at startup for information
|
177 |
space_host_startup = os.getenv("SPACE_HOST")
|
178 |
-
space_id_startup = os.getenv("SPACE_ID")
|
179 |
|
180 |
if space_host_startup:
|
181 |
print(f"✅ SPACE_HOST found: {space_host_startup}")
|
@@ -183,14 +191,18 @@ if __name__ == "__main__":
|
|
183 |
else:
|
184 |
print("ℹ️ SPACE_HOST environment variable not found (running locally?).")
|
185 |
|
186 |
-
if space_id_startup:
|
187 |
print(f"✅ SPACE_ID found: {space_id_startup}")
|
188 |
print(f" Repo URL: https://huggingface.co/spaces/{space_id_startup}")
|
189 |
-
print(
|
|
|
|
|
190 |
else:
|
191 |
-
print(
|
|
|
|
|
192 |
|
193 |
-
print("-"*(60 + len(" App Starting ")) + "\n")
|
194 |
|
195 |
print("Launching Gradio Interface for Basic Agent Evaluation...")
|
196 |
-
demo.launch(debug=True, share=False)
|
|
|
3 |
import requests
|
4 |
import inspect
|
5 |
import pandas as pd
|
6 |
+
from agent import BaseAgent
|
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.")
|
|
|
31 |
|
32 |
# 1. Instantiate Agent ( modify this part to create your agent)
|
33 |
try:
|
34 |
+
base_agent = BaseAgent()
|
35 |
except Exception as e:
|
36 |
print(f"Error instantiating agent: {e}")
|
37 |
return f"Error initializing agent: {e}", None
|
|
|
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
|
|
|
71 |
print(f"Skipping item with missing task_id or question: {item}")
|
72 |
continue
|
73 |
try:
|
74 |
+
submitted_answer = base_agent.run(question_text)
|
75 |
+
answers_payload.append(
|
76 |
+
{"task_id": task_id, "submitted_answer": submitted_answer}
|
77 |
+
)
|
78 |
+
results_log.append(
|
79 |
+
{
|
80 |
+
"Task ID": task_id,
|
81 |
+
"Question": question_text,
|
82 |
+
"Submitted Answer": submitted_answer,
|
83 |
+
}
|
84 |
+
)
|
85 |
except Exception as e:
|
86 |
+
print(f"Error running agent on task {task_id}: {e}")
|
87 |
+
results_log.append(
|
88 |
+
{
|
89 |
+
"Task ID": task_id,
|
90 |
+
"Question": question_text,
|
91 |
+
"Submitted Answer": f"AGENT ERROR: {e}",
|
92 |
+
}
|
93 |
+
)
|
94 |
|
95 |
if not answers_payload:
|
96 |
print("Agent did not produce any answers to submit.")
|
97 |
return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)
|
98 |
|
99 |
+
# 4. Prepare Submission
|
100 |
+
submission_data = {
|
101 |
+
"username": username.strip(),
|
102 |
+
"agent_code": agent_code,
|
103 |
+
"answers": answers_payload,
|
104 |
+
}
|
105 |
status_update = f"Agent finished. Submitting {len(answers_payload)} answers for user '{username}'..."
|
106 |
print(status_update)
|
107 |
|
|
|
171 |
|
172 |
run_button = gr.Button("Run Evaluation & Submit All Answers")
|
173 |
|
174 |
+
status_output = gr.Textbox(
|
175 |
+
label="Run Status / Submission Result", lines=5, interactive=False
|
176 |
+
)
|
177 |
# Removed max_rows=10 from DataFrame constructor
|
178 |
results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True)
|
179 |
|
180 |
+
run_button.click(fn=run_and_submit_all, outputs=[status_output, results_table])
|
|
|
|
|
|
|
181 |
|
182 |
if __name__ == "__main__":
|
183 |
+
print("\n" + "-" * 30 + " App Starting " + "-" * 30)
|
184 |
# Check for SPACE_HOST and SPACE_ID at startup for information
|
185 |
space_host_startup = os.getenv("SPACE_HOST")
|
186 |
+
space_id_startup = os.getenv("SPACE_ID") # Get SPACE_ID at startup
|
187 |
|
188 |
if space_host_startup:
|
189 |
print(f"✅ SPACE_HOST found: {space_host_startup}")
|
|
|
191 |
else:
|
192 |
print("ℹ️ SPACE_HOST environment variable not found (running locally?).")
|
193 |
|
194 |
+
if space_id_startup: # Print repo URLs if SPACE_ID is found
|
195 |
print(f"✅ SPACE_ID found: {space_id_startup}")
|
196 |
print(f" Repo URL: https://huggingface.co/spaces/{space_id_startup}")
|
197 |
+
print(
|
198 |
+
f" Repo Tree URL: https://huggingface.co/spaces/{space_id_startup}/tree/main"
|
199 |
+
)
|
200 |
else:
|
201 |
+
print(
|
202 |
+
"ℹ️ SPACE_ID environment variable not found (running locally?). Repo URL cannot be determined."
|
203 |
+
)
|
204 |
|
205 |
+
print("-" * (60 + len(" App Starting ")) + "\n")
|
206 |
|
207 |
print("Launching Gradio Interface for Basic Agent Evaluation...")
|
208 |
+
demo.launch(debug=True, share=False)
|
requirements.txt
CHANGED
@@ -1,2 +1,4 @@
|
|
1 |
gradio
|
2 |
-
requests
|
|
|
|
|
|
1 |
gradio
|
2 |
+
requests
|
3 |
+
smolagents[toolkit,openai,vision,transformers,litellm]
|
4 |
+
gradio[oauth]
|
src/config/__init__.py
ADDED
@@ -0,0 +1,7 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from dotenv import load_dotenv
|
2 |
+
import os
|
3 |
+
|
4 |
+
# Load environment variables from .env
|
5 |
+
load_dotenv()
|
6 |
+
|
7 |
+
OPENAI_API_KEY = os.getenv("OPENAI_API_KEY", "")
|
src/config/model.py
ADDED
@@ -0,0 +1,7 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from smolagents import OpenAIServerModel
|
2 |
+
from src.config import OPENAI_API_KEY
|
3 |
+
|
4 |
+
openai_model = OpenAIServerModel(
|
5 |
+
model_id="gpt-4.1-mini",
|
6 |
+
api_key=OPENAI_API_KEY,
|
7 |
+
)
|
tool.py
ADDED
@@ -0,0 +1,24 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from smolagents import Tool
|
2 |
+
|
3 |
+
|
4 |
+
class AdditionTool(Tool):
|
5 |
+
name = "add_numbers"
|
6 |
+
description = """
|
7 |
+
This is a tool that adds two numbers."""
|
8 |
+
inputs = {
|
9 |
+
"a": {
|
10 |
+
"type": "number",
|
11 |
+
"description": "the first number",
|
12 |
+
},
|
13 |
+
"b": {
|
14 |
+
"type": "number",
|
15 |
+
"description": "the second number",
|
16 |
+
},
|
17 |
+
}
|
18 |
+
output_type = "number"
|
19 |
+
|
20 |
+
def forward(self, a: float, b: float) -> float:
|
21 |
+
return a + b
|
22 |
+
|
23 |
+
|
24 |
+
addition_tool = AdditionTool()
|