Update app.py
Browse files
app.py
CHANGED
@@ -1,196 +1,186 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
import os
|
2 |
-
import
|
|
|
3 |
import requests
|
4 |
-
import
|
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 |
-
|
23 |
"""
|
24 |
-
|
25 |
-
and displays the results.
|
26 |
"""
|
27 |
-
|
28 |
-
|
29 |
-
|
30 |
-
|
31 |
-
|
32 |
-
|
33 |
-
|
34 |
-
|
35 |
-
|
36 |
-
|
37 |
-
|
38 |
-
|
39 |
-
|
40 |
-
|
41 |
-
|
42 |
-
|
43 |
-
|
44 |
-
|
45 |
-
|
46 |
-
|
47 |
-
|
48 |
-
|
49 |
-
|
50 |
-
|
51 |
-
|
52 |
-
|
53 |
-
|
54 |
-
|
55 |
-
|
56 |
-
|
57 |
-
if not questions_data:
|
58 |
-
print("Fetched questions list is empty.")
|
59 |
-
return "Fetched questions list is empty or invalid format.", None
|
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 |
-
print(f"Error decoding JSON response from questions endpoint: {e}")
|
66 |
-
print(f"Response text: {response.text[:500]}")
|
67 |
-
return f"Error decoding server response for questions: {e}", None
|
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
|
71 |
-
|
72 |
-
# 3. Run your Agent
|
73 |
-
results_log = []
|
74 |
-
answers_payload = []
|
75 |
-
print(f"Running agent on {len(questions_data)} questions...")
|
76 |
-
for item in questions_data:
|
77 |
-
task_id = item.get("task_id")
|
78 |
-
question_text = item.get("question")
|
79 |
-
if not task_id or question_text is None:
|
80 |
-
print(f"Skipping item with missing task_id or question: {item}")
|
81 |
-
continue
|
82 |
try:
|
83 |
-
|
84 |
-
|
85 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
86 |
except Exception as e:
|
87 |
-
|
88 |
-
results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": f"AGENT ERROR: {e}"})
|
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 = {"username": username.strip(), "agent_code": agent_code, "answers": answers_payload}
|
96 |
-
status_update = f"Agent finished. Submitting {len(answers_payload)} answers for user '{username}'..."
|
97 |
-
print(status_update)
|
98 |
-
|
99 |
-
# 5. Submit
|
100 |
-
print(f"Submitting {len(answers_payload)} answers to: {submit_url}")
|
101 |
-
try:
|
102 |
-
response = requests.post(submit_url, json=submission_data, timeout=60)
|
103 |
-
response.raise_for_status()
|
104 |
-
result_data = response.json()
|
105 |
-
final_status = (
|
106 |
-
f"Submission Successful!\n"
|
107 |
-
f"User: {result_data.get('username')}\n"
|
108 |
-
f"Overall Score: {result_data.get('score', 'N/A')}% "
|
109 |
-
f"({result_data.get('correct_count', '?')}/{result_data.get('total_attempted', '?')} correct)\n"
|
110 |
-
f"Message: {result_data.get('message', 'No message received.')}"
|
111 |
-
)
|
112 |
-
print("Submission successful.")
|
113 |
-
results_df = pd.DataFrame(results_log)
|
114 |
-
return final_status, results_df
|
115 |
-
except requests.exceptions.HTTPError as e:
|
116 |
-
error_detail = f"Server responded with status {e.response.status_code}."
|
117 |
-
try:
|
118 |
-
error_json = e.response.json()
|
119 |
-
error_detail += f" Detail: {error_json.get('detail', e.response.text)}"
|
120 |
-
except requests.exceptions.JSONDecodeError:
|
121 |
-
error_detail += f" Response: {e.response.text[:500]}"
|
122 |
-
status_message = f"Submission Failed: {error_detail}"
|
123 |
-
print(status_message)
|
124 |
-
results_df = pd.DataFrame(results_log)
|
125 |
-
return status_message, results_df
|
126 |
-
except requests.exceptions.Timeout:
|
127 |
-
status_message = "Submission Failed: The request timed out."
|
128 |
-
print(status_message)
|
129 |
-
results_df = pd.DataFrame(results_log)
|
130 |
-
return status_message, results_df
|
131 |
-
except requests.exceptions.RequestException as e:
|
132 |
-
status_message = f"Submission Failed: Network error - {e}"
|
133 |
-
print(status_message)
|
134 |
-
results_df = pd.DataFrame(results_log)
|
135 |
-
return status_message, results_df
|
136 |
-
except Exception as e:
|
137 |
-
status_message = f"An unexpected error occurred during submission: {e}"
|
138 |
-
print(status_message)
|
139 |
-
results_df = pd.DataFrame(results_log)
|
140 |
-
return status_message, results_df
|
141 |
|
142 |
|
143 |
-
|
144 |
-
|
145 |
-
|
146 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
147 |
"""
|
148 |
-
|
149 |
-
|
150 |
-
|
151 |
-
|
152 |
-
|
153 |
-
|
154 |
-
|
155 |
-
|
156 |
-
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).
|
157 |
-
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.
|
158 |
"""
|
159 |
-
|
160 |
-
|
161 |
-
|
162 |
-
|
163 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
164 |
|
165 |
-
status_output = gr.Textbox(label="Run Status / Submission Result", lines=5, interactive=False)
|
166 |
-
# Removed max_rows=10 from DataFrame constructor
|
167 |
-
results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True)
|
168 |
|
169 |
-
|
170 |
-
|
171 |
-
outputs=[status_output, results_table]
|
172 |
-
)
|
173 |
|
|
|
174 |
if __name__ == "__main__":
|
175 |
-
|
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") # Get SPACE_ID at startup
|
179 |
-
|
180 |
-
if space_host_startup:
|
181 |
-
print(f"✅ SPACE_HOST found: {space_host_startup}")
|
182 |
-
print(f" Runtime URL should be: https://{space_host_startup}.hf.space")
|
183 |
-
else:
|
184 |
-
print("ℹ️ SPACE_HOST environment variable not found (running locally?).")
|
185 |
-
|
186 |
-
if space_id_startup: # Print repo URLs if SPACE_ID is found
|
187 |
-
print(f"✅ SPACE_ID found: {space_id_startup}")
|
188 |
-
print(f" Repo URL: https://huggingface.co/spaces/{space_id_startup}")
|
189 |
-
print(f" Repo Tree URL: https://huggingface.co/spaces/{space_id_startup}/tree/main")
|
190 |
-
else:
|
191 |
-
print("ℹ️ SPACE_ID environment variable not found (running locally?). Repo URL cannot be determined.")
|
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)
|
|
|
1 |
+
"""
|
2 |
+
Minimal Gradio interface for a simple AI assistant without smolagents
|
3 |
+
|
4 |
+
This is a standalone version that uses only Hugging Face Inference API directly.
|
5 |
+
It creates a simple Gradio interface for text generation.
|
6 |
+
"""
|
7 |
+
|
8 |
import os
|
9 |
+
import sys
|
10 |
+
import json
|
11 |
import requests
|
12 |
+
import gradio as gr
|
|
|
|
|
|
|
|
|
|
|
13 |
|
14 |
+
# Check if running in Hugging Face Spaces
|
15 |
+
IS_HF_SPACES = os.environ.get("SPACE_ID") is not None
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
16 |
|
17 |
+
class MinimalAIAssistant:
|
18 |
"""
|
19 |
+
Minimal AI Assistant using Hugging Face Inference API directly
|
|
|
20 |
"""
|
21 |
+
def __init__(self, api_key=None, model_id="mistralai/Mixtral-8x7B-Instruct-v0.1"):
|
22 |
+
"""
|
23 |
+
Initialize the minimal AI assistant
|
24 |
+
|
25 |
+
Args:
|
26 |
+
api_key: Hugging Face API key
|
27 |
+
model_id: Model ID to use
|
28 |
+
"""
|
29 |
+
self.api_key = api_key or os.environ.get("HF_API_KEY", "")
|
30 |
+
self.model_id = model_id
|
31 |
+
self.api_url = f"https://api-inference.huggingface.co/models/{model_id}"
|
32 |
+
self.headers = {"Authorization": f"Bearer {self.api_key}"}
|
33 |
+
|
34 |
+
# System prompt
|
35 |
+
self.system_prompt = """
|
36 |
+
You are an advanced AI assistant designed to help with various tasks.
|
37 |
+
You can answer questions, provide information, and assist with problem-solving.
|
38 |
+
Always be helpful, accurate, and concise in your responses.
|
39 |
+
"""
|
40 |
+
|
41 |
+
def query(self, prompt):
|
42 |
+
"""
|
43 |
+
Query the model with a prompt
|
44 |
+
|
45 |
+
Args:
|
46 |
+
prompt: User prompt
|
47 |
+
|
48 |
+
Returns:
|
49 |
+
Model response
|
50 |
+
"""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
51 |
try:
|
52 |
+
# Format the prompt with system message
|
53 |
+
formatted_prompt = f"{self.system_prompt}\n\nUser: {prompt}\n\nAssistant:"
|
54 |
+
|
55 |
+
# Prepare the payload
|
56 |
+
payload = {
|
57 |
+
"inputs": formatted_prompt,
|
58 |
+
"parameters": {
|
59 |
+
"max_new_tokens": 1024,
|
60 |
+
"temperature": 0.7,
|
61 |
+
"top_p": 0.95,
|
62 |
+
"do_sample": True
|
63 |
+
}
|
64 |
+
}
|
65 |
+
|
66 |
+
# Make the API request
|
67 |
+
response = requests.post(self.api_url, headers=self.headers, json=payload)
|
68 |
+
|
69 |
+
# Check for errors
|
70 |
+
if response.status_code != 200:
|
71 |
+
return f"Error: API returned status code {response.status_code}. {response.text}"
|
72 |
+
|
73 |
+
# Parse the response
|
74 |
+
result = response.json()
|
75 |
+
|
76 |
+
# Extract the generated text
|
77 |
+
if isinstance(result, list) and len(result) > 0:
|
78 |
+
generated_text = result[0].get("generated_text", "")
|
79 |
+
# Remove the prompt from the response
|
80 |
+
if generated_text.startswith(formatted_prompt):
|
81 |
+
generated_text = generated_text[len(formatted_prompt):].strip()
|
82 |
+
return generated_text
|
83 |
+
else:
|
84 |
+
return "Error: Unexpected response format from API"
|
85 |
+
|
86 |
except Exception as e:
|
87 |
+
return f"Error querying model: {str(e)}"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
88 |
|
89 |
|
90 |
+
def create_gradio_interface():
|
91 |
+
"""
|
92 |
+
Create a Gradio interface for the minimal AI assistant
|
93 |
+
|
94 |
+
Returns:
|
95 |
+
Gradio interface
|
96 |
+
"""
|
97 |
+
# Initialize the assistant
|
98 |
+
assistant = MinimalAIAssistant()
|
99 |
+
|
100 |
+
def process_query(query, api_key=""):
|
101 |
"""
|
102 |
+
Process a user query
|
103 |
+
|
104 |
+
Args:
|
105 |
+
query: User query
|
106 |
+
api_key: Hugging Face API key (optional)
|
107 |
+
|
108 |
+
Returns:
|
109 |
+
Assistant's response
|
|
|
|
|
110 |
"""
|
111 |
+
# Update API key if provided
|
112 |
+
if api_key:
|
113 |
+
assistant.api_key = api_key
|
114 |
+
assistant.headers = {"Authorization": f"Bearer {api_key}"}
|
115 |
+
|
116 |
+
# Check if API key is set
|
117 |
+
if not assistant.api_key:
|
118 |
+
return "Error: No API key provided. Please enter your Hugging Face API key."
|
119 |
+
|
120 |
+
# Process the query
|
121 |
+
return assistant.query(query)
|
122 |
+
|
123 |
+
# Create the interface
|
124 |
+
with gr.Blocks(title="Minimal AI Assistant") as interface:
|
125 |
+
gr.Markdown("# Minimal AI Assistant")
|
126 |
+
gr.Markdown("""
|
127 |
+
This is a minimal AI assistant using the Hugging Face Inference API.
|
128 |
+
Enter your query below and the assistant will respond.
|
129 |
+
""")
|
130 |
+
|
131 |
+
api_key_input = gr.Textbox(
|
132 |
+
label="Hugging Face API Key",
|
133 |
+
placeholder="Enter your Hugging Face API key here...",
|
134 |
+
type="password"
|
135 |
+
)
|
136 |
+
|
137 |
+
query_input = gr.Textbox(
|
138 |
+
label="Your Query",
|
139 |
+
placeholder="Enter your query here...",
|
140 |
+
lines=3
|
141 |
+
)
|
142 |
+
|
143 |
+
submit_button = gr.Button("Submit")
|
144 |
+
|
145 |
+
response_output = gr.Textbox(
|
146 |
+
label="Assistant Response",
|
147 |
+
lines=15
|
148 |
+
)
|
149 |
+
|
150 |
+
# Sample queries
|
151 |
+
gr.Markdown("### Sample Queries")
|
152 |
+
sample_queries = [
|
153 |
+
"What is the capital of France?",
|
154 |
+
"Explain the concept of machine learning in simple terms.",
|
155 |
+
"Write a short poem about artificial intelligence."
|
156 |
+
]
|
157 |
+
|
158 |
+
for query in sample_queries:
|
159 |
+
sample_button = gr.Button(f"Try: {query}")
|
160 |
+
sample_button.click(
|
161 |
+
fn=lambda q=query: q,
|
162 |
+
outputs=query_input
|
163 |
+
)
|
164 |
+
|
165 |
+
# Set up event handlers
|
166 |
+
submit_button.click(
|
167 |
+
fn=process_query,
|
168 |
+
inputs=[query_input, api_key_input],
|
169 |
+
outputs=response_output
|
170 |
+
)
|
171 |
+
|
172 |
+
# Add examples
|
173 |
+
gr.Examples(
|
174 |
+
examples=sample_queries,
|
175 |
+
inputs=query_input
|
176 |
+
)
|
177 |
+
|
178 |
+
return interface
|
179 |
|
|
|
|
|
|
|
180 |
|
181 |
+
# Create and launch the interface
|
182 |
+
interface = create_gradio_interface()
|
|
|
|
|
183 |
|
184 |
+
# For Hugging Face Spaces
|
185 |
if __name__ == "__main__":
|
186 |
+
interface.launch()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|