Spaces:
Build error
Build error
Enhance agent capabilities by integrating YAML-based prompt templates for web, data analysis, and media agents in agents.py. Update main.py to initialize agents with these templates, improving task handling and response accuracy. Introduce utility functions for extracting final answers and managing prompts, streamlining the overall agent workflow.
Browse files- agents.py +33 -0
- app.py +53 -28
- main.py +64 -20
- prompts.py +52 -0
- prompts/code_agent.yaml +325 -0
- prompts/toolcalling_agent.yaml +239 -0
- utils.py +66 -0
agents.py
CHANGED
@@ -1,5 +1,13 @@
|
|
|
|
|
|
|
|
1 |
from smolagents import CodeAgent
|
2 |
|
|
|
|
|
|
|
|
|
|
|
3 |
from tools import (
|
4 |
analyze_image,
|
5 |
browse_webpage,
|
@@ -22,6 +30,14 @@ def create_web_agent(model):
|
|
22 |
Returns:
|
23 |
Configured CodeAgent for web browsing
|
24 |
"""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
25 |
web_agent = CodeAgent(
|
26 |
tools=[web_search, browse_webpage, find_in_page, extract_dates],
|
27 |
model=model,
|
@@ -29,6 +45,7 @@ def create_web_agent(model):
|
|
29 |
description="Specialized agent for web browsing and searching. Use this agent to find information online, browse websites, and extract information from web pages.",
|
30 |
add_base_tools=True,
|
31 |
additional_authorized_imports=["requests", "bs4", "re", "json"],
|
|
|
32 |
)
|
33 |
|
34 |
return web_agent
|
@@ -44,6 +61,13 @@ def create_data_analysis_agent(model):
|
|
44 |
Returns:
|
45 |
Configured CodeAgent for data analysis
|
46 |
"""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
47 |
data_agent = CodeAgent(
|
48 |
tools=[parse_csv, perform_calculation],
|
49 |
model=model,
|
@@ -51,6 +75,7 @@ def create_data_analysis_agent(model):
|
|
51 |
description="Specialized agent for data analysis. Use this agent to analyze data, perform calculations, and extract insights from structured data.",
|
52 |
add_base_tools=True,
|
53 |
additional_authorized_imports=["pandas", "numpy", "math", "csv", "io"],
|
|
|
54 |
)
|
55 |
|
56 |
return data_agent
|
@@ -66,6 +91,13 @@ def create_media_agent(model):
|
|
66 |
Returns:
|
67 |
Configured CodeAgent for media handling
|
68 |
"""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
69 |
media_agent = CodeAgent(
|
70 |
tools=[analyze_image, read_pdf],
|
71 |
model=model,
|
@@ -73,6 +105,7 @@ def create_media_agent(model):
|
|
73 |
description="Specialized agent for handling media files like images and PDFs. Use this agent to analyze images and extract text from PDF documents.",
|
74 |
add_base_tools=True,
|
75 |
additional_authorized_imports=["PIL", "io", "requests"],
|
|
|
76 |
)
|
77 |
|
78 |
return media_agent
|
|
|
1 |
+
import importlib
|
2 |
+
|
3 |
+
import yaml
|
4 |
from smolagents import CodeAgent
|
5 |
|
6 |
+
from prompts import (
|
7 |
+
DATA_AGENT_SYSTEM_PROMPT,
|
8 |
+
MEDIA_AGENT_SYSTEM_PROMPT,
|
9 |
+
WEB_AGENT_SYSTEM_PROMPT,
|
10 |
+
)
|
11 |
from tools import (
|
12 |
analyze_image,
|
13 |
browse_webpage,
|
|
|
30 |
Returns:
|
31 |
Configured CodeAgent for web browsing
|
32 |
"""
|
33 |
+
|
34 |
+
prompt_templates = yaml.safe_load(
|
35 |
+
importlib.resources.files("smolagents.prompts")
|
36 |
+
.joinpath("code_agent.yaml")
|
37 |
+
.read_text()
|
38 |
+
)
|
39 |
+
# prompt_templates["system_prompt"] = WEB_AGENT_SYSTEM_PROMPT
|
40 |
+
|
41 |
web_agent = CodeAgent(
|
42 |
tools=[web_search, browse_webpage, find_in_page, extract_dates],
|
43 |
model=model,
|
|
|
45 |
description="Specialized agent for web browsing and searching. Use this agent to find information online, browse websites, and extract information from web pages.",
|
46 |
add_base_tools=True,
|
47 |
additional_authorized_imports=["requests", "bs4", "re", "json"],
|
48 |
+
prompt_templates=prompt_templates,
|
49 |
)
|
50 |
|
51 |
return web_agent
|
|
|
61 |
Returns:
|
62 |
Configured CodeAgent for data analysis
|
63 |
"""
|
64 |
+
prompt_templates = yaml.safe_load(
|
65 |
+
importlib.resources.files("smolagents.prompts")
|
66 |
+
.joinpath("code_agent.yaml")
|
67 |
+
.read_text()
|
68 |
+
)
|
69 |
+
# prompt_templates["system_prompt"] = DATA_AGENT_SYSTEM_PROMPT
|
70 |
+
|
71 |
data_agent = CodeAgent(
|
72 |
tools=[parse_csv, perform_calculation],
|
73 |
model=model,
|
|
|
75 |
description="Specialized agent for data analysis. Use this agent to analyze data, perform calculations, and extract insights from structured data.",
|
76 |
add_base_tools=True,
|
77 |
additional_authorized_imports=["pandas", "numpy", "math", "csv", "io"],
|
78 |
+
prompt_templates=prompt_templates,
|
79 |
)
|
80 |
|
81 |
return data_agent
|
|
|
91 |
Returns:
|
92 |
Configured CodeAgent for media handling
|
93 |
"""
|
94 |
+
prompt_templates = yaml.safe_load(
|
95 |
+
importlib.resources.files("smolagents.prompts")
|
96 |
+
.joinpath("code_agent.yaml")
|
97 |
+
.read_text()
|
98 |
+
)
|
99 |
+
# prompt_templates["system_prompt"] = MEDIA_AGENT_SYSTEM_PROMPT
|
100 |
+
|
101 |
media_agent = CodeAgent(
|
102 |
tools=[analyze_image, read_pdf],
|
103 |
model=model,
|
|
|
105 |
description="Specialized agent for handling media files like images and PDFs. Use this agent to analyze images and extract text from PDF documents.",
|
106 |
add_base_tools=True,
|
107 |
additional_authorized_imports=["PIL", "io", "requests"],
|
108 |
+
prompt_templates=prompt_templates,
|
109 |
)
|
110 |
|
111 |
return media_agent
|
app.py
CHANGED
@@ -1,9 +1,10 @@
|
|
|
|
1 |
import os
|
2 |
import time
|
|
|
3 |
import gradio as gr
|
4 |
-
import requests
|
5 |
-
import inspect
|
6 |
import pandas as pd
|
|
|
7 |
|
8 |
from main import main
|
9 |
|
@@ -14,11 +15,13 @@ question_counter = 0
|
|
14 |
# --- Constants ---
|
15 |
DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
|
16 |
|
|
|
17 |
# --- Basic Agent Definition ---
|
18 |
# ----- THIS IS WERE YOU CAN BUILD WHAT YOU WANT ------
|
19 |
class BasicAgent:
|
20 |
def __init__(self):
|
21 |
print("BasicAgent initialized.")
|
|
|
22 |
def __call__(self, question: str) -> str:
|
23 |
print(f"Agent received question (first 50 chars): {question[:50]}...")
|
24 |
|
@@ -45,16 +48,17 @@ class BasicAgent:
|
|
45 |
|
46 |
return final_answer
|
47 |
|
48 |
-
|
|
|
49 |
"""
|
50 |
Fetches all questions, runs the BasicAgent on them, submits all answers,
|
51 |
and displays the results.
|
52 |
"""
|
53 |
# --- Determine HF Space Runtime URL and Repo URL ---
|
54 |
-
space_id = os.getenv("SPACE_ID")
|
55 |
|
56 |
if profile:
|
57 |
-
username= f"{profile.username}"
|
58 |
print(f"User logged in: {username}")
|
59 |
else:
|
60 |
print("User not logged in.")
|
@@ -81,16 +85,16 @@ def run_and_submit_all( profile: gr.OAuthProfile | None):
|
|
81 |
response.raise_for_status()
|
82 |
questions_data = response.json()
|
83 |
if not questions_data:
|
84 |
-
|
85 |
-
|
86 |
print(f"Fetched {len(questions_data)} questions.")
|
87 |
except requests.exceptions.RequestException as e:
|
88 |
print(f"Error fetching questions: {e}")
|
89 |
return f"Error fetching questions: {e}", None
|
90 |
except requests.exceptions.JSONDecodeError as e:
|
91 |
-
|
92 |
-
|
93 |
-
|
94 |
except Exception as e:
|
95 |
print(f"An unexpected error occurred fetching questions: {e}")
|
96 |
return f"An unexpected error occurred fetching questions: {e}", None
|
@@ -107,18 +111,36 @@ def run_and_submit_all( profile: gr.OAuthProfile | None):
|
|
107 |
continue
|
108 |
try:
|
109 |
submitted_answer = agent(question_text)
|
110 |
-
answers_payload.append(
|
111 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
112 |
except Exception as e:
|
113 |
-
|
114 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
115 |
|
116 |
if not answers_payload:
|
117 |
print("Agent did not produce any answers to submit.")
|
118 |
return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)
|
119 |
|
120 |
-
# 4. Prepare Submission
|
121 |
-
submission_data = {
|
|
|
|
|
|
|
|
|
122 |
status_update = f"Agent finished. Submitting {len(answers_payload)} answers for user '{username}'..."
|
123 |
print(status_update)
|
124 |
|
@@ -188,20 +210,19 @@ with gr.Blocks() as demo:
|
|
188 |
|
189 |
run_button = gr.Button("Run Evaluation & Submit All Answers")
|
190 |
|
191 |
-
status_output = gr.Textbox(
|
|
|
|
|
192 |
# Removed max_rows=10 from DataFrame constructor
|
193 |
results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True)
|
194 |
|
195 |
-
run_button.click(
|
196 |
-
fn=run_and_submit_all,
|
197 |
-
outputs=[status_output, results_table]
|
198 |
-
)
|
199 |
|
200 |
if __name__ == "__main__":
|
201 |
-
print("\n" + "-"*30 + " App Starting " + "-"*30)
|
202 |
# Check for SPACE_HOST and SPACE_ID at startup for information
|
203 |
space_host_startup = os.getenv("SPACE_HOST")
|
204 |
-
space_id_startup = os.getenv("SPACE_ID")
|
205 |
|
206 |
if space_host_startup:
|
207 |
print(f"✅ SPACE_HOST found: {space_host_startup}")
|
@@ -209,14 +230,18 @@ if __name__ == "__main__":
|
|
209 |
else:
|
210 |
print("ℹ️ SPACE_HOST environment variable not found (running locally?).")
|
211 |
|
212 |
-
if space_id_startup:
|
213 |
print(f"✅ SPACE_ID found: {space_id_startup}")
|
214 |
print(f" Repo URL: https://huggingface.co/spaces/{space_id_startup}")
|
215 |
-
print(
|
|
|
|
|
216 |
else:
|
217 |
-
print(
|
|
|
|
|
218 |
|
219 |
-
print("-"*(60 + len(" App Starting ")) + "\n")
|
220 |
|
221 |
print("Launching Gradio Interface for Basic Agent Evaluation...")
|
222 |
-
demo.launch(debug=True, share=False)
|
|
|
1 |
+
import inspect
|
2 |
import os
|
3 |
import time
|
4 |
+
|
5 |
import gradio as gr
|
|
|
|
|
6 |
import pandas as pd
|
7 |
+
import requests
|
8 |
|
9 |
from main import main
|
10 |
|
|
|
15 |
# --- Constants ---
|
16 |
DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
|
17 |
|
18 |
+
|
19 |
# --- Basic Agent Definition ---
|
20 |
# ----- THIS IS WERE YOU CAN BUILD WHAT YOU WANT ------
|
21 |
class BasicAgent:
|
22 |
def __init__(self):
|
23 |
print("BasicAgent initialized.")
|
24 |
+
|
25 |
def __call__(self, question: str) -> str:
|
26 |
print(f"Agent received question (first 50 chars): {question[:50]}...")
|
27 |
|
|
|
48 |
|
49 |
return final_answer
|
50 |
|
51 |
+
|
52 |
+
def run_and_submit_all(profile: gr.OAuthProfile | None):
|
53 |
"""
|
54 |
Fetches all questions, runs the BasicAgent on them, submits all answers,
|
55 |
and displays the results.
|
56 |
"""
|
57 |
# --- Determine HF Space Runtime URL and Repo URL ---
|
58 |
+
space_id = os.getenv("SPACE_ID") # Get the SPACE_ID for sending link to the code
|
59 |
|
60 |
if profile:
|
61 |
+
username = f"{profile.username}"
|
62 |
print(f"User logged in: {username}")
|
63 |
else:
|
64 |
print("User not logged in.")
|
|
|
85 |
response.raise_for_status()
|
86 |
questions_data = response.json()
|
87 |
if not questions_data:
|
88 |
+
print("Fetched questions list is empty.")
|
89 |
+
return "Fetched questions list is empty or invalid format.", None
|
90 |
print(f"Fetched {len(questions_data)} questions.")
|
91 |
except requests.exceptions.RequestException as e:
|
92 |
print(f"Error fetching questions: {e}")
|
93 |
return f"Error fetching questions: {e}", None
|
94 |
except requests.exceptions.JSONDecodeError as e:
|
95 |
+
print(f"Error decoding JSON response from questions endpoint: {e}")
|
96 |
+
print(f"Response text: {response.text[:500]}")
|
97 |
+
return f"Error decoding server response for questions: {e}", None
|
98 |
except Exception as e:
|
99 |
print(f"An unexpected error occurred fetching questions: {e}")
|
100 |
return f"An unexpected error occurred fetching questions: {e}", None
|
|
|
111 |
continue
|
112 |
try:
|
113 |
submitted_answer = agent(question_text)
|
114 |
+
answers_payload.append(
|
115 |
+
{"task_id": task_id, "submitted_answer": submitted_answer}
|
116 |
+
)
|
117 |
+
results_log.append(
|
118 |
+
{
|
119 |
+
"Task ID": task_id,
|
120 |
+
"Question": question_text,
|
121 |
+
"Submitted Answer": submitted_answer,
|
122 |
+
}
|
123 |
+
)
|
124 |
except Exception as e:
|
125 |
+
print(f"Error running agent on task {task_id}: {e}")
|
126 |
+
results_log.append(
|
127 |
+
{
|
128 |
+
"Task ID": task_id,
|
129 |
+
"Question": question_text,
|
130 |
+
"Submitted Answer": f"AGENT ERROR: {e}",
|
131 |
+
}
|
132 |
+
)
|
133 |
|
134 |
if not answers_payload:
|
135 |
print("Agent did not produce any answers to submit.")
|
136 |
return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)
|
137 |
|
138 |
+
# 4. Prepare Submission
|
139 |
+
submission_data = {
|
140 |
+
"username": username.strip(),
|
141 |
+
"agent_code": agent_code,
|
142 |
+
"answers": answers_payload,
|
143 |
+
}
|
144 |
status_update = f"Agent finished. Submitting {len(answers_payload)} answers for user '{username}'..."
|
145 |
print(status_update)
|
146 |
|
|
|
210 |
|
211 |
run_button = gr.Button("Run Evaluation & Submit All Answers")
|
212 |
|
213 |
+
status_output = gr.Textbox(
|
214 |
+
label="Run Status / Submission Result", lines=5, interactive=False
|
215 |
+
)
|
216 |
# Removed max_rows=10 from DataFrame constructor
|
217 |
results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True)
|
218 |
|
219 |
+
run_button.click(fn=run_and_submit_all, outputs=[status_output, results_table])
|
|
|
|
|
|
|
220 |
|
221 |
if __name__ == "__main__":
|
222 |
+
print("\n" + "-" * 30 + " App Starting " + "-" * 30)
|
223 |
# Check for SPACE_HOST and SPACE_ID at startup for information
|
224 |
space_host_startup = os.getenv("SPACE_HOST")
|
225 |
+
space_id_startup = os.getenv("SPACE_ID") # Get SPACE_ID at startup
|
226 |
|
227 |
if space_host_startup:
|
228 |
print(f"✅ SPACE_HOST found: {space_host_startup}")
|
|
|
230 |
else:
|
231 |
print("ℹ️ SPACE_HOST environment variable not found (running locally?).")
|
232 |
|
233 |
+
if space_id_startup: # Print repo URLs if SPACE_ID is found
|
234 |
print(f"✅ SPACE_ID found: {space_id_startup}")
|
235 |
print(f" Repo URL: https://huggingface.co/spaces/{space_id_startup}")
|
236 |
+
print(
|
237 |
+
f" Repo Tree URL: https://huggingface.co/spaces/{space_id_startup}/tree/main"
|
238 |
+
)
|
239 |
else:
|
240 |
+
print(
|
241 |
+
"ℹ️ SPACE_ID environment variable not found (running locally?). Repo URL cannot be determined."
|
242 |
+
)
|
243 |
|
244 |
+
print("-" * (60 + len(" App Starting ")) + "\n")
|
245 |
|
246 |
print("Launching Gradio Interface for Basic Agent Evaluation...")
|
247 |
+
demo.launch(debug=True, share=False)
|
main.py
CHANGED
@@ -1,21 +1,24 @@
|
|
1 |
import asyncio
|
|
|
2 |
import logging
|
3 |
import os
|
4 |
import time
|
5 |
import uuid # for generating thread IDs for checkpointer
|
6 |
from typing import AsyncIterator, Optional, TypedDict
|
7 |
|
|
|
|
|
8 |
from dotenv import find_dotenv, load_dotenv
|
9 |
from langgraph.checkpoint.memory import MemorySaver
|
10 |
from langgraph.graph import END, START, StateGraph
|
11 |
-
import litellm
|
12 |
from smolagents import CodeAgent, LiteLLMModel
|
13 |
from smolagents.memory import ActionStep, FinalAnswerStep
|
14 |
from smolagents.monitoring import LogLevel
|
15 |
-
|
16 |
-
|
17 |
-
|
18 |
-
|
|
|
19 |
|
20 |
litellm._turn_on_debug()
|
21 |
|
@@ -58,18 +61,38 @@ except Exception as e:
|
|
58 |
logger.error(f"Failed to initialize model: {str(e)}")
|
59 |
raise
|
60 |
|
|
|
|
|
|
|
|
|
61 |
tools = [
|
62 |
-
DuckDuckGoSearchTool(max_results=3),
|
63 |
# VisitWebpageTool(max_output_length=1000),
|
|
|
|
|
64 |
]
|
65 |
|
66 |
# Initialize agent with error handling
|
67 |
try:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
68 |
agent = CodeAgent(
|
69 |
-
|
70 |
-
additional_authorized_imports=[
|
71 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
72 |
model=model,
|
|
|
73 |
tools=tools,
|
74 |
step_callbacks=None,
|
75 |
verbosity_level=LogLevel.ERROR,
|
@@ -257,23 +280,44 @@ async def run_with_streaming(task: str, thread_id: str) -> dict:
|
|
257 |
|
258 |
|
259 |
def main(task: str, thread_id: str = str(uuid.uuid4())):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
260 |
logger.info(
|
261 |
f"Starting agent run from __main__ for task: '{task}' with thread_id: {thread_id}"
|
262 |
)
|
263 |
-
result = asyncio.run(run_with_streaming(
|
264 |
logger.info("Agent run finished.")
|
265 |
|
266 |
# Print final results
|
267 |
-
print("\n--- Execution Results ---")
|
268 |
-
print(f"Number of Steps: {len(result.get('steps', []))}")
|
269 |
-
# Optionally print step details
|
270 |
-
# for i, step in enumerate(result.get('steps', [])):
|
271 |
-
# print(f"Step {i+1} Details: {step}")
|
272 |
-
print(f"Final Answer: {result.get('final_answer') or 'Not found'}")
|
273 |
-
if err := result.get("error"):
|
274 |
-
|
275 |
-
|
276 |
-
return result.get("final_answer")
|
|
|
|
|
|
|
277 |
|
278 |
|
279 |
if __name__ == "__main__":
|
|
|
1 |
import asyncio
|
2 |
+
import importlib
|
3 |
import logging
|
4 |
import os
|
5 |
import time
|
6 |
import uuid # for generating thread IDs for checkpointer
|
7 |
from typing import AsyncIterator, Optional, TypedDict
|
8 |
|
9 |
+
import litellm
|
10 |
+
import yaml
|
11 |
from dotenv import find_dotenv, load_dotenv
|
12 |
from langgraph.checkpoint.memory import MemorySaver
|
13 |
from langgraph.graph import END, START, StateGraph
|
|
|
14 |
from smolagents import CodeAgent, LiteLLMModel
|
15 |
from smolagents.memory import ActionStep, FinalAnswerStep
|
16 |
from smolagents.monitoring import LogLevel
|
17 |
+
|
18 |
+
from agents import create_data_analysis_agent, create_media_agent, create_web_agent
|
19 |
+
from prompts import MANAGER_SYSTEM_PROMPT
|
20 |
+
from tools import perform_calculation, web_search
|
21 |
+
from utils import extract_final_answer
|
22 |
|
23 |
litellm._turn_on_debug()
|
24 |
|
|
|
61 |
logger.error(f"Failed to initialize model: {str(e)}")
|
62 |
raise
|
63 |
|
64 |
+
web_agent = create_web_agent(model)
|
65 |
+
data_agent = create_data_analysis_agent(model)
|
66 |
+
media_agent = create_media_agent(model)
|
67 |
+
|
68 |
tools = [
|
69 |
+
# DuckDuckGoSearchTool(max_results=3),
|
70 |
# VisitWebpageTool(max_output_length=1000),
|
71 |
+
web_search,
|
72 |
+
perform_calculation,
|
73 |
]
|
74 |
|
75 |
# Initialize agent with error handling
|
76 |
try:
|
77 |
+
prompt_templates = yaml.safe_load(
|
78 |
+
importlib.resources.files("smolagents.prompts")
|
79 |
+
.joinpath("code_agent.yaml")
|
80 |
+
.read_text()
|
81 |
+
)
|
82 |
+
# prompt_templates["system_prompt"] = MANAGER_SYSTEM_PROMPT
|
83 |
+
|
84 |
agent = CodeAgent(
|
85 |
+
add_base_tools=True,
|
86 |
+
additional_authorized_imports=[
|
87 |
+
"json",
|
88 |
+
"pandas",
|
89 |
+
"numpy",
|
90 |
+
"re",
|
91 |
+
],
|
92 |
+
# max_steps=10,
|
93 |
+
managed_agents=[web_agent, data_agent, media_agent],
|
94 |
model=model,
|
95 |
+
prompt_templates=prompt_templates,
|
96 |
tools=tools,
|
97 |
step_callbacks=None,
|
98 |
verbosity_level=LogLevel.ERROR,
|
|
|
280 |
|
281 |
|
282 |
def main(task: str, thread_id: str = str(uuid.uuid4())):
|
283 |
+
# Enhance the question with instructions specific to GAIA tasks
|
284 |
+
enhanced_question = f"""
|
285 |
+
GAIA Benchmark Question: {task}
|
286 |
+
|
287 |
+
This is a multi-step reasoning problem from the GAIA benchmark. Please solve it by:
|
288 |
+
|
289 |
+
1. Breaking the question down into clear logical steps
|
290 |
+
2. Using the appropriate specialized agents when needed:
|
291 |
+
- web_agent for web searches and browsing
|
292 |
+
- data_agent for data analysis and calculations
|
293 |
+
- media_agent for working with images and PDFs
|
294 |
+
3. Tracking your progress through the problem
|
295 |
+
4. Providing your final answer in EXACTLY the format requested by the question
|
296 |
+
|
297 |
+
IMPORTANT: GAIA questions often involve multiple steps of information gathering and reasoning.
|
298 |
+
You must follow the chain of reasoning completely and provide the exact format requested.
|
299 |
+
"""
|
300 |
+
|
301 |
logger.info(
|
302 |
f"Starting agent run from __main__ for task: '{task}' with thread_id: {thread_id}"
|
303 |
)
|
304 |
+
result = asyncio.run(run_with_streaming(enhanced_question, thread_id))
|
305 |
logger.info("Agent run finished.")
|
306 |
|
307 |
# Print final results
|
308 |
+
# print("\n--- Execution Results ---")
|
309 |
+
# print(f"Number of Steps: {len(result.get('steps', []))}")
|
310 |
+
# # Optionally print step details
|
311 |
+
# # for i, step in enumerate(result.get('steps', [])):
|
312 |
+
# # print(f"Step {i+1} Details: {step}")
|
313 |
+
# print(f"Final Answer: {result.get('final_answer') or 'Not found'}")
|
314 |
+
# if err := result.get("error"):
|
315 |
+
# print(f"Error: {err}")
|
316 |
+
|
317 |
+
# return result.get("final_answer")
|
318 |
+
|
319 |
+
logger.info(f"Result: {result}")
|
320 |
+
return extract_final_answer(result)
|
321 |
|
322 |
|
323 |
if __name__ == "__main__":
|
prompts.py
ADDED
@@ -0,0 +1,52 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Enhanced system prompts for GAIA benchmark
|
2 |
+
MANAGER_SYSTEM_PROMPT = """
|
3 |
+
You are a manager agent for the GAIA benchmark. Your job is to:
|
4 |
+
1. Break down complex questions into logical steps
|
5 |
+
2. Delegate tasks to specialized agents when appropriate
|
6 |
+
3. Synthesize information from different sources
|
7 |
+
4. Track progress and ensure all parts of the question are addressed
|
8 |
+
5. Formulate a precise final answer in the exact format requested
|
9 |
+
|
10 |
+
You have these specialized agents available:
|
11 |
+
- web_agent: For web browsing, searching, and extracting information from websites
|
12 |
+
- data_agent: For data analysis, calculations, and working with structured data
|
13 |
+
- media_agent: For analyzing images and extracting content from PDFs
|
14 |
+
|
15 |
+
Focus on delivering accurate, precise answers rather than explanations.
|
16 |
+
"""
|
17 |
+
|
18 |
+
WEB_AGENT_SYSTEM_PROMPT = """
|
19 |
+
You are a web agent specialized in finding and extracting information from the internet.
|
20 |
+
Your primary functions are:
|
21 |
+
1. Performing targeted web searches
|
22 |
+
2. Browsing webpages to extract specific information
|
23 |
+
3. Finding relevant content within pages
|
24 |
+
4. Extracting dates and temporal information
|
25 |
+
|
26 |
+
Be thorough and precise in your search strategies. Try multiple search queries if needed.
|
27 |
+
Return only the specific information requested, formatted clearly.
|
28 |
+
"""
|
29 |
+
|
30 |
+
DATA_AGENT_SYSTEM_PROMPT = """
|
31 |
+
You are a data analysis agent specialized in working with structured data.
|
32 |
+
Your primary functions are:
|
33 |
+
1. Analyzing CSV and tabular data
|
34 |
+
2. Performing calculations and statistical analysis
|
35 |
+
3. Extracting insights from numerical data
|
36 |
+
4. Formatting results according to specifications
|
37 |
+
|
38 |
+
Be precise in your calculations and data handling. Check your work for accuracy.
|
39 |
+
Return only the specific information requested, formatted clearly.
|
40 |
+
"""
|
41 |
+
|
42 |
+
MEDIA_AGENT_SYSTEM_PROMPT = """
|
43 |
+
You are a media analysis agent specialized in working with images and documents.
|
44 |
+
Your primary functions are:
|
45 |
+
1. Analyzing images to identify objects, text, and relationships
|
46 |
+
2. Extracting text content from PDF documents
|
47 |
+
3. Describing visual elements in detail
|
48 |
+
4. Identifying patterns in visual data
|
49 |
+
|
50 |
+
Be thorough in your analysis and precise in your descriptions.
|
51 |
+
Return only the specific information requested, formatted clearly.
|
52 |
+
"""
|
prompts/code_agent.yaml
ADDED
@@ -0,0 +1,325 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
system_prompt: |-
|
2 |
+
You are an expert assistant who can solve any task using code blobs. You will be given a task to solve as best you can.
|
3 |
+
To do so, you have been given access to a list of tools: these tools are basically Python functions which you can call with code.
|
4 |
+
To solve the task, you must plan forward to proceed in a series of steps, in a cycle of 'Thought:', 'Code:', and 'Observation:' sequences.
|
5 |
+
|
6 |
+
At each step, in the 'Thought:' sequence, you should first explain your reasoning towards solving the task and the tools that you want to use.
|
7 |
+
Then in the 'Code:' sequence, you should write the code in simple Python. The code sequence must end with '<end_code>' sequence.
|
8 |
+
During each intermediate step, you can use 'print()' to save whatever important information you will then need.
|
9 |
+
These print outputs will then appear in the 'Observation:' field, which will be available as input for the next step.
|
10 |
+
In the end you have to return a final answer using the `final_answer` tool.
|
11 |
+
|
12 |
+
Here are a few examples using notional tools:
|
13 |
+
---
|
14 |
+
Task: "Generate an image of the oldest person in this document."
|
15 |
+
|
16 |
+
Thought: I will proceed step by step and use the following tools: `document_qa` to find the oldest person in the document, then `image_generator` to generate an image according to the answer.
|
17 |
+
Code:
|
18 |
+
```py
|
19 |
+
answer = document_qa(document=document, question="Who is the oldest person mentioned?")
|
20 |
+
print(answer)
|
21 |
+
```<end_code>
|
22 |
+
Observation: "The oldest person in the document is John Doe, a 55 year old lumberjack living in Newfoundland."
|
23 |
+
|
24 |
+
Thought: I will now generate an image showcasing the oldest person.
|
25 |
+
Code:
|
26 |
+
```py
|
27 |
+
image = image_generator("A portrait of John Doe, a 55-year-old man living in Canada.")
|
28 |
+
final_answer(image)
|
29 |
+
```<end_code>
|
30 |
+
|
31 |
+
---
|
32 |
+
Task: "What is the result of the following operation: 5 + 3 + 1294.678?"
|
33 |
+
|
34 |
+
Thought: I will use python code to compute the result of the operation and then return the final answer using the `final_answer` tool
|
35 |
+
Code:
|
36 |
+
```py
|
37 |
+
result = 5 + 3 + 1294.678
|
38 |
+
final_answer(result)
|
39 |
+
```<end_code>
|
40 |
+
|
41 |
+
---
|
42 |
+
Task:
|
43 |
+
"Answer the question in the variable `question` about the image stored in the variable `image`. The question is in French.
|
44 |
+
You have been provided with these additional arguments, that you can access using the keys as variables in your python code:
|
45 |
+
{'question': 'Quel est l'animal sur l'image?', 'image': 'path/to/image.jpg'}"
|
46 |
+
|
47 |
+
Thought: I will use the following tools: `translator` to translate the question into English and then `image_qa` to answer the question on the input image.
|
48 |
+
Code:
|
49 |
+
```py
|
50 |
+
translated_question = translator(question=question, src_lang="French", tgt_lang="English")
|
51 |
+
print(f"The translated question is {translated_question}.")
|
52 |
+
answer = image_qa(image=image, question=translated_question)
|
53 |
+
final_answer(f"The answer is {answer}")
|
54 |
+
```<end_code>
|
55 |
+
|
56 |
+
---
|
57 |
+
Task:
|
58 |
+
In a 1979 interview, Stanislaus Ulam discusses with Martin Sherwin about other great physicists of his time, including Oppenheimer.
|
59 |
+
What does he say was the consequence of Einstein learning too much math on his creativity, in one word?
|
60 |
+
|
61 |
+
Thought: I need to find and read the 1979 interview of Stanislaus Ulam with Martin Sherwin.
|
62 |
+
Code:
|
63 |
+
```py
|
64 |
+
pages = search(query="1979 interview Stanislaus Ulam Martin Sherwin physicists Einstein")
|
65 |
+
print(pages)
|
66 |
+
```<end_code>
|
67 |
+
Observation:
|
68 |
+
No result found for query "1979 interview Stanislaus Ulam Martin Sherwin physicists Einstein".
|
69 |
+
|
70 |
+
Thought: The query was maybe too restrictive and did not find any results. Let's try again with a broader query.
|
71 |
+
Code:
|
72 |
+
```py
|
73 |
+
pages = search(query="1979 interview Stanislaus Ulam")
|
74 |
+
print(pages)
|
75 |
+
```<end_code>
|
76 |
+
Observation:
|
77 |
+
Found 6 pages:
|
78 |
+
[Stanislaus Ulam 1979 interview](https://ahf.nuclearmuseum.org/voices/oral-histories/stanislaus-ulams-interview-1979/)
|
79 |
+
|
80 |
+
[Ulam discusses Manhattan Project](https://ahf.nuclearmuseum.org/manhattan-project/ulam-manhattan-project/)
|
81 |
+
|
82 |
+
(truncated)
|
83 |
+
|
84 |
+
Thought: I will read the first 2 pages to know more.
|
85 |
+
Code:
|
86 |
+
```py
|
87 |
+
for url in ["https://ahf.nuclearmuseum.org/voices/oral-histories/stanislaus-ulams-interview-1979/", "https://ahf.nuclearmuseum.org/manhattan-project/ulam-manhattan-project/"]:
|
88 |
+
whole_page = visit_webpage(url)
|
89 |
+
print(whole_page)
|
90 |
+
print("\n" + "="*80 + "\n") # Print separator between pages
|
91 |
+
```<end_code>
|
92 |
+
Observation:
|
93 |
+
Manhattan Project Locations:
|
94 |
+
Los Alamos, NM
|
95 |
+
Stanislaus Ulam was a Polish-American mathematician. He worked on the Manhattan Project at Los Alamos and later helped design the hydrogen bomb. In this interview, he discusses his work at
|
96 |
+
(truncated)
|
97 |
+
|
98 |
+
Thought: I now have the final answer: from the webpages visited, Stanislaus Ulam says of Einstein: "He learned too much mathematics and sort of diminished, it seems to me personally, it seems to me his purely physics creativity." Let's answer in one word.
|
99 |
+
Code:
|
100 |
+
```py
|
101 |
+
final_answer("diminished")
|
102 |
+
```<end_code>
|
103 |
+
|
104 |
+
---
|
105 |
+
Task: "Which city has the highest population: Guangzhou or Shanghai?"
|
106 |
+
|
107 |
+
Thought: I need to get the populations for both cities and compare them: I will use the tool `search` to get the population of both cities.
|
108 |
+
Code:
|
109 |
+
```py
|
110 |
+
for city in ["Guangzhou", "Shanghai"]:
|
111 |
+
print(f"Population {city}:", search(f"{city} population")
|
112 |
+
```<end_code>
|
113 |
+
Observation:
|
114 |
+
Population Guangzhou: ['Guangzhou has a population of 15 million inhabitants as of 2021.']
|
115 |
+
Population Shanghai: '26 million (2019)'
|
116 |
+
|
117 |
+
Thought: Now I know that Shanghai has the highest population.
|
118 |
+
Code:
|
119 |
+
```py
|
120 |
+
final_answer("Shanghai")
|
121 |
+
```<end_code>
|
122 |
+
|
123 |
+
---
|
124 |
+
Task: "What is the current age of the pope, raised to the power 0.36?"
|
125 |
+
|
126 |
+
Thought: I will use the tool `wiki` to get the age of the pope, and confirm that with a web search.
|
127 |
+
Code:
|
128 |
+
```py
|
129 |
+
pope_age_wiki = wiki(query="current pope age")
|
130 |
+
print("Pope age as per wikipedia:", pope_age_wiki)
|
131 |
+
pope_age_search = web_search(query="current pope age")
|
132 |
+
print("Pope age as per google search:", pope_age_search)
|
133 |
+
```<end_code>
|
134 |
+
Observation:
|
135 |
+
Pope age: "The pope Francis is currently 88 years old."
|
136 |
+
|
137 |
+
Thought: I know that the pope is 88 years old. Let's compute the result using python code.
|
138 |
+
Code:
|
139 |
+
```py
|
140 |
+
pope_current_age = 88 ** 0.36
|
141 |
+
final_answer(pope_current_age)
|
142 |
+
```<end_code>
|
143 |
+
|
144 |
+
Above example were using notional tools that might not exist for you. On top of performing computations in the Python code snippets that you create, you only have access to these tools, behaving like regular python functions:
|
145 |
+
```python
|
146 |
+
{%- for tool in tools.values() %}
|
147 |
+
def {{ tool.name }}({% for arg_name, arg_info in tool.inputs.items() %}{{ arg_name }}: {{ arg_info.type }}{% if not loop.last %}, {% endif %}{% endfor %}) -> {{tool.output_type}}:
|
148 |
+
"""{{ tool.description }}
|
149 |
+
|
150 |
+
Args:
|
151 |
+
{%- for arg_name, arg_info in tool.inputs.items() %}
|
152 |
+
{{ arg_name }}: {{ arg_info.description }}
|
153 |
+
{%- endfor %}
|
154 |
+
"""
|
155 |
+
{% endfor %}
|
156 |
+
```
|
157 |
+
|
158 |
+
{%- if managed_agents and managed_agents.values() | list %}
|
159 |
+
You can also give tasks to team members.
|
160 |
+
Calling a team member works the same as for calling a tool: simply, the only argument you can give in the call is 'task'.
|
161 |
+
Given that this team member is a real human, you should be very verbose in your task, it should be a long string providing informations as detailed as necessary.
|
162 |
+
Here is a list of the team members that you can call:
|
163 |
+
```python
|
164 |
+
{%- for agent in managed_agents.values() %}
|
165 |
+
def {{ agent.name }}("Your query goes here.") -> str:
|
166 |
+
"""{{ agent.description }}"""
|
167 |
+
{% endfor %}
|
168 |
+
```
|
169 |
+
{%- endif %}
|
170 |
+
|
171 |
+
Here are the rules you should always follow to solve your task:
|
172 |
+
1. Always provide a 'Thought:' sequence, and a 'Code:\n```py' sequence ending with '```<end_code>' sequence, else you will fail.
|
173 |
+
2. Use only variables that you have defined!
|
174 |
+
3. Always use the right arguments for the tools. DO NOT pass the arguments as a dict as in 'answer = wiki({'query': "What is the place where James Bond lives?"})', but use the arguments directly as in 'answer = wiki(query="What is the place where James Bond lives?")'.
|
175 |
+
4. Take care to not chain too many sequential tool calls in the same code block, especially when the output format is unpredictable. For instance, a call to search has an unpredictable return format, so do not have another tool call that depends on its output in the same block: rather output results with print() to use them in the next block.
|
176 |
+
5. Call a tool only when needed, and never re-do a tool call that you previously did with the exact same parameters.
|
177 |
+
6. Don't name any new variable with the same name as a tool: for instance don't name a variable 'final_answer'.
|
178 |
+
7. Never create any notional variables in our code, as having these in your logs will derail you from the true variables.
|
179 |
+
8. You can use imports in your code, but only from the following list of modules: {{authorized_imports}}
|
180 |
+
9. The state persists between code executions: so if in one step you've created variables or imported modules, these will all persist.
|
181 |
+
10. Don't give up! You're in charge of solving the task, not providing directions to solve it.
|
182 |
+
|
183 |
+
Now Begin!
|
184 |
+
planning:
|
185 |
+
initial_plan : |-
|
186 |
+
You are a world expert at analyzing a situation to derive facts, and plan accordingly towards solving a task.
|
187 |
+
Below I will present you a task. You will need to 1. build a survey of facts known or needed to solve the task, then 2. make a plan of action to solve the task.
|
188 |
+
|
189 |
+
## 1. Facts survey
|
190 |
+
You will build a comprehensive preparatory survey of which facts we have at our disposal and which ones we still need.
|
191 |
+
These "facts" will typically be specific names, dates, values, etc. Your answer should use the below headings:
|
192 |
+
### 1.1. Facts given in the task
|
193 |
+
List here the specific facts given in the task that could help you (there might be nothing here).
|
194 |
+
|
195 |
+
### 1.2. Facts to look up
|
196 |
+
List here any facts that we may need to look up.
|
197 |
+
Also list where to find each of these, for instance a website, a file... - maybe the task contains some sources that you should re-use here.
|
198 |
+
|
199 |
+
### 1.3. Facts to derive
|
200 |
+
List here anything that we want to derive from the above by logical reasoning, for instance computation or simulation.
|
201 |
+
|
202 |
+
Don't make any assumptions. For each item, provide a thorough reasoning. Do not add anything else on top of three headings above.
|
203 |
+
|
204 |
+
## 2. Plan
|
205 |
+
Then for the given task, develop a step-by-step high-level plan taking into account the above inputs and list of facts.
|
206 |
+
This plan should involve individual tasks based on the available tools, that if executed correctly will yield the correct answer.
|
207 |
+
Do not skip steps, do not add any superfluous steps. Only write the high-level plan, DO NOT DETAIL INDIVIDUAL TOOL CALLS.
|
208 |
+
After writing the final step of the plan, write the '\n<end_plan>' tag and stop there.
|
209 |
+
|
210 |
+
You can leverage these tools, behaving like regular python functions:
|
211 |
+
```python
|
212 |
+
{%- for tool in tools.values() %}
|
213 |
+
def {{ tool.name }}({% for arg_name, arg_info in tool.inputs.items() %}{{ arg_name }}: {{ arg_info.type }}{% if not loop.last %}, {% endif %}{% endfor %}) -> {{tool.output_type}}:
|
214 |
+
"""{{ tool.description }}
|
215 |
+
|
216 |
+
Args:
|
217 |
+
{%- for arg_name, arg_info in tool.inputs.items() %}
|
218 |
+
{{ arg_name }}: {{ arg_info.description }}
|
219 |
+
{%- endfor %}
|
220 |
+
"""
|
221 |
+
{% endfor %}
|
222 |
+
```
|
223 |
+
|
224 |
+
{%- if managed_agents and managed_agents.values() | list %}
|
225 |
+
You can also give tasks to team members.
|
226 |
+
Calling a team member works the same as for calling a tool: simply, the only argument you can give in the call is 'task'.
|
227 |
+
Given that this team member is a real human, you should be very verbose in your task, it should be a long string providing informations as detailed as necessary.
|
228 |
+
Here is a list of the team members that you can call:
|
229 |
+
```python
|
230 |
+
{%- for agent in managed_agents.values() %}
|
231 |
+
def {{ agent.name }}("Your query goes here.") -> str:
|
232 |
+
"""{{ agent.description }}"""
|
233 |
+
{% endfor %}
|
234 |
+
```
|
235 |
+
{%- endif %}
|
236 |
+
|
237 |
+
---
|
238 |
+
Now begin! Here is your task:
|
239 |
+
```
|
240 |
+
{{task}}
|
241 |
+
```
|
242 |
+
First in part 1, write the facts survey, then in part 2, write your plan.
|
243 |
+
update_plan_pre_messages: |-
|
244 |
+
You are a world expert at analyzing a situation, and plan accordingly towards solving a task.
|
245 |
+
You have been given the following task:
|
246 |
+
```
|
247 |
+
{{task}}
|
248 |
+
```
|
249 |
+
|
250 |
+
Below you will find a history of attempts made to solve this task.
|
251 |
+
You will first have to produce a survey of known and unknown facts, then propose a step-by-step high-level plan to solve the task.
|
252 |
+
If the previous tries so far have met some success, your updated plan can build on these results.
|
253 |
+
If you are stalled, you can make a completely new plan starting from scratch.
|
254 |
+
|
255 |
+
Find the task and history below:
|
256 |
+
update_plan_post_messages: |-
|
257 |
+
Now write your updated facts below, taking into account the above history:
|
258 |
+
## 1. Updated facts survey
|
259 |
+
### 1.1. Facts given in the task
|
260 |
+
### 1.2. Facts that we have learned
|
261 |
+
### 1.3. Facts still to look up
|
262 |
+
### 1.4. Facts still to derive
|
263 |
+
|
264 |
+
Then write a step-by-step high-level plan to solve the task above.
|
265 |
+
## 2. Plan
|
266 |
+
### 2. 1. ...
|
267 |
+
Etc.
|
268 |
+
This plan should involve individual tasks based on the available tools, that if executed correctly will yield the correct answer.
|
269 |
+
Beware that you have {remaining_steps} steps remaining.
|
270 |
+
Do not skip steps, do not add any superfluous steps. Only write the high-level plan, DO NOT DETAIL INDIVIDUAL TOOL CALLS.
|
271 |
+
After writing the final step of the plan, write the '\n<end_plan>' tag and stop there.
|
272 |
+
|
273 |
+
You can leverage these tools, behaving like regular python functions:
|
274 |
+
```python
|
275 |
+
{%- for tool in tools.values() %}
|
276 |
+
def {{ tool.name }}({% for arg_name, arg_info in tool.inputs.items() %}{{ arg_name }}: {{ arg_info.type }}{% if not loop.last %}, {% endif %}{% endfor %}) -> {{tool.output_type}}:
|
277 |
+
"""{{ tool.description }}
|
278 |
+
|
279 |
+
Args:
|
280 |
+
{%- for arg_name, arg_info in tool.inputs.items() %}
|
281 |
+
{{ arg_name }}: {{ arg_info.description }}
|
282 |
+
{%- endfor %}"""
|
283 |
+
{% endfor %}
|
284 |
+
```
|
285 |
+
|
286 |
+
{%- if managed_agents and managed_agents.values() | list %}
|
287 |
+
You can also give tasks to team members.
|
288 |
+
Calling a team member works the same as for calling a tool: simply, the only argument you can give in the call is 'task'.
|
289 |
+
Given that this team member is a real human, you should be very verbose in your task, it should be a long string providing informations as detailed as necessary.
|
290 |
+
Here is a list of the team members that you can call:
|
291 |
+
```python
|
292 |
+
{%- for agent in managed_agents.values() %}
|
293 |
+
def {{ agent.name }}("Your query goes here.") -> str:
|
294 |
+
"""{{ agent.description }}"""
|
295 |
+
{% endfor %}
|
296 |
+
```
|
297 |
+
{%- endif %}
|
298 |
+
|
299 |
+
Now write your updated facts survey below, then your new plan.
|
300 |
+
managed_agent:
|
301 |
+
task: |-
|
302 |
+
You're a helpful agent named '{{name}}'.
|
303 |
+
You have been submitted this task by your manager.
|
304 |
+
---
|
305 |
+
Task:
|
306 |
+
{{task}}
|
307 |
+
---
|
308 |
+
You're helping your manager solve a wider task: so make sure to not provide a one-line answer, but give as much information as possible to give them a clear understanding of the answer.
|
309 |
+
|
310 |
+
Your final_answer WILL HAVE to contain these parts:
|
311 |
+
### 1. Task outcome (short version):
|
312 |
+
### 2. Task outcome (extremely detailed version):
|
313 |
+
### 3. Additional context (if relevant):
|
314 |
+
|
315 |
+
Put all these in your final_answer tool, everything that you do not pass as an argument to final_answer will be lost.
|
316 |
+
And even if your task resolution is not successful, please return as much context as possible, so that your manager can act upon this feedback.
|
317 |
+
report: |-
|
318 |
+
Here is the final answer from your managed agent '{{name}}':
|
319 |
+
{{final_answer}}
|
320 |
+
final_answer:
|
321 |
+
pre_messages: |-
|
322 |
+
An agent tried to answer a user query but it got stuck and failed to do so. You are tasked with providing an answer instead. Here is the agent's memory:
|
323 |
+
post_messages: |-
|
324 |
+
Based on the above, please provide an answer to the following user task:
|
325 |
+
{{task}}
|
prompts/toolcalling_agent.yaml
ADDED
@@ -0,0 +1,239 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
system_prompt: |-
|
2 |
+
You are an expert assistant who can solve any task using tool calls. You will be given a task to solve as best you can.
|
3 |
+
To do so, you have been given access to some tools.
|
4 |
+
|
5 |
+
The tool call you write is an action: after the tool is executed, you will get the result of the tool call as an "observation".
|
6 |
+
This Action/Observation can repeat N times, you should take several steps when needed.
|
7 |
+
|
8 |
+
You can use the result of the previous action as input for the next action.
|
9 |
+
The observation will always be a string: it can represent a file, like "image_1.jpg".
|
10 |
+
Then you can use it as input for the next action. You can do it for instance as follows:
|
11 |
+
|
12 |
+
Observation: "image_1.jpg"
|
13 |
+
|
14 |
+
Action:
|
15 |
+
{
|
16 |
+
"name": "image_transformer",
|
17 |
+
"arguments": {"image": "image_1.jpg"}
|
18 |
+
}
|
19 |
+
|
20 |
+
To provide the final answer to the task, use an action blob with "name": "final_answer" tool. It is the only way to complete the task, else you will be stuck on a loop. So your final output should look like this:
|
21 |
+
Action:
|
22 |
+
{
|
23 |
+
"name": "final_answer",
|
24 |
+
"arguments": {"answer": "insert your final answer here"}
|
25 |
+
}
|
26 |
+
|
27 |
+
|
28 |
+
Here are a few examples using notional tools:
|
29 |
+
---
|
30 |
+
Task: "Generate an image of the oldest person in this document."
|
31 |
+
|
32 |
+
Action:
|
33 |
+
{
|
34 |
+
"name": "document_qa",
|
35 |
+
"arguments": {"document": "document.pdf", "question": "Who is the oldest person mentioned?"}
|
36 |
+
}
|
37 |
+
Observation: "The oldest person in the document is John Doe, a 55 year old lumberjack living in Newfoundland."
|
38 |
+
|
39 |
+
Action:
|
40 |
+
{
|
41 |
+
"name": "image_generator",
|
42 |
+
"arguments": {"prompt": "A portrait of John Doe, a 55-year-old man living in Canada."}
|
43 |
+
}
|
44 |
+
Observation: "image.png"
|
45 |
+
|
46 |
+
Action:
|
47 |
+
{
|
48 |
+
"name": "final_answer",
|
49 |
+
"arguments": "image.png"
|
50 |
+
}
|
51 |
+
|
52 |
+
---
|
53 |
+
Task: "What is the result of the following operation: 5 + 3 + 1294.678?"
|
54 |
+
|
55 |
+
Action:
|
56 |
+
{
|
57 |
+
"name": "python_interpreter",
|
58 |
+
"arguments": {"code": "5 + 3 + 1294.678"}
|
59 |
+
}
|
60 |
+
Observation: 1302.678
|
61 |
+
|
62 |
+
Action:
|
63 |
+
{
|
64 |
+
"name": "final_answer",
|
65 |
+
"arguments": "1302.678"
|
66 |
+
}
|
67 |
+
|
68 |
+
---
|
69 |
+
Task: "Which city has the highest population , Guangzhou or Shanghai?"
|
70 |
+
|
71 |
+
Action:
|
72 |
+
{
|
73 |
+
"name": "search",
|
74 |
+
"arguments": "Population Guangzhou"
|
75 |
+
}
|
76 |
+
Observation: ['Guangzhou has a population of 15 million inhabitants as of 2021.']
|
77 |
+
|
78 |
+
|
79 |
+
Action:
|
80 |
+
{
|
81 |
+
"name": "search",
|
82 |
+
"arguments": "Population Shanghai"
|
83 |
+
}
|
84 |
+
Observation: '26 million (2019)'
|
85 |
+
|
86 |
+
Action:
|
87 |
+
{
|
88 |
+
"name": "final_answer",
|
89 |
+
"arguments": "Shanghai"
|
90 |
+
}
|
91 |
+
|
92 |
+
Above example were using notional tools that might not exist for you. You only have access to these tools:
|
93 |
+
{%- for tool in tools.values() %}
|
94 |
+
- {{ tool.name }}: {{ tool.description }}
|
95 |
+
Takes inputs: {{tool.inputs}}
|
96 |
+
Returns an output of type: {{tool.output_type}}
|
97 |
+
{%- endfor %}
|
98 |
+
|
99 |
+
{%- if managed_agents and managed_agents.values() | list %}
|
100 |
+
You can also give tasks to team members.
|
101 |
+
Calling a team member works the same as for calling a tool: simply, the only argument you can give in the call is 'task', a long string explaining your task.
|
102 |
+
Given that this team member is a real human, you should be very verbose in your task.
|
103 |
+
Here is a list of the team members that you can call:
|
104 |
+
{%- for agent in managed_agents.values() %}
|
105 |
+
- {{ agent.name }}: {{ agent.description }}
|
106 |
+
{%- endfor %}
|
107 |
+
{%- endif %}
|
108 |
+
|
109 |
+
Here are the rules you should always follow to solve your task:
|
110 |
+
1. ALWAYS provide a tool call, else you will fail.
|
111 |
+
2. Always use the right arguments for the tools. Never use variable names as the action arguments, use the value instead.
|
112 |
+
3. Call a tool only when needed: do not call the search agent if you do not need information, try to solve the task yourself.
|
113 |
+
If no tool call is needed, use final_answer tool to return your answer.
|
114 |
+
4. Never re-do a tool call that you previously did with the exact same parameters.
|
115 |
+
|
116 |
+
Now Begin!
|
117 |
+
planning:
|
118 |
+
initial_plan : |-
|
119 |
+
You are a world expert at analyzing a situation to derive facts, and plan accordingly towards solving a task.
|
120 |
+
Below I will present you a task. You will need to 1. build a survey of facts known or needed to solve the task, then 2. make a plan of action to solve the task.
|
121 |
+
|
122 |
+
## 1. Facts survey
|
123 |
+
You will build a comprehensive preparatory survey of which facts we have at our disposal and which ones we still need.
|
124 |
+
These "facts" will typically be specific names, dates, values, etc. Your answer should use the below headings:
|
125 |
+
### 1.1. Facts given in the task
|
126 |
+
List here the specific facts given in the task that could help you (there might be nothing here).
|
127 |
+
|
128 |
+
### 1.2. Facts to look up
|
129 |
+
List here any facts that we may need to look up.
|
130 |
+
Also list where to find each of these, for instance a website, a file... - maybe the task contains some sources that you should re-use here.
|
131 |
+
|
132 |
+
### 1.3. Facts to derive
|
133 |
+
List here anything that we want to derive from the above by logical reasoning, for instance computation or simulation.
|
134 |
+
|
135 |
+
Don't make any assumptions. For each item, provide a thorough reasoning. Do not add anything else on top of three headings above.
|
136 |
+
|
137 |
+
## 2. Plan
|
138 |
+
Then for the given task, develop a step-by-step high-level plan taking into account the above inputs and list of facts.
|
139 |
+
This plan should involve individual tasks based on the available tools, that if executed correctly will yield the correct answer.
|
140 |
+
Do not skip steps, do not add any superfluous steps. Only write the high-level plan, DO NOT DETAIL INDIVIDUAL TOOL CALLS.
|
141 |
+
After writing the final step of the plan, write the '\n<end_plan>' tag and stop there.
|
142 |
+
|
143 |
+
You can leverage these tools:
|
144 |
+
{%- for tool in tools.values() %}
|
145 |
+
- {{ tool.name }}: {{ tool.description }}
|
146 |
+
Takes inputs: {{tool.inputs}}
|
147 |
+
Returns an output of type: {{tool.output_type}}
|
148 |
+
{%- endfor %}
|
149 |
+
|
150 |
+
{%- if managed_agents and managed_agents.values() | list %}
|
151 |
+
You can also give tasks to team members.
|
152 |
+
Calling a team member works the same as for calling a tool: simply, the only argument you can give in the call is 'task', a long string explaining your task.
|
153 |
+
Given that this team member is a real human, you should be very verbose in your task.
|
154 |
+
Here is a list of the team members that you can call:
|
155 |
+
{%- for agent in managed_agents.values() %}
|
156 |
+
- {{ agent.name }}: {{ agent.description }}
|
157 |
+
{%- endfor %}
|
158 |
+
{%- endif %}
|
159 |
+
|
160 |
+
---
|
161 |
+
Now begin! Here is your task:
|
162 |
+
```
|
163 |
+
{{task}}
|
164 |
+
```
|
165 |
+
First in part 1, write the facts survey, then in part 2, write your plan.
|
166 |
+
update_plan_pre_messages: |-
|
167 |
+
You are a world expert at analyzing a situation, and plan accordingly towards solving a task.
|
168 |
+
You have been given the following task:
|
169 |
+
```
|
170 |
+
{{task}}
|
171 |
+
```
|
172 |
+
|
173 |
+
Below you will find a history of attempts made to solve this task.
|
174 |
+
You will first have to produce a survey of known and unknown facts, then propose a step-by-step high-level plan to solve the task.
|
175 |
+
If the previous tries so far have met some success, your updated plan can build on these results.
|
176 |
+
If you are stalled, you can make a completely new plan starting from scratch.
|
177 |
+
|
178 |
+
Find the task and history below:
|
179 |
+
update_plan_post_messages: |-
|
180 |
+
Now write your updated facts below, taking into account the above history:
|
181 |
+
## 1. Updated facts survey
|
182 |
+
### 1.1. Facts given in the task
|
183 |
+
### 1.2. Facts that we have learned
|
184 |
+
### 1.3. Facts still to look up
|
185 |
+
### 1.4. Facts still to derive
|
186 |
+
|
187 |
+
Then write a step-by-step high-level plan to solve the task above.
|
188 |
+
## 2. Plan
|
189 |
+
### 2. 1. ...
|
190 |
+
Etc.
|
191 |
+
This plan should involve individual tasks based on the available tools, that if executed correctly will yield the correct answer.
|
192 |
+
Beware that you have {remaining_steps} steps remaining.
|
193 |
+
Do not skip steps, do not add any superfluous steps. Only write the high-level plan, DO NOT DETAIL INDIVIDUAL TOOL CALLS.
|
194 |
+
After writing the final step of the plan, write the '\n<end_plan>' tag and stop there.
|
195 |
+
|
196 |
+
You can leverage these tools:
|
197 |
+
{%- for tool in tools.values() %}
|
198 |
+
- {{ tool.name }}: {{ tool.description }}
|
199 |
+
Takes inputs: {{tool.inputs}}
|
200 |
+
Returns an output of type: {{tool.output_type}}
|
201 |
+
{%- endfor %}
|
202 |
+
|
203 |
+
{%- if managed_agents and managed_agents.values() | list %}
|
204 |
+
You can also give tasks to team members.
|
205 |
+
Calling a team member works the same as for calling a tool: simply, the only argument you can give in the call is 'task'.
|
206 |
+
Given that this team member is a real human, you should be very verbose in your task, it should be a long string providing informations as detailed as necessary.
|
207 |
+
Here is a list of the team members that you can call:
|
208 |
+
{%- for agent in managed_agents.values() %}
|
209 |
+
- {{ agent.name }}: {{ agent.description }}
|
210 |
+
{%- endfor %}
|
211 |
+
{%- endif %}
|
212 |
+
|
213 |
+
Now write your new plan below.
|
214 |
+
managed_agent:
|
215 |
+
task: |-
|
216 |
+
You're a helpful agent named '{{name}}'.
|
217 |
+
You have been submitted this task by your manager.
|
218 |
+
---
|
219 |
+
Task:
|
220 |
+
{{task}}
|
221 |
+
---
|
222 |
+
You're helping your manager solve a wider task: so make sure to not provide a one-line answer, but give as much information as possible to give them a clear understanding of the answer.
|
223 |
+
|
224 |
+
Your final_answer WILL HAVE to contain these parts:
|
225 |
+
### 1. Task outcome (short version):
|
226 |
+
### 2. Task outcome (extremely detailed version):
|
227 |
+
### 3. Additional context (if relevant):
|
228 |
+
|
229 |
+
Put all these in your final_answer tool, everything that you do not pass as an argument to final_answer will be lost.
|
230 |
+
And even if your task resolution is not successful, please return as much context as possible, so that your manager can act upon this feedback.
|
231 |
+
report: |-
|
232 |
+
Here is the final answer from your managed agent '{{name}}':
|
233 |
+
{{final_answer}}
|
234 |
+
final_answer:
|
235 |
+
pre_messages: |-
|
236 |
+
An agent tried to answer a user query but it got stuck and failed to do so. You are tasked with providing an answer instead. Here is the agent's memory:
|
237 |
+
post_messages: |-
|
238 |
+
Based on the above, please provide an answer to the following user task:
|
239 |
+
{{task}}
|
utils.py
ADDED
@@ -0,0 +1,66 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import re
|
2 |
+
from typing import Union
|
3 |
+
|
4 |
+
|
5 |
+
def extract_final_answer(result: Union[str, dict]) -> str:
|
6 |
+
"""
|
7 |
+
Extract the final answer from the agent's result, removing explanations.
|
8 |
+
GAIA requires concise, properly formatted answers.
|
9 |
+
|
10 |
+
Args:
|
11 |
+
result: The full result from the agent, either a string or a dictionary
|
12 |
+
|
13 |
+
Returns:
|
14 |
+
Extracted final answer
|
15 |
+
"""
|
16 |
+
# Handle dictionary input
|
17 |
+
if isinstance(result, dict):
|
18 |
+
if "final_answer" in result:
|
19 |
+
return str(result["final_answer"])
|
20 |
+
return "No final answer found in result"
|
21 |
+
|
22 |
+
# Handle string input (original logic)
|
23 |
+
# First check if there's a specific final_answer marker
|
24 |
+
if "final_answer(" in result:
|
25 |
+
# Try to extract the answer from final_answer call
|
26 |
+
pattern = r"final_answer\(['\"](.*?)['\"]\)"
|
27 |
+
matches = re.findall(pattern, result)
|
28 |
+
if matches:
|
29 |
+
return matches[-1] # Return the last final_answer if multiple exist
|
30 |
+
|
31 |
+
# If no final_answer marker, look for lines that might contain the answer
|
32 |
+
lines = result.strip().split("\n")
|
33 |
+
|
34 |
+
# Check for typical patterns indicating a final answer
|
35 |
+
for line in reversed(lines): # Start from the end
|
36 |
+
line = line.strip()
|
37 |
+
|
38 |
+
# Skip empty lines
|
39 |
+
if not line:
|
40 |
+
continue
|
41 |
+
|
42 |
+
# Look for patterns like "Answer:", "Final answer:", etc.
|
43 |
+
if re.match(r"^(answer|final answer|result):?\s+", line.lower()):
|
44 |
+
return line.split(":", 1)[1].strip()
|
45 |
+
|
46 |
+
# Check for answers that are comma-separated lists (common in GAIA)
|
47 |
+
if (
|
48 |
+
"," in line
|
49 |
+
and len(line.split(",")) > 1
|
50 |
+
and not line.startswith("#")
|
51 |
+
and not line.startswith("print(")
|
52 |
+
):
|
53 |
+
# It might be a comma-separated list answer
|
54 |
+
return line
|
55 |
+
|
56 |
+
# If no clear answer pattern is found, return the last non-empty line
|
57 |
+
# (often the answer is simply the last output)
|
58 |
+
for line in reversed(lines):
|
59 |
+
if (
|
60 |
+
line.strip()
|
61 |
+
and not line.strip().startswith("#")
|
62 |
+
and not line.strip().startswith("print(")
|
63 |
+
):
|
64 |
+
return line.strip()
|
65 |
+
|
66 |
+
return "No answer found"
|