Update app.py
Browse files
app.py
CHANGED
|
@@ -1,34 +1,246 @@
|
|
| 1 |
import os
|
| 2 |
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("
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 16 |
def __call__(self, question: str) -> str:
|
| 17 |
-
print(f"
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
|
|
|
| 21 |
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 29 |
|
| 30 |
if profile:
|
| 31 |
-
username= f"{profile.username}"
|
| 32 |
print(f"User logged in: {username}")
|
| 33 |
else:
|
| 34 |
print("User not logged in.")
|
|
@@ -38,15 +250,15 @@ def run_and_submit_all( profile: gr.OAuthProfile | None):
|
|
| 38 |
questions_url = f"{api_url}/questions"
|
| 39 |
submit_url = f"{api_url}/submit"
|
| 40 |
|
| 41 |
-
# 1.
|
| 42 |
try:
|
| 43 |
agent = BasicAgent()
|
| 44 |
except Exception as e:
|
| 45 |
print(f"Error instantiating agent: {e}")
|
| 46 |
return f"Error initializing agent: {e}", None
|
| 47 |
-
|
| 48 |
agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
|
| 49 |
-
print(agent_code)
|
| 50 |
|
| 51 |
# 2. Fetch Questions
|
| 52 |
print(f"Fetching questions from: {questions_url}")
|
|
@@ -55,24 +267,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 |
-
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 |
-
|
| 70 |
-
return f"An unexpected error occurred fetching questions: {e}", None
|
| 71 |
|
| 72 |
-
# 3. Run
|
| 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")
|
|
@@ -82,24 +286,32 @@ def run_and_submit_all( profile: gr.OAuthProfile | None):
|
|
| 82 |
try:
|
| 83 |
submitted_answer = agent(question_text)
|
| 84 |
answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
|
| 85 |
-
results_log.append({
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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.
|
| 95 |
-
submission_data = {
|
| 96 |
-
|
| 97 |
-
|
|
|
|
|
|
|
|
|
|
| 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=
|
| 103 |
response.raise_for_status()
|
| 104 |
result_data = response.json()
|
| 105 |
final_status = (
|
|
@@ -110,60 +322,41 @@ def run_and_submit_all( profile: gr.OAuthProfile | None):
|
|
| 110 |
f"Message: {result_data.get('message', 'No message received.')}"
|
| 111 |
)
|
| 112 |
print("Submission successful.")
|
| 113 |
-
|
| 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
|
| 121 |
error_detail += f" Response: {e.response.text[:500]}"
|
| 122 |
-
|
| 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 |
-
|
| 138 |
-
print(status_message)
|
| 139 |
-
results_df = pd.DataFrame(results_log)
|
| 140 |
-
return status_message, results_df
|
| 141 |
|
| 142 |
|
| 143 |
-
#
|
|
|
|
|
|
|
|
|
|
| 144 |
with gr.Blocks() as demo:
|
| 145 |
-
gr.Markdown("#
|
| 146 |
-
gr.Markdown(
|
| 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 |
gr.LoginButton()
|
| 162 |
|
| 163 |
-
run_button = gr.Button("Run Evaluation & Submit All Answers")
|
| 164 |
|
| 165 |
-
status_output = gr.Textbox(label="Run Status / Submission Result", lines=
|
| 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(
|
|
@@ -172,25 +365,13 @@ with gr.Blocks() as demo:
|
|
| 172 |
)
|
| 173 |
|
| 174 |
if __name__ == "__main__":
|
| 175 |
-
print("\n" + "-"*30 + " App Starting " + "-"*30)
|
| 176 |
-
|
| 177 |
-
|
| 178 |
-
|
| 179 |
-
|
| 180 |
-
if
|
| 181 |
-
print(f"β
|
| 182 |
-
print(f"
|
| 183 |
-
|
| 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 |
import os
|
| 2 |
import gradio as gr
|
| 3 |
import requests
|
|
|
|
| 4 |
import pandas as pd
|
| 5 |
+
import re
|
| 6 |
+
import json
|
| 7 |
+
import math
|
| 8 |
+
import unicodedata
|
| 9 |
+
from datetime import datetime
|
| 10 |
+
|
| 11 |
+
# --- LangGraph + LangChain imports ---
|
| 12 |
+
from langgraph.prebuilt import create_react_agent
|
| 13 |
+
from langchain_huggingface import ChatHuggingFace, HuggingFaceEndpoint
|
| 14 |
+
from langchain_core.tools import tool
|
| 15 |
+
from langchain_community.tools import DuckDuckGoSearchRun
|
| 16 |
+
from langchain_community.utilities import WikipediaAPIWrapper
|
| 17 |
+
from langchain_core.messages import SystemMessage
|
| 18 |
|
|
|
|
| 19 |
# --- Constants ---
|
| 20 |
DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
|
| 21 |
|
| 22 |
+
# βββββββββββββββββββββββββββββββββββββββββββββ
|
| 23 |
+
# TOOLS
|
| 24 |
+
# βββββββββββββββββββββββββββββββββββββββββββββ
|
| 25 |
+
|
| 26 |
+
@tool
|
| 27 |
+
def web_search(query: str) -> str:
|
| 28 |
+
"""Search the web using DuckDuckGo. Use for current events, facts, and general knowledge."""
|
| 29 |
+
try:
|
| 30 |
+
search = DuckDuckGoSearchRun()
|
| 31 |
+
return search.run(query)
|
| 32 |
+
except Exception as e:
|
| 33 |
+
return f"Search error: {e}"
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
@tool
|
| 37 |
+
def wikipedia_search(query: str) -> str:
|
| 38 |
+
"""Search Wikipedia for encyclopedic knowledge, historical facts, biographies, science."""
|
| 39 |
+
try:
|
| 40 |
+
wiki = WikipediaAPIWrapper(top_k_results=2, doc_content_chars_max=3000)
|
| 41 |
+
return wiki.run(query)
|
| 42 |
+
except Exception as e:
|
| 43 |
+
return f"Wikipedia error: {e}"
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
@tool
|
| 47 |
+
def python_repl(code: str) -> str:
|
| 48 |
+
"""
|
| 49 |
+
Execute Python code for math calculations, data processing, logic.
|
| 50 |
+
Always print() the final result.
|
| 51 |
+
Example: print(2 + 2)
|
| 52 |
+
"""
|
| 53 |
+
import io, sys, math, json, re, unicodedata, datetime
|
| 54 |
+
old_stdout = sys.stdout
|
| 55 |
+
sys.stdout = io.StringIO()
|
| 56 |
+
try:
|
| 57 |
+
exec(code, {
|
| 58 |
+
"math": math, "json": json, "re": re,
|
| 59 |
+
"unicodedata": unicodedata, "datetime": datetime,
|
| 60 |
+
"__builtins__": __builtins__
|
| 61 |
+
})
|
| 62 |
+
output = sys.stdout.getvalue()
|
| 63 |
+
return output.strip() if output.strip() else "Code executed (no output). Use print() to see results."
|
| 64 |
+
except Exception as e:
|
| 65 |
+
return f"Code error: {e}"
|
| 66 |
+
finally:
|
| 67 |
+
sys.stdout = old_stdout
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
@tool
|
| 71 |
+
def read_file_from_url(url: str) -> str:
|
| 72 |
+
"""
|
| 73 |
+
Download and read a file from a URL (txt, csv, json, py, etc.).
|
| 74 |
+
Returns the file content as text.
|
| 75 |
+
"""
|
| 76 |
+
try:
|
| 77 |
+
response = requests.get(url, timeout=15)
|
| 78 |
+
response.raise_for_status()
|
| 79 |
+
content_type = response.headers.get("Content-Type", "")
|
| 80 |
+
if "text" in content_type or "json" in content_type:
|
| 81 |
+
return response.text[:5000]
|
| 82 |
+
else:
|
| 83 |
+
return f"Binary file ({content_type}), cannot read as text."
|
| 84 |
+
except Exception as e:
|
| 85 |
+
return f"Error reading file: {e}"
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
@tool
|
| 89 |
+
def get_task_file(task_id: str) -> str:
|
| 90 |
+
"""
|
| 91 |
+
Fetch the file associated with a GAIA task by its task_id.
|
| 92 |
+
Returns file content or description.
|
| 93 |
+
"""
|
| 94 |
+
try:
|
| 95 |
+
api_url = "https://agents-course-unit4-scoring.hf.space"
|
| 96 |
+
url = f"{api_url}/files/{task_id}"
|
| 97 |
+
response = requests.get(url, timeout=15)
|
| 98 |
+
if response.status_code == 200:
|
| 99 |
+
content_type = response.headers.get("Content-Type", "")
|
| 100 |
+
if "text" in content_type or "json" in content_type:
|
| 101 |
+
return response.text[:5000]
|
| 102 |
+
elif "image" in content_type:
|
| 103 |
+
return f"[Image file attached to task {task_id} - content-type: {content_type}]"
|
| 104 |
+
elif "audio" in content_type:
|
| 105 |
+
return f"[Audio file attached to task {task_id} - content-type: {content_type}]"
|
| 106 |
+
else:
|
| 107 |
+
return f"[File attached: {content_type}]"
|
| 108 |
+
else:
|
| 109 |
+
return f"No file found for task {task_id}"
|
| 110 |
+
except Exception as e:
|
| 111 |
+
return f"Error fetching task file: {e}"
|
| 112 |
+
|
| 113 |
+
|
| 114 |
+
@tool
|
| 115 |
+
def calculator(expression: str) -> str:
|
| 116 |
+
"""
|
| 117 |
+
Evaluate a simple math expression safely.
|
| 118 |
+
Examples: '2 + 2', '100 * 1.07 ** 5', 'math.sqrt(144)'
|
| 119 |
+
"""
|
| 120 |
+
try:
|
| 121 |
+
result = eval(expression, {"math": math, "__builtins__": {}})
|
| 122 |
+
return str(result)
|
| 123 |
+
except Exception as e:
|
| 124 |
+
return f"Calculation error: {e}. Try python_repl for complex code."
|
| 125 |
+
|
| 126 |
+
|
| 127 |
+
# βββββββββββββββββββββββββββββββββββββββββββββ
|
| 128 |
+
# SYSTEM PROMPT
|
| 129 |
+
# βββββββββββββββββββββββββββββββββββββββββββββ
|
| 130 |
+
|
| 131 |
+
SYSTEM_PROMPT = """You are a precise, expert AI assistant solving GAIA benchmark questions.
|
| 132 |
+
|
| 133 |
+
GAIA questions require careful reasoning and often multiple steps. Follow these rules:
|
| 134 |
+
|
| 135 |
+
## Answer Format (CRITICAL)
|
| 136 |
+
- Your FINAL answer must be the **bare minimum**: a number, a word, a name, a date, a short phrase.
|
| 137 |
+
- NO explanations, NO punctuation at the end, NO "The answer is...", NO sentences.
|
| 138 |
+
- Examples of correct final answers: `42`, `Marie Curie`, `Paris`, `1969`, `blue`, `$14.50`
|
| 139 |
+
- For lists, separate items with commas: `item1, item2, item3`
|
| 140 |
+
|
| 141 |
+
## Strategy
|
| 142 |
+
1. **Read carefully** β identify exactly what is being asked.
|
| 143 |
+
2. **Use tools** β search the web, Wikipedia, or run code to verify facts.
|
| 144 |
+
3. **Verify numbers** β always double-check calculations with the calculator or python_repl.
|
| 145 |
+
4. **Check for files** β if the question mentions an attachment or file, use get_task_file.
|
| 146 |
+
5. **Be specific** β GAIA answers are exact; approximate answers are wrong.
|
| 147 |
+
|
| 148 |
+
## Tool Usage
|
| 149 |
+
- Use `web_search` for recent events, facts, and general knowledge.
|
| 150 |
+
- Use `wikipedia_search` for biographies, history, science.
|
| 151 |
+
- Use `python_repl` for calculations, data manipulation, logic puzzles.
|
| 152 |
+
- Use `calculator` for quick arithmetic.
|
| 153 |
+
- Use `get_task_file` when a question refers to an attached file or document.
|
| 154 |
+
|
| 155 |
+
## Final Answer
|
| 156 |
+
Always end your response with:
|
| 157 |
+
FINAL ANSWER: <your answer here>
|
| 158 |
+
"""
|
| 159 |
+
|
| 160 |
+
# βββββββββββββββββββββββββββββββββββββββββββββ
|
| 161 |
+
# AGENT
|
| 162 |
+
# βββββββββββββββββββββββββββββββββββββββββββββ
|
| 163 |
+
|
| 164 |
class BasicAgent:
|
| 165 |
def __init__(self):
|
| 166 |
+
print("Initializing LangGraph ReAct Agent with Llama 3.3 70B...")
|
| 167 |
+
|
| 168 |
+
hf_token = os.getenv("HF_TOKEN")
|
| 169 |
+
|
| 170 |
+
llm_endpoint = HuggingFaceEndpoint(
|
| 171 |
+
repo_id="meta-llama/Llama-3.3-70B-Instruct",
|
| 172 |
+
huggingfacehub_api_token=hf_token,
|
| 173 |
+
task="text-generation",
|
| 174 |
+
max_new_tokens=1024,
|
| 175 |
+
temperature=0.1,
|
| 176 |
+
do_sample=False,
|
| 177 |
+
)
|
| 178 |
+
llm = ChatHuggingFace(llm=llm_endpoint)
|
| 179 |
+
|
| 180 |
+
tools = [
|
| 181 |
+
web_search,
|
| 182 |
+
wikipedia_search,
|
| 183 |
+
python_repl,
|
| 184 |
+
calculator,
|
| 185 |
+
read_file_from_url,
|
| 186 |
+
get_task_file,
|
| 187 |
+
]
|
| 188 |
+
|
| 189 |
+
self.agent = create_react_agent(
|
| 190 |
+
model=llm,
|
| 191 |
+
tools=tools,
|
| 192 |
+
state_modifier=SYSTEM_PROMPT,
|
| 193 |
+
)
|
| 194 |
+
|
| 195 |
+
print("Agent ready.")
|
| 196 |
+
|
| 197 |
def __call__(self, question: str) -> str:
|
| 198 |
+
print(f"\n[AGENT] Question: {question[:100]}...")
|
| 199 |
+
try:
|
| 200 |
+
result = self.agent.invoke({
|
| 201 |
+
"messages": [("user", question)]
|
| 202 |
+
})
|
| 203 |
|
| 204 |
+
# Extract last AI message
|
| 205 |
+
last_message = result["messages"][-1].content
|
| 206 |
+
print(f"[AGENT] Raw output: {last_message[:200]}...")
|
| 207 |
+
|
| 208 |
+
# Extract FINAL ANSWER if present
|
| 209 |
+
answer = self._extract_final_answer(last_message)
|
| 210 |
+
print(f"[AGENT] Final answer: {answer}")
|
| 211 |
+
return answer
|
| 212 |
+
|
| 213 |
+
except Exception as e:
|
| 214 |
+
print(f"[AGENT] Error: {e}")
|
| 215 |
+
return f"Error: {e}"
|
| 216 |
+
|
| 217 |
+
def _extract_final_answer(self, text: str) -> str:
|
| 218 |
+
"""Extract the FINAL ANSWER from agent output."""
|
| 219 |
+
# Try to find "FINAL ANSWER: ..." pattern
|
| 220 |
+
patterns = [
|
| 221 |
+
r"FINAL ANSWER:\s*(.+?)(?:\n|$)",
|
| 222 |
+
r"Final Answer:\s*(.+?)(?:\n|$)",
|
| 223 |
+
r"final answer:\s*(.+?)(?:\n|$)",
|
| 224 |
+
]
|
| 225 |
+
for pattern in patterns:
|
| 226 |
+
match = re.search(pattern, text, re.IGNORECASE)
|
| 227 |
+
if match:
|
| 228 |
+
return match.group(1).strip()
|
| 229 |
+
|
| 230 |
+
# Fallback: return last non-empty line
|
| 231 |
+
lines = [l.strip() for l in text.strip().split("\n") if l.strip()]
|
| 232 |
+
return lines[-1] if lines else text.strip()
|
| 233 |
+
|
| 234 |
+
|
| 235 |
+
# βββββββββββββββββββββββββββββββββββββββββββββ
|
| 236 |
+
# GRADIO RUNNER
|
| 237 |
+
# βββββββββββββββββββββββββββββββββββββββββββββ
|
| 238 |
+
|
| 239 |
+
def run_and_submit_all(profile: gr.OAuthProfile | None):
|
| 240 |
+
space_id = os.getenv("SPACE_ID")
|
| 241 |
|
| 242 |
if profile:
|
| 243 |
+
username = f"{profile.username}"
|
| 244 |
print(f"User logged in: {username}")
|
| 245 |
else:
|
| 246 |
print("User not logged in.")
|
|
|
|
| 250 |
questions_url = f"{api_url}/questions"
|
| 251 |
submit_url = f"{api_url}/submit"
|
| 252 |
|
| 253 |
+
# 1. Init Agent
|
| 254 |
try:
|
| 255 |
agent = BasicAgent()
|
| 256 |
except Exception as e:
|
| 257 |
print(f"Error instantiating agent: {e}")
|
| 258 |
return f"Error initializing agent: {e}", None
|
| 259 |
+
|
| 260 |
agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
|
| 261 |
+
print(f"Agent code: {agent_code}")
|
| 262 |
|
| 263 |
# 2. Fetch Questions
|
| 264 |
print(f"Fetching questions from: {questions_url}")
|
|
|
|
| 267 |
response.raise_for_status()
|
| 268 |
questions_data = response.json()
|
| 269 |
if not questions_data:
|
| 270 |
+
return "Fetched questions list is empty or invalid format.", None
|
|
|
|
| 271 |
print(f"Fetched {len(questions_data)} questions.")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 272 |
except Exception as e:
|
| 273 |
+
return f"Error fetching questions: {e}", None
|
|
|
|
| 274 |
|
| 275 |
+
# 3. Run Agent
|
| 276 |
results_log = []
|
| 277 |
answers_payload = []
|
| 278 |
print(f"Running agent on {len(questions_data)} questions...")
|
| 279 |
+
|
| 280 |
for item in questions_data:
|
| 281 |
task_id = item.get("task_id")
|
| 282 |
question_text = item.get("question")
|
|
|
|
| 286 |
try:
|
| 287 |
submitted_answer = agent(question_text)
|
| 288 |
answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
|
| 289 |
+
results_log.append({
|
| 290 |
+
"Task ID": task_id,
|
| 291 |
+
"Question": question_text[:100],
|
| 292 |
+
"Submitted Answer": submitted_answer
|
| 293 |
+
})
|
| 294 |
except Exception as e:
|
| 295 |
+
print(f"Error on task {task_id}: {e}")
|
| 296 |
+
results_log.append({
|
| 297 |
+
"Task ID": task_id,
|
| 298 |
+
"Question": question_text[:100],
|
| 299 |
+
"Submitted Answer": f"AGENT ERROR: {e}"
|
| 300 |
+
})
|
| 301 |
|
| 302 |
if not answers_payload:
|
|
|
|
| 303 |
return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)
|
| 304 |
|
| 305 |
+
# 4. Submit
|
| 306 |
+
submission_data = {
|
| 307 |
+
"username": username.strip(),
|
| 308 |
+
"agent_code": agent_code,
|
| 309 |
+
"answers": answers_payload
|
| 310 |
+
}
|
| 311 |
+
print(f"Submitting {len(answers_payload)} answers...")
|
| 312 |
|
|
|
|
|
|
|
| 313 |
try:
|
| 314 |
+
response = requests.post(submit_url, json=submission_data, timeout=120)
|
| 315 |
response.raise_for_status()
|
| 316 |
result_data = response.json()
|
| 317 |
final_status = (
|
|
|
|
| 322 |
f"Message: {result_data.get('message', 'No message received.')}"
|
| 323 |
)
|
| 324 |
print("Submission successful.")
|
| 325 |
+
return final_status, pd.DataFrame(results_log)
|
|
|
|
| 326 |
except requests.exceptions.HTTPError as e:
|
| 327 |
error_detail = f"Server responded with status {e.response.status_code}."
|
| 328 |
try:
|
| 329 |
error_json = e.response.json()
|
| 330 |
error_detail += f" Detail: {error_json.get('detail', e.response.text)}"
|
| 331 |
+
except Exception:
|
| 332 |
error_detail += f" Response: {e.response.text[:500]}"
|
| 333 |
+
return f"Submission Failed: {error_detail}", pd.DataFrame(results_log)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 334 |
except Exception as e:
|
| 335 |
+
return f"Submission Failed: {e}", pd.DataFrame(results_log)
|
|
|
|
|
|
|
|
|
|
| 336 |
|
| 337 |
|
| 338 |
+
# βββββββββββββββββββββββββββββββββββββββββββββ
|
| 339 |
+
# GRADIO UI
|
| 340 |
+
# βββββββββββββββββββββββββββββββββββββββββββββ
|
| 341 |
+
|
| 342 |
with gr.Blocks() as demo:
|
| 343 |
+
gr.Markdown("# π€ GAIA Agent β LangGraph + Llama 3.3 70B")
|
| 344 |
+
gr.Markdown("""
|
| 345 |
+
**Stack:** LangGraph ReAct Β· Llama 3.3 70B (HF Inference) Β· DuckDuckGo Β· Wikipedia Β· Python REPL
|
| 346 |
+
|
| 347 |
+
**Instructions:**
|
| 348 |
+
1. Log in with your HuggingFace account below.
|
| 349 |
+
2. Make sure `HF_TOKEN` is set as a Space secret (with access to Llama 3.3 70B).
|
| 350 |
+
3. Click **Run Evaluation & Submit All Answers**.
|
| 351 |
+
|
| 352 |
+
> β οΈ The run can take several minutes β the agent reasons through each question step by step.
|
| 353 |
+
""")
|
|
|
|
|
|
|
|
|
|
|
|
|
| 354 |
|
| 355 |
gr.LoginButton()
|
| 356 |
|
| 357 |
+
run_button = gr.Button("βΆοΈ Run Evaluation & Submit All Answers", variant="primary")
|
| 358 |
|
| 359 |
+
status_output = gr.Textbox(label="Run Status / Submission Result", lines=6, interactive=False)
|
|
|
|
| 360 |
results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True)
|
| 361 |
|
| 362 |
run_button.click(
|
|
|
|
| 365 |
)
|
| 366 |
|
| 367 |
if __name__ == "__main__":
|
| 368 |
+
print("\n" + "-" * 30 + " App Starting " + "-" * 30)
|
| 369 |
+
space_host = os.getenv("SPACE_HOST")
|
| 370 |
+
space_id = os.getenv("SPACE_ID")
|
| 371 |
+
if space_host:
|
| 372 |
+
print(f"β
SPACE_HOST: {space_host}")
|
| 373 |
+
if space_id:
|
| 374 |
+
print(f"β
SPACE_ID: {space_id}")
|
| 375 |
+
print(f" Repo: https://huggingface.co/spaces/{space_id}/tree/main")
|
| 376 |
+
print("-" * 60 + "\n")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 377 |
demo.launch(debug=True, share=False)
|