Building AI agents, atomically
Refactoring, add tool interface agent, add example
KennyVaneetveldeaa8f7f438ed3
diff --git a/atomic_agents/agents/base_chat_agent.py b/atomic_agents/agents/base_chat_agent.pyindex 2f534cf..c105dc4 100644--- a/atomic_agents/agents/base_chat_agent.py+++ b/atomic_agents/agents/base_chat_agent.py@@ -2,9 +2,9 @@ from typing import Listfrom pydantic import BaseModel, Fieldfrom atomic_agents.lib.components.chat_memory import ChatMemoryfrom atomic_agents.lib.utils.logger import logger-from atomic_agents.lib.tools.searx import SearxNGSearchTool-from atomic_agents.lib.components.system_prompt_generator import DynamicInfoProviderBase, SystemPromptInfo, SystemPromptGenerator+from atomic_agents.lib.components.system_prompt_generator import SystemPromptGenerator+# Input and Response Schemasclass BaseChatAgentInputSchema(BaseModel):chat_input: str = Field(..., description='The input text for the chat agent.')@@ -13,7 +13,7 @@ class BaseChatAgentResponse(BaseModel):class Config:title = 'BaseChatAgentResponse'- description = 'Response from the base chat agent. The response can be in markdown format.'+ description = 'Response from the base chat agent. The response can be in markdown format. This response is the only thing the user will see in the chat interface.'json_schema_extra = {'title': title,'description': description@@ -37,6 +37,7 @@ class GeneralPlanResponse(BaseModel):'description': description}+# Base Chat Agent Classclass BaseChatAgent:def __init__(self, client, system_prompt_generator: SystemPromptGenerator = None, model: str = 'gpt-3.5-turbo', memory: ChatMemory = None, include_planning_step = False, input_schema = BaseChatAgentInputSchema, output_schema = BaseChatAgentResponse):self.input_schema = input_schema@@ -46,7 +47,11 @@ class BaseChatAgent:self.memory = memory or ChatMemory()self.system_prompt_generator = system_prompt_generator or SystemPromptGenerator()self.include_planning_step = include_planning_step-+ self.initial_memory = self.memory.copy()++ def reset_memory(self):+ self.memory = self.initial_memory.copy()+def get_system_prompt(self) -> str:return self.system_prompt_generator.generate_prompt()@@ -63,19 +68,27 @@ class BaseChatAgent:return responsedef run(self, user_input: str) -> str:- self.memory.add_message('user', user_input)+ self._init_run(user_input)self._pre_run()if self.include_planning_step:- self.memory.add_message('assistant', 'I will now note the observations about the input and context and the thought process involved in preparing the response.')- plan = self.get_response(response_model=GeneralPlanResponse)- self.memory.add_message('assistant', plan.model_dump_json())- response = self.get_response(response_model=self.output_schema)- self.memory.add_message('assistant', response.model_dump_json())- self._post_run()+ self._plan_run()+ response = self._get_and_handle_response()+ self._post_run(response)return response++ def _get_and_handle_response(self):+ return self.get_response(response_model=self.output_schema)++ def _plan_run(self):+ self.memory.add_message('assistant', 'I will now note any observations about the relevant input, context and thought process involved in preparing the response.')+ plan = self.get_response(response_model=GeneralPlanResponse)+ self.memory.add_message('assistant', plan.model_dump_json())++ def _init_run(self, user_input):+ self.memory.add_message('user', user_input)def _pre_run(self):pass- def _post_run(self):- pass\ No newline at end of file+ def _post_run(self, response):+ self.memory.add_message('assistant', response.model_dump_json())\ No newline at end of filediff --git a/atomic_agents/agents/tool_interface_agent.py b/atomic_agents/agents/tool_interface_agent.pynew file mode 100644index 0000000..8a46762--- /dev/null+++ b/atomic_agents/agents/tool_interface_agent.py@@ -0,0 +1,63 @@+from pydantic import Field, create_model+from atomic_agents.agents.base_chat_agent import BaseChatAgent+from atomic_agents.lib.components.system_prompt_generator import SystemPromptGenerator, SystemPromptInfo+from atomic_agents.lib.utils.format_tool_message import format_tool_message+from atomic_agents.lib.tools.searx import SearxNGSearchTool+from rich.console import Console+import instructor+import openai++class ToolInterfaceAgent(BaseChatAgent):+ def __init__(self, tool_instance, return_raw_output=False, *args, **kwargs):+ super().__init__(*args, **kwargs)++ self.tool_instance = tool_instance++ self.input_schema = create_model(+ self.tool_instance.tool_name,+ tool_input=(str, Field(..., description=f"{self.tool_instance.tool_name} tool input. Presented as a single question or instruction", alias=f'tool_input_{self.tool_instance.tool_name}')),+ __config__=type('Config', (), {+ 'title': self.tool_instance.tool_name,+ 'description': self.tool_instance.tool_description,+ 'json_schema_extra': {+ "title": self.tool_instance.tool_name,+ "description": self.tool_instance.tool_description+ }+ })+ )++ self.return_raw_output = return_raw_output+ if self.return_raw_output:+ self.output_schema = self.tool_instance.output_schema++ self.system_prompt_generator = SystemPromptGenerator(+ system_prompt_info=SystemPromptInfo(+ background=[+ f"This AI agent is designed to interact with the {self.tool_instance.tool_name} tool.",+ f"Tool description: {self.tool_instance.tool_description}"+ ],+ steps=[+ "Get the user input.",+ "Convert the input to the proper parameters to call the tool.",+ "Call the tool with the parameters.",+ "Respond to the user"+ ],+ output_instructions=[+ "Make sure the tool call will maximize the utility of the tool in the context of the user input.",+ "Process the output of the tool into a human readable format and/or use it to respond to the user input." if return_raw_output else "Return the raw output of the tool."+ ]+ )+ )++ def _get_and_handle_response(self):+ tool_input = self.get_response(response_model=self.tool_instance.input_schema)+ formatted_tool_input = format_tool_message(tool_input)+ self.memory.add_message('assistant', '', tool_message=formatted_tool_input, tool_id=formatted_tool_input['id'])+ tool_output = self.tool_instance.run(tool_input)+ self.memory.add_message('tool', tool_output.model_dump_json(), tool_id=formatted_tool_input['id'])++ if self.return_raw_output:+ return tool_output++ response = self.get_response(response_model=self.output_schema)+ return response\ No newline at end of filediff --git a/atomic_agents/lib/components/chat_memory.py b/atomic_agents/lib/components/chat_memory.pyindex 516d8f9..9f04354 100644--- a/atomic_agents/lib/components/chat_memory.py+++ b/atomic_agents/lib/components/chat_memory.py@@ -61,7 +61,7 @@ class ChatMemory:"""return self.history- def to_dict_list(self) -> List[Dict]:+ def dump(self) -> List[Dict]:"""Converts the chat history to a list of dictionaries.@@ -70,11 +70,21 @@ class ChatMemory:"""return [message.model_dump() for message in self.history]- def load_from_dict_list(self, dict_list: List[Dict]) -> None:+ def load(self, dict_list: List[Dict]) -> None:"""Loads the chat history from a list of dictionaries.Args:dict_list (List[Dict]): The list of messages as dictionaries."""- self.history = [Message(**message_dict) for message_dict in dict_list]\ No newline at end of file+ self.history = [Message(**message_dict) for message_dict in dict_list]++ def copy(self) -> 'ChatMemory':+ """+ Creates a copy of the chat memory.++ Returns:+ ChatMemory: A copy of the chat memory.+ """+ new_memory = ChatMemory()+ new_memory.load(self.dump())\ No newline at end of filediff --git a/examples/article_idea_outline_gen_with_search.py b/examples/article_idea_outline_gen_with_search.pyindex 8441db9..d206aa9 100644--- a/examples/article_idea_outline_gen_with_search.py+++ b/examples/article_idea_outline_gen_with_search.py@@ -79,7 +79,7 @@ memory = ChatMemory()initial_memory = [{'role': 'assistant', 'content': 'Hello! I\'m an AI assistant that can help you brainstorm ideas and generate article outlines. Please provide me with a topic to get started.'}]-memory.load_from_dict_list(initial_memory)+memory.load(initial_memory)agent = MyChatAgent(client=instructor.from_openai(openai.OpenAI()),diff --git a/examples/basic_custom_chatbot.py b/examples/basic_custom_chatbot.pyindex c942f09..853d691 100644--- a/examples/basic_custom_chatbot.py+++ b/examples/basic_custom_chatbot.py@@ -44,7 +44,7 @@ initial_memory = [{'role': 'assistant', 'content': 'How do you do? What can I do for you? Tell me, pray, what is your need today?'}]-memory.load_from_dict_list(initial_memory)+memory.load(initial_memory)agent = BaseChatAgent(client=instructor.from_openai(openai.OpenAI()),diff --git a/examples/simple_tool_interface_agent.py b/examples/simple_tool_interface_agent.pynew file mode 100644index 0000000..0ef02f9--- /dev/null+++ b/examples/simple_tool_interface_agent.py@@ -0,0 +1,32 @@+import instructor+import openai+from rich.console import Console++from atomic_agents.agents.tool_interface_agent import ToolInterfaceAgent+from atomic_agents.lib.tools.searx import SearxNGSearchTool++console = Console()++# Initialize the client+client = instructor.from_openai(openai.OpenAI())++# Initialize the SearxNGSearchTool+searx_tool = SearxNGSearchTool(max_results=5)++# Initialize the ToolInterfaceAgent with the SearxNGSearchTool+agent = ToolInterfaceAgent(+ tool_instance=searx_tool,+ client=client,+ model='gpt-3.5-turbo'+)++console.print("ToolInterfaceAgent with SearxNGSearchTool is ready.")++while True:+ user_input = input('You: ')+ if user_input.lower() in ['exit', 'quit']:+ print('Exiting chat...')+ break++ response = agent.run(user_input)+ console.print(f'Agent: {response.response}')\ No newline at end of file