Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add example tools #82

Merged
merged 4 commits into from
May 20, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
62 changes: 34 additions & 28 deletions polymind/core/task.py
Original file line number Diff line number Diff line change
Expand Up @@ -103,10 +103,14 @@ class AtomTask(BaseTask):
Please read the requirement carefully and think step by step.
Your task is to generate the parameters (key-value pairs) for the tool to be used, according to its input spec.
Please fill the value with your own understanding of the requirement, instead of using the examples.
Please set the value according to the objective:
If there are useful data in the context, please use them.
---
Objective:
{objective}
Tool Description:
{tool_description}
Context:
{context}
---
It is expected the output is a json dict with param keys and values.
The below is the input_spec.
Expand Down Expand Up @@ -134,38 +138,38 @@ class AtomTask(BaseTask):

reformat_output_text_prompt: str = """
Sometimes the text may contains the json blob or other metadata that is not needed.
Please reformat the text by following the below rules:
Please reformat the text following the below rules:
1. Remove keys in the text if it looks like a json blob.
2. Remove excessive escape characters, such as '\n', '\t', etc.

Example inputs:
1.
---
'{{"context": "I\'m unable to connect the Internet.", "answer": "Please check the network connection}}'
---
2.
---
'{{"context": "\n what's the biggest news about AI today?\n\t\t\n\n.", "answer": "OpenAI released GPT-10."}}'
---
Corresponding outputs:
1.
```
{{
"output": "If unable to provide real-time data, please check the network connection."
}}
```
2.
```
{{
"output": "The biggest news about AI today is OpenAI has released GPT-10.",
}}
```

Examples:
<example1>
<input1>
'{{"context": "I\'m unable to connect the Internet.", "answer": "Please check the network connection}}'
</input1>
<output1>
{{
"output": "If unable to provide real-time data, please check the network connection."
}}
</output1>
</example1>
<example2>
<input2>
'{{"context": "\n what's the news about AI today?\n\t\t\n\n.", "answer": "OpenAI released GPT-10."}}'
</input2>
<output2>
{{
"output": "The news about AI today is OpenAI has released GPT-10."
}}
</output2>
</example2>
<real_input>
The real input is available in the below json blob.
Please consolidate and convert the info into the ```json blob```, and the key should be "output".
```json
{input}
```
</real_input>
"""

def __init__(self, tool_manager: ToolManager, tool_retriever: RetrieveTool, **kwargs):
Expand Down Expand Up @@ -201,9 +205,11 @@ async def _use_tool(self, objective: str, tool_description: str) -> Message:
raise ValueError(f"Cannot find the tool: [{tool_name}] from the tool manager.")
tool_spec = tool_instance.to_open_function_format()
json_blob = json.dumps(tool_spec)
memory_context = self.memory.get_memory() if self.memory else ""
# Generate the parameters for the tool.
tool_param_gen_prompt = self.gen_param_prompt.format(
objective=objective,
context=memory_context,
tool_description=tool_description,
tool_spec=json_blob,
)
Expand Down Expand Up @@ -234,13 +240,13 @@ async def _reformat_output(self, text: str) -> str:
Returns:
str: The reformatted text.
"""
reformat_text_prompt = self.reformat_output_text_prompt.format(input=text)
self._logger.debug(f"Before reformating text: {text}")
reformat_text_prompt = self.reformat_output_text_prompt.format(input=text)
llm_response = await self.llm_tool(Message(content={"input": reformat_text_prompt}))
content = llm_response.content["output"]
# Extract the json from the ```json blob```.
if "```" in content:
texts = re.findall(r"```(.*?)```", content, re.DOTALL)
texts = re.findall(r"```json(.*?)```", content, re.DOTALL)
if not texts:
raise ValueError("Cannot find the text in the response.")
content = texts[0]
Expand Down Expand Up @@ -273,7 +279,7 @@ async def _execute(self, input: Message) -> Message:
{input_field}
Objective: {self.task_name}
"""
self._logger.task_log(f"Task {self.task_name}: Context: {self.task_context}")
self._logger.task_log(f"Task {self.task_name}: Context: {self.task_context}\n{memory_context}")
prompt = input.content["input"]
enhanced_prompt = f"""
{self.system_prompt}
Expand Down
8 changes: 6 additions & 2 deletions polymind/core/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
from typing import Any, Dict, List, get_args, get_origin

from polymind.core.tool import BaseTool, Param
from polymind.core.logger import Logger


def extract_content_from_blob(text: str, blob_type: str = "json") -> str:
Expand All @@ -22,7 +23,7 @@ def extract_content_from_blob(text: str, blob_type: str = "json") -> str:
return text


def json_text_to_tool_param(json_text: str, tool: BaseTool) -> Dict[str, Any]:
def json_text_to_tool_param(json_text: str, tool: BaseTool, logger: Logger = None) -> Dict[str, Any]:
"""Convert the JSON text that contains the params to call the tool to the tool parameter dictionary.

Args:
Expand All @@ -39,6 +40,8 @@ def json_text_to_tool_param(json_text: str, tool: BaseTool) -> Dict[str, Any]:
else:
tool_param = json_text
tool_param_dict = json.loads(tool_param)
if logger:
logger.debug(f"Tool param dict: {tool_param_dict}")
input_spec: List[Param] = tool.input_spec()

def _convert_value(value: Any, target_type: type) -> Any:
Expand Down Expand Up @@ -83,7 +86,8 @@ def _convert_value(value: Any, target_type: type) -> Any:
)
elif param.required:
raise ValueError(
f"The required parameter [{param_name}] is not provided. Provided params: {tool_param_dict}"
f"The required parameter [{param_name}] is not provided for tool {tool.tool_name}.",
f"Provided params: {tool_param_dict}",
)

return tool_param_dict_typed
3 changes: 1 addition & 2 deletions polymind/core_tools/llm_tool.py
Original file line number Diff line number Diff line change
Expand Up @@ -236,9 +236,8 @@ class OpenAICodeGenerationTool(CodeGenerationTool):
tool_name: str = "open-ai-code-generation"

def _set_llm_client(self):
model_name = os.environ.get("MODEL_NAME", "gpt-3.5-turbo")
model_name = os.environ.get("CODEGEN_MODEL_NAME", os.environ.get("MODEL_NAME", "gpt-3.5-turbo"))
self._llm_tool = OpenAIChatTool(model_name=model_name)
# self._llm_tool = AnthropicClaudeTool()


class AnthropicClaudeTool(LLMTool):
Expand Down
5 changes: 3 additions & 2 deletions polymind/core_tools/rest_api_tool.py
Original file line number Diff line number Diff line change
Expand Up @@ -141,10 +141,11 @@ class TavilyRestAPITool(RestAPITool):
tool_name: str = "tavily-rest-api-tool"
descriptions: List[str] = [
"Search engine to search for external information.",
"Search for information on the internet for timely information.",
"External search engine to search for public information.",
"Retrieve for information on the internet for timely information.",
"Retrieve external search engine to search for public information.",
"Search latest information on the internet.",
"Search up-to-date information on the internet.",
"Look up the world wide web for information.",
]

def __init__(self):
Expand Down
2 changes: 1 addition & 1 deletion polymind/core_tools/retrieve_tool.py
Original file line number Diff line number Diff line change
Expand Up @@ -118,7 +118,7 @@ class ToolRetriever(RetrieveTool):
3. Return the result as List[str], where each str is the name of the tool.
4. Please carefully review the available tools,
and pick ONLY ONE that is the highest chance to fulfill the below query:

<query>
{query}
</query>
Expand Down
23 changes: 16 additions & 7 deletions polymind/thought_process/chain_of_tasks.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,20 +32,23 @@ class ChainOfTasks(ThoughtProcess):
retry_interval: int = Field(default=5, description="The interval between retries in seconds.")

problem_decomposition_prompt: str = """
Please read the requirement carefully, and think step-by-step before answering the question.
You need to breakdown a complex problem into a series of tasks.
Please read the requirement carefully and think step-by-step before answering the question.
Follow the below rules:
1. Please decompose the problem into up to 5 sub-tasks, depending on the complexity of the problem.
Each of the following sub-task will use the output of the previous task as input.
Each sub-task is considered to be an atomic task that can be resolved using one tool.
1. Decompose the problem into UP TO 5 sub-tasks, depending on the complexity of the problem.
Each sub-task can use the output of the previous tasks as input.
Each sub-task is considered to solvable using ONE LLM inference or ONE tool.
2. For each step, please give it an "objective", "input" and "output".
Objectives: Make it less ambiguous and more specific to the requirement, e.g. including date if provided.
Input: Make it to explain how to use the input. Use declarative name and please describe the type as well.
3. Please write down the decomposition into the json blob.

An example of the decomposition is as follows:
<example_requirements>
The biggest city of the south neighbor country of the country whose capital is Paris.
</example_requirements>

The question: The south neighbor country of the country whose capital is Paris.

<example_decomposition>
{
"steps": [
{
Expand All @@ -57,9 +60,15 @@ class ChainOfTasks(ThoughtProcess):
"objective": "Find the south neighbor country of the country",
"input": {"name": "target_country", "type": "str"},
"output": {"name": "neighbor_country", "type": "str"}
}
},
(
"objective": "Find the biggest city of the neighbor country",
"input": {"name": "neighbor_country", "type": "str"},
"output": {"name": "biggest_city", "type": "str"}
)
]
}
</example_decomposition>
"""

def __init__(
Expand Down
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[tool.poetry]
name = "polymind"
version = "0.0.44" # Update this version before publishing to PyPI
version = "0.0.45" # Update this version before publishing to PyPI
description = "PolyMind is a customizable collaborative multi-agent framework for collective intelligence and distributed problem solving."
authors = ["TechTao"]
license = "MIT License"
Expand Down
Loading