Refactor prompts (#502)
Co-authored-by: Albert Villanova del Moral <8515462+albertvillanova@users.noreply.github.com>
This commit is contained in:
parent
f09b17f86d
commit
8ba036bba0
File diff suppressed because it is too large
Load Diff
|
@ -13,6 +13,7 @@ import subprocess
|
||||||
import sys
|
import sys
|
||||||
import tempfile
|
import tempfile
|
||||||
import traceback
|
import traceback
|
||||||
|
import zipfile
|
||||||
from typing import Any, Dict, List, Optional, Union
|
from typing import Any, Dict, List, Optional, Union
|
||||||
from urllib.parse import parse_qs, quote, unquote, urlparse, urlunparse
|
from urllib.parse import parse_qs, quote, unquote, urlparse, urlunparse
|
||||||
|
|
||||||
|
@ -624,6 +625,54 @@ class Mp3Converter(WavConverter):
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
|
class ZipConverter(DocumentConverter):
|
||||||
|
"""
|
||||||
|
Extracts ZIP files to a permanent local directory and returns a listing of extracted files.
|
||||||
|
"""
|
||||||
|
|
||||||
|
def __init__(self, extract_dir: str = "downloads"):
|
||||||
|
"""
|
||||||
|
Initialize with path to extraction directory.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
extract_dir: The directory where files will be extracted. Defaults to "downloads"
|
||||||
|
"""
|
||||||
|
self.extract_dir = extract_dir
|
||||||
|
# Create the extraction directory if it doesn't exist
|
||||||
|
os.makedirs(self.extract_dir, exist_ok=True)
|
||||||
|
|
||||||
|
def convert(self, local_path: str, **kwargs: Any) -> Union[None, DocumentConverterResult]:
|
||||||
|
# Bail if not a ZIP file
|
||||||
|
extension = kwargs.get("file_extension", "")
|
||||||
|
if extension.lower() != ".zip":
|
||||||
|
return None
|
||||||
|
|
||||||
|
# Verify it's actually a ZIP file
|
||||||
|
if not zipfile.is_zipfile(local_path):
|
||||||
|
return None
|
||||||
|
|
||||||
|
# Extract all files and build list
|
||||||
|
extracted_files = []
|
||||||
|
with zipfile.ZipFile(local_path, "r") as zip_ref:
|
||||||
|
# Extract all files
|
||||||
|
zip_ref.extractall(self.extract_dir)
|
||||||
|
# Get list of all files
|
||||||
|
for file_path in zip_ref.namelist():
|
||||||
|
# Skip directories
|
||||||
|
if not file_path.endswith("/"):
|
||||||
|
extracted_files.append(self.extract_dir + "/" + file_path)
|
||||||
|
|
||||||
|
# Sort files for consistent output
|
||||||
|
extracted_files.sort()
|
||||||
|
|
||||||
|
# Build the markdown content
|
||||||
|
md_content = "Downloaded the following files:\n"
|
||||||
|
for file in extracted_files:
|
||||||
|
md_content += f"* {file}\n"
|
||||||
|
|
||||||
|
return DocumentConverterResult(title="Extracted Files", text_content=md_content.strip())
|
||||||
|
|
||||||
|
|
||||||
class ImageConverter(MediaConverter):
|
class ImageConverter(MediaConverter):
|
||||||
"""
|
"""
|
||||||
Converts images to markdown via extraction of metadata (if `exiftool` is installed), OCR (if `easyocr` is installed), and description via a multimodal LLM (if an mlm_client is configured).
|
Converts images to markdown via extraction of metadata (if `exiftool` is installed), OCR (if `easyocr` is installed), and description via a multimodal LLM (if an mlm_client is configured).
|
||||||
|
@ -705,11 +754,11 @@ class ImageConverter(MediaConverter):
|
||||||
return response.choices[0].message.content
|
return response.choices[0].message.content
|
||||||
|
|
||||||
|
|
||||||
class FileConversionException(BaseException):
|
class FileConversionException(Exception):
|
||||||
pass
|
pass
|
||||||
|
|
||||||
|
|
||||||
class UnsupportedFormatException(BaseException):
|
class UnsupportedFormatException(Exception):
|
||||||
pass
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
@ -746,6 +795,7 @@ class MarkdownConverter:
|
||||||
self.register_page_converter(WavConverter())
|
self.register_page_converter(WavConverter())
|
||||||
self.register_page_converter(Mp3Converter())
|
self.register_page_converter(Mp3Converter())
|
||||||
self.register_page_converter(ImageConverter())
|
self.register_page_converter(ImageConverter())
|
||||||
|
self.register_page_converter(ZipConverter())
|
||||||
self.register_page_converter(PdfConverter())
|
self.register_page_converter(PdfConverter())
|
||||||
|
|
||||||
def convert(
|
def convert(
|
||||||
|
|
|
@ -15,11 +15,16 @@
|
||||||
# See the License for the specific language governing permissions and
|
# See the License for the specific language governing permissions and
|
||||||
# limitations under the License.
|
# limitations under the License.
|
||||||
import inspect
|
import inspect
|
||||||
|
import os
|
||||||
|
import re
|
||||||
|
import textwrap
|
||||||
import time
|
import time
|
||||||
from collections import deque
|
from collections import deque
|
||||||
from logging import getLogger
|
from logging import getLogger
|
||||||
from typing import Any, Callable, Dict, Generator, List, Optional, Tuple, Union
|
from typing import Any, Callable, Dict, Generator, List, Optional, Set, Tuple, Union
|
||||||
|
|
||||||
|
import yaml
|
||||||
|
from jinja2 import StrictUndefined, Template
|
||||||
from rich.console import Group
|
from rich.console import Group
|
||||||
from rich.panel import Panel
|
from rich.panel import Panel
|
||||||
from rich.rule import Rule
|
from rich.rule import Rule
|
||||||
|
@ -56,70 +61,23 @@ from .models import (
|
||||||
MessageRole,
|
MessageRole,
|
||||||
)
|
)
|
||||||
from .monitoring import Monitor
|
from .monitoring import Monitor
|
||||||
from .prompts import (
|
from .tools import Tool
|
||||||
CODE_SYSTEM_PROMPT,
|
|
||||||
MANAGED_AGENT_PROMPT,
|
|
||||||
PLAN_UPDATE_FINAL_PLAN_REDACTION,
|
|
||||||
SYSTEM_PROMPT_FACTS,
|
|
||||||
SYSTEM_PROMPT_FACTS_UPDATE,
|
|
||||||
SYSTEM_PROMPT_PLAN,
|
|
||||||
SYSTEM_PROMPT_PLAN_UPDATE,
|
|
||||||
TOOL_CALLING_SYSTEM_PROMPT,
|
|
||||||
USER_PROMPT_FACTS_UPDATE,
|
|
||||||
USER_PROMPT_PLAN,
|
|
||||||
USER_PROMPT_PLAN_UPDATE,
|
|
||||||
)
|
|
||||||
from .tools import (
|
|
||||||
DEFAULT_TOOL_DESCRIPTION_TEMPLATE,
|
|
||||||
Tool,
|
|
||||||
get_tool_description_with_args,
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
logger = getLogger(__name__)
|
logger = getLogger(__name__)
|
||||||
|
|
||||||
|
|
||||||
def get_tool_descriptions(tools: Dict[str, Tool], tool_description_template: str) -> str:
|
def get_variable_names(self, template: str) -> Set[str]:
|
||||||
return "\n".join([get_tool_description_with_args(tool, tool_description_template) for tool in tools.values()])
|
pattern = re.compile(r"\{\{([^{}]+)\}\}")
|
||||||
|
return {match.group(1).strip() for match in pattern.finditer(template)}
|
||||||
|
|
||||||
|
|
||||||
def format_prompt_with_tools(tools: Dict[str, Tool], prompt_template: str, tool_description_template: str) -> str:
|
def populate_template(template: str, variables: Dict[str, Any]) -> str:
|
||||||
tool_descriptions = get_tool_descriptions(tools, tool_description_template)
|
compiled_template = Template(template, undefined=StrictUndefined)
|
||||||
prompt = prompt_template.replace("{{tool_descriptions}}", tool_descriptions)
|
try:
|
||||||
if "{{tool_names}}" in prompt:
|
return compiled_template.render(**variables)
|
||||||
prompt = prompt.replace(
|
except Exception as e:
|
||||||
"{{tool_names}}",
|
raise Exception(f"Error during jinja template rendering: {type(e).__name__}: {e}")
|
||||||
", ".join([f"'{tool.name}'" for tool in tools.values()]),
|
|
||||||
)
|
|
||||||
return prompt
|
|
||||||
|
|
||||||
|
|
||||||
def show_agents_descriptions(managed_agents: Dict):
|
|
||||||
managed_agents_descriptions = """
|
|
||||||
You can also give requests to team members.
|
|
||||||
Calling a team member works the same as for calling a tool: simply, the only argument you can give in the call is 'request', a long string explaining your request.
|
|
||||||
Given that this team member is a real human, you should be very verbose in your request.
|
|
||||||
Here is a list of the team members that you can call:"""
|
|
||||||
for agent in managed_agents.values():
|
|
||||||
managed_agents_descriptions += f"\n- {agent.name}: {agent.description}"
|
|
||||||
return managed_agents_descriptions
|
|
||||||
|
|
||||||
|
|
||||||
def format_prompt_with_managed_agents_descriptions(
|
|
||||||
prompt_template,
|
|
||||||
managed_agents,
|
|
||||||
agent_descriptions_placeholder: Optional[str] = None,
|
|
||||||
) -> str:
|
|
||||||
if agent_descriptions_placeholder is None:
|
|
||||||
agent_descriptions_placeholder = "{{managed_agents_descriptions}}"
|
|
||||||
if agent_descriptions_placeholder not in prompt_template:
|
|
||||||
raise ValueError(
|
|
||||||
f"Provided prompt template does not contain the managed agents descriptions placeholder '{agent_descriptions_placeholder}'"
|
|
||||||
)
|
|
||||||
if len(managed_agents.keys()) > 0:
|
|
||||||
return prompt_template.replace(agent_descriptions_placeholder, show_agents_descriptions(managed_agents))
|
|
||||||
else:
|
|
||||||
return prompt_template.replace(agent_descriptions_placeholder, "")
|
|
||||||
|
|
||||||
|
|
||||||
class MultiStepAgent:
|
class MultiStepAgent:
|
||||||
|
@ -130,8 +88,7 @@ class MultiStepAgent:
|
||||||
Args:
|
Args:
|
||||||
tools (`list[Tool]`): [`Tool`]s that the agent can use.
|
tools (`list[Tool]`): [`Tool`]s that the agent can use.
|
||||||
model (`Callable[[list[dict[str, str]]], ChatMessage]`): Model that will generate the agent's actions.
|
model (`Callable[[list[dict[str, str]]], ChatMessage]`): Model that will generate the agent's actions.
|
||||||
system_prompt (`str`, *optional*): System prompt that will be used to generate the agent's actions.
|
prompts_path (`str`, *optional*): The path from which to load this agent's prompt dictionary.
|
||||||
tool_description_template (`str`, *optional*): Template used to describe the tools in the system prompt.
|
|
||||||
max_steps (`int`, default `6`): Maximum number of steps the agent can take to solve the task.
|
max_steps (`int`, default `6`): Maximum number of steps the agent can take to solve the task.
|
||||||
tool_parser (`Callable`, *optional*): Function used to parse the tool calls from the LLM output.
|
tool_parser (`Callable`, *optional*): Function used to parse the tool calls from the LLM output.
|
||||||
add_base_tools (`bool`, default `False`): Whether to add the base tools to the agent's tools.
|
add_base_tools (`bool`, default `False`): Whether to add the base tools to the agent's tools.
|
||||||
|
@ -142,16 +99,15 @@ class MultiStepAgent:
|
||||||
planning_interval (`int`, *optional*): Interval at which the agent will run a planning step.
|
planning_interval (`int`, *optional*): Interval at which the agent will run a planning step.
|
||||||
name (`str`, *optional*): Necessary for a managed agent only - the name by which this agent can be called.
|
name (`str`, *optional*): Necessary for a managed agent only - the name by which this agent can be called.
|
||||||
description (`str`, *optional*): Necessary for a managed agent only - the description of this agent.
|
description (`str`, *optional*): Necessary for a managed agent only - the description of this agent.
|
||||||
managed_agent_prompt (`str`, *optional*): Custom prompt for the managed agent. Defaults to None.
|
provide_run_summary (`bool`, *optional*): Whether to provide a run summary when called as a managed agent.
|
||||||
provide_run_summary (`bool`, *optional*): Wether to provide a run summary when called as a managed agent.
|
final_answer_checks (`list`, *optional*): List of Callables to run before returning a final answer for checking validity.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
def __init__(
|
def __init__(
|
||||||
self,
|
self,
|
||||||
tools: List[Tool],
|
tools: List[Tool],
|
||||||
model: Callable[[List[Dict[str, str]]], ChatMessage],
|
model: Callable[[List[Dict[str, str]]], ChatMessage],
|
||||||
system_prompt: Optional[str] = None,
|
prompts_path: Optional[str] = None,
|
||||||
tool_description_template: Optional[str] = None,
|
|
||||||
max_steps: int = 6,
|
max_steps: int = 6,
|
||||||
tool_parser: Optional[Callable] = None,
|
tool_parser: Optional[Callable] = None,
|
||||||
add_base_tools: bool = False,
|
add_base_tools: bool = False,
|
||||||
|
@ -162,19 +118,13 @@ class MultiStepAgent:
|
||||||
planning_interval: Optional[int] = None,
|
planning_interval: Optional[int] = None,
|
||||||
name: Optional[str] = None,
|
name: Optional[str] = None,
|
||||||
description: Optional[str] = None,
|
description: Optional[str] = None,
|
||||||
managed_agent_prompt: Optional[str] = None,
|
|
||||||
provide_run_summary: bool = False,
|
provide_run_summary: bool = False,
|
||||||
|
final_answer_checks: Optional[List[Callable]] = None,
|
||||||
):
|
):
|
||||||
if system_prompt is None:
|
|
||||||
system_prompt = CODE_SYSTEM_PROMPT
|
|
||||||
if tool_parser is None:
|
if tool_parser is None:
|
||||||
tool_parser = parse_json_tool_call
|
tool_parser = parse_json_tool_call
|
||||||
self.agent_name = self.__class__.__name__
|
self.agent_name = self.__class__.__name__
|
||||||
self.model = model
|
self.model = model
|
||||||
self.system_prompt_template = system_prompt
|
|
||||||
self.tool_description_template = (
|
|
||||||
tool_description_template if tool_description_template else DEFAULT_TOOL_DESCRIPTION_TEMPLATE
|
|
||||||
)
|
|
||||||
self.max_steps = max_steps
|
self.max_steps = max_steps
|
||||||
self.step_number: int = 0
|
self.step_number: int = 0
|
||||||
self.tool_parser = tool_parser
|
self.tool_parser = tool_parser
|
||||||
|
@ -183,7 +133,6 @@ class MultiStepAgent:
|
||||||
self.state = {}
|
self.state = {}
|
||||||
self.name = name
|
self.name = name
|
||||||
self.description = description
|
self.description = description
|
||||||
self.managed_agent_prompt = managed_agent_prompt if managed_agent_prompt else MANAGED_AGENT_PROMPT
|
|
||||||
self.provide_run_summary = provide_run_summary
|
self.provide_run_summary = provide_run_summary
|
||||||
|
|
||||||
self.managed_agents = {}
|
self.managed_agents = {}
|
||||||
|
@ -206,11 +155,12 @@ class MultiStepAgent:
|
||||||
self.system_prompt = self.initialize_system_prompt()
|
self.system_prompt = self.initialize_system_prompt()
|
||||||
self.input_messages = None
|
self.input_messages = None
|
||||||
self.task = None
|
self.task = None
|
||||||
self.memory = AgentMemory(system_prompt)
|
self.memory = AgentMemory(self.system_prompt)
|
||||||
self.logger = AgentLogger(level=verbosity_level)
|
self.logger = AgentLogger(level=verbosity_level)
|
||||||
self.monitor = Monitor(self.model, self.logger)
|
self.monitor = Monitor(self.model, self.logger)
|
||||||
self.step_callbacks = step_callbacks if step_callbacks is not None else []
|
self.step_callbacks = step_callbacks if step_callbacks is not None else []
|
||||||
self.step_callbacks.append(self.monitor.update_metrics)
|
self.step_callbacks.append(self.monitor.update_metrics)
|
||||||
|
self.final_answer_checks = final_answer_checks
|
||||||
|
|
||||||
@property
|
@property
|
||||||
def logs(self):
|
def logs(self):
|
||||||
|
@ -220,13 +170,8 @@ class MultiStepAgent:
|
||||||
return [self.memory.system_prompt] + self.memory.steps
|
return [self.memory.system_prompt] + self.memory.steps
|
||||||
|
|
||||||
def initialize_system_prompt(self):
|
def initialize_system_prompt(self):
|
||||||
system_prompt = format_prompt_with_tools(
|
"""To be implemented in child classes"""
|
||||||
self.tools,
|
pass
|
||||||
self.system_prompt_template,
|
|
||||||
self.tool_description_template,
|
|
||||||
)
|
|
||||||
system_prompt = format_prompt_with_managed_agents_descriptions(system_prompt, self.managed_agents)
|
|
||||||
return system_prompt
|
|
||||||
|
|
||||||
def write_memory_to_messages(
|
def write_memory_to_messages(
|
||||||
self,
|
self,
|
||||||
|
@ -358,10 +303,10 @@ class MultiStepAgent:
|
||||||
return observation
|
return observation
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
if tool_name in self.tools:
|
if tool_name in self.tools:
|
||||||
tool_description = get_tool_description_with_args(available_tools[tool_name])
|
tool = self.tools[tool_name]
|
||||||
error_msg = (
|
error_msg = (
|
||||||
f"Error in tool call execution: {type(e).__name__}: {e}\nYou should only use this tool with a correct input.\n"
|
f"Error whene executing tool {tool_name} with arguments {arguments}: {type(e).__name__}: {e}\nYou should only use this tool with a correct input.\n"
|
||||||
f"As a reminder, this tool's description is the following:\n{tool_description}"
|
f"As a reminder, this tool's description is the following: '{tool.description}'.\nIt takes inputs: {tool.inputs} and returns output type {tool.output_type}"
|
||||||
)
|
)
|
||||||
raise AgentExecutionError(error_msg, self.logger)
|
raise AgentExecutionError(error_msg, self.logger)
|
||||||
elif tool_name in self.managed_agents:
|
elif tool_name in self.managed_agents:
|
||||||
|
@ -380,7 +325,6 @@ class MultiStepAgent:
|
||||||
task: str,
|
task: str,
|
||||||
stream: bool = False,
|
stream: bool = False,
|
||||||
reset: bool = True,
|
reset: bool = True,
|
||||||
single_step: bool = False,
|
|
||||||
images: Optional[List[str]] = None,
|
images: Optional[List[str]] = None,
|
||||||
additional_args: Optional[Dict] = None,
|
additional_args: Optional[Dict] = None,
|
||||||
):
|
):
|
||||||
|
@ -391,7 +335,6 @@ class MultiStepAgent:
|
||||||
task (`str`): Task to perform.
|
task (`str`): Task to perform.
|
||||||
stream (`bool`): Whether to run in a streaming way.
|
stream (`bool`): Whether to run in a streaming way.
|
||||||
reset (`bool`): Whether to reset the conversation or keep it going from previous run.
|
reset (`bool`): Whether to reset the conversation or keep it going from previous run.
|
||||||
single_step (`bool`): Whether to run the agent in one-shot fashion.
|
|
||||||
images (`list[str]`, *optional*): Paths to image(s).
|
images (`list[str]`, *optional*): Paths to image(s).
|
||||||
additional_args (`dict`): Any other variables that you want to pass to the agent run, for instance images or dataframes. Give them clear names!
|
additional_args (`dict`): Any other variables that you want to pass to the agent run, for instance images or dataframes. Give them clear names!
|
||||||
|
|
||||||
|
@ -420,19 +363,10 @@ You have been provided with these additional arguments, that you can access usin
|
||||||
content=self.task.strip(),
|
content=self.task.strip(),
|
||||||
subtitle=f"{type(self.model).__name__} - {(self.model.model_id if hasattr(self.model, 'model_id') else '')}",
|
subtitle=f"{type(self.model).__name__} - {(self.model.model_id if hasattr(self.model, 'model_id') else '')}",
|
||||||
level=LogLevel.INFO,
|
level=LogLevel.INFO,
|
||||||
|
title=self.name if hasattr(self, "name") else None,
|
||||||
)
|
)
|
||||||
|
|
||||||
self.memory.steps.append(TaskStep(task=self.task, task_images=images))
|
self.memory.steps.append(TaskStep(task=self.task, task_images=images))
|
||||||
if single_step:
|
|
||||||
self.step_number = 1
|
|
||||||
step_start_time = time.time()
|
|
||||||
memory_step = ActionStep(start_time=step_start_time, observations_images=images)
|
|
||||||
memory_step.end_time = time.time()
|
|
||||||
memory_step.duration = memory_step.end_time - step_start_time
|
|
||||||
|
|
||||||
# Run the agent's step
|
|
||||||
result = self.step(memory_step)
|
|
||||||
return result
|
|
||||||
|
|
||||||
if stream:
|
if stream:
|
||||||
# The steps are returned as they are executed through a generator to iterate on.
|
# The steps are returned as they are executed through a generator to iterate on.
|
||||||
|
@ -468,6 +402,13 @@ You have been provided with these additional arguments, that you can access usin
|
||||||
|
|
||||||
# Run one step!
|
# Run one step!
|
||||||
final_answer = self.step(memory_step)
|
final_answer = self.step(memory_step)
|
||||||
|
if final_answer is not None and self.final_answer_checks is not None:
|
||||||
|
for check_function in self.final_answer_checks:
|
||||||
|
try:
|
||||||
|
assert check_function(final_answer, self.memory)
|
||||||
|
except Exception as e:
|
||||||
|
final_answer = None
|
||||||
|
raise AgentError(f"Check {check_function.__name__} failed with error: {e}", self.logger)
|
||||||
except AgentError as e:
|
except AgentError as e:
|
||||||
memory_step.error = e
|
memory_step.error = e
|
||||||
finally:
|
finally:
|
||||||
|
@ -515,46 +456,32 @@ You have been provided with these additional arguments, that you can access usin
|
||||||
if is_first_step:
|
if is_first_step:
|
||||||
message_prompt_facts = {
|
message_prompt_facts = {
|
||||||
"role": MessageRole.SYSTEM,
|
"role": MessageRole.SYSTEM,
|
||||||
"content": [{"type": "text", "text": SYSTEM_PROMPT_FACTS}],
|
"content": [{"type": "text", "text": self.prompt_templates["planning"]["initial_facts"]}],
|
||||||
}
|
}
|
||||||
message_prompt_task = {
|
input_messages = [message_prompt_facts]
|
||||||
"role": MessageRole.USER,
|
|
||||||
"content": [
|
|
||||||
{
|
|
||||||
"type": "text",
|
|
||||||
"text": f"""Here is the task:
|
|
||||||
```
|
|
||||||
{task}
|
|
||||||
```
|
|
||||||
Now begin!""",
|
|
||||||
}
|
|
||||||
],
|
|
||||||
}
|
|
||||||
input_messages = [message_prompt_facts, message_prompt_task]
|
|
||||||
|
|
||||||
chat_message_facts: ChatMessage = self.model(input_messages)
|
chat_message_facts: ChatMessage = self.model(input_messages)
|
||||||
answer_facts = chat_message_facts.content
|
answer_facts = chat_message_facts.content
|
||||||
|
|
||||||
message_system_prompt_plan = {
|
message_prompt_plan = {
|
||||||
"role": MessageRole.SYSTEM,
|
|
||||||
"content": [{"type": "text", "text": SYSTEM_PROMPT_PLAN}],
|
|
||||||
}
|
|
||||||
message_user_prompt_plan = {
|
|
||||||
"role": MessageRole.USER,
|
"role": MessageRole.USER,
|
||||||
"content": [
|
"content": [
|
||||||
{
|
{
|
||||||
"type": "text",
|
"type": "text",
|
||||||
"text": USER_PROMPT_PLAN.format(
|
"text": populate_template(
|
||||||
task=task,
|
self.prompt_templates["planning"]["initial_plan"],
|
||||||
tool_descriptions=get_tool_descriptions(self.tools, self.tool_description_template),
|
variables={
|
||||||
managed_agents_descriptions=(show_agents_descriptions(self.managed_agents)),
|
"task": task,
|
||||||
answer_facts=answer_facts,
|
"tools": self.tools,
|
||||||
|
"managed_agents": self.managed_agents,
|
||||||
|
"answer_facts": answer_facts,
|
||||||
|
},
|
||||||
),
|
),
|
||||||
}
|
}
|
||||||
],
|
],
|
||||||
}
|
}
|
||||||
chat_message_plan: ChatMessage = self.model(
|
chat_message_plan: ChatMessage = self.model(
|
||||||
[message_system_prompt_plan, message_user_prompt_plan],
|
[message_prompt_plan],
|
||||||
stop_sequences=["<end_plan>"],
|
stop_sequences=["<end_plan>"],
|
||||||
)
|
)
|
||||||
answer_plan = chat_message_plan.content
|
answer_plan = chat_message_plan.content
|
||||||
|
@ -587,51 +514,72 @@ Now begin!""",
|
||||||
) # This will not log the plan but will log facts
|
) # This will not log the plan but will log facts
|
||||||
|
|
||||||
# Redact updated facts
|
# Redact updated facts
|
||||||
facts_update_system_prompt = {
|
facts_update_pre_messages = {
|
||||||
"role": MessageRole.SYSTEM,
|
"role": MessageRole.SYSTEM,
|
||||||
"content": [{"type": "text", "text": SYSTEM_PROMPT_FACTS_UPDATE}],
|
"content": [{"type": "text", "text": self.prompt_templates["planning"]["update_facts_pre_messages"]}],
|
||||||
}
|
}
|
||||||
facts_update_message = {
|
facts_update_post_messages = {
|
||||||
"role": MessageRole.USER,
|
"role": MessageRole.SYSTEM,
|
||||||
"content": [{"type": "text", "text": USER_PROMPT_FACTS_UPDATE}],
|
"content": [{"type": "text", "text": self.prompt_templates["planning"]["update_facts_post_messages"]}],
|
||||||
}
|
}
|
||||||
input_messages = [facts_update_system_prompt] + memory_messages + [facts_update_message]
|
input_messages = [facts_update_pre_messages] + memory_messages + [facts_update_post_messages]
|
||||||
chat_message_facts: ChatMessage = self.model(input_messages)
|
chat_message_facts: ChatMessage = self.model(input_messages)
|
||||||
facts_update = chat_message_facts.content
|
facts_update = chat_message_facts.content
|
||||||
|
|
||||||
# Redact updated plan
|
# Redact updated plan
|
||||||
plan_update_message = {
|
update_plan_pre_messages = {
|
||||||
"role": MessageRole.SYSTEM,
|
"role": MessageRole.SYSTEM,
|
||||||
"content": [{"type": "text", "text": SYSTEM_PROMPT_PLAN_UPDATE.format(task=task)}],
|
|
||||||
}
|
|
||||||
plan_update_message_user = {
|
|
||||||
"role": MessageRole.USER,
|
|
||||||
"content": [
|
"content": [
|
||||||
{
|
{
|
||||||
"type": "text",
|
"type": "text",
|
||||||
"text": USER_PROMPT_PLAN_UPDATE.format(
|
"text": populate_template(
|
||||||
task=task,
|
self.prompt_templates["planning"]["update_plan_pre_messages"], variables={"task": task}
|
||||||
tool_descriptions=get_tool_descriptions(self.tools, self.tool_description_template),
|
),
|
||||||
managed_agents_descriptions=(show_agents_descriptions(self.managed_agents)),
|
}
|
||||||
facts_update=facts_update,
|
],
|
||||||
remaining_steps=(self.max_steps - step),
|
}
|
||||||
|
update_plan_post_messages = {
|
||||||
|
"role": MessageRole.SYSTEM,
|
||||||
|
"content": [
|
||||||
|
{
|
||||||
|
"type": "text",
|
||||||
|
"text": populate_template(
|
||||||
|
self.prompt_templates["planning"]["update_plan_pre_messages"],
|
||||||
|
variables={
|
||||||
|
"task": task,
|
||||||
|
"tools": self.tools,
|
||||||
|
"managed_agents": self.managed_agents,
|
||||||
|
"facts_update": facts_update,
|
||||||
|
"remaining_steps": (self.max_steps - step),
|
||||||
|
},
|
||||||
),
|
),
|
||||||
}
|
}
|
||||||
],
|
],
|
||||||
}
|
}
|
||||||
chat_message_plan: ChatMessage = self.model(
|
chat_message_plan: ChatMessage = self.model(
|
||||||
[plan_update_message] + memory_messages + [plan_update_message_user],
|
[update_plan_pre_messages] + memory_messages + [update_plan_post_messages],
|
||||||
stop_sequences=["<end_plan>"],
|
stop_sequences=["<end_plan>"],
|
||||||
)
|
)
|
||||||
|
|
||||||
# Log final facts and plan
|
# Log final facts and plan
|
||||||
final_plan_redaction = PLAN_UPDATE_FINAL_PLAN_REDACTION.format(
|
final_plan_redaction = textwrap.dedent(
|
||||||
task=task, plan_update=chat_message_plan.content
|
f"""I still need to solve the task I was given:
|
||||||
|
```
|
||||||
|
{task}
|
||||||
|
```
|
||||||
|
|
||||||
|
Here is my new/updated plan of action to solve the task:
|
||||||
|
```
|
||||||
|
{chat_message_plan.content}
|
||||||
|
```"""
|
||||||
|
)
|
||||||
|
|
||||||
|
final_facts_redaction = textwrap.dedent(
|
||||||
|
f"""Here is the updated list of the facts that I know:
|
||||||
|
```
|
||||||
|
{facts_update}
|
||||||
|
```"""
|
||||||
)
|
)
|
||||||
final_facts_redaction = f"""Here is the updated list of the facts that I know:
|
|
||||||
```
|
|
||||||
{facts_update}
|
|
||||||
```"""
|
|
||||||
self.memory.steps.append(
|
self.memory.steps.append(
|
||||||
PlanningStep(
|
PlanningStep(
|
||||||
model_input_messages=input_messages,
|
model_input_messages=input_messages,
|
||||||
|
@ -656,20 +604,25 @@ Now begin!""",
|
||||||
"""
|
"""
|
||||||
self.memory.replay(self.logger, detailed=detailed)
|
self.memory.replay(self.logger, detailed=detailed)
|
||||||
|
|
||||||
def __call__(self, request: str, **kwargs):
|
def __call__(self, task: str, **kwargs):
|
||||||
"""
|
"""
|
||||||
This methd is called only by a manager agent.
|
This methd is called only by a manager agent.
|
||||||
Adds additional prompting for the managed agent, runs it, and wraps the output.
|
Adds additional prompting for the managed agent, runs it, and wraps the output.
|
||||||
"""
|
"""
|
||||||
full_task = self.managed_agent_prompt.format(name=self.name, task=request).strip()
|
full_task = populate_template(
|
||||||
output = self.run(full_task, **kwargs)
|
self.prompt_templates["managed_agent"]["task"],
|
||||||
answer = f"Here is the final answer from your managed agent '{self.name}':\n{str(output)}"
|
variables=dict(name=self.name, task=task),
|
||||||
|
)
|
||||||
|
report = self.run(full_task, **kwargs)
|
||||||
|
answer = populate_template(
|
||||||
|
self.prompt_templates["managed_agent"]["report"], variables=dict(name=self.name, final_answer=report)
|
||||||
|
)
|
||||||
if self.provide_run_summary:
|
if self.provide_run_summary:
|
||||||
answer += f"\n\nFor more detail, find below a summary of this agent's work:\nSUMMARY OF WORK FROM AGENT '{self.name}':\n"
|
answer += "\n\nFor more detail, find below a summary of this agent's work:\n<summary_of_work>\n"
|
||||||
for message in self.write_memory_to_messages(summary_mode=True):
|
for message in self.write_memory_to_messages(summary_mode=True):
|
||||||
content = message["content"]
|
content = message["content"]
|
||||||
answer += "\n" + truncate_content(str(content)) + "\n---"
|
answer += "\n" + truncate_content(str(content)) + "\n---"
|
||||||
answer += f"\nEND OF SUMMARY OF WORK FROM AGENT '{self.name}'."
|
answer += "\n</summary_of_work>"
|
||||||
return answer
|
return answer
|
||||||
|
|
||||||
|
|
||||||
|
@ -680,30 +633,37 @@ class ToolCallingAgent(MultiStepAgent):
|
||||||
Args:
|
Args:
|
||||||
tools (`list[Tool]`): [`Tool`]s that the agent can use.
|
tools (`list[Tool]`): [`Tool`]s that the agent can use.
|
||||||
model (`Callable[[list[dict[str, str]]], ChatMessage]`): Model that will generate the agent's actions.
|
model (`Callable[[list[dict[str, str]]], ChatMessage]`): Model that will generate the agent's actions.
|
||||||
system_prompt (`str`, *optional*): System prompt that will be used to generate the agent's actions.
|
prompts_path (`str`, *optional*): The path from which to load this agent's prompt dictionary.
|
||||||
planning_interval (`int`, *optional*): Interval at which the agent will run a planning step.
|
planning_interval (`int`, *optional*): Interval at which the agent will run a planning step.
|
||||||
**kwargs: Additional keyword arguments.
|
**kwargs: Additional keyword arguments.
|
||||||
|
|
||||||
"""
|
"""
|
||||||
|
|
||||||
def __init__(
|
def __init__(
|
||||||
self,
|
self,
|
||||||
tools: List[Tool],
|
tools: List[Tool],
|
||||||
model: Callable[[List[Dict[str, str]]], ChatMessage],
|
model: Callable[[List[Dict[str, str]]], ChatMessage],
|
||||||
system_prompt: Optional[str] = None,
|
prompts_path: Optional[str] = None,
|
||||||
planning_interval: Optional[int] = None,
|
planning_interval: Optional[int] = None,
|
||||||
**kwargs,
|
**kwargs,
|
||||||
):
|
):
|
||||||
if system_prompt is None:
|
yaml_path = os.path.join(os.path.dirname(__file__), "prompts", "toolcalling_agent.yaml")
|
||||||
system_prompt = TOOL_CALLING_SYSTEM_PROMPT
|
with open(yaml_path, "r") as f:
|
||||||
|
self.prompt_templates = yaml.safe_load(f)
|
||||||
super().__init__(
|
super().__init__(
|
||||||
tools=tools,
|
tools=tools,
|
||||||
model=model,
|
model=model,
|
||||||
system_prompt=system_prompt,
|
prompts_path=prompts_path,
|
||||||
planning_interval=planning_interval,
|
planning_interval=planning_interval,
|
||||||
**kwargs,
|
**kwargs,
|
||||||
)
|
)
|
||||||
|
|
||||||
|
def initialize_system_prompt(self) -> str:
|
||||||
|
system_prompt = populate_template(
|
||||||
|
self.prompt_templates["system_prompt"],
|
||||||
|
variables={"tools": self.tools, "managed_agents": self.managed_agents},
|
||||||
|
)
|
||||||
|
return system_prompt
|
||||||
|
|
||||||
def step(self, memory_step: ActionStep) -> Union[None, Any]:
|
def step(self, memory_step: ActionStep) -> Union[None, Any]:
|
||||||
"""
|
"""
|
||||||
Perform one step in the ReAct framework: the agent thinks, acts, and observes the result.
|
Perform one step in the ReAct framework: the agent thinks, acts, and observes the result.
|
||||||
|
@ -795,7 +755,7 @@ class CodeAgent(MultiStepAgent):
|
||||||
Args:
|
Args:
|
||||||
tools (`list[Tool]`): [`Tool`]s that the agent can use.
|
tools (`list[Tool]`): [`Tool`]s that the agent can use.
|
||||||
model (`Callable[[list[dict[str, str]]], ChatMessage]`): Model that will generate the agent's actions.
|
model (`Callable[[list[dict[str, str]]], ChatMessage]`): Model that will generate the agent's actions.
|
||||||
system_prompt (`str`, *optional*): System prompt that will be used to generate the agent's actions.
|
prompts_path (`str`, *optional*): The path from which to load this agent's prompt dictionary.
|
||||||
grammar (`dict[str, str]`, *optional*): Grammar used to parse the LLM output.
|
grammar (`dict[str, str]`, *optional*): Grammar used to parse the LLM output.
|
||||||
additional_authorized_imports (`list[str]`, *optional*): Additional authorized imports for the agent.
|
additional_authorized_imports (`list[str]`, *optional*): Additional authorized imports for the agent.
|
||||||
planning_interval (`int`, *optional*): Interval at which the agent will run a planning step.
|
planning_interval (`int`, *optional*): Interval at which the agent will run a planning step.
|
||||||
|
@ -809,7 +769,7 @@ class CodeAgent(MultiStepAgent):
|
||||||
self,
|
self,
|
||||||
tools: List[Tool],
|
tools: List[Tool],
|
||||||
model: Callable[[List[Dict[str, str]]], ChatMessage],
|
model: Callable[[List[Dict[str, str]]], ChatMessage],
|
||||||
system_prompt: Optional[str] = None,
|
prompts_path: Optional[str] = None,
|
||||||
grammar: Optional[Dict[str, str]] = None,
|
grammar: Optional[Dict[str, str]] = None,
|
||||||
additional_authorized_imports: Optional[List[str]] = None,
|
additional_authorized_imports: Optional[List[str]] = None,
|
||||||
planning_interval: Optional[int] = None,
|
planning_interval: Optional[int] = None,
|
||||||
|
@ -817,17 +777,14 @@ class CodeAgent(MultiStepAgent):
|
||||||
max_print_outputs_length: Optional[int] = None,
|
max_print_outputs_length: Optional[int] = None,
|
||||||
**kwargs,
|
**kwargs,
|
||||||
):
|
):
|
||||||
if system_prompt is None:
|
|
||||||
system_prompt = CODE_SYSTEM_PROMPT
|
|
||||||
|
|
||||||
self.additional_authorized_imports = additional_authorized_imports if additional_authorized_imports else []
|
self.additional_authorized_imports = additional_authorized_imports if additional_authorized_imports else []
|
||||||
self.authorized_imports = list(set(BASE_BUILTIN_MODULES) | set(self.additional_authorized_imports))
|
self.authorized_imports = list(set(BASE_BUILTIN_MODULES) | set(self.additional_authorized_imports))
|
||||||
if "{{authorized_imports}}" not in system_prompt:
|
yaml_path = os.path.join(os.path.dirname(__file__), "prompts", "code_agent.yaml")
|
||||||
raise ValueError("Tag '{{authorized_imports}}' should be provided in the prompt.")
|
with open(yaml_path, "r") as f:
|
||||||
|
self.prompt_templates = yaml.safe_load(f)
|
||||||
super().__init__(
|
super().__init__(
|
||||||
tools=tools,
|
tools=tools,
|
||||||
model=model,
|
model=model,
|
||||||
system_prompt=system_prompt,
|
|
||||||
grammar=grammar,
|
grammar=grammar,
|
||||||
planning_interval=planning_interval,
|
planning_interval=planning_interval,
|
||||||
**kwargs,
|
**kwargs,
|
||||||
|
@ -857,17 +814,20 @@ class CodeAgent(MultiStepAgent):
|
||||||
max_print_outputs_length=max_print_outputs_length,
|
max_print_outputs_length=max_print_outputs_length,
|
||||||
)
|
)
|
||||||
|
|
||||||
def initialize_system_prompt(self):
|
def initialize_system_prompt(self) -> str:
|
||||||
self.system_prompt = super().initialize_system_prompt()
|
system_prompt = populate_template(
|
||||||
self.system_prompt = self.system_prompt.replace(
|
self.prompt_templates["system_prompt"],
|
||||||
"{{authorized_imports}}",
|
variables={
|
||||||
(
|
"tools": self.tools,
|
||||||
"You can import from any package you want."
|
"managed_agents": self.managed_agents,
|
||||||
if "*" in self.authorized_imports
|
"authorized_imports": (
|
||||||
else str(self.authorized_imports)
|
"You can import from any package you want."
|
||||||
),
|
if "*" in self.authorized_imports
|
||||||
|
else str(self.authorized_imports)
|
||||||
|
),
|
||||||
|
},
|
||||||
)
|
)
|
||||||
return self.system_prompt
|
return system_prompt
|
||||||
|
|
||||||
def step(self, memory_step: ActionStep) -> Union[None, Any]:
|
def step(self, memory_step: ActionStep) -> Union[None, Any]:
|
||||||
"""
|
"""
|
||||||
|
|
|
@ -156,7 +156,7 @@ class PlanningStep(MemoryStep):
|
||||||
)
|
)
|
||||||
)
|
)
|
||||||
|
|
||||||
if not summary_mode:
|
if not summary_mode: # This step is not shown to a model writing a plan to avoid influencing the new plan
|
||||||
messages.append(
|
messages.append(
|
||||||
Message(
|
Message(
|
||||||
role=MessageRole.ASSISTANT, content=[{"type": "text", "text": f"[PLAN]:\n{self.plan.strip()}"}]
|
role=MessageRole.ASSISTANT, content=[{"type": "text", "text": f"[PLAN]:\n{self.plan.strip()}"}]
|
||||||
|
@ -186,7 +186,7 @@ class SystemPromptStep(MemoryStep):
|
||||||
def to_messages(self, summary_mode: bool = False, **kwargs) -> List[Message]:
|
def to_messages(self, summary_mode: bool = False, **kwargs) -> List[Message]:
|
||||||
if summary_mode:
|
if summary_mode:
|
||||||
return []
|
return []
|
||||||
return [Message(role=MessageRole.SYSTEM, content=[{"type": "text", "text": self.system_prompt.strip()}])]
|
return [Message(role=MessageRole.SYSTEM, content=[{"type": "text", "text": self.system_prompt}])]
|
||||||
|
|
||||||
|
|
||||||
class AgentMemory:
|
class AgentMemory:
|
||||||
|
|
|
@ -141,11 +141,11 @@ class AgentLogger:
|
||||||
level=LogLevel.INFO,
|
level=LogLevel.INFO,
|
||||||
)
|
)
|
||||||
|
|
||||||
def log_task(self, content: str, subtitle: str, level: int = LogLevel.INFO) -> None:
|
def log_task(self, content: str, subtitle: str, title: Optional[str] = None, level: int = LogLevel.INFO) -> None:
|
||||||
self.log(
|
self.log(
|
||||||
Panel(
|
Panel(
|
||||||
f"\n[bold]{content}\n",
|
f"\n[bold]{content}\n",
|
||||||
title="[bold]New run",
|
title="[bold]New run" + (f" - {title}" if title else ""),
|
||||||
subtitle=subtitle,
|
subtitle=subtitle,
|
||||||
border_style=YELLOW_HEX,
|
border_style=YELLOW_HEX,
|
||||||
subtitle_align="left",
|
subtitle_align="left",
|
||||||
|
@ -167,7 +167,7 @@ class AgentLogger:
|
||||||
def visualize_agent_tree(self, agent):
|
def visualize_agent_tree(self, agent):
|
||||||
def create_tools_section(tools_dict):
|
def create_tools_section(tools_dict):
|
||||||
table = Table(show_header=True, header_style="bold")
|
table = Table(show_header=True, header_style="bold")
|
||||||
table.add_column("Name", style="blue")
|
table.add_column("Name", style="#1E90FF")
|
||||||
table.add_column("Description")
|
table.add_column("Description")
|
||||||
table.add_column("Arguments")
|
table.add_column("Arguments")
|
||||||
|
|
||||||
|
@ -178,26 +178,32 @@ class AgentLogger:
|
||||||
]
|
]
|
||||||
table.add_row(name, getattr(tool, "description", str(tool)), "\n".join(args))
|
table.add_row(name, getattr(tool, "description", str(tool)), "\n".join(args))
|
||||||
|
|
||||||
return Group(Text("🛠️ Tools", style="bold italic blue"), table)
|
return Group("🛠️ [italic #1E90FF]Tools:[/italic #1E90FF]", table)
|
||||||
|
|
||||||
|
def get_agent_headline(agent, name: Optional[str] = None):
|
||||||
|
name_headline = f"{name} | " if name else ""
|
||||||
|
return f"[bold {YELLOW_HEX}]{name_headline}{agent.__class__.__name__} | {agent.model.model_id}"
|
||||||
|
|
||||||
def build_agent_tree(parent_tree, agent_obj):
|
def build_agent_tree(parent_tree, agent_obj):
|
||||||
"""Recursively builds the agent tree."""
|
"""Recursively builds the agent tree."""
|
||||||
if agent_obj.tools:
|
parent_tree.add(create_tools_section(agent_obj.tools))
|
||||||
parent_tree.add(create_tools_section(agent_obj.tools))
|
|
||||||
|
|
||||||
if agent_obj.managed_agents:
|
if agent_obj.managed_agents:
|
||||||
agents_branch = parent_tree.add("[bold italic blue]🤖 Managed agents")
|
agents_branch = parent_tree.add("🤖 [italic #1E90FF]Managed agents:")
|
||||||
for name, managed_agent in agent_obj.managed_agents.items():
|
for name, managed_agent in agent_obj.managed_agents.items():
|
||||||
agent_node_text = f"[bold {YELLOW_HEX}]{name} - {managed_agent.agent.__class__.__name__}"
|
agent_tree = agents_branch.add(get_agent_headline(managed_agent, name))
|
||||||
agent_tree = agents_branch.add(agent_node_text)
|
if managed_agent.__class__.__name__ == "CodeAgent":
|
||||||
if hasattr(managed_agent, "description"):
|
|
||||||
agent_tree.add(
|
agent_tree.add(
|
||||||
f"[bold italic blue]📝 Description:[/bold italic blue] {managed_agent.description}"
|
f"✅ [italic #1E90FF]Authorized imports:[/italic #1E90FF] {managed_agent.additional_authorized_imports}"
|
||||||
)
|
)
|
||||||
if hasattr(managed_agent, "agent"):
|
agent_tree.add(f"📝 [italic #1E90FF]Description:[/italic #1E90FF] {managed_agent.description}")
|
||||||
build_agent_tree(agent_tree, managed_agent.agent)
|
build_agent_tree(agent_tree, managed_agent)
|
||||||
|
|
||||||
main_tree = Tree(f"[bold {YELLOW_HEX}]{agent.__class__.__name__}")
|
main_tree = Tree(get_agent_headline(agent))
|
||||||
|
if agent.__class__.__name__ == "CodeAgent":
|
||||||
|
main_tree.add(
|
||||||
|
f"✅ [italic #1E90FF]Authorized imports:[/italic #1E90FF] {agent.additional_authorized_imports}"
|
||||||
|
)
|
||||||
build_agent_tree(main_tree, agent)
|
build_agent_tree(main_tree, agent)
|
||||||
self.console.print(main_tree)
|
self.console.print(main_tree)
|
||||||
|
|
||||||
|
|
|
@ -1,523 +0,0 @@
|
||||||
#!/usr/bin/env python
|
|
||||||
# coding=utf-8
|
|
||||||
|
|
||||||
# Copyright 2024 The HuggingFace Inc. team. All rights reserved.
|
|
||||||
#
|
|
||||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
|
||||||
# you may not use this file except in compliance with the License.
|
|
||||||
# You may obtain a copy of the License at
|
|
||||||
#
|
|
||||||
# http://www.apache.org/licenses/LICENSE-2.0
|
|
||||||
#
|
|
||||||
# Unless required by applicable law or agreed to in writing, software
|
|
||||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
|
||||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
||||||
# See the License for the specific language governing permissions and
|
|
||||||
# limitations under the License.
|
|
||||||
SINGLE_STEP_CODE_SYSTEM_PROMPT = """You will be given a task to solve, your job is to come up with a series of simple commands in Python that will perform the task.
|
|
||||||
To help you, I will give you access to a set of tools that you can use. Each tool is a Python function and has a description explaining the task it performs, the inputs it expects and the outputs it returns.
|
|
||||||
You should first explain which tool you will use to perform the task and for what reason, then write the code in Python.
|
|
||||||
Each instruction in Python should be a simple assignment. You can print intermediate results if it makes sense to do so.
|
|
||||||
In the end, use tool 'final_answer' to return your answer, its argument will be what gets returned.
|
|
||||||
You can use imports in your code, but only from the following list of modules: <<authorized_imports>>
|
|
||||||
Be sure to provide a 'Code:' token, else the run will fail.
|
|
||||||
|
|
||||||
Tools:
|
|
||||||
{{tool_descriptions}}
|
|
||||||
|
|
||||||
Examples:
|
|
||||||
---
|
|
||||||
Task:
|
|
||||||
"Answer the question in the variable `question` about the image stored in the variable `image`. The question is in French.
|
|
||||||
You have been provided with these additional arguments, that you can access using the keys as variables in your python code:
|
|
||||||
{'question': 'Quel est l'animal sur l'image?', 'image': 'path/to/image.jpg'}"
|
|
||||||
|
|
||||||
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.
|
|
||||||
Code:
|
|
||||||
```py
|
|
||||||
translated_question = translator(question=question, src_lang="French", tgt_lang="English")
|
|
||||||
print(f"The translated question is {translated_question}.")
|
|
||||||
answer = image_qa(image=image, question=translated_question)
|
|
||||||
final_answer(f"The answer is {answer}")
|
|
||||||
```<end_code>
|
|
||||||
|
|
||||||
---
|
|
||||||
Task: "Identify the oldest person in the `document` and create an image showcasing the result."
|
|
||||||
|
|
||||||
Thought: I will 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.
|
|
||||||
Code:
|
|
||||||
```py
|
|
||||||
answer = document_qa(document, question="What is the oldest person?")
|
|
||||||
print(f"The answer is {answer}.")
|
|
||||||
image = image_generator(answer)
|
|
||||||
final_answer(image)
|
|
||||||
```<end_code>
|
|
||||||
|
|
||||||
---
|
|
||||||
Task: "Generate an image using the text given in the variable `caption`."
|
|
||||||
|
|
||||||
Thought: I will use the following tool: `image_generator` to generate an image.
|
|
||||||
Code:
|
|
||||||
```py
|
|
||||||
image = image_generator(prompt=caption)
|
|
||||||
final_answer(image)
|
|
||||||
```<end_code>
|
|
||||||
|
|
||||||
---
|
|
||||||
Task: "Summarize the text given in the variable `text` and read it out loud."
|
|
||||||
|
|
||||||
Thought: I will use the following tools: `summarizer` to create a summary of the input text, then `text_reader` to read it out loud.
|
|
||||||
Code:
|
|
||||||
```py
|
|
||||||
summarized_text = summarizer(text)
|
|
||||||
print(f"Summary: {summarized_text}")
|
|
||||||
audio_summary = text_reader(summarized_text)
|
|
||||||
final_answer(audio_summary)
|
|
||||||
```<end_code>
|
|
||||||
|
|
||||||
---
|
|
||||||
Task: "Answer the question in the variable `question` about the text in the variable `text`. Use the answer to generate an image."
|
|
||||||
|
|
||||||
Thought: I will use the following tools: `text_qa` to create the answer, then `image_generator` to generate an image according to the answer.
|
|
||||||
Code:
|
|
||||||
```py
|
|
||||||
answer = text_qa(text=text, question=question)
|
|
||||||
print(f"The answer is {answer}.")
|
|
||||||
image = image_generator(answer)
|
|
||||||
final_answer(image)
|
|
||||||
```<end_code>
|
|
||||||
|
|
||||||
---
|
|
||||||
Task: "Caption the following `image`."
|
|
||||||
|
|
||||||
Thought: I will use the following tool: `image_captioner` to generate a caption for the image.
|
|
||||||
Code:
|
|
||||||
```py
|
|
||||||
caption = image_captioner(image)
|
|
||||||
final_answer(caption)
|
|
||||||
```<end_code>
|
|
||||||
|
|
||||||
---
|
|
||||||
Above example were using tools that might not exist for you. You only have access to these tools:
|
|
||||||
{{tool_names}}
|
|
||||||
|
|
||||||
{{managed_agents_descriptions}}
|
|
||||||
|
|
||||||
Remember to make sure that variables you use are all defined. In particular don't import packages!
|
|
||||||
Be sure to provide a 'Code:\n```' sequence before the code and '```<end_code>' after, else you will get an error.
|
|
||||||
DO NOT pass the arguments as a dict as in 'answer = ask_search_agent({'query': "What is the place where James Bond lives?"})', but use the arguments directly as in 'answer = ask_search_agent(query="What is the place where James Bond lives?")'.
|
|
||||||
|
|
||||||
Now Begin! If you solve the task correctly, you will receive a reward of $1,000,000.
|
|
||||||
"""
|
|
||||||
|
|
||||||
|
|
||||||
TOOL_CALLING_SYSTEM_PROMPT = """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.
|
|
||||||
To do so, you have been given access to the following tools: {{tool_names}}
|
|
||||||
|
|
||||||
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".
|
|
||||||
This Action/Observation can repeat N times, you should take several steps when needed.
|
|
||||||
|
|
||||||
You can use the result of the previous action as input for the next action.
|
|
||||||
The observation will always be a string: it can represent a file, like "image_1.jpg".
|
|
||||||
Then you can use it as input for the next action. You can do it for instance as follows:
|
|
||||||
|
|
||||||
Observation: "image_1.jpg"
|
|
||||||
|
|
||||||
Action:
|
|
||||||
{
|
|
||||||
"name": "image_transformer",
|
|
||||||
"arguments": {"image": "image_1.jpg"}
|
|
||||||
}
|
|
||||||
|
|
||||||
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:
|
|
||||||
Action:
|
|
||||||
{
|
|
||||||
"name": "final_answer",
|
|
||||||
"arguments": {"answer": "insert your final answer here"}
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
Here are a few examples using notional tools:
|
|
||||||
---
|
|
||||||
Task: "Generate an image of the oldest person in this document."
|
|
||||||
|
|
||||||
Action:
|
|
||||||
{
|
|
||||||
"name": "document_qa",
|
|
||||||
"arguments": {"document": "document.pdf", "question": "Who is the oldest person mentioned?"}
|
|
||||||
}
|
|
||||||
Observation: "The oldest person in the document is John Doe, a 55 year old lumberjack living in Newfoundland."
|
|
||||||
|
|
||||||
Action:
|
|
||||||
{
|
|
||||||
"name": "image_generator",
|
|
||||||
"arguments": {"prompt": "A portrait of John Doe, a 55-year-old man living in Canada."}
|
|
||||||
}
|
|
||||||
Observation: "image.png"
|
|
||||||
|
|
||||||
Action:
|
|
||||||
{
|
|
||||||
"name": "final_answer",
|
|
||||||
"arguments": "image.png"
|
|
||||||
}
|
|
||||||
|
|
||||||
---
|
|
||||||
Task: "What is the result of the following operation: 5 + 3 + 1294.678?"
|
|
||||||
|
|
||||||
Action:
|
|
||||||
{
|
|
||||||
"name": "python_interpreter",
|
|
||||||
"arguments": {"code": "5 + 3 + 1294.678"}
|
|
||||||
}
|
|
||||||
Observation: 1302.678
|
|
||||||
|
|
||||||
Action:
|
|
||||||
{
|
|
||||||
"name": "final_answer",
|
|
||||||
"arguments": "1302.678"
|
|
||||||
}
|
|
||||||
|
|
||||||
---
|
|
||||||
Task: "Which city has the highest population , Guangzhou or Shanghai?"
|
|
||||||
|
|
||||||
Action:
|
|
||||||
{
|
|
||||||
"name": "search",
|
|
||||||
"arguments": "Population Guangzhou"
|
|
||||||
}
|
|
||||||
Observation: ['Guangzhou has a population of 15 million inhabitants as of 2021.']
|
|
||||||
|
|
||||||
|
|
||||||
Action:
|
|
||||||
{
|
|
||||||
"name": "search",
|
|
||||||
"arguments": "Population Shanghai"
|
|
||||||
}
|
|
||||||
Observation: '26 million (2019)'
|
|
||||||
|
|
||||||
Action:
|
|
||||||
{
|
|
||||||
"name": "final_answer",
|
|
||||||
"arguments": "Shanghai"
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
Above example were using notional tools that might not exist for you. You only have access to these tools:
|
|
||||||
|
|
||||||
{{tool_descriptions}}
|
|
||||||
|
|
||||||
{{managed_agents_descriptions}}
|
|
||||||
|
|
||||||
Here are the rules you should always follow to solve your task:
|
|
||||||
1. ALWAYS provide a tool call, else you will fail.
|
|
||||||
2. Always use the right arguments for the tools. Never use variable names as the action arguments, use the value instead.
|
|
||||||
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.
|
|
||||||
If no tool call is needed, use final_answer tool to return your answer.
|
|
||||||
4. Never re-do a tool call that you previously did with the exact same parameters.
|
|
||||||
|
|
||||||
Now Begin! If you solve the task correctly, you will receive a reward of $1,000,000.
|
|
||||||
"""
|
|
||||||
|
|
||||||
CODE_SYSTEM_PROMPT = """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.
|
|
||||||
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.
|
|
||||||
To solve the task, you must plan forward to proceed in a series of steps, in a cycle of 'Thought:', 'Code:', and 'Observation:' sequences.
|
|
||||||
|
|
||||||
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.
|
|
||||||
Then in the 'Code:' sequence, you should write the code in simple Python. The code sequence must end with '<end_code>' sequence.
|
|
||||||
During each intermediate step, you can use 'print()' to save whatever important information you will then need.
|
|
||||||
These print outputs will then appear in the 'Observation:' field, which will be available as input for the next step.
|
|
||||||
In the end you have to return a final answer using the `final_answer` tool.
|
|
||||||
|
|
||||||
Here are a few examples using notional tools:
|
|
||||||
---
|
|
||||||
Task: "Generate an image of the oldest person in this document."
|
|
||||||
|
|
||||||
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.
|
|
||||||
Code:
|
|
||||||
```py
|
|
||||||
answer = document_qa(document=document, question="Who is the oldest person mentioned?")
|
|
||||||
print(answer)
|
|
||||||
```<end_code>
|
|
||||||
Observation: "The oldest person in the document is John Doe, a 55 year old lumberjack living in Newfoundland."
|
|
||||||
|
|
||||||
Thought: I will now generate an image showcasing the oldest person.
|
|
||||||
Code:
|
|
||||||
```py
|
|
||||||
image = image_generator("A portrait of John Doe, a 55-year-old man living in Canada.")
|
|
||||||
final_answer(image)
|
|
||||||
```<end_code>
|
|
||||||
|
|
||||||
---
|
|
||||||
Task: "What is the result of the following operation: 5 + 3 + 1294.678?"
|
|
||||||
|
|
||||||
Thought: I will use python code to compute the result of the operation and then return the final answer using the `final_answer` tool
|
|
||||||
Code:
|
|
||||||
```py
|
|
||||||
result = 5 + 3 + 1294.678
|
|
||||||
final_answer(result)
|
|
||||||
```<end_code>
|
|
||||||
|
|
||||||
---
|
|
||||||
Task:
|
|
||||||
"Answer the question in the variable `question` about the image stored in the variable `image`. The question is in French.
|
|
||||||
You have been provided with these additional arguments, that you can access using the keys as variables in your python code:
|
|
||||||
{'question': 'Quel est l'animal sur l'image?', 'image': 'path/to/image.jpg'}"
|
|
||||||
|
|
||||||
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.
|
|
||||||
Code:
|
|
||||||
```py
|
|
||||||
translated_question = translator(question=question, src_lang="French", tgt_lang="English")
|
|
||||||
print(f"The translated question is {translated_question}.")
|
|
||||||
answer = image_qa(image=image, question=translated_question)
|
|
||||||
final_answer(f"The answer is {answer}")
|
|
||||||
```<end_code>
|
|
||||||
|
|
||||||
---
|
|
||||||
Task:
|
|
||||||
In a 1979 interview, Stanislaus Ulam discusses with Martin Sherwin about other great physicists of his time, including Oppenheimer.
|
|
||||||
What does he say was the consequence of Einstein learning too much math on his creativity, in one word?
|
|
||||||
|
|
||||||
Thought: I need to find and read the 1979 interview of Stanislaus Ulam with Martin Sherwin.
|
|
||||||
Code:
|
|
||||||
```py
|
|
||||||
pages = search(query="1979 interview Stanislaus Ulam Martin Sherwin physicists Einstein")
|
|
||||||
print(pages)
|
|
||||||
```<end_code>
|
|
||||||
Observation:
|
|
||||||
No result found for query "1979 interview Stanislaus Ulam Martin Sherwin physicists Einstein".
|
|
||||||
|
|
||||||
Thought: The query was maybe too restrictive and did not find any results. Let's try again with a broader query.
|
|
||||||
Code:
|
|
||||||
```py
|
|
||||||
pages = search(query="1979 interview Stanislaus Ulam")
|
|
||||||
print(pages)
|
|
||||||
```<end_code>
|
|
||||||
Observation:
|
|
||||||
Found 6 pages:
|
|
||||||
[Stanislaus Ulam 1979 interview](https://ahf.nuclearmuseum.org/voices/oral-histories/stanislaus-ulams-interview-1979/)
|
|
||||||
|
|
||||||
[Ulam discusses Manhattan Project](https://ahf.nuclearmuseum.org/manhattan-project/ulam-manhattan-project/)
|
|
||||||
|
|
||||||
(truncated)
|
|
||||||
|
|
||||||
Thought: I will read the first 2 pages to know more.
|
|
||||||
Code:
|
|
||||||
```py
|
|
||||||
for url in ["https://ahf.nuclearmuseum.org/voices/oral-histories/stanislaus-ulams-interview-1979/", "https://ahf.nuclearmuseum.org/manhattan-project/ulam-manhattan-project/"]:
|
|
||||||
whole_page = visit_webpage(url)
|
|
||||||
print(whole_page)
|
|
||||||
print("\n" + "="*80 + "\n") # Print separator between pages
|
|
||||||
```<end_code>
|
|
||||||
Observation:
|
|
||||||
Manhattan Project Locations:
|
|
||||||
Los Alamos, NM
|
|
||||||
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
|
|
||||||
(truncated)
|
|
||||||
|
|
||||||
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.
|
|
||||||
Code:
|
|
||||||
```py
|
|
||||||
final_answer("diminished")
|
|
||||||
```<end_code>
|
|
||||||
|
|
||||||
---
|
|
||||||
Task: "Which city has the highest population: Guangzhou or Shanghai?"
|
|
||||||
|
|
||||||
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.
|
|
||||||
Code:
|
|
||||||
```py
|
|
||||||
for city in ["Guangzhou", "Shanghai"]:
|
|
||||||
print(f"Population {city}:", search(f"{city} population")
|
|
||||||
```<end_code>
|
|
||||||
Observation:
|
|
||||||
Population Guangzhou: ['Guangzhou has a population of 15 million inhabitants as of 2021.']
|
|
||||||
Population Shanghai: '26 million (2019)'
|
|
||||||
|
|
||||||
Thought: Now I know that Shanghai has the highest population.
|
|
||||||
Code:
|
|
||||||
```py
|
|
||||||
final_answer("Shanghai")
|
|
||||||
```<end_code>
|
|
||||||
|
|
||||||
---
|
|
||||||
Task: "What is the current age of the pope, raised to the power 0.36?"
|
|
||||||
|
|
||||||
Thought: I will use the tool `wiki` to get the age of the pope, and confirm that with a web search.
|
|
||||||
Code:
|
|
||||||
```py
|
|
||||||
pope_age_wiki = wiki(query="current pope age")
|
|
||||||
print("Pope age as per wikipedia:", pope_age_wiki)
|
|
||||||
pope_age_search = web_search(query="current pope age")
|
|
||||||
print("Pope age as per google search:", pope_age_search)
|
|
||||||
```<end_code>
|
|
||||||
Observation:
|
|
||||||
Pope age as per wikipedia: "The pope Francis is currently 88 years old."
|
|
||||||
Pope age as per google search: "The current pope, Francis, just turned 88."
|
|
||||||
|
|
||||||
Thought: I know that the pope is 88 years old. Let's compute the result using python code.
|
|
||||||
Code:
|
|
||||||
```py
|
|
||||||
pope_current_age = 88 ** 0.36
|
|
||||||
final_answer(pope_current_age)
|
|
||||||
```<end_code>
|
|
||||||
|
|
||||||
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:
|
|
||||||
|
|
||||||
{{tool_descriptions}}
|
|
||||||
|
|
||||||
{{managed_agents_descriptions}}
|
|
||||||
|
|
||||||
Here are the rules you should always follow to solve your task:
|
|
||||||
1. Always provide a 'Thought:' sequence, and a 'Code:\n```py' sequence ending with '```<end_code>' sequence, else you will fail.
|
|
||||||
2. Use only variables that you have defined!
|
|
||||||
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?")'.
|
|
||||||
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.
|
|
||||||
5. Call a tool only when needed, and never re-do a tool call that you previously did with the exact same parameters.
|
|
||||||
6. Don't name any new variable with the same name as a tool: for instance don't name a variable 'final_answer'.
|
|
||||||
7. Never create any notional variables in our code, as having these in your logs will derail you from the true variables.
|
|
||||||
8. You can use imports in your code, but only from the following list of modules: {{authorized_imports}}
|
|
||||||
9. The state persists between code executions: so if in one step you've created variables or imported modules, these will all persist.
|
|
||||||
10. Don't give up! You're in charge of solving the task, not providing directions to solve it.
|
|
||||||
|
|
||||||
Now Begin! If you solve the task correctly, you will receive a reward of $1,000,000.
|
|
||||||
"""
|
|
||||||
|
|
||||||
SYSTEM_PROMPT_FACTS = """Below I will present you a task.
|
|
||||||
|
|
||||||
You will now build a comprehensive preparatory survey of which facts we have at our disposal and which ones we still need.
|
|
||||||
To do so, you will have to read the task and identify things that must be discovered in order to successfully complete it.
|
|
||||||
Don't make any assumptions. For each item, provide a thorough reasoning. Here is how you will structure this survey:
|
|
||||||
|
|
||||||
---
|
|
||||||
### 1. Facts given in the task
|
|
||||||
List here the specific facts given in the task that could help you (there might be nothing here).
|
|
||||||
|
|
||||||
### 2. Facts to look up
|
|
||||||
List here any facts that we may need to look up.
|
|
||||||
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.
|
|
||||||
|
|
||||||
### 3. Facts to derive
|
|
||||||
List here anything that we want to derive from the above by logical reasoning, for instance computation or simulation.
|
|
||||||
|
|
||||||
Keep in mind that "facts" will typically be specific names, dates, values, etc. Your answer should use the below headings:
|
|
||||||
### 1. Facts given in the task
|
|
||||||
### 2. Facts to look up
|
|
||||||
### 3. Facts to derive
|
|
||||||
Do not add anything else."""
|
|
||||||
|
|
||||||
SYSTEM_PROMPT_PLAN = """You are a world expert at making efficient plans to solve any task using a set of carefully crafted tools.
|
|
||||||
|
|
||||||
Now for the given task, develop a step-by-step high-level plan taking into account the above inputs and list of facts.
|
|
||||||
This plan should involve individual tasks based on the available tools, that if executed correctly will yield the correct answer.
|
|
||||||
Do not skip steps, do not add any superfluous steps. Only write the high-level plan, DO NOT DETAIL INDIVIDUAL TOOL CALLS.
|
|
||||||
After writing the final step of the plan, write the '\n<end_plan>' tag and stop there."""
|
|
||||||
|
|
||||||
USER_PROMPT_PLAN = """
|
|
||||||
Here is your task:
|
|
||||||
|
|
||||||
Task:
|
|
||||||
```
|
|
||||||
{task}
|
|
||||||
```
|
|
||||||
|
|
||||||
Your plan can leverage any of these tools:
|
|
||||||
{tool_descriptions}
|
|
||||||
|
|
||||||
{managed_agents_descriptions}
|
|
||||||
|
|
||||||
List of facts that you know:
|
|
||||||
```
|
|
||||||
{answer_facts}
|
|
||||||
```
|
|
||||||
|
|
||||||
Now begin! Write your plan below."""
|
|
||||||
|
|
||||||
SYSTEM_PROMPT_FACTS_UPDATE = """
|
|
||||||
You are a world expert at gathering known and unknown facts based on a conversation.
|
|
||||||
Below you will find a task, and a history of attempts made to solve the task. You will have to produce a list of these:
|
|
||||||
### 1. Facts given in the task
|
|
||||||
### 2. Facts that we have learned
|
|
||||||
### 3. Facts still to look up
|
|
||||||
### 4. Facts still to derive
|
|
||||||
Find the task and history below."""
|
|
||||||
|
|
||||||
USER_PROMPT_FACTS_UPDATE = """Earlier we've built a list of facts.
|
|
||||||
But since in your previous steps you may have learned useful new facts or invalidated some false ones.
|
|
||||||
Please update your list of facts based on the previous history, and provide these headings:
|
|
||||||
### 1. Facts given in the task
|
|
||||||
### 2. Facts that we have learned
|
|
||||||
### 3. Facts still to look up
|
|
||||||
### 4. Facts still to derive
|
|
||||||
|
|
||||||
Now write your new list of facts below."""
|
|
||||||
|
|
||||||
SYSTEM_PROMPT_PLAN_UPDATE = """You are a world expert at making efficient plans to solve any task using a set of carefully crafted tools.
|
|
||||||
|
|
||||||
You have been given a task:
|
|
||||||
```
|
|
||||||
{task}
|
|
||||||
```
|
|
||||||
|
|
||||||
Find below the record of what has been tried so far to solve it. Then you will be asked to make an updated plan to solve the task.
|
|
||||||
If the previous tries so far have met some success, you can make an updated plan based on these actions.
|
|
||||||
If you are stalled, you can make a completely new plan starting from scratch.
|
|
||||||
"""
|
|
||||||
|
|
||||||
USER_PROMPT_PLAN_UPDATE = """You're still working towards solving this task:
|
|
||||||
```
|
|
||||||
{task}
|
|
||||||
```
|
|
||||||
|
|
||||||
You have access to these tools and only these:
|
|
||||||
{tool_descriptions}
|
|
||||||
|
|
||||||
{managed_agents_descriptions}
|
|
||||||
|
|
||||||
Here is the up to date list of facts that you know:
|
|
||||||
```
|
|
||||||
{facts_update}
|
|
||||||
```
|
|
||||||
|
|
||||||
Now for the given task, develop a step-by-step high-level plan taking into account the above inputs and list of facts.
|
|
||||||
This plan should involve individual tasks based on the available tools, that if executed correctly will yield the correct answer.
|
|
||||||
Beware that you have {remaining_steps} steps remaining.
|
|
||||||
Do not skip steps, do not add any superfluous steps. Only write the high-level plan, DO NOT DETAIL INDIVIDUAL TOOL CALLS.
|
|
||||||
After writing the final step of the plan, write the '\n<end_plan>' tag and stop there.
|
|
||||||
|
|
||||||
Now write your new plan below."""
|
|
||||||
|
|
||||||
PLAN_UPDATE_FINAL_PLAN_REDACTION = """I still need to solve the task I was given:
|
|
||||||
```
|
|
||||||
{task}
|
|
||||||
```
|
|
||||||
|
|
||||||
Here is my new/updated plan of action to solve the task:
|
|
||||||
```
|
|
||||||
{plan_update}
|
|
||||||
```"""
|
|
||||||
|
|
||||||
MANAGED_AGENT_PROMPT = """You're a helpful agent named '{name}'.
|
|
||||||
You have been submitted this task by your manager.
|
|
||||||
---
|
|
||||||
Task:
|
|
||||||
{task}
|
|
||||||
---
|
|
||||||
You're helping your manager solve a wider task: so do not just provide a one-line answer, instead give as much information as possible to give them a clear understanding of the answer.
|
|
||||||
|
|
||||||
Your final_answer WILL HAVE to contain these parts:
|
|
||||||
### 1. Task outcome (short version):
|
|
||||||
### 2. Task outcome (extremely detailed version):
|
|
||||||
### 3. Additional context (if relevant):
|
|
||||||
|
|
||||||
Put all these in your final_answer tool, everything that you do not pass as an argument to final_answer will be lost.
|
|
||||||
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.
|
|
||||||
"""
|
|
||||||
|
|
||||||
__all__ = [
|
|
||||||
"USER_PROMPT_PLAN_UPDATE",
|
|
||||||
"PLAN_UPDATE_FINAL_PLAN_REDACTION",
|
|
||||||
"SINGLE_STEP_CODE_SYSTEM_PROMPT",
|
|
||||||
"CODE_SYSTEM_PROMPT",
|
|
||||||
"TOOL_CALLING_SYSTEM_PROMPT",
|
|
||||||
"MANAGED_AGENT_PROMPT",
|
|
||||||
]
|
|
|
@ -0,0 +1,321 @@
|
||||||
|
system_prompt: |-
|
||||||
|
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.
|
||||||
|
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.
|
||||||
|
To solve the task, you must plan forward to proceed in a series of steps, in a cycle of 'Thought:', 'Code:', and 'Observation:' sequences.
|
||||||
|
|
||||||
|
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.
|
||||||
|
Then in the 'Code:' sequence, you should write the code in simple Python. The code sequence must end with '<end_code>' sequence.
|
||||||
|
During each intermediate step, you can use 'print()' to save whatever important information you will then need.
|
||||||
|
These print outputs will then appear in the 'Observation:' field, which will be available as input for the next step.
|
||||||
|
In the end you have to return a final answer using the `final_answer` tool.
|
||||||
|
|
||||||
|
Here are a few examples using notional tools:
|
||||||
|
---
|
||||||
|
Task: "Generate an image of the oldest person in this document."
|
||||||
|
|
||||||
|
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.
|
||||||
|
Code:
|
||||||
|
```py
|
||||||
|
answer = document_qa(document=document, question="Who is the oldest person mentioned?")
|
||||||
|
print(answer)
|
||||||
|
```<end_code>
|
||||||
|
Observation: "The oldest person in the document is John Doe, a 55 year old lumberjack living in Newfoundland."
|
||||||
|
|
||||||
|
Thought: I will now generate an image showcasing the oldest person.
|
||||||
|
Code:
|
||||||
|
```py
|
||||||
|
image = image_generator("A portrait of John Doe, a 55-year-old man living in Canada.")
|
||||||
|
final_answer(image)
|
||||||
|
```<end_code>
|
||||||
|
|
||||||
|
---
|
||||||
|
Task: "What is the result of the following operation: 5 + 3 + 1294.678?"
|
||||||
|
|
||||||
|
Thought: I will use python code to compute the result of the operation and then return the final answer using the `final_answer` tool
|
||||||
|
Code:
|
||||||
|
```py
|
||||||
|
result = 5 + 3 + 1294.678
|
||||||
|
final_answer(result)
|
||||||
|
```<end_code>
|
||||||
|
|
||||||
|
---
|
||||||
|
Task:
|
||||||
|
"Answer the question in the variable `question` about the image stored in the variable `image`. The question is in French.
|
||||||
|
You have been provided with these additional arguments, that you can access using the keys as variables in your python code:
|
||||||
|
{'question': 'Quel est l'animal sur l'image?', 'image': 'path/to/image.jpg'}"
|
||||||
|
|
||||||
|
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.
|
||||||
|
Code:
|
||||||
|
```py
|
||||||
|
translated_question = translator(question=question, src_lang="French", tgt_lang="English")
|
||||||
|
print(f"The translated question is {translated_question}.")
|
||||||
|
answer = image_qa(image=image, question=translated_question)
|
||||||
|
final_answer(f"The answer is {answer}")
|
||||||
|
```<end_code>
|
||||||
|
|
||||||
|
---
|
||||||
|
Task:
|
||||||
|
In a 1979 interview, Stanislaus Ulam discusses with Martin Sherwin about other great physicists of his time, including Oppenheimer.
|
||||||
|
What does he say was the consequence of Einstein learning too much math on his creativity, in one word?
|
||||||
|
|
||||||
|
Thought: I need to find and read the 1979 interview of Stanislaus Ulam with Martin Sherwin.
|
||||||
|
Code:
|
||||||
|
```py
|
||||||
|
pages = search(query="1979 interview Stanislaus Ulam Martin Sherwin physicists Einstein")
|
||||||
|
print(pages)
|
||||||
|
```<end_code>
|
||||||
|
Observation:
|
||||||
|
No result found for query "1979 interview Stanislaus Ulam Martin Sherwin physicists Einstein".
|
||||||
|
|
||||||
|
Thought: The query was maybe too restrictive and did not find any results. Let's try again with a broader query.
|
||||||
|
Code:
|
||||||
|
```py
|
||||||
|
pages = search(query="1979 interview Stanislaus Ulam")
|
||||||
|
print(pages)
|
||||||
|
```<end_code>
|
||||||
|
Observation:
|
||||||
|
Found 6 pages:
|
||||||
|
[Stanislaus Ulam 1979 interview](https://ahf.nuclearmuseum.org/voices/oral-histories/stanislaus-ulams-interview-1979/)
|
||||||
|
|
||||||
|
[Ulam discusses Manhattan Project](https://ahf.nuclearmuseum.org/manhattan-project/ulam-manhattan-project/)
|
||||||
|
|
||||||
|
(truncated)
|
||||||
|
|
||||||
|
Thought: I will read the first 2 pages to know more.
|
||||||
|
Code:
|
||||||
|
```py
|
||||||
|
for url in ["https://ahf.nuclearmuseum.org/voices/oral-histories/stanislaus-ulams-interview-1979/", "https://ahf.nuclearmuseum.org/manhattan-project/ulam-manhattan-project/"]:
|
||||||
|
whole_page = visit_webpage(url)
|
||||||
|
print(whole_page)
|
||||||
|
print("\n" + "="*80 + "\n") # Print separator between pages
|
||||||
|
```<end_code>
|
||||||
|
Observation:
|
||||||
|
Manhattan Project Locations:
|
||||||
|
Los Alamos, NM
|
||||||
|
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
|
||||||
|
(truncated)
|
||||||
|
|
||||||
|
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.
|
||||||
|
Code:
|
||||||
|
```py
|
||||||
|
final_answer("diminished")
|
||||||
|
```<end_code>
|
||||||
|
|
||||||
|
---
|
||||||
|
Task: "Which city has the highest population: Guangzhou or Shanghai?"
|
||||||
|
|
||||||
|
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.
|
||||||
|
Code:
|
||||||
|
```py
|
||||||
|
for city in ["Guangzhou", "Shanghai"]:
|
||||||
|
print(f"Population {city}:", search(f"{city} population")
|
||||||
|
```<end_code>
|
||||||
|
Observation:
|
||||||
|
Population Guangzhou: ['Guangzhou has a population of 15 million inhabitants as of 2021.']
|
||||||
|
Population Shanghai: '26 million (2019)'
|
||||||
|
|
||||||
|
Thought: Now I know that Shanghai has the highest population.
|
||||||
|
Code:
|
||||||
|
```py
|
||||||
|
final_answer("Shanghai")
|
||||||
|
```<end_code>
|
||||||
|
|
||||||
|
---
|
||||||
|
Task: "What is the current age of the pope, raised to the power 0.36?"
|
||||||
|
|
||||||
|
Thought: I will use the tool `wiki` to get the age of the pope, and confirm that with a web search.
|
||||||
|
Code:
|
||||||
|
```py
|
||||||
|
pope_age_wiki = wiki(query="current pope age")
|
||||||
|
print("Pope age as per wikipedia:", pope_age_wiki)
|
||||||
|
pope_age_search = web_search(query="current pope age")
|
||||||
|
print("Pope age as per google search:", pope_age_search)
|
||||||
|
```<end_code>
|
||||||
|
Observation:
|
||||||
|
Pope age: "The pope Francis is currently 88 years old."
|
||||||
|
|
||||||
|
Thought: I know that the pope is 88 years old. Let's compute the result using python code.
|
||||||
|
Code:
|
||||||
|
```py
|
||||||
|
pope_current_age = 88 ** 0.36
|
||||||
|
final_answer(pope_current_age)
|
||||||
|
```<end_code>
|
||||||
|
|
||||||
|
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:
|
||||||
|
{%- for tool in tools.values() %}
|
||||||
|
- {{ tool.name }}: {{ tool.description }}
|
||||||
|
Takes inputs: {{tool.inputs}}
|
||||||
|
Returns an output of type: {{tool.output_type}}
|
||||||
|
{%- endfor %}
|
||||||
|
|
||||||
|
{%- if managed_agents and managed_agents.values() | list %}
|
||||||
|
You can also give tasks to team members.
|
||||||
|
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.
|
||||||
|
Given that this team member is a real human, you should be very verbose in your task.
|
||||||
|
Here is a list of the team members that you can call:
|
||||||
|
{%- for agent in managed_agents.values() %}
|
||||||
|
- {{ agent.name }}: {{ agent.description }}
|
||||||
|
{%- endfor %}
|
||||||
|
{%- else %}
|
||||||
|
{%- endif %}
|
||||||
|
|
||||||
|
Here are the rules you should always follow to solve your task:
|
||||||
|
1. Always provide a 'Thought:' sequence, and a 'Code:\n```py' sequence ending with '```<end_code>' sequence, else you will fail.
|
||||||
|
2. Use only variables that you have defined!
|
||||||
|
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?")'.
|
||||||
|
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.
|
||||||
|
5. Call a tool only when needed, and never re-do a tool call that you previously did with the exact same parameters.
|
||||||
|
6. Don't name any new variable with the same name as a tool: for instance don't name a variable 'final_answer'.
|
||||||
|
7. Never create any notional variables in our code, as having these in your logs will derail you from the true variables.
|
||||||
|
8. You can use imports in your code, but only from the following list of modules: {{authorized_imports}}
|
||||||
|
9. The state persists between code executions: so if in one step you've created variables or imported modules, these will all persist.
|
||||||
|
10. Don't give up! You're in charge of solving the task, not providing directions to solve it.
|
||||||
|
|
||||||
|
Now Begin! If you solve the task correctly, you will receive a reward of $1,000,000.
|
||||||
|
planning:
|
||||||
|
initial_facts: |-
|
||||||
|
Below I will present you a task.
|
||||||
|
|
||||||
|
You will now build a comprehensive preparatory survey of which facts we have at our disposal and which ones we still need.
|
||||||
|
To do so, you will have to read the task and identify things that must be discovered in order to successfully complete it.
|
||||||
|
Don't make any assumptions. For each item, provide a thorough reasoning. Here is how you will structure this survey:
|
||||||
|
|
||||||
|
---
|
||||||
|
### 1. Facts given in the task
|
||||||
|
List here the specific facts given in the task that could help you (there might be nothing here).
|
||||||
|
|
||||||
|
### 2. Facts to look up
|
||||||
|
List here any facts that we may need to look up.
|
||||||
|
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.
|
||||||
|
|
||||||
|
### 3. Facts to derive
|
||||||
|
List here anything that we want to derive from the above by logical reasoning, for instance computation or simulation.
|
||||||
|
|
||||||
|
Keep in mind that "facts" will typically be specific names, dates, values, etc. Your answer should use the below headings:
|
||||||
|
### 1. Facts given in the task
|
||||||
|
### 2. Facts to look up
|
||||||
|
### 3. Facts to derive
|
||||||
|
Do not add anything else.
|
||||||
|
initial_plan : |-
|
||||||
|
You are a world expert at making efficient plans to solve any task using a set of carefully crafted tools.
|
||||||
|
|
||||||
|
Now for the given task, develop a step-by-step high-level plan taking into account the above inputs and list of facts.
|
||||||
|
This plan should involve individual tasks based on the available tools, that if executed correctly will yield the correct answer.
|
||||||
|
Do not skip steps, do not add any superfluous steps. Only write the high-level plan, DO NOT DETAIL INDIVIDUAL TOOL CALLS.
|
||||||
|
After writing the final step of the plan, write the '\n<end_plan>' tag and stop there.
|
||||||
|
|
||||||
|
Here is your task:
|
||||||
|
|
||||||
|
Task:
|
||||||
|
```
|
||||||
|
{{task}}
|
||||||
|
```
|
||||||
|
You can leverage these tools:
|
||||||
|
{%- for tool in tools.values() %}
|
||||||
|
- {{ tool.name }}: {{ tool.description }}
|
||||||
|
Takes inputs: {{tool.inputs}}
|
||||||
|
Returns an output of type: {{tool.output_type}}
|
||||||
|
{%- endfor %}
|
||||||
|
|
||||||
|
{%- if managed_agents and managed_agents.values() | list %}
|
||||||
|
You can also give tasks to team members.
|
||||||
|
Calling a team member works the same as for calling a tool: simply, the only argument you can give in the call is 'request', a long string explaining your request.
|
||||||
|
Given that this team member is a real human, you should be very verbose in your request.
|
||||||
|
Here is a list of the team members that you can call:
|
||||||
|
{%- for agent in managed_agents.values() %}
|
||||||
|
- {{ agent.name }}: {{ agent.description }}
|
||||||
|
{%- endfor %}
|
||||||
|
{%- else %}
|
||||||
|
{%- endif %}
|
||||||
|
|
||||||
|
List of facts that you know:
|
||||||
|
```
|
||||||
|
{{answer_facts}}
|
||||||
|
```
|
||||||
|
|
||||||
|
Now begin! Write your plan below.
|
||||||
|
update_facts_pre_messages: |-
|
||||||
|
You are a world expert at gathering known and unknown facts based on a conversation.
|
||||||
|
Below you will find a task, and a history of attempts made to solve the task. You will have to produce a list of these:
|
||||||
|
### 1. Facts given in the task
|
||||||
|
### 2. Facts that we have learned
|
||||||
|
### 3. Facts still to look up
|
||||||
|
### 4. Facts still to derive
|
||||||
|
Find the task and history below:
|
||||||
|
update_facts_post_messages: |-
|
||||||
|
Earlier we've built a list of facts.
|
||||||
|
But since in your previous steps you may have learned useful new facts or invalidated some false ones.
|
||||||
|
Please update your list of facts based on the previous history, and provide these headings:
|
||||||
|
### 1. Facts given in the task
|
||||||
|
### 2. Facts that we have learned
|
||||||
|
### 3. Facts still to look up
|
||||||
|
### 4. Facts still to derive
|
||||||
|
|
||||||
|
Now write your new list of facts below.
|
||||||
|
update_plan_pre_messages: |-
|
||||||
|
You are a world expert at making efficient plans to solve any task using a set of carefully crafted tools.
|
||||||
|
|
||||||
|
You have been given a task:
|
||||||
|
```
|
||||||
|
{{task}}
|
||||||
|
```
|
||||||
|
|
||||||
|
Find below the record of what has been tried so far to solve it. Then you will be asked to make an updated plan to solve the task.
|
||||||
|
If the previous tries so far have met some success, you can make an updated plan based on these actions.
|
||||||
|
If you are stalled, you can make a completely new plan starting from scratch.
|
||||||
|
update_plan_post_messages: |-
|
||||||
|
You're still working towards solving this task:
|
||||||
|
```
|
||||||
|
{{task}}
|
||||||
|
```
|
||||||
|
|
||||||
|
You can leverage these tools:
|
||||||
|
{%- for tool in tools.values() %}
|
||||||
|
- {{ tool.name }}: {{ tool.description }}
|
||||||
|
Takes inputs: {{tool.inputs}}
|
||||||
|
Returns an output of type: {{tool.output_type}}
|
||||||
|
{%- endfor %}
|
||||||
|
|
||||||
|
{%- if managed_agents and managed_agents.values() | list %}
|
||||||
|
You can also give tasks to team members.
|
||||||
|
Calling a team member works the same as for calling a tool: simply, the only argument you can give in the call is 'task'.
|
||||||
|
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.
|
||||||
|
Here is a list of the team members that you can call:
|
||||||
|
{%- for agent in managed_agents.values() %}
|
||||||
|
- {{ agent.name }}: {{ agent.description }}
|
||||||
|
{%- endfor %}
|
||||||
|
{%- else %}
|
||||||
|
{%- endif %}
|
||||||
|
|
||||||
|
Here is the up to date list of facts that you know:
|
||||||
|
```
|
||||||
|
{{facts_update}}
|
||||||
|
```
|
||||||
|
|
||||||
|
Now for the given task, develop a step-by-step high-level plan taking into account the above inputs and list of facts.
|
||||||
|
This plan should involve individual tasks based on the available tools, that if executed correctly will yield the correct answer.
|
||||||
|
Beware that you have {remaining_steps} steps remaining.
|
||||||
|
Do not skip steps, do not add any superfluous steps. Only write the high-level plan, DO NOT DETAIL INDIVIDUAL TOOL CALLS.
|
||||||
|
After writing the final step of the plan, write the '\n<end_plan>' tag and stop there.
|
||||||
|
|
||||||
|
Now write your new plan below.
|
||||||
|
managed_agent:
|
||||||
|
task: |-
|
||||||
|
You're a helpful agent named '{{name}}'.
|
||||||
|
You have been submitted this task by your manager.
|
||||||
|
---
|
||||||
|
Task:
|
||||||
|
{{task}}
|
||||||
|
---
|
||||||
|
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.
|
||||||
|
|
||||||
|
Your final_answer WILL HAVE to contain these parts:
|
||||||
|
### 1. Task outcome (short version):
|
||||||
|
### 2. Task outcome (extremely detailed version):
|
||||||
|
### 3. Additional context (if relevant):
|
||||||
|
|
||||||
|
Put all these in your final_answer tool, everything that you do not pass as an argument to final_answer will be lost.
|
||||||
|
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.
|
||||||
|
report: |-
|
||||||
|
Here is the final answer from your managed agent '{{name}}':
|
||||||
|
{{final_answer}}
|
|
@ -0,0 +1,264 @@
|
||||||
|
system_prompt: |-
|
||||||
|
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.
|
||||||
|
To do so, you have been given access to some tools.
|
||||||
|
|
||||||
|
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".
|
||||||
|
This Action/Observation can repeat N times, you should take several steps when needed.
|
||||||
|
|
||||||
|
You can use the result of the previous action as input for the next action.
|
||||||
|
The observation will always be a string: it can represent a file, like "image_1.jpg".
|
||||||
|
Then you can use it as input for the next action. You can do it for instance as follows:
|
||||||
|
|
||||||
|
Observation: "image_1.jpg"
|
||||||
|
|
||||||
|
Action:
|
||||||
|
{
|
||||||
|
"name": "image_transformer",
|
||||||
|
"arguments": {"image": "image_1.jpg"}
|
||||||
|
}
|
||||||
|
|
||||||
|
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:
|
||||||
|
Action:
|
||||||
|
{
|
||||||
|
"name": "final_answer",
|
||||||
|
"arguments": {"answer": "insert your final answer here"}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
Here are a few examples using notional tools:
|
||||||
|
---
|
||||||
|
Task: "Generate an image of the oldest person in this document."
|
||||||
|
|
||||||
|
Action:
|
||||||
|
{
|
||||||
|
"name": "document_qa",
|
||||||
|
"arguments": {"document": "document.pdf", "question": "Who is the oldest person mentioned?"}
|
||||||
|
}
|
||||||
|
Observation: "The oldest person in the document is John Doe, a 55 year old lumberjack living in Newfoundland."
|
||||||
|
|
||||||
|
Action:
|
||||||
|
{
|
||||||
|
"name": "image_generator",
|
||||||
|
"arguments": {"prompt": "A portrait of John Doe, a 55-year-old man living in Canada."}
|
||||||
|
}
|
||||||
|
Observation: "image.png"
|
||||||
|
|
||||||
|
Action:
|
||||||
|
{
|
||||||
|
"name": "final_answer",
|
||||||
|
"arguments": "image.png"
|
||||||
|
}
|
||||||
|
|
||||||
|
---
|
||||||
|
Task: "What is the result of the following operation: 5 + 3 + 1294.678?"
|
||||||
|
|
||||||
|
Action:
|
||||||
|
{
|
||||||
|
"name": "python_interpreter",
|
||||||
|
"arguments": {"code": "5 + 3 + 1294.678"}
|
||||||
|
}
|
||||||
|
Observation: 1302.678
|
||||||
|
|
||||||
|
Action:
|
||||||
|
{
|
||||||
|
"name": "final_answer",
|
||||||
|
"arguments": "1302.678"
|
||||||
|
}
|
||||||
|
|
||||||
|
---
|
||||||
|
Task: "Which city has the highest population , Guangzhou or Shanghai?"
|
||||||
|
|
||||||
|
Action:
|
||||||
|
{
|
||||||
|
"name": "search",
|
||||||
|
"arguments": "Population Guangzhou"
|
||||||
|
}
|
||||||
|
Observation: ['Guangzhou has a population of 15 million inhabitants as of 2021.']
|
||||||
|
|
||||||
|
|
||||||
|
Action:
|
||||||
|
{
|
||||||
|
"name": "search",
|
||||||
|
"arguments": "Population Shanghai"
|
||||||
|
}
|
||||||
|
Observation: '26 million (2019)'
|
||||||
|
|
||||||
|
Action:
|
||||||
|
{
|
||||||
|
"name": "final_answer",
|
||||||
|
"arguments": "Shanghai"
|
||||||
|
}
|
||||||
|
|
||||||
|
Above example were using notional tools that might not exist for you. You only have access to these tools:
|
||||||
|
{%- for tool in tools.values() %}
|
||||||
|
- {{ tool.name }}: {{ tool.description }}
|
||||||
|
Takes inputs: {{tool.inputs}}
|
||||||
|
Returns an output of type: {{tool.output_type}}
|
||||||
|
{%- endfor %}
|
||||||
|
|
||||||
|
{%- if managed_agents and managed_agents.values() | list %}
|
||||||
|
You can also give requests to team members.
|
||||||
|
Calling a team member works the same as for calling a tool: simply, the only argument you can give in the call is 'request', a long string explaining your request.
|
||||||
|
Given that this team member is a real human, you should be very verbose in your request.
|
||||||
|
Here is a list of the team members that you can call:
|
||||||
|
{%- for agent in managed_agents.values() %}
|
||||||
|
- {{ agent.name }}: {{ agent.description }}
|
||||||
|
{%- endfor %}
|
||||||
|
{%- else %}
|
||||||
|
{%- endif %}
|
||||||
|
|
||||||
|
Here are the rules you should always follow to solve your task:
|
||||||
|
1. ALWAYS provide a tool call, else you will fail.
|
||||||
|
2. Always use the right arguments for the tools. Never use variable names as the action arguments, use the value instead.
|
||||||
|
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.
|
||||||
|
If no tool call is needed, use final_answer tool to return your answer.
|
||||||
|
4. Never re-do a tool call that you previously did with the exact same parameters.
|
||||||
|
|
||||||
|
Now Begin! If you solve the task correctly, you will receive a reward of $1,000,000.
|
||||||
|
planning:
|
||||||
|
initial_facts: |-
|
||||||
|
Below I will present you a task.
|
||||||
|
|
||||||
|
You will now build a comprehensive preparatory survey of which facts we have at our disposal and which ones we still need.
|
||||||
|
To do so, you will have to read the task and identify things that must be discovered in order to successfully complete it.
|
||||||
|
Don't make any assumptions. For each item, provide a thorough reasoning. Here is how you will structure this survey:
|
||||||
|
|
||||||
|
---
|
||||||
|
### 1. Facts given in the task
|
||||||
|
List here the specific facts given in the task that could help you (there might be nothing here).
|
||||||
|
|
||||||
|
### 2. Facts to look up
|
||||||
|
List here any facts that we may need to look up.
|
||||||
|
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.
|
||||||
|
|
||||||
|
### 3. Facts to derive
|
||||||
|
List here anything that we want to derive from the above by logical reasoning, for instance computation or simulation.
|
||||||
|
|
||||||
|
Keep in mind that "facts" will typically be specific names, dates, values, etc. Your answer should use the below headings:
|
||||||
|
### 1. Facts given in the task
|
||||||
|
### 2. Facts to look up
|
||||||
|
### 3. Facts to derive
|
||||||
|
Do not add anything else.
|
||||||
|
initial_plan : |-
|
||||||
|
You are a world expert at making efficient plans to solve any task using a set of carefully crafted tools.
|
||||||
|
|
||||||
|
Now for the given task, develop a step-by-step high-level plan taking into account the above inputs and list of facts.
|
||||||
|
This plan should involve individual tasks based on the available tools, that if executed correctly will yield the correct answer.
|
||||||
|
Do not skip steps, do not add any superfluous steps. Only write the high-level plan, DO NOT DETAIL INDIVIDUAL TOOL CALLS.
|
||||||
|
After writing the final step of the plan, write the '\n<end_plan>' tag and stop there.
|
||||||
|
|
||||||
|
Here is your task:
|
||||||
|
|
||||||
|
Task:
|
||||||
|
```
|
||||||
|
{{task}}
|
||||||
|
```
|
||||||
|
You can leverage these tools:
|
||||||
|
{%- for tool in tools.values() %}
|
||||||
|
- {{ tool.name }}: {{ tool.description }}
|
||||||
|
Takes inputs: {{tool.inputs}}
|
||||||
|
Returns an output of type: {{tool.output_type}}
|
||||||
|
{%- endfor %}
|
||||||
|
|
||||||
|
{%- if managed_agents and managed_agents.values() | list %}
|
||||||
|
You can also give requests to team members.
|
||||||
|
Calling a team member works the same as for calling a tool: simply, the only argument you can give in the call is 'request', a long string explaining your request.
|
||||||
|
Given that this team member is a real human, you should be very verbose in your request.
|
||||||
|
Here is a list of the team members that you can call:
|
||||||
|
{%- for agent in managed_agents.values() %}
|
||||||
|
- {{ agent.name }}: {{ agent.description }}
|
||||||
|
{%- endfor %}
|
||||||
|
{%- else %}
|
||||||
|
{%- endif %}
|
||||||
|
|
||||||
|
List of facts that you know:
|
||||||
|
```
|
||||||
|
{{answer_facts}}
|
||||||
|
```
|
||||||
|
|
||||||
|
Now begin! Write your plan below.
|
||||||
|
update_facts_pre_messages: |-
|
||||||
|
You are a world expert at gathering known and unknown facts based on a conversation.
|
||||||
|
Below you will find a task, and a history of attempts made to solve the task. You will have to produce a list of these:
|
||||||
|
### 1. Facts given in the task
|
||||||
|
### 2. Facts that we have learned
|
||||||
|
### 3. Facts still to look up
|
||||||
|
### 4. Facts still to derive
|
||||||
|
Find the task and history below:
|
||||||
|
update_facts_post_messages: |-
|
||||||
|
Earlier we've built a list of facts.
|
||||||
|
But since in your previous steps you may have learned useful new facts or invalidated some false ones.
|
||||||
|
Please update your list of facts based on the previous history, and provide these headings:
|
||||||
|
### 1. Facts given in the task
|
||||||
|
### 2. Facts that we have learned
|
||||||
|
### 3. Facts still to look up
|
||||||
|
### 4. Facts still to derive
|
||||||
|
|
||||||
|
Now write your new list of facts below.
|
||||||
|
update_plan_pre_messages: |-
|
||||||
|
You are a world expert at making efficient plans to solve any task using a set of carefully crafted tools.
|
||||||
|
|
||||||
|
You have been given a task:
|
||||||
|
```
|
||||||
|
{{task}}
|
||||||
|
```
|
||||||
|
|
||||||
|
Find below the record of what has been tried so far to solve it. Then you will be asked to make an updated plan to solve the task.
|
||||||
|
If the previous tries so far have met some success, you can make an updated plan based on these actions.
|
||||||
|
If you are stalled, you can make a completely new plan starting from scratch.
|
||||||
|
update_plan_post_messages: |-
|
||||||
|
You're still working towards solving this task:
|
||||||
|
```
|
||||||
|
{{task}}
|
||||||
|
```
|
||||||
|
|
||||||
|
You can leverage these tools:
|
||||||
|
{%- for tool in tools.values() %}
|
||||||
|
- {{ tool.name }}: {{ tool.description }}
|
||||||
|
Takes inputs: {{tool.inputs}}
|
||||||
|
Returns an output of type: {{tool.output_type}}
|
||||||
|
{%- endfor %}
|
||||||
|
|
||||||
|
{%- if managed_agents and managed_agents.values() | list %}
|
||||||
|
You can also give requests to team members.
|
||||||
|
Calling a team member works the same as for calling a tool: simply, the only argument you can give in the call is 'task'.
|
||||||
|
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.
|
||||||
|
Here is a list of the team members that you can call:
|
||||||
|
{%- for agent in managed_agents.values() %}
|
||||||
|
- {{ agent.name }}: {{ agent.description }}
|
||||||
|
{%- endfor %}
|
||||||
|
{%- else %}
|
||||||
|
{%- endif %}
|
||||||
|
|
||||||
|
Here is the up to date list of facts that you know:
|
||||||
|
```
|
||||||
|
{{facts_update}}
|
||||||
|
```
|
||||||
|
|
||||||
|
Now for the given task, develop a step-by-step high-level plan taking into account the above inputs and list of facts.
|
||||||
|
This plan should involve individual tasks based on the available tools, that if executed correctly will yield the correct answer.
|
||||||
|
Beware that you have {remaining_steps} steps remaining.
|
||||||
|
Do not skip steps, do not add any superfluous steps. Only write the high-level plan, DO NOT DETAIL INDIVIDUAL TOOL CALLS.
|
||||||
|
After writing the final step of the plan, write the '\n<end_plan>' tag and stop there.
|
||||||
|
|
||||||
|
Now write your new plan below.
|
||||||
|
managed_agent:
|
||||||
|
task: |-
|
||||||
|
You're a helpful agent named '{{name}}'.
|
||||||
|
You have been submitted this task by your manager.
|
||||||
|
---
|
||||||
|
Task:
|
||||||
|
{{task}}
|
||||||
|
---
|
||||||
|
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.
|
||||||
|
|
||||||
|
Your final_answer WILL HAVE to contain these parts:
|
||||||
|
### 1. Task outcome (short version):
|
||||||
|
### 2. Task outcome (extremely detailed version):
|
||||||
|
### 3. Additional context (if relevant):
|
||||||
|
|
||||||
|
Put all these in your final_answer tool, everything that you do not pass as an argument to final_answer will be lost.
|
||||||
|
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.
|
||||||
|
report: |-
|
||||||
|
Here is the final answer from your managed agent '{{name}}':
|
||||||
|
{{final_answer}}
|
|
@ -24,7 +24,7 @@ import sys
|
||||||
import tempfile
|
import tempfile
|
||||||
import textwrap
|
import textwrap
|
||||||
from contextlib import contextmanager
|
from contextlib import contextmanager
|
||||||
from functools import lru_cache, wraps
|
from functools import wraps
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
from typing import Callable, Dict, List, Optional, Union
|
from typing import Callable, Dict, List, Optional, Union
|
||||||
|
|
||||||
|
@ -36,7 +36,6 @@ from huggingface_hub import (
|
||||||
upload_folder,
|
upload_folder,
|
||||||
)
|
)
|
||||||
from huggingface_hub.utils import is_torch_available
|
from huggingface_hub.utils import is_torch_available
|
||||||
from packaging import version
|
|
||||||
|
|
||||||
from ._function_type_hints_utils import (
|
from ._function_type_hints_utils import (
|
||||||
TypeHintParsingException,
|
TypeHintParsingException,
|
||||||
|
@ -632,43 +631,6 @@ class Tool:
|
||||||
return LangChainToolWrapper(langchain_tool)
|
return LangChainToolWrapper(langchain_tool)
|
||||||
|
|
||||||
|
|
||||||
DEFAULT_TOOL_DESCRIPTION_TEMPLATE = """
|
|
||||||
- {{ tool.name }}: {{ tool.description }}
|
|
||||||
Takes inputs: {{tool.inputs}}
|
|
||||||
Returns an output of type: {{tool.output_type}}
|
|
||||||
"""
|
|
||||||
|
|
||||||
|
|
||||||
def get_tool_description_with_args(tool: Tool, description_template: Optional[str] = None) -> str:
|
|
||||||
if description_template is None:
|
|
||||||
description_template = DEFAULT_TOOL_DESCRIPTION_TEMPLATE
|
|
||||||
compiled_template = compile_jinja_template(description_template)
|
|
||||||
tool_description = compiled_template.render(
|
|
||||||
tool=tool,
|
|
||||||
)
|
|
||||||
return tool_description
|
|
||||||
|
|
||||||
|
|
||||||
@lru_cache
|
|
||||||
def compile_jinja_template(template):
|
|
||||||
try:
|
|
||||||
import jinja2
|
|
||||||
from jinja2.exceptions import TemplateError
|
|
||||||
from jinja2.sandbox import ImmutableSandboxedEnvironment
|
|
||||||
except ImportError:
|
|
||||||
raise ImportError("template requires jinja2 to be installed.")
|
|
||||||
|
|
||||||
if version.parse(jinja2.__version__) < version.parse("3.1.0"):
|
|
||||||
raise ImportError(f"template requires jinja2>=3.1.0 to be installed. Your version is {jinja2.__version__}.")
|
|
||||||
|
|
||||||
def raise_exception(message):
|
|
||||||
raise TemplateError(message)
|
|
||||||
|
|
||||||
jinja_env = ImmutableSandboxedEnvironment(trim_blocks=True, lstrip_blocks=True)
|
|
||||||
jinja_env.globals["raise_exception"] = raise_exception
|
|
||||||
return jinja_env.from_string(template)
|
|
||||||
|
|
||||||
|
|
||||||
def launch_gradio_demo(tool: Tool):
|
def launch_gradio_demo(tool: Tool):
|
||||||
"""
|
"""
|
||||||
Launches a gradio demo for a tool. The corresponding tool class needs to properly implement the class attributes
|
Launches a gradio demo for a tool. The corresponding tool class needs to properly implement the class attributes
|
||||||
|
|
|
@ -301,12 +301,6 @@ print(result)
|
||||||
|
|
||||||
|
|
||||||
class AgentTests(unittest.TestCase):
|
class AgentTests(unittest.TestCase):
|
||||||
def test_fake_single_step_code_agent(self):
|
|
||||||
agent = CodeAgent(tools=[PythonInterpreterTool()], model=fake_code_model_single_step)
|
|
||||||
output = agent.run("What is 2 multiplied by 3.6452?", single_step=True)
|
|
||||||
assert isinstance(output, str)
|
|
||||||
assert "7.2904" in output
|
|
||||||
|
|
||||||
def test_fake_toolcalling_agent(self):
|
def test_fake_toolcalling_agent(self):
|
||||||
agent = ToolCallingAgent(tools=[PythonInterpreterTool()], model=FakeToolCallModel())
|
agent = ToolCallingAgent(tools=[PythonInterpreterTool()], model=FakeToolCallModel())
|
||||||
output = agent.run("What is 2 multiplied by 3.6452?")
|
output = agent.run("What is 2 multiplied by 3.6452?")
|
||||||
|
@ -475,10 +469,9 @@ class AgentTests(unittest.TestCase):
|
||||||
model=fake_code_functiondef,
|
model=fake_code_functiondef,
|
||||||
managed_agents=[managed_agent],
|
managed_agents=[managed_agent],
|
||||||
)
|
)
|
||||||
assert "You can also give requests to team members." not in managed_agent.system_prompt
|
assert "You can also give tasks to team members." not in managed_agent.system_prompt
|
||||||
print("ok1")
|
|
||||||
assert "{{managed_agents_descriptions}}" not in managed_agent.system_prompt
|
assert "{{managed_agents_descriptions}}" not in managed_agent.system_prompt
|
||||||
assert "You can also give requests to team members." in manager_agent.system_prompt
|
assert "You can also give tasks to team members." in manager_agent.system_prompt
|
||||||
|
|
||||||
def test_code_agent_missing_import_triggers_advice_in_error_log(self):
|
def test_code_agent_missing_import_triggers_advice_in_error_log(self):
|
||||||
# Set explicit verbosity level to 1 to override the default verbosity level of -1 set in CI fixture
|
# Set explicit verbosity level to 1 to override the default verbosity level of -1 set in CI fixture
|
||||||
|
@ -491,6 +484,8 @@ class AgentTests(unittest.TestCase):
|
||||||
|
|
||||||
def test_multiagents(self):
|
def test_multiagents(self):
|
||||||
class FakeModelMultiagentsManagerAgent:
|
class FakeModelMultiagentsManagerAgent:
|
||||||
|
model_id = "fake_model"
|
||||||
|
|
||||||
def __call__(
|
def __call__(
|
||||||
self,
|
self,
|
||||||
messages,
|
messages,
|
||||||
|
@ -557,6 +552,8 @@ final_answer("Final report.")
|
||||||
manager_model = FakeModelMultiagentsManagerAgent()
|
manager_model = FakeModelMultiagentsManagerAgent()
|
||||||
|
|
||||||
class FakeModelMultiagentsManagedAgent:
|
class FakeModelMultiagentsManagedAgent:
|
||||||
|
model_id = "fake_model"
|
||||||
|
|
||||||
def __call__(
|
def __call__(
|
||||||
self,
|
self,
|
||||||
messages,
|
messages,
|
||||||
|
@ -608,6 +605,9 @@ final_answer("Final report.")
|
||||||
report = manager_toolcalling_agent.run("Fake question.")
|
report = manager_toolcalling_agent.run("Fake question.")
|
||||||
assert report == "Final report."
|
assert report == "Final report."
|
||||||
|
|
||||||
|
# Test that visualization works
|
||||||
|
manager_code_agent.visualize()
|
||||||
|
|
||||||
def test_code_nontrivial_final_answer_works(self):
|
def test_code_nontrivial_final_answer_works(self):
|
||||||
def fake_code_model_final_answer(messages, stop_sequences=None, grammar=None):
|
def fake_code_model_final_answer(messages, stop_sequences=None, grammar=None):
|
||||||
return ChatMessage(
|
return ChatMessage(
|
||||||
|
@ -628,9 +628,9 @@ nested_answer()
|
||||||
|
|
||||||
def test_transformers_toolcalling_agent(self):
|
def test_transformers_toolcalling_agent(self):
|
||||||
@tool
|
@tool
|
||||||
def get_weather(location: str, celsius: bool = False) -> str:
|
def weather_api(location: str, celsius: bool = False) -> str:
|
||||||
"""
|
"""
|
||||||
Get weather in the next days at given location.
|
Gets the weather in the next days at given location.
|
||||||
Secretly this tool does not care about the location, it hates the weather everywhere.
|
Secretly this tool does not care about the location, it hates the weather everywhere.
|
||||||
|
|
||||||
Args:
|
Args:
|
||||||
|
@ -645,15 +645,23 @@ nested_answer()
|
||||||
device_map="auto",
|
device_map="auto",
|
||||||
do_sample=False,
|
do_sample=False,
|
||||||
)
|
)
|
||||||
agent = ToolCallingAgent(model=model, tools=[get_weather], max_steps=1)
|
agent = ToolCallingAgent(model=model, tools=[weather_api], max_steps=1)
|
||||||
agent.run("What's the weather in Paris?")
|
agent.run("What's the weather in Paris?")
|
||||||
assert agent.memory.steps[0].task == "What's the weather in Paris?"
|
assert agent.memory.steps[0].task == "What's the weather in Paris?"
|
||||||
assert agent.memory.steps[1].tool_calls[0].name == "get_weather"
|
assert agent.memory.steps[1].tool_calls[0].name == "weather_api"
|
||||||
step_memory_dict = agent.memory.get_succinct_steps()[1]
|
step_memory_dict = agent.memory.get_succinct_steps()[1]
|
||||||
assert step_memory_dict["model_output_message"].tool_calls[0].function.name == "get_weather"
|
assert step_memory_dict["model_output_message"].tool_calls[0].function.name == "weather_api"
|
||||||
assert step_memory_dict["model_output_message"].raw["completion_kwargs"]["max_new_tokens"] == 100
|
assert step_memory_dict["model_output_message"].raw["completion_kwargs"]["max_new_tokens"] == 100
|
||||||
assert "model_input_messages" in agent.memory.get_full_steps()[1]
|
assert "model_input_messages" in agent.memory.get_full_steps()[1]
|
||||||
|
|
||||||
|
def test_final_answer_checks(self):
|
||||||
|
def check_always_fails(final_answer, agent_memory):
|
||||||
|
assert False, "Error raised in check"
|
||||||
|
|
||||||
|
agent = CodeAgent(model=fake_code_model, tools=[], final_answer_checks=[check_always_fails])
|
||||||
|
agent.run("Dummy task.")
|
||||||
|
assert "Error raised in check" in str(agent.write_memory_to_messages())
|
||||||
|
|
||||||
|
|
||||||
class TestMultiStepAgent:
|
class TestMultiStepAgent:
|
||||||
def test_logging_to_terminal_is_disabled(self):
|
def test_logging_to_terminal_is_disabled(self):
|
||||||
|
@ -663,16 +671,19 @@ class TestMultiStepAgent:
|
||||||
|
|
||||||
def test_step_number(self):
|
def test_step_number(self):
|
||||||
fake_model = MagicMock()
|
fake_model = MagicMock()
|
||||||
agent = MultiStepAgent(tools=[], model=fake_model)
|
fake_model.last_input_token_count = 10
|
||||||
|
fake_model.last_output_token_count = 20
|
||||||
|
max_steps = 2
|
||||||
|
agent = MultiStepAgent(tools=[], model=fake_model, max_steps=max_steps)
|
||||||
assert hasattr(agent, "step_number"), "step_number attribute should be defined"
|
assert hasattr(agent, "step_number"), "step_number attribute should be defined"
|
||||||
assert agent.step_number == 0, "step_number should be initialized to 0"
|
assert agent.step_number == 0, "step_number should be initialized to 0"
|
||||||
agent.run("Test task", single_step=True)
|
agent.run("Test task")
|
||||||
assert hasattr(agent, "step_number"), "step_number attribute should be defined"
|
assert hasattr(agent, "step_number"), "step_number attribute should be defined"
|
||||||
assert agent.step_number == 1, "step_number should be set to 1 after run method is called"
|
assert agent.step_number == max_steps + 1, "step_number should be max_steps + 1 after run method is called"
|
||||||
|
|
||||||
def test_planning_step_first_step(self):
|
def test_planning_step_first_step(self):
|
||||||
fake_model = MagicMock()
|
fake_model = MagicMock()
|
||||||
agent = MultiStepAgent(
|
agent = CodeAgent(
|
||||||
tools=[],
|
tools=[],
|
||||||
model=fake_model,
|
model=fake_model,
|
||||||
)
|
)
|
||||||
|
@ -683,7 +694,7 @@ class TestMultiStepAgent:
|
||||||
assert isinstance(planning_step, PlanningStep)
|
assert isinstance(planning_step, PlanningStep)
|
||||||
messages = planning_step.model_input_messages
|
messages = planning_step.model_input_messages
|
||||||
assert isinstance(messages, list)
|
assert isinstance(messages, list)
|
||||||
assert len(messages) == 2
|
assert len(messages) == 1
|
||||||
for message in messages:
|
for message in messages:
|
||||||
assert isinstance(message, dict)
|
assert isinstance(message, dict)
|
||||||
assert "role" in message
|
assert "role" in message
|
||||||
|
@ -701,7 +712,7 @@ class TestMultiStepAgent:
|
||||||
assert len(call_args.args) == 1
|
assert len(call_args.args) == 1
|
||||||
messages = call_args.args[0]
|
messages = call_args.args[0]
|
||||||
assert isinstance(messages, list)
|
assert isinstance(messages, list)
|
||||||
assert len(messages) == 2
|
assert len(messages) == 1
|
||||||
for message in messages:
|
for message in messages:
|
||||||
assert isinstance(message, dict)
|
assert isinstance(message, dict)
|
||||||
assert "role" in message
|
assert "role" in message
|
||||||
|
|
Loading…
Reference in New Issue