Building AI agents, atomically
re-organization and chat with search demo
Kenny Vaneetveldeb08b2116e366
diff --git a/atomic_agents/agents/basic_chat_agent_new.py b/atomic_agents/agents/basic_chat_agent_new.pyindex 2940b57..3e8ad88 100644--- a/atomic_agents/agents/basic_chat_agent_new.py+++ b/atomic_agents/agents/basic_chat_agent_new.py@@ -1,13 +1,8 @@-import osfrom typing import Callable, Listfrom pydantic import BaseModel, Fieldfrom datetime import datetimefrom abc import ABC, abstractmethod-from groq import Groq-import instructor-import openaifrom atomic_agents.lib.chat_memory import ChatMemory-from rich.console import Consoleclass BasicChatAgentInputSchema(BaseModel):chat_input: str = Field(..., description='The input text for the chat agent.')@@ -36,24 +31,6 @@ class DynamicInfoProviderBase(ABC):def get_info(self) -> str:pass-class CurrentDateProvider(DynamicInfoProviderBase):- def __init__(self, title: str, format: str = '%Y-%m-%d %H:%M:%S'):- super().__init__(title)- self.format = format-- def get_info(self) -> str:- return f'The current date, in the format "{self.format}", is {datetime.now().strftime(self.format)}'--class LiveSearchResultsProvider(DynamicInfoProviderBase):- def __init__(self, title: str, search_query: str):- super().__init__(title)- self.search_query = search_query-- def get_info(self) -> str:- # Placeholder for live search results fetching logic- # In a real implementation, this would fetch live data from a search API- return f'Live search results for "{self.search_query}"'-class SystemPromptGenerator:def __init__(self, system_prompt: SystemPrompt, dynamic_info_providers: List[DynamicInfoProviderBase] = None):self.system_prompt = system_prompt@@ -67,7 +44,7 @@ class SystemPromptGenerator:system_prompt += f'-{'\n-'.join(self.system_prompt.background)}\n\n'if self.system_prompt.steps:- system_prompt += '# Steps\n'+ system_prompt += '# INTERNAL ASSISTANT STEPS\n'system_prompt += f'-{'\n-'.join(self.system_prompt.steps)}\n\n'if self.system_prompt.output_instructions:@@ -117,7 +94,31 @@ class BasicChatAgent:self.memory.add_message('assistant', response.model_dump_json())return response-if __name__ == '__main__':+if __name__ == '__main__':+ import os+ import instructor+ import openai+ from groq import Groq+ from rich.console import Console++ class CurrentDateProvider(DynamicInfoProviderBase):+ def __init__(self, title: str, format: str = '%Y-%m-%d %H:%M:%S'):+ super().__init__(title)+ self.format = format++ def get_info(self) -> str:+ return f'The current date, in the format "{self.format}", is {datetime.now().strftime(self.format)}'++ class LiveSearchResultsProvider(DynamicInfoProviderBase):+ def __init__(self, title: str, search_query: str):+ super().__init__(title)+ self.search_query = search_query++ def get_info(self) -> str:+ # Placeholder for live search results fetching logic+ # In a real implementation, this would fetch live data from a search API+ return f'Live search results for "{self.search_query}"'+console = Console()# Configuration dictionary@@ -136,33 +137,59 @@ if __name__ == '__main__':use_groq = False # Set this to True to use Groq, False to use OpenAIchosen_config = config['groq'] if use_groq else config['openai']- class MyChatAgentResponse(BaseModel):- observations: List[str] = Field(..., description='What the agent observes in the current state of the conversation.')- thought_process: List[str] = Field(..., description='The thought process of the agent in formulating the response.')- final_response: str = Field(..., description='The markdown-enabled response from the chat agent.')+ class PlanStep(BaseModel):+ step: str+ description: str+ substeps: List[str] = []++ class ArticleBuddyPlanResponse(BaseModel):+ observations: List[str] = Field(..., description='What is the conversation about? What are the key points?')+ thoughts: List[str] = Field(..., description='What is the thought process involved in preparing the ideas and outline?')+ response_plan: List[PlanStep] = Field(..., description='What are the steps involved in generating the ideas and outline?')class Config:- title = 'BasicChatAgentResponse'- description = 'Response from the basic chat agent. The response can be in markdown format.'+ title = 'ArticleBuddyPlanResponse'+ description = 'Response plan from the Article Buddy chat agent.'json_schema_extra = {'title': title,'description': description}+ class ArticleBuddyResponse(BaseModel):+ response: str = Field(..., description='The markdown-enabled response from the chat agent.')++ class Config:+ title = 'ArticleBuddyResponse'+ description = 'Response from the Article Buddy chat agent.'+ json_schema_extra = {+ 'title': title,+ 'description': description+ }++ class MyChatAgent(BasicChatAgent):+ def run(self, user_input: str) -> ArticleBuddyResponse:+ self.memory.add_message('user', user_input)+ self.memory.add_message('assistant', 'First, let me note the observations about the input and thought process involved in preparing the ideas and outline.')+ plan = self.get_response(response_model=ArticleBuddyPlanResponse)+ self.memory.add_message('assistant', plan.model_dump_json())+ response = self.get_response(response_model=ArticleBuddyResponse)+ self.memory.add_message('assistant', response.model_dump_json())+ return response+system_prompt = SystemPrompt(background=[- 'You are an expert in brainstorming ideas and creating article outlines.',- 'Your goal is to generate engaging and creative ideas and structured outlines for articles based on the given topic.'+ 'This assistant is an expert in brainstorming ideas and creating article outlines.',+ 'This assistant\'s goal is to generate engaging and creative ideas and structured outlines for articles based on the given topic.'],steps=[- 'Take the input given as the topic for the ideas and article outline.',- 'Brainstorm and create a list of 10 unique and creative ideas based on the given topic.',- 'Generate a structured article outline based on the given topic and the brainstormed ideas.'+ 'Note the observations about the input and thought process involved in preparing the ideas and outline.',+ 'Respond with a list of 10 ideas and a structured outline for the article in a markdown-formatted text.'],output_instructions=['Ensure each idea is clearly numbered from 1 to 10.','Output the list of ideas and the article outline in human-readable Markdown format.',- 'Do not include any additional text or confirmation messages; only provide the list of ideas and the article outline.'+ 'Do not include any additional text or confirmation messages; only provide the list of ideas and the article outline.',+ 'Do not reply to the user\'s input with anything except the list of ideas and the article outline.'])@@ -177,13 +204,13 @@ if __name__ == '__main__':CurrentDateProvider('Current date', format='%Y-%m-%d %H:%M:%S'),]- agent = BasicChatAgent(+ agent = MyChatAgent(client=chosen_config['client'],model=chosen_config['model'],system_prompt=system_prompt,memory=memory,dynamic_info_providers=dynamic_info_providers,- output_schema=MyChatAgentResponse+ output_schema=ArticleBuddyResponse)console.print(f'Agent: {initial_memory[0]["content"]}')@@ -194,4 +221,4 @@ if __name__ == '__main__':breakresponse = agent.run(user_input)- console.print(f'Agent: {response.final_response}')\ No newline at end of file+ console.print(f'Agent: {response.response}')diff --git a/atomic_agents/agents/basic_chat_agent_new_with_search.py b/atomic_agents/agents/basic_chat_agent_new_with_search.pynew file mode 100644index 0000000..7096ecf--- /dev/null+++ b/atomic_agents/agents/basic_chat_agent_new_with_search.py@@ -0,0 +1,224 @@+from typing import Callable, List+from pydantic import BaseModel, Field+from datetime import datetime+from abc import ABC, abstractmethod+from atomic_agents.lib.chat_memory import ChatMemory+from atomic_agents.lib.utils.logger import logger++class BasicChatAgentInputSchema(BaseModel):+ chat_input: str = Field(..., description='The input text for the chat agent.')++class BasicChatAgentResponse(BaseModel):+ response: str = Field(..., description='The markdown-enabled response from the chat agent.')++ class Config:+ title = 'BasicChatAgentResponse'+ description = 'Response from the basic chat agent. The response can be in markdown format.'+ json_schema_extra = {+ 'title': title,+ 'description': description+ }++class SystemPrompt(BaseModel):+ background: List[str]+ steps: List[str]+ output_instructions: List[str]++class DynamicInfoProviderBase(ABC):+ def __init__(self, title: str):+ self.title = title++ @abstractmethod+ def get_info(self) -> str:+ pass++class SystemPromptGenerator:+ def __init__(self, system_prompt: SystemPrompt, dynamic_info_providers: dict[str, DynamicInfoProviderBase] = None):+ self.system_prompt = system_prompt+ self.dynamic_info_providers = dynamic_info_providers or {}++ def generate_prompt(self) -> str:+ system_prompt = ''++ if self.system_prompt.background:+ system_prompt += '# IDENTITY and PURPOSE\n'+ system_prompt += f'-{'\n-'.join(self.system_prompt.background)}\n\n'++ if self.system_prompt.steps:+ system_prompt += '# INTERNAL ASSISTANT STEPS\n'+ system_prompt += f'-{'\n-'.join(self.system_prompt.steps)}\n\n'++ if self.system_prompt.output_instructions:+ system_prompt += '# OUTPUT INSTRUCTIONS\n'+ system_prompt += f'-{'\n-'.join(self.system_prompt.output_instructions)}\n\n'++ if self.dynamic_info_providers:+ system_prompt += '# EXTRA INFORMATION AND CONTEXT\n'+ for provider in self.dynamic_info_providers.values():+ info = provider.get_info()+ if info:+ system_prompt += f'## {provider.title}\n'+ system_prompt += f'{info}\n\n'++ return system_prompt++class GeneralPlanStep(BaseModel):+ step: str+ description: str+ substeps: List[str] = []++class GeneralPlanResponse(BaseModel):+ observations: List[str] = Field(..., description='Key points or observations about the input.')+ thoughts: List[str] = Field(..., description='Thought process or considerations involved in preparing the response.')+ response_plan: List[GeneralPlanStep] = Field(..., description='Steps involved in generating the response.')++ class Config:+ title = 'GeneralPlanResponse'+ description = 'General response plan from the chat agent.'+ json_schema_extra = {+ 'title': title,+ 'description': description+ }++class BasicChatAgent:+ def __init__(self, client, model: str = 'gpt-3.5-turbo', system_prompt: SystemPrompt = None, memory: ChatMemory = None, include_planning_step = False, input_schema = BasicChatAgentInputSchema, output_schema = BasicChatAgentResponse, dynamic_info_providers: dict[str, DynamicInfoProviderBase] = None):+ self.input_schema = input_schema+ self.output_schema = output_schema+ self.client = client+ self.model = model+ self.memory = memory or ChatMemory()+ self.system_prompt = system_prompt or SystemPrompt(+ background=['You are a helpful AI assistant.'],+ steps=[],+ output_instructions=[]+ )+ self.system_prompt_generator = SystemPromptGenerator(self.system_prompt, dynamic_info_providers)+ self.include_planning_step = include_planning_step++ def get_system_prompt(self) -> str:+ return self.system_prompt_generator.generate_prompt()++ def get_response(self, response_model=None) -> BaseModel:+ if response_model is None:+ response_model = self.output_schema++ messages = [{'role': 'system', 'content': self.get_system_prompt()}] + self.memory.get_history()+ response = self.client.chat.completions.create(+ model=self.model,+ messages=messages,+ response_model=response_model+ )+ return response++ def run(self, user_input: str) -> str:+ self.memory.add_message('user', 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()+ return response++ def _pre_run(self):+ pass++ def _post_run(self):+ pass++if __name__ == '__main__':+ import instructor+ import openai+ from rich.console import Console+ from atomic_agents.tools.searx import SearxNGSearchTool++ class CurrentDateProvider(DynamicInfoProviderBase):+ def __init__(self, title: str, format: str = '%Y-%m-%d %H:%M:%S'):+ super().__init__(title)+ self.format = format++ def get_info(self) -> str:+ return f'The current date, in the format "{self.format}", is {datetime.now().strftime(self.format)}'++ class SearchResultsProvider(DynamicInfoProviderBase):+ def __init__(self, *args, **kwargs):+ super().__init__(*args, **kwargs)+ self.search_results: SearxNGSearchTool.output_schema = None++ def get_info(self) -> str:+ response = ''+ if not self.search_results:+ return response++ for result in self.search_results.results:+ response += f'--- {result.title} ---\n'+ response += f'{result.content}\n'+ response += f'[Read more]({result.url})\n'+ response += '--------------------------------\n\n'++ return response++ # Define dynamic info providers+ dynamic_info_providers = {+ 'date': CurrentDateProvider('Current date', format='%Y-%m-%d %H:%M:%S'),+ 'search': SearchResultsProvider('Search results')+ }++ console = Console()++ system_prompt = SystemPrompt(+ background=[+ 'This assistant is an expert in brainstorming ideas and creating article outlines.',+ 'This assistant\'s goal is to generate engaging and creative ideas and structured outlines for articles based on the given topic.'+ ],+ steps=[+ 'Note the observations about the input and thought process involved in preparing the ideas and outline.',+ 'Respond with a list of 10 ideas and a structured outline for the article in a markdown-formatted text.'+ ],+ output_instructions=[+ 'Ensure each idea is clearly numbered from 1 to 10.',+ 'Output the list of ideas and the article outline in human-readable Markdown format.',+ 'Do not include any additional text or confirmation messages; only provide the list of ideas and the article outline.',+ 'Do not reply to the user\'s input with anything except the list of ideas and the article outline.'+ ]+ )++ 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)++ class MyChatAgent(BasicChatAgent):+ def __init__(self, *args, **kwargs):+ super().__init__(*args, **kwargs)+ self.search_tool = SearxNGSearchTool(max_results=15)++ def _pre_run(self):+ self.memory.add_message('assistant', 'First, I will perform a search with 3 different search queries to gather relevant information on the topic.')+ search_input = self.get_response(response_model=SearxNGSearchTool.input_schema)+ logger.verbose(f'Search input: {search_input}')+ search_results = self.search_tool.run(search_input)+ self.system_prompt_generator.dynamic_info_providers['search'].search_results = search_results+ self.memory.add_message('assistant', 'I have gathered the search results and they have been added to the context.')+++ agent = MyChatAgent(+ client=instructor.from_openai(openai.OpenAI()),+ model='gpt-3.5-turbo',+ system_prompt=system_prompt,+ memory=memory,+ dynamic_info_providers=dynamic_info_providers+ )+ console.print(f'Agent: {initial_memory[0]["content"]}')++ 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 filediff --git a/atomic_agents_new/agents/basic_chat_agent.py b/atomic_agents_new/agents/basic_chat_agent.pynew file mode 100644index 0000000..05d936c--- /dev/null+++ b/atomic_agents_new/agents/basic_chat_agent.py@@ -0,0 +1,88 @@+from typing import Callable, List+from pydantic import BaseModel, Field+from datetime import datetime+from abc import ABC, abstractmethod+from atomic_agents.lib.chat_memory import ChatMemory+from atomic_agents.lib.utils.logger import logger+from atomic_agents.tools.searx import SearxNGSearchTool+from atomic_agents_new.lib.system_prompt_generator import SystemPrompt, SystemPromptGenerator++class BasicChatAgentInputSchema(BaseModel):+ chat_input: str = Field(..., description='The input text for the chat agent.')++class BasicChatAgentResponse(BaseModel):+ response: str = Field(..., description='The markdown-enabled response from the chat agent.')++ class Config:+ title = 'BasicChatAgentResponse'+ description = 'Response from the basic chat agent. The response can be in markdown format.'+ json_schema_extra = {+ 'title': title,+ 'description': description+ }++class GeneralPlanStep(BaseModel):+ step: str+ description: str+ substeps: List[str] = []++class GeneralPlanResponse(BaseModel):+ observations: List[str] = Field(..., description='Key points or observations about the input.')+ thoughts: List[str] = Field(..., description='Thought process or considerations involved in preparing the response.')+ response_plan: List[GeneralPlanStep] = Field(..., description='Steps involved in generating the response.')++ class Config:+ title = 'GeneralPlanResponse'+ description = 'General response plan from the chat agent.'+ json_schema_extra = {+ 'title': title,+ 'description': description+ }++class BasicChatAgent:+ def __init__(self, client, model: str = 'gpt-3.5-turbo', system_prompt: SystemPrompt = None, memory: ChatMemory = None, include_planning_step = False, input_schema = BasicChatAgentInputSchema, output_schema = BasicChatAgentResponse, dynamic_info_providers: dict[str, DynamicInfoProviderBase] = None):+ self.input_schema = input_schema+ self.output_schema = output_schema+ self.client = client+ self.model = model+ self.memory = memory or ChatMemory()+ self.system_prompt = system_prompt or SystemPrompt(+ background=['You are a helpful AI assistant.'],+ steps=[],+ output_instructions=[]+ )+ self.system_prompt_generator = SystemPromptGenerator(self.system_prompt, dynamic_info_providers)+ self.include_planning_step = include_planning_step++ def get_system_prompt(self) -> str:+ return self.system_prompt_generator.generate_prompt()++ def get_response(self, response_model=None) -> BaseModel:+ if response_model is None:+ response_model = self.output_schema++ messages = [{'role': 'system', 'content': self.get_system_prompt()}] + self.memory.get_history()+ response = self.client.chat.completions.create(+ model=self.model,+ messages=messages,+ response_model=response_model+ )+ return response++ def run(self, user_input: str) -> str:+ self.memory.add_message('user', 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()+ return response++ def _pre_run(self):+ pass++ def _post_run(self):+ pass\ No newline at end of filediff --git a/atomic_agents_new/examples/basic_custom_chat_agent.py b/atomic_agents_new/examples/basic_custom_chat_agent.pynew file mode 100644index 0000000..a1db9a8--- /dev/null+++ b/atomic_agents_new/examples/basic_custom_chat_agent.py@@ -0,0 +1,97 @@+from datetime import datetime+from rich.console import Console+from atomic_agents.lib.chat_memory import ChatMemory+from atomic_agents_new.agents.basic_chat_agent import BasicChatAgent+from atomic_agents_new.lib.system_prompt_generator import DynamicInfoProviderBase, SystemPrompt+import instructor+import openai+from atomic_agents.tools.searx import SearxNGSearchTool+from atomic_agents.lib.utils.logger import logger++class MyChatAgent(BasicChatAgent):+ def __init__(self, *args, **kwargs):+ super().__init__(*args, **kwargs)+ self.search_tool = SearxNGSearchTool(max_results=15)++ def _pre_run(self):+ self.memory.add_message('assistant', 'First, I will perform a search with 3 different search queries to gather relevant information on the topic.')+ search_input = self.get_response(response_model=SearxNGSearchTool.input_schema)+ logger.verbose(f'Search input: {search_input}')+ search_results = self.search_tool.run(search_input)+ self.system_prompt_generator.dynamic_info_providers['search'].search_results = search_results+ self.memory.add_message('assistant', 'I have gathered the search results and they have been added to the context.')++class CurrentDateProvider(DynamicInfoProviderBase):+ def __init__(self, title: str, format: str = '%Y-%m-%d %H:%M:%S'):+ super().__init__(title)+ self.format = format++ def get_info(self) -> str:+ return f'The current date, in the format "{self.format}", is {datetime.now().strftime(self.format)}'++class SearchResultsProvider(DynamicInfoProviderBase):+ def __init__(self, *args, **kwargs):+ super().__init__(*args, **kwargs)+ self.search_results: SearxNGSearchTool.output_schema = None++ def get_info(self) -> str:+ response = ''+ if not self.search_results:+ return response++ for result in self.search_results.results:+ response += f'--- {result.title} ---\n'+ response += f'{result.content}\n'+ response += f'[Read more]({result.url})\n'+ response += '--------------------------------\n\n'++ return response++# Define dynamic info providers+dynamic_info_providers = {+ 'date': CurrentDateProvider('Current date', format='%Y-%m-%d %H:%M:%S'),+ 'search': SearchResultsProvider('Search results')+}++console = Console()++system_prompt = SystemPrompt(+ background=[+ 'This assistant is an expert in brainstorming ideas and creating article outlines.',+ 'This assistant\'s goal is to generate engaging and creative ideas and structured outlines for articles based on the given topic.'+ ],+ steps=[+ 'Note the observations about the input and thought process involved in preparing the ideas and outline.',+ 'Respond with a list of 10 ideas and a structured outline for the article in a markdown-formatted text.'+ ],+ output_instructions=[+ 'Ensure each idea is clearly numbered from 1 to 10.',+ 'Output the list of ideas and the article outline in human-readable Markdown format.',+ 'Do not include any additional text or confirmation messages; only provide the list of ideas and the article outline.',+ 'Do not reply to the user\'s input with anything except the list of ideas and the article outline.'+ ]+)++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)++agent = MyChatAgent(+ client=instructor.from_openai(openai.OpenAI()),+ model='gpt-3.5-turbo',+ system_prompt=system_prompt,+ memory=memory,+ dynamic_info_providers=dynamic_info_providers+)+console.print(f'Agent: {initial_memory[0]["content"]}')++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 filediff --git a/atomic_agents_new/lib/system_prompt_generator.py b/atomic_agents_new/lib/system_prompt_generator.pynew file mode 100644index 0000000..40a01c7--- /dev/null+++ b/atomic_agents_new/lib/system_prompt_generator.py@@ -0,0 +1,46 @@+from typing import List+from pydantic import BaseModel+from abc import ABC, abstractmethod++class SystemPrompt(BaseModel):+ background: List[str]+ steps: List[str]+ output_instructions: List[str]++class DynamicInfoProviderBase(ABC):+ def __init__(self, title: str):+ self.title = title++ @abstractmethod+ def get_info(self) -> str:+ pass++class SystemPromptGenerator:+ def __init__(self, system_prompt: SystemPrompt, dynamic_info_providers: dict[str, DynamicInfoProviderBase] = None):+ self.system_prompt = system_prompt+ self.dynamic_info_providers = dynamic_info_providers or {}++ def generate_prompt(self) -> str:+ system_prompt = ''++ if self.system_prompt.background:+ system_prompt += '# IDENTITY and PURPOSE\n'+ system_prompt += f'-{'\n-'.join(self.system_prompt.background)}\n\n'++ if self.system_prompt.steps:+ system_prompt += '# INTERNAL ASSISTANT STEPS\n'+ system_prompt += f'-{'\n-'.join(self.system_prompt.steps)}\n\n'++ if self.system_prompt.output_instructions:+ system_prompt += '# OUTPUT INSTRUCTIONS\n'+ system_prompt += f'-{'\n-'.join(self.system_prompt.output_instructions)}\n\n'++ if self.dynamic_info_providers:+ system_prompt += '# EXTRA INFORMATION AND CONTEXT\n'+ for provider in self.dynamic_info_providers.values():+ info = provider.get_info()+ if info:+ system_prompt += f'## {provider.title}\n'+ system_prompt += f'{info}\n\n'++ return system_prompt\ No newline at end of file