Spaces:
Sleeping
Sleeping
My agent
Browse files
app.py
CHANGED
|
@@ -1,34 +1,377 @@
|
|
| 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("BasicAgent initialized.")
|
|
|
|
| 16 |
def __call__(self, question: str) -> str:
|
| 17 |
-
print(f"Agent received question (first
|
| 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 |
-
|
| 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,70 +381,95 @@ 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. Instantiate Agent ( modify this part to create your agent)
|
| 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 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 49 |
print(agent_code)
|
| 50 |
|
| 51 |
-
# 2. Fetch Questions
|
| 52 |
print(f"Fetching questions from: {questions_url}")
|
| 53 |
try:
|
| 54 |
response = requests.get(questions_url, timeout=15)
|
| 55 |
response.raise_for_status()
|
| 56 |
questions_data = response.json()
|
|
|
|
| 57 |
if not questions_data:
|
| 58 |
-
|
| 59 |
-
|
|
|
|
| 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
|
| 65 |
-
|
| 66 |
-
|
| 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 |
submitted_answer = agent(question_text)
|
| 84 |
-
answers_payload.append(
|
| 85 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
-
|
| 95 |
-
|
| 96 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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"
|
|
@@ -109,30 +477,36 @@ def run_and_submit_all( profile: gr.OAuthProfile | None):
|
|
| 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
|
| 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)
|
|
@@ -140,21 +514,19 @@ def run_and_submit_all( profile: gr.OAuthProfile | None):
|
|
| 140 |
return status_message, results_df
|
| 141 |
|
| 142 |
|
| 143 |
-
# --- Build Gradio Interface using Blocks ---
|
| 144 |
with gr.Blocks() as demo:
|
| 145 |
gr.Markdown("# Basic Agent Evaluation Runner")
|
| 146 |
gr.Markdown(
|
| 147 |
"""
|
| 148 |
**Instructions:**
|
| 149 |
|
| 150 |
-
1.
|
| 151 |
-
2.
|
| 152 |
-
3.
|
| 153 |
|
| 154 |
---
|
| 155 |
**Disclaimers:**
|
| 156 |
-
Once clicking on the
|
| 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 |
|
|
@@ -162,20 +534,24 @@ with gr.Blocks() as demo:
|
|
| 162 |
|
| 163 |
run_button = gr.Button("Run Evaluation & Submit All Answers")
|
| 164 |
|
| 165 |
-
status_output = gr.Textbox(
|
| 166 |
-
|
|
|
|
|
|
|
|
|
|
| 167 |
results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True)
|
| 168 |
|
| 169 |
run_button.click(
|
| 170 |
fn=run_and_submit_all,
|
| 171 |
-
outputs=[status_output, results_table]
|
| 172 |
)
|
| 173 |
|
|
|
|
| 174 |
if __name__ == "__main__":
|
| 175 |
-
print("\n" + "-"*30 + " App Starting " + "-"*30)
|
| 176 |
-
|
| 177 |
space_host_startup = os.getenv("SPACE_HOST")
|
| 178 |
-
space_id_startup = os.getenv("SPACE_ID")
|
| 179 |
|
| 180 |
if space_host_startup:
|
| 181 |
print(f"✅ SPACE_HOST found: {space_host_startup}")
|
|
@@ -183,14 +559,13 @@ if __name__ == "__main__":
|
|
| 183 |
else:
|
| 184 |
print("ℹ️ SPACE_HOST environment variable not found (running locally?).")
|
| 185 |
|
| 186 |
-
if space_id_startup:
|
| 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 json
|
| 3 |
+
import ast
|
| 4 |
+
import operator as op
|
| 5 |
+
from typing import TypedDict, Annotated, Dict, List
|
| 6 |
+
|
| 7 |
import gradio as gr
|
| 8 |
import requests
|
|
|
|
| 9 |
import pandas as pd
|
| 10 |
+
from dotenv import load_dotenv
|
| 11 |
+
from tavily import TavilyClient
|
| 12 |
+
|
| 13 |
+
from langchain.tools import tool
|
| 14 |
+
from langchain_openai import ChatOpenAI
|
| 15 |
+
from langchain_core.messages import SystemMessage, HumanMessage, AnyMessage, RemoveMessage
|
| 16 |
+
from langgraph.graph.message import add_messages, REMOVE_ALL_MESSAGES
|
| 17 |
+
from langgraph.graph import START, END, StateGraph
|
| 18 |
+
from langgraph.prebuilt import ToolNode
|
| 19 |
+
|
| 20 |
|
|
|
|
|
|
|
| 21 |
DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
|
| 22 |
|
| 23 |
+
load_dotenv()
|
| 24 |
+
|
| 25 |
+
OPENAI_API_KEY = os.getenv("OPENAI_API_KEY")
|
| 26 |
+
TAVILY_API_KEY = os.getenv("TAVILY_API_KEY")
|
| 27 |
+
|
| 28 |
+
if not OPENAI_API_KEY:
|
| 29 |
+
raise ValueError("OPENAI_API_KEY is missing")
|
| 30 |
+
|
| 31 |
+
if not TAVILY_API_KEY:
|
| 32 |
+
raise ValueError("TAVILY_API_KEY is missing")
|
| 33 |
+
|
| 34 |
+
tavily_client = TavilyClient(TAVILY_API_KEY)
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
class GaiaState(TypedDict):
|
| 38 |
+
original_question: str
|
| 39 |
+
subquestions: List[str]
|
| 40 |
+
current_subquestion_index: int
|
| 41 |
+
subanswers: Dict[str, str]
|
| 42 |
+
final_answer: str
|
| 43 |
+
messages: Annotated[list[AnyMessage], add_messages]
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
_ALLOWED_OPERATORS = {
|
| 47 |
+
ast.Add: op.add,
|
| 48 |
+
ast.Sub: op.sub,
|
| 49 |
+
ast.Mult: op.mul,
|
| 50 |
+
ast.Div: op.truediv,
|
| 51 |
+
ast.USub: op.neg,
|
| 52 |
+
ast.UAdd: op.pos,
|
| 53 |
+
}
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
def _safe_eval(node):
|
| 57 |
+
if isinstance(node, ast.Expression):
|
| 58 |
+
return _safe_eval(node.body)
|
| 59 |
+
if isinstance(node, ast.Constant):
|
| 60 |
+
if isinstance(node.value, (int, float)):
|
| 61 |
+
return node.value
|
| 62 |
+
raise ValueError("Only numeric constants are allowed")
|
| 63 |
+
if isinstance(node, ast.Num):
|
| 64 |
+
return node.n
|
| 65 |
+
if isinstance(node, ast.BinOp):
|
| 66 |
+
if type(node.op) not in _ALLOWED_OPERATORS:
|
| 67 |
+
raise ValueError("Unsupported operation")
|
| 68 |
+
left = _safe_eval(node.left)
|
| 69 |
+
right = _safe_eval(node.right)
|
| 70 |
+
if isinstance(node.op, ast.Div) and right == 0:
|
| 71 |
+
raise ValueError("Division by zero")
|
| 72 |
+
return _ALLOWED_OPERATORS[type(node.op)](left, right)
|
| 73 |
+
if isinstance(node, ast.UnaryOp):
|
| 74 |
+
if type(node.op) not in _ALLOWED_OPERATORS:
|
| 75 |
+
raise ValueError("Unsupported unary operation")
|
| 76 |
+
operand = _safe_eval(node.operand)
|
| 77 |
+
return _ALLOWED_OPERATORS[type(node.op)](operand)
|
| 78 |
+
raise ValueError("Invalid expression")
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
@tool
|
| 82 |
+
def calculator(expression: str) -> str:
|
| 83 |
+
"""
|
| 84 |
+
Evaluate a mathematical expression safely.
|
| 85 |
+
Supports numbers, parentheses, +, -, *, /, and unary +/-.
|
| 86 |
+
Returns the result as a string.
|
| 87 |
+
"""
|
| 88 |
+
try:
|
| 89 |
+
parsed = ast.parse(expression, mode="eval")
|
| 90 |
+
result = _safe_eval(parsed)
|
| 91 |
+
if isinstance(result, float) and result.is_integer():
|
| 92 |
+
result = int(result)
|
| 93 |
+
return str(result)
|
| 94 |
+
except Exception as e:
|
| 95 |
+
return f"Error: {e}"
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
@tool
|
| 99 |
+
def web_search(query: str) -> str:
|
| 100 |
+
"""
|
| 101 |
+
Search the web for up-to-date information relevant to a question.
|
| 102 |
+
Returns top search results with titles, URLs, and snippets.
|
| 103 |
+
"""
|
| 104 |
+
try:
|
| 105 |
+
search_response = tavily_client.search(query, max_results=5)
|
| 106 |
+
results = search_response.get("results", [])
|
| 107 |
+
|
| 108 |
+
if not results:
|
| 109 |
+
return f"No search results found for query: {query}"
|
| 110 |
+
|
| 111 |
+
formatted_results = [f"Search query: {query}", "", "Top results:"]
|
| 112 |
+
|
| 113 |
+
for i, result in enumerate(results, start=1):
|
| 114 |
+
title = result.get("title", "No title")
|
| 115 |
+
url = result.get("url", "No URL")
|
| 116 |
+
content = result.get("content", "No snippet available")
|
| 117 |
+
formatted_results.append(
|
| 118 |
+
f"{i}. {title}\nURL: {url}\nSnippet: {content}\n"
|
| 119 |
+
)
|
| 120 |
+
|
| 121 |
+
return "\n".join(formatted_results)
|
| 122 |
+
except Exception as e:
|
| 123 |
+
return f"Web search error: {e}"
|
| 124 |
+
|
| 125 |
+
|
| 126 |
+
tools = [web_search, calculator]
|
| 127 |
+
tool_node = ToolNode(tools)
|
| 128 |
+
|
| 129 |
+
|
| 130 |
+
def get_model(temperature: float = 0):
|
| 131 |
+
return ChatOpenAI(
|
| 132 |
+
model="gpt-4.1-mini",
|
| 133 |
+
temperature=temperature,
|
| 134 |
+
api_key=OPENAI_API_KEY,
|
| 135 |
+
)
|
| 136 |
+
|
| 137 |
+
|
| 138 |
+
def planner(state: GaiaState):
|
| 139 |
+
model = get_model()
|
| 140 |
+
|
| 141 |
+
prompt = """You are an expert problem decomposition agent.
|
| 142 |
+
|
| 143 |
+
Your job is to analyze a question and decide whether it should be decomposed into smaller subquestions.
|
| 144 |
+
|
| 145 |
+
Rules:
|
| 146 |
+
1. If the question is simple and can be answered directly, return a single subquestion equal to the original question.
|
| 147 |
+
2. If the question requires multiple reasoning steps, break it into clear atomic subquestions.
|
| 148 |
+
3. Each subquestion should be answerable independently using tools such as web search or calculation.
|
| 149 |
+
4. Do NOT answer the question yourself.
|
| 150 |
+
5. Only produce subquestions needed to solve the problem.
|
| 151 |
+
|
| 152 |
+
Output format (JSON only):
|
| 153 |
+
{
|
| 154 |
+
"subquestions": [
|
| 155 |
+
"subquestion 1",
|
| 156 |
+
"subquestion 2"
|
| 157 |
+
]
|
| 158 |
+
}
|
| 159 |
+
|
| 160 |
+
Do not include explanations.
|
| 161 |
+
Do not include text outside the JSON."""
|
| 162 |
+
|
| 163 |
+
messages = [
|
| 164 |
+
SystemMessage(content=prompt),
|
| 165 |
+
HumanMessage(content=state["original_question"]),
|
| 166 |
+
]
|
| 167 |
+
|
| 168 |
+
response = model.invoke(messages)
|
| 169 |
+
|
| 170 |
+
subquestions = []
|
| 171 |
+
try:
|
| 172 |
+
content = response.content if isinstance(response.content, str) else str(response.content)
|
| 173 |
+
parsed = json.loads(content)
|
| 174 |
+
subquestions = parsed.get("subquestions", [])
|
| 175 |
+
except Exception:
|
| 176 |
+
subquestions = []
|
| 177 |
+
|
| 178 |
+
if not isinstance(subquestions, list) or not subquestions:
|
| 179 |
+
subquestions = [state["original_question"]]
|
| 180 |
+
|
| 181 |
+
subquestions = [str(q).strip() for q in subquestions if str(q).strip()]
|
| 182 |
+
|
| 183 |
+
if not subquestions:
|
| 184 |
+
subquestions = [state["original_question"]]
|
| 185 |
+
|
| 186 |
+
return {
|
| 187 |
+
"subquestions": subquestions,
|
| 188 |
+
"current_subquestion_index": 0,
|
| 189 |
+
}
|
| 190 |
+
|
| 191 |
+
|
| 192 |
+
def answer_subquestion(state: GaiaState):
|
| 193 |
+
current_index = state["current_subquestion_index"]
|
| 194 |
+
current_subquestion = state["subquestions"][current_index]
|
| 195 |
+
|
| 196 |
+
solver_model = get_model().bind_tools(tools)
|
| 197 |
+
|
| 198 |
+
if not state["messages"]:
|
| 199 |
+
prompt = """You are a research assistant solving a complex question.
|
| 200 |
+
|
| 201 |
+
You may use tools when necessary to obtain information or perform calculations.
|
| 202 |
+
|
| 203 |
+
Use tools when:
|
| 204 |
+
- the answer requires up-to-date information
|
| 205 |
+
- the answer requires external data
|
| 206 |
+
- the answer requires arithmetic computation
|
| 207 |
+
|
| 208 |
+
If you already know the answer with high confidence, answer directly.
|
| 209 |
+
|
| 210 |
+
Be concise and accurate."""
|
| 211 |
+
|
| 212 |
+
messages = [
|
| 213 |
+
SystemMessage(content=prompt),
|
| 214 |
+
HumanMessage(content=current_subquestion),
|
| 215 |
+
]
|
| 216 |
+
else:
|
| 217 |
+
messages = state["messages"]
|
| 218 |
+
|
| 219 |
+
response = solver_model.invoke(messages)
|
| 220 |
+
return {"messages": [response]}
|
| 221 |
+
|
| 222 |
+
|
| 223 |
+
def route_after_llm(state: GaiaState):
|
| 224 |
+
last_message = state["messages"][-1]
|
| 225 |
+
if getattr(last_message, "tool_calls", None):
|
| 226 |
+
return "tools"
|
| 227 |
+
return "store_subanswer"
|
| 228 |
+
|
| 229 |
+
|
| 230 |
+
def store_subanswer(state: GaiaState):
|
| 231 |
+
current_index = state["current_subquestion_index"]
|
| 232 |
+
next_index = current_index + 1
|
| 233 |
+
current_subquestion = state["subquestions"][current_index]
|
| 234 |
+
last_message = state["messages"][-1]
|
| 235 |
+
|
| 236 |
+
answer_text = last_message.content
|
| 237 |
+
if isinstance(answer_text, list):
|
| 238 |
+
answer_text = " ".join(str(x) for x in answer_text)
|
| 239 |
+
else:
|
| 240 |
+
answer_text = str(answer_text)
|
| 241 |
+
|
| 242 |
+
updated_subanswers = dict(state["subanswers"])
|
| 243 |
+
updated_subanswers[current_subquestion] = answer_text.strip()
|
| 244 |
+
|
| 245 |
+
return {
|
| 246 |
+
"current_subquestion_index": next_index,
|
| 247 |
+
"subanswers": updated_subanswers,
|
| 248 |
+
"messages": [RemoveMessage(id=REMOVE_ALL_MESSAGES)],
|
| 249 |
+
}
|
| 250 |
+
|
| 251 |
+
|
| 252 |
+
def route_subquestion_loop(state: GaiaState):
|
| 253 |
+
if state["current_subquestion_index"] < len(state["subquestions"]):
|
| 254 |
+
return "answer_subquestion"
|
| 255 |
+
return "final_answer"
|
| 256 |
+
|
| 257 |
+
|
| 258 |
+
def final_answer(state: GaiaState):
|
| 259 |
+
model = get_model()
|
| 260 |
+
|
| 261 |
+
prompt = """You are a general AI assistant. I will give you an original question and a set of subquestions with their answers. You must formulate one final answer based only on that information.
|
| 262 |
+
|
| 263 |
+
Finish your answer with the following template exactly:
|
| 264 |
+
FINAL ANSWER: [YOUR FINAL ANSWER]
|
| 265 |
+
|
| 266 |
+
YOUR FINAL ANSWER should be:
|
| 267 |
+
- a number, OR
|
| 268 |
+
- as few words as possible, OR
|
| 269 |
+
- a comma separated list of numbers and/or strings
|
| 270 |
+
|
| 271 |
+
Rules:
|
| 272 |
+
- If asked for a number, do not use commas in the number and do not use units unless explicitly requested.
|
| 273 |
+
- If asked for a string, do not use articles and do not use abbreviations unless explicitly requested.
|
| 274 |
+
- If asked for a comma separated list, apply the same rules to each element.
|
| 275 |
+
- Do not add anything after FINAL ANSWER."""
|
| 276 |
+
|
| 277 |
+
question_answer = ""
|
| 278 |
+
for question, answer in state["subanswers"].items():
|
| 279 |
+
question_answer += f"Question: {question}\nAnswer: {answer}\n\n"
|
| 280 |
+
|
| 281 |
+
user_content = (
|
| 282 |
+
f"Original question: {state['original_question']}\n\n"
|
| 283 |
+
f"Subquestion answers:\n{question_answer}"
|
| 284 |
+
)
|
| 285 |
+
|
| 286 |
+
messages = [
|
| 287 |
+
SystemMessage(content=prompt),
|
| 288 |
+
HumanMessage(content=user_content),
|
| 289 |
+
]
|
| 290 |
+
|
| 291 |
+
response = model.invoke(messages)
|
| 292 |
+
|
| 293 |
+
content = response.content
|
| 294 |
+
if isinstance(content, list):
|
| 295 |
+
content = " ".join(str(x) for x in content)
|
| 296 |
+
else:
|
| 297 |
+
content = str(content)
|
| 298 |
+
|
| 299 |
+
return {"final_answer": content.strip()}
|
| 300 |
+
|
| 301 |
+
|
| 302 |
+
def build_graph():
|
| 303 |
+
builder = StateGraph(GaiaState)
|
| 304 |
+
|
| 305 |
+
builder.add_node("planner", planner)
|
| 306 |
+
builder.add_node("answer_subquestion", answer_subquestion)
|
| 307 |
+
builder.add_node("tools", tool_node)
|
| 308 |
+
builder.add_node("store_subanswer", store_subanswer)
|
| 309 |
+
builder.add_node("final_answer", final_answer)
|
| 310 |
+
|
| 311 |
+
builder.add_edge(START, "planner")
|
| 312 |
+
builder.add_edge("planner", "answer_subquestion")
|
| 313 |
+
builder.add_edge("tools", "answer_subquestion")
|
| 314 |
+
builder.add_edge("final_answer", END)
|
| 315 |
+
|
| 316 |
+
builder.add_conditional_edges(
|
| 317 |
+
"answer_subquestion",
|
| 318 |
+
route_after_llm,
|
| 319 |
+
{
|
| 320 |
+
"tools": "tools",
|
| 321 |
+
"store_subanswer": "store_subanswer",
|
| 322 |
+
},
|
| 323 |
+
)
|
| 324 |
+
|
| 325 |
+
builder.add_conditional_edges(
|
| 326 |
+
"store_subanswer",
|
| 327 |
+
route_subquestion_loop,
|
| 328 |
+
{
|
| 329 |
+
"answer_subquestion": "answer_subquestion",
|
| 330 |
+
"final_answer": "final_answer",
|
| 331 |
+
},
|
| 332 |
+
)
|
| 333 |
+
|
| 334 |
+
return builder.compile()
|
| 335 |
+
|
| 336 |
+
|
| 337 |
class BasicAgent:
|
| 338 |
def __init__(self):
|
| 339 |
+
print("Initializing BasicAgent...")
|
| 340 |
+
self.graph = build_graph()
|
| 341 |
print("BasicAgent initialized.")
|
| 342 |
+
|
| 343 |
def __call__(self, question: str) -> str:
|
| 344 |
+
print(f"Agent received question (first 100 chars): {question[:100]}")
|
|
|
|
|
|
|
|
|
|
| 345 |
|
| 346 |
+
initial_state: GaiaState = {
|
| 347 |
+
"original_question": question,
|
| 348 |
+
"subquestions": [],
|
| 349 |
+
"current_subquestion_index": 0,
|
| 350 |
+
"subanswers": {},
|
| 351 |
+
"final_answer": "",
|
| 352 |
+
"messages": [],
|
| 353 |
+
}
|
| 354 |
+
|
| 355 |
+
result = self.graph.invoke(initial_state)
|
| 356 |
+
answer = str(result.get("final_answer", "")).strip()
|
| 357 |
+
|
| 358 |
+
if "FINAL ANSWER:" in answer:
|
| 359 |
+
answer = answer.split("FINAL ANSWER:", 1)[1].strip()
|
| 360 |
+
|
| 361 |
+
answer = answer.strip().strip('"').strip("'")
|
| 362 |
+
|
| 363 |
+
if not answer:
|
| 364 |
+
answer = "Unable to determine answer"
|
| 365 |
+
|
| 366 |
+
print(f"Agent returning answer: {answer}")
|
| 367 |
+
return answer
|
| 368 |
+
|
| 369 |
+
|
| 370 |
+
def run_and_submit_all(profile: gr.OAuthProfile | None):
|
| 371 |
+
space_id = os.getenv("SPACE_ID")
|
| 372 |
|
| 373 |
if profile:
|
| 374 |
+
username = f"{profile.username}"
|
| 375 |
print(f"User logged in: {username}")
|
| 376 |
else:
|
| 377 |
print("User not logged in.")
|
|
|
|
| 381 |
questions_url = f"{api_url}/questions"
|
| 382 |
submit_url = f"{api_url}/submit"
|
| 383 |
|
|
|
|
| 384 |
try:
|
| 385 |
agent = BasicAgent()
|
| 386 |
except Exception as e:
|
| 387 |
print(f"Error instantiating agent: {e}")
|
| 388 |
return f"Error initializing agent: {e}", None
|
| 389 |
+
|
| 390 |
+
if space_id:
|
| 391 |
+
agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
|
| 392 |
+
else:
|
| 393 |
+
agent_code = ""
|
| 394 |
+
|
| 395 |
print(agent_code)
|
| 396 |
|
|
|
|
| 397 |
print(f"Fetching questions from: {questions_url}")
|
| 398 |
try:
|
| 399 |
response = requests.get(questions_url, timeout=15)
|
| 400 |
response.raise_for_status()
|
| 401 |
questions_data = response.json()
|
| 402 |
+
|
| 403 |
if not questions_data:
|
| 404 |
+
print("Fetched questions list is empty.")
|
| 405 |
+
return "Fetched questions list is empty or invalid format.", None
|
| 406 |
+
|
| 407 |
print(f"Fetched {len(questions_data)} questions.")
|
| 408 |
except requests.exceptions.RequestException as e:
|
| 409 |
print(f"Error fetching questions: {e}")
|
| 410 |
return f"Error fetching questions: {e}", None
|
| 411 |
+
except ValueError as e:
|
| 412 |
+
print(f"Error decoding JSON response from questions endpoint: {e}")
|
| 413 |
+
return f"Error decoding server response for questions: {e}", None
|
|
|
|
| 414 |
except Exception as e:
|
| 415 |
print(f"An unexpected error occurred fetching questions: {e}")
|
| 416 |
return f"An unexpected error occurred fetching questions: {e}", None
|
| 417 |
|
|
|
|
| 418 |
results_log = []
|
| 419 |
answers_payload = []
|
| 420 |
+
|
| 421 |
print(f"Running agent on {len(questions_data)} questions...")
|
| 422 |
for item in questions_data:
|
| 423 |
task_id = item.get("task_id")
|
| 424 |
question_text = item.get("question")
|
| 425 |
+
|
| 426 |
if not task_id or question_text is None:
|
| 427 |
print(f"Skipping item with missing task_id or question: {item}")
|
| 428 |
continue
|
| 429 |
+
|
| 430 |
try:
|
| 431 |
submitted_answer = agent(question_text)
|
| 432 |
+
answers_payload.append(
|
| 433 |
+
{"task_id": task_id, "submitted_answer": submitted_answer}
|
| 434 |
+
)
|
| 435 |
+
results_log.append(
|
| 436 |
+
{
|
| 437 |
+
"Task ID": task_id,
|
| 438 |
+
"Question": question_text,
|
| 439 |
+
"Submitted Answer": submitted_answer,
|
| 440 |
+
}
|
| 441 |
+
)
|
| 442 |
except Exception as e:
|
| 443 |
+
print(f"Error running agent on task {task_id}: {e}")
|
| 444 |
+
results_log.append(
|
| 445 |
+
{
|
| 446 |
+
"Task ID": task_id,
|
| 447 |
+
"Question": question_text,
|
| 448 |
+
"Submitted Answer": f"AGENT ERROR: {e}",
|
| 449 |
+
}
|
| 450 |
+
)
|
| 451 |
|
| 452 |
if not answers_payload:
|
| 453 |
print("Agent did not produce any answers to submit.")
|
| 454 |
return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)
|
| 455 |
|
| 456 |
+
submission_data = {
|
| 457 |
+
"username": username.strip(),
|
| 458 |
+
"agent_code": agent_code,
|
| 459 |
+
"answers": answers_payload,
|
| 460 |
+
}
|
| 461 |
+
|
| 462 |
+
status_update = (
|
| 463 |
+
f"Agent finished. Submitting {len(answers_payload)} answers for user '{username}'..."
|
| 464 |
+
)
|
| 465 |
print(status_update)
|
| 466 |
|
|
|
|
| 467 |
print(f"Submitting {len(answers_payload)} answers to: {submit_url}")
|
| 468 |
try:
|
| 469 |
response = requests.post(submit_url, json=submission_data, timeout=60)
|
| 470 |
response.raise_for_status()
|
| 471 |
result_data = response.json()
|
| 472 |
+
|
| 473 |
final_status = (
|
| 474 |
f"Submission Successful!\n"
|
| 475 |
f"User: {result_data.get('username')}\n"
|
|
|
|
| 477 |
f"({result_data.get('correct_count', '?')}/{result_data.get('total_attempted', '?')} correct)\n"
|
| 478 |
f"Message: {result_data.get('message', 'No message received.')}"
|
| 479 |
)
|
| 480 |
+
|
| 481 |
print("Submission successful.")
|
| 482 |
results_df = pd.DataFrame(results_log)
|
| 483 |
return final_status, results_df
|
| 484 |
+
|
| 485 |
except requests.exceptions.HTTPError as e:
|
| 486 |
error_detail = f"Server responded with status {e.response.status_code}."
|
| 487 |
try:
|
| 488 |
error_json = e.response.json()
|
| 489 |
error_detail += f" Detail: {error_json.get('detail', e.response.text)}"
|
| 490 |
+
except ValueError:
|
| 491 |
error_detail += f" Response: {e.response.text[:500]}"
|
| 492 |
+
|
| 493 |
status_message = f"Submission Failed: {error_detail}"
|
| 494 |
print(status_message)
|
| 495 |
results_df = pd.DataFrame(results_log)
|
| 496 |
return status_message, results_df
|
| 497 |
+
|
| 498 |
except requests.exceptions.Timeout:
|
| 499 |
status_message = "Submission Failed: The request timed out."
|
| 500 |
print(status_message)
|
| 501 |
results_df = pd.DataFrame(results_log)
|
| 502 |
return status_message, results_df
|
| 503 |
+
|
| 504 |
except requests.exceptions.RequestException as e:
|
| 505 |
status_message = f"Submission Failed: Network error - {e}"
|
| 506 |
print(status_message)
|
| 507 |
results_df = pd.DataFrame(results_log)
|
| 508 |
return status_message, results_df
|
| 509 |
+
|
| 510 |
except Exception as e:
|
| 511 |
status_message = f"An unexpected error occurred during submission: {e}"
|
| 512 |
print(status_message)
|
|
|
|
| 514 |
return status_message, results_df
|
| 515 |
|
| 516 |
|
|
|
|
| 517 |
with gr.Blocks() as demo:
|
| 518 |
gr.Markdown("# Basic Agent Evaluation Runner")
|
| 519 |
gr.Markdown(
|
| 520 |
"""
|
| 521 |
**Instructions:**
|
| 522 |
|
| 523 |
+
1. Please clone this space, then modify the code to define your agent's logic, the tools, the necessary packages, etc.
|
| 524 |
+
2. Log in to your Hugging Face account using the button below. This uses your HF username for submission.
|
| 525 |
+
3. Click 'Run Evaluation & Submit All Answers' to fetch questions, run your agent, submit answers, and see the score.
|
| 526 |
|
| 527 |
---
|
| 528 |
**Disclaimers:**
|
| 529 |
+
Once clicking on the submit button, it can take quite some time.
|
|
|
|
| 530 |
"""
|
| 531 |
)
|
| 532 |
|
|
|
|
| 534 |
|
| 535 |
run_button = gr.Button("Run Evaluation & Submit All Answers")
|
| 536 |
|
| 537 |
+
status_output = gr.Textbox(
|
| 538 |
+
label="Run Status / Submission Result",
|
| 539 |
+
lines=5,
|
| 540 |
+
interactive=False,
|
| 541 |
+
)
|
| 542 |
results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True)
|
| 543 |
|
| 544 |
run_button.click(
|
| 545 |
fn=run_and_submit_all,
|
| 546 |
+
outputs=[status_output, results_table],
|
| 547 |
)
|
| 548 |
|
| 549 |
+
|
| 550 |
if __name__ == "__main__":
|
| 551 |
+
print("\n" + "-" * 30 + " App Starting " + "-" * 30)
|
| 552 |
+
|
| 553 |
space_host_startup = os.getenv("SPACE_HOST")
|
| 554 |
+
space_id_startup = os.getenv("SPACE_ID")
|
| 555 |
|
| 556 |
if space_host_startup:
|
| 557 |
print(f"✅ SPACE_HOST found: {space_host_startup}")
|
|
|
|
| 559 |
else:
|
| 560 |
print("ℹ️ SPACE_HOST environment variable not found (running locally?).")
|
| 561 |
|
| 562 |
+
if space_id_startup:
|
| 563 |
print(f"✅ SPACE_ID found: {space_id_startup}")
|
| 564 |
print(f" Repo URL: https://huggingface.co/spaces/{space_id_startup}")
|
| 565 |
print(f" Repo Tree URL: https://huggingface.co/spaces/{space_id_startup}/tree/main")
|
| 566 |
else:
|
| 567 |
print("ℹ️ SPACE_ID environment variable not found (running locally?). Repo URL cannot be determined.")
|
| 568 |
|
| 569 |
+
print("-" * (60 + len(" App Starting ")) + "\n")
|
|
|
|
| 570 |
print("Launching Gradio Interface for Basic Agent Evaluation...")
|
| 571 |
demo.launch(debug=True, share=False)
|