Skip to content

Building AI agents, atomically

The big configuration refactor

KennyVaneetveldeff11b3c2a257
diff --git a/atomic_agents/agents/base_chat_agent.py b/atomic_agents/agents/base_chat_agent.py
index 9b699da..cae033b 100644
--- a/atomic_agents/agents/base_chat_agent.py
+++ b/atomic_agents/agents/base_chat_agent.py
@@ -5,11 +5,21 @@ from pydantic import BaseModel, Field
from atomic_agents.lib.components.chat_memory import ChatMemory
from atomic_agents.lib.components.system_prompt_generator import SystemPromptGenerator
+class BaseAgentIO(BaseModel):
+ """
+ Base class for input and output schemas for chat agents.
+ """
+ def stringify(self):
+ raise NotImplementedError
+
# Input and Response Schemas
-class BaseChatAgentInputSchema(BaseModel):
+class BaseChatAgentInputSchema(BaseAgentIO):
chat_input: str = Field(..., description='The input text for the chat agent.')
+
+ def stringify(self):
+ return self.chat_input
-class BaseChatAgentResponse(BaseModel):
+class BaseChatAgentResponse(BaseAgentIO):
response: str = Field(..., description='The markdown-enabled response from the chat agent.')
class Config:
@@ -19,13 +29,15 @@ class BaseChatAgentResponse(BaseModel):
'title': title,
'description': description
}
+
+ def stringify(self):
+ return self.response
class BaseChatAgentConfig(BaseModel):
client: instructor.client.Instructor = Field(..., description='Client for interacting with the language model.')
model: str = Field("gpt-3.5-turbo", description='The model to use for generating responses.')
memory: Optional[ChatMemory] = Field(None, description='Memory component for storing chat history.')
system_prompt_generator: Optional[SystemPromptGenerator] = Field(None, description='Component for generating system prompts.')
- input_schema: Type[BaseModel] = Field(BaseChatAgentInputSchema, description='Schema for the input data.')
output_schema: Type[BaseModel] = Field(BaseChatAgentResponse, description='Schema for the output data.')
class Config:
@@ -39,14 +51,15 @@ class BaseChatAgent:
generating system prompts, and obtaining responses from a language model.
Attributes:
- input_schema (Type[BaseModel]): Schema for the input data.
- output_schema (Type[BaseModel]): Schema for the output data.
+ input_schema (Type[BaseAgentIO]): Schema for the input data.
+ output_schema (Type[BaseAgentIO]): Schema for the output data.
client: Client for interacting with the language model.
model (str): The model to use for generating responses.
memory (ChatMemory): Memory component for storing chat history.
system_prompt_generator (SystemPromptGenerator): Component for generating system prompts.
initial_memory (ChatMemory): Initial state of the memory.
"""
+ input_schema = BaseChatAgentInputSchema
def __init__(self, config: BaseChatAgentConfig = BaseChatAgentConfig(client=instructor.from_openai(openai.OpenAI()))):
"""
@@ -55,7 +68,6 @@ class BaseChatAgent:
Args:
config (BaseChatAgentConfig): Configuration for the chat agent.
"""
- self.input_schema = config.input_schema
self.output_schema = config.output_schema
self.client = config.client
self.model = config.model
@@ -99,7 +111,7 @@ class BaseChatAgent:
)
return response
- def run(self, user_input: Optional[str] = None) -> str:
+ def run(self, user_input: Optional[Type[BaseAgentIO]] = None) -> str:
"""
Runs the chat agent with the given user input.
@@ -126,14 +138,14 @@ class BaseChatAgent:
return self.get_response(response_model=self.output_schema)
- def _init_run(self, user_input):
+ def _init_run(self, user_input: Type[BaseAgentIO]):
"""
Initializes the run with the given user input.
Args:
user_input (str): The input text from the user.
"""
- self.memory.add_message('user', user_input)
+ self.memory.add_message('user', user_input.stringify())
def _pre_run(self):
"""
diff --git a/atomic_agents/agents/tool_interface_agent.py b/atomic_agents/agents/tool_interface_agent.py
index fba6729..e32371b 100644
--- a/atomic_agents/agents/tool_interface_agent.py
+++ b/atomic_agents/agents/tool_interface_agent.py
@@ -1,15 +1,27 @@
import json
from pydantic import Field, create_model
-from atomic_agents.agents.base_chat_agent import BaseChatAgent, BaseChatAgentConfig
+from atomic_agents.agents.base_chat_agent import BaseAgentIO, BaseChatAgent, BaseChatAgentConfig
from atomic_agents.lib.components.system_prompt_generator import SystemPromptGenerator, SystemPromptInfo
from atomic_agents.lib.tools.base import BaseTool
from atomic_agents.lib.utils.format_tool_message import format_tool_message
-
class ToolInterfaceAgentConfig(BaseChatAgentConfig):
tool_instance: BaseTool
return_raw_output: bool = False
+class ToolInputModel(BaseAgentIO):
+ tool_input: str = Field(..., description="Tool input. Presented as a single question or instruction")
+
+ class Config:
+ title = "Default Tool"
+ description = "Default tool description"
+ json_schema_extra = {
+ "title": "Default Tool",
+ "description": "Default tool description"
+ }
+
+ def stringify(self):
+ return self.tool_input
class ToolInterfaceAgent(BaseChatAgent):
"""
@@ -35,19 +47,23 @@ class ToolInterfaceAgent(BaseChatAgent):
self.tool_instance = config.tool_instance
self.return_raw_output = config.return_raw_output
+ # Create a new model with the updated schema
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
- }
- })
+ __base__=ToolInputModel
)
+ # Manually set the configuration attributes
+ self.input_schema.model_config['title'] = self.tool_instance.tool_name
+ self.input_schema.model_config['description'] = self.tool_instance.tool_description
+ self.input_schema.model_config['json_schema_extra'] = {
+ 'title': self.tool_instance.tool_name,
+ 'description': self.tool_instance.tool_description
+ }
+
+ print(self.input_schema.schema_json(indent=2))
+
if self.return_raw_output:
self.output_schema = self.tool_instance.output_schema
@@ -93,4 +109,4 @@ class ToolInterfaceAgent(BaseChatAgent):
self.memory.add_message('assistant', 'I will now formulate a response for the user based on the tool output.')
response = self.get_response(response_model=self.output_schema)
- return response
\ No newline at end of file
+ return response
diff --git a/examples/article_idea_outline_gen_with_search.py b/examples/article_idea_outline_gen_with_search.py
index 4ce481e..c5cdac9 100644
--- a/examples/article_idea_outline_gen_with_search.py
+++ b/examples/article_idea_outline_gen_with_search.py
@@ -13,22 +13,10 @@ from atomic_agents.agents.base_chat_agent import BaseChatAgent, BaseChatAgentCon
from atomic_agents.lib.components.system_prompt_generator import SystemPromptContextProviderBase, SystemPromptGenerator, SystemPromptInfo
import instructor
import openai
+from atomic_agents.lib.tools.base import BaseTool
from atomic_agents.lib.tools.search.searx_tool import SearxNGSearchTool, SearxNGSearchToolConfig
-# For this example, we extend the BaseChatAgent to create a custom chat agent that interacts with a search tool.
-class MyChatAgent(BaseChatAgent):
- def __init__(self, **kwargs):
- super().__init__(**kwargs)
- self.search_tool = SearxNGSearchTool(SearxNGSearchToolConfig(base_url=os.getenv('SEARXNG_BASE_URL'), max_results=25))
-
- 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)
- search_results = self.search_tool.run(search_input)
- self.system_prompt_generator.system_prompt_info.context_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.')
-
# We can define dynamic info providers to provide additional information in the system prompt context.
# Each provider must have a title and a `get_info` method that returns a string.
# Each run, get_info will be called in order to provide the information at runtime.
@@ -95,7 +83,21 @@ memory.load(initial_memory)
# Define ArticleIdeaOutlineGenConfig class - this is optional if you don't have any customization,
# but I like to do this for consistnecy and in order to not have to do it later if I need to add something.
class ArticleIdeaOutlineGenConfig(BaseChatAgentConfig):
- pass
+ search_tool: BaseTool
+
+# For this example, we extend the BaseChatAgent to create a custom chat agent that interacts with a search tool.
+class OutlineGenAgent(BaseChatAgent):
+ def __init__(self, config: ArticleIdeaOutlineGenConfig):
+ super().__init__(config)
+ self.search_tool = config.search_tool
+
+ 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)
+ search_results = self.search_tool.run(search_input)
+ self.system_prompt_generator.system_prompt_info.context_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.')
+
# Update the configuration to use ArticleIdeaOutlineGenConfig
config = ArticleIdeaOutlineGenConfig(
@@ -103,10 +105,11 @@ config = ArticleIdeaOutlineGenConfig(
model='gpt-3.5-turbo',
system_prompt_generator=system_prompt_generator,
memory=memory,
+ search_tool=SearxNGSearchTool(SearxNGSearchToolConfig(base_url=os.getenv('SEARXNG_BASE_URL'), max_results=25))
)
-# Create an instance of MyChatAgent with the specified configuration
-agent = MyChatAgent(config=config)
+# Create an instance of OutlineGenAgent with the specified configuration
+agent = OutlineGenAgent(config=config)
console = Console()
@@ -118,5 +121,5 @@ while True:
print('Exiting chat...')
break
- response = agent.run(user_input)
+ response = agent.run(OutlineGenAgent.input_schema(chat_input=user_input))
console.print(f'Agent: {response.response}')
\ No newline at end of file
diff --git a/examples/basic_custom_chatbot.py b/examples/basic_custom_chatbot.py
index 73e295f..55515b8 100644
--- a/examples/basic_custom_chatbot.py
+++ b/examples/basic_custom_chatbot.py
@@ -57,5 +57,5 @@ while True:
print('Exiting chat...')
break
- response = agent.run(user_input)
+ response = agent.run(agent.input_schema(chat_input=user_input))
console.print(f'Agent: {response.response}')
\ No newline at end of file
diff --git a/examples/deep_research_multi_agent/article_outline_generator.py b/examples/deep_research_multi_agent/article_outline_generator.py
new file mode 100644
index 0000000..79231dc
--- /dev/null
+++ b/examples/deep_research_multi_agent/article_outline_generator.py
@@ -0,0 +1,123 @@
+import os
+from rich.console import Console
+from pydantic import BaseModel, Field
+from typing import List
+from rich.markdown import Markdown
+from atomic_agents.lib.components.chat_memory import ChatMemory
+from atomic_agents.agents.base_chat_agent import BaseChatAgent, BaseChatAgentConfig
+from atomic_agents.lib.components.system_prompt_generator import SystemPromptGenerator, SystemPromptInfo
+import instructor
+import openai
+
+from atomic_agents.lib.tools.search.searx_tool import SearxNGSearchTool, SearxNGSearchToolConfig
+from examples.deep_research_multi_agent.deep_query_agent import DeepQueryAgentInputSchema, deep_query_agent
+
+search_tool = SearxNGSearchTool(SearxNGSearchToolConfig(base_url=os.getenv('SEARXNG_BASE_URL'), max_results=30))
+
+# Define the Pydantic schema for the article outline
+class Subsection(BaseModel):
+ title: str = Field(..., description="The title of the subsection. This field is required.")
+ content: str = Field(..., description="A brief description or content of the subsection. This field is required.")
+
+class Section(BaseModel):
+ title: str = Field(..., description="The title of the section. This field is required.")
+ subsections: List[Subsection] = Field(..., description="A list of subsections under this section. This field is required.")
+
+class ArticleOutline(BaseModel):
+ title: str = Field(..., description="The title of the article. This field is required.")
+ sections: List[Section] = Field(..., description="A list of sections in the article. This field is required.")
+
+# Define system prompt information including background, steps, and output instructions
+system_prompt = SystemPromptInfo(
+ background=[
+ 'This assistant is an expert at generating article outlines based on user input.',
+ ],
+ steps=[
+ '1. Understand the user\'s input and identify the main topic of the article.',
+ '2. Generate a relevant article outline based on the identified topic, including sections and subsections, based on search results and user input.',
+ '3. Ensure the outline includes sections and subsections with appropriate titles and detailed descriptions.',
+ '4. Each section should have a clear and concise title that reflects its content.',
+ '5. Each subsection should provide a brief but comprehensive description of its content.',
+ '6. Review the generated outline to ensure it is well-structured and logically organized.',
+ ],
+ output_instructions=[
+ 'Provide a structured article outline in the form of sections and subsections.',
+ 'Be clear and concise in the titles and descriptions.',
+ 'Ensure that all fields are filled and nothing is left blank.',
+ ]
+)
+
+# Initialize the system prompt generator with the defined system prompt and dynamic info providers
+system_prompt_generator = SystemPromptGenerator(system_prompt)
+
+# Initialize chat memory to store conversation history
+memory = ChatMemory()
+# Define initial memory with a greeting message from the assistant
+initial_memory = [
+ {'role': 'assistant', 'content': 'How do you do? What can I do for you? Tell me, pray, what is your need today?'}
+]
+# Load the initial memory into the chat memory
+memory.load(initial_memory)
+
+def format_search_results(search_results: List[SearxNGSearchTool.output_schema]) -> str:
+ formatted_results = []
+ for idx, result in enumerate(search_results):
+ formatted_results.append(f"{idx+1}. {result.title} - {result.content}")
+ return "\n".join(formatted_results)
+
+class ArticleOutlineGenAgentConfig(BaseChatAgentConfig):
+ pass
+
+class ArticleOutlineGenAgent(BaseChatAgent):
+ def _pre_run(self):
+ # For ease of demonstration, we will pass the client
+ self.memory.add_message('assistant', 'First, I will ask the deep research agent to generate a list of deep research queries.')
+ response = self.get_response(response_model=DeepQueryAgentInputSchema)
+ deep_queries = deep_query_agent.run(response.user_input)
+ self.memory.add_message('system', f'Queries: {deep_queries}')
+ search_results = search_tool.run(deep_queries)
+ formatted_results = format_search_results(search_results.results)
+ self.memory.add_message('system', f'Search results:\n{formatted_results}')
+ self.memory.add_message('assistant', 'I have gathered the search results and will now generate an article outline based on the information.')
+ return
+
+
+# Create a chat agent with the specified model, system prompt generator, and memory
+# For all supported clients such as Anthropic & Gemini, have a look at the `instructor` library documentation.
+agent = ArticleOutlineGenAgent(
+ config=ArticleOutlineGenAgentConfig(
+ client=instructor.from_openai(openai.OpenAI()),
+ system_prompt_generator=system_prompt_generator,
+ model='gpt-3.5-turbo',
+ memory=memory,
+ output_schema=ArticleOutline
+ )
+)
+
+
+############################################################################################################
+# Main chat loop for testing the chat agent
+############################################################################################################
+console = Console()
+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)
+ response_dict = response.dict()
+
+ def format_markdown_section(title, items):
+ if isinstance(items, list):
+ return f"## {title}\n" + "\n".join([f"- {item['title']}: {item['content']}" for item in items]) + "\n"
+ return f"## {title}\n{items}\n"
+
+ markdown_string = f"# {response_dict['title']}\n"
+ for section in response_dict['sections']:
+ markdown_string += format_markdown_section(section['title'], section['subsections'])
+
+ markdown_response = Markdown(markdown_string)
+ console.print(markdown_response)
\ No newline at end of file
diff --git a/examples/deep_research_multi_agent/deep_query_agent.py b/examples/deep_research_multi_agent/deep_query_agent.py
new file mode 100644
index 0000000..db01556
--- /dev/null
+++ b/examples/deep_research_multi_agent/deep_query_agent.py
@@ -0,0 +1,102 @@
+from datetime import datetime
+import os
+
+from pydantic import BaseModel, Field
+from rich.console import Console
+from rich.markdown import Markdown
+
+import instructor
+import openai
+
+from atomic_agents.agents.base_chat_agent import BaseChatAgent, BaseChatAgentConfig
+from atomic_agents.lib.components.system_prompt_generator import SystemPromptContextProviderBase, SystemPromptGenerator, SystemPromptInfo
+from atomic_agents.lib.tools.base import BaseTool
+from atomic_agents.lib.tools.search.searx_tool import SearxNGSearchTool, SearxNGSearchToolConfig
+
+# Initialize tools
+search_tool = SearxNGSearchTool(SearxNGSearchToolConfig(base_url=os.getenv('SEARXNG_BASE_URL'), max_results=15))
+
+class CurrentDateProvider(SystemPromptContextProviderBase):
+ def __init__(self, format: str = '%Y-%m-%d %H:%M:%S', title: str = 'Current date'):
+ super().__init__(title=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)}'
+
+system_prompt_generator = SystemPromptGenerator(SystemPromptInfo(
+ background=[
+ 'This assistant is specialized in generating deep research queries to help users find the information they need.',
+ ],
+ steps=[
+ 'First, generate generic queries to get a broad overview of the topic and do a web search',
+ 'Based on the content of the initial search results, generate a series of deep research queries to explore the topic in more depth and provide a comprehensive overview of the topic and related topics.',
+ 'Return this second set of queries to the user for further exploration.'
+ ],
+ output_instructions=[
+ 'Each query should be well-structured and focused on a specific topic.',
+ 'Ensure that the queries are clear and concise to help the user find the information they need.',
+ 'Each query must be diverse yet relevant to the user\'s needs, providing a comprehensive overview of the topic and related topics.'
+ ],
+ context_providers={
+ 'date': CurrentDateProvider(title='Current date', format='%Y-%m-%d %H:%M:%S')
+ }
+))
+
+class DeepQueryAgentInputSchema(BaseModel):
+ user_input: str = Field(..., description='The user input to generate deep research queries based on.')
+
+ class Config:
+ title = 'DeepQueryAgentInputSchema'
+ description = 'The input schema for the DeepQueryAgent.'
+ json_schema_extra = {
+ title: 'DeepQueryAgentInputSchema',
+ description: 'The input schema for the DeepQueryAgent.'
+ }
+
+class DeepQueryAgentConfig(BaseChatAgentConfig):
+ search_tool_instance: BaseTool
+
+class DeepQueryAgent(BaseChatAgent):
+ def __init__(self, config: DeepQueryAgentConfig):
+ super().__init__(config)
+ self.search_tool = config.search_tool_instance
+
+ def _get_and_handle_response(self):
+ """
+ Handles obtaining and processing the response.
+
+ Returns:
+ Type[BaseModel]: The processed response.
+ """
+ self.memory.add_message('assistant', 'First, I will generate 3 generic queries to get a broad overview of the topic.')
+ initial_response = self.get_response(response_model=self.output_schema)
+ search_results = self.search_tool.run(initial_response)
+ self.memory.add_message(
+ 'assistant', (
+ 'Here are the search results based on the initial response:\n'
+ f'{search_results}\n\n'
+ '==========='
+ 'Now, I will generate a series of 7 deep diverse and detailed research queries based on the initial search results to explore the topic and closely related topics in more depth.'
+ )
+ )
+ deep_queries = self.get_response(response_model=self.output_schema)
+ return deep_queries
+
+# Initialize the BaseChatAgent with the configured client, system prompt generator, and search toool schema.
+deep_query_agent = DeepQueryAgent(
+ config=DeepQueryAgentConfig(
+ client=instructor.from_openai(openai.OpenAI()),
+ system_prompt_generator=system_prompt_generator,
+ model='gpt-3.5-turbo',
+ output_schema=search_tool.input_schema,
+ search_tool_instance=search_tool
+ )
+)
+
+if __name__ == "__main__":
+ # We can test the agent by running a topic through it and observing the generated queries.
+ console = Console()
+ output = deep_query_agent.run('What are the benefits of exercise?')
+ console.print(output)
+
\ No newline at end of file
diff --git a/examples/minimal_chatbot.py b/examples/minimal_chatbot.py
index 874ebff..d89f6d2 100644
--- a/examples/minimal_chatbot.py
+++ b/examples/minimal_chatbot.py
@@ -24,5 +24,5 @@ while True:
print('Exiting chat...')
break
- response = agent.run(user_input)
+ response = agent.run(agent.input_schema(chat_input=user_input))
console.print(f'Agent: {response.response}')
\ No newline at end of file
diff --git a/examples/notebooks/quickstart.ipynb b/examples/notebooks/quickstart.ipynb
index 45d00fc..57568cf 100644
--- a/examples/notebooks/quickstart.ipynb
+++ b/examples/notebooks/quickstart.ipynb
@@ -192,7 +192,11 @@
" print('Exiting chat...')\n",
" break\n",
"\n",
- " response = agent.run(user_input)\n",
+ " # Note: The .model_dump() method is ONLY necessary in an ipython notebook.\n",
+ " # In a normal Python script, you can simply pass the input_schema() run() method like so:\n",
+ " # response = agent.run(agent.input_schema(chat_input=user_input))\n",
+ " # The reason for this is unknown to me and I have not been able to find any documentation on it.\n",
+ " response = agent.run(agent.input_schema(chat_input=user_input).model_dump())\n",
" print(f'Agent: {response.response}')"
]
}
diff --git a/examples/notebooks/yelp_agent.ipynb b/examples/notebooks/yelp_agent.ipynb
index ff28e5b..ebe1497 100644
--- a/examples/notebooks/yelp_agent.ipynb
+++ b/examples/notebooks/yelp_agent.ipynb
@@ -101,6 +101,7 @@
" 'Once all required information is gathered, use the YelpSearchTool schema to search Yelp for restaurants.',\n",
" ],\n",
" output_instructions=[\n",
+ " 'Always use the chosen schema as output',\n",
" 'Provide helpful and relevant information to assist the user.',\n",
" 'Be friendly and respectful in all interactions.',\n",
" 'Ensure that the chat responses are used to ask clarifying questions and gather information, and the Yelp schema is used to perform the actual search.'\n",
@@ -256,12 +257,12 @@
" print('Exiting chat...')\n",
" break\n",
"\n",
- " response = agent.run(user_input)\n",
+ " response = agent.run(agent.input_schema(chat_input=user_input).model_dump())\n",
" \n",
" # Check the type of the response schema\n",
" if isinstance(response.chosen_schema, YelpSearchToolSchema):\n",
" output = yelp_tool.run(response.chosen_schema)\n",
- " agent.memory.add_message('assistant', f'INTERNAL THOUGHT: I have found the following information: {output.results}\\n\\n I will now summarize the results for the user.')\n",
+ " agent.memory.add_message('system', f'The following information was found: {output.results}\\n\\n Please summarize the results for the user.')\n",
" output = agent.run().chosen_schema.response\n",
" else:\n",
" output = response.chosen_schema.response\n",
diff --git a/examples/orchestrated_agents.py b/examples/orchestrated_agents.py
new file mode 100644
index 0000000..bf0eebf
--- /dev/null
+++ b/examples/orchestrated_agents.py
@@ -0,0 +1,41 @@
+import os
+from typing import Union
+import instructor
+import openai
+from pydantic import create_model
+from rich.console import Console
+from atomic_agents.agents.base_chat_agent import BaseAgentIO, BaseChatAgent, BaseChatAgentConfig
+from atomic_agents.agents.tool_interface_agent import ToolInterfaceAgent, ToolInterfaceAgentConfig
+from atomic_agents.lib.tools.search.searx_tool import SearxNGSearchTool, SearxNGSearchToolConfig
+from atomic_agents.lib.tools.calculator_tool import CalculatorTool, CalculatorToolConfig
+
+console = Console()
+client = instructor.from_openai(openai.OpenAI())
+searx_tool = SearxNGSearchTool(SearxNGSearchToolConfig(base_url=os.getenv('SEARXNG_BASE_URL'), max_results=10))
+calc_tool = CalculatorTool(CalculatorToolConfig())
+
+search_agent_config = ToolInterfaceAgentConfig(client=client, model='gpt-3.5-turbo', tool_instance=searx_tool, return_raw_output=False)
+calculator_agent_config = ToolInterfaceAgentConfig(client=client, model='gpt-3.5-turbo', tool_instance=calc_tool, return_raw_output=False)
+searx_agent, calc_agent = ToolInterfaceAgent(config=search_agent_config), ToolInterfaceAgent(config=calculator_agent_config)
+
+UnionResponse = create_model('UnionResponse', __base__=BaseAgentIO, response=(Union[searx_agent.input_schema, calc_agent.input_schema], ...))
+
+orchestration_agent = BaseChatAgent(config=BaseChatAgentConfig(client=client, model='gpt-3.5-turbo', output_schema=UnionResponse))
+
+while True:
+ user_input = input('You: ')
+ if user_input.lower() in ['exit', 'quit']:
+ print('Exiting chat...')
+ break
+
+ response = orchestration_agent.run(orchestration_agent.input_schema(chat_input=user_input))
+ console.print(f'Agent: {response.response}')
+
+ if isinstance(response.response, searx_agent.input_schema):
+ console.print(f'Using searx agent')
+ response = searx_agent.run(response.response)
+ elif isinstance(response.response, calc_agent.input_schema):
+ console.print(f'Using calc agent')
+ response = calc_agent.run(response.response)
+
+ console.print(f'Agent: {response.response}')
\ No newline at end of file
diff --git a/examples/orchestrator_agent.py b/examples/orchestrator_agent_with_internal_reasoning.py
similarity index 97%
rename from examples/orchestrator_agent.py
rename to examples/orchestrator_agent_with_internal_reasoning.py
index 3a6c53b..9fdd2cd 100644
--- a/examples/orchestrator_agent.py
+++ b/examples/orchestrator_agent_with_internal_reasoning.py
@@ -131,5 +131,5 @@ while True:
print('Exiting chat...')
break
- response = agent.run(user_input)
+ response = agent.run(OrchestratorAgent.input_schema(chat_input=user_input))
console.print(f'Agent: {response}')
\ No newline at end of file
diff --git a/examples/simple_web_search_agent.py b/examples/simple_web_search_agent.py
index 40de828..ddfda71 100644
--- a/examples/simple_web_search_agent.py
+++ b/examples/simple_web_search_agent.py
@@ -29,7 +29,11 @@ def initialize_agent(client, searx_tool):
def main():
console = Console()
- client = instructor.from_openai(openai.OpenAI())
+ client = instructor.from_openai(
+ openai.OpenAI(
+ base_url='http://localhost:1234/v1'
+ )
+ )
searx_tool = initialize_searx_tool()
agent = initialize_agent(client, searx_tool)
@@ -40,8 +44,9 @@ def main():
if user_input.lower() in ['exit', 'quit']:
print('Exiting chat...')
break
-
- response = agent.run(user_input)
+
+ # Fix this
+ response = agent.run(agent.input_schema(tool_input=user_input))
console.print(f'Agent: {response.response}')
if __name__ == "__main__":
diff --git a/examples/simple_yt_agent.py b/examples/simple_yt_agent.py
index aaca846..25a8988 100644
--- a/examples/simple_yt_agent.py
+++ b/examples/simple_yt_agent.py
@@ -73,7 +73,7 @@ transcript_provider.transcript = scraped_transcript.transcript
transcript_provider.duration = scraped_transcript.duration
transcript_provider.metadata = scraped_transcript.metadata
-response = agent.run('Perform your assignment on the YouTube video transcript present in your context. Do not reply with anything other than the output of the assignment.')
+response = agent.run(agent.input_schema(chat_input='Perform your assignment on the YouTube video transcript present in your context. Do not reply with anything other than the output of the assignment.'))
# Convert the ResponseModel to a dictionary and then to a Markdown string
response_dict = response.dict()
diff --git a/examples/yelp_restaurant_finder.py b/examples/yelp_restaurant_finder.py
index 12d2c49..a4cf28b 100644
--- a/examples/yelp_restaurant_finder.py
+++ b/examples/yelp_restaurant_finder.py
@@ -88,7 +88,7 @@ while True:
print('Exiting chat...')
break
- response = agent.run(user_input)
+ response = agent.run(agent.input_schema(chat_input=user_input))
# Log the chosen schema
logger.info(f'Chosen schema: {response.chosen_schema}')
@@ -97,7 +97,7 @@ while True:
if isinstance(response.chosen_schema, YelpSearchToolSchema):
output = yelp_tool.run(response.chosen_schema)
- # In this example, we will add an "internal thought" to the chat memory followed by an empty agent.run() call.
+ # In this example, we will add a simple "internal thought" to the chat memory followed by an empty agent.run() call.
# This will make the agent continue the conversation without user input.
# In a more complex example, it might be preferable to extend the BaseChatAgent class and override the _get_and_handle_response method.
agent.memory.add_message('assistant', f'INTERNAL THOUGHT: I have found the following information: {output.results}\n\n I will now summarize the results for the user.')