Spaces:
Sleeping
Sleeping
Commit
Β·
99c4fdf
1
Parent(s):
8823cad
First commit
Browse files- .gitignore +1 -0
- README.md +7 -7
- app.py +222 -0
- prompt.md +44 -0
- requirements.txt +7 -0
- tools.py +58 -0
- utils/functions.py +7 -0
.gitignore
ADDED
@@ -0,0 +1 @@
|
|
|
|
|
1 |
+
.env
|
README.md
CHANGED
@@ -1,13 +1,13 @@
|
|
1 |
---
|
2 |
title: GAIA Agent
|
3 |
-
emoji:
|
4 |
colorFrom: indigo
|
5 |
-
colorTo:
|
6 |
sdk: gradio
|
7 |
-
sdk_version: 5.
|
8 |
app_file: app.py
|
9 |
pinned: false
|
10 |
-
|
11 |
-
|
12 |
-
|
13 |
-
|
|
|
1 |
---
|
2 |
title: GAIA Agent
|
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 |
+
---
|
app.py
ADDED
@@ -0,0 +1,222 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
import gradio as gr
|
3 |
+
import requests
|
4 |
+
import inspect
|
5 |
+
from langchain_openai import ChatOpenAI
|
6 |
+
import pandas as pd
|
7 |
+
from smolagents import CodeAgent, InferenceClientModel, OpenAIServerModel
|
8 |
+
from tools import return_tools
|
9 |
+
from utils.functions import load_system_prompt
|
10 |
+
import base64
|
11 |
+
# (Keep Constants as is)
|
12 |
+
# --- Constants ---
|
13 |
+
DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
|
14 |
+
SYSTEM_PROMPT = load_system_prompt()
|
15 |
+
|
16 |
+
# model
|
17 |
+
model_id="qwen/qwen-2.5-7b-instruct"
|
18 |
+
|
19 |
+
model = OpenAIServerModel(
|
20 |
+
model_id=model_id, # Your desired model on OpenRouter
|
21 |
+
api_base=os.getenv("OPENROUTER_BASE_URL"), # Should be "https://openrouter.ai/api/v1"
|
22 |
+
api_key=os.getenv("OPENROUTER_API_KEY"),
|
23 |
+
)
|
24 |
+
# Create the constant
|
25 |
+
|
26 |
+
# --- Basic Agent Definition ---
|
27 |
+
# ----- THIS IS WERE YOU CAN BUILD WHAT YOU WANT ------
|
28 |
+
class BasicAgent:
|
29 |
+
def __init__(self):
|
30 |
+
print("BasicAgent initialized.")
|
31 |
+
self.agent = CodeAgent(
|
32 |
+
model=model,
|
33 |
+
tools=return_tools(),
|
34 |
+
)
|
35 |
+
self.agent.prompt_templates["system_prompt"] = self.agent.prompt_templates["system_prompt"] + "\n" + SYSTEM_PROMPT
|
36 |
+
def __call__(self, question: str) -> str:
|
37 |
+
print(f"Agent received question (first 50 chars): {question[:50]}...")
|
38 |
+
|
39 |
+
res = self.agent.run(question)
|
40 |
+
print(f"Agent returning fixed answer: {res}")
|
41 |
+
return res
|
42 |
+
|
43 |
+
def encode_image(image_path: str) -> str:
|
44 |
+
"""Encode image to base64 string."""
|
45 |
+
with open(image_path, "rb") as image_file:
|
46 |
+
return base64.b64encode(image_file.read()).decode("utf-8")
|
47 |
+
|
48 |
+
def run_and_submit_all( profile: gr.OAuthProfile | None):
|
49 |
+
"""
|
50 |
+
Fetches all questions, runs the BasicAgent on them, submits all answers,
|
51 |
+
and displays the results.
|
52 |
+
"""
|
53 |
+
# --- Determine HF Space Runtime URL and Repo URL ---
|
54 |
+
space_id = os.getenv("SPACE_ID") # Get the SPACE_ID for sending link to the code
|
55 |
+
|
56 |
+
if profile:
|
57 |
+
username= f"{profile.username}"
|
58 |
+
print(f"User logged in: {username}")
|
59 |
+
else:
|
60 |
+
print("User not logged in.")
|
61 |
+
return "Please Login to Hugging Face with the button.", None
|
62 |
+
|
63 |
+
api_url = DEFAULT_API_URL
|
64 |
+
questions_url = f"{api_url}/questions"
|
65 |
+
submit_url = f"{api_url}/submit"
|
66 |
+
|
67 |
+
# 1. Instantiate Agent ( modify this part to create your agent)
|
68 |
+
try:
|
69 |
+
agent = BasicAgent()
|
70 |
+
except Exception as e:
|
71 |
+
print(f"Error instantiating agent: {e}")
|
72 |
+
return f"Error initializing agent: {e}", None
|
73 |
+
# 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)
|
74 |
+
agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
|
75 |
+
print(agent_code)
|
76 |
+
|
77 |
+
# 2. Fetch Questions
|
78 |
+
print(f"Fetching questions from: {questions_url}")
|
79 |
+
try:
|
80 |
+
response = requests.get(questions_url, timeout=15)
|
81 |
+
response.raise_for_status()
|
82 |
+
questions_data = response.json()
|
83 |
+
if not questions_data:
|
84 |
+
print("Fetched questions list is empty.")
|
85 |
+
return "Fetched questions list is empty or invalid format.", None
|
86 |
+
print(f"Fetched {len(questions_data)} questions.")
|
87 |
+
except requests.exceptions.RequestException as e:
|
88 |
+
print(f"Error fetching questions: {e}")
|
89 |
+
return f"Error fetching questions: {e}", None
|
90 |
+
except requests.exceptions.JSONDecodeError as e:
|
91 |
+
print(f"Error decoding JSON response from questions endpoint: {e}")
|
92 |
+
print(f"Response text: {response.text[:500]}")
|
93 |
+
return f"Error decoding server response for questions: {e}", None
|
94 |
+
except Exception as e:
|
95 |
+
print(f"An unexpected error occurred fetching questions: {e}")
|
96 |
+
return f"An unexpected error occurred fetching questions: {e}", None
|
97 |
+
|
98 |
+
# 3. Run your Agent
|
99 |
+
results_log = []
|
100 |
+
answers_payload = []
|
101 |
+
print(f"Running agent on {len(questions_data)} questions...")
|
102 |
+
for item in questions_data:
|
103 |
+
task_id = item.get("task_id")
|
104 |
+
question_text = item.get("question")
|
105 |
+
if not task_id or question_text is None:
|
106 |
+
print(f"Skipping item with missing task_id or question: {item}")
|
107 |
+
continue
|
108 |
+
try:
|
109 |
+
submitted_answer = agent(question_text)
|
110 |
+
answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
|
111 |
+
results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})
|
112 |
+
except Exception as e:
|
113 |
+
print(f"Error running agent on task {task_id}: {e}")
|
114 |
+
results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": f"AGENT ERROR: {e}"})
|
115 |
+
|
116 |
+
if not answers_payload:
|
117 |
+
print("Agent did not produce any answers to submit.")
|
118 |
+
return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)
|
119 |
+
|
120 |
+
# 4. Prepare Submission
|
121 |
+
submission_data = {"username": username.strip(), "agent_code": agent_code, "answers": answers_payload}
|
122 |
+
status_update = f"Agent finished. Submitting {len(answers_payload)} answers for user '{username}'..."
|
123 |
+
print(status_update)
|
124 |
+
|
125 |
+
# 5. Submit
|
126 |
+
print(f"Submitting {len(answers_payload)} answers to: {submit_url}")
|
127 |
+
try:
|
128 |
+
response = requests.post(submit_url, json=submission_data, timeout=60)
|
129 |
+
response.raise_for_status()
|
130 |
+
result_data = response.json()
|
131 |
+
final_status = (
|
132 |
+
f"Submission Successful!\n"
|
133 |
+
f"User: {result_data.get('username')}\n"
|
134 |
+
f"Overall Score: {result_data.get('score', 'N/A')}% "
|
135 |
+
f"({result_data.get('correct_count', '?')}/{result_data.get('total_attempted', '?')} correct)\n"
|
136 |
+
f"Message: {result_data.get('message', 'No message received.')}"
|
137 |
+
)
|
138 |
+
print("Submission successful.")
|
139 |
+
results_df = pd.DataFrame(results_log)
|
140 |
+
return final_status, results_df
|
141 |
+
except requests.exceptions.HTTPError as e:
|
142 |
+
error_detail = f"Server responded with status {e.response.status_code}."
|
143 |
+
try:
|
144 |
+
error_json = e.response.json()
|
145 |
+
error_detail += f" Detail: {error_json.get('detail', e.response.text)}"
|
146 |
+
except requests.exceptions.JSONDecodeError:
|
147 |
+
error_detail += f" Response: {e.response.text[:500]}"
|
148 |
+
status_message = f"Submission Failed: {error_detail}"
|
149 |
+
print(status_message)
|
150 |
+
results_df = pd.DataFrame(results_log)
|
151 |
+
return status_message, results_df
|
152 |
+
except requests.exceptions.Timeout:
|
153 |
+
status_message = "Submission Failed: The request timed out."
|
154 |
+
print(status_message)
|
155 |
+
results_df = pd.DataFrame(results_log)
|
156 |
+
return status_message, results_df
|
157 |
+
except requests.exceptions.RequestException as e:
|
158 |
+
status_message = f"Submission Failed: Network error - {e}"
|
159 |
+
print(status_message)
|
160 |
+
results_df = pd.DataFrame(results_log)
|
161 |
+
return status_message, results_df
|
162 |
+
except Exception as e:
|
163 |
+
status_message = f"An unexpected error occurred during submission: {e}"
|
164 |
+
print(status_message)
|
165 |
+
results_df = pd.DataFrame(results_log)
|
166 |
+
return status_message, results_df
|
167 |
+
|
168 |
+
|
169 |
+
# --- Build Gradio Interface using Blocks ---
|
170 |
+
with gr.Blocks() as demo:
|
171 |
+
gr.Markdown("# Basic Agent Evaluation Runner")
|
172 |
+
gr.Markdown(
|
173 |
+
"""
|
174 |
+
**Instructions:**
|
175 |
+
|
176 |
+
1. Please clone this space, then modify the code to define your agent's logic, the tools, the necessary packages, etc ...
|
177 |
+
2. Log in to your Hugging Face account using the button below. This uses your HF username for submission.
|
178 |
+
3. Click 'Run Evaluation & Submit All Answers' to fetch questions, run your agent, submit answers, and see the score.
|
179 |
+
|
180 |
+
---
|
181 |
+
**Disclaimers:**
|
182 |
+
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).
|
183 |
+
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.
|
184 |
+
"""
|
185 |
+
)
|
186 |
+
|
187 |
+
gr.LoginButton()
|
188 |
+
|
189 |
+
run_button = gr.Button("Run Evaluation & Submit All Answers")
|
190 |
+
|
191 |
+
status_output = gr.Textbox(label="Run Status / Submission Result", lines=5, interactive=False)
|
192 |
+
# Removed max_rows=10 from DataFrame constructor
|
193 |
+
results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True)
|
194 |
+
|
195 |
+
run_button.click(
|
196 |
+
fn=run_and_submit_all,
|
197 |
+
outputs=[status_output, results_table]
|
198 |
+
)
|
199 |
+
|
200 |
+
if __name__ == "__main__":
|
201 |
+
print("\n" + "-"*30 + " App Starting " + "-"*30)
|
202 |
+
# Check for SPACE_HOST and SPACE_ID at startup for information
|
203 |
+
space_host_startup = os.getenv("SPACE_HOST")
|
204 |
+
space_id_startup = os.getenv("SPACE_ID") # Get SPACE_ID at startup
|
205 |
+
|
206 |
+
if space_host_startup:
|
207 |
+
print(f"β
SPACE_HOST found: {space_host_startup}")
|
208 |
+
print(f" Runtime URL should be: https://{space_host_startup}.hf.space")
|
209 |
+
else:
|
210 |
+
print("βΉοΈ SPACE_HOST environment variable not found (running locally?).")
|
211 |
+
|
212 |
+
if space_id_startup: # Print repo URLs if SPACE_ID is found
|
213 |
+
print(f"β
SPACE_ID found: {space_id_startup}")
|
214 |
+
print(f" Repo URL: https://huggingface.co/spaces/{space_id_startup}")
|
215 |
+
print(f" Repo Tree URL: https://huggingface.co/spaces/{space_id_startup}/tree/main")
|
216 |
+
else:
|
217 |
+
print("βΉοΈ SPACE_ID environment variable not found (running locally?). Repo URL cannot be determined.")
|
218 |
+
|
219 |
+
print("-"*(60 + len(" App Starting ")) + "\n")
|
220 |
+
|
221 |
+
print("Launching Gradio Interface for Basic Agent Evaluation...")
|
222 |
+
demo.launch(debug=True, share=False)
|
prompt.md
ADDED
@@ -0,0 +1,44 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
You are GAIA (Generalist AI Agent), a powerful AI assistant built on the Qwen2.5-Coder-32B-Instruct model with specialized tools for file operations, audio transcription, and web search. Your purpose is to assist users with coding tasks, data analysis, file management, audio processing, and information retrieval.
|
2 |
+
|
3 |
+
## Core Capabilities
|
4 |
+
- You can read files and process their contents using the read_file tool
|
5 |
+
- You can transcribe audio files to text using the transcribe_audio tool
|
6 |
+
- You can search the web for information using the DuckDuckGoSearchTool
|
7 |
+
- You excel at coding tasks, especially with Python
|
8 |
+
- You can analyze data, debug code, and suggest optimizations
|
9 |
+
|
10 |
+
## Interaction Guidelines
|
11 |
+
1. Be precise and accurate in your responses
|
12 |
+
2. When using tools, explain what you're doing and why
|
13 |
+
3. If a task requires multiple steps, outline your approach before proceeding
|
14 |
+
4. When facing ambiguity, ask clarifying questions
|
15 |
+
5. Prioritize code quality, readability, and best practices
|
16 |
+
6. Provide explanations that are clear but concise
|
17 |
+
7. Use web search when questions are outside your knowledge or require up-to-date information
|
18 |
+
|
19 |
+
## Tool Usage
|
20 |
+
You have access to the following tools:
|
21 |
+
|
22 |
+
1. read_file
|
23 |
+
- Description: Reads the content of a file at the specified path
|
24 |
+
- Use when: User needs to access file contents
|
25 |
+
- Example usage: read_file(file_path="data.txt")
|
26 |
+
|
27 |
+
2. transcribe_audio
|
28 |
+
- Description: Transcribes audio files to text using Whisper
|
29 |
+
- Use when: User needs speech-to-text conversion
|
30 |
+
- Example usage: transcribe_audio(audio_path="recording.wav")
|
31 |
+
|
32 |
+
## Response Format
|
33 |
+
- For code: Provide well-structured, commented code
|
34 |
+
- For explanations: Be clear and precise
|
35 |
+
- For tool usage: Show your reasoning, the tool call, and interpretation of results
|
36 |
+
- For web search results: Synthesize information from multiple sources when appropriate, and cite sources
|
37 |
+
|
38 |
+
## Limitations
|
39 |
+
- You cannot modify files directly (only read them)
|
40 |
+
- Audio transcription works best with clear speech in supported languages
|
41 |
+
- Web search results may vary in relevance and accuracy
|
42 |
+
- You cannot execute arbitrary code outside of your sandbox environment
|
43 |
+
|
44 |
+
Always prioritize helping the user accomplish their task efficiently while maintaining code quality and security standards. When providing information from web searches, critically evaluate the sources and present balanced information.
|
requirements.txt
ADDED
@@ -0,0 +1,7 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
gradio
|
2 |
+
requests
|
3 |
+
whisper
|
4 |
+
smolagents
|
5 |
+
langchain_openai
|
6 |
+
langchain_core
|
7 |
+
PIL
|
tools.py
ADDED
@@ -0,0 +1,58 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from smolagents import Tool, DuckDuckGoSearchTool
|
2 |
+
import whisper
|
3 |
+
|
4 |
+
class read_file(Tool):
|
5 |
+
name="read_file"
|
6 |
+
description="Read a file and return the content."
|
7 |
+
inputs={
|
8 |
+
"file_path": {
|
9 |
+
"type": "string",
|
10 |
+
"description": "The path to the file to read."
|
11 |
+
}
|
12 |
+
}
|
13 |
+
|
14 |
+
output_type = "string"
|
15 |
+
|
16 |
+
def forward(self, file_path: str) -> str:
|
17 |
+
"""
|
18 |
+
Read the content of a file and return it as a string.
|
19 |
+
"""
|
20 |
+
try:
|
21 |
+
with open(file_path, 'r') as file:
|
22 |
+
content = file.read()
|
23 |
+
return content
|
24 |
+
except Exception as e:
|
25 |
+
return f"Error reading file: {str(e)}"
|
26 |
+
|
27 |
+
class transcribe_audio(Tool):
|
28 |
+
name="transcribe_audio"
|
29 |
+
description="Transcribe an audio file and return the text."
|
30 |
+
inputs={
|
31 |
+
"audio_path": {
|
32 |
+
"type": "string",
|
33 |
+
"description": "The path to the audio file to transcribe."
|
34 |
+
}
|
35 |
+
}
|
36 |
+
|
37 |
+
output_type = "string"
|
38 |
+
|
39 |
+
def forward(self, audio_path: str) -> str:
|
40 |
+
try:
|
41 |
+
# Load the Whisper model
|
42 |
+
model = whisper.load_model("small")
|
43 |
+
# Transcribe the audio file
|
44 |
+
result = model.transcribe(audio_path)
|
45 |
+
return result['text']
|
46 |
+
except Exception as e:
|
47 |
+
return f"Error transcribing audio: {str(e)}"
|
48 |
+
|
49 |
+
|
50 |
+
def return_tools() -> list[Tool]:
|
51 |
+
"""
|
52 |
+
Returns a list of tools to be used by the agent.
|
53 |
+
"""
|
54 |
+
return [
|
55 |
+
read_file(),
|
56 |
+
transcribe_audio(),
|
57 |
+
DuckDuckGoSearchTool(),
|
58 |
+
]
|
utils/functions.py
ADDED
@@ -0,0 +1,7 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
def load_system_prompt():
|
2 |
+
try:
|
3 |
+
with open("prompt.md", "r") as file:
|
4 |
+
return file.read()
|
5 |
+
except Exception as e:
|
6 |
+
print(f"Error loading system prompt: {str(e)}")
|
7 |
+
return "You are GAIA, a helpful AI assistant." # Fallback prompt
|