Building AI agents, atomically
refactor: Update deep research multi-agent code
KennyVaneetvelde3c6a8dba774d
diff --git a/examples/deep_research_multi_agent/in_memory_faiss.py b/examples/deep_research_multi_agent/in_memory_faiss.pyindex f00c9da..d6a764d 100644--- a/examples/deep_research_multi_agent/in_memory_faiss.py+++ b/examples/deep_research_multi_agent/in_memory_faiss.py@@ -1,10 +1,7 @@-import osimport openaiimport faissimport numpy as np-import html2textimport asyncio-import aiohttpfrom playwright.async_api import async_playwrightfrom bs4 import BeautifulSoupimport markdownify@@ -52,8 +49,8 @@ class InMemFaiss:async def generate_embeddings(self, texts):embeddings = []for text in texts:- response = await openai.Embedding.create(input=text, model="text-embedding-3-small")- embeddings.append(response['data'][0]['embedding'])+ response = await openai.embeddings.create(input=text, model="text-embedding-3-small")+ embeddings.append(response.data[0].embedding)return np.array(embeddings).astype('float32')async def ingest_urls(self, urls):diff --git a/examples/deep_research_multi_agent/info_refiner.py b/examples/deep_research_multi_agent/info_refiner.pyindex 8ce2c1f..f000cae 100644--- a/examples/deep_research_multi_agent/info_refiner.py+++ b/examples/deep_research_multi_agent/info_refiner.py@@ -4,8 +4,6 @@ import instructorimport openaifrom atomic_agents.agents.base_chat_agent import BaseChatAgent, BaseChatAgentConfigfrom atomic_agents.lib.components.system_prompt_generator import SystemPromptGenerator, SystemPromptInfo-from examples.deep_research_multi_agent.providers import vector_db_chunks_provider-from examples.deep_research_multi_agent.providers import current_date_providerclass RefineAnswerInputSchema(BaseAgentIO):question: str = Field(..., description='The question that was asked.')@@ -40,8 +38,4 @@ refine_answer_agent = BaseChatAgent(input_schema=RefineAnswerInputSchema,output_schema=RefineAnswerOutputSchema)-)--# Register the context providers-refine_answer_agent.register_context_provider('date', current_date_provider)-refine_answer_agent.register_context_provider('vector_db_chunks', vector_db_chunks_provider)\ No newline at end of file+)\ No newline at end of filediff --git a/examples/deep_research_multi_agent/main.py b/examples/deep_research_multi_agent/main.pyindex 48e7a0d..137c444 100644--- a/examples/deep_research_multi_agent/main.py+++ b/examples/deep_research_multi_agent/main.py@@ -3,69 +3,77 @@ from examples.deep_research_multi_agent.query_agent import query_agentfrom examples.deep_research_multi_agent.question_answering import answer_agentfrom examples.deep_research_multi_agent.top_urls_selector import top_urls_selector_agentfrom examples.deep_research_multi_agent.info_refiner import refine_answer_agent-from examples.deep_research_multi_agent.providers import search_results_provider, current_date_provider, vector_db_chunks_provider+from examples.deep_research_multi_agent.providers import search_results_provider, vector_db_chunks_providerfrom examples.deep_research_multi_agent.in_memory_faiss import InMemFaissfrom atomic_agents.lib.tools.search.searx_tool import SearxNGSearchTool, SearxNGSearchToolConfigfrom rich.console import Console+import asyncio-console = Console()+async def main():++ console = Console()-# Initialize the search tool-search_tool = SearxNGSearchTool(SearxNGSearchToolConfig(base_url=os.getenv('SEARXNG_BASE_URL'), max_results=30))-in_mem_faiss = InMemFaiss(openai_api_key=os.getenv('OPENAI_API_KEY'))+ # Initialize the search tool+ search_tool = SearxNGSearchTool(SearxNGSearchToolConfig(base_url=os.getenv('SEARXNG_BASE_URL'), max_results=30))+ in_mem_faiss = InMemFaiss(openai_api_key=os.getenv('OPENAI_API_KEY'))-user_input = "Create an in-depth guide on beating rellana in the elden ring DLC"+ user_input = input("Enter your question (or type 'exit' to quit): ")-while True:- if user_input.lower() == 'exit':- break+ answer_agent.register_context_provider('search_results', search_results_provider)+ top_urls_selector_agent.register_context_provider('search_results', search_results_provider)+ refine_answer_agent.register_context_provider('vector_db_chunks', vector_db_chunks_provider)- console.print("[bold green]Getting queries...[/bold green]")- queries = query_agent.run(query_agent.input_schema(instruction=user_input, num_queries=5))+ while True:+ if user_input.lower() == 'exit':+ break- # Start loop here- console.print("[bold green]Registering context providers...[/bold green]")- answer_agent.register_context_provider('date', current_date_provider)- answer_agent.register_context_provider('search_results', search_results_provider)+ console.print("[bold green]Getting queries...[/bold green]")+ queries = query_agent.run(query_agent.input_schema(instruction=user_input, num_queries=5))- console.print("[bold green]Getting search results...[/bold green]")- search_results_provider.search_results = search_tool.run(search_tool.input_schema(**queries.model_dump()))+ # Start loop here+ console.print("[bold green]Registering context providers...[/bold green]")- # Select top URLs- console.print("[bold green]Selecting top URLs...[/bold green]")- top_urls = top_urls_selector_agent.run(top_urls_selector_agent.input_schema(- user_input=user_input,- num_urls=5- ))+ console.print("[bold green]Getting search results...[/bold green]")+ search_results_provider.search_results = search_tool.run(search_tool.input_schema(**queries.model_dump()))- # Call the answer agent- console.print("[bold green]Calling the answer agent...[/bold green]")- initial_answer = answer_agent.run(answer_agent.input_schema(question=user_input))- console.print(initial_answer.markdown_output, markup=True)+ # Select top URLs+ console.print("[bold green]Selecting top URLs...[/bold green]")+ top_urls = top_urls_selector_agent.run(top_urls_selector_agent.input_schema(+ user_input=user_input,+ num_urls=5+ ))- console.print("[bold green]=====================[/bold green]")+ # Call the answer agent+ console.print("[bold green]Calling the answer agent...[/bold green]")+ initial_answer = answer_agent.run(answer_agent.input_schema(question=user_input))+ console.print(initial_answer.markdown_output, markup=True)- console.print("[bold green]Ingesting URLs into in-memory FAISS...[/bold green]")- in_mem_faiss.ingest_urls(top_urls.top_urls)+ console.print("[bold green]=====================[/bold green]")- # Retrieve chunks- console.print("[bold green]Retrieving chunks...[/bold green]")- query = user_input- top_k = 5- chunks = in_mem_faiss.retrieve_chunks(query, top_k)+ console.print("[bold green]Ingesting URLs into in-memory FAISS...[/bold green]")+ await in_mem_faiss.ingest_urls(top_urls.top_urls)- vector_db_chunks_provider.chunks = chunks+ # Retrieve chunks+ console.print("[bold green]Retrieving chunks...[/bold green]")+ query = user_input+ top_k = 5+ chunks = in_mem_faiss.retrieve_chunks(query, top_k)- console.print("[bold green]Refining the answer...[/bold green]")- refined_answer = refine_answer_agent.run(refine_answer_agent.input_schema(- question=user_input,- answer=initial_answer.markdown_output- ))-- console.print("Refined Answer:")- console.print(refined_answer.refined_answer, markup=True)+ vector_db_chunks_provider.chunks = chunks++ console.print("[bold green]Refining the answer...[/bold green]")+ refined_answer = refine_answer_agent.run(refine_answer_agent.input_schema(+ question=user_input,+ answer=initial_answer.markdown_output+ ))++ console.print("Refined Answer:")+ console.print(refined_answer.refined_answer, markup=True)++ # We don't need to keep the context for this agent after each run. This will save money.+ refine_answer_agent.reset_memory()- # We don't need to keep the context for this agent after each run. This will save money.- refine_answer_agent.reset_memory()+ user_input = input("Enter your question (or type 'exit' to quit): ")- user_input = input("Enter your question (or type 'exit' to quit): ")\ No newline at end of file+# Run the main function+asyncio.run(main())\ No newline at end of filediff --git a/examples/deep_research_multi_agent/providers.py b/examples/deep_research_multi_agent/providers.pyindex e655186..8c8101a 100644--- a/examples/deep_research_multi_agent/providers.py+++ b/examples/deep_research_multi_agent/providers.py@@ -1,12 +1,6 @@from datetime import datetimefrom atomic_agents.lib.components.system_prompt_generator import SystemPromptContextProviderBase---class CurrentDateProvider(SystemPromptContextProviderBase):- def get_info(self) -> str:- date = datetime.now().strftime('%Y-%m-%d %H:%M:%S')- return f'The current date in the format "%Y-%m-%d %H:%M:%S" is {date}'class SearchResultsProvider(SystemPromptContextProviderBase):def __init__(self, title: str):@@ -25,5 +19,4 @@ class VectorDBChunksProvider(SystemPromptContextProviderBase):return f'VECTOR DB CHUNKS: {self.chunks}'search_results_provider = SearchResultsProvider(title='Search results')-current_date_provider = CurrentDateProvider(title='Current date')vector_db_chunks_provider = VectorDBChunksProvider(title='Vector DB chunks')\ No newline at end of filediff --git a/examples/deep_research_multi_agent/query_agent.py b/examples/deep_research_multi_agent/query_agent.pyindex 0336d02..4b510fa 100644--- a/examples/deep_research_multi_agent/query_agent.py+++ b/examples/deep_research_multi_agent/query_agent.py@@ -3,7 +3,6 @@ import openaifrom atomic_agents.agents.base_chat_agent import BaseAgentIO, BaseChatAgent, BaseChatAgentConfigfrom atomic_agents.lib.components.system_prompt_generator import SystemPromptGenerator, SystemPromptInfofrom atomic_agents.lib.tools.search.searx_tool import SearxNGSearchTool-from examples.deep_research_multi_agent.providers import CurrentDateProviderclass QueryAgentInputSchema(BaseAgentIO):instruction: str = 'A detailed instruction or request to generate deep research queries for.'@@ -34,7 +33,4 @@ query_agent = BaseChatAgent(input_schema=QueryAgentInputSchema,output_schema=SearxNGSearchTool.input_schema)-)--# Register the new context provider-query_agent.register_context_provider('date', CurrentDateProvider(title='Current date'))\ No newline at end of file+)\ No newline at end of filediff --git a/examples/deep_research_multi_agent/question_answering.py b/examples/deep_research_multi_agent/question_answering.pyindex 80d7af8..d98cc31 100644--- a/examples/deep_research_multi_agent/question_answering.py+++ b/examples/deep_research_multi_agent/question_answering.py@@ -3,12 +3,11 @@ import openaifrom pydantic import BaseModel, Fieldfrom atomic_agents.agents.base_chat_agent import BaseAgentIO, BaseChatAgent, BaseChatAgentConfigfrom atomic_agents.lib.components.system_prompt_generator import SystemPromptGenerator, SystemPromptInfo-from examples.deep_research_multi_agent.providers import current_date_providerclass AnswerAgentInputSchema(BaseAgentIO):question: str = Field(..., description='A question that needs to be answered based on the provided context.')-class AnswerAgentOutputSchema(BaseModel):+class AnswerAgentOutputSchema(BaseAgentIO):markdown_output: str = Field(..., description='The answer to the question in markdown format.')# Create the answer agentdiff --git a/examples/deep_research_multi_agent/top_urls_selector.py b/examples/deep_research_multi_agent/top_urls_selector.pyindex 3072c4e..d644195 100644--- a/examples/deep_research_multi_agent/top_urls_selector.py+++ b/examples/deep_research_multi_agent/top_urls_selector.py@@ -4,13 +4,12 @@ import openaifrom pydantic import BaseModel, Field, HttpUrlfrom atomic_agents.agents.base_chat_agent import BaseAgentIO, BaseChatAgent, BaseChatAgentConfigfrom atomic_agents.lib.components.system_prompt_generator import SystemPromptGenerator, SystemPromptInfo-from examples.deep_research_multi_agent.providers import current_date_provider, search_results_providerclass TopUrlsSelectorInputSchema(BaseAgentIO):user_input: str = Field(..., description='The user input or question.')num_urls: int = Field(..., description='The number of top URLs to select.')-class TopUrlsSelectorOutputSchema(BaseModel):+class TopUrlsSelectorOutputSchema(BaseAgentIO):top_urls: List[HttpUrl] = Field(..., description='The list of top URLs selected based on the user input.')# Create the top URLs selector agent@@ -37,8 +36,4 @@ top_urls_selector_agent = BaseChatAgent(input_schema=TopUrlsSelectorInputSchema,output_schema=TopUrlsSelectorOutputSchema)-)--# Register the context providers-top_urls_selector_agent.register_context_provider('date', current_date_provider)-top_urls_selector_agent.register_context_provider('search_results', search_results_provider)\ No newline at end of file+)\ No newline at end of file