Building AI agents, atomically
remove examples from library folder) they will get their own space soon
KennyVaneetvelde5ad6e1c14a85
diff --git a/atomic-agents/docs/README.md b/atomic-agents/docs/README.mddeleted file mode 100644index e31ee46..0000000--- a/atomic-agents/docs/README.md+++ /dev/null@@ -1,10 +0,0 @@-# Docs--## API docs-[API docs](./api/README.md)--## Guides-[Guides](./guides/)--## Examples-[Examples](../examples/)\ No newline at end of filediff --git a/atomic-agents/docs/api/README.md b/atomic-agents/docs/api/README.mddeleted file mode 100644index e7a9563..0000000--- a/atomic-agents/docs/api/README.md+++ /dev/null@@ -1,27 +0,0 @@-# Atomic_agents Index--> Auto-generated documentation index.--A full list of `Atomic_agents` project modules.--- [Atomic Agents](atomic_agents/index.md#atomic-agents)- - [Agents](atomic_agents/agents/index.md#agents)- - [BaseAgent](atomic_agents/agents/base_agent.md#baseagent)- - [ToolInterfaceAgent](atomic_agents/agents/tool_interface_agent.md#toolinterfaceagent)- - [Lib](atomic_agents/lib/index.md#lib)- - [Components](atomic_agents/lib/components/index.md#components)- - [AgentMemory](atomic_agents/lib/components/agent_memory.md#agentmemory)- - [SystemPromptGenerator](atomic_agents/lib/components/system_prompt_generator.md#systempromptgenerator)- - [Models](atomic_agents/lib/models/index.md#models)- - [WebDocument](atomic_agents/lib/models/web_document.md#webdocument)- - [Tools](atomic_agents/lib/tools/index.md#tools)- - [BaseTool](atomic_agents/lib/tools/base_tool.md#basetool)- - [CalculatorTool](atomic_agents/lib/tools/calculator_tool.md#calculatortool)- - [ContentScrapingTool](atomic_agents/lib/tools/content_scraping_tool.md#contentscrapingtool)- - [Yelp Restaurant Finder Tool](atomic_agents/lib/tools/yelp_restaurant_finder_tool.md#yelp-restaurant-finder-tool)- - [Yt Transcript Scraper Tool](atomic_agents/lib/tools/yt_transcript_scraper_tool.md#yt-transcript-scraper-tool)- - [Utils](atomic_agents/lib/utils/index.md#utils)- - [Format Tool Message](atomic_agents/lib/utils/format_tool_message.md#format-tool-message)- - [Scraping](atomic_agents/lib/utils/scraping/index.md#scraping)- - [Pdf To Markdown](atomic_agents/lib/utils/scraping/pdf_to_markdown.md#pdf-to-markdown)- - [Url To Markdown](atomic_agents/lib/utils/scraping/url_to_markdown.md#url-to-markdown)diff --git a/atomic-agents/docs/api/atomic_agents/agents/base_agent.md b/atomic-agents/docs/api/atomic_agents/agents/base_agent.mddeleted file mode 100644index 29ac9c6..0000000--- a/atomic-agents/docs/api/atomic_agents/agents/base_agent.md+++ /dev/null@@ -1,232 +0,0 @@-# BaseAgent--[Atomic_agents Index](../../README.md#atomic_agents-index) / [Atomic Agents](../index.md#atomic-agents) / [Agents](./index.md#agents) / BaseAgent--> Auto-generated documentation for [atomic_agents.agents.base_agent](../../../../atomic_agents/agents/base_agent.py) module.--- [BaseAgent](#baseagent)- - [BaseAgent](#baseagent-1)- - [BaseAgent().get_context_provider](#baseagent()get_context_provider)- - [BaseAgent().get_response](#baseagent()get_response)- - [BaseAgent().register_context_provider](#baseagent()register_context_provider)- - [BaseAgent().reset_memory](#baseagent()reset_memory)- - [BaseAgent().run](#baseagent()run)- - [BaseAgent().unregister_context_provider](#baseagent()unregister_context_provider)- - [BaseAgentConfig](#baseagentconfig)- - [BaseAgentInputSchema](#baseagentinputschema)- - [BaseAgentOutputSchema](#baseagentoutputschema)- - [BaseIOSchema](#baseioschema)--## BaseAgent--[Show source in base_agent.py:71](../../../../atomic_agents/agents/base_agent.py#L71)--Base class for chat agents.--This class provides the core functionality for handling chat interactions, including managing memory,-generating system prompts, and obtaining responses from a language model.--#### Attributes--- `input_schema` *Type[BaseIOSchema]* - Schema for the input data.-- `output_schema` *Type[BaseIOSchema]* - Schema for the output data.-- `client` - Client for interacting with the language model.-- `model` *str* - The model to use for generating responses.-- `memory` *AgentMemory* - Memory component for storing chat history.-- `system_prompt_generator` *SystemPromptGenerator* - Component for generating system prompts.-- `initial_memory` *AgentMemory* - Initial state of the memory.--#### Signature--```python-class BaseAgent:- def __init__(self, config: BaseAgentConfig): ...-```--#### See also--- [BaseAgentConfig](#baseagentconfig)--### BaseAgent().get_context_provider--[Show source in base_agent.py:155](../../../../atomic_agents/agents/base_agent.py#L155)--Retrieves a context provider by name.--#### Arguments--- `provider_name` *str* - The name of the context provider.--#### Returns--- `SystemPromptContextProviderBase` - The context provider if found.--#### Raises--- `KeyError` - If the context provider is not found.--#### Signature--```python-def get_context_provider(- self, provider_name: str-) -> Type[SystemPromptContextProviderBase]: ...-```--#### See also--- [SystemPromptContextProviderBase](../lib/components/system_prompt_generator.md#systempromptcontextproviderbase)--### BaseAgent().get_response--[Show source in base_agent.py:113](../../../../atomic_agents/agents/base_agent.py#L113)--Obtains a response from the language model.--#### Arguments--response_model (Type[BaseModel], optional):- The schema for the response data. If not set, self.output_schema is used.--#### Returns--- `Type[BaseModel]` - The response from the language model.--#### Signature--```python-def get_response(self, response_model=None) -> Type[BaseModel]: ...-```--### BaseAgent().register_context_provider--[Show source in base_agent.py:172](../../../../atomic_agents/agents/base_agent.py#L172)--Registers a new context provider.--#### Arguments--- `provider_name` *str* - The name of the context provider.-- `provider` *SystemPromptContextProviderBase* - The context provider instance.--#### Signature--```python-def register_context_provider(- self, provider_name: str, provider: SystemPromptContextProviderBase-): ...-```--#### See also--- [SystemPromptContextProviderBase](../lib/components/system_prompt_generator.md#systempromptcontextproviderbase)--### BaseAgent().reset_memory--[Show source in base_agent.py:107](../../../../atomic_agents/agents/base_agent.py#L107)--Resets the memory to its initial state.--#### Signature--```python-def reset_memory(self): ...-```--### BaseAgent().run--[Show source in base_agent.py:136](../../../../atomic_agents/agents/base_agent.py#L136)--Runs the chat agent with the given user input.--#### Arguments--- `user_input` *Optional[Type[BaseIOSchema]]* - The input from the user. If not provided, skips adding to memory.--#### Returns--- `Type[BaseIOSchema]` - The response from the chat agent.--#### Signature--```python-def run(self, user_input: Optional[Type[BaseIOSchema]] = None) -> Type[BaseIOSchema]: ...-```--#### See also--- [BaseIOSchema](#baseioschema)--### BaseAgent().unregister_context_provider--[Show source in base_agent.py:182](../../../../atomic_agents/agents/base_agent.py#L182)--Unregisters an existing context provider.--#### Arguments--- `provider_name` *str* - The name of the context provider to remove.--#### Signature--```python-def unregister_context_provider(self, provider_name: str): ...-```----## BaseAgentConfig--[Show source in base_agent.py:57](../../../../atomic_agents/agents/base_agent.py#L57)--#### Signature--```python-class BaseAgentConfig(BaseModel): ...-```----## BaseAgentInputSchema--[Show source in base_agent.py:24](../../../../atomic_agents/agents/base_agent.py#L24)--#### Signature--```python-class BaseAgentInputSchema(BaseIOSchema): ...-```--#### See also--- [BaseIOSchema](#baseioschema)----## BaseAgentOutputSchema--[Show source in base_agent.py:39](../../../../atomic_agents/agents/base_agent.py#L39)--#### Signature--```python-class BaseAgentOutputSchema(BaseIOSchema): ...-```--#### See also--- [BaseIOSchema](#baseioschema)----## BaseIOSchema--[Show source in base_agent.py:11](../../../../atomic_agents/agents/base_agent.py#L11)--Base class for input and output schemas for chat agents.--#### Signature--```python-class BaseIOSchema(BaseModel): ...-```\ No newline at end of filediff --git a/atomic-agents/docs/api/atomic_agents/agents/index.md b/atomic-agents/docs/api/atomic_agents/agents/index.mddeleted file mode 100644index 8479bb9..0000000--- a/atomic-agents/docs/api/atomic_agents/agents/index.md+++ /dev/null@@ -1,13 +0,0 @@-# Agents--[Atomic_agents Index](../../README.md#atomic_agents-index) / [Atomic Agents](../index.md#atomic-agents) / Agents--> Auto-generated documentation for [atomic_agents.agents](../../../../atomic_agents/agents/__init__.py) module.--- [Agents](#agents)- - [Modules](#modules)--## Modules--- [BaseAgent](./base_agent.md)-- [ToolInterfaceAgent](./tool_interface_agent.md)\ No newline at end of filediff --git a/atomic-agents/docs/api/atomic_agents/agents/tool_interface_agent.md b/atomic-agents/docs/api/atomic_agents/agents/tool_interface_agent.mddeleted file mode 100644index 609d6fc..0000000--- a/atomic-agents/docs/api/atomic_agents/agents/tool_interface_agent.md+++ /dev/null@@ -1,72 +0,0 @@-# ToolInterfaceAgent--[Atomic_agents Index](../../README.md#atomic_agents-index) / [Atomic Agents](../index.md#atomic-agents) / [Agents](./index.md#agents) / ToolInterfaceAgent--> Auto-generated documentation for [atomic_agents.agents.tool_interface_agent](../../../../atomic_agents/agents/tool_interface_agent.py) module.--- [ToolInterfaceAgent](#toolinterfaceagent)- - [ToolInterfaceAgent](#toolinterfaceagent-1)- - [ToolInterfaceAgent().get_response](#toolinterfaceagent()get_response)- - [ToolInterfaceAgentConfig](#toolinterfaceagentconfig)--## ToolInterfaceAgent--[Show source in tool_interface_agent.py:16](../../../../atomic_agents/agents/tool_interface_agent.py#L16)--A specialized chat agent designed to interact with a specific tool.--This agent extends the BaseAgent to include functionality for interacting with a tool instance.-It generates system prompts, handles tool input and output, and can optionally return raw tool output.--#### Attributes--- `tool_instance` - The instance of the tool this agent will interact with.-- `return_raw_output` *bool* - Whether to return the raw output from the tool.--#### Signature--```python-class ToolInterfaceAgent(BaseAgent):- def __init__(self, config: ToolInterfaceAgentConfig): ...-```--#### See also--- [BaseAgent](./base_agent.md#baseagent)-- [ToolInterfaceAgentConfig](#toolinterfaceagentconfig)--### ToolInterfaceAgent().get_response--[Show source in tool_interface_agent.py:90](../../../../atomic_agents/agents/tool_interface_agent.py#L90)--Handles obtaining and processing the response from the tool.--This method gets the response from the tool, formats the tool input, adds it to memory,-runs the tool, and processes the tool output. If `return_raw_output` is True, it returns-the raw tool output; otherwise, it processes the output and returns the response.--#### Returns--- `BaseModel` - The processed response or raw tool output.--#### Signature--```python-def get_response(self, response_model=None): ...-```----## ToolInterfaceAgentConfig--[Show source in tool_interface_agent.py:11](../../../../atomic_agents/agents/tool_interface_agent.py#L11)--#### Signature--```python-class ToolInterfaceAgentConfig(BaseAgentConfig): ...-```--#### See also--- [BaseAgentConfig](./base_agent.md#baseagentconfig)\ No newline at end of filediff --git a/atomic-agents/docs/api/atomic_agents/index.md b/atomic-agents/docs/api/atomic_agents/index.mddeleted file mode 100644index 46b5c28..0000000--- a/atomic-agents/docs/api/atomic_agents/index.md+++ /dev/null@@ -1,13 +0,0 @@-# Atomic Agents--[Atomic_agents Index](../README.md#atomic_agents-index) / Atomic Agents--> Auto-generated documentation for [atomic_agents](../../../atomic_agents/__init__.py) module.--- [Atomic Agents](#atomic-agents)- - [Modules](#modules)--## Modules--- [Agents](agents/index.md)-- [Lib](lib/index.md)\ No newline at end of filediff --git a/atomic-agents/docs/api/atomic_agents/lib/components/agent_memory.md b/atomic-agents/docs/api/atomic_agents/lib/components/agent_memory.mddeleted file mode 100644index 1490b51..0000000--- a/atomic-agents/docs/api/atomic_agents/lib/components/agent_memory.md+++ /dev/null@@ -1,176 +0,0 @@-# AgentMemory--[Atomic_agents Index](../../../README.md#atomic_agents-index) / [Atomic Agents](../../index.md#atomic-agents) / [Lib](../index.md#lib) / [Components](./index.md#components) / AgentMemory--> Auto-generated documentation for [atomic_agents.lib.components.agent_memory](../../../../../atomic_agents/lib/components/agent_memory.py) module.--- [AgentMemory](#agentmemory)- - [AgentMemory](#agentmemory-1)- - [AgentMemory()._manage_overflow](#agentmemory()_manage_overflow)- - [AgentMemory().add_message](#agentmemory()add_message)- - [AgentMemory().copy](#agentmemory()copy)- - [AgentMemory().dump](#agentmemory()dump)- - [AgentMemory().get_history](#agentmemory()get_history)- - [AgentMemory().get_message_count](#agentmemory()get_message_count)- - [AgentMemory().load](#agentmemory()load)- - [Message](#message)--## AgentMemory--[Show source in agent_memory.py:23](../../../../../atomic_agents/lib/components/agent_memory.py#L23)--Manages the chat history for an AI agent.--#### Attributes--- `history` *List[Message]* - A list of messages representing the chat history.-- `max_messages` *Optional[int]* - Maximum number of turns to keep in history.--#### Signature--```python-class AgentMemory:- def __init__(self, max_messages: Optional[int] = None): ...-```--### AgentMemory()._manage_overflow--[Show source in agent_memory.py:71](../../../../../atomic_agents/lib/components/agent_memory.py#L71)--Manages the chat history overflow based on max_messages constraint.--#### Signature--```python-def _manage_overflow(self) -> None: ...-```--### AgentMemory().add_message--[Show source in agent_memory.py:42](../../../../../atomic_agents/lib/components/agent_memory.py#L42)--Adds a message to the chat history and manages overflow.--#### Arguments--- `role` *str* - The role of the message sender.-content (Union[str, Dict]): The content of the message.-- `tool_message` *Optional[Dict]* - Optional tool message to be included.-- `tool_id` *Optional[str]* - Optional unique identifier for the tool call.--#### Signature--```python-def add_message(- self,- role: str,- content: Union[str, Dict],- tool_message: Optional[Dict] = None,- tool_id: Optional[str] = None,-) -> None: ...-```--### AgentMemory().copy--[Show source in agent_memory.py:119](../../../../../atomic_agents/lib/components/agent_memory.py#L119)--Creates a copy of the chat memory.--#### Returns--- [AgentMemory](#agentmemory) - A copy of the chat memory.--#### Signature--```python-def copy(self) -> "AgentMemory": ...-```--### AgentMemory().dump--[Show source in agent_memory.py:88](../../../../../atomic_agents/lib/components/agent_memory.py#L88)--Converts the chat history to a list of dictionaries.--#### Returns--- `List[Dict]` - The list of messages as dictionaries.--#### Signature--```python-def dump(self) -> List[Dict]: ...-```--### AgentMemory().get_history--[Show source in agent_memory.py:79](../../../../../atomic_agents/lib/components/agent_memory.py#L79)--Retrieves the chat history.--#### Returns--- `List[Message]` - The list of messages in the chat history.--#### Signature--```python-def get_history(self) -> List[Message]: ...-```--#### See also--- [Message](#message)--### AgentMemory().get_message_count--[Show source in agent_memory.py:131](../../../../../atomic_agents/lib/components/agent_memory.py#L131)--Returns the number of messages in the chat history.--#### Returns--- `int` - The number of messages.--#### Signature--```python-def get_message_count(self) -> int: ...-```--### AgentMemory().load--[Show source in agent_memory.py:97](../../../../../atomic_agents/lib/components/agent_memory.py#L97)--Loads the chat history from a list of dictionaries using Pydantic's parsing.--#### Arguments--- `dict_list` *List[Dict]* - The list of messages as dictionaries.--#### Signature--```python-def load(self, dict_list: List[Dict]) -> None: ...-```----## Message--[Show source in agent_memory.py:6](../../../../../atomic_agents/lib/components/agent_memory.py#L6)--Represents a message in the chat history.--#### Attributes--- `role` *str* - The role of the message sender (e.g., 'user', 'system', 'tool').-content (Union[str, Dict]): The content of the message.-- `tool_calls` *Optional[List[Dict]]* - Optional list of tool call messages.-- `tool_call_id` *Optional[str]* - Optional unique identifier for the tool call.--#### Signature--```python-class Message(BaseModel): ...-```\ No newline at end of filediff --git a/atomic-agents/docs/api/atomic_agents/lib/components/index.md b/atomic-agents/docs/api/atomic_agents/lib/components/index.mddeleted file mode 100644index f181501..0000000--- a/atomic-agents/docs/api/atomic_agents/lib/components/index.md+++ /dev/null@@ -1,13 +0,0 @@-# Components--[Atomic_agents Index](../../../README.md#atomic_agents-index) / [Atomic Agents](../../index.md#atomic-agents) / [Lib](../index.md#lib) / Components--> Auto-generated documentation for [atomic_agents.lib.components](../../../../../atomic_agents/lib/components/__init__.py) module.--- [Components](#components)- - [Modules](#modules)--## Modules--- [AgentMemory](./agent_memory.md)-- [SystemPromptGenerator](./system_prompt_generator.md)\ No newline at end of filediff --git a/atomic-agents/docs/api/atomic_agents/lib/components/system_prompt_generator.md b/atomic-agents/docs/api/atomic_agents/lib/components/system_prompt_generator.mddeleted file mode 100644index 465afc3..0000000--- a/atomic-agents/docs/api/atomic_agents/lib/components/system_prompt_generator.md+++ /dev/null@@ -1,66 +0,0 @@-# SystemPromptGenerator--[Atomic_agents Index](../../../README.md#atomic_agents-index) / [Atomic Agents](../../index.md#atomic-agents) / [Lib](../index.md#lib) / [Components](./index.md#components) / SystemPromptGenerator--> Auto-generated documentation for [atomic_agents.lib.components.system_prompt_generator](../../../../../atomic_agents/lib/components/system_prompt_generator.py) module.--- [SystemPromptGenerator](#systempromptgenerator)- - [SystemPromptContextProviderBase](#systempromptcontextproviderbase)- - [SystemPromptContextProviderBase().get_info](#systempromptcontextproviderbase()get_info)- - [SystemPromptGenerator](#systempromptgenerator-1)- - [SystemPromptGenerator().generate_prompt](#systempromptgenerator()generate_prompt)--## SystemPromptContextProviderBase--[Show source in system_prompt_generator.py:5](../../../../../atomic_agents/lib/components/system_prompt_generator.py#L5)--#### Signature--```python-class SystemPromptContextProviderBase(ABC):- def __init__(self, title: str): ...-```--### SystemPromptContextProviderBase().get_info--[Show source in system_prompt_generator.py:9](../../../../../atomic_agents/lib/components/system_prompt_generator.py#L9)--#### Signature--```python-@abstractmethod-def get_info(self) -> str: ...-```----## SystemPromptGenerator--[Show source in system_prompt_generator.py:17](../../../../../atomic_agents/lib/components/system_prompt_generator.py#L17)--#### Signature--```python-class SystemPromptGenerator:- def __init__(- self,- background: Optional[List[str]] = None,- steps: Optional[List[str]] = None,- output_instructions: Optional[List[str]] = None,- context_providers: Optional[Dict[str, SystemPromptContextProviderBase]] = None,- ): ...-```--#### See also--- [SystemPromptContextProviderBase](#systempromptcontextproviderbase)--### SystemPromptGenerator().generate_prompt--[Show source in system_prompt_generator.py:37](../../../../../atomic_agents/lib/components/system_prompt_generator.py#L37)--#### Signature--```python-def generate_prompt(self) -> str: ...-```\ No newline at end of filediff --git a/atomic-agents/docs/api/atomic_agents/lib/index.md b/atomic-agents/docs/api/atomic_agents/lib/index.mddeleted file mode 100644index a408192..0000000--- a/atomic-agents/docs/api/atomic_agents/lib/index.md+++ /dev/null@@ -1,15 +0,0 @@-# Lib--[Atomic_agents Index](../../README.md#atomic_agents-index) / [Atomic Agents](../index.md#atomic-agents) / Lib--> Auto-generated documentation for [atomic_agents.lib](../../../../atomic_agents/lib/__init__.py) module.--- [Lib](#lib)- - [Modules](#modules)--## Modules--- [Components](components/index.md)-- [Models](models/index.md)-- [Tools](tools/index.md)-- [Utils](utils/index.md)\ No newline at end of filediff --git a/atomic-agents/docs/api/atomic_agents/lib/models/index.md b/atomic-agents/docs/api/atomic_agents/lib/models/index.mddeleted file mode 100644index c0ed091..0000000--- a/atomic-agents/docs/api/atomic_agents/lib/models/index.md+++ /dev/null@@ -1,12 +0,0 @@-# Models--[Atomic_agents Index](../../../README.md#atomic_agents-index) / [Atomic Agents](../../index.md#atomic-agents) / [Lib](../index.md#lib) / Models--> Auto-generated documentation for [atomic_agents.lib.models](../../../../../atomic_agents/lib/models/__init__.py) module.--- [Models](#models)- - [Modules](#modules)--## Modules--- [WebDocument](./web_document.md)\ No newline at end of filediff --git a/atomic-agents/docs/api/atomic_agents/lib/models/web_document.md b/atomic-agents/docs/api/atomic_agents/lib/models/web_document.mddeleted file mode 100644index 157149e..0000000--- a/atomic-agents/docs/api/atomic_agents/lib/models/web_document.md+++ /dev/null@@ -1,35 +0,0 @@-# WebDocument--[Atomic_agents Index](../../../README.md#atomic_agents-index) / [Atomic Agents](../../index.md#atomic-agents) / [Lib](../index.md#lib) / [Models](./index.md#models) / WebDocument--> Auto-generated documentation for [atomic_agents.lib.models.web_document](../../../../../atomic_agents/lib/models/web_document.py) module.--- [WebDocument](#webdocument)- - [WebDocument](#webdocument-1)- - [WebDocumentMetadata](#webdocumentmetadata)--## WebDocument--[Show source in web_document.py:14](../../../../../atomic_agents/lib/models/web_document.py#L14)--#### Signature--```python-class WebDocument(BaseIOSchema): ...-```--#### See also--- [BaseIOSchema](../../agents/base_agent.md#baseioschema)----## WebDocumentMetadata--[Show source in web_document.py:6](../../../../../atomic_agents/lib/models/web_document.py#L6)--#### Signature--```python-class WebDocumentMetadata(BaseModel): ...-```\ No newline at end of filediff --git a/atomic-agents/docs/api/atomic_agents/lib/tools/base_tool.md b/atomic-agents/docs/api/atomic_agents/lib/tools/base_tool.mddeleted file mode 100644index b7e5365..0000000--- a/atomic-agents/docs/api/atomic_agents/lib/tools/base_tool.md+++ /dev/null@@ -1,75 +0,0 @@-# BaseTool--[Atomic_agents Index](../../../README.md#atomic_agents-index) / [Atomic Agents](../../index.md#atomic-agents) / [Lib](../index.md#lib) / [Tools](./index.md#tools) / BaseTool--> Auto-generated documentation for [atomic_agents.lib.tools.base_tool](../../../../../atomic_agents/lib/tools/base_tool.py) module.--- [BaseTool](#basetool)- - [BaseTool](#basetool-1)- - [BaseTool().run](#basetool()run)- - [BaseToolConfig](#basetoolconfig)--## BaseTool--[Show source in base_tool.py:13](../../../../../atomic_agents/lib/tools/base_tool.py#L13)--Base class for all tools in the Atomic Agents framework.--#### Attributes--- `input_schema` *Type[BaseIOSchema]* - The schema for the input data.-- `output_schema` *Type[BaseIOSchema]* - The schema for the output data.-- `tool_name` *str* - The name of the tool, derived from the input schema's title.-tool_description (str):- The description of the tool, derived from the input schema's description or overridden by the user.--#### Signature--```python-class BaseTool:- def __init__(self, config: BaseToolConfig = BaseToolConfig()): ...-```--#### See also--- [BaseToolConfig](#basetoolconfig)--### BaseTool().run--[Show source in base_tool.py:38](../../../../../atomic_agents/lib/tools/base_tool.py#L38)--Runs the tool with the given parameters. This method should be implemented by subclasses.--#### Arguments--- `params` *BaseIOSchema* - The input parameters for the tool, adhering to the input schema.--#### Returns--- `BaseIOSchema` - The output of the tool, adhering to the output schema.--#### Raises--- `NotImplementedError` - If the method is not implemented by a subclass.--#### Signature--```python-def run(self, params: Type[BaseIOSchema]) -> BaseIOSchema: ...-```--#### See also--- [BaseIOSchema](../../agents/base_agent.md#baseioschema)----## BaseToolConfig--[Show source in base_tool.py:8](../../../../../atomic_agents/lib/tools/base_tool.py#L8)--#### Signature--```python-class BaseToolConfig(BaseModel): ...-```\ No newline at end of filediff --git a/atomic-agents/docs/api/atomic_agents/lib/tools/calculator_tool.md b/atomic-agents/docs/api/atomic_agents/lib/tools/calculator_tool.mddeleted file mode 100644index cbd0f6a..0000000--- a/atomic-agents/docs/api/atomic_agents/lib/tools/calculator_tool.md+++ /dev/null@@ -1,108 +0,0 @@-# CalculatorTool--[Atomic_agents Index](../../../README.md#atomic_agents-index) / [Atomic Agents](../../index.md#atomic-agents) / [Lib](../index.md#lib) / [Tools](./index.md#tools) / CalculatorTool--> Auto-generated documentation for [atomic_agents.lib.tools.calculator_tool](../../../../../atomic_agents/lib/tools/calculator_tool.py) module.--- [CalculatorTool](#calculatortool)- - [CalculatorTool](#calculatortool-1)- - [CalculatorTool().run](#calculatortool()run)- - [CalculatorToolConfig](#calculatortoolconfig)- - [CalculatorToolInputSchema](#calculatortoolinputschema)- - [CalculatorToolOutputSchema](#calculatortooloutputschema)--## CalculatorTool--[Show source in calculator_tool.py:40](../../../../../atomic_agents/lib/tools/calculator_tool.py#L40)--Tool for performing calculations based on the provided mathematical expression.--#### Attributes--- `input_schema` *CalculatorToolInputSchema* - The schema for the input data.-- `output_schema` *CalculatorToolOutputSchema* - The schema for the output data.--#### Signature--```python-class CalculatorTool(BaseTool):- def __init__(self, config: CalculatorToolConfig = CalculatorToolConfig()): ...-```--#### See also--- [BaseTool](./base_tool.md#basetool)-- [CalculatorToolConfig](#calculatortoolconfig)--### CalculatorTool().run--[Show source in calculator_tool.py:61](../../../../../atomic_agents/lib/tools/calculator_tool.py#L61)--Runs the CalculatorTool with the given parameters.--#### Arguments--- `params` *CalculatorToolInputSchema* - The input parameters for the tool, adhering to the input schema.--#### Returns--- [CalculatorToolOutputSchema](#calculatortooloutputschema) - The output of the tool, adhering to the output schema.--#### Signature--```python-def run(self, params: CalculatorToolInputSchema) -> CalculatorToolOutputSchema: ...-```--#### See also--- [CalculatorToolInputSchema](#calculatortoolinputschema)-- [CalculatorToolOutputSchema](#calculatortooloutputschema)----## CalculatorToolConfig--[Show source in calculator_tool.py:36](../../../../../atomic_agents/lib/tools/calculator_tool.py#L36)--#### Signature--```python-class CalculatorToolConfig(BaseToolConfig): ...-```--#### See also--- [BaseToolConfig](./base_tool.md#basetoolconfig)----## CalculatorToolInputSchema--[Show source in calculator_tool.py:12](../../../../../atomic_agents/lib/tools/calculator_tool.py#L12)--#### Signature--```python-class CalculatorToolInputSchema(BaseIOSchema): ...-```--#### See also--- [BaseIOSchema](../../agents/base_agent.md#baseioschema)----## CalculatorToolOutputSchema--[Show source in calculator_tool.py:29](../../../../../atomic_agents/lib/tools/calculator_tool.py#L29)--#### Signature--```python-class CalculatorToolOutputSchema(BaseIOSchema): ...-```--#### See also--- [BaseIOSchema](../../agents/base_agent.md#baseioschema)\ No newline at end of filediff --git a/atomic-agents/docs/api/atomic_agents/lib/tools/content_scraping_tool.md b/atomic-agents/docs/api/atomic_agents/lib/tools/content_scraping_tool.mddeleted file mode 100644index f435934..0000000--- a/atomic-agents/docs/api/atomic_agents/lib/tools/content_scraping_tool.md+++ /dev/null@@ -1,123 +0,0 @@-# ContentScrapingTool--[Atomic_agents Index](../../../README.md#atomic_agents-index) / [Atomic Agents](../../index.md#atomic-agents) / [Lib](../index.md#lib) / [Tools](./index.md#tools) / ContentScrapingTool--> Auto-generated documentation for [atomic_agents.lib.tools.content_scraping_tool](../../../../../atomic_agents/lib/tools/content_scraping_tool.py) module.--#### Attributes--- `result` - ################- TEST WEB PAGE #- ################: client.chat.completions.create(model='gpt-4o-mini', response_model=ContentScrapingTool.input_schema, messages=[{'role': 'user', 'content': 'Scrape the content of https://brainblendai.com'}])--- `result` - ###############- TEST PDF URL #- ###############: client.chat.completions.create(model='gpt-4o-mini', response_model=ContentScrapingTool.input_schema, messages=[{'role': 'user', 'content': 'Scrape the content of https://pdfobject.com/pdf/sample.pdf'}])---- [ContentScrapingTool](#contentscrapingtool)- - [ContentScrapingTool](#contentscrapingtool-1)- - [ContentScrapingTool().run](#contentscrapingtool()run)- - [ContentScrapingToolConfig](#contentscrapingtoolconfig)- - [ContentScrapingToolInputSchema](#contentscrapingtoolinputschema)- - [ContentScrapingToolOutputSchema](#contentscrapingtooloutputschema)--## ContentScrapingTool--[Show source in content_scraping_tool.py:50](../../../../../atomic_agents/lib/tools/content_scraping_tool.py#L50)--Tool for scraping web pages or PDFs and converting content to markdown.--#### Attributes--- `input_schema` *ContentScrapingToolInputSchema* - The schema for the input data.-- `output_schema` *ContentScrapingToolOutputSchema* - The schema for the output data.--#### Signature--```python-class ContentScrapingTool(BaseTool):- def __init__(- self, config: ContentScrapingToolConfig = ContentScrapingToolConfig()- ): ...-```--#### See also--- [BaseTool](./base_tool.md#basetool)-- [ContentScrapingToolConfig](#contentscrapingtoolconfig)--### ContentScrapingTool().run--[Show source in content_scraping_tool.py:71](../../../../../atomic_agents/lib/tools/content_scraping_tool.py#L71)--Runs the ContentScrapingTool with the given parameters.--#### Arguments--- `params` *ContentScrapingToolInputSchema* - The input parameters for the tool, adhering to the input schema.--#### Returns--- [ContentScrapingToolOutputSchema](#contentscrapingtooloutputschema) - The output of the tool, adhering to the output schema.--#### Signature--```python-def run(- self, params: ContentScrapingToolInputSchema-) -> ContentScrapingToolOutputSchema: ...-```--#### See also--- [ContentScrapingToolInputSchema](#contentscrapingtoolinputschema)-- [ContentScrapingToolOutputSchema](#contentscrapingtooloutputschema)----## ContentScrapingToolConfig--[Show source in content_scraping_tool.py:46](../../../../../atomic_agents/lib/tools/content_scraping_tool.py#L46)--#### Signature--```python-class ContentScrapingToolConfig(BaseToolConfig): ...-```--#### See also--- [BaseToolConfig](./base_tool.md#basetoolconfig)----## ContentScrapingToolInputSchema--[Show source in content_scraping_tool.py:21](../../../../../atomic_agents/lib/tools/content_scraping_tool.py#L21)--#### Signature--```python-class ContentScrapingToolInputSchema(BaseIOSchema): ...-```--#### See also--- [BaseIOSchema](../../agents/base_agent.md#baseioschema)----## ContentScrapingToolOutputSchema--[Show source in content_scraping_tool.py:38](../../../../../atomic_agents/lib/tools/content_scraping_tool.py#L38)--#### Signature--```python-class ContentScrapingToolOutputSchema(BaseIOSchema): ...-```--#### See also--- [BaseIOSchema](../../agents/base_agent.md#baseioschema)\ No newline at end of filediff --git a/atomic-agents/docs/api/atomic_agents/lib/tools/index.md b/atomic-agents/docs/api/atomic_agents/lib/tools/index.mddeleted file mode 100644index 17fc170..0000000--- a/atomic-agents/docs/api/atomic_agents/lib/tools/index.md+++ /dev/null@@ -1,16 +0,0 @@-# Tools--[Atomic_agents Index](../../../README.md#atomic_agents-index) / [Atomic Agents](../../index.md#atomic-agents) / [Lib](../index.md#lib) / Tools--> Auto-generated documentation for [atomic_agents.lib.tools](../../../../../atomic_agents/lib/tools/__init__.py) module.--- [Tools](#tools)- - [Modules](#modules)--## Modules--- [BaseTool](./base_tool.md)-- [CalculatorTool](./calculator_tool.md)-- [ContentScrapingTool](./content_scraping_tool.md)-- [Yelp Restaurant Finder Tool](./yelp_restaurant_finder_tool.md)-- [Yt Transcript Scraper Tool](./yt_transcript_scraper_tool.md)\ No newline at end of filediff --git a/atomic-agents/docs/api/atomic_agents/lib/tools/yelp_restaurant_finder_tool.md b/atomic-agents/docs/api/atomic_agents/lib/tools/yelp_restaurant_finder_tool.mddeleted file mode 100644index ac052d9..0000000--- a/atomic-agents/docs/api/atomic_agents/lib/tools/yelp_restaurant_finder_tool.md+++ /dev/null@@ -1,159 +0,0 @@-# Yelp Restaurant Finder Tool--[Atomic_agents Index](../../../README.md#atomic_agents-index) / [Atomic Agents](../../index.md#atomic-agents) / [Lib](../index.md#lib) / [Tools](./index.md#tools) / Yelp Restaurant Finder Tool--> Auto-generated documentation for [atomic_agents.lib.tools.yelp_restaurant_finder_tool](../../../../../atomic_agents/lib/tools/yelp_restaurant_finder_tool.py) module.--- [Yelp Restaurant Finder Tool](#yelp-restaurant-finder-tool)- - [PriceRange](#pricerange)- - [YelpCategory](#yelpcategory)- - [YelpSearchResultSchema](#yelpsearchresultschema)- - [YelpSearchTool](#yelpsearchtool)- - [YelpSearchTool().run](#yelpsearchtool()run)- - [YelpSearchToolConfig](#yelpsearchtoolconfig)- - [YelpSearchToolInputSchema](#yelpsearchtoolinputschema)- - [YelpSearchToolOutputSchema](#yelpsearchtooloutputschema)--## PriceRange--[Show source in yelp_restaurant_finder_tool.py:39](../../../../../atomic_agents/lib/tools/yelp_restaurant_finder_tool.py#L39)--#### Signature--```python-class PriceRange(Enum): ...-```----## YelpCategory--[Show source in yelp_restaurant_finder_tool.py:17](../../../../../atomic_agents/lib/tools/yelp_restaurant_finder_tool.py#L17)--#### Signature--```python-class YelpCategory(Enum): ...-```----## YelpSearchResultSchema--[Show source in yelp_restaurant_finder_tool.py:78](../../../../../atomic_agents/lib/tools/yelp_restaurant_finder_tool.py#L78)--#### Signature--```python-class YelpSearchResultSchema(BaseIOSchema): ...-```--#### See also--- [BaseIOSchema](../../agents/base_agent.md#baseioschema)----## YelpSearchTool--[Show source in yelp_restaurant_finder_tool.py:110](../../../../../atomic_agents/lib/tools/yelp_restaurant_finder_tool.py#L110)--Tool for performing searches using the Yelp API based on the provided queries.--#### Attributes--- `input_schema` *YelpSearchToolInputSchema* - The schema for the input data.-- `output_schema` *YelpSearchToolOutputSchema* - The schema for the output data.-- `api_key` *str* - The API key for the Yelp API.-- `max_results` *int* - The maximum number of search results to return.--#### Signature--```python-class YelpSearchTool(BaseTool):- def __init__(self, config: YelpSearchToolConfig = YelpSearchToolConfig()): ...-```--#### See also--- [BaseTool](./base_tool.md#basetool)-- [YelpSearchToolConfig](#yelpsearchtoolconfig)--### YelpSearchTool().run--[Show source in yelp_restaurant_finder_tool.py:136](../../../../../atomic_agents/lib/tools/yelp_restaurant_finder_tool.py#L136)--Runs the YelpSearchTool with the given parameters.--#### Arguments--- `params` *YelpSearchToolInputSchema* - The input parameters for the tool, adhering to the input schema.-- `max_results` *Optional[int]* - The maximum number of search results to return.--#### Returns--- [YelpSearchToolOutputSchema](#yelpsearchtooloutputschema) - The output of the tool, adhering to the output schema.--#### Raises--- `ValueError` - If the API key is not provided.-- `Exception` - If the request to Yelp API fails.--#### Signature--```python-def run(self, params: YelpSearchToolInputSchema) -> YelpSearchToolOutputSchema: ...-```--#### See also--- [YelpSearchToolInputSchema](#yelpsearchtoolinputschema)-- [YelpSearchToolOutputSchema](#yelpsearchtooloutputschema)----## YelpSearchToolConfig--[Show source in yelp_restaurant_finder_tool.py:105](../../../../../atomic_agents/lib/tools/yelp_restaurant_finder_tool.py#L105)--#### Signature--```python-class YelpSearchToolConfig(BaseToolConfig): ...-```--#### See also--- [BaseToolConfig](./base_tool.md#basetoolconfig)----## YelpSearchToolInputSchema--[Show source in yelp_restaurant_finder_tool.py:46](../../../../../atomic_agents/lib/tools/yelp_restaurant_finder_tool.py#L46)--#### Signature--```python-class YelpSearchToolInputSchema(BaseIOSchema): ...-```--#### See also--- [BaseIOSchema](../../agents/base_agent.md#baseioschema)----## YelpSearchToolOutputSchema--[Show source in yelp_restaurant_finder_tool.py:88](../../../../../atomic_agents/lib/tools/yelp_restaurant_finder_tool.py#L88)--#### Signature--```python-class YelpSearchToolOutputSchema(BaseIOSchema): ...-```--#### See also--- [BaseIOSchema](../../agents/base_agent.md#baseioschema)\ No newline at end of filediff --git a/atomic-agents/docs/api/atomic_agents/lib/tools/yt_transcript_scraper_tool.md b/atomic-agents/docs/api/atomic_agents/lib/tools/yt_transcript_scraper_tool.mddeleted file mode 100644index e918f70..0000000--- a/atomic-agents/docs/api/atomic_agents/lib/tools/yt_transcript_scraper_tool.md+++ /dev/null@@ -1,157 +0,0 @@-# Yt Transcript Scraper Tool--[Atomic_agents Index](../../../README.md#atomic_agents-index) / [Atomic Agents](../../index.md#atomic-agents) / [Lib](../index.md#lib) / [Tools](./index.md#tools) / Yt Transcript Scraper Tool--> Auto-generated documentation for [atomic_agents.lib.tools.yt_transcript_scraper_tool](../../../../../atomic_agents/lib/tools/yt_transcript_scraper_tool.py) module.--- [Yt Transcript Scraper Tool](#yt-transcript-scraper-tool)- - [YouTubeTranscriptTool](#youtubetranscripttool)- - [YouTubeTranscriptTool.extract_video_id](#youtubetranscripttoolextract_video_id)- - [YouTubeTranscriptTool().fetch_video_metadata](#youtubetranscripttool()fetch_video_metadata)- - [YouTubeTranscriptTool().run](#youtubetranscripttool()run)- - [YouTubeTranscriptToolConfig](#youtubetranscripttoolconfig)- - [YouTubeTranscriptToolInputSchema](#youtubetranscripttoolinputschema)- - [YouTubeTranscriptToolOutputSchema](#youtubetranscripttooloutputschema)--## YouTubeTranscriptTool--[Show source in yt_transcript_scraper_tool.py:59](../../../../../atomic_agents/lib/tools/yt_transcript_scraper_tool.py#L59)--Tool for fetching the transcript of a YouTube video using the YouTube Transcript API.--#### Attributes--- `input_schema` *YouTubeTranscriptToolInputSchema* - The schema for the input data.-- `output_schema` *YouTubeTranscriptToolOutputSchema* - The schema for the output data.--#### Signature--```python-class YouTubeTranscriptTool(BaseTool):- def __init__(self, config: YouTubeTranscriptToolConfig): ...-```--#### See also--- [BaseTool](./base_tool.md#basetool)-- [YouTubeTranscriptToolConfig](#youtubetranscripttoolconfig)--### YouTubeTranscriptTool.extract_video_id--[Show source in yt_transcript_scraper_tool.py:115](../../../../../atomic_agents/lib/tools/yt_transcript_scraper_tool.py#L115)--Extracts the video ID from a YouTube URL.--#### Arguments--- `url` *str* - The YouTube video URL.--#### Returns--- `str` - The extracted video ID.--#### Signature--```python-@staticmethod-def extract_video_id(url: str) -> str: ...-```--### YouTubeTranscriptTool().fetch_video_metadata--[Show source in yt_transcript_scraper_tool.py:128](../../../../../atomic_agents/lib/tools/yt_transcript_scraper_tool.py#L128)--Fetches metadata for a YouTube video.--#### Arguments--- `video_id` *str* - The YouTube video ID.--#### Returns--- `dict` - The metadata of the video.--#### Signature--```python-def fetch_video_metadata(self, video_id: str) -> dict: ...-```--### YouTubeTranscriptTool().run--[Show source in yt_transcript_scraper_tool.py:81](../../../../../atomic_agents/lib/tools/yt_transcript_scraper_tool.py#L81)--Runs the YouTubeTranscriptTool with the given parameters.--#### Arguments--- `params` *YouTubeTranscriptToolInputSchema* - The input parameters for the tool, adhering to the input schema.--#### Returns--- [YouTubeTranscriptToolOutputSchema](#youtubetranscripttooloutputschema) - The output of the tool, adhering to the output schema.--#### Raises--- `Exception` - If fetching the transcript fails.--#### Signature--```python-def run(- self, params: YouTubeTranscriptToolInputSchema-) -> YouTubeTranscriptToolOutputSchema: ...-```--#### See also--- [YouTubeTranscriptToolInputSchema](#youtubetranscripttoolinputschema)-- [YouTubeTranscriptToolOutputSchema](#youtubetranscripttooloutputschema)----## YouTubeTranscriptToolConfig--[Show source in yt_transcript_scraper_tool.py:52](../../../../../atomic_agents/lib/tools/yt_transcript_scraper_tool.py#L52)--#### Signature--```python-class YouTubeTranscriptToolConfig(BaseToolConfig): ...-```--#### See also--- [BaseToolConfig](./base_tool.md#basetoolconfig)----## YouTubeTranscriptToolInputSchema--[Show source in yt_transcript_scraper_tool.py:17](../../../../../atomic_agents/lib/tools/yt_transcript_scraper_tool.py#L17)--#### Signature--```python-class YouTubeTranscriptToolInputSchema(BaseIOSchema): ...-```--#### See also--- [BaseIOSchema](../../agents/base_agent.md#baseioschema)----## YouTubeTranscriptToolOutputSchema--[Show source in yt_transcript_scraper_tool.py:35](../../../../../atomic_agents/lib/tools/yt_transcript_scraper_tool.py#L35)--#### Signature--```python-class YouTubeTranscriptToolOutputSchema(BaseIOSchema): ...-```--#### See also--- [BaseIOSchema](../../agents/base_agent.md#baseioschema)\ No newline at end of filediff --git a/atomic-agents/docs/api/atomic_agents/lib/utils/format_tool_message.md b/atomic-agents/docs/api/atomic_agents/lib/utils/format_tool_message.mddeleted file mode 100644index b3f21cc..0000000--- a/atomic-agents/docs/api/atomic_agents/lib/utils/format_tool_message.md+++ /dev/null@@ -1,31 +0,0 @@-# Format Tool Message--[Atomic_agents Index](../../../README.md#atomic_agents-index) / [Atomic Agents](../../index.md#atomic-agents) / [Lib](../index.md#lib) / [Utils](./index.md#utils) / Format Tool Message--> Auto-generated documentation for [atomic_agents.lib.utils.format_tool_message](../../../../../atomic_agents/lib/utils/format_tool_message.py) module.--- [Format Tool Message](#format-tool-message)- - [format_tool_message](#format_tool_message)--## format_tool_message--[Show source in format_tool_message.py:8](../../../../../atomic_agents/lib/utils/format_tool_message.py#L8)--Formats a message for a tool call.--#### Arguments--- `tool_call` *Type[BaseModel]* - The Pydantic model instance representing the tool call.-- `tool_id` *str, optional* - The unique identifier for the tool call. If not provided, a random UUID will be generated.--#### Returns--- `Dict` - A formatted message dictionary for the tool call.--#### Signature--```python-def format_tool_message(- tool_call: Type[BaseModel], tool_id: Optional[str] = None-) -> Dict: ...-```\ No newline at end of filediff --git a/atomic-agents/docs/api/atomic_agents/lib/utils/index.md b/atomic-agents/docs/api/atomic_agents/lib/utils/index.mddeleted file mode 100644index bd78561..0000000--- a/atomic-agents/docs/api/atomic_agents/lib/utils/index.md+++ /dev/null@@ -1,13 +0,0 @@-# Utils--[Atomic_agents Index](../../../README.md#atomic_agents-index) / [Atomic Agents](../../index.md#atomic-agents) / [Lib](../index.md#lib) / Utils--> Auto-generated documentation for [atomic_agents.lib.utils](../../../../../atomic_agents/lib/utils/__init__.py) module.--- [Utils](#utils)- - [Modules](#modules)--## Modules--- [Format Tool Message](./format_tool_message.md)-- [Scraping](scraping/index.md)\ No newline at end of filediff --git a/atomic-agents/docs/api/atomic_agents/lib/utils/scraping/index.md b/atomic-agents/docs/api/atomic_agents/lib/utils/scraping/index.mddeleted file mode 100644index 9e95b14..0000000--- a/atomic-agents/docs/api/atomic_agents/lib/utils/scraping/index.md+++ /dev/null@@ -1,13 +0,0 @@-# Scraping--[Atomic_agents Index](../../../../README.md#atomic_agents-index) / [Atomic Agents](../../../index.md#atomic-agents) / [Lib](../../index.md#lib) / [Utils](../index.md#utils) / Scraping--> Auto-generated documentation for [atomic_agents.lib.utils.scraping](../../../../../../atomic_agents/lib/utils/scraping/__init__.py) module.--- [Scraping](#scraping)- - [Modules](#modules)--## Modules--- [Pdf To Markdown](./pdf_to_markdown.md)-- [Url To Markdown](./url_to_markdown.md)\ No newline at end of filediff --git a/atomic-agents/docs/api/atomic_agents/lib/utils/scraping/pdf_to_markdown.md b/atomic-agents/docs/api/atomic_agents/lib/utils/scraping/pdf_to_markdown.mddeleted file mode 100644index d9eb205..0000000--- a/atomic-agents/docs/api/atomic_agents/lib/utils/scraping/pdf_to_markdown.md+++ /dev/null@@ -1,30 +0,0 @@-# Pdf To Markdown--[Atomic_agents Index](../../../../README.md#atomic_agents-index) / [Atomic Agents](../../../index.md#atomic-agents) / [Lib](../../index.md#lib) / [Utils](../index.md#utils) / [Scraping](./index.md#scraping) / Pdf To Markdown--> Auto-generated documentation for [atomic_agents.lib.utils.scraping.pdf_to_markdown](../../../../../../atomic_agents/lib/utils/scraping/pdf_to_markdown.py) module.--- [Pdf To Markdown](#pdf-to-markdown)- - [PdfToMarkdownConverter](#pdftomarkdownconverter)- - [PdfToMarkdownConverter.convert](#pdftomarkdownconverterconvert)--## PdfToMarkdownConverter--[Show source in pdf_to_markdown.py:11](../../../../../../atomic_agents/lib/utils/scraping/pdf_to_markdown.py#L11)--#### Signature--```python-class PdfToMarkdownConverter: ...-```--### PdfToMarkdownConverter.convert--[Show source in pdf_to_markdown.py:34](../../../../../../atomic_agents/lib/utils/scraping/pdf_to_markdown.py#L34)--#### Signature--```python-@staticmethod-def convert(url=None, file_path=None): ...-```\ No newline at end of filediff --git a/atomic-agents/docs/api/atomic_agents/lib/utils/scraping/url_to_markdown.md b/atomic-agents/docs/api/atomic_agents/lib/utils/scraping/url_to_markdown.mddeleted file mode 100644index e1e7f00..0000000--- a/atomic-agents/docs/api/atomic_agents/lib/utils/scraping/url_to_markdown.md+++ /dev/null@@ -1,30 +0,0 @@-# Url To Markdown--[Atomic_agents Index](../../../../README.md#atomic_agents-index) / [Atomic Agents](../../../index.md#atomic-agents) / [Lib](../../index.md#lib) / [Utils](../index.md#utils) / [Scraping](./index.md#scraping) / Url To Markdown--> Auto-generated documentation for [atomic_agents.lib.utils.scraping.url_to_markdown](../../../../../../atomic_agents/lib/utils/scraping/url_to_markdown.py) module.--- [Url To Markdown](#url-to-markdown)- - [UrlToMarkdownConverter](#urltomarkdownconverter)- - [UrlToMarkdownConverter.convert](#urltomarkdownconverterconvert)--## UrlToMarkdownConverter--[Show source in url_to_markdown.py:10](../../../../../../atomic_agents/lib/utils/scraping/url_to_markdown.py#L10)--#### Signature--```python-class UrlToMarkdownConverter: ...-```--### UrlToMarkdownConverter.convert--[Show source in url_to_markdown.py:61](../../../../../../atomic_agents/lib/utils/scraping/url_to_markdown.py#L61)--#### Signature--```python-@staticmethod-def convert(url): ...-```\ No newline at end of filediff --git a/atomic-agents/docs/guides/agents.md b/atomic-agents/docs/guides/agents.mddeleted file mode 100644index 1062944..0000000--- a/atomic-agents/docs/guides/agents.md+++ /dev/null@@ -1,11 +0,0 @@-# Agents-## Overview-In the Atomic Agents framework, an agent is a class that can interact with a user or another agent. Agents can be used to handle chat interactions, interface with tools, or perform other specialized tasks. The `BaseAgent` class is the base class for all chat agents, and the `ToolInterfaceAgent` class extends the `BaseAgent` to add tool interfacing capabilities.--## BaseAgent-The `BaseAgent` class serves two primary purposes:-1. It can be used directly to handle chat interactions.-2. It can be extended to create more specialized agents either to be re-used such as the `ToolInterfaceAgent` or to create new agents for specific tasks. For examples, see the `examples` directory.--## ToolInterfaceAgent-The `ToolInterfaceAgent` class extends the `BaseAgent` class to add tool interfacing capabilities. It provides a standard interface for interacting with tools such as those in the `atomic_agents.tools` package.\ No newline at end of filediff --git a/atomic-agents/docs/guides/creating_a_new_tool.md b/atomic-agents/docs/guides/creating_a_new_tool.mddeleted file mode 100644index f985016..0000000--- a/atomic-agents/docs/guides/creating_a_new_tool.md+++ /dev/null@@ -1,155 +0,0 @@-# Tools-## Creating a New Tool--This guide will walk you through the steps to create a new tool in the `atomic_agents` framework. We will cover the necessary components and provide an example to illustrate the process.--### Components of a Tool--A tool in the `atomic_agents` framework consists of the following components:--1. **Input Schema**: Defines the input parameters for the tool.-2. **Output Schema**: Defines the output structure of the tool.-3. **Tool Logic**: Implements the core functionality of the tool.-4. **Configuration**: Defines the configuration parameters for the tool.-5. **Example Usage**: Demonstrates how to use the tool.--### Step-by-Step Guide--#### 1. Define the Input Schema--The input schema is a Pydantic `BaseModel` that specifies the input parameters for the tool. It should inherit from `BaseIOSchema` and include a `Config` class with `title`, `description`, and `json_schema_extra` attributes. Here's an example:--```python-from pydantic import Field-from atomic_agents.agents.base_agent import BaseIOSchema--class MyToolInputSchema(BaseIOSchema):- """Describe the tool / input schema here, this docstring is used in the LLM's prompt"""-- parameter: str = Field(..., description="Description of the parameter.")- list_param: list[str] = Field(..., description="A list of strings.")-```--#### 2. Define the Output Schema--The output schema is also a Pydantic `BaseModel` that inherits from `BaseIOSchema`. It specifies the structure of the tool's output. Here's an example:--```python-class MyToolOutputSchema(BaseIOSchema):- result: str = Field(..., description="Result of the tool's operation.")- details: dict = Field(..., description="Additional details about the result.")-```--#### 3. Define the Configuration--The configuration is a Pydantic `BaseModel` that specifies the configuration parameters for the tool. It should extend from `BaseToolConfig`. Here's an example:--```python-from atomic_agents.lib.tools.base import BaseToolConfig--class MyToolConfig(BaseToolConfig):- api_key: str = Field(..., description="API key for accessing external services.")-```--#### 4. Implement the Tool Logic--Create a class that inherits from `BaseTool` and implements the core functionality of the tool. This class should define the `input_schema`, `output_schema`, and implement the `run` method.--```python-from atomic_agents.lib.tools.base import BaseTool--class MyTool(BaseTool):- input_schema = MyToolInputSchema- output_schema = MyToolOutputSchema-- def __init__(self, config: MyToolConfig = MyToolConfig()):- super().__init__(config)- self.api_key = config.api_key-- def run(self, params: MyToolInputSchema) -> MyToolOutputSchema:- # Implement the core logic here- result = f"Processed {params.parameter}"- details = {"list_param_length": len(params.list_param)}- return MyToolOutputSchema(result=result, details=details)-```--#### 5. Example Usage--Provide an example of how to use the tool. This typically involves initializing the tool and running it with sample input.--```python-if __name__ == "__main__":- from rich.console import Console-- rich_console = Console()-- input_data = MyToolInputSchema(- parameter="example input",- list_param=["item1", "item2"]- )- config = MyToolConfig(api_key="your_api_key_here")- tool = MyTool(config=config)- output = tool.run(input_data)- rich_console.print(output)-```--### Full Example--Here is a complete example of a new tool called `MyTool`:--```python-# my_tool.py--from pydantic import Field-from atomic_agents.agents.base_agent import BaseIOSchema-from atomic_agents.lib.tools.base import BaseTool, BaseToolConfig-from rich.console import Console--# Input Schema-class MyToolInputSchema(BaseIOSchema):- """Input schema for the MyTool tool."""-- parameter: str = Field(..., description="Description of the parameter.")- list_param: list[str] = Field(..., description="A list of strings.")--# Output Schema-class MyToolOutputSchema(BaseIOSchema):- result: str = Field(..., description="Result of the tool's operation.")- details: dict = Field(..., description="Additional details about the result.")--# Configuration-class MyToolConfig(BaseToolConfig):- api_key: str = Field(..., description="API key for accessing external services.")--# Tool Logic-class MyTool(BaseTool):- input_schema = MyToolInputSchema- output_schema = MyToolOutputSchema-- def __init__(self, config: MyToolConfig = MyToolConfig()):- super().__init__(config)- self.api_key = config.api_key-- def run(self, params: MyToolInputSchema) -> MyToolOutputSchema:- # Implement the core logic here- result = f"Processed {params.parameter}"- details = {"list_param_length": len(params.list_param)}- return MyToolOutputSchema(result=result, details=details)--# Example Usage-if __name__ == "__main__":- rich_console = Console()-- input_data = MyToolInputSchema(- parameter="example input",- list_param=["item1", "item2"]- )- config = MyToolConfig(api_key="your_api_key_here")- tool = MyTool(config=config)- output = tool.run(input_data)- rich_console.print(output)-```--### Conclusion--By following these steps, you can create a new tool in the `atomic_agents` framework. Define the input and output schemas, implement the tool logic, and provide an example usage to demonstrate how the tool works. Remember to inherit from the appropriate base classes (`BaseIOSchema`, `BaseToolConfig`, and `BaseTool`) and use the `rich` library for console output in your example usage.diff --git a/atomic-agents/examples/basic_custom_chatbot.py b/atomic-agents/examples/basic_custom_chatbot.pydeleted file mode 100644index fc50896..0000000--- a/atomic-agents/examples/basic_custom_chatbot.py+++ /dev/null@@ -1,58 +0,0 @@-import os-from rich.console import Console-from atomic_agents.lib.components.agent_memory import AgentMemory-from atomic_agents.agents.base_agent import BaseAgent, BaseAgentConfig-from atomic_agents.lib.components.system_prompt_generator import SystemPromptGenerator-import instructor-import openai--# Define system prompt information including background, steps, and output instructions-system_prompt_generator = SystemPromptGenerator(- background=[- "This assistant is a general-purpose AI designed to be helpful and friendly.",- ],- steps=["Understand the user's input and provide a relevant response.", "Respond to the user."],- output_instructions=[- "Provide helpful and relevant information to assist the user.",- "Be friendly and respectful in all interactions.",- "Always answer in rhyming verse.",- ],-)--# Initialize chat memory to store conversation history-memory = AgentMemory()-# 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)--# 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.--base_url = None # Replace with your OpenAI API base URL-api_key = None # Replace with your OpenAI API key-agent = BaseAgent(- config=BaseAgentConfig(- client=instructor.from_openai(- openai.OpenAI(base_url=base_url or os.getenv("OPENAI_BASE_URL"), api_key=api_key or os.getenv("OPENAI_API_KEY"))- ),- system_prompt_generator=system_prompt_generator,- model="gpt-4o-mini",- memory=memory,- )-)--# 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(agent.input_schema(chat_message=user_input))- console.print(f"Agent: {response.chat_message}")diff --git a/atomic-agents/examples/conversing_agents.py b/atomic-agents/examples/conversing_agents.pydeleted file mode 100644index b5fb8cf..0000000--- a/atomic-agents/examples/conversing_agents.py+++ /dev/null@@ -1,66 +0,0 @@-import json-import os-import random-import groq-import instructor-import openai-from rich.console import Console-from atomic_agents.agents.base_agent import BaseAgentConfig, BaseAgent, BaseAgentInputSchema, BaseAgentOutputSchema-from atomic_agents.lib.components.system_prompt_generator import SystemPromptGenerator--# Initialize the system prompts. For simplicity, we use the same system prompt for both agents.-agent1_system_prompt_generator = SystemPromptGenerator(- background=["You are an agent that adds 1 to the number said by the previous person in the conversation."],- steps=["If the previous message contains a number, add 1 to it."],- output_instructions=[- "Respond with only the resulting added number and never anything else. Do not include any additional text."- ],-)--agent2_system_prompt_generator = SystemPromptGenerator(- background=["You are an agent that adds 1 to the number said by the previous person in the conversation."],- steps=["If the previous message contains a number, add 1 to it."],- output_instructions=[- "Respond with only the resulting added number and never anything else. Do not include any additional text."- ],-)--# Initialize the agents. For fun, we use two different clients for the agents. One uses Groq and the other uses OpenAI.-# You can use the same client for both agents if you prefer. For a list of supported clients, refer to the `instructor` library documentation.-agent1 = BaseAgent(- config=BaseAgentConfig(- client=instructor.from_openai(openai.OpenAI()),- model="gpt-4o-mini",- system_prompt_generator=agent2_system_prompt_generator,- )-)---agent2 = BaseAgent(- config=BaseAgentConfig(- client=instructor.from_openai(openai.OpenAI()),- model="gpt-4o-mini",- system_prompt_generator=agent2_system_prompt_generator,- )-)---# Function to simulate a conversation between the two agents-def simulate_conversation(num_turns=5):- console = Console()- next_input = "123"-- for _ in range(num_turns):- agent1_response = agent1.run(agent1.input_schema(chat_message=next_input))- console.print(f"[bold blue]Agent 1:[/bold blue] {agent1_response.chat_message}")- next_input = agent1_response.chat_message-- agent2_response = agent2.run(agent2.input_schema(chat_message=next_input))- console.print(f"[bold green]Agent 2:[/bold green] {agent2_response.chat_message}")- next_input = agent2_response.chat_message-- print("Done")---if __name__ == "__main__":- simulate_conversation(num_turns=5)diff --git a/atomic-agents/examples/deep_research_multi_agent/agents/info_refiner_agent.py b/atomic-agents/examples/deep_research_multi_agent/agents/info_refiner_agent.pydeleted file mode 100644index e582919..0000000--- a/atomic-agents/examples/deep_research_multi_agent/agents/info_refiner_agent.py+++ /dev/null@@ -1,47 +0,0 @@-from pydantic import BaseModel, Field-from atomic_agents.agents.base_agent import BaseIOSchema-import instructor-import openai-from atomic_agents.agents.base_agent import BaseAgent, BaseAgentConfig-from atomic_agents.lib.components.system_prompt_generator import SystemPromptGenerator---class RefineAnswerInputSchema(BaseIOSchema):- """This schema defines the input for the RefineAnswer agent."""-- question: str = Field(..., description="The question that was asked.")- answer: str = Field(..., description="The initial answer to the question.")---class RefineAnswerOutputSchema(BaseIOSchema):- """This schema defines the output for the RefineAnswer agent."""-- refined_answer: str = Field(..., description="The refined answer to the question.")---# Create the refine answer agent-refine_answer_agent = BaseAgent(- BaseAgentConfig(- client=instructor.from_openai(openai.OpenAI()),- model="gpt-4o-mini",- system_prompt_generator=SystemPromptGenerator(- background=[- "You are an intelligent answer refinement expert.",- "Your task is to expand and elaborate on an existing answer to a question using additional context from vector DB chunks.",- ],- steps=[- "You will receive a question or instruction, the initial answer, and additional context from vector DB chunks.",- "Correct any inaccuracies and factual errors in the initial answer.",- "Expand and elaborate on the initial answer using the additional context to provide a more comprehensive and detailed response.",- ],- output_instructions=[- "Ensure the refined answer is clear, concise, and well-structured.",- "Ensure the refined answer is directly relevant to the question and incorporates the additional context provided.",- "Add new information and details to make the final answer more elaborate and informative.",- "Do not make up any new information; only use the information present in the context.",- ],- ),- input_schema=RefineAnswerInputSchema,- output_schema=RefineAnswerOutputSchema,- )-)diff --git a/atomic-agents/examples/deep_research_multi_agent/agents/query_agent.py b/atomic-agents/examples/deep_research_multi_agent/agents/query_agent.pydeleted file mode 100644index e30e0a9..0000000--- a/atomic-agents/examples/deep_research_multi_agent/agents/query_agent.py+++ /dev/null@@ -1,39 +0,0 @@-import instructor-import openai-from pydantic import Field-from atomic_agents.agents.base_agent import BaseIOSchema, BaseAgent, BaseAgentConfig-from atomic_agents.lib.components.system_prompt_generator import SystemPromptGenerator-from atomic_agents.lib.tools.search.searxng_tool import SearxNGTool---class QueryAgentInputSchema(BaseIOSchema):- """This is the input schema for the QueryAgent."""-- instruction: str = Field(..., "A detailed instruction or request to generate deep research queries for.")- num_queries: int = Field(..., "The number of queries to generate.")---# Create the query agent-query_agent = BaseAgent(- BaseAgentConfig(- client=instructor.from_openai(openai.OpenAI()),- model="gpt-4o-mini",- system_prompt_generator=SystemPromptGenerator(- background=[- "You are an intelligent query generation expert.",- "Your task is to generate a specified number of diverse and highly relevant queries based on a given instruction or request.",- "The queries should cover different aspects of the instruction to ensure comprehensive exploration.",- ],- steps=[- "You will receive a detailed instruction or request and the number of queries to generate.",- "Generate the requested number of queries in a JSON format.",- ],- output_instructions=[- "Ensure clarity and conciseness in each query.",- "Ensure each query is unique and as diverse as possible while remaining relevant to the instruction.",- ],- ),- input_schema=QueryAgentInputSchema,- output_schema=SearxNGTool.input_schema,- )-)diff --git a/atomic-agents/examples/deep_research_multi_agent/agents/question_answering_agent.py b/atomic-agents/examples/deep_research_multi_agent/agents/question_answering_agent.pydeleted file mode 100644index dde081f..0000000--- a/atomic-agents/examples/deep_research_multi_agent/agents/question_answering_agent.py+++ /dev/null@@ -1,42 +0,0 @@-import instructor-import openai-from pydantic import BaseModel, Field-from atomic_agents.agents.base_agent import BaseIOSchema, BaseAgent, BaseAgentConfig-from atomic_agents.lib.components.system_prompt_generator import SystemPromptGenerator---class AnswerAgentInputSchema(BaseIOSchema):- """This schema defines the input schema for the AnswerAgent."""-- question: str = Field(..., description="A question that needs to be answered based on the provided context.")---class AnswerAgentOutputSchema(BaseIOSchema):- """This schema defines the output schema for the AnswerAgent."""-- markdown_output: str = Field(..., description="The answer to the question in markdown format.")---# Create the answer agent-answer_agent = BaseAgent(- BaseAgentConfig(- client=instructor.from_openai(openai.OpenAI()),- model="gpt-4o-mini",- system_prompt_generator=SystemPromptGenerator(- background=[- "You are an intelligent answering expert.",- "Your task is to provide accurate and detailed answers to user questions based on the given context.",- ],- steps=[- "You will receive a question and the context information.",- "Generate a detailed and accurate answer based on the context.",- ],- output_instructions=[- "Ensure clarity and conciseness in each answer.",- "Ensure the answer is directly relevant to the question and context provided.",- ],- ),- input_schema=AnswerAgentInputSchema,- output_schema=AnswerAgentOutputSchema,- )-)diff --git a/atomic-agents/examples/deep_research_multi_agent/agents/top_urls_selector_agent.py b/atomic-agents/examples/deep_research_multi_agent/agents/top_urls_selector_agent.pydeleted file mode 100644index 4f8cd1c..0000000--- a/atomic-agents/examples/deep_research_multi_agent/agents/top_urls_selector_agent.py+++ /dev/null@@ -1,44 +0,0 @@-from typing import List-import instructor-import openai-from pydantic import Field, HttpUrl-from atomic_agents.agents.base_agent import BaseIOSchema, BaseAgent, BaseAgentConfig-from atomic_agents.lib.components.system_prompt_generator import SystemPromptGenerator---class TopUrlsSelectorInputSchema(BaseIOSchema):- """This schema defines the input schema for the TopUrlsSelector agent."""-- user_input: str = Field(..., description="The user input or question.")- num_urls: int = Field(..., description="The number of top URLs to select.")---class TopUrlsSelectorOutputSchema(BaseIOSchema):- """This schema defines the output schema for the TopUrlsSelector agent."""-- top_urls: List[HttpUrl] = Field(..., description="The list of top URLs selected based on the user input.")---# Create the top URLs selector agent-top_urls_selector_agent = BaseAgent(- BaseAgentConfig(- client=instructor.from_openai(openai.OpenAI()),- model="gpt-4o-mini",- system_prompt_generator=SystemPromptGenerator(- background=[- "You are an intelligent URL selection expert.",- "Your task is to select the best URLs from a list of search results that are most relevant to the user input or question.",- ],- steps=[- "You will receive the user input or question, the list of search results, and the number of best URLs to select.",- "Analyze the search results and select the best URLs that are most relevant to the user input or question.",- ],- output_instructions=[- "Ensure each selected URL is highly relevant to the user input or question.",- "Ensure the selected URLs are diverse yet as relevant as possible.",- ],- ),- input_schema=TopUrlsSelectorInputSchema,- output_schema=TopUrlsSelectorOutputSchema,- )-)diff --git a/atomic-agents/examples/deep_research_multi_agent/in_memory_faiss.py b/atomic-agents/examples/deep_research_multi_agent/in_memory_faiss.pydeleted file mode 100644index 7c91ca6..0000000--- a/atomic-agents/examples/deep_research_multi_agent/in_memory_faiss.py+++ /dev/null@@ -1,77 +0,0 @@-import openai-import faiss-import numpy as np-import asyncio-from playwright.async_api import async_playwright-from bs4 import BeautifulSoup-import markdownify---class InMemFaiss:- def __init__(self, openai_api_key):- openai.api_key = openai_api_key- self.index = faiss.IndexFlatL2(1536)- self.texts = []- self.metadata = []-- async def download_content(self, url):- async with async_playwright() as p:- browser = await p.chromium.launch(headless=True)- page = await browser.new_page()- await page.goto(url)- html_content = await page.content()- await browser.close()-- # Clean HTML content- cleaned_html = self.clean_html(html_content)-- # Convert cleaned HTML to Markdown- markdown_content = markdownify.markdownify(cleaned_html, heading_style="ATX")- return markdown_content-- def clean_html(self, html_content):- soup = BeautifulSoup(html_content, "html.parser")-- # Example cleaning: remove script and style tags- for script_or_style in soup(["script", "style"]):- script_or_style.decompose()-- # Additional cleaning can be done here- cleaned_html = str(soup)- return cleaned_html-- def split_text(self, text, chunk_size=1000, overlap=250):- chunks = []- for i in range(0, len(text), chunk_size - overlap):- chunk = text[i : i + chunk_size].strip()- chunks.append(chunk)- return chunks-- async def generate_embeddings(self, texts):- embeddings = []- for text in texts:- response = openai.embeddings.create(input=text, model="text-embedding-3-small")- embedding = response.data[0].embedding- embeddings.append(embedding)- return np.array(embeddings).astype("float32")-- async def ingest_urls(self, urls):- tasks = [self.process_url(url) for url in urls]- await asyncio.gather(*tasks)-- async def process_url(self, url):- try:- url = str(url)- content = await self.download_content(url)- chunks = self.split_text(content)- embeddings = await self.generate_embeddings(chunks)- self.index.add(embeddings)- self.texts.extend(chunks)- self.metadata.extend([{"url": url}] * len(chunks))- except Exception as e:- print(f"Failed to ingest URL {url}: {e}")-- async def retrieve_chunks(self, query, top_k=5):- query_embedding = await self.generate_embeddings([query])- distances, indices = self.index.search(query_embedding, top_k)- return [self.texts[idx] for idx in indices[0]]diff --git a/atomic-agents/examples/deep_research_multi_agent/main.py b/atomic-agents/examples/deep_research_multi_agent/main.pydeleted file mode 100644index fa8a5af..0000000--- a/atomic-agents/examples/deep_research_multi_agent/main.py+++ /dev/null@@ -1,77 +0,0 @@-import os-from examples.deep_research_multi_agent.agents.query_agent import query_agent-from examples.deep_research_multi_agent.agents.question_answering_agent import answer_agent-from examples.deep_research_multi_agent.agents.top_urls_selector_agent import top_urls_selector_agent-from examples.deep_research_multi_agent.agents.info_refiner_agent import refine_answer_agent-from examples.deep_research_multi_agent.providers import search_results_provider, vector_db_chunks_provider-from examples.deep_research_multi_agent.in_memory_faiss import InMemFaiss-from atomic_agents.lib.tools.search.searxng_tool import SearxNGTool, SearxNGToolConfig-from rich.console import Console-import asyncio---async def main():-- console = Console()-- # Initialize the search tool- search_tool = SearxNGTool(SearxNGToolConfig(base_url=os.getenv("SEARXNG_BASE_URL"), max_results=30))- in_mem_faiss = InMemFaiss(openai_api_key=os.getenv("OPENAI_API_KEY"))-- user_input = input("Enter your question (or type 'exit' to quit): ")-- 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)-- while True:- if user_input.lower() == "exit":- break-- console.print("[bold green]Getting queries...[/bold green]")- queries = query_agent.run(query_agent.input_schema(instruction=user_input, num_queries=5))-- # Start loop here- console.print("[bold green]Registering context providers...[/bold green]")-- console.print("[bold green]Getting search results...[/bold green]")- search_results_provider.search_results = search_tool.run(search_tool.input_schema(**queries.model_dump()))-- # 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))-- # 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]=====================[/bold green]")-- console.print("[bold green]Ingesting URLs into in-memory FAISS...[/bold green]")- await in_mem_faiss.ingest_urls(top_urls.top_urls)-- # 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)-- 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()-- user_input = input("Enter your question (or type 'exit' to quit): ")---# Run the main function-asyncio.run(main())diff --git a/atomic-agents/examples/deep_research_multi_agent/providers.py b/atomic-agents/examples/deep_research_multi_agent/providers.pydeleted file mode 100644index 0bff2b9..0000000--- a/atomic-agents/examples/deep_research_multi_agent/providers.py+++ /dev/null@@ -1,23 +0,0 @@-from atomic_agents.lib.components.system_prompt_generator import SystemPromptContextProviderBase---class SearchResultsProvider(SystemPromptContextProviderBase):- def __init__(self, title: str):- super().__init__(title=title)- self.search_results = []-- def get_info(self) -> str:- return f"SEARCH RESULTS: {self.search_results}"---class VectorDBChunksProvider(SystemPromptContextProviderBase):- def __init__(self, title: str):- super().__init__(title=title)- self.chunks = []-- def get_info(self) -> str:- return f"VECTOR DB CHUNKS: {self.chunks}"---search_results_provider = SearchResultsProvider(title="Search results")-vector_db_chunks_provider = VectorDBChunksProvider(title="Vector DB chunks")diff --git a/atomic-agents/examples/dynamic_multichoice_answer_agent.py b/atomic-agents/examples/dynamic_multichoice_answer_agent.pydeleted file mode 100644index 8dcff75..0000000--- a/atomic-agents/examples/dynamic_multichoice_answer_agent.py+++ /dev/null@@ -1,161 +0,0 @@-# File: multiple_choice_agent.py--import instructor-import openai-from pydantic import BaseModel, Field, create_model-from typing import List, Dict, Any, Literal, Union-from atomic_agents.agents.base_agent import BaseIOSchema, BaseAgent, BaseAgentConfig-from atomic_agents.lib.components.system_prompt_generator import SystemPromptGenerator---class Question(BaseModel):- question: str = Field(..., description="The multiple-choice question")- options: List[str] = Field(..., min_items=2, description="List of possible answer options")---class MultipleChoiceAgentInputSchema(BaseIOSchema):- """This schema defines the input schema for the MultipleChoiceAgent."""-- questions: List[Question] = Field(..., min_items=1, description="List of multiple-choice questions")- context: str = Field(..., description="Additional context or information to help answer the questions")---def create_dynamic_output_schema(question: Question):- field_name = "answer"- options_literal = Literal[tuple(question.options)]- fields = {- # "step_by_step_reasoning": (List[str], Field(..., description="Step-by-step reasoning for the answer")),- field_name: (options_literal, Field(..., description=f"Answer for question: {question.question}")),- }- return create_model(f"DynamicMultipleChoiceOutput_{id(question)}", **fields)---def run_multiple_choice_agent(questions: List[Question], context: str):- results = {}-- for i, question in enumerate(questions):- # Create a dynamic output schema for each question- dynamic_output_schema = create_dynamic_output_schema(question)-- # Update the agent's output schema with the dynamic schema for this question- multiple_choice_agent.output_schema = dynamic_output_schema-- # Create a single-question input for the agent- single_question_input = MultipleChoiceAgentInputSchema(questions=[question], context=context)-- # Run the agent for this question- result = multiple_choice_agent.run(single_question_input)-- # Store the result- results[f"question_{i+1}"] = {"answer": result.answer, "reasoning": "result.step_by_step_reasoning"}-- return results---# Create the multiple choice agent-multiple_choice_agent = BaseAgent(- BaseAgentConfig(- client=instructor.from_openai(openai.OpenAI()),- model="gpt-4o-mini", # Updated to a more recent model- system_prompt_generator=SystemPromptGenerator(- background=[- "You are an expert AI multiple-choice question answering system.",- "Your task is to provide accurate answers to multiple-choice questions based on the given context and options.",- ],- steps=[- "Analyze each question and its options carefully.",- "Consider the provided context to inform your decision.",- "Develop a step-by-step reasoning process for your answer.",- "Select the most appropriate answer for each question based on the context and options.",- "Provide clear and concise answers along with your reasoning.",- ],- output_instructions=[- "For each question, select the best answer from the provided options.",- "Provide a list of step-by-step reasoning points that led to your answer.",- "Ensure your answers and reasoning are directly relevant to the questions and context.",- "Format your output as requested, with both the selected answer and the step-by-step reasoning.",- ],- ),- input_schema=MultipleChoiceAgentInputSchema,- output_schema=None, # We will set this dynamically- )-)---# Example usage-if __name__ == "__main__":- questions = [- Question(question="What is the capital of Egypt?", options=["London", "Berlin", "Paris", "Cairo", "Madrid"]),- Question(question="Which planet is known as the Red Planet?", options=["Venus", "Mars", "Jupiter", "Saturn"]),- Question(- question="Who wrote 'To Kill a Mockingbird'?",- options=["Ernest Hemingway", "Harper Lee", "F. Scott Fitzgerald", "John Steinbeck"],- ),- Question(question="Is the Earth flat?", options=["Yes", "No"]),- Question(- question="What is the largest mammal on Earth?",- options=["African Elephant", "Blue Whale", "Giraffe", "Hippopotamus"],- ),- Question(- question="Who was the first person to step on the Moon?",- options=["Yuri Gagarin", "Neil Armstrong", "Buzz Aldrin", "John Glenn"],- ),- # New complex questions- Question(- question="What is the capital of Burkina Faso?",- options=["Ouagadougou", "Bamako", "Niamey", "Accra", "Lomé"],- ),- Question(- question="Is JavaScript a compiled or interpreted language?",- options=["Compiled", "Interpreted", "Both", "Neither"],- ),- Question(- question="Who painted 'The Persistence of Memory'?",- options=["Pablo Picasso", "Salvador Dalí", "Vincent van Gogh", "Claude Monet"],- ),- Question(- question="What is the primary function of mitochondria in a cell?",- options=["Energy production", "Protein synthesis", "Cell division", "Waste removal"],- ),- Question(question="Does the moon have its own light source?", options=["Yes", "No"]),- Question(- question="Which of these is not a programming paradigm?",- options=["Object-Oriented", "Functional", "Imperative", "Alphabetical"],- ),- Question(- question="What is the capital of Canada?",- options=["Toronto", "Vancouver", "Montreal", "Ottawa", "Quebec City"],- ),- Question(- question="Who wrote '1984'?",- options=["George Orwell", "Aldous Huxley", "Ray Bradbury", "Philip K. Dick"],- ),- Question(- question="What is the largest planet in our solar system?",- options=["Earth", "Mars", "Jupiter", "Saturn"],- ),- Question(- question="Which of these is not a type of cloud?",- options=["Cumulus", "Stratus", "Nimbus", "Nebulus"],- ),- ]- context = """- Egypt's capital is Cairo. Mars is often called the Red Planet due to its reddish appearance.- Harper Lee wrote the classic novel 'To Kill a Mockingbird'. The Earth is not flat; it is an oblate spheroid.- The Blue Whale is the largest animal known to have ever existed. Neil Armstrong was the first person to walk on the Moon in 1969.- Ouagadougou is the capital of Burkina Faso. JavaScript is primarily an interpreted language, although modern engines use just-in-time compilation.- Salvador Dalí painted 'The Persistence of Memory'. Mitochondria are often referred to as the powerhouses of the cell due to their role in energy production.- The moon does not have its own light source; it reflects sunlight. Ottawa is the capital city of Canada.- George Orwell wrote the dystopian novel '1984'. Jupiter is the largest planet in our solar system.- """-- answers = run_multiple_choice_agent(questions, context)- for i, (question_num, result) in enumerate(answers.items()):- print(f"\n{question_num}:")- print(f"\n{question_num}:")- print(f"Question: {questions[i].question}")- print(f"Options: {questions[i].options}")- print(f"Answer: {result['answer']}")- # print("Reasoning:")- # for step in result["reasoning"]:- # print(f"- {step}")diff --git a/atomic-agents/examples/memory_demo.py b/atomic-agents/examples/memory_demo.pydeleted file mode 100644index 6440b22..0000000--- a/atomic-agents/examples/memory_demo.py+++ /dev/null@@ -1,121 +0,0 @@-from rich.console import Console-from rich.panel import Panel-from rich.text import Text-from rich.table import Table--from atomic_agents.lib.components.agent_memory import AgentMemory--console = Console()---def print_panel(title, content):- console.print(Panel(content, title=title, expand=False, border_style="cyan"))---# Create a AgentMemory with a maximum of 5 messages-memory = AgentMemory(max_messages=5)--console.print("[bold magenta]AgentMemory Test Cases[/bold magenta]", justify="center")-console.print()--# Test Case 1: Adding regular messages and displaying the current history-content = Text()-memory.add_message("user", "Hello, how are you?")-memory.add_message("assistant", "I'm doing well, thank you for asking!")-memory.add_message("user", "Can you help me with the weather?")-content.append(f"Total messages: {memory.get_message_count()}\n\n")-content.append("Current history:\n")-for msg in memory.get_history():- content.append(f"- {msg.role}: {msg.content}\n", style=f"{'green' if msg.role == 'user' else 'blue'}")-print_panel("1. Adding regular messages", content)--# Test Case 2: Adding a message with a tool call and displaying the last message-content = Text()-tool_message = {- "id": "weather_1",- "type": "function",- "function": {"name": "get_weather", "arguments": '{"location": "New York"}'},-}-memory.add_message("assistant", "Certainly! I'll check the weather for you.", tool_message=tool_message)-content.append(f"Total messages: {memory.get_message_count()}\n\n")-content.append("Last message:\n")-last_msg = memory.get_history()[-1]-content.append(f"- {last_msg.role}: {last_msg.content}\n", style="blue")-content.append(f" Tool call: {last_msg.tool_calls}\n", style="yellow")-print_panel("2. Adding a message with a tool call", content)--# Test Case 3: Adding a tool response and displaying the last message-content = Text()-memory.add_message("tool", "The weather in New York is sunny with a high of 75°F.", tool_id="weather_1")-content.append(f"Total messages: {memory.get_message_count()}\n\n")-content.append("Last message:\n")-last_msg = memory.get_history()[-1]-content.append(f"- {last_msg.role}: {last_msg.content}\n", style="yellow")-content.append(f" Tool call ID: {last_msg.tool_call_id}\n", style="yellow")-print_panel("3. Adding a tool response", content)--# Test Case 4: Testing overflow management by adding more messages than the maximum allowed-content = Text()-memory.add_message("user", "Thanks for the weather info!")-content.append(f"Total messages: {memory.get_message_count()}\n\n")-content.append("Current history (should only have 5 most recent messages):\n")-for msg in memory.get_history():- content.append(- f"- {msg.role}: {msg.content}\n",- style=f"{'green' if msg.role == 'user' else 'blue' if msg.role == 'assistant' else 'yellow'}",- )-print_panel("4. Testing overflow management", content)--# Test Case 5: Testing dump and load functionality-content = Text()-dumped_data = memory.dump()-content.append("Dumped data:\n")-content.append(str(dumped_data), style="dim")-content.append("\n\n")-new_memory = AgentMemory(max_messages=5)-new_memory.load(dumped_data)-content.append("Loaded memory:\n")-for msg in new_memory.get_history():- content.append(- f"- {msg.role}: {msg.content}\n",- style=f"{'green' if msg.role == 'user' else 'blue' if msg.role == 'assistant' else 'yellow'}",- )-content.append(f"\nTotal messages in loaded memory: {new_memory.get_message_count()}")-print_panel("5. Testing dump and load", content)--# Test Case 6: Testing copy functionality-content = Text()-copied_memory = memory.copy()-content.append(f"Original memory message count: {memory.get_message_count()}\n")-content.append(f"Copied memory message count: {copied_memory.get_message_count()}\n\n")-content.append("Adding a message to the copy:\n")-copied_memory.add_message("user", "This is a new message in the copy.")-content.append(f"Original memory message count: {memory.get_message_count()}\n")-content.append(f"Copied memory message count: {copied_memory.get_message_count()}")-print_panel("6. Testing copy", content)--# Test Case 7: Testing loading a larger buffer than max_messages-content = Text()-large_buffer = [{"role": "user", "content": f"Message {i}"} for i in range(10)]-large_memory = AgentMemory(max_messages=5)-large_memory.load(large_buffer)-content.append(f"Total messages after loading large buffer: {large_memory.get_message_count()}\n\n")-content.append("Current history (should only have 5 most recent messages):\n")-for msg in large_memory.get_history():- content.append(f"- {msg.role}: {msg.content}\n", style="green")-print_panel("7. Testing loading a larger buffer than max_messages", content)--# Test Case 8: Testing adding messages with different content types-content = Text()-mixed_memory = AgentMemory(max_messages=10)-mixed_memory.add_message("user", "Hello")-mixed_memory.add_message("assistant", {"text": "Hi there!", "confidence": 0.95})-mixed_memory.add_message("system", {"command": "reset_conversation"})-content.append(f"Total messages in mixed memory: {mixed_memory.get_message_count()}\n\n")-content.append("Mixed memory contents:\n")-for msg in mixed_memory.get_history():- content.append(- f"- {msg.role}: {msg.content}\n",- style=f"{'green' if msg.role == 'user' else 'blue' if msg.role == 'assistant' else 'red'}",- )-print_panel("8. Testing adding messages with different content types", content)diff --git a/atomic-agents/examples/mesop_example.py b/atomic-agents/examples/mesop_example.pydeleted file mode 100644index 62790eb..0000000--- a/atomic-agents/examples/mesop_example.py+++ /dev/null@@ -1,63 +0,0 @@-##########-# This example is basically the same as "simple_web_search_agent.py",-# but it uses the Google Mesop library for a simple and easy chat UI-# simply do "pip install mesop" to install it.-# https://google.github.io/mesop/-#-# To run, do "mesop simple_web_search_agent.py"-##########--import os-import instructor-import openai-from rich.console import Console-import mesop as me-import mesop.labs as mel-from dataclasses import field--from atomic_agents.agents.tool_interface_agent import ToolInterfaceAgent, ToolInterfaceAgentConfig-from atomic_agents.lib.tools.search.searxng_tool import SearxNGTool, SearxNGToolConfig--# Initialize the console, client, and tools-console = Console()-client = instructor.from_openai(openai.OpenAI())---def initialize_searxng_tool():- base_url = os.getenv("SEARXNG_BASE_URL")- config = SearxNGToolConfig(base_url=base_url, max_results=10)- return SearxNGTool(config)---searxng_tool = initialize_searxng_tool()---def initialize_agent(client, searxng_tool):- agent_config = ToolInterfaceAgentConfig(- client=client, model="gpt-4o-mini", tool_instance=searxng_tool, return_raw_output=False- )- return ToolInterfaceAgent(config=agent_config)---agent = initialize_agent(client, searxng_tool)---# Mesop state class-class State:- chat_history: list[mel.ChatMessage] = field(default_factory=list)---# Mesop transform function-def transform(input: str, history: list[mel.ChatMessage]):- state = me.state(State)- response = agent.run(agent.input_schema(tool_input_SearxNGTool=input))- state.chat_history.append(mel.ChatMessage(content=f"You: {input}"))- state.chat_history.append(mel.ChatMessage(content=f"Agent: {response.chat_message}"))- yield response.chat_message---# Mesop page[email protected](path="/", title="ToolInterfaceAgent Chat")-def page():- mel.chat(transform, title="ToolInterfaceAgent with SearxNGTool", bot_user="Agent")diff --git a/atomic-agents/examples/minimal_chatbot.py b/atomic-agents/examples/minimal_chatbot.pydeleted file mode 100644index bff9a8e..0000000--- a/atomic-agents/examples/minimal_chatbot.py+++ /dev/null@@ -1,23 +0,0 @@-from rich.console import Console-import instructor-import openai--# `BaseAgent` is the core class for creating chat agents in the Atomic Agents framework.-from atomic_agents.agents.base_agent import BaseAgent, BaseAgentConfig--# Create an instance of `BaseAgent` with default settings.-# For all supported clients such as Anthropic & Gemini, have a look at the `instructor` library documentation.-agent = BaseAgent(config=BaseAgentConfig(client=instructor.from_openai(openai.OpenAI()), model="gpt-4o-mini"))--# Initialize a `Console` object for rich text output in the terminal.-console = Console()--# Main chat loop for testing the chat agent.-while True:- user_input = input("You: ")- if user_input.lower() in ["/exit", "/quit"]:- print("Exiting chat...")- break-- response = agent.run(agent.input_schema(chat_message=user_input))- console.print(f"Agent: {response.chat_message}")diff --git a/atomic-agents/examples/minimal_chatbot_llama.py b/atomic-agents/examples/minimal_chatbot_llama.pydeleted file mode 100644index aee55b7..0000000--- a/atomic-agents/examples/minimal_chatbot_llama.py+++ /dev/null@@ -1,26 +0,0 @@-from rich.console import Console-import llama_cpp--# `BaseAgent` is the core class for creating chat agents in the Atomic Agents framework.-from atomic_agents.agents.base_agent import BaseAgent, BaseAgentConfig--# Create an instance of `BaseAgent` with LLaMA settings.-# Ensure you have the LLaMA model path correctly set.-llama_model_path = "./models/7B" # Update this path to your LLaMA model location-agent = BaseAgent(config=BaseAgentConfig(client=llama_cpp.Llama(model_path=llama_model_path), model="llama-7B"))--# Initialize a `Console` object for rich text output in the terminal.-console = Console()--# Main chat loop for testing the chat agent.-while True:- user_input = input("You: ")- if user_input.lower() in ["/exit", "/quit"]:- print("Exiting chat...")- break-- response = agent.run(agent.input_schema(chat_message=user_input))- console.print(f"Agent: {response.chat_message}")--#! Make sure you have the llama-cpp-python package installed and the model files available at the specified path.-#! You can refer to the llama-cpp-python documentation for more details on setup and usage. https://llama-cpp-python.readthedocs.io/en/latest/\ No newline at end of filediff --git a/atomic-agents/examples/minimal_multi_agent_tool_use.py b/atomic-agents/examples/minimal_multi_agent_tool_use.pydeleted file mode 100644index 87f2ec6..0000000--- a/atomic-agents/examples/minimal_multi_agent_tool_use.py+++ /dev/null@@ -1,57 +0,0 @@-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_agent import BaseIOSchema, BaseAgent, BaseAgentConfig-from atomic_agents.agents.tool_interface_agent import ToolInterfaceAgent, ToolInterfaceAgentConfig-from atomic_agents.lib.tools.search.searxng_tool import SearxNGTool, SearxNGToolConfig-from atomic_agents.lib.tools.calculator_tool import CalculatorTool, CalculatorToolConfig--import logging--# Configure logging-logging.basicConfig(level=logging.DEBUG, format="%(asctime)s - %(levelname)s - %(message)s")-logger = logging.getLogger(__name__)--console = Console()-client = instructor.from_openai(openai.OpenAI())-searxng_tool = SearxNGTool(SearxNGToolConfig(base_url=os.getenv("SEARXNG_BASE_URL"), max_results=10))-calc_tool = CalculatorTool(CalculatorToolConfig())--search_agent_config = ToolInterfaceAgentConfig(- client=client, model="gpt-4o-mini", tool_instance=searxng_tool, return_raw_output=False-)-calculator_agent_config = ToolInterfaceAgentConfig(- client=client, model="gpt-4o-mini", tool_instance=calc_tool, return_raw_output=False-)-searx_agent = ToolInterfaceAgent(config=search_agent_config)-calc_agent = ToolInterfaceAgent(config=calculator_agent_config)--UnionResponse = create_model(- "UnionResponse",- __base__=BaseIOSchema,- response=(Union[searx_agent.input_schema, calc_agent.input_schema], ...),- __doc__="This schema represents the output of the orchestration agent, which can be any of the provided agents.",-)--orchestration_agent = BaseAgent(config=BaseAgentConfig(client=client, model="gpt-4o-mini", output_schema=UnionResponse))--while True:- user_input = input("You: ")- if user_input.lower() in ["exit", "quit"]:- print("Exiting chat...")- break-- orchestration_agent_output = orchestration_agent.run(orchestration_agent.input_schema(chat_message=user_input))- console.print(f"Agent: {orchestration_agent_output.response}")-- if isinstance(orchestration_agent_output.response, searx_agent.input_schema):- console.print(f"Using searx agent")- response = searx_agent.run(orchestration_agent_output.response)- elif isinstance(orchestration_agent_output.response, calc_agent.input_schema):- console.print(f"Using calc agent")- response = calc_agent.run(orchestration_agent_output.response)-- console.print(f"Agent: {response}")diff --git a/atomic-agents/examples/notebooks/multi_agent_quickstart.ipynb b/atomic-agents/examples/notebooks/multi_agent_quickstart.ipynbdeleted file mode 100644index 7ec1abf..0000000--- a/atomic-agents/examples/notebooks/multi_agent_quickstart.ipynb+++ /dev/null@@ -1,240 +0,0 @@-{- "cells": [- {- "cell_type": "markdown",- "metadata": {},- "source": [- "# Multi-Agent Quickstart Tutorial\n",- "\n",- "This quickstart tutorial demonstrates how to create a multi-agent system using the Atomic Agents library. The system will include a search agent and a calculator agent, which can be orchestrated to handle different types of user queries.\n",- "\n",- "[](https://colab.research.google.com/github/KennyVaneetvelde/atomic_agents/blob/main/examples/notebooks/multi_agent_quickstart.ipynb)\n"- ]- },- {- "cell_type": "markdown",- "metadata": {},- "source": [- "## Prerequisites\n",- "\n",- "Before proceeding with this notebook, it is highly recommended to read up on the basics of the following libraries:\n",- "\n",- "- **Pydantic**: A data validation and settings management library using Python type annotations. You can find more information and documentation at [Pydantic GitHub](https://github.com/pydantic/pydantic).\n",- "- **Instructor**: A Python library that simplifies working with structured outputs from large language models (LLMs). It provides a user-friendly API to manage validation, retries, and streaming responses. More details can be found at [Instructor GitHub](https://github.com/jxnl/instructor).\n",- "\n",- "Understanding these libraries will help you make the most of this library.\n"- ]- },- {- "cell_type": "markdown",- "metadata": {},- "source": [- "## Install Necessary Packages\n",- "\n",- "First, we need to install the required packages. Run the following command to install `atomic-agents`, `openai`, and `instructor` libraries."- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "# Install necessary packages\n",- "%pip install atomic-agents openai instructor"- ]- },- {- "cell_type": "markdown",- "metadata": {},- "source": [- "## Import Libraries\n",- "\n",- "We will import the necessary libraries for creating the multi-agent system."- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "import os\n",- "from typing import Union\n",- "import instructor\n",- "import openai\n",- "from pydantic import create_model\n",- "from rich.console import Console\n",- "from atomic_agents.agents.base_agent import BaseIOSchema, BaseAgent, BaseAgentConfig\n",- "from atomic_agents.agents.tool_interface_agent import ToolInterfaceAgent, ToolInterfaceAgentConfig\n",- "from atomic_agents.lib.tools.search.searxng_tool import SearxNGTool, SearxNGToolConfig\n",- "from atomic_agents.lib.tools.calculator_tool import CalculatorTool, CalculatorToolConfig"- ]- },- {- "cell_type": "markdown",- "metadata": {},- "source": [- "## Initialize Components\n",- "\n",- "Initialize the necessary components including the client, tools, and agents."- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "# Initialize the console for output\n",- "console = Console()\n",- "\n",- "# Initialize the client\n",- "client = instructor.from_openai(openai.OpenAI())\n",- "\n",- "# Initialize the SearxNG search tool\n",- "searxng_tool = SearxNGTool(SearxNGToolConfig(base_url=os.getenv('SEARXNG_BASE_URL'), max_results=10))\n",- "\n",- "# Initialize the calculator tool\n",- "calc_tool = CalculatorTool(CalculatorToolConfig())"- ]- },- {- "cell_type": "markdown",- "metadata": {},- "source": [- "## Configure and Create Agents\n",- "\n",- "Configure and create the search agent and calculator agent."- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "# Configure the search agent\n",- "search_agent_config = ToolInterfaceAgentConfig(client=client, model='gpt-4o-mini', tool_instance=searxng_tool, return_raw_output=False)\n",- "\n",- "# Configure the calculator agent\n",- "calculator_agent_config = ToolInterfaceAgentConfig(client=client, model='gpt-4o-mini', tool_instance=calc_tool, return_raw_output=False)\n",- "\n",- "# Create the search agent and calculator agent\n",- "searx_agent = ToolInterfaceAgent(config=search_agent_config)\n",- "calc_agent = ToolInterfaceAgent(config=calculator_agent_config)"- ]- },- {- "cell_type": "markdown",- "metadata": {},- "source": [- "## Define Union Response Schema\n",- "\n",- "Create a union response schema that can handle responses from both the search agent and the calculator agent."- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "# Define a union response schema\n",- "UnionResponse = create_model('UnionResponse', __base__=BaseIOSchema, response=(Union[searx_agent.input_schema, calc_agent.input_schema], ...))"- ]- },- {- "cell_type": "markdown",- "metadata": {},- "source": [- "Notice how instead of defining the response schema as a class, we use create_model() to define the schema. This is because we want to use the TOOL.input_schema to dynamically get the input schema of the agent, which is not possible with a class definition."- ]- },- {- "cell_type": "markdown",- "metadata": {},- "source": [- "## Create Orchestration Agent\n",- "\n",- "Create an orchestration agent that can manage the interactions between the user and the individual agents."- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "# Create the orchestration agent\n",- "orchestration_agent = BaseAgent(config=BaseAgentConfig(client=client, model='gpt-4o-mini', output_schema=UnionResponse))"- ]- },- {- "cell_type": "markdown",- "metadata": {},- "source": [- "## Main Chat Loop\n",- "\n",- "Create a main chat loop to interact with the orchestration agent. The agent will determine whether to use the search tool or the calculator tool based on the user's input."- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "while True:\n",- " user_input = input('You: ')\n",- " if user_input.lower() in ['exit', 'quit']:\n",- " print('Exiting chat...')\n",- " break\n",- "\n",- " response = orchestration_agent.run(orchestration_agent.input_schema(chat_message=user_input))\n",- " console.print(f'Agent: {response.response}')\n",- "\n",- " if isinstance(response.response, searx_agent.input_schema):\n",- " console.print(f'Using searx agent')\n",- " response = searx_agent.run(response.response)\n",- " elif isinstance(response.response, calc_agent.input_schema):\n",- " console.print(f'Using calc agent')\n",- " response = calc_agent.run(response.response)\n",- "\n",- " console.print(f'Agent: {response.chat_message}')"- ]- },- {- "cell_type": "markdown",- "metadata": {},- "source": [- "## Conclusion\n",- "\n",- "In this notebook, we demonstrated how to create a multi-agent system using the Atomic Agents library. The system includes a search agent and a calculator agent, which can be orchestrated to handle different types of user queries. You can further customize the agents and enhance their capabilities based on your requirements.\n",- "\n",- "You can also create your own tools and wrap them into the tool agent. This allows you to extend the functionality of the multi-agent system to suit your specific needs."- ]- }- ],- "metadata": {- "kernelspec": {- "display_name": "Python 3",- "language": "python",- "name": "python3"- },- "language_info": {- "codemirror_mode": {- "name": "ipython",- "version": 3- },- "file_extension": ".py",- "mimetype": "text/x-python",- "name": "python",- "nbconvert_exporter": "python",- "pygments_lexer": "ipython3",- "version": "3.12.3"- }- },- "nbformat": 4,- "nbformat_minor": 4-}diff --git a/atomic-agents/examples/notebooks/quickstart.ipynb b/atomic-agents/examples/notebooks/quickstart.ipynbdeleted file mode 100644index 428d7b8..0000000--- a/atomic-agents/examples/notebooks/quickstart.ipynb+++ /dev/null@@ -1,220 +0,0 @@-{- "cells": [- {- "cell_type": "markdown",- "metadata": {},- "source": [- "# Quickstart Tutorial: Basic Custom Chatbot using Atomic Agents\n",- "\n",- "This quickstart tutorial demonstrates how to create a custom chatbot with a unique personality using the Atomic Agents library. The chatbot will respond to user inputs in rhyming verse.\n",- "\n",- "[](https://colab.research.google.com/github/KennyVaneetvelde/atomic_agents/blob/main/examples/notebooks/quickstart.ipynb#)\n"- ]- },- {- "cell_type": "markdown",- "metadata": {},- "source": [- "# Prerequisites\n",- "\n",- "Before proceeding with this notebook, it is highly recommended to read up on the basics of the following libraries:\n",- "\n",- "- **Pydantic**: A data validation and settings management library using Python type annotations. You can find more information and documentation at [Pydantic GitHub](https://github.com/pydantic/pydantic).\n",- "- **Instructor**: A Python library that simplifies working with structured outputs from large language models (LLMs). It provides a user-friendly API to manage validation, retries, and streaming responses. More details can be found at [Instructor GitHub](https://github.com/jxnl/instructor).\n",- "\n",- "Understanding these libraries will help you make the most of this library.\n"- ]- },- {- "cell_type": "markdown",- "metadata": {},- "source": [- "## Step 1: Install Necessary Packages\n",- "\n",- "First, we need to install the required packages. Run the following command to install `atomic-agents`, `openai`, and `instructor` libraries."- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "# Install necessary packages\n",- "%pip install atomic-agents openai instructor jsonref"- ]- },- {- "cell_type": "markdown",- "metadata": {},- "source": [- "## Step 2: Import Libraries\n",- "\n",- "We will import the necessary libraries for creating the chatbot. Each library serves a specific purpose:\n",- "- `AgentMemory`: Manages the chat history.\n",- "- `BaseAgent`: The base class to create a custom chatbot. Can be extended for additional functionality if needed.\n",- "- `SystemPromptGenerator` and `SystemPromptInfo`: To define and generate system prompts."- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "import os\n",- "import instructor\n",- "import openai\n",- "from atomic_agents.lib.components.agent_memory import AgentMemory\n",- "from atomic_agents.agents.base_agent import BaseAgent, BaseAgentConfig\n",- "from atomic_agents.lib.components.system_prompt_generator import SystemPromptGenerator"- ]- },- {- "cell_type": "markdown",- "metadata": {},- "source": [- "## Step 3: Define System Prompt Information\n",- "\n",- "We will define the system prompt information including background, steps, and output instructions. This helps the chatbot understand how to respond to user inputs.\n",- "In this example, we will define a system prompt that asks the chatbot to respond to user inputs in rhyming verse.\n",- "\n",- "The structuring of the system prompts in this library is loosely inspired by Patterns in the [Fabric library](https://github.com/danielmiessler/fabric/tree/main/patterns)."- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "system_prompt_generator = SystemPromptGenerator(\n",- " background=[\n",- " 'This assistant is a general-purpose AI designed to be helpful and friendly.',\n",- " ],\n",- " steps=[\n",- " 'Understand the user\\'s input and provide a relevant response.',\n",- " 'Respond to the user.'\n",- " ],\n",- " output_instructions=[\n",- " 'Provide helpful and relevant information to assist the user.',\n",- " 'Be friendly and respectful in all interactions.',\n",- " 'Always answer in rhyming verse.'\n",- " ]\n",- ")\n",- "\n",- "from rich.markdown import Markdown\n",- "Markdown(system_prompt_generator.generate_prompt())"- ]- },- {- "cell_type": "markdown",- "metadata": {},- "source": [- "## Step 4: Initialize Chat Memory\n",- "\n",- "We will initialize the chat memory to store conversation history and load an initial greeting message."- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "memory = AgentMemory()\n",- "initial_memory = [\n",- " {'role': 'assistant', 'content': 'How do you do? What can I do for you? Tell me, pray, what is your need today?'}\n",- "]\n",- "memory.load(initial_memory)"- ]- },- {- "cell_type": "markdown",- "metadata": {},- "source": [- "## Step 5: Set Up API Key and Create Chat Agent\n",- "\n",- "To use the **OpenAI** API, you need to set up your API key. You can either enter it directly in the code or set it as an environment variable. Additionally, you can choose other clients such as **Anthropic**, **Mistral**, etc. For a full list, check out the [Instructor library docs](https://github.com/jxnl/instructor)."- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "##################################################################\n",- "# ENTER YOUR API KEY BELOW, OR SET IT AS AN ENVIRONMENT VARIABLE #\n",- "##################################################################\n",- "API_KEY = ''\n",- "if not API_KEY:\n",- " # Get the environment variable\n",- " API_KEY = os.getenv('OPENAI_API_KEY')\n",- "\n",- "if not API_KEY:\n",- " raise ValueError('API key is not set. Please set the API key as a static variable or in the environment variable OPENAI_API_KEY.')\n",- "\n",- "client = instructor.from_openai(openai.OpenAI(api_key=API_KEY))\n",- "\n",- "agent = BaseAgent(\n",- " config=BaseAgentConfig(\n",- " client=client,\n",- " system_prompt_generator=system_prompt_generator,\n",- " model='gpt-4o-mini',\n",- " memory=memory,\n",- " )\n",- ")"- ]- },- {- "cell_type": "markdown",- "metadata": {},- "source": [- "## Step 6: Main Chat Loop\n",- "\n",- "We will create a main chat loop for testing the chat agent. This loop will allow you to interact with the chatbot in real-time.\n",- "To exit the loop, type `/exit` or `/quit`."- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "print(f'Agent: {initial_memory[0][\"content\"]}')\n",- "\n",- "while True:\n",- " user_input = input('You: ')\n",- " if user_input.lower() in ['/exit', '/quit']:\n",- " print('Exiting chat...')\n",- " break\n",- " \n",- " response = agent.run(agent.input_schema(chat_message=user_input))\n",- " print(f'Agent: {response.chat_message}')"- ]- }- ],- "metadata": {- "kernelspec": {- "display_name": "Python 3",- "language": "python",- "name": "python3"- },- "language_info": {- "codemirror_mode": {- "name": "ipython",- "version": 3- },- "file_extension": ".py",- "mimetype": "text/x-python",- "name": "python",- "nbconvert_exporter": "python",- "pygments_lexer": "ipython3",- "version": "3.12.3"- }- },- "nbformat": 4,- "nbformat_minor": 4-}diff --git a/atomic-agents/examples/notebooks/what_is_atomic_agents.ipynb b/atomic-agents/examples/notebooks/what_is_atomic_agents.ipynbdeleted file mode 100644index 8f169fe..0000000--- a/atomic-agents/examples/notebooks/what_is_atomic_agents.ipynb+++ /dev/null@@ -1,675 +0,0 @@-{- "cells": [- {- "attachments": {- "image.png": {- "image/png": "iVBORw0KGgoAAAANSUhEUgAAA1kAAAC/CAYAAAAM9BYxAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAC1DSURBVHhe7d0HlJTV3cfxq4iF2Ess5EXFAnY0Ruw9VkRjjxoVUWNXghpRFLsee+y9966g2LvE3o29YUDsBRVFI6/f69xldphdZnefLTPP93POnp2dbcPyzJ37u+V/p5jwqyBJkiRJysSUhfeSJEmSpAwYsiRJkiQpQ4YsSZIkScqQIUuSJEmSMmTIkiRJkqQMGbIkSZIkKUOGLEmSJEnKkCFLkiRJkjJkyJIkSZKkDBmyJEmSJClDhixJkiRJypAhS5IkSZIyZMiSJEmSpAwZsiRJkiQpQ4YsSZIkScqQIUuSJEmSMmTIkiRJkqQMGbIkSZIkKUOGLEmSJEnKkCFLkiRJkjJkyJIkSZKkDBmyJEmSJClDhixJkiRJypAhS5IkSZIyZMiSJEmSpAwZsiRJkiQpQ4YsSZIkScqQIUuSJEmSMmTIkiRJkqQMGbIkSZIkKUOGLEmSJEnKkCFLkiRJkjJkyJIkSZKkDBmyJEmSJClDhixJkiRJypAhS5IkSZIyZMiSJEmSpAwZsiRJkiQpQ4YsSZIkScqQIUuSJEmSMmTIkiRJkqQMGbIkSZIkKUNTTPhV4bYkKSP//e9/w4cffhiefPLJ+PG///3v+F5qLf/3f/9XuDVR7969wx/+8IewwgorFO6RJLUFQ5YkZYRgdeONN4Ybbrgh3k7o5PImtbYnnniicKu+dP1tscUWYfPNN/d6lKRWZsiSpBZK4erUU0+NH9ORpRPLLIIzCGpraRaV98ykEvqLcW1yXW622WZen5LUSgxZktQCdGD333//2HElXO23336Fz0gdRxoIYNlq8WzX8ssvH6677rrCR5KkrBiyJKmZCFeELDuqqiYErtNOO61uhosBAq5flxBKUnYMWZLUDFtttVWcERgwYICzV6pKxW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z3XvNZ4NBGv6OzoLX995778VlZVTnO/744+Nsz7PPPttqIYtlfD/++GMMQM2dLXv++efDtttuG7777rvCPRP9/ve/j/+eNddcM8w+++yhc+fOhc/kE7NYLLP3yILWQYjiKA6CVdovnqTBYAeF1Za4JnkrxjXIa5/L5ZsuFyGLUWguGmexlBdc74xCw1HolkmB1fajPmaEjj322HDFFVeEAw88MPztb3+LQauxkMW+po8++iiMHDkyzDnnnGG++eab7KHFfA/LNS+44IK6JXuELF7wt9tuu9ClS5d4H/i5hC+qGzKrxtldJ554Yrj00kvD3//+9/g9PO7DDjssvPDCC2H99dcPq6++ephmmmnCMcccE0NcR56Fa2t0/lky6Yx4tgivtCupM5s6scwewL+12hvXJs9/2t60Jzldp5tvvrmvhRXKxZ6s4oZMygOudV6oU0MpZYm9TJdddlkMWOuss07YbLPNwtRTT134bHnvvvtuDKsrrrhi7LivscYaMewQehpC6GFpX//+/evtiWIWilB09NFHx6/B119/HYYMGRL23XffMGbMmPgYzznnnBiwwAHJFOdghur0008PjzzySDj00EPDKqusEhZaaKEw00wzxa/TRGkJUdqTqJYhXDErnopwccYhs4QM4DAAQJttwFJHkAIVKzi4PrlWwbXrmZyVq/mQlRK4y3yUN2lQwQ5SNhykmYjzpM4444zQtWvXsMcee4S55pqr8JkQZpxxxnqzS8xE3XbbbeEvf/lL3VljydNPPx1ntlhQwaxTcQU/QtIll1xSt9z1kEMOCS+99FI8i4sXeH73o48+GsMbmI1iBuubb76JIeyOO+6I31/szjvvjJ9ntqt4ueF0000X/3+pLMjj0G+85rORVhYUh6sUrKSOjnaAa5VjYrh2uZ7pWxu0Ji831QXTNLyUF17z2SiumqcQK/ClowIOOOCAsNRSS8XbhKJx48bFfUzFe5nuu+++WBiDQ37XXXfd8OCDD8a9XLyxH4WR/csvvzwWlmB26qefforf98ADD9QFOYpU7LzzznG2iQBHkQ3CHBUB00xY+v28Z3kbv5PHwawVv2fBBReMAS2tbCiHn5dmxvQbg1bLsJKALQvsueJvybVpuFI1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yy3HpkaSObeqpp46H/aaS7Nzed99945lYkiTVGkNWDeNgzqFDh8YODecXcIhnjx494iZ0TqU//vjjw3nnnRceeeSRcPLJJ4dbbrml8J3VhfN2JFUHNkZTkp1ZrTnmmKNwr1Q7nPlTnlnVeyJDVg37+eef47ky3333XeGe+pZeeumw6qqrxiU7BK811lgjBrNq88EHH8R/KzNbL774YjynhHN0mLWTJDWf1cIkqXkMWTWsc+fOYffddw/XXntteOyxx8KIESNC37594+cGDx4cZ67Y13T++efHJYOcV1MNG9AJjW+88UasTAY20C+wwAKhV69e8d+39dZbh/XXXz8MGDAglo/OK0dTW86/oSRJlfE1s75chKw8/6dTHnmFFVaI07ezzTZbrPQFPq6mil7PPfdcWG+99eKSx0UXXTSss8464eabby58dqLu3buHLbbYIhx11FGxVLSHlkqS2pIdTUlwJitHWArI/iXKJs8111yFezu+H3/8MQYqCniUs8EGG4TbbrstvPLKK/EcnpNOOilsv/32YcEFFwxTTuklLklqWwYtSfZAc4Q9Sh999FGc0ZpxxhkL906KMPb222+Hzz//vHBPiNUJ99hjjziTdMkll8Q9UKVGjx4dDjjggDjTtNRSS4Ujjjgi/pxy+7yoZPjMM8/E75ncPjCqki233HKx9PNKK60Ui3TcfvvtsUIiFl544fj7mKXzvB2Ba4Nr5bTTTrOzI0mS2pwhK0cINt9++22cySo+q6YUhST222+/cPjhh8ev5+2EE06IpZdx9tlnh2effTbeTig4sdNOO4Xrr78+7pn66quvwsUXXxwPIP3Xv/41SRGKq6++OlY9JJR98cUXhXvr4/EyK3XPPfeEjTbaKDz11FPhqquuCptvvnkMVVawUUO4tnDqqafGsJUClyS1Bc8KkmTIypFvvvkmBpq55547TDfddIV7JzXTTDOFWWedNX4tgYniGDfddFPhsyF88sknYfjw4WH8+PHxY8IQX1O8nG+11VYL/fr1i2GOji5nc6XZLwJXOkB4zjnnDNNMM028XYqwN2zYsBisCG18XfFMVap69fXXX4effvop3pbAPsTrrrsuhnSuE2azUuDaaqut4hEGklTKme+mo59ARV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7/dpWjaATLsh9//PFw+eWXh4MPPjiWTp533nnj24ILLhh69eoVllxyyTD//PPX3b/ooouGK664ot1KK//444/hk08+KXwktZx7wJVXXvv15SJkkarpLBWP7ku1av/99y/cCuGkk04q3JKyRahi4OrUU08NW221VejRo0dYeeWVwzbbbBMOPfTQcNVVV8WSyZPDTNJdd91V0ddKHR39DTuayiuufbcoTJSLkEXAcjZLecD1XTyL5VLBlnM2q77vv/8+nHvuuWHNNdcMW2+9dRy8euKJJwqfDWHppZcOq666aujevXv8eMMNNwwPPvhgeOGFF8Irr7wS3n///XgAcPHbZZddFpfrtSf/n5Ul+xrKmzS4YFs6US5CFuhs8h9fPMov1RIaODq9yYABA2zsMuDfsD7Ok7r11lvDqFGj4sfseR00aFAYNmxYeOONN+LnWP631157xc8TulgeSPnkGWaYIZZTLjXVVFPFt/Y05ZRTln1seWdl3uZxNkt5kwYW3JM1UW5CFh2lk08+OTZ8LG2RagnX9cCBAwsf/dbxZfZW2bCjOdFcc80VB62WW265OKNFoNptt93igZ/FB32mSn2zzjprhw4vH330UeGW1HJpUObGG2+M76W8cWByotyELPAfzx4VlrastNJKTuerJnAdcz2nJVtc59ddd128LWWtS5cuYciQIXFZ6vrrrx+mnnrqwmfq++yzzwq3mo4qhCwhZECM4hgrrrhi2HPPPcPtt98elys2pDnflwpu2DFomCPTlUv7UZzJUt5wVNIWW2xR+EjIVcgCFwDLqNLSKpYPGrZUjbiG2Q9TvESQGSwDVraYtbHD1HSNhaGGjB8/Ptx2221h0003DYcddljdwAFLE1mOuPfee4e11147PPDAA/XKwDf3+zBy5MjCLZXjtd80KZDyd7NvoTxh4M2iF/XlLmSBZVSUGWbkkouCTiozAXRYbRTV0aVwxTVLZbeEwQMCliPyqkZUKzz++OPDPvvsE959991437rrrhuGDx8ennvuuXDttdeGvn37xuDUr1+/OGP1888/N/v7VBnaG9uUyvG3Sn8vKxorL1LBLYtt1ZfLkAUaQTqkdEzBCwkd1hS4mOHioiF0OZKn9paCFcugisMV1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FmSJEmSlCFDliRJkiRlyJAlSZIkSRkyZEmSJElShgxZkiRJkpQhQ5YkSZIkZciQJUmSJEkZMmRJkiRJUoYMWZIkSZKUIUOWJEmSJGXIkCVJkiRJGTJkSZIkSVKGDFmSJEmSlCFDliRJkiRlyJAlSZIkSRkyZEmSJElSZkL4f+cyzpxOWESZAAAAAElFTkSuQmCC"- }- },- "cell_type": "markdown",- "metadata": {},- "source": [- "# Introducing Atomic Agents: Building AI with Modular Design\n",- "\n",- "Imagine building AI applications as easily as snapping together LEGO blocks. That's the idea behind [Atomic Agents](https://github.com/KennyVaneetvelde/atomic_agents), a new multi-agent framework inspired by **Atomic Design** principles.\n",- "\n",- "## Before we start, a brief background on Atomic Design\n",- "\n",- "First, let's talk about **Atomic Design**. Created by **Brad Frost**, it's a methodology for crafting design systems by breaking down interfaces into smaller, self-contained, reusable components. Think of it like atoms, molecules, and organisms in chemistry, but for UI design. This approach helps in creating scalable and consistent user interfaces while also allowing to modify/switch out any single part with minimal impact. Another analogy, as previously mentioned, is LEGO blocks where you can combine all the different, simple pieces to create something completely new and complex.\n",- "\n",- "## Why Atomic Agents?\n",- "\n",- "A lot of existing frameworks and methodologies for **Agentic AI** are focused on building autonomous multi-agent systems that you basically wind up and let go. While these can be fun to demo, they're not always practical for real-world applications. Real-life companies aren't looking for a bot that writes articles in a different style each time, with a different structure and a different tone. They want a bot that can write articles in a consistent style, with a consistent structure and a consistent tone that aligns with their brand. Beside fine-tuning a model, which requires a lot of data and money, and isn't even possible if you really want to use the latest GPT model, there's no practical way to gain full control of the output of these frameworks.\n",- "\n",- "In business, management rarely allocates budget just to create something that's cool but has no value. They want to see a return on investment. They want to see real business issues being solved and automated and cut costs. To achieve this, you need **modularity**, you need to be able to control the output, make sure it's not a black box, make the output reproducible, and make it reliable. This is where **Atomic Agents** come in.\n",- "\n",- "So how are these business problems solved traditionally, pre-AI? Well, before we even start writing code, we usually start with flows, user stories, customer journeys, ... and then we start breaking these down into smaller parts. We then start writing the necessary code. We'll have a function that takes in some input, processes it, and returns some output. We'll have another function that takes in that output, processes it, and stores it in a database. We'll have another function that queries the database, processes the data, and returns it to the user. The aim of **Atomic Agents** is to bring this same level of modularity and predictability to AI agent development.\n",- "\n",- "In other words, we are not looking to build \"An AI system that writes a blogpost\". We are looking for something highly structured and verbose. Specifically, we want to build an AI system that:\n",- "\n",- "1. Generates queries related to a subject\n",- "2. Identifies the top X most relevant articles\n",- "3. Visits each identified article's page\n",- "4. Extracts the text from each article\n",- "5. Generates a summary of each article\n",- "6. Stores the summaries in a vector database\n",- "7. Generates X questions around the subject\n",- "8. Uses the vector database to answer those questions\n",- "9. Re-synthesizes the answers into a coherent blogpost\n",- "\n",- "This approach; while being a lot more verbose, is also a lot more predictable, reliable, and, more importantly, usable in a real-world business.\n",- "\n",- "On top of that, we want to be able to fine-tune each individual step of that system if necessary, we want to be able to modify the system prompt for each task individually, be able to modify which tools are used, and how they are used, be able to choose where memory or context is shared, ... This is where **Atomic Agents** come in.\n",- "\n",- "## Anatomy of an Agent\n",- "\n",- "AI agents, not just in the **Atomic Agents** framework, take input from several sources, such as the **system prompt**, the **user input**, the (optionally) **available tools**, and **memory**. Within **Atomic Agents**, I wanted the developer to have full control over how each of these affects the output. This is why each of these are separate components within the framework. In developer terms, we speak of \"separation of concerns\" and \"single responsibility principle\" here.\n",- "\n",- "\n",- "\n",- "In the diagram above, you can see the different components that make up an **Atomic Agent**. Each agent has a \"run\" method, an input schema and an output schema, each with their own schema descriptions, property descriptions, ... all defined by the developer using **Pydantic models**. This enables us to dynamically generate the input to the agent, and to validate its output. This is important because it allows us to chain agents together effortlessly, all the while ensuring that the output of one agent is the correct input for the next agent. Thus, in the schema all the green boxes are things that are always sent to the agent, the blue boxes are sent to the agent in the case where Agent1 is chained to Agent2, and Agent1 must generate output using the input schema of Agent2.\n",- "\n",- "Tools have almost the exact same setup, each tool has an input schema, an output schema, and a \"run\" method. This allows us to largely treat tools and agents the same way, and to chain them together in the same way. This is in line with a personal philosophy of mine that, at least until we reach AGI, we should treat AI agents as very advanced text-processing tools that are part of a bigger pipeline, rather than as a completely new paradigm (See [my article on Defensive & Robust design in AI automation](https://medium.com/@kenny_v/defensive-and-robust-design-in-ai-automation-8e951c8e7fd7)).\n",- "\n",- "\n",- "\n",- "The real fun begins when you start chaining the input and output of different tools and agents together. By simply assigning the output schema of an agent to be the input schema to a tool, or to another agent, you can create complex AI applications that are still modular and easy to understand. If at any later point you change the tool, and change the schema, the entire system will still work without needing to change anything else."- ]- },- {- "cell_type": "markdown",- "metadata": {},- "source": [- "## Example: Building a simple AI agent\n",- "Now that we've covered the basics, let's build a simple AI agent using **Atomic Agents** and examine how it works under the hood.\n",- "\n",- "First, we need to install the Atomic Agents package. You can do this by running the following command:"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "# Install necessary packages\n",- "%pip install atomic-agents openai instructor"- ]- },- {- "cell_type": "markdown",- "metadata": {},- "source": [- "Or better yet, you can clone the repository from [here](https://github.com/KennyVaneetvelde/atomic_agents) and help me improve it!"- ]- },- {- "cell_type": "markdown",- "metadata": {},- "source": [- "Next, we will import the necessary components for creating the chatbot. Each component serves a specific purpose:\n",- "- `AgentMemory`: Manages the chat history.\n",- "- `BaseAgent`: The base class to create a custom chatbot. Can be extended for additional functionality if needed.\n",- "- `SystemPromptGenerator`: To define and generate system prompts."- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "import os\n",- "from atomic_agents.lib.components.system_prompt_generator import SystemPromptGenerator"- ]- },- {- "cell_type": "markdown",- "metadata": {},- "source": [- "Now let's define the system prompt information including background, steps, and output instructions. In this example, we will define a system prompt that asks the chatbot to respond to user inputs in rhyming verse.\n",- "\n",- "The structuring of the system prompts in this library is loosely inspired by the concept of **Patterns** in the [Fabric library](https://github.com/danielmiessler/fabric/tree/main/patterns)."- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "from rich.console import Console\n",- "\n",- "system_prompt_generator = SystemPromptGenerator(\n",- " background=[\n",- " 'This assistant is a general-purpose AI designed to be helpful and friendly.',\n",- " ],\n",- " steps=[\n",- " 'Understand the user\\'s input and provide a relevant response.',\n",- " 'Respond to the user.'\n",- " ],\n",- " output_instructions=[\n",- " 'Provide helpful and relevant information to assist the user.',\n",- " 'Be friendly and respectful in all interactions.',\n",- " 'Always answer in rhyming verse.'\n",- " ]\n",- ")\n",- "\n",- "Console().print(system_prompt_generator.generate_prompt())"- ]- },- {- "cell_type": "markdown",- "metadata": {},- "source": [- "This should have generated the following system prompt:\n",- "\n",- "``` markdown\n",- "# IDENTITY and PURPOSE\n",- "- This assistant is a general-purpose AI designed to be helpful and friendly.\n",- "\n",- "# INTERNAL ASSISTANT STEPS\n",- "- Understand the user's input and provide a relevant response.\n",- "- Respond to the user.\n",- "\n",- "# OUTPUT INSTRUCTIONS\n",- "- Provide helpful and relevant information to assist the user.\n",- "- Be friendly and respectful in all interactions.\n",- "- Always answer in rhyming verse.\n",- "- Always respond using the proper JSON schema.\n",- "- Always use the available additional information and context to enhance the response.\n",- "```\n",- "\n",- "Note how the last two output instructions are not part of the developer's specification, but are automatically added by the framework to increase reliability in the system prompt."- ]- },- {- "cell_type": "markdown",- "metadata": {},- "source": [- "Now that we have defined the system prompt, and thus essentially the behavior and purpose of the chatbot, it makes sense to define an initial memory with a message from the assistant to the user. This step is completely optional however as the `BaseAgent` that we will be using later has a check for this and will automatically create an empty memory if none is provided."- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "from atomic_agents.lib.components.agent_memory import AgentMemory\n",- "\n",- "memory = AgentMemory()\n",- "initial_memory = [\n",- " {'role': 'assistant', 'content': 'How do you do? What can I do for you? Tell me, pray, what is your need today?'}\n",- "]\n",- "memory.load(initial_memory)"- ]- },- {- "cell_type": "markdown",- "metadata": {},- "source": [- "Now we are ready to create a custom chatbot. Either by using the `BaseAgent` class, or by extending it. Since this is a simple usecase, let's look at what it will look like if we simply use the class. In the code below, you can either specify your API key directly in the code or use an environment variable to store it.\n",- "\n",- "In this instance, I will use the OpenAI client with gpt-3.5-turbo. However, you can choose other clients such as **Anthropic**, **Mistral**, **Groq**, etc... For a full list, check out the [Instructor library docs](https://github.com/jxnl/instructor). Changing the client is as simple as changing the import statement, defining the client, and changing the `model` parameter to a model that is supported by that client (so, for example `llama3-70b-8192` on **Groq**)\n",- "\n",- "First, we'll set up the API key"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "API_KEY = ''\n",- "if not API_KEY:\n",- " # Get the environment variable\n",- " API_KEY = os.getenv('OPENAI_API_KEY')\n",- "\n",- "if not API_KEY:\n",- " raise ValueError('API key is not set. Please set the API key as a static variable or in the environment variable OPENAI_API_KEY.')"- ]- },- {- "cell_type": "markdown",- "metadata": {},- "source": [- "Now we'll set up the patched `Instructor` client. This is what takes the `Pydantic` models and uses them for input validation and output generation."- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "import instructor\n",- "import openai\n",- "from atomic_agents.agents.base_agent import BaseAgent, BaseAgentConfig\n",- "\n",- "client = instructor.from_openai(openai.OpenAI(api_key=API_KEY))\n",- "\n",- "agent = BaseAgent(\n",- " config=BaseAgentConfig(\n",- " client=client,\n",- " system_prompt_generator=system_prompt_generator,\n",- " model='gpt-4o-mini',\n",- " memory=memory,\n",- " )\n",- ")\n",- "\n",- "# Groq, for example would look like this:\n",- "# import groq\n",- "# client = instructor.from_groq(groq.Client(api_key=[YOUR API KEY]))\n",- "# agent = BaseAgent(\n",- "# config=BaseAgentConfig(\n",- "# model='llama3-70b-8192',\n",- "# ...\n",- "# )\n",- "# )"- ]- },- {- "cell_type": "markdown",- "metadata": {},- "source": [- "Now we are ready to run the chatbot. Let's start by printing the initial message, followed by a simple chat-loop. Personally, I like to have /exit and /quit as commands to exit the chatbot, but you can change this to whatever you like."- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "print(f'Agent: {initial_memory[0][\"content\"]}')\n",- "\n",- "while True:\n",- " user_input = input('You: ')\n",- " if user_input.lower() in ['/exit', '/quit']:\n",- " print('Exiting chat...')\n",- " break\n",- " \n",- " response = agent.run(agent.input_schema(chat_message=user_input))\n",- " print(f'Agent: {response.chat_message}')"- ]- },- {- "cell_type": "markdown",- "metadata": {},- "source": [- "## Behind the scenes\n",- "\n",- "So, what is happening behind the scenes when we run the chatbot? Let's dissect the `BaseAgent` and understand how it works.\n",- "\n",- "First off, as mentioned before, each tool and each agent has an **input schema** and an **output schema**.\n",- "\n",- "These schemas all extend from what is called the `BaseIOSchema` class. This class itself is a Pydantic model with some predefined methods to facilitate storing a structured response in memory and to facilitate printing the response to the console using the `rich` library."- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "from pydantic import BaseModel, Field\n",- "from rich.json import JSON\n",- "\n",- "class BaseIOSchema(BaseModel):\n",- " \"\"\"\n",- " Base class for input and output schemas for chat agents.\n",- " \"\"\"\n",- " def __str__(self):\n",- " return self.model_dump_json()\n",- " \n",- " def __rich__(self):\n",- " json_str = self.model_dump_json()\n",- " return JSON(json_str)\n",- " \n",- "class BaseAgentInputSchema(BaseIOSchema):\n",- " \"\"\"This schema represents the user input message exchanged between the user and the chat agent.\"\"\"\n",- " \n",- " chat_message: str = Field(\n",- " ...,\n",- " description='The chat message exchanged between the user and the chat agent. '\n",- " 'This represents the message sent by the user.'\n",- " )\n",- "\n",- "class BaseAgentOutputSchema(BaseIOSchema):\n",- " \"\"\"This schema represents the response message exchanged between the user and the chat agent.\"\"\"\n",- " \n",- " chat_message: str = Field(\n",- " ...,\n",- " description='The chat message exchanged between the user and the chat agent. '\n",- " 'This contains the markdown-enabled response generated by the chat agent.'\n",- " )"- ]- },- {- "cell_type": "markdown",- "metadata": {},- "source": [- "In the code above, you can see that the `BaseAgentInputSchema` and `BaseAgentOutputSchema` both:\n",- "- Extend from `BaseIOSchema`\n",- "- Have a `chat_message` field with a `description` property \n",- "- Have a Config class with a `title`, `description`, and `json_schema_extra` property.\n",- "\n",- "Let's analyze why these title and description properties are important, by looking at what will be presented to the LLM model when we run the chatbot. We can do this by simply dumping one of the schemas to JSON"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "import json\n",- "\n",- "print(json.dumps(BaseAgentOutputSchema.model_json_schema(), indent=2))"- ]- },- {- "cell_type": "markdown",- "metadata": {},- "source": [- "This will output something like this:\n",- "\n",- "```json\n",- "{\n",- " \"description\": \"This schema represents the response message exchanged between the user and the chat agent.\",\n",- " \"properties\": {\n",- " \"chat_message\": {\n",- " \"description\": \"The chat message exchanged between the user and the chat agent. This contains the markdown-enabled response generated by the chat agent.\",\n",- " \"title\": \"Chat Message\",\n",- " \"type\": \"string\"\n",- " }\n",- " },\n",- " \"required\": [\n",- " \"chat_message\"\n",- " ],\n",- " \"title\": \"BaseAgentOutputSchema\",\n",- " \"type\": \"object\"\n",- "}\n",- "```\n",- "\n",- "This is what the LLM model will see and be constricted by when generating a response. Additionally, this allows for easy generation of documentation as well since these properties are generally accepted by most documentation generators. For example by using [sphinx-pydantic](https://sphinx-pydantic.readthedocs.io/en/latest/).\n",- "\n",- "Thus, changing the title and description to be more clear, descriptive and precise is encouraged both to improve & fine-tune the agent's performance, but also to improve the documentation of the agent.\n",- "\n",- "Note that even though in the base chat agent both the input and output schemas have a `chat_message` field, this is not a requirement. We can easily specify any schema we like as the input or the output schema.\n",- "\n",- "For example, we can even have a nested schema with enums, lists, and more complex structures as demonstrated below:"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "from enum import Enum\n",- "from typing import List, Optional\n",- "\n",- "\n",- "class YelpCategory(Enum):\n",- " ITALIAN = \"italian\"\n",- " MEXICAN = \"mexican\"\n",- " PIZZA = \"pizza\"\n",- " SUSHI = \"sushi\"\n",- " CHINESE = \"chinese\"\n",- " INDIAN = \"indian\"\n",- " THAI = \"thai\"\n",- " FRENCH = \"french\"\n",- " GREEK = \"greek\"\n",- " JAPANESE = \"japanese\"\n",- " KOREAN = \"korean\"\n",- " VIETNAMESE = \"vietnamese\"\n",- " AMERICAN = \"american\"\n",- " BBQ = \"bbq\"\n",- " BURGERS = \"burgers\"\n",- " SEAFOOD = \"seafood\"\n",- " STEAKHOUSES = \"steakhouses\"\n",- " VEGAN = \"vegan\"\n",- " VEGETARIAN = \"vegetarian\"\n",- "\n",- "class PriceRange(Enum):\n",- " ONE = \"1\"\n",- " TWO = \"2\"\n",- " THREE = \"3\"\n",- " FOUR = \"4\"\n",- "\n",- "class YelpSearchToolInputSchema(BaseIOSchema):\n",- " \"\"\"This schema represents a single result from the Yelp API.\"\"\"\n",- " \n",- " location: str = Field(..., description=\"Location to search for food.\")\n",- " term: Optional[str] = Field(None, description=\"Search term (e.g., 'pizza', 'sushi').\")\n",- " categories: Optional[List[YelpCategory]] = Field(None, description=\"Categories to filter by (e.g., 'italian, mexican').\")\n",- " price: Optional[List[PriceRange]] = Field(None, description=\"Price range to filter by (e.g., '1', '2', '3', '4'). Can be multiple. 1 is cheap. 2 and 3 are mid-range. 4 is the most high-end.\")\n",- " open_now: Optional[bool] = Field(False, description=\"Filter for businesses that are open now.\")\n",- " limit: Optional[int] = Field(10, description=\"Number of results to return.\")"- ]- },- {- "cell_type": "markdown",- "metadata": {},- "source": [- "Some interesting things to note here:\n",- "- The price ranges and categories are defined as an enum, which means that the only valid values are the ones specified in the enum.\n",- "- The description of the `price_range` field lists what the values mean, which is important for the model to understand the context of the input. This essentially replaces the need for a prompt or few-show examples in the traditional sense.\n",- "- If this is not sufficient, [Pydantic examples](https://docs.pydantic.dev/latest/concepts/fields/#customizing-json-schema) can still be added as well per property."- ]- },- {- "cell_type": "markdown",- "metadata": {},- "source": [- "## Extending the BaseAgent"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "import json\n",- "from pydantic import Field, create_model\n",- "from atomic_agents.agents.base_agent import BaseIOSchema, BaseAgent, BaseAgentConfig\n",- "from atomic_agents.lib.components.system_prompt_generator import SystemPromptGenerator, SystemPromptInfo\n",- "from atomic_agents.lib.tools.base_tool import BaseTool\n",- "from atomic_agents.lib.utils.format_tool_message import format_tool_message\n",- "\n",- "class ToolInterfaceAgentConfig(BaseAgentConfig):\n",- " tool_instance: BaseTool\n",- " return_raw_output: bool = False\n",- "\n",- "class ToolInputModel(BaseIOSchema):\n",- " \"\"\"This model is used to define the input schema for the tool interface agent.\"\"\"\n",- " \n",- " tool_input: str = Field(..., description=\"Tool input. Presented as a single question or instruction\")\n",- "\n",- "\n",- "class ToolInterfaceAgent(BaseAgent):\n",- " \"\"\"\n",- " A specialized chat agent designed to interact with a specific tool.\n",- "\n",- " This agent extends the BaseAgent to include functionality for interacting with a tool instance.\n",- " It generates system prompts, handles tool input and output, and can optionally return raw tool output.\n",- "\n",- " Attributes:\n",- " tool_instance: The instance of the tool this agent will interact with.\n",- " return_raw_output (bool): Whether to return the raw output from the tool.\n",- " \"\"\"\n",- "\n",- " def __init__(self, config: ToolInterfaceAgentConfig):\n",- " \"\"\"\n",- " Initializes the ToolInterfaceAgent.\n",- "\n",- " Args:\n",- " config (ToolInterfaceAgentConfig): Configuration for the tool interface agent.\n",- " \"\"\"\n",- " super().__init__(config=config)\n",- " \n",- " self.tool_instance = config.tool_instance\n",- " self.return_raw_output = config.return_raw_output\n",- " \n",- " # Create a new model with the updated schema\n",- " self.input_schema = create_model(\n",- " self.tool_instance.tool_name,\n",- " 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}')),\n",- " __base__=ToolInputModel\n",- " )\n",- " \n",- " # Manually set the configuration attributes\n",- " self.input_schema.model_config['title'] = self.tool_instance.tool_name\n",- " self.input_schema.model_config['description'] = self.tool_instance.tool_description\n",- " self.input_schema.model_config['json_schema_extra'] = {\n",- " 'title': self.tool_instance.tool_name,\n",- " 'description': self.tool_instance.tool_description\n",- " }\n",- " \n",- " if self.return_raw_output:\n",- " self.output_schema = self.tool_instance.output_schema\n",- " \n",- " self.system_prompt_generator = SystemPromptGenerator(\n",- " background=[\n",- " f\"This AI agent is designed to interact with the {self.tool_instance.tool_name} tool.\",\n",- " f\"Tool description: {self.tool_instance.tool_description}\"\n",- " ],\n",- " steps=[\n",- " \"Get the user input.\",\n",- " \"Convert the input to the proper parameters to call the tool.\",\n",- " \"Call the tool with the parameters.\",\n",- " \"Respond to the user\"\n",- " ],\n",- " output_instructions=[\n",- " \"Make sure the tool call will maximize the utility of the tool in the context of the user input.\",\n",- " \"Process the output of the tool into a human readable format and/or use it to respond to the user input.\" if self.return_raw_output else \"Return the raw output of the tool.\"\n",- " ]\n",- " )\n",- " \n",- " \n",- " def _get_and_handle_response(self):\n",- " \"\"\"\n",- " Handles obtaining and processing the response from the tool.\n",- "\n",- " This method gets the response from the tool, formats the tool input, adds it to memory,\n",- " runs the tool, and processes the tool output. If `return_raw_output` is True, it returns\n",- " the raw tool output; otherwise, it processes the output and returns the response.\n",- " \n",- " Returns:\n",- " BaseModel: The processed response or raw tool output.\n",- " \"\"\"\n",- " tool_input = self.get_response(response_model=self.tool_instance.input_schema)\n",- " formatted_tool_input = format_tool_message(tool_input)\n",- " \n",- " self.memory.add_message('assistant', 'TOOL CALL: ' + json.dumps(formatted_tool_input))\n",- " tool_output = self.tool_instance.run(tool_input)\n",- " self.memory.add_message('assistant', 'TOOL RESPONSE: ' + tool_output.model_dump_json())\n",- " \n",- " if self.return_raw_output:\n",- " return tool_output\n",- " \n",- " self.memory.add_message('assistant', 'I will now formulate a response for the user based on the tool output.')\n",- " response = self.get_response(response_model=self.output_schema) \n",- " return response\n"- ]- },- {- "cell_type": "markdown",- "metadata": {},- "source": [- "As mentioned before, another way to create a new agent is by extending the `BaseAgent` class. This allows for more flexibility and customization. Let's look at an example where we extend the `BaseAgent` class to create an agent of which the output will always match the required input for a tool. To achieve this and get both the tool call and tool response in the memory, we will want to override the method `_get_and_handle_response`. Additionally, we will want to generate the input schema **dynamically** in order to be able to use any tool we want with this new agent.\n",- "\n",- "A simple example of how to use this ToolInterfaceAgent could be as follows:"- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "import os\n",- "import instructor\n",- "import openai\n",- "from rich.console import Console\n",- "\n",- "from atomic_agents.agents.tool_interface_agent import ToolInterfaceAgent, ToolInterfaceAgentConfig\n",- "from atomic_agents.lib.tools.search.searxng_tool import SearxNGTool, SearxNGToolConfig\n",- "\n",- "def initialize_searxng_tool():\n",- " \"\"\"\n",- " Initialize the SearxNGTool with configuration.\n",- " \"\"\"\n",- " base_url = os.getenv('SEARXNG_BASE_URL')\n",- " config = SearxNGToolConfig(base_url=base_url, max_results=10)\n",- " return SearxNGTool(config)\n",- "\n",- "def initialize_agent(client, searxng_tool):\n",- " \"\"\"\n",- " Initialize the ToolInterfaceAgent with the given client and SearxNGTool.\n",- " \"\"\"\n",- " agent_config = ToolInterfaceAgentConfig(\n",- " client=client,\n",- " model='gpt-4o-mini',\n",- " tool_instance=searxng_tool,\n",- " return_raw_output=False\n",- " )\n",- " return ToolInterfaceAgent(config=agent_config)\n",- "\n",- "def main():\n",- " console = Console()\n",- " client = instructor.from_openai(\n",- " openai.OpenAI(\n",- " base_url='http://localhost:1234/v1'\n",- " )\n",- " )\n",- " searxng_tool = initialize_searxng_tool()\n",- " agent = initialize_agent(client, searxng_tool)\n",- "\n",- " console.print(\"ToolInterfaceAgent with SearxNGTool is ready.\")\n",- "\n",- " while True:\n",- " user_input = input('You: ')\n",- " if user_input.lower() in ['exit', 'quit']:\n",- " print('Exiting chat...')\n",- " break\n",- " \n",- " # Fix this\n",- " response = agent.run(agent.input_schema(tool_input=user_input))\n",- " console.print(f'Agent: {response.chat_message}')\n",- "\n",- "if __name__ == \"__main__\":\n",- " main()"- ]- },- {- "cell_type": "markdown",- "metadata": {},- "source": [- "## Conclusion\n",- "\n",- "For now, that's it! While this guide is by no means complete, it should serve as a decent starting point for anyone looking to get started with **Atomic Agents**. If you have any questions, feel free to reach out to me! I'm always happy to help out and answer any questions you might have. If you want to contribute to the project, feel free to open a pull request on the [GitHub repository](https://github.com/KennyVaneetvelde/atomic_agents). Any help is greatly appreciated!"- ]- },- {- "cell_type": "markdown",- "metadata": {},- "source": [- "---"- ]- },- {- "cell_type": "markdown",- "metadata": {},- "source": [- "\n",- "If this article sparks your interest and you have any business inquiries, feel free to get in touch with me on [LinkedIn](https://www.linkedin.com/in/kennyvaneetvelde/). As an experienced life-long full-stack developer and course author with a grand fascination for what makes things ‘tick’ and a love for AI that started in my early teens, I am absolutely certain I can assist with anything from coaching to product development to bespoke consultancy services."- ]- }- ],- "metadata": {- "kernelspec": {- "display_name": "venv",- "language": "python",- "name": "python3"- },- "language_info": {- "codemirror_mode": {- "name": "ipython",- "version": 3- },- "file_extension": ".py",- "mimetype": "text/x-python",- "name": "python",- "nbconvert_exporter": "python",- "pygments_lexer": "ipython3",- "version": "3.12.3"- }- },- "nbformat": 4,- "nbformat_minor": 2-}diff --git a/atomic-agents/examples/notebooks/yelp_agent.ipynb b/atomic-agents/examples/notebooks/yelp_agent.ipynbdeleted file mode 100644index 0cf2902..0000000--- a/atomic-agents/examples/notebooks/yelp_agent.ipynb+++ /dev/null@@ -1,295 +0,0 @@-{- "cells": [- {- "cell_type": "markdown",- "metadata": {},- "source": [- "# Yelp Restaurant Finder Agent\n",- "\n",- "This notebook demonstrates how to create a restaurant finder agent using the Atomic Agents library. The agent will interact with users to gather their preferences and search for restaurants using the Yelp API.\n",- "\n",- "[](https://colab.research.google.com/github/KennyVaneetvelde/atomic_agents/blob/main/examples/notebooks/yelp_agent.ipynb)\n"- ]- },- {- "cell_type": "markdown",- "metadata": {},- "source": [- "## Prerequisites\n",- "\n",- "Before proceeding with this notebook, it is highly recommended to read up on the basics of the following libraries:\n",- "\n",- "- **Pydantic**: A data validation and settings management library using Python type annotations. You can find more information and documentation at [Pydantic GitHub](https://github.com/pydantic/pydantic).\n",- "- **Instructor**: A Python library that simplifies working with structured outputs from large language models (LLMs). It provides a user-friendly API to manage validation, retries, and streaming responses. More details can be found at [Instructor GitHub](https://github.com/jxnl/instructor).\n",- "\n",- "Understanding these libraries will help you make the most of this library.\n"- ]- },- {- "cell_type": "markdown",- "metadata": {},- "source": [- "## Step 1: Install Necessary Packages\n",- "\n",- "First, we need to install the required packages. Run the following command to install `atomic-agents`, `openai`, and `instructor` libraries."- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "# Install necessary packages\n",- "%pip install atomic-agents openai instructor"- ]- },- {- "cell_type": "markdown",- "metadata": {},- "source": [- "## Step 2: Import Libraries\n",- "\n",- "We will import the necessary libraries for creating the restaurant finder agent."- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "import os\n",- "import logging\n",- "from typing import Union\n",- "from pydantic import BaseModel, Field\n",- "import instructor\n",- "import openai\n",- "from rich.console import Console\n",- "\n",- "from atomic_agents.lib.components.agent_memory import AgentMemory\n",- "from atomic_agents.lib.components.system_prompt_generator import SystemPromptGenerator\n",- "from atomic_agents.agents.base_agent import BaseAgent, BaseAgentOutputSchema, BaseAgentConfig\n",- "from atomic_agents.lib.tools.yelp_restaurant_finder_tool import YelpSearchTool, YelpSearchToolConfig, YelpSearchToolInputSchema"- ]- },- {- "cell_type": "markdown",- "metadata": {},- "source": [- "## Step 3: Define System Prompt Information\n",- "\n",- "Define the system prompt information including background, steps, and output instructions."- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "# Initialize the system prompt generator with the defined system prompt and dynamic info providers\n",- "system_prompt_generator = SystemPromptGenerator(\n",- " background=[\n",- " 'This assistant is a restaurant finder AI designed to help users find the best restaurants based on their preferences by asking clarifying questions.',\n",- " ],\n",- " steps=[\n",- " 'Greet the user and introduce yourself as a restaurant finder assistant.',\n",- " 'Inspect the required Yelp schema and identify the necessary filters.',\n",- " 'Ask the user questions to gather information for each filter until all required information is clear.',\n",- " 'Use the chat responses to gather all necessary information from the user.',\n",- " '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",- " ]\n",- ")"- ]- },- {- "cell_type": "markdown",- "metadata": {},- "source": [- "## Step 4: Initialize Components\n",- "\n",- "Initialize the system prompt generator, chat memory, and console for output."- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "# Initialize chat memory to store conversation history\n",- "memory = AgentMemory()\n",- "# Define initial memory with a greeting message from the assistant\n",- "initial_memory = [\n",- " {'role': 'assistant', 'content': 'Hello, can I help you find a restaurant?'}\n",- "]\n",- "# Load the initial memory into the chat memory\n",- "memory.load(initial_memory)\n",- "\n",- "console = Console()"- ]- },- {- "cell_type": "markdown",- "metadata": {},- "source": [- "## Step 5: Initialize the Client\n",- "\n",- "Initialize the client using the `instructor` library. For all supported clients such as Anthropic & Gemini, refer to the `instructor` library documentation."- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "# Initialize the client\n",- "client = instructor.from_openai(openai.OpenAI())"- ]- },- {- "cell_type": "markdown",- "metadata": {},- "source": [- "## Step 6: Initialize the YelpSearchTool\n",- "\n",- "Set up the YelpSearchTool with the necessary configuration."- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "# Initialize the YelpSearchTool\n",- "yelp_tool = YelpSearchTool(YelpSearchToolConfig(api_key=os.getenv('YELP_API_KEY'), max_results=10))"- ]- },- {- "cell_type": "markdown",- "metadata": {},- "source": [- "## Step 7: Define a Custom Response Schema\n",- "\n",- "Create a custom response schema that can handle both chat responses and Yelp search tool responses."- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "# Define a custom response schema that can handle both chat responses and Yelp search tool responses\n",- "class ResponseSchema(BaseModel):\n",- " \"\"\"The response schema for the chat agent. The output will either be a chat response, or an API call to the yelp search tool.\"\"\"\n",- " \n",- " chosen_schema: Union[BaseAgentOutputSchema, YelpSearchToolInputSchema] = Field(..., description='The response from the chat agent.')"- ]- },- {- "cell_type": "markdown",- "metadata": {},- "source": [- "## Step 8: Create the Chat Agent\n",- "\n",- "Create a chat agent with the specified model, system prompt generator, and memory."- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "# Create a chat agent with the specified model, system prompt generator, and memory\n",- "agent = BaseAgent(\n",- " config=BaseAgentConfig(\n",- " client=client, \n",- " system_prompt_generator=system_prompt_generator,\n",- " model='gpt-4o-mini',\n",- " memory=memory,\n",- " output_schema=ResponseSchema\n",- " )\n",- ")\n",- "\n",- "console.print(\"BaseAgent with YelpSearchTool is ready.\")\n",- "console.print(f'Agent: {initial_memory[0][\"content\"]}')"- ]- },- {- "cell_type": "markdown",- "metadata": {},- "source": [- "## Step 9: Run the Agent\n",- "\n",- "Start the agent to interact with the user. The agent will ask for user input, process it, and provide responses based on the gathered information.\n",- "Try telling it you would like some pizza, it should ask for your location and other information until it feels it can properly call the Yelp API with the information it has gathered."- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "while True:\n",- " user_input = input('You: ')\n",- " if user_input.lower() in ['exit', 'quit']:\n",- " print('Exiting chat...')\n",- " break\n",- "\n",- " response = agent.run(agent.input_schema(chat_message=user_input).model_dump())\n",- " \n",- " # Check the type of the response schema\n",- " if isinstance(response.chosen_schema, YelpSearchToolInputSchema):\n",- " output = yelp_tool.run(response.chosen_schema)\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.chat_message\n",- " else:\n",- " output = response.chosen_schema.chat_message\n",- " \n",- " console.print(f'Agent: {output}')"- ]- },- {- "cell_type": "markdown",- "metadata": {},- "source": [- "## Conclusion\n",- "\n",- "In this notebook, we demonstrated how to create a restaurant finder agent using the Atomic Agents library. The agent interacts with users to gather their preferences and searches for restaurants using the Yelp API. You can further customize the agent and enhance its capabilities based on your requirements."- ]- }- ],- "metadata": {- "kernelspec": {- "display_name": "venv",- "language": "python",- "name": "python3"- },- "language_info": {- "codemirror_mode": {- "name": "ipython",- "version": 3- },- "file_extension": ".py",- "mimetype": "text/x-python",- "name": "python",- "nbconvert_exporter": "python",- "pygments_lexer": "ipython3",- "version": "3.12.3"- }- },- "nbformat": 4,- "nbformat_minor": 2-}diff --git a/atomic-agents/examples/notebooks/youtube_knowledge_extraction.ipynb b/atomic-agents/examples/notebooks/youtube_knowledge_extraction.ipynbdeleted file mode 100644index 55689f0..0000000--- a/atomic-agents/examples/notebooks/youtube_knowledge_extraction.ipynb+++ /dev/null@@ -1,343 +0,0 @@-{- "cells": [- {- "cell_type": "markdown",- "metadata": {},- "source": [- "# YouTube Knowledge Extraction Tutorial\n",- "\n",- "This tutorial demonstrates how to use the Atomic Agents library to create an agent that extracts knowledge and insights from YouTube video transcripts.\n",- "\n",- "[](https://colab.research.google.com/github/KennyVaneetvelde/atomic_agents/blob/main/examples/notebooks/youtube_knowledge_extraction.ipynb)\n",- "\n",- "## Prerequisites\n",- "\n",- "Before proceeding, make sure you have a good understanding of the following libraries:\n",- "\n",- "- **Pydantic**: A data validation and settings management library using Python type annotations. ([Pydantic GitHub](https://github.com/pydantic/pydantic))\n",- "- **Instructor**: A Python library that simplifies working with structured outputs from large language models (LLMs). ([Instructor GitHub](https://github.com/jxnl/instructor))\n",- "\n",- "You'll also need an OpenAI API key to use the GPT models. If you don't have one, you can sign up at [OpenAI's website](https://openai.com/).\n"- ]- },- {- "cell_type": "markdown",- "metadata": {},- "source": [- "## Step 1: Install Required Packages\n",- "\n",- "First, let's install the necessary packages for our YouTube knowledge extraction agent."- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "# Install required packages\n",- "%pip install atomic-agents openai instructor python-dotenv"- ]- },- {- "cell_type": "markdown",- "metadata": {},- "source": [- "## Step 2: Set Up OpenAI API Key\n",- "\n",- "To use the OpenAI API, you need to set up your API key. You have three options:\n",- "\n",- "1. Enter it directly in the code (not recommended for shared notebooks)\n",- "2. Use a .env file\n",- "3. Input the key manually when prompted\n",- "\n",- "Choose the method that best suits your needs and security requirements."- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "import os\n",- "from dotenv import load_dotenv\n",- "\n",- "# Option 1: Set the API key directly (replace with your actual API key)\n",- "# os.environ[\"OPENAI_API_KEY\"] = \"your-api-key-here\"\n",- "\n",- "# Option 2: Load from .env file\n",- "load_dotenv()\n",- "\n",- "# Option 3: Input the key manually\n",- "if \"OPENAI_API_KEY\" not in os.environ:\n",- " os.environ[\"OPENAI_API_KEY\"] = input(\"Enter your OpenAI API key: \")\n",- "\n",- "# Verify that the API key is set\n",- "if not os.getenv(\"OPENAI_API_KEY\"):\n",- " raise ValueError(\"OpenAI API key is not set. Please set it using one of the provided methods.\")"- ]- },- {- "cell_type": "markdown",- "metadata": {},- "source": [- "## Step 3: Import Libraries\n",- "\n",- "Now, let's import the necessary libraries for creating the YouTube knowledge extraction agent."- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "import instructor\n",- "import openai\n",- "from pydantic import BaseModel, Field\n",- "from rich.console import Console\n",- "from rich.markdown import Markdown\n",- "from typing import List, Optional\n",- "\n",- "from atomic_agents.agents.base_agent import BaseAgent, BaseAgentConfig\n",- "from atomic_agents.lib.components.system_prompt_generator import SystemPromptContextProviderBase, SystemPromptGenerator\n",- "from atomic_agents.lib.tools.yt_transcript_scraper_tool import YouTubeTranscriptTool, YouTubeTranscriptToolConfig, YouTubeTranscriptToolInputSchema"- ]- },- {- "cell_type": "markdown",- "metadata": {},- "source": [- "## Step 4: Initialize Components\n",- "\n",- "Let's initialize the necessary components including the console, client, and YouTube transcript scraper tool."- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "console = Console()\n",- "client = instructor.from_openai(openai.OpenAI())\n",- "yt_scraper_tool = YouTubeTranscriptTool(config=YouTubeTranscriptToolConfig())"- ]- },- {- "cell_type": "markdown",- "metadata": {},- "source": [- "## Step 5: Define System Prompt Information\n",- "\n",- "Now, we'll define the system prompt information including background, steps, output instructions, and context providers. This information guides the agent's behavior and output format."- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "class YtTranscriptProvider(SystemPromptContextProviderBase):\n",- " def __init__(self, title):\n",- " super().__init__(title)\n",- " self.transcript = None\n",- " self.duration = None\n",- " self.metadata = None\n",- " \n",- " def get_info(self) -> str:\n",- " return f'VIDEO TRANSCRIPT: \"{self.transcript}\"\\n\\nDURATION: {self.duration}\\n\\nMETADATA: {self.metadata}'\n",- " \n",- "transcript_provider = YtTranscriptProvider(title='YouTube Transcript')\n",- "system_prompt_generator = SystemPromptGenerator(\n",- " background=[\n",- " 'This Assistant is an expert at extracting knowledge and other insightful and interesting information from YouTube transcripts.'\n",- " ],\n",- " steps=[\n",- " 'Analyse the YouTube transcript thoroughly to extract the most valuable insights, facts, and recommendations.',\n",- " 'Adhere strictly to the provided schema when extracting information from the input content.',\n",- " 'Ensure that the output matches the field descriptions, types and constraints exactly.',\n",- " ],\n",- " output_instructions=[\n",- " 'Only output Markdown-compatible strings.',\n",- " 'Ensure you follow ALL these instructions when creating your output.'\n",- " ],\n",- " context_providers={'yt_transcript': transcript_provider}\n",- ")"- ]- },- {- "cell_type": "markdown",- "metadata": {},- "source": [- "## Step 6: Define Response Model\n",- "\n",- "Let's define the response model with detailed descriptions, constraints, and field types. This model will structure the output of our knowledge extraction agent."- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "class ResponseModel(BaseModel):\n",- " summary: str = Field(..., description=\"A short summary of the content, including who is presenting and the content being discussed.\")\n",- " insights: List[str] = Field(..., min_items=5, max_items=5, description=\"exactly 5 of the best insights and ideas from the input.\")\n",- " quotes: List[str] = Field(None, min_items=5, max_items=5, description=\"exactly 5 of the most surprising, insightful, and/or interesting quotes from the input.\")\n",- " habits: Optional[List[str]] = Field(None, min_items=5, max_items=5, description=\"exactly 5 of the most practical and useful personal habits mentioned by the speakers.\")\n",- " facts: List[str] = Field(..., min_items=5, max_items=5, description=\"exactly 5 of the most surprising, insightful, and/or interesting valid facts about the greater world mentioned in the content.\")\n",- " recommendations: List[str] = Field(..., min_items=5, max_items=5, description=\"exactly 5 of the most surprising, insightful, and/or interesting recommendations from the content.\") \n",- " references: List[str] = Field(..., description=\"All mentions of writing, art, tools, projects, and other sources of inspiration mentioned by the speakers.\")\n",- " one_sentence_takeaway: str = Field(..., description=\"The most potent takeaways and recommendations condensed into a single 20-word sentence.\")"- ]- },- {- "cell_type": "markdown",- "metadata": {},- "source": [- "## Step 7: Create the Chat Agent\n",- "\n",- "Now, let's create a chat agent with the specified model, system prompt generator, and response model."- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "agent = BaseAgent(\n",- " config=BaseAgentConfig(\n",- " client=client,\n",- " system_prompt_generator=system_prompt_generator,\n",- " model='gpt-4o-mini',\n",- " output_schema=ResponseModel\n",- " )\n",- ")"- ]- },- {- "cell_type": "markdown",- "metadata": {},- "source": [- "## Step 8: Get YouTube Video URL\n",- "\n",- "Let's prompt the user to enter a YouTube video URL and use the YouTube transcript scraper tool to extract the transcript, duration, and metadata."- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "video_url = input('Enter the YouTube video URL: ')\n",- "scraped_transcript = yt_scraper_tool.run(YouTubeTranscriptToolInputSchema(video_url=video_url))\n",- "transcript_provider.transcript = scraped_transcript.transcript\n",- "transcript_provider.duration = scraped_transcript.duration\n",- "transcript_provider.metadata = scraped_transcript.metadata\n",- "\n",- "print(f\"Successfully scraped transcript for video: {scraped_transcript.metadata.get('title', 'Unknown Title')}\")\n",- "print(f\"Video duration: {scraped_transcript.duration} seconds\")"- ]- },- {- "cell_type": "markdown",- "metadata": {},- "source": [- "## Step 9: Run the Agent\n",- "\n",- "Now, let's run the agent to extract knowledge and insights from the YouTube video transcript."- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "print(\"Analyzing the transcript. This may take a few moments...\")\n",- "response = agent.run(agent.input_schema(chat_message='Perform your assignment on the YouTube video transcript present in your context. Do not reply with anything other than the output of the assignment.'))\n",- "print(\"Analysis complete!\")"- ]- },- {- "cell_type": "markdown",- "metadata": {},- "source": [- "## Step 10: Format and Print the Response\n",- "\n",- "Finally, let's convert the response to a dictionary, format it as a Markdown string, and print the response in a pretty Markdown format."- ]- },- {- "cell_type": "code",- "execution_count": null,- "metadata": {},- "outputs": [],- "source": [- "response_dict = response.model_dump()\n",- "\n",- "def format_markdown_section(title, items):\n",- " if isinstance(items, list):\n",- " return f\"## {title}\\n\" + \"\\n\".join([f\"- {item}\" for item in items]) + \"\\n\"\n",- " return f\"## {title}\\n{items}\\n\"\n",- "\n",- "markdown_string = \"\"\n",- "for key, value in response_dict.items():\n",- " title = key.replace('_', ' ').title()\n",- " markdown_string += format_markdown_section(title, value)\n",- "\n",- "markdown_response = Markdown(markdown_string)\n",- "console.print(markdown_response)"- ]- },- {- "cell_type": "markdown",- "metadata": {},- "source": [- "## Conclusion\n",- "\n",- "Congratulations! You've successfully created a YouTube knowledge extraction agent using the Atomic Agents library. Here's a summary of what we accomplished:\n",- "\n",- "1. Set up the environment and installed necessary packages.\n",- "2. Configured the OpenAI API key securely.\n",- "3. Initialized components including the OpenAI client and YouTube transcript scraper tool.\n",- "4. Defined a system prompt to guide the agent's behavior.\n",- "5. Created a structured response model to format the extracted information.\n",- "6. Built a chat agent using the Atomic Agents library.\n",- "7. Extracted and processed a YouTube video transcript.\n",- "8. Ran the agent to analyze the transcript and generate insights.\n",- "9. Formatted and displayed the results in a readable Markdown format.\n",- "\n",- "This agent can be further customized by modifying the system prompt information, response model, and other components to suit specific requirements. For example, you could adapt it to focus on different aspects of the video content or integrate it with other tools and APIs.\n",- "\n",- "Remember to handle API keys securely in your projects, especially when sharing or deploying your code."- ]- }- ],- "metadata": {- "kernelspec": {- "display_name": "Python 3",- "language": "python",- "name": "python3"- },- "language_info": {- "codemirror_mode": {- "name": "ipython",- "version": 3- },- "file_extension": ".py",- "mimetype": "text/x-python",- "name": "python",- "nbconvert_exporter": "python",- "pygments_lexer": "ipython3",- "version": "3.12.3"- }- },- "nbformat": 4,- "nbformat_minor": 4-}diff --git a/atomic-agents/examples/product_finder.py b/atomic-agents/examples/product_finder.pydeleted file mode 100644index afe2c2f..0000000--- a/atomic-agents/examples/product_finder.py+++ /dev/null@@ -1,123 +0,0 @@-###########-# IMPORTS #-###########-import os-import logging-from typing import Union, List-from pydantic import BaseModel, Field-import instructor-import openai-from rich.console import Console--from atomic_agents.lib.components.agent_memory import AgentMemory-from atomic_agents.lib.components.system_prompt_generator import SystemPromptGenerator-from atomic_agents.agents.base_agent import BaseAgent, BaseAgentOutputSchema, BaseAgentConfig, BaseIOSchema-from atomic_agents.lib.tools.search.searxng_tool import SearxNGTool, SearxNGToolConfig, SearxNGToolInputSchema--#######################-# AGENT CONFIGURATION #-#######################-# Define system prompt information-system_prompt_generator = SystemPromptGenerator(- background=[- "This assistant is a product finder AI designed to help users find products based on their preferences by asking clarifying questions.",- ],- steps=[- "Greet the user and introduce yourself as a product finder assistant.",- "Ask the user questions to gather information about the product they are looking for.",- "Use the chat responses to gather all necessary information from the user.",- "Once sufficient information is gathered, use the SearxNGTool to search for products.",- "Summarize the search results and provide recommendations to the user.",- ],- output_instructions=[- "Always think in steps before answering using internal reasoning.",- "Provide helpful and relevant information to assist the user.",- "Be friendly and respectful in all interactions.",- "Ensure that the chat responses are used to ask clarifying questions and gather information, and the search tool is used to find products.",- ],-)--# Initialize chat memory-memory = AgentMemory()-initial_memory = [- {- "role": "assistant",- "content": "Hello! I'm your product finder assistant. What kind of product are you looking for today?",- }-]-memory.load(initial_memory)--# Initialize the console-console = Console()--# Initialize the OpenAI client-client = instructor.from_openai(openai.OpenAI())--# Initialize the SearxNGTool-searxng_tool = SearxNGTool(SearxNGToolConfig(base_url=os.getenv("SEARXNG_BASE_URL"), max_results=5))---class ChatOutputSchema(BaseIOSchema):- """This schema defines a markdown-enabled chat output."""-- markdown_output: str = Field(..., description="The answer to the question in markdown format.")---######################-# SCHEMA DEFINITIONS #-######################-class OutputSchema(BaseIOSchema):- """- Output schema for the agent.-- This schema defines the structure of the agent's output, including its internal reasoning- and the next action it plans to take.- """-- internal_reasoning: List[str] = Field(- ..., description="A list of strings representing the agent's step-by-step thought process leading to its decision."- )- action: Union[ChatOutputSchema, SearxNGToolInputSchema] = Field(- ...,- description="The next action to be taken by the agent. This can be either a chat response (ChatOutputSchema) or a search request (SearxNGToolInputSchema), depending on whether the agent needs to communicate with the user or perform a product search.",- )---# Create a config for the chat agent-agent_config = BaseAgentConfig(- client=client,- system_prompt_generator=system_prompt_generator,- model="gpt-4o-mini",- memory=memory,- output_schema=OutputSchema,-)--# Create a chat agent-agent = BaseAgent(config=agent_config)--#############-# MAIN LOOP #-#############-console.print("Product Finder Agent is ready.")-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(agent.input_schema(chat_message=user_input))-- if isinstance(response.action, SearxNGToolInputSchema):- search_results = searxng_tool.run(response.action)-- agent.memory.add_message(- "assistant",- f"INTERNAL THOUGHT: I have found the following products: {search_results.results}\n\n I will now summarize the results for the user.",- )- output = agent.run().action.markdown_output- else:- output = response.action.markdown_output-- console.print(f"Agent: {output}")diff --git a/atomic-agents/examples/shared_context.py b/atomic-agents/examples/shared_context.pydeleted file mode 100644index 4a9fe1f..0000000--- a/atomic-agents/examples/shared_context.py+++ /dev/null@@ -1,64 +0,0 @@-import json-import random-import instructor-import openai-from atomic_agents.lib.components.system_prompt_generator import SystemPromptContextProviderBase-from atomic_agents.agents.base_agent import BaseAgentConfig, BaseAgent---class SharedContextProvider(SystemPromptContextProviderBase):- def __init__(self, title):- super().__init__(title)- self.shared_context = {}-- def get_info(self) -> str:- # Here you can do something with the shared context to display it, to keep it simple we will just turn it into JSON- return json.dumps(self.shared_context)-- def update_context(self, key: str, value: str):- self.shared_context[key] = value---# Define two simple agents with shared context-agent_one = BaseAgent(- config=BaseAgentConfig(- client=instructor.from_openai(openai.OpenAI()),- model="gpt-4o-mini",- )-)--agent_two = BaseAgent(- config=BaseAgentConfig(- client=instructor.from_openai(openai.OpenAI()),- model="gpt-4o-mini",- )-)--# Add an additional output instruction to agent two, to have some differences between the two agents-agent_two.system_prompt_generator.system_prompt_info.output_instructions.append(- "Always respond in a beautiful poetic rhyming verse."-)--# Define a context provider that will be shared between the two agents-shared_context_provider = SharedContextProvider("Shared Context Provider")--agent_one.register_context_provider("shared_context", shared_context_provider)-agent_two.register_context_provider("shared_context", shared_context_provider)---# Function to update context with a random number and query both agents-def query_agents_with_random_number():- random_number = random.randint(1, 100)- shared_context_provider.update_context("random_number", str(random_number))- print(f"Updated shared context with random number: {random_number}")-- # Get responses from both agents- response_one = agent_one.run(agent_one.input_schema(chat_message="What is the random number?"))- response_two = agent_two.run(agent_two.input_schema(chat_message="What is the random number?"))-- print(f"Agent One: {response_one.chat_message}")- print(f"Agent Two: {response_two.chat_message}")---if __name__ == "__main__":- query_agents_with_random_number()diff --git a/atomic-agents/examples/simple_web_search_agent.py b/atomic-agents/examples/simple_web_search_agent.pydeleted file mode 100644index 1970fb6..0000000--- a/atomic-agents/examples/simple_web_search_agent.py+++ /dev/null@@ -1,50 +0,0 @@-# simple_web_search_agent.py-import os-import instructor-import openai-from rich.console import Console--from atomic_agents.agents.tool_interface_agent import ToolInterfaceAgent, ToolInterfaceAgentConfig-from atomic_agents.lib.tools.search.searxng_tool import SearxNGTool, SearxNGToolConfig---def initialize_searxng_tool():- """- Initialize the SearxNGTool with configuration.- """- base_url = os.getenv("SEARXNG_BASE_URL")- config = SearxNGToolConfig(base_url=base_url, max_results=10)- return SearxNGTool(config)---def initialize_agent(client, searxng_tool):- """- Initialize the ToolInterfaceAgent with the given client and SearxNGTool.- """- agent_config = ToolInterfaceAgentConfig(- client=client, model="gpt-4o-mini", tool_instance=searxng_tool, return_raw_output=False- )- return ToolInterfaceAgent(config=agent_config)---def main():- console = Console()- client = instructor.from_openai(openai.OpenAI())- searxng_tool = initialize_searxng_tool()- agent = initialize_agent(client, searxng_tool)-- console.print("ToolInterfaceAgent with SearxNGTool is ready.")-- while True:- user_input = input("You: ")- if user_input.lower() in ["exit", "quit"]:- print("Exiting chat...")- break-- # Fix this- response = agent.run(agent.input_schema(tool_input_SearxNGTool=user_input))- console.print(f"Agent: {response.chat_message}")---if __name__ == "__main__":- main()diff --git a/atomic-agents/examples/system_prompt_generator_demo.py b/atomic-agents/examples/system_prompt_generator_demo.pydeleted file mode 100644index 1ac58ac..0000000--- a/atomic-agents/examples/system_prompt_generator_demo.py+++ /dev/null@@ -1,40 +0,0 @@-from datetime import datetime-from unittest.mock import Mock-from atomic_agents.lib.components.system_prompt_generator import SystemPromptContextProviderBase, SystemPromptGenerator---class CurrentDateProvider(SystemPromptContextProviderBase):- def __init__(self, title, 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 LoremIpsumProvider(SystemPromptContextProviderBase):- def get_info(self) -> str:- return (- "Lorem ipsum dolor sit amet, consectetur adipiscing elit. "- "Sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. "- "Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat."- )---system_prompt_generator = SystemPromptGenerator(- background=[- "This assistant is a general-purpose AI designed to be helpful and friendly.",- ],- steps=["Understand the user's input and provide a relevant response.", "Respond to the user."],- output_instructions=[- "Provide helpful and relevant information to assist the user.",- "Be friendly and respectful in all interactions.",- "Always answer in rhyming verse.",- ],- context_providers={- "date": CurrentDateProvider(title="Current date", format="%Y-%m-%d %H:%M:%S"),- "lorem": LoremIpsumProvider(title="Lorem Ipsum"),- },-)--print(system_prompt_generator.generate_prompt())diff --git a/atomic-agents/examples/wiki_creator_agent/agents/article_writer_agent.py b/atomic-agents/examples/wiki_creator_agent/agents/article_writer_agent.pydeleted file mode 100644index cf64463..0000000--- a/atomic-agents/examples/wiki_creator_agent/agents/article_writer_agent.py+++ /dev/null@@ -1,155 +0,0 @@-# File: article_writer_agent.py--import instructor-import openai-from pydantic import BaseModel, Field-from typing import List-from atomic_agents.agents.base_agent import BaseAgent, BaseAgentConfig, BaseIOSchema-from atomic_agents.lib.components.system_prompt_generator import SystemPromptGenerator-from examples.wiki_creator_agent.agents.outline_agent import OutlineSection, Question---class QuestionAnswer(BaseModel):- """Represents a question and its corresponding answer."""-- question: str- answer: str---class ArticleWriterAgentInputSchema(BaseIOSchema):- """- Input schema for the ArticleWriterAgent.-- This schema defines the necessary input data for generating a comprehensive,- well-written Medium article of approximately 3000 words, including the main topic,- detailed outline, and extensive question-answer pairs.- """-- topic: str = Field(..., description="The main topic of the article")- outline: List[OutlineSection] = Field(- ..., description="The detailed outline of the article, including main sections and subsections"- )- qa_pairs: List[QuestionAnswer] = Field(- ...,- description="Extensive list of question-answer pairs for each section and subsection, providing in-depth information",- )---class ArticleWriterAgentOutputSchema(BaseIOSchema):- """- Output schema for the ArticleWriterAgent.-- This schema defines the structure of the agent's output, which is a- comprehensive, well-written markdown-formatted Medium article of- approximately 3000 words.- """-- article: str = Field(- ..., description="The comprehensive, well-written markdown-formatted Medium article of approximately 3000 words"- )---article_writer_agent = BaseAgent(- BaseAgentConfig(- client=instructor.from_openai(openai.OpenAI()),- model="gpt-4o-mini",- system_prompt_generator=SystemPromptGenerator(- background=[- "You are an expert AI article writer for Medium, specializing in long-form content.",- "Your task is to create a comprehensive, well-written, engaging, and informative article based on the given outline and question-answer pairs.",- "The article MUST be approximately 3000 words long. This is a strict requirement.",- "Adhere to the following quantitative metrics:",- "- Average words per sentence: 20-25",- "- Syntactic complexity: Moderate to high",- "- Simple to complex sentence ratio: 1:2",- "- Type-token ratio: 0.50",- "- Unique words percentage: 50-55%",- "- Rare/complex words usage: Moderate",- "- Parts of Speech: Nouns 25%, Verbs 15%, Adjectives 7%, Adverbs 6%",- "- Punctuation: 1.4 commas per sentence, 0.04 colons per sentence, 0.05 em dashes per sentence",- "Qualitative measures:",- "- Overall tone: Informative and conversational",- "- Formality level: Semi-formal with frequent conversational elements",- "- Objectivity vs. subjectivity: Mostly objective with occasional personal insights",- "- Authorial presence: Slightly more present",- "- Narrative perspective: Primarily third-person with occasional first-person insights",- "- Use of rhetorical devices: Moderate, using examples, analogies, and occasional humor",- "- Direct address to reader: Moderate",- "- Use of questions: Moderate (in the title and occasionally in the text)",- "- Anticipation of audience needs: High, through relatable examples and explanations",- "Specific aspects:",- "- Enthusiasm: Moderate use of intensifiers and positive language",- "- Professionalism: Balanced use of industry-specific terms and everyday language",- "- Sentence structures: High variety in openings, mix of lengths, moderate use of parallel structures",- "- Vocabulary level: Academic/specialized vocabulary ratio of 0.30, high consistency, appropriate use of technical terms with explanations",- "Key characteristics:",- "1. Demonstrate deep understanding of the topic",- "2. Present information in a clear, logical manner",- "3. Balance technical details with accessible explanations",- "4. Show awareness of both theoretical and practical aspects",- "5. Maintain a professional and educational tone throughout",- "6. Provide concrete examples to illustrate complex concepts",- "7. Emphasize practical implications of technical decisions",- "8. Show understanding of challenges in modern software development",- "9. Tailor content for developers with varying levels of experience",- "10. Explain complex issues in a structured and comprehensible way",- "11. Showcase understanding of software architecture and its impact",- "12. Maintain objectivity while presenting potentially controversial issues",- "13. Anticipate potential questions or areas of confusion",- "14. Emphasize the evolving nature of development tools and practices",- "15. Provide critical analysis of common development practices and their limitations",- ],- steps=[- "Analyze the provided outline and question-answer pairs thoroughly.",- "Plan a detailed structure to reach the 3000-word target while maintaining coherence and depth.",- "Write a comprehensive introduction (about 300 words) that hooks the reader and outlines key points.",- "Develop each main section into 500-700 words, ensuring thorough coverage of all subsections.",- "For each section and subsection:",- " - Provide in-depth explanations and analysis",- " - Include relevant examples, case studies, or hypothetical scenarios",- " - Incorporate statistics, expert opinions, or research findings",- " - Address potential counterarguments or alternative viewpoints",- "Use paragraphs of 4-6 sentences, allowing for detailed exploration of ideas.",- "Create smooth transitions between sections for a cohesive narrative.",- "Conclude with a comprehensive summary (about 300 words) that recaps main points and offers insights.",- "Review the article to ensure it meets the 3000-word requirement and adheres to all specified metrics and characteristics.",- "Refine the content to balance accessibility for beginners with depth for advanced readers.",- "Double-check adherence to quantitative metrics, qualitative measures, and key characteristics.",- ],- output_instructions=[- "Produce a well-structured, engaging Medium article in markdown format, with a STRICT target length of 3000 words (±100 words).",- "Use a clear hierarchy of headers: # for main sections, ## for subsections, ### for sub-subsections.",- "Seamlessly incorporate information from question-answer pairs, expanding with context and insights.",- "Include a compelling title and subtitle reflecting the comprehensive nature of the article.",- "Aim for 3-5 sentences per paragraph, allowing for a mix of detailed explanations and punchier points.",- "Use bold for key concepts and italic for emphasis or to add a conversational tone.",- "Ensure natural flow between sections, maintaining a coherent narrative.",- "Include relevant code snippets using proper markdown syntax, followed by clear, relatable explanations.",- "Use lists when appropriate, balancing them with explanatory paragraphs.",- "Incorporate relevant subheadings within main sections to improve organization and scannability.",- "Use block quotes for important statements or expert opinions, providing context and analysis with a personal touch.",- "Conclude with a strong summary recapping main points and offering compelling insights, possibly with a call to action or thought-provoking question.",- "Adhere to the specified quantitative metrics for sentence structure, vocabulary, and punctuation, but allow for some flexibility to maintain a natural flow.",- "Maintain the required tone and style as outlined in the writer profile, leaning towards a more conversational approach.",- "Demonstrate deep understanding while balancing technical details with accessible explanations.",- "Use industry-specific jargon and technical terms appropriately, but always provide clear explanations or analogies for complex concepts.",- "Provide critical analysis and emphasize practical implications of technical decisions, relating them to real-world scenarios when possible.",- "Anticipate and address potential questions or areas of confusion proactively, using a friendly, guiding tone.",- "Maintain high objectivity with analytical insights throughout the article.",- "Maintain objectivity with analytical insights throughout the article, but don't shy away from adding occasional personal perspectives or experiences.",- "Use rhetorical devices moderately, including examples, analogies, and occasional humor to keep the reader engaged.",- "Incorporate direct address to the reader and use questions occasionally to create a more interactive feel.",- "Ensure high anticipation of audience needs through relatable examples and clear explanations.",- "Allow for moderate enthusiasm by using some intensifiers and positive language to convey excitement about the topic.",- "Achieve the specified academic/specialized vocabulary ratio, but prioritize clarity and accessibility.",- "Vary sentence openings and lengths to create a natural, flowing rhythm.",- "IMPORTANT: The final article MUST be approximately 3000 words. If significantly shorter, expand key points or add more examples and analysis to reach the target length.",- "IMPORTANT: The final article MUST flow nicely from section to section and have a single overarching narrative, with a conversational thread tying it all together.",- "IMPORTANT: The final article MUST have a good balance between prose and lists, with a minimum of 80% being prose, and a maximum of 20% being lists",- "IMPORTANT: If the article is about code, include plenty of didactic code snippets with clear, relatable explanations",- ],- ),- input_schema=ArticleWriterAgentInputSchema,- output_schema=ArticleWriterAgentOutputSchema,- )-)diff --git a/atomic-agents/examples/wiki_creator_agent/agents/outline_agent.py b/atomic-agents/examples/wiki_creator_agent/agents/outline_agent.pydeleted file mode 100644index 5d25a1d..0000000--- a/atomic-agents/examples/wiki_creator_agent/agents/outline_agent.py+++ /dev/null@@ -1,86 +0,0 @@-# File: outline_agent.py--import instructor-import openai-from pydantic import BaseModel, Field-from typing import List-from atomic_agents.agents.base_agent import BaseIOSchema, BaseAgent, BaseAgentConfig-from atomic_agents.lib.components.system_prompt_generator import SystemPromptGenerator---class Question(BaseModel):- question: str = Field(..., description="The question to answer in this section or subsection")- potential_sources: List[str] = Field(- default_factory=list, description="URLs of potential sources or references for this question. Required. Min. 1."- )---class OutlineSubSection(BaseModel):- title: str = Field(..., description="The title of the outline subsection")- questions_to_answer: List[Question] = Field(- default_factory=list,- description="A list of 2-4 hypothetical questions that the contents of this subsection should answer.",- )---class OutlineSection(BaseModel):- title: str = Field(..., description="The title of the outline section")- questions_to_answer: List[Question] = Field(- default_factory=list, description="2-3 overarching questions to answer in this section"- )- subsections: List[OutlineSubSection] = Field(- default_factory=list, description="Subsections of this outline section. Each section must have 3-5 subsections."- )---class OutlineAgentInputSchema(BaseIOSchema):- """This schema defines the input schema for the OutlineAgent."""-- topic: str = Field(..., description="The main topic of the article")---class OutlineAgentOutputSchema(BaseIOSchema):- """This schema defines the output schema for the OutlineAgent."""-- internal_reasoning: List[str] = Field(- ...,- description="Internal reasoning about the context and what information it contains that could be useful in generating or modifying an outline.",- )- title: str = Field(..., description="The title of the article")- outline: List[OutlineSection] = Field(- ..., description="The generated or modified outline. The outline must have 5-7 main sections."- )---# Create the outline agent-outline_agent = BaseAgent(- BaseAgentConfig(- client=instructor.from_openai(openai.OpenAI()),- model="gpt-4o-mini",- system_prompt_generator=SystemPromptGenerator(- background=[- "You are an expert AI outline creator and editor, specializing in creating comprehensive and well-structured outlines.",- "Your task is to generate or modify article outlines based on the given topic and context, ensuring a logical flow and thorough coverage of the subject.",- ],- steps=[- "Analyze the given topic and any additional context provided in depth.",- "Create a comprehensive structure for the article with 5-7 main sections.",- "For each main section, develop 3-5 subsections that explore different aspects of the main section's topic.",- "Ensure the outline is well-organized, logical, and covers all important aspects of the topic in a balanced manner.",- "For each section, provide 2-3 overarching questions to answer.",- "For each subsection, provide 2-4 specific questions to answer, including potential sources for each question.",- ],- output_instructions=[- "Create a clear, concise, and comprehensive outline with 5-7 main sections.",- "Ensure each main section has 3-5 well-defined subsections.",- "Provide 1-2 overarching questions for each main section.",- "Include 2-4 specific questions to answer for each subsection, along with potential sources.",- "Use descriptive and informative titles for each section and subsection.",- "Ensure each section and subsection is relevant to the main topic and contributes to a cohesive narrative.",- "Aim for a balanced structure that covers the topic comprehensively, with appropriate depth in each section.",- ],- ),- input_schema=OutlineAgentInputSchema,- output_schema=OutlineAgentOutputSchema,- )-)diff --git a/atomic-agents/examples/wiki_creator_agent/agents/query_agent.py b/atomic-agents/examples/wiki_creator_agent/agents/query_agent.pydeleted file mode 100644index ef5d3f4..0000000--- a/atomic-agents/examples/wiki_creator_agent/agents/query_agent.py+++ /dev/null@@ -1,48 +0,0 @@-# File: query_agent.py--import instructor-import openai-from pydantic import BaseModel, Field-from typing import List-from atomic_agents.agents.base_agent import BaseIOSchema, BaseAgent, BaseAgentConfig-from atomic_agents.lib.components.system_prompt_generator import SystemPromptGenerator---class QueryAgentInputSchema(BaseIOSchema):- """This schema defines the input schema for the QueryAgent."""-- instruction: str = Field(..., description="The user's input or question for which queries need to be generated.")- num_queries: int = Field(default=5, description="The number of queries to generate.")---class QueryAgentOutputSchema(BaseIOSchema):- """This schema defines the output schema for the QueryAgent."""-- queries: List[str] = Field(..., description="A list of generated queries based on the user's input.")---# Create the query agent-query_agent = BaseAgent(- BaseAgentConfig(- client=instructor.from_openai(openai.OpenAI()),- model="gpt-4o-mini",- system_prompt_generator=SystemPromptGenerator(- background=[- "You are an expert google query generator.",- "Your task is to generate relevant and diverse google search queries based on the user's input or question.",- ],- steps=[- "Analyze the user's input or question.",- "Generate a specified number of relevant google search queries.",- "Ensure the queries cover different aspects of the user's input.",- ],- output_instructions=[- "Generate clear and concise google queries.",- "Ensure each google query is directly relevant to the user's input.",- "Avoid repetitive queries and aim for diversity in the generated set.",- ],- ),- input_schema=QueryAgentInputSchema,- output_schema=QueryAgentOutputSchema,- )-)diff --git a/atomic-agents/examples/wiki_creator_agent/agents/question_answering_agent.py b/atomic-agents/examples/wiki_creator_agent/agents/question_answering_agent.pydeleted file mode 100644index 1c9a485..0000000--- a/atomic-agents/examples/wiki_creator_agent/agents/question_answering_agent.py+++ /dev/null@@ -1,42 +0,0 @@-import instructor-import openai-from pydantic import BaseModel, Field-from atomic_agents.agents.base_agent import BaseAgent, BaseAgentConfig-from atomic_agents.lib.components.system_prompt_generator import SystemPromptGenerator---class QuestionAnsweringAgentInputSchema(BaseModel):- question: str = Field(..., description="The question to be answered")---class QuestionAnsweringAgentOutputSchema(BaseModel):- answer: str = Field(..., description="The answer to the provided question")---# Create the question answering agent-question_answering_agent = BaseAgent(- BaseAgentConfig(- client=instructor.from_openai(openai.OpenAI()),- model="gpt-4o-mini",- system_prompt_generator=SystemPromptGenerator(- background=[- "You are an expert AI question answering system.",- "Your task is to provide accurate and concise answers to questions based on the given context.",- ],- steps=[- "Analyze the provided question and context.",- "Search the context for relevant information.",- "Generate a clear and concise answer based on the context.",- "Identify the sources used for the answer.",- ],- output_instructions=[- "Provide an accurate answer to the question.",- "Ensure the answer is directly relevant to the question.",- "Include sources for the answer when available.",- "Keep the answer concise but informative.",- ],- ),- input_schema=QuestionAnsweringAgentInputSchema,- output_schema=QuestionAnsweringAgentOutputSchema,- )-)diff --git a/atomic-agents/examples/wiki_creator_agent/main.py b/atomic-agents/examples/wiki_creator_agent/main.pydeleted file mode 100644index bd0ad5f..0000000--- a/atomic-agents/examples/wiki_creator_agent/main.py+++ /dev/null@@ -1,229 +0,0 @@-import os-import asyncio-from typing import List-import rich-from atomic_agents.lib.tools.search.searxng_tool import SearxNGTool, SearxNGToolConfig-from atomic_agents.lib.components.system_prompt_generator import SystemPromptContextProviderBase-from examples.wiki_creator_agent.agents.query_agent import query_agent, QueryAgentInputSchema-from examples.wiki_creator_agent.agents.outline_agent import outline_agent, OutlineAgentInputSchema-from examples.wiki_creator_agent.agents.question_answering_agent import (- question_answering_agent,- QuestionAnsweringAgentInputSchema,-)-from examples.wiki_creator_agent.utils.scraper import ContentScraper-from examples.wiki_creator_agent.utils.vector_db import InMemFaiss-from examples.wiki_creator_agent.agents.article_writer_agent import (- article_writer_agent,- ArticleWriterAgentInputSchema,- QuestionAnswer,-)--rich_console = rich.console.Console()---###################-# CONTEXT PROVIDERS #-###################-class SearchResultsProvider(SystemPromptContextProviderBase):- def __init__(self, title="Search Results"):- super().__init__(title)- self.search_results = None-- def get_info(self) -> str:- if self.search_results is None:- return "No search results available."-- results_str = "Search Results:\n"- for i, result in enumerate(self.search_results.results, 1):- results_str += f"{i}. Title: {result.title}\n URL: {result.url}\n Content: {result.content[:100]}...\n\n"- return results_str---class VectorDBResultsProvider(SystemPromptContextProviderBase):- def __init__(self, title="Vector Database Results"):- super().__init__(title)- self.vector_db_results = None-- def get_info(self) -> str:- if self.vector_db_results is None:- return "No vector database results available."-- results_str = "Vector Database Results:\n\n"- for i, chunk in enumerate(self.vector_db_results, 1):- results_str += f"## RESULT {i}\n"- results_str += f"{chunk}\n"- results_str += "=" * 50 + "\n\n"-- return results_str---class OutlineProvider(SystemPromptContextProviderBase):- def __init__(self, title="Article Outline"):- super().__init__(title)- self.outline = None-- def get_info(self) -> str:- if self.outline is None:- return "No outline available."-- outline_str = "Article Outline:\n"- for section in self.outline:- outline_str += f"Section: {section.title}\n"- for subsection in section.subsections:- outline_str += f" Subsection: {subsection.title}\n"- return outline_str---#############-# PIPELINES #-#############-class QueryAndSearchPipeline:- @staticmethod- def generate_queries_and_search(user_input: str, num_queries: int = 3):- # Generate queries- query_instruction = f"Generate research queries for an article about {user_input}"- query_input = QueryAgentInputSchema(instruction=query_instruction, num_queries=num_queries)- query_output = query_agent.run(query_input)- queries = query_output.queries-- # Perform search- search_tool_instance = SearxNGTool(config=SearxNGToolConfig(base_url=os.getenv("SEARXNG_BASE_URL"), max_results=30))- search_input = SearxNGTool.input_schema(queries=queries)- search_output = search_tool_instance.run(search_input)-- return queries, search_output---class OutlineGenerationPipeline:- @staticmethod- def generate_outline(user_input: str, search_results_provider):- outline_agent.register_context_provider("search_results", search_results_provider)- outline_input = OutlineAgentInputSchema(topic=user_input)- outline_output = outline_agent.run(outline_input)- return outline_output.outline-- @staticmethod- def extract_urls_from_outline(outline):- urls = set()- for section in outline:- urls.update(url for point in section.questions_to_answer for url in point.potential_sources)- for subsection in section.subsections:- urls.update(url for point in subsection.questions_to_answer for url in point.potential_sources)- return sorted(list(urls))---class ContentScrapingPipeline:- @staticmethod- async def scrape_and_ingest_urls(urls: List[str], batch_size: int = 5):- faiss_db = InMemFaiss(openai_api_key=os.getenv("OPENAI_API_KEY"))- batches = [urls[i : i + batch_size] for i in range(0, len(urls), batch_size)]-- for batch_num, batch in enumerate(batches, 1):- rich_console.print(f"[bold magenta]Scraping and ingesting batch {batch_num} of {len(batches)}[/bold magenta]")- scraped_content = await ContentScraper.scrape_urls(batch)- await faiss_db.ingest_documents(scraped_content)-- for url in scraped_content.keys():- rich_console.print(f"[green]Ingested content from {url}[/green]")-- return faiss_db---class QuestionAnsweringPipeline:- @staticmethod- async def answer_questions(outline, faiss_db, faiss_db_context_provider, outline_provider):- question_answering_agent.register_context_provider("vector_db_results", faiss_db_context_provider)- question_answering_agent.register_context_provider("outline", outline_provider)-- qa_pairs = []-- for section in outline:- for subsection in section.subsections:- questions_to_answer = "\n".join([item.question for item in subsection.questions_to_answer])- context = faiss_db.retrieve_chunks(questions_to_answer)- faiss_db_context_provider.vector_db_results = context-- for question_item in subsection.questions_to_answer:- question_input = QuestionAnsweringAgentInputSchema(question=question_item.question)- answer_output = question_answering_agent.run(question_input)-- rich_console.print(f"[bold cyan]Question:[/bold cyan] {question_item.question}")- rich_console.print(f"[bold green]Answer:[/bold green] {answer_output.answer}\n")-- qa_pairs.append(QuestionAnswer(question=question_item.question, answer=answer_output.answer))-- return qa_pairs---class ArticleWritingPipeline:- @staticmethod- def write_article(topic: str, outline, qa_pairs):- input_data = ArticleWriterAgentInputSchema(topic=topic, outline=outline, qa_pairs=qa_pairs)- output = article_writer_agent.run(input_data)- return output.article---###################-# MAIN APPLICATION #-###################-class WikiCreatorApplication:- def __init__(self):- self.rich_console = rich.console.Console()- self.search_results_provider = SearchResultsProvider()- self.vector_db_results_provider = VectorDBResultsProvider()- self.outline_provider = OutlineProvider()- self.qa_pairs = []-- async def run(self):- self.rich_console.print("[bold blue]Script execution started[/bold blue]")- user_input = input("I want to write an article about ")-- queries, search_output = QueryAndSearchPipeline.generate_queries_and_search(user_input, num_queries=5)- self.rich_console.print("[bold yellow]Generated Queries:[/bold yellow]")- for i, query in enumerate(queries, 1):- self.rich_console.print(f"[yellow]{i}. {query}[/yellow]")- self.rich_console.print()-- self.search_results_provider.search_results = search_output-- outline = OutlineGenerationPipeline.generate_outline(user_input, self.search_results_provider)- self.rich_console.print("[bold green]Generated Outline:[/bold green]")- self.rich_console.print(outline)-- urls = OutlineGenerationPipeline.extract_urls_from_outline(outline)- self.rich_console.print("\n[bold cyan]Extracted Potential Source URLs:[/bold cyan]")- for i, url in enumerate(urls, 1):- self.rich_console.print(f"[cyan]{i}. {url}[/cyan]")-- batch_size = 10 # You can change this value or make it configurable- faiss_db = await ContentScrapingPipeline.scrape_and_ingest_urls(urls, batch_size)-- self.outline_provider.outline = outline- self.qa_pairs = await QuestionAnsweringPipeline.answer_questions(- outline, faiss_db, self.vector_db_results_provider, self.outline_provider- )-- # New code for article writing- self.rich_console.print("[bold magenta]Writing the article...[/bold magenta]")- article = ArticleWritingPipeline.write_article(user_input, outline, self.qa_pairs)-- self.rich_console.print("[bold green]Article generated successfully![/bold green]")- self.rich_console.print("\n[bold cyan]Generated Article:[/bold cyan]")- self.rich_console.print(article)-- # Optionally, save the article to a file- with open("generated_article.md", "w", encoding="utf-8") as f:- f.write(article)- self.rich_console.print("\n[bold green]Article saved to 'generated_article.md'[/bold green]")---####################-# SCRIPT EXECUTION #-####################-async def main():- app = WikiCreatorApplication()- await app.run()---if __name__ == "__main__":- asyncio.run(main())diff --git a/atomic-agents/examples/wiki_creator_agent/utils/scraper.py b/atomic-agents/examples/wiki_creator_agent/utils/scraper.pydeleted file mode 100644index aa62404..0000000--- a/atomic-agents/examples/wiki_creator_agent/utils/scraper.py+++ /dev/null@@ -1,45 +0,0 @@-import aiohttp-import asyncio-from bs4 import BeautifulSoup-from readability import Document-import html2text-from typing import List, Dict-import trafilatura---class ContentScraper:- @staticmethod- async def scrape_urls(urls: List[str]) -> Dict[str, str]:- async def fetch_url(session: aiohttp.ClientSession, url: str) -> tuple:- try:- async with session.get(url, timeout=30) as response: # Added timeout- html_content = await response.text()-- # Try trafilatura first- extracted_content = trafilatura.extract(html_content)-- if not extracted_content:- # If trafilatura fails, fall back to readability- doc = Document(html_content)- extracted_content = doc.summary()-- # Clean up the extracted content- soup = BeautifulSoup(extracted_content, "html.parser")- for script in soup(["script", "style"]):- script.decompose()- cleaned_content = soup.get_text()-- # Convert to markdown- h = html2text.HTML2Text()- h.ignore_links = False- markdown_content = h.handle(cleaned_content)-- return url, markdown_content.strip()- except Exception as e:- return url, f"Error scraping {url}: {str(e)}"-- async with aiohttp.ClientSession() as session:- tasks = [fetch_url(session, url) for url in urls]- results = await asyncio.gather(*tasks)-- return dict(results)diff --git a/atomic-agents/examples/wiki_creator_agent/utils/vector_db.py b/atomic-agents/examples/wiki_creator_agent/utils/vector_db.pydeleted file mode 100644index 3214261..0000000--- a/atomic-agents/examples/wiki_creator_agent/utils/vector_db.py+++ /dev/null@@ -1,57 +0,0 @@-import openai-import faiss-import numpy as np-from typing import List, Dict-from tqdm import tqdm---class InMemFaiss:- def __init__(self, openai_api_key):- openai.api_key = openai_api_key- self.index = faiss.IndexFlatL2(1536)- self.texts = []- self.metadata = []-- def split_text(self, text, chunk_size=1750, overlap=250):- chunks = []- for i in range(0, len(text), chunk_size - overlap):- chunk = text[i : i + chunk_size].strip()- chunks.append(chunk)- return chunks-- def generate_embeddings(self, texts):- embeddings = []- batch_size = 1000 # Adjust this based on your needs and API limits-- for i in tqdm(range(0, len(texts), batch_size)):- batch = texts[i : i + batch_size]- try:- response = openai.embeddings.create(input=batch, model="text-embedding-3-small")- batch_embeddings = [item.embedding for item in response.data]- embeddings.extend(batch_embeddings)- except Exception as e:- print(f"Error generating embeddings for batch {i//batch_size}: {e}")- # Handle the error appropriately, e.g., retry or skip-- return np.array(embeddings).astype("float32")-- async def ingest_documents(self, documents: Dict[str, str]):- all_chunks = []- all_metadata = []-- for url, content in documents.items():- if len(content) == 0:- continue- chunks = self.split_text(content)- all_chunks.extend(chunks)- all_metadata.extend([{"url": url}] * len(chunks))-- embeddings = self.generate_embeddings(all_chunks)- self.index.add(embeddings)- self.texts.extend(all_chunks)- self.metadata.extend(all_metadata)-- def retrieve_chunks(self, query, top_k=5):- query_embedding = self.generate_embeddings([query])- distances, indices = self.index.search(query_embedding, top_k)- return [self.texts[idx] for idx in indices[0]]diff --git a/atomic-agents/examples/yelp_restaurant_finder.py b/atomic-agents/examples/yelp_restaurant_finder.pydeleted file mode 100644index 4321990..0000000--- a/atomic-agents/examples/yelp_restaurant_finder.py+++ /dev/null@@ -1,124 +0,0 @@-###########-# IMPORTS #-###########-import os-import logging-from typing import Union, List-from pydantic import BaseModel, Field-import instructor-import openai-from rich.console import Console--from atomic_agents.lib.components.agent_memory import AgentMemory-from atomic_agents.lib.components.system_prompt_generator import SystemPromptGenerator-from atomic_agents.agents.base_agent import BaseAgent, BaseAgentOutputSchema, BaseAgentConfig, BaseIOSchema-from atomic_agents.lib.tools.yelp_restaurant_finder_tool import YelpSearchTool, YelpSearchToolConfig, YelpSearchToolInputSchema--#######################-# AGENT CONFIGURATION #-#######################-# Define system prompt information-system_prompt_generator = SystemPromptGenerator(- background=[- "This assistant is a restaurant finder AI designed to help users find the best restaurants based on their preferences by asking clarifying questions.",- ],- steps=[- "Greet the user and introduce yourself as a restaurant finder assistant.",- "Inspect the required Yelp schema and identify the necessary filters.",- "Ask the user questions to gather information for each filter until all required information is clear.",- "Use the chat responses to gather all necessary information from the user.",- "Once all required information is gathered, use the YelpSearchTool schema to search Yelp for restaurants.",- "Summarize the search results and provide recommendations to the user.",- ],- output_instructions=[- "Always think in steps before answering using internal reasoning.",- "Provide helpful and relevant information to assist the user.",- "Be friendly and respectful in all interactions.",- "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.",- ],-)--# Initialize chat memory-memory = AgentMemory()-initial_memory = [- {- "role": "assistant",- "content": "Hello! I'm your restaurant finder assistant. How can I help you find a great place to eat today?",- }-]-memory.load(initial_memory)--# Initialize the console-console = Console()--# Initialize the OpenAI client-client = instructor.from_openai(openai.OpenAI())--# Initialize the YelpSearchTool-yelp_tool = YelpSearchTool(YelpSearchToolConfig(api_key=os.getenv("YELP_API_KEY"), max_results=10))---######################-# SCHEMA DEFINITIONS #-######################-class ChatOutputSchema(BaseIOSchema):- """This schema defines a markdown-enabled chat output."""-- markdown_output: str = Field(..., description="The answer to the question in markdown format.")---class OutputSchema(BaseIOSchema):- """- Output schema for the agent.-- This schema defines the structure of the agent's output, including its internal reasoning- and the next action it plans to take.- """-- internal_reasoning: List[str] = Field(- ..., description="A list of strings representing the agent's step-by-step thought process leading to its decision."- )- action: Union[ChatOutputSchema, YelpSearchToolInputSchema] = Field(- ...,- description="The next action to be taken by the agent. This can be either a chat response (ChatOutputSchema) or a Yelp search request (YelpSearchToolInputSchema), depending on whether the agent needs to communicate with the user or perform a restaurant search.",- )---# Create a config for the chat agent-agent_config = BaseAgentConfig(- client=client,- system_prompt_generator=system_prompt_generator,- model="gpt-4o-mini",- memory=memory,- output_schema=OutputSchema,-)--# Create a chat agent-agent = BaseAgent(config=agent_config)--#############-# MAIN LOOP #-#############-console.print("Restaurant Finder Agent is ready.")-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(agent.input_schema(chat_message=user_input))-- if isinstance(response.action, YelpSearchToolInputSchema):- search_results = yelp_tool.run(response.action)-- agent.memory.add_message(- "assistant",- f"INTERNAL THOUGHT: I have found the following restaurants: {search_results.results}\n\n I will now summarize the results for the user.",- )- output = agent.run().action.markdown_output- else:- output = response.action.markdown_output-- console.print(f"Agent: {output}")diff --git a/atomic-agents/examples/youtube_knowledge_extraction/agents/youtube_knowledge_extraction_agent.py b/atomic-agents/examples/youtube_knowledge_extraction/agents/youtube_knowledge_extraction_agent.pydeleted file mode 100644index 1570734..0000000--- a/atomic-agents/examples/youtube_knowledge_extraction/agents/youtube_knowledge_extraction_agent.py+++ /dev/null@@ -1,93 +0,0 @@-import instructor-import openai-from pydantic import BaseModel, Field-from typing import List, Optional--from atomic_agents.agents.base_agent import BaseAgent, BaseAgentConfig, BaseIOSchema-from atomic_agents.lib.components.system_prompt_generator import SystemPromptContextProviderBase, SystemPromptGenerator---class YtTranscriptProvider(SystemPromptContextProviderBase):- def __init__(self, title):- super().__init__(title)- self.transcript = None- self.duration = None- self.metadata = None-- def get_info(self) -> str:- return f'VIDEO TRANSCRIPT: "{self.transcript}"\n\nDURATION: {self.duration}\n\nMETADATA: {self.metadata}'---class YouTubeKnowledgeExtractionInputSchema(BaseIOSchema):- """This schema defines the input schema for the YouTubeKnowledgeExtractionAgent."""-- video_url: str = Field(..., description="The URL of the YouTube video to analyze")---class YouTubeKnowledgeExtractionOutputSchema(BaseIOSchema):- """This schema defines an elaborate set of insights about the contentof the video."""-- summary: str = Field(- ..., description="A short summary of the content, including who is presenting and the content being discussed."- )- insights: List[str] = Field(- ..., min_items=5, max_items=5, description="exactly 5 of the best insights and ideas from the input."- )- quotes: List[str] = Field(- ...,- min_items=5,- max_items=5,- description="exactly 5 of the most surprising, insightful, and/or interesting quotes from the input.",- )- habits: Optional[List[str]] = Field(- None,- min_items=5,- max_items=5,- description="exactly 5 of the most practical and useful personal habits mentioned by the speakers.",- )- facts: List[str] = Field(- ...,- min_items=5,- max_items=5,- description="exactly 5 of the most surprising, insightful, and/or interesting valid facts about the greater world mentioned in the content.",- )- recommendations: List[str] = Field(- ...,- min_items=5,- max_items=5,- description="exactly 5 of the most surprising, insightful, and/or interesting recommendations from the content.",- )- references: List[str] = Field(- ...,- description="All mentions of writing, art, tools, projects, and other sources of inspiration mentioned by the speakers.",- )- one_sentence_takeaway: str = Field(- ..., description="The most potent takeaways and recommendations condensed into a single 20-word sentence."- )---transcript_provider = YtTranscriptProvider(title="YouTube Transcript")--youtube_knowledge_extraction_agent = BaseAgent(- config=BaseAgentConfig(- client=instructor.from_openai(openai.OpenAI()),- model="gpt-4o-mini",- system_prompt_generator=SystemPromptGenerator(- background=[- "This Assistant is an expert at extracting knowledge and other insightful and interesting information from YouTube transcripts."- ],- steps=[- "Analyse the YouTube transcript thoroughly to extract the most valuable insights, facts, and recommendations.",- "Adhere strictly to the provided schema when extracting information from the input content.",- "Ensure that the output matches the field descriptions, types and constraints exactly.",- ],- output_instructions=[- "Only output Markdown-compatible strings.",- "Ensure you follow ALL these instructions when creating your output.",- ],- context_providers={"yt_transcript": transcript_provider},- ),- input_schema=YouTubeKnowledgeExtractionInputSchema,- output_schema=YouTubeKnowledgeExtractionOutputSchema,- )-)diff --git a/atomic-agents/examples/youtube_knowledge_extraction/pipeline.py b/atomic-agents/examples/youtube_knowledge_extraction/pipeline.pydeleted file mode 100644index a49e0b5..0000000--- a/atomic-agents/examples/youtube_knowledge_extraction/pipeline.py+++ /dev/null@@ -1,80 +0,0 @@-from typing import Dict, List, Type-from pydantic import Field-from rich.console import Console-from rich.markdown import Markdown--from atomic_agents.agents.base_agent import BaseIOSchema-from atomic_agents.lib.tools.yt_transcript_scraper_tool import (- YouTubeTranscriptTool,- YouTubeTranscriptToolConfig,- YouTubeTranscriptToolInputSchema,-)--from agents.youtube_knowledge_extraction_agent import (- youtube_knowledge_extraction_agent,- YouTubeKnowledgeExtractionInputSchema,- YouTubeKnowledgeExtractionOutputSchema,- transcript_provider,-)--console = Console()--# Type aliases-SchemaType = Type[BaseIOSchema]-OrchestrationGraphType = Dict[BaseIOSchema, List[BaseIOSchema]]--# Tool initialization-yt_scraper_tool = YouTubeTranscriptTool(config=YouTubeTranscriptToolConfig())---# Schema models-class InputSchema(BaseIOSchema):- """This schema defines the input for the pipeline."""-- user_input: str = Field(..., description="The YouTube video URL provided by the user.")---class ChatReplySchema(BaseIOSchema):- """This schema defines a standard chat reply."""-- chat_message: str = Field(..., description="The chat message to be sent back to the user.")---# Orchestration flow config-OrchestrationGraph: OrchestrationGraphType = {- InputSchema: [YouTubeKnowledgeExtractionInputSchema],- YouTubeKnowledgeExtractionInputSchema: [YouTubeKnowledgeExtractionOutputSchema],- YouTubeKnowledgeExtractionOutputSchema: [ChatReplySchema],-}---def format_markdown_section(title, items):- if isinstance(items, list):- return f"## {title}\n" + "\n".join([f"- {item}" for item in items]) + "\n"- return f"## {title}\n{items}\n"---def run_pipeline(video_url: str):- # Step 1: Scrape YouTube transcript- scraped_transcript = yt_scraper_tool.run(YouTubeTranscriptToolInputSchema(video_url=video_url))- transcript_provider.transcript = scraped_transcript.transcript- transcript_provider.duration = scraped_transcript.duration- transcript_provider.metadata = scraped_transcript.metadata-- # Step 2: Run YouTube knowledge extraction agent- response = youtube_knowledge_extraction_agent.run(YouTubeKnowledgeExtractionInputSchema(video_url=video_url))-- # Step 3: Format and display the response- response_dict = response.model_dump()- markdown_string = ""- for key, value in response_dict.items():- title = key.replace("_", " ").title()- markdown_string += format_markdown_section(title, value)-- markdown_response = Markdown(markdown_string)- console.print(markdown_response)---if __name__ == "__main__":- video_url = input("Enter the YouTube video URL: ")- run_pipeline(video_url)