Update app.py
Browse files
app.py
CHANGED
|
@@ -1,348 +1,234 @@
|
|
| 1 |
-
# --- LangGraph & LangChain Imports ---
|
| 2 |
import os
|
| 3 |
-
import gradio as gr
|
| 4 |
import requests
|
| 5 |
import pandas as pd
|
| 6 |
-
|
|
|
|
| 7 |
|
| 8 |
-
# ---
|
| 9 |
-
from
|
| 10 |
-
from langgraph.graph import StateGraph, END, START
|
| 11 |
-
from langgraph.graph.message import add_messages
|
| 12 |
-
from langchain_groq import ChatGroq
|
| 13 |
-
from langchain_core.tools import tool
|
| 14 |
-
from langgraph.prebuilt import ToolNode
|
| 15 |
-
from langchain_tavily import TavilySearch
|
| 16 |
-
from smolagents import CodeAgent, LiteLLMModel, VisitWebpageTool, WebSearchTool
|
| 17 |
|
| 18 |
-
# ---
|
| 19 |
DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
|
| 20 |
|
| 21 |
-
# ---
|
| 22 |
-
GROQ_API_KEY = os.getenv("GROQ_API_KEY")
|
| 23 |
-
MISTRAL_API_KEY = os.getenv("MISTRAL_API_KEY")
|
| 24 |
-
TAVILY_API_KEY = os.getenv("TAVILY_API_KEY")
|
| 25 |
-
|
| 26 |
class BasicAgent:
|
| 27 |
def __init__(self):
|
| 28 |
-
print("Initializing
|
| 29 |
-
|
| 30 |
-
# --- 1.
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 36 |
)
|
| 37 |
|
| 38 |
-
#
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 42 |
)
|
| 43 |
-
|
| 44 |
-
# SmolAgent Tool (Complex tasks ke liye)
|
| 45 |
-
self.avii_agent = CodeAgent(
|
| 46 |
-
tools=[WebSearchTool(), VisitWebpageTool()],
|
| 47 |
-
model=model_mistral,
|
| 48 |
-
additional_authorized_imports=["numpy", "pandas", "math", "datetime"],
|
| 49 |
-
name="avii"
|
| 50 |
-
)
|
| 51 |
-
|
| 52 |
-
# --- 2. DEFINE TOOLS ---
|
| 53 |
-
self.web_search = TavilySearch(
|
| 54 |
-
max_results=2,
|
| 55 |
-
include_raw_content=False,
|
| 56 |
-
include_images=False,
|
| 57 |
-
api_key=TAVILY_API_KEY
|
| 58 |
-
)
|
| 59 |
-
|
| 60 |
-
@tool
|
| 61 |
-
def execute_code_agent(task_description: str) -> str:
|
| 62 |
-
"""Use strictly for coding/calculation tasks."""
|
| 63 |
-
try:
|
| 64 |
-
sys_prompt = "You are jarvis. Solve this using Python code."
|
| 65 |
-
full_command = f"{sys_prompt}\nTask: {task_description}"
|
| 66 |
-
result = self.avii_agent.run(full_command)
|
| 67 |
-
return str(result)
|
| 68 |
-
except Exception as e:
|
| 69 |
-
return f"Error: {e}"
|
| 70 |
-
|
| 71 |
-
@tool
|
| 72 |
-
def safe_web_search(query: str) -> str:
|
| 73 |
-
"""Search the web safely."""
|
| 74 |
-
try:
|
| 75 |
-
results = self.web_search.invoke(query)
|
| 76 |
-
return str(results)
|
| 77 |
-
except Exception as e:
|
| 78 |
-
return f"Search Error: {str(e)}"
|
| 79 |
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
# ---
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
# Tools se wapas Agent ke paas
|
| 100 |
-
workflow.add_edge("tools", "agent")
|
| 101 |
|
| 102 |
-
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
# --- Helper Classes ---
|
| 106 |
-
class AgentState(TypedDict):
|
| 107 |
-
messages: Annotated[list, add_messages]
|
| 108 |
|
| 109 |
-
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
# Context window management
|
| 114 |
-
if len(messages) > 6:
|
| 115 |
-
trimmed_messages = [messages[0]] + messages[-5:]
|
| 116 |
-
else:
|
| 117 |
-
trimmed_messages = messages
|
| 118 |
-
|
| 119 |
-
# SYSTEM PROMPT INJECTION (Strict Formatting)
|
| 120 |
-
# Ye prompt ensure karega ki agent 'FINAL ANSWER:' format use kare
|
| 121 |
-
sys_prompt_content = (
|
| 122 |
-
"You are a general AI assistant. Solve the user's question.\n"
|
| 123 |
-
"IMPORTANT: Once you have the answer, you MUST end your response with:\n"
|
| 124 |
-
"FINAL ANSWER: [value]\n"
|
| 125 |
-
"Example: FINAL ANSWER: 2\n"
|
| 126 |
-
"Do not add extra conversational text after the final answer."
|
| 127 |
-
)
|
| 128 |
-
|
| 129 |
-
# Ensure system prompt is always first
|
| 130 |
-
if not isinstance(trimmed_messages[0], SystemMessage):
|
| 131 |
-
trimmed_messages.insert(0, SystemMessage(content=sys_prompt_content))
|
| 132 |
|
| 133 |
-
|
| 134 |
-
|
| 135 |
-
|
| 136 |
-
def router(self, state) -> Literal["tools", "__end__"]:
|
| 137 |
-
messages = state["messages"]
|
| 138 |
-
last_message = messages[-1]
|
| 139 |
-
|
| 140 |
-
if last_message.tool_calls:
|
| 141 |
-
return "tools"
|
| 142 |
-
return "__end__"
|
| 143 |
-
|
| 144 |
-
# --- MAIN EXECUTION (CLEANING MAGIC HERE) ---
|
| 145 |
-
def __call__(self, question: str) -> str:
|
| 146 |
-
# print(f"Agent received question: {question}")
|
| 147 |
-
|
| 148 |
-
inputs = {"messages": [HumanMessage(content=question)]}
|
| 149 |
-
result = self.app.invoke(inputs)
|
| 150 |
-
|
| 151 |
-
# Raw Answer from Agent
|
| 152 |
-
raw_answer = result["messages"][-1].content
|
| 153 |
-
|
| 154 |
-
# --- CLEANING LOGIC START ---
|
| 155 |
-
# 1. 'FINAL ANSWER:' ke baad ka hissa nikalo
|
| 156 |
-
if "FINAL ANSWER:" in raw_answer:
|
| 157 |
-
final_clean = raw_answer.split("FINAL ANSWER:")[-1].strip()
|
| 158 |
-
else:
|
| 159 |
-
final_clean = raw_answer.strip()
|
| 160 |
|
| 161 |
-
|
| 162 |
-
|
| 163 |
-
final_clean = final_clean[:-1]
|
| 164 |
-
|
| 165 |
-
# 3. Double check: Agar empty hai to original return kar do
|
| 166 |
-
if not final_clean:
|
| 167 |
-
final_clean = raw_answer
|
| 168 |
|
| 169 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 170 |
|
| 171 |
-
|
| 172 |
-
|
|
|
|
| 173 |
|
| 174 |
-
|
|
|
|
| 175 |
"""
|
| 176 |
-
|
| 177 |
-
|
|
|
|
|
|
|
| 178 |
"""
|
| 179 |
-
|
| 180 |
-
|
| 181 |
-
|
| 182 |
-
|
| 183 |
-
|
| 184 |
-
|
| 185 |
-
|
| 186 |
-
|
| 187 |
-
|
| 188 |
-
|
| 189 |
api_url = DEFAULT_API_URL
|
| 190 |
questions_url = f"{api_url}/questions"
|
| 191 |
submit_url = f"{api_url}/submit"
|
| 192 |
|
| 193 |
-
#
|
| 194 |
try:
|
| 195 |
agent = BasicAgent()
|
| 196 |
except Exception as e:
|
| 197 |
-
|
| 198 |
-
return f"Error initializing agent: {e}", None
|
| 199 |
-
# 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)
|
| 200 |
-
agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
|
| 201 |
-
print(agent_code)
|
| 202 |
|
| 203 |
-
|
| 204 |
-
print(f"
|
|
|
|
|
|
|
| 205 |
try:
|
| 206 |
-
|
| 207 |
-
|
| 208 |
-
questions_data = response.json()
|
| 209 |
-
if not questions_data:
|
| 210 |
-
print("Fetched questions list is empty.")
|
| 211 |
-
return "Fetched questions list is empty or invalid format.", None
|
| 212 |
-
print(f"Fetched {len(questions_data)} questions.")
|
| 213 |
-
except requests.exceptions.RequestException as e:
|
| 214 |
-
print(f"Error fetching questions: {e}")
|
| 215 |
-
return f"Error fetching questions: {e}", None
|
| 216 |
-
except requests.exceptions.JSONDecodeError as e:
|
| 217 |
-
print(f"Error decoding JSON response from questions endpoint: {e}")
|
| 218 |
-
print(f"Response text: {response.text[:500]}")
|
| 219 |
-
return f"Error decoding server response for questions: {e}", None
|
| 220 |
except Exception as e:
|
| 221 |
-
|
| 222 |
-
return f"An unexpected error occurred fetching questions: {e}", None
|
| 223 |
|
| 224 |
-
# 3. Run your Agent
|
| 225 |
results_log = []
|
| 226 |
answers_payload = []
|
| 227 |
-
|
|
|
|
|
|
|
|
|
|
| 228 |
for item in questions_data:
|
| 229 |
-
task_id = item
|
| 230 |
-
question_text = item
|
| 231 |
-
|
| 232 |
-
|
| 233 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 234 |
try:
|
| 235 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 236 |
answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
|
| 237 |
-
results_log.append({
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 238 |
except Exception as e:
|
| 239 |
-
|
| 240 |
-
results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": f"AGENT ERROR: {e}"})
|
| 241 |
|
| 242 |
-
|
| 243 |
-
|
| 244 |
-
|
| 245 |
|
| 246 |
-
#
|
| 247 |
-
|
| 248 |
-
|
| 249 |
-
|
|
|
|
|
|
|
|
|
|
| 250 |
|
| 251 |
-
# 5. Submit
|
| 252 |
-
print(f"Submitting {len(answers_payload)} answers to: {submit_url}")
|
| 253 |
try:
|
| 254 |
response = requests.post(submit_url, json=submission_data, timeout=60)
|
| 255 |
-
response.
|
| 256 |
-
|
| 257 |
-
|
| 258 |
-
|
| 259 |
-
|
| 260 |
-
|
| 261 |
-
f"
|
| 262 |
-
f"
|
|
|
|
|
|
|
| 263 |
)
|
| 264 |
-
|
| 265 |
-
|
| 266 |
-
return final_status, results_df
|
| 267 |
-
except requests.exceptions.HTTPError as e:
|
| 268 |
-
error_detail = f"Server responded with status {e.response.status_code}."
|
| 269 |
-
try:
|
| 270 |
-
error_json = e.response.json()
|
| 271 |
-
error_detail += f" Detail: {error_json.get('detail', e.response.text)}"
|
| 272 |
-
except requests.exceptions.JSONDecodeError:
|
| 273 |
-
error_detail += f" Response: {e.response.text[:500]}"
|
| 274 |
-
status_message = f"Submission Failed: {error_detail}"
|
| 275 |
-
print(status_message)
|
| 276 |
-
results_df = pd.DataFrame(results_log)
|
| 277 |
-
return status_message, results_df
|
| 278 |
-
except requests.exceptions.Timeout:
|
| 279 |
-
status_message = "Submission Failed: The request timed out."
|
| 280 |
-
print(status_message)
|
| 281 |
-
results_df = pd.DataFrame(results_log)
|
| 282 |
-
return status_message, results_df
|
| 283 |
-
except requests.exceptions.RequestException as e:
|
| 284 |
-
status_message = f"Submission Failed: Network error - {e}"
|
| 285 |
-
print(status_message)
|
| 286 |
-
results_df = pd.DataFrame(results_log)
|
| 287 |
-
return status_message, results_df
|
| 288 |
except Exception as e:
|
| 289 |
-
|
| 290 |
-
print(status_message)
|
| 291 |
-
results_df = pd.DataFrame(results_log)
|
| 292 |
-
return status_message, results_df
|
| 293 |
|
| 294 |
|
| 295 |
-
# ---
|
| 296 |
with gr.Blocks() as demo:
|
| 297 |
-
gr.Markdown("#
|
| 298 |
-
gr.Markdown(
|
| 299 |
-
|
| 300 |
-
|
| 301 |
-
|
| 302 |
-
|
| 303 |
-
|
| 304 |
-
|
| 305 |
-
|
| 306 |
-
---
|
| 307 |
-
**Disclaimers:**
|
| 308 |
-
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).
|
| 309 |
-
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.
|
| 310 |
-
"""
|
| 311 |
-
)
|
| 312 |
-
|
| 313 |
gr.LoginButton()
|
| 314 |
-
|
| 315 |
-
|
| 316 |
-
|
| 317 |
-
|
| 318 |
-
|
| 319 |
-
|
| 320 |
-
|
| 321 |
-
run_button.click(
|
| 322 |
fn=run_and_submit_all,
|
| 323 |
-
outputs=[
|
| 324 |
)
|
| 325 |
|
| 326 |
if __name__ == "__main__":
|
| 327 |
-
|
| 328 |
-
# Check for SPACE_HOST and SPACE_ID at startup for information
|
| 329 |
-
space_host_startup = os.getenv("SPACE_HOST")
|
| 330 |
-
space_id_startup = os.getenv("SPACE_ID") # Get SPACE_ID at startup
|
| 331 |
-
|
| 332 |
-
if space_host_startup:
|
| 333 |
-
print(f"β
SPACE_HOST found: {space_host_startup}")
|
| 334 |
-
print(f" Runtime URL should be: https://{space_host_startup}.hf.space")
|
| 335 |
-
else:
|
| 336 |
-
print("βΉοΈ SPACE_HOST environment variable not found (running locally?).")
|
| 337 |
-
|
| 338 |
-
if space_id_startup: # Print repo URLs if SPACE_ID is found
|
| 339 |
-
print(f"β
SPACE_ID found: {space_id_startup}")
|
| 340 |
-
print(f" Repo URL: https://huggingface.co/spaces/{space_id_startup}")
|
| 341 |
-
print(f" Repo Tree URL: https://huggingface.co/spaces/{space_id_startup}/tree/main")
|
| 342 |
-
else:
|
| 343 |
-
print("βΉοΈ SPACE_ID environment variable not found (running locally?). Repo URL cannot be determined.")
|
| 344 |
-
|
| 345 |
-
print("-"*(60 + len(" App Starting ")) + "\n")
|
| 346 |
-
|
| 347 |
-
print("Launching Gradio Interface for Basic Agent Evaluation...")
|
| 348 |
-
demo.launch(debug=True, share=False)
|
|
|
|
|
|
|
| 1 |
import os
|
|
|
|
| 2 |
import requests
|
| 3 |
import pandas as pd
|
| 4 |
+
import gradio as gr
|
| 5 |
+
from typing import Optional
|
| 6 |
|
| 7 |
+
# --- SMOLAGENTS IMPORTS ---
|
| 8 |
+
from smolagents import CodeAgent, LiteLLMModel, VisitWebpageTool, DuckDuckGoSearchTool
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 9 |
|
| 10 |
+
# --- CONSTANTS ---
|
| 11 |
DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
|
| 12 |
|
| 13 |
+
# --- AGENT CLASS (MISTRAL FOCUSED) ---
|
|
|
|
|
|
|
|
|
|
|
|
|
| 14 |
class BasicAgent:
|
| 15 |
def __init__(self):
|
| 16 |
+
print("π Initializing Mistral-Powered Agent...")
|
| 17 |
+
|
| 18 |
+
# --- 1. API KEY CHECK ---
|
| 19 |
+
mistral_key = os.getenv("MISTRAL_API_KEY")
|
| 20 |
+
if not mistral_key:
|
| 21 |
+
raise ValueError("β οΈ MISTRAL_API_KEY environment variable mein nahi mili! Settings me add karo.")
|
| 22 |
+
|
| 23 |
+
# --- 2. MODEL SETUP (Mistral Large) ---
|
| 24 |
+
# Mistral Large logic aur code ke liye best hai
|
| 25 |
+
model = LiteLLMModel(
|
| 26 |
+
model_id="mistral/mistral-large-latest",
|
| 27 |
+
api_key=mistral_key
|
| 28 |
)
|
| 29 |
|
| 30 |
+
# --- 3. TOOLS ---
|
| 31 |
+
# Web Search aur Page Visit tools
|
| 32 |
+
search_tool = DuckDuckGoSearchTool()
|
| 33 |
+
visit_tool = VisitWebpageTool()
|
| 34 |
+
|
| 35 |
+
# --- 4. CREATE AGENT ---
|
| 36 |
+
# CodeAgent use kar rahe hain jo seedha Python likhta hai
|
| 37 |
+
self.agent = CodeAgent(
|
| 38 |
+
tools=[search_tool, visit_tool],
|
| 39 |
+
model=model,
|
| 40 |
+
# GAIA ke liye ye libraries zaroori hain
|
| 41 |
+
additional_authorized_imports=[
|
| 42 |
+
"numpy", "pandas", "math", "datetime", "re", "csv", "json", "random", "itertools"
|
| 43 |
+
],
|
| 44 |
+
max_steps=25, # Mushkil sawalon ke liye steps badhaye
|
| 45 |
+
verbosity_level=2,
|
| 46 |
+
name="Mistral-Gaia-Solver"
|
| 47 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 48 |
|
| 49 |
+
def __call__(self, question: str, file_path: Optional[str] = None) -> str:
|
| 50 |
+
"""
|
| 51 |
+
Ye function agent ko run karta hai aur answer clean karta hai.
|
| 52 |
+
"""
|
| 53 |
+
# --- PROMPT ENGINEERING FOR EXACT MATCH ---
|
| 54 |
+
prompt = f"""
|
| 55 |
+
Current Task: {question}
|
| 56 |
+
|
| 57 |
+
INSTRUCTIONS:
|
| 58 |
+
1. You are an expert Python coding agent. Solve this step-by-step.
|
| 59 |
+
2. If a file is attached, YOU MUST READ IT using Python code immediately.
|
| 60 |
+
3. Do not assume values. Calculate them using the file or web search.
|
| 61 |
+
|
| 62 |
+
OUTPUT FORMAT RULES:
|
| 63 |
+
- Once you find the answer, output ONLY the final value.
|
| 64 |
+
- Do not write "The answer is...".
|
| 65 |
+
- Do not add units (like $, kg, years) unless specifically asked.
|
| 66 |
+
- Example: If the answer is 42, just print 42.
|
| 67 |
+
"""
|
|
|
|
|
|
|
| 68 |
|
| 69 |
+
if file_path:
|
| 70 |
+
prompt += f"\n\nβ οΈ ATTACHED FILE: A file is available at path '{file_path}'. Read it now."
|
|
|
|
|
|
|
|
|
|
|
|
|
| 71 |
|
| 72 |
+
try:
|
| 73 |
+
# Agent Run
|
| 74 |
+
print(f"π€ Agent thinking on: {question[:50]}...")
|
| 75 |
+
response = self.agent.run(prompt)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 76 |
|
| 77 |
+
# --- OUTPUT CLEANING ---
|
| 78 |
+
final_answer = str(response)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 79 |
|
| 80 |
+
# Common text removal
|
| 81 |
+
final_answer = final_answer.replace("Final Answer:", "").strip()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 82 |
|
| 83 |
+
# Remove trailing dot (e.g., "100." -> "100")
|
| 84 |
+
if final_answer.endswith(".") and len(final_answer) < 20:
|
| 85 |
+
final_answer = final_answer[:-1]
|
| 86 |
+
|
| 87 |
+
return final_answer
|
| 88 |
|
| 89 |
+
except Exception as e:
|
| 90 |
+
print(f"β Error in Agent: {e}")
|
| 91 |
+
return f"Error: {e}"
|
| 92 |
|
| 93 |
+
# --- MAIN EVALUATION RUNNER ---
|
| 94 |
+
def run_and_submit_all(profile: gr.OAuthProfile | None):
|
| 95 |
"""
|
| 96 |
+
1. Questions fetch karega.
|
| 97 |
+
2. FILE DOWNLOAD karega (Ye missing tha pehle).
|
| 98 |
+
3. Agent run karega.
|
| 99 |
+
4. Submit karega.
|
| 100 |
"""
|
| 101 |
+
|
| 102 |
+
# --- A. LOGIN CHECK ---
|
| 103 |
+
if profile is None:
|
| 104 |
+
return "β οΈ Please Login to Hugging Face with the button above.", None
|
| 105 |
+
|
| 106 |
+
username = profile.username
|
| 107 |
+
space_id = os.getenv("SPACE_ID")
|
| 108 |
+
|
| 109 |
+
# URLs
|
|
|
|
| 110 |
api_url = DEFAULT_API_URL
|
| 111 |
questions_url = f"{api_url}/questions"
|
| 112 |
submit_url = f"{api_url}/submit"
|
| 113 |
|
| 114 |
+
# --- B. INIT AGENT ---
|
| 115 |
try:
|
| 116 |
agent = BasicAgent()
|
| 117 |
except Exception as e:
|
| 118 |
+
return f"β Agent Init Error: {e}", None
|
|
|
|
|
|
|
|
|
|
|
|
|
| 119 |
|
| 120 |
+
agent_code_link = f"https://huggingface.co/spaces/{space_id}/tree/main"
|
| 121 |
+
print(f"π Code Link: {agent_code_link}")
|
| 122 |
+
|
| 123 |
+
# --- C. FETCH QUESTIONS ---
|
| 124 |
try:
|
| 125 |
+
print("π₯ Fetching questions...")
|
| 126 |
+
questions_data = requests.get(questions_url).json()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 127 |
except Exception as e:
|
| 128 |
+
return f"Error fetching questions: {e}", None
|
|
|
|
| 129 |
|
|
|
|
| 130 |
results_log = []
|
| 131 |
answers_payload = []
|
| 132 |
+
|
| 133 |
+
print(f"π Starting processing of {len(questions_data)} questions...")
|
| 134 |
+
|
| 135 |
+
# --- D. PROCESSING LOOP ---
|
| 136 |
for item in questions_data:
|
| 137 |
+
task_id = item["task_id"]
|
| 138 |
+
question_text = item["question"]
|
| 139 |
+
file_name = item.get("file_name") # GAIA tasks often have files
|
| 140 |
+
|
| 141 |
+
print(f"\n--- Processing Task {task_id} ---")
|
| 142 |
+
|
| 143 |
+
local_file_path = None
|
| 144 |
+
|
| 145 |
+
# 1. DOWNLOAD FILE (CRITICAL STEP)
|
| 146 |
+
if file_name:
|
| 147 |
+
print(f"π Downloading file: {file_name}")
|
| 148 |
+
try:
|
| 149 |
+
file_url = f"{api_url}/files/{task_id}"
|
| 150 |
+
file_resp = requests.get(file_url, timeout=10)
|
| 151 |
+
|
| 152 |
+
if file_resp.status_code == 200:
|
| 153 |
+
with open(file_name, "wb") as f:
|
| 154 |
+
f.write(file_resp.content)
|
| 155 |
+
local_file_path = file_name
|
| 156 |
+
print("β
File downloaded successfully.")
|
| 157 |
+
else:
|
| 158 |
+
print(f"β File download failed (Status {file_resp.status_code})")
|
| 159 |
+
except Exception as e:
|
| 160 |
+
print(f"β File download error: {e}")
|
| 161 |
+
|
| 162 |
+
# 2. RUN AGENT
|
| 163 |
try:
|
| 164 |
+
# Agent ko file path pass kar rahe hain
|
| 165 |
+
submitted_answer = agent(question_text, file_path=local_file_path)
|
| 166 |
+
|
| 167 |
+
print(f"π‘ Final Answer: {submitted_answer}")
|
| 168 |
+
|
| 169 |
answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
|
| 170 |
+
results_log.append({
|
| 171 |
+
"Task ID": task_id,
|
| 172 |
+
"Question": question_text,
|
| 173 |
+
"File": file_name if file_name else "None",
|
| 174 |
+
"Answer": submitted_answer
|
| 175 |
+
})
|
| 176 |
+
|
| 177 |
except Exception as e:
|
| 178 |
+
results_log.append({"Task ID": task_id, "Error": str(e)})
|
|
|
|
| 179 |
|
| 180 |
+
# 3. CLEANUP (File delete karo)
|
| 181 |
+
if local_file_path and os.path.exists(local_file_path):
|
| 182 |
+
os.remove(local_file_path)
|
| 183 |
|
| 184 |
+
# --- E. SUBMIT ---
|
| 185 |
+
print("π€ Submitting answers to leaderboard...")
|
| 186 |
+
submission_data = {
|
| 187 |
+
"username": username,
|
| 188 |
+
"agent_code": agent_code_link,
|
| 189 |
+
"answers": answers_payload
|
| 190 |
+
}
|
| 191 |
|
|
|
|
|
|
|
| 192 |
try:
|
| 193 |
response = requests.post(submit_url, json=submission_data, timeout=60)
|
| 194 |
+
res_json = response.json()
|
| 195 |
+
|
| 196 |
+
score = res_json.get('score', 0)
|
| 197 |
+
correct = res_json.get('correct_count', 0)
|
| 198 |
+
|
| 199 |
+
status_msg = (
|
| 200 |
+
f"β
Submission Done!\n"
|
| 201 |
+
f"User: {username}\n"
|
| 202 |
+
f"π Score: {score}%\n"
|
| 203 |
+
f"Correct: {correct}"
|
| 204 |
)
|
| 205 |
+
return status_msg, pd.DataFrame(results_log)
|
| 206 |
+
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 207 |
except Exception as e:
|
| 208 |
+
return f"β Submission Failed: {e}", pd.DataFrame(results_log)
|
|
|
|
|
|
|
|
|
|
| 209 |
|
| 210 |
|
| 211 |
+
# --- GRADIO UI ---
|
| 212 |
with gr.Blocks() as demo:
|
| 213 |
+
gr.Markdown("# π€ GAIA Agent Solver (Mistral + Files Fix)")
|
| 214 |
+
gr.Markdown("""
|
| 215 |
+
**Instruction:**
|
| 216 |
+
1. Login via Hugging Face button.
|
| 217 |
+
2. Click 'Run Evaluation'.
|
| 218 |
+
3. Wait (it takes time to process all questions).
|
| 219 |
+
""")
|
| 220 |
+
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 221 |
gr.LoginButton()
|
| 222 |
+
|
| 223 |
+
run_btn = gr.Button("Run Evaluation & Submit", variant="primary")
|
| 224 |
+
|
| 225 |
+
status_out = gr.Textbox(label="Status")
|
| 226 |
+
results_df = gr.DataFrame(label="Detailed Logs")
|
| 227 |
+
|
| 228 |
+
run_btn.click(
|
|
|
|
| 229 |
fn=run_and_submit_all,
|
| 230 |
+
outputs=[status_out, results_df]
|
| 231 |
)
|
| 232 |
|
| 233 |
if __name__ == "__main__":
|
| 234 |
+
demo.launch()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|