Commit ·
cf1596c
1
Parent(s): 137241f
Simplify app.py to display CLI instructions instead of web interface
Browse files
app.py
CHANGED
|
@@ -1,240 +1,68 @@
|
|
| 1 |
import os
|
| 2 |
import gradio as gr
|
| 3 |
-
import requests
|
| 4 |
-
import inspect
|
| 5 |
-
import pandas as pd
|
| 6 |
from dotenv import load_dotenv
|
| 7 |
|
| 8 |
-
# Load environment variables
|
| 9 |
-
|
|
|
|
|
|
|
|
|
|
| 10 |
|
| 11 |
-
#
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
# --- Import and use our SmolAgent implementation ---
|
| 16 |
-
from agent import SmolAgent
|
| 17 |
-
|
| 18 |
-
# Function to download file for a task
|
| 19 |
-
def download_file(task_id, file_name, api_url=DEFAULT_API_URL):
|
| 20 |
-
"""Download a file for a task if one exists."""
|
| 21 |
-
file_url = f"{api_url}/files/{task_id}"
|
| 22 |
-
try:
|
| 23 |
-
response = requests.get(file_url, timeout=15)
|
| 24 |
-
if response.status_code == 404:
|
| 25 |
-
print(f"No file found for task {task_id}")
|
| 26 |
-
return None, None
|
| 27 |
-
response.raise_for_status()
|
| 28 |
-
|
| 29 |
-
# Save the file
|
| 30 |
-
os.makedirs("downloaded_files", exist_ok=True)
|
| 31 |
-
file_path = os.path.join("downloaded_files", file_name)
|
| 32 |
-
with open(file_path, "wb") as f:
|
| 33 |
-
f.write(response.content)
|
| 34 |
-
print(f"File saved to: {file_path}")
|
| 35 |
-
return file_path, response.content
|
| 36 |
-
except Exception as e:
|
| 37 |
-
print(f"Error downloading file: {e}")
|
| 38 |
-
return None, None
|
| 39 |
-
|
| 40 |
-
# --- Agent Wrapper Class ---
|
| 41 |
-
class BasicAgent:
|
| 42 |
-
def __init__(self):
|
| 43 |
-
# Get API key from environment variables
|
| 44 |
-
openrouter_api_key = os.getenv("OPENROUTER_API_KEY")
|
| 45 |
-
if not openrouter_api_key:
|
| 46 |
-
print("WARNING: OPENROUTER_API_KEY not set in environment!")
|
| 47 |
-
# Will raise an exception when the agent is used
|
| 48 |
-
|
| 49 |
-
self.model = os.getenv("OPENROUTER_MODEL", "anthropic/claude-3-5-sonnet")
|
| 50 |
-
print(f"BasicAgent initializing with model: {self.model}")
|
| 51 |
-
|
| 52 |
-
self.agent = SmolAgent(openrouter_api_key, model=self.model)
|
| 53 |
-
print("BasicAgent initialized successfully.")
|
| 54 |
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
# Extract task_id and file_name if present in the context
|
| 59 |
-
task_id = None
|
| 60 |
-
file_name = None
|
| 61 |
-
file_path = None
|
| 62 |
-
context = {}
|
| 63 |
-
|
| 64 |
-
# Check if this is a question that includes file metadata
|
| 65 |
-
if isinstance(question, dict):
|
| 66 |
-
task_id = question.get("task_id")
|
| 67 |
-
file_name = question.get("file_name", "")
|
| 68 |
-
|
| 69 |
-
# If there's a file, download it
|
| 70 |
-
if file_name:
|
| 71 |
-
file_path, _ = download_file(task_id, file_name)
|
| 72 |
-
if file_path:
|
| 73 |
-
context = {
|
| 74 |
-
"file_name": file_name,
|
| 75 |
-
"file_path": file_path
|
| 76 |
-
}
|
| 77 |
-
|
| 78 |
-
# Get the actual question text
|
| 79 |
-
question = question.get("question", "")
|
| 80 |
-
|
| 81 |
-
# Process the question with our agent
|
| 82 |
-
answer = self.agent(question, context=context)
|
| 83 |
-
print(f"Agent returning answer (first 50 chars): {answer[:50]}...")
|
| 84 |
-
return answer
|
| 85 |
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
and displays the results.
|
| 90 |
-
"""
|
| 91 |
-
# --- Determine HF Space Runtime URL and Repo URL ---
|
| 92 |
-
space_id = os.getenv("SPACE_ID") # Get the SPACE_ID for sending link to the code
|
| 93 |
|
| 94 |
-
|
| 95 |
-
username= f"{profile.username}"
|
| 96 |
-
print(f"User logged in: {username}")
|
| 97 |
-
else:
|
| 98 |
-
print("User not logged in.")
|
| 99 |
-
return "Please Login to Hugging Face with the button.", None
|
| 100 |
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
|
|
|
|
| 104 |
|
| 105 |
-
|
| 106 |
-
try:
|
| 107 |
-
agent = BasicAgent()
|
| 108 |
-
except Exception as e:
|
| 109 |
-
print(f"Error instantiating agent: {e}")
|
| 110 |
-
return f"Error initializing agent: {e}", None
|
| 111 |
-
# 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)
|
| 112 |
-
agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
|
| 113 |
-
print(agent_code)
|
| 114 |
|
| 115 |
-
|
| 116 |
-
print(f"Fetching questions from: {questions_url}")
|
| 117 |
-
try:
|
| 118 |
-
response = requests.get(questions_url, timeout=15)
|
| 119 |
-
response.raise_for_status()
|
| 120 |
-
questions_data = response.json()
|
| 121 |
-
if not questions_data:
|
| 122 |
-
print("Fetched questions list is empty.")
|
| 123 |
-
return "Fetched questions list is empty or invalid format.", None
|
| 124 |
-
print(f"Fetched {len(questions_data)} questions.")
|
| 125 |
-
except requests.exceptions.RequestException as e:
|
| 126 |
-
print(f"Error fetching questions: {e}")
|
| 127 |
-
return f"Error fetching questions: {e}", None
|
| 128 |
-
except requests.exceptions.JSONDecodeError as e:
|
| 129 |
-
print(f"Error decoding JSON response from questions endpoint: {e}")
|
| 130 |
-
print(f"Response text: {response.text[:500]}")
|
| 131 |
-
return f"Error decoding server response for questions: {e}", None
|
| 132 |
-
except Exception as e:
|
| 133 |
-
print(f"An unexpected error occurred fetching questions: {e}")
|
| 134 |
-
return f"An unexpected error occurred fetching questions: {e}", None
|
| 135 |
|
| 136 |
-
|
| 137 |
-
|
| 138 |
-
|
| 139 |
-
print(f"Running agent on {len(questions_data)} questions...")
|
| 140 |
-
for item in questions_data:
|
| 141 |
-
task_id = item.get("task_id")
|
| 142 |
-
question_text = item.get("question")
|
| 143 |
-
if not task_id or question_text is None:
|
| 144 |
-
print(f"Skipping item with missing task_id or question: {item}")
|
| 145 |
-
continue
|
| 146 |
-
try:
|
| 147 |
-
submitted_answer = agent(question_text)
|
| 148 |
-
answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
|
| 149 |
-
results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})
|
| 150 |
-
except Exception as e:
|
| 151 |
-
print(f"Error running agent on task {task_id}: {e}")
|
| 152 |
-
results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": f"AGENT ERROR: {e}"})
|
| 153 |
|
| 154 |
-
|
| 155 |
-
|
| 156 |
-
return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)
|
| 157 |
|
| 158 |
-
|
| 159 |
-
|
| 160 |
-
status_update = f"Agent finished. Submitting {len(answers_payload)} answers for user '{username}'..."
|
| 161 |
-
print(status_update)
|
| 162 |
|
| 163 |
-
|
| 164 |
-
|
| 165 |
-
|
| 166 |
-
response = requests.post(submit_url, json=submission_data, timeout=60)
|
| 167 |
-
response.raise_for_status()
|
| 168 |
-
result_data = response.json()
|
| 169 |
-
final_status = (
|
| 170 |
-
f"Submission Successful!\n"
|
| 171 |
-
f"User: {result_data.get('username')}\n"
|
| 172 |
-
f"Overall Score: {result_data.get('score', 'N/A')}% "
|
| 173 |
-
f"({result_data.get('correct_count', '?')}/{result_data.get('total_attempted', '?')} correct)\n"
|
| 174 |
-
f"Message: {result_data.get('message', 'No message received.')}"
|
| 175 |
-
)
|
| 176 |
-
print("Submission successful.")
|
| 177 |
-
results_df = pd.DataFrame(results_log)
|
| 178 |
-
return final_status, results_df
|
| 179 |
-
except requests.exceptions.HTTPError as e:
|
| 180 |
-
error_detail = f"Server responded with status {e.response.status_code}."
|
| 181 |
-
try:
|
| 182 |
-
error_json = e.response.json()
|
| 183 |
-
error_detail += f" Detail: {error_json.get('detail', e.response.text)}"
|
| 184 |
-
except requests.exceptions.JSONDecodeError:
|
| 185 |
-
error_detail += f" Response: {e.response.text[:500]}"
|
| 186 |
-
status_message = f"Submission Failed: {error_detail}"
|
| 187 |
-
print(status_message)
|
| 188 |
-
results_df = pd.DataFrame(results_log)
|
| 189 |
-
return status_message, results_df
|
| 190 |
-
except requests.exceptions.Timeout:
|
| 191 |
-
status_message = "Submission Failed: The request timed out."
|
| 192 |
-
print(status_message)
|
| 193 |
-
results_df = pd.DataFrame(results_log)
|
| 194 |
-
return status_message, results_df
|
| 195 |
-
except requests.exceptions.RequestException as e:
|
| 196 |
-
status_message = f"Submission Failed: Network error - {e}"
|
| 197 |
-
print(status_message)
|
| 198 |
-
results_df = pd.DataFrame(results_log)
|
| 199 |
-
return status_message, results_df
|
| 200 |
-
except Exception as e:
|
| 201 |
-
status_message = f"An unexpected error occurred during submission: {e}"
|
| 202 |
-
print(status_message)
|
| 203 |
-
results_df = pd.DataFrame(results_log)
|
| 204 |
-
return status_message, results_df
|
| 205 |
|
|
|
|
| 206 |
|
| 207 |
-
|
| 208 |
-
with gr.Blocks() as demo:
|
| 209 |
-
gr.Markdown("# Basic Agent Evaluation Runner")
|
| 210 |
-
gr.Markdown(
|
| 211 |
-
"""
|
| 212 |
-
**Instructions:**
|
| 213 |
-
|
| 214 |
-
1. Please clone this space, then modify the code to define your agent's logic, the tools, the necessary packages, etc ...
|
| 215 |
-
2. Log in to your Hugging Face account using the button below. This uses your HF username for submission.
|
| 216 |
-
3. Click 'Run Evaluation & Submit All Answers' to fetch questions, run your agent, submit answers, and see the score.
|
| 217 |
|
| 218 |
-
|
| 219 |
-
|
| 220 |
-
|
| 221 |
-
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.
|
| 222 |
-
"""
|
| 223 |
-
)
|
| 224 |
|
| 225 |
-
|
|
|
|
|
|
|
| 226 |
|
| 227 |
-
|
| 228 |
|
| 229 |
-
|
| 230 |
-
|
| 231 |
-
results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True)
|
| 232 |
-
|
| 233 |
-
run_button.click(
|
| 234 |
-
fn=run_and_submit_all,
|
| 235 |
-
outputs=[status_output, results_table]
|
| 236 |
)
|
| 237 |
-
|
| 238 |
if __name__ == "__main__":
|
| 239 |
print("\n" + "-"*30 + " App Starting " + "-"*30)
|
| 240 |
# Check for SPACE_HOST and SPACE_ID at startup for information
|
|
@@ -256,5 +84,5 @@ if __name__ == "__main__":
|
|
| 256 |
|
| 257 |
print("-"*(60 + len(" App Starting ")) + "\n")
|
| 258 |
|
| 259 |
-
print("Launching Gradio Interface
|
| 260 |
demo.launch(debug=True, share=False)
|
|
|
|
| 1 |
import os
|
| 2 |
import gradio as gr
|
|
|
|
|
|
|
|
|
|
| 3 |
from dotenv import load_dotenv
|
| 4 |
|
| 5 |
+
# Load environment variables (if available)
|
| 6 |
+
try:
|
| 7 |
+
load_dotenv()
|
| 8 |
+
except:
|
| 9 |
+
pass
|
| 10 |
|
| 11 |
+
# --- Build Gradio Interface using Blocks ---
|
| 12 |
+
with gr.Blocks() as demo:
|
| 13 |
+
gr.Markdown("# Enhanced Agent for API Question Evaluation")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 14 |
|
| 15 |
+
gr.Markdown(
|
| 16 |
+
"""
|
| 17 |
+
## CLI-Based Enhanced Agent
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 18 |
|
| 19 |
+
This enhanced agent is designed to be run from the command line rather than through a web interface.
|
| 20 |
+
It features specialized tools for handling different types of data and performing various tasks
|
| 21 |
+
to effectively answer questions from the evaluation API.
|
|
|
|
|
|
|
|
|
|
|
|
|
| 22 |
|
| 23 |
+
### Key Features
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 24 |
|
| 25 |
+
- **Multiple Specialized Tools**: Web search, Excel analysis, audio transcription, code execution, and more
|
| 26 |
+
- **File Attachment Handling**: Automatically downloads and processes file attachments from the API
|
| 27 |
+
- **Minimal Answer Enforcement**: Ensures answers are concise and match the expected format
|
| 28 |
+
- **Robust Error Handling**: Prevents crashes with fallbacks for all tool operations
|
| 29 |
|
| 30 |
+
### Running the Agent
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 31 |
|
| 32 |
+
To run the agent, please use the command-line interface:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 33 |
|
| 34 |
+
```bash
|
| 35 |
+
# Run the evaluation against the API
|
| 36 |
+
python run_enhanced_evaluation.py
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 37 |
|
| 38 |
+
# Use a different model
|
| 39 |
+
python run_enhanced_evaluation.py --model anthropic/claude-3-opus-20240229
|
|
|
|
| 40 |
|
| 41 |
+
# Run with parallel workers (experimental)
|
| 42 |
+
python run_enhanced_evaluation.py --workers 2
|
|
|
|
|
|
|
| 43 |
|
| 44 |
+
# Provide username and code link via command line
|
| 45 |
+
python run_enhanced_evaluation.py --username "YourName" --code-link "https://github.com/yourusername/your-repo"
|
| 46 |
+
```
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 47 |
|
| 48 |
+
### Testing the Agent
|
| 49 |
|
| 50 |
+
You can also test the agent with various question types:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 51 |
|
| 52 |
+
```bash
|
| 53 |
+
# Run tests with basic questions
|
| 54 |
+
python test_enhanced_agent.py
|
|
|
|
|
|
|
|
|
|
| 55 |
|
| 56 |
+
# Test with a specific model
|
| 57 |
+
python test_enhanced_agent.py --model openai/gpt-4o
|
| 58 |
+
```
|
| 59 |
|
| 60 |
+
### Repository
|
| 61 |
|
| 62 |
+
For more details, please check the [GitHub repository](https://github.com/yourusername/your-repo).
|
| 63 |
+
"""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 64 |
)
|
| 65 |
+
|
| 66 |
if __name__ == "__main__":
|
| 67 |
print("\n" + "-"*30 + " App Starting " + "-"*30)
|
| 68 |
# Check for SPACE_HOST and SPACE_ID at startup for information
|
|
|
|
| 84 |
|
| 85 |
print("-"*(60 + len(" App Starting ")) + "\n")
|
| 86 |
|
| 87 |
+
print("Launching Gradio Interface...")
|
| 88 |
demo.launch(debug=True, share=False)
|