Spaces:
Sleeping
Sleeping
Improved agent
Browse files
app.py
CHANGED
|
@@ -1,7 +1,9 @@
|
|
| 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
|
|
@@ -32,6 +34,7 @@ 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):
|
|
@@ -78,6 +81,34 @@ def _safe_eval(node):
|
|
| 78 |
raise ValueError("Invalid expression")
|
| 79 |
|
| 80 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 81 |
@tool
|
| 82 |
def calculator(expression: str) -> str:
|
| 83 |
"""
|
|
@@ -123,7 +154,104 @@ def web_search(query: str) -> str:
|
|
| 123 |
return f"Web search error: {e}"
|
| 124 |
|
| 125 |
|
| 126 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 127 |
tool_node = ToolNode(tools)
|
| 128 |
|
| 129 |
|
|
@@ -139,16 +267,13 @@ 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": [
|
|
@@ -156,7 +281,6 @@ Output format (JSON only):
|
|
| 156 |
"subquestion 2"
|
| 157 |
]
|
| 158 |
}
|
| 159 |
-
|
| 160 |
Do not include explanations.
|
| 161 |
Do not include text outside the JSON."""
|
| 162 |
|
|
@@ -170,7 +294,7 @@ Do not include text outside the JSON."""
|
|
| 170 |
subquestions = []
|
| 171 |
try:
|
| 172 |
content = response.content if isinstance(response.content, str) else str(response.content)
|
| 173 |
-
parsed =
|
| 174 |
subquestions = parsed.get("subquestions", [])
|
| 175 |
except Exception:
|
| 176 |
subquestions = []
|
|
@@ -197,16 +321,14 @@ def answer_subquestion(state: GaiaState):
|
|
| 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 = [
|
|
@@ -217,6 +339,8 @@ Be concise and accurate."""
|
|
| 217 |
messages = state["messages"]
|
| 218 |
|
| 219 |
response = solver_model.invoke(messages)
|
|
|
|
|
|
|
| 220 |
return {"messages": [response]}
|
| 221 |
|
| 222 |
|
|
@@ -259,15 +383,12 @@ 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.
|
|
@@ -358,6 +479,8 @@ class BasicAgent:
|
|
| 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:
|
|
@@ -519,11 +642,9 @@ with gr.Blocks() as demo:
|
|
| 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.
|
|
@@ -568,4 +689,4 @@ if __name__ == "__main__":
|
|
| 568 |
|
| 569 |
print("-" * (60 + len(" App Starting ")) + "\n")
|
| 570 |
print("Launching Gradio Interface for Basic Agent Evaluation...")
|
| 571 |
-
demo.launch(debug=True, share=False)
|
|
|
|
| 1 |
import os
|
| 2 |
import json
|
| 3 |
import ast
|
| 4 |
+
import re
|
| 5 |
import operator as op
|
| 6 |
+
from pathlib import Path
|
| 7 |
from typing import TypedDict, Annotated, Dict, List
|
| 8 |
|
| 9 |
import gradio as gr
|
|
|
|
| 34 |
raise ValueError("TAVILY_API_KEY is missing")
|
| 35 |
|
| 36 |
tavily_client = TavilyClient(TAVILY_API_KEY)
|
| 37 |
+
WORKSPACE_ROOT = Path(__file__).resolve().parent
|
| 38 |
|
| 39 |
|
| 40 |
class GaiaState(TypedDict):
|
|
|
|
| 81 |
raise ValueError("Invalid expression")
|
| 82 |
|
| 83 |
|
| 84 |
+
def _truncate_text(value: str, max_chars: int = 6000) -> str:
|
| 85 |
+
if len(value) <= max_chars:
|
| 86 |
+
return value
|
| 87 |
+
return value[:max_chars] + "\n...[truncated]..."
|
| 88 |
+
|
| 89 |
+
|
| 90 |
+
def _extract_json_block(text: str):
|
| 91 |
+
text = text.strip()
|
| 92 |
+
if text.startswith("```"):
|
| 93 |
+
text = re.sub(r"^```(?:json)?\s*", "", text)
|
| 94 |
+
text = re.sub(r"\s*```$", "", text)
|
| 95 |
+
match = re.search(r"\{.*\}", text, re.DOTALL)
|
| 96 |
+
if match:
|
| 97 |
+
return json.loads(match.group(0))
|
| 98 |
+
return json.loads(text)
|
| 99 |
+
|
| 100 |
+
|
| 101 |
+
def _resolve_workspace_path(path_str: str) -> Path:
|
| 102 |
+
candidate = Path(path_str).expanduser()
|
| 103 |
+
if not candidate.is_absolute():
|
| 104 |
+
candidate = (WORKSPACE_ROOT / candidate).resolve()
|
| 105 |
+
else:
|
| 106 |
+
candidate = candidate.resolve()
|
| 107 |
+
if WORKSPACE_ROOT not in candidate.parents and candidate != WORKSPACE_ROOT:
|
| 108 |
+
raise ValueError("Path must be inside the workspace")
|
| 109 |
+
return candidate
|
| 110 |
+
|
| 111 |
+
|
| 112 |
@tool
|
| 113 |
def calculator(expression: str) -> str:
|
| 114 |
"""
|
|
|
|
| 154 |
return f"Web search error: {e}"
|
| 155 |
|
| 156 |
|
| 157 |
+
@tool
|
| 158 |
+
def list_local_files() -> str:
|
| 159 |
+
"""
|
| 160 |
+
List local files in the workspace so you can inspect attachments such as Excel, CSV, JSON, or text files.
|
| 161 |
+
"""
|
| 162 |
+
allowed_suffixes = {
|
| 163 |
+
".xlsx", ".xls", ".csv", ".tsv", ".json", ".txt", ".md",
|
| 164 |
+
".pdf", ".png", ".jpg", ".jpeg", ".parquet"
|
| 165 |
+
}
|
| 166 |
+
files = []
|
| 167 |
+
for path in WORKSPACE_ROOT.rglob("*"):
|
| 168 |
+
if path.is_file() and path.suffix.lower() in allowed_suffixes:
|
| 169 |
+
try:
|
| 170 |
+
relative_path = path.relative_to(WORKSPACE_ROOT)
|
| 171 |
+
except ValueError:
|
| 172 |
+
relative_path = path
|
| 173 |
+
files.append(str(relative_path))
|
| 174 |
+
if not files:
|
| 175 |
+
return "No supported local files found in the workspace."
|
| 176 |
+
return "Local files:\n" + "\n".join(sorted(files))
|
| 177 |
+
|
| 178 |
+
|
| 179 |
+
@tool
|
| 180 |
+
def read_local_file(path: str) -> str:
|
| 181 |
+
"""
|
| 182 |
+
Read a local file from the workspace. Supports text, JSON, CSV/TSV, and Excel files.
|
| 183 |
+
For spreadsheets, this returns sheet names, preview rows, column names, and numeric column sums when possible.
|
| 184 |
+
"""
|
| 185 |
+
try:
|
| 186 |
+
resolved_path = _resolve_workspace_path(path)
|
| 187 |
+
if not resolved_path.exists():
|
| 188 |
+
return f"File not found: {path}"
|
| 189 |
+
|
| 190 |
+
suffix = resolved_path.suffix.lower()
|
| 191 |
+
|
| 192 |
+
if suffix in {".txt", ".md", ".json"}:
|
| 193 |
+
content = resolved_path.read_text(encoding="utf-8", errors="replace")
|
| 194 |
+
if suffix == ".json":
|
| 195 |
+
try:
|
| 196 |
+
parsed = json.loads(content)
|
| 197 |
+
content = json.dumps(parsed, indent=2, ensure_ascii=True)
|
| 198 |
+
except Exception:
|
| 199 |
+
pass
|
| 200 |
+
return _truncate_text(content)
|
| 201 |
+
|
| 202 |
+
if suffix in {".csv", ".tsv"}:
|
| 203 |
+
sep = "\t" if suffix == ".tsv" else ","
|
| 204 |
+
df = pd.read_csv(resolved_path, sep=sep)
|
| 205 |
+
summary = [
|
| 206 |
+
f"File: {resolved_path.name}",
|
| 207 |
+
f"Columns: {', '.join(str(col) for col in df.columns)}",
|
| 208 |
+
f"Rows: {len(df)}",
|
| 209 |
+
"",
|
| 210 |
+
"Preview:",
|
| 211 |
+
df.head(20).to_csv(index=False),
|
| 212 |
+
]
|
| 213 |
+
numeric_df = df.select_dtypes(include="number")
|
| 214 |
+
if not numeric_df.empty:
|
| 215 |
+
summary.extend(
|
| 216 |
+
[
|
| 217 |
+
"",
|
| 218 |
+
"Numeric column sums:",
|
| 219 |
+
numeric_df.sum(numeric_only=True).to_string(),
|
| 220 |
+
]
|
| 221 |
+
)
|
| 222 |
+
return _truncate_text("\n".join(summary))
|
| 223 |
+
|
| 224 |
+
if suffix in {".xlsx", ".xls"}:
|
| 225 |
+
excel_file = pd.ExcelFile(resolved_path)
|
| 226 |
+
output_parts = [f"File: {resolved_path.name}", f"Sheets: {', '.join(excel_file.sheet_names)}"]
|
| 227 |
+
for sheet_name in excel_file.sheet_names[:5]:
|
| 228 |
+
df = excel_file.parse(sheet_name)
|
| 229 |
+
output_parts.extend(
|
| 230 |
+
[
|
| 231 |
+
"",
|
| 232 |
+
f"Sheet: {sheet_name}",
|
| 233 |
+
f"Columns: {', '.join(str(col) for col in df.columns)}",
|
| 234 |
+
f"Rows: {len(df)}",
|
| 235 |
+
"Preview:",
|
| 236 |
+
df.head(20).to_csv(index=False),
|
| 237 |
+
]
|
| 238 |
+
)
|
| 239 |
+
numeric_df = df.select_dtypes(include="number")
|
| 240 |
+
if not numeric_df.empty:
|
| 241 |
+
output_parts.extend(
|
| 242 |
+
[
|
| 243 |
+
"Numeric column sums:",
|
| 244 |
+
numeric_df.sum(numeric_only=True).to_string(),
|
| 245 |
+
]
|
| 246 |
+
)
|
| 247 |
+
return _truncate_text("\n".join(output_parts))
|
| 248 |
+
|
| 249 |
+
return f"Unsupported file type for reading: {suffix}"
|
| 250 |
+
except Exception as e:
|
| 251 |
+
return f"File read error: {e}"
|
| 252 |
+
|
| 253 |
+
|
| 254 |
+
tools = [web_search, calculator, list_local_files, read_local_file]
|
| 255 |
tool_node = ToolNode(tools)
|
| 256 |
|
| 257 |
|
|
|
|
| 267 |
model = get_model()
|
| 268 |
|
| 269 |
prompt = """You are an expert problem decomposition agent.
|
|
|
|
| 270 |
Your job is to analyze a question and decide whether it should be decomposed into smaller subquestions.
|
|
|
|
| 271 |
Rules:
|
| 272 |
1. If the question is simple and can be answered directly, return a single subquestion equal to the original question.
|
| 273 |
2. If the question requires multiple reasoning steps, break it into clear atomic subquestions.
|
| 274 |
3. Each subquestion should be answerable independently using tools such as web search or calculation.
|
| 275 |
4. Do NOT answer the question yourself.
|
| 276 |
5. Only produce subquestions needed to solve the problem.
|
|
|
|
| 277 |
Output format (JSON only):
|
| 278 |
{
|
| 279 |
"subquestions": [
|
|
|
|
| 281 |
"subquestion 2"
|
| 282 |
]
|
| 283 |
}
|
|
|
|
| 284 |
Do not include explanations.
|
| 285 |
Do not include text outside the JSON."""
|
| 286 |
|
|
|
|
| 294 |
subquestions = []
|
| 295 |
try:
|
| 296 |
content = response.content if isinstance(response.content, str) else str(response.content)
|
| 297 |
+
parsed = _extract_json_block(content)
|
| 298 |
subquestions = parsed.get("subquestions", [])
|
| 299 |
except Exception:
|
| 300 |
subquestions = []
|
|
|
|
| 321 |
|
| 322 |
if not state["messages"]:
|
| 323 |
prompt = """You are a research assistant solving a complex question.
|
|
|
|
| 324 |
You may use tools when necessary to obtain information or perform calculations.
|
|
|
|
| 325 |
Use tools when:
|
| 326 |
- the answer requires up-to-date information
|
| 327 |
- the answer requires external data
|
| 328 |
- the answer requires arithmetic computation
|
| 329 |
+
- the answer depends on a local attachment such as an Excel, CSV, JSON, or text file
|
| 330 |
+
When local files may be relevant, first use list_local_files and then read_local_file.
|
| 331 |
If you already know the answer with high confidence, answer directly.
|
|
|
|
| 332 |
Be concise and accurate."""
|
| 333 |
|
| 334 |
messages = [
|
|
|
|
| 339 |
messages = state["messages"]
|
| 340 |
|
| 341 |
response = solver_model.invoke(messages)
|
| 342 |
+
if not state["messages"]:
|
| 343 |
+
return {"messages": messages + [response]}
|
| 344 |
return {"messages": [response]}
|
| 345 |
|
| 346 |
|
|
|
|
| 383 |
model = get_model()
|
| 384 |
|
| 385 |
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.
|
|
|
|
| 386 |
Finish your answer with the following template exactly:
|
| 387 |
FINAL ANSWER: [YOUR FINAL ANSWER]
|
|
|
|
| 388 |
YOUR FINAL ANSWER should be:
|
| 389 |
- a number, OR
|
| 390 |
- as few words as possible, OR
|
| 391 |
- a comma separated list of numbers and/or strings
|
|
|
|
| 392 |
Rules:
|
| 393 |
- If asked for a number, do not use commas in the number and do not use units unless explicitly requested.
|
| 394 |
- If asked for a string, do not use articles and do not use abbreviations unless explicitly requested.
|
|
|
|
| 479 |
if "FINAL ANSWER:" in answer:
|
| 480 |
answer = answer.split("FINAL ANSWER:", 1)[1].strip()
|
| 481 |
|
| 482 |
+
answer = answer.splitlines()[0].strip()
|
| 483 |
+
|
| 484 |
answer = answer.strip().strip('"').strip("'")
|
| 485 |
|
| 486 |
if not answer:
|
|
|
|
| 642 |
gr.Markdown(
|
| 643 |
"""
|
| 644 |
**Instructions:**
|
|
|
|
| 645 |
1. Please clone this space, then modify the code to define your agent's logic, the tools, the necessary packages, etc.
|
| 646 |
2. Log in to your Hugging Face account using the button below. This uses your HF username for submission.
|
| 647 |
3. Click 'Run Evaluation & Submit All Answers' to fetch questions, run your agent, submit answers, and see the score.
|
|
|
|
| 648 |
---
|
| 649 |
**Disclaimers:**
|
| 650 |
Once clicking on the submit button, it can take quite some time.
|
|
|
|
| 689 |
|
| 690 |
print("-" * (60 + len(" App Starting ")) + "\n")
|
| 691 |
print("Launching Gradio Interface for Basic Agent Evaluation...")
|
| 692 |
+
demo.launch(debug=True, share=False)
|