Building AI agents, atomically
Use markdown for docs
KennyVaneetvelde96432be8e260
diff --git a/docs/api/agents.md b/docs/api/agents.mdnew file mode 100644index 0000000..4c5a6a0--- /dev/null+++ b/docs/api/agents.md@@ -0,0 +1,348 @@+# Agents++## Schema Hierarchy++The Atomic Agents framework uses Pydantic for schema validation and serialization. All input and output schemas follow this inheritance pattern:++```+pydantic.BaseModel+ └── BaseIOSchema+ ├── BaseAgentInputSchema+ └── BaseAgentOutputSchema+```++### BaseIOSchema++The base schema class that all agent input/output schemas inherit from.++```{eval-rst}+.. py:class:: BaseIOSchema++ Base schema class for all agent input/output schemas. Inherits from :class:`pydantic.BaseModel`.++ All agent schemas must inherit from this class to ensure proper serialization and validation.++ **Inheritance:**+ - :class:`pydantic.BaseModel`+```++### BaseAgentInputSchema++The default input schema for agents.++```{eval-rst}+.. py:class:: BaseAgentInputSchema++ Default input schema for agent interactions.++ **Inheritance:**+ - :class:`BaseIOSchema` → :class:`pydantic.BaseModel`++ .. py:attribute:: chat_message+ :type: str++ The message to send to the agent.++ Example:+ >>> input_schema = BaseAgentInputSchema(chat_message="Hello, agent!")+ >>> agent.run(input_schema)+```++### BaseAgentOutputSchema++The default output schema for agents.++```{eval-rst}+.. py:class:: BaseAgentOutputSchema++ Default output schema for agent responses.++ **Inheritance:**+ - :class:`BaseIOSchema` → :class:`pydantic.BaseModel`++ .. py:attribute:: chat_message+ :type: str++ The response message from the agent.++ Example:+ >>> response = agent.run(input_schema)+ >>> print(response.chat_message)+```++### Creating Custom Schemas++You can create custom input/output schemas by inheriting from `BaseIOSchema`:++```python+from pydantic import Field+from typing import List+from atomic_agents.lib.base.base_io_schema import BaseIOSchema++class CustomInputSchema(BaseIOSchema):+ chat_message: str = Field(..., description="User's message")+ context: str = Field(None, description="Optional context for the agent")++class CustomOutputSchema(BaseIOSchema):+ chat_message: str = Field(..., description="Agent's response")+ follow_up_questions: List[str] = Field(+ default_factory=list,+ description="Suggested follow-up questions"+ )+ confidence: float = Field(+ ...,+ description="Confidence score for the response",+ ge=0.0,+ le=1.0+ )+```++## Base Agent Configuration++### BaseAgentConfig++The configuration class for BaseAgent that defines all settings and components.++```{eval-rst}+.. py:class:: BaseAgentConfig++ Configuration class for BaseAgent.++ **Inheritance:**+ - :class:`pydantic.BaseModel`++ .. py:attribute:: client+ :type: Any++ The LLM client to use (e.g., OpenAI, Anthropic, etc.). Must be wrapped with instructor.++ .. py:attribute:: model+ :type: str++ The model identifier to use with the client (e.g., "gpt-4", "claude-3-opus-20240229").++ .. py:attribute:: memory+ :type: Optional[AgentMemory]++ Memory component for storing conversation history. Defaults to None.++ .. py:attribute:: system_prompt_generator+ :type: Optional[SystemPromptGenerator]++ Generator for creating system prompts. Defaults to None.++ .. py:attribute:: input_schema+ :type: Optional[Type[BaseIOSchema]]++ Schema for validating agent inputs. Defaults to BaseAgentInputSchema.+ Must be a subclass of BaseIOSchema.++ .. py:attribute:: output_schema+ :type: Optional[Type[BaseIOSchema]]++ Schema for validating agent outputs. Defaults to BaseAgentOutputSchema.+ Must be a subclass of BaseIOSchema.++ .. py:attribute:: tools+ :type: Optional[List[str]]++ List of tool names to make available to the agent. Defaults to None.++ .. py:attribute:: tool_configs+ :type: Optional[Dict[str, Dict[str, Any]]]++ Configuration parameters for tools. Defaults to None.++ .. py:attribute:: components+ :type: Optional[Dict[str, Any]]++ Additional components to attach to the agent. Defaults to None.++ Example:+ >>> config = BaseAgentConfig(+ ... client=instructor.from_openai(OpenAI()),+ ... model="gpt-4",+ ... input_schema=CustomInputSchema,+ ... output_schema=CustomOutputSchema,+ ... memory=AgentMemory(),+ ... system_prompt_generator=SystemPromptGenerator(+ ... background=["You are a helpful assistant"],+ ... steps=["1. Understand the request", "2. Provide a response"]+ ... )+ ... )+```++## Base Agent++The BaseAgent class provides core functionality for building AI agents with structured input/output schemas,+memory management, and streaming capabilities.++### Basic Usage++```python+import instructor+from openai import OpenAI+from atomic_agents.agents.base_agent import BaseAgent, BaseAgentConfig+from atomic_agents.lib.components.agent_memory import AgentMemory++# Initialize with OpenAI+client = instructor.from_openai(OpenAI())++# Create basic configuration+config = BaseAgentConfig(+ client=client,+ model="gpt-4",+ memory=AgentMemory()+)++# Initialize agent+agent = BaseAgent(config)+```++### Class Documentation++```{eval-rst}+.. py:class:: BaseAgent++ .. py:method:: __init__(config: BaseAgentConfig)++ Initializes a new BaseAgent instance.++ :param config: Configuration object containing client, model, memory, and other settings+ :type config: BaseAgentConfig++ .. py:method:: run(user_input: Optional[BaseIOSchema] = None) -> BaseIOSchema++ Runs the chat agent with the given user input synchronously.++ :param user_input: The input from the user+ :type user_input: Optional[BaseIOSchema]+ :return: The response from the chat agent+ :rtype: BaseIOSchema++ .. py:method:: run_async(user_input: Optional[BaseIOSchema] = None) -> AsyncGenerator[BaseIOSchema, None]++ Runs the chat agent with streaming output asynchronously.++ :param user_input: The input from the user+ :type user_input: Optional[BaseIOSchema]+ :return: An async generator yielding partial responses+ :rtype: AsyncGenerator[BaseIOSchema, None]++ .. py:method:: reset_memory()++ Resets the agent's memory to its initial state.++ .. py:method:: get_context_provider(provider_name: str) -> Type[SystemPromptContextProviderBase]++ Retrieves a context provider by name.++ :param provider_name: The name of the context provider+ :type provider_name: str+ :return: The context provider if found+ :rtype: SystemPromptContextProviderBase+ :raises KeyError: If the context provider is not found++ .. py:method:: register_context_provider(provider_name: str, provider: SystemPromptContextProviderBase)++ Registers a new context provider.++ :param provider_name: The name of the context provider+ :type provider_name: str+ :param provider: The context provider instance+ :type provider: SystemPromptContextProviderBase++ .. py:method:: unregister_context_provider(provider_name: str)++ Unregisters an existing context provider.++ :param provider_name: The name of the context provider to remove+ :type provider_name: str+ :raises KeyError: If the context provider is not found+```++### Examples++#### Basic Synchronous Interaction++```python+# Create input and get response+user_input = agent.input_schema(chat_message="Tell me about quantum computing")+response = agent.run(user_input)++print(f"Assistant: {response.chat_message}")+```++#### Streaming Response++```python+import asyncio++async def stream_chat():+ # Initialize with AsyncOpenAI for streaming+ client = instructor.from_openai(AsyncOpenAI())+ agent = BaseAgent(BaseAgentConfig(client=client, model="gpt-4"))++ # Create input and stream response+ user_input = agent.input_schema(chat_message="Explain streaming")+ print("\nUser: Explain streaming")+ print("Assistant: ", end="", flush=True)++ async for partial_response in agent.run_async(user_input):+ if hasattr(partial_response, "chat_message"):+ print(partial_response.chat_message, end="", flush=True)+ print()++asyncio.run(stream_chat())+```++#### Using Tools++```python+# Create agent with tools+agent = BaseAgent(+ config=BaseAgentConfig(+ client=client,+ model="gpt-4",+ tools=["calculator", "searxng_search"],+ tool_configs={+ "searxng_search": {+ "instance_url": "https://your-searxng-instance.com"+ }+ }+ )+)++# The agent can now use these tools in its responses+response = agent.run(+ agent.input_schema(+ chat_message="What is the square root of 144 plus the current temperature in London?"+ )+)+```++#### Custom Memory and System Prompt++```python+from atomic_agents.lib.components.system_prompt_generator import SystemPromptGenerator++# Create custom system prompt+generator = SystemPromptGenerator(+ background=["You are a helpful AI assistant specializing in technical support."],+ steps=[+ "1. Understand the technical issue",+ "2. Ask clarifying questions if needed",+ "3. Provide step-by-step solutions"+ ]+)++# Create agent with custom memory and prompt+agent = BaseAgent(+ config=BaseAgentConfig(+ client=client,+ model="gpt-4",+ memory=AgentMemory(),+ system_prompt_generator=generator+ )+)+```diff --git a/docs/api/agents.rst b/docs/api/agents.rstdeleted file mode 100644index d1c1c8b..0000000--- a/docs/api/agents.rst+++ /dev/null@@ -1,369 +0,0 @@-Agents-======--Base Agent-------------The BaseAgent class provides core functionality for building AI agents with structured input/output schemas,-memory management, and streaming capabilities.--Basic Usage-^^^^^^^^^^--.. code-block:: python-- import instructor- from openai import OpenAI- from atomic_agents.agents.base_agent import BaseAgent, BaseAgentConfig- from atomic_agents.lib.components.agent_memory import AgentMemory-- # Initialize with OpenAI- client = instructor.from_openai(OpenAI())-- # Create basic configuration- config = BaseAgentConfig(- client=client,- model="gpt-4o-mini",- memory=AgentMemory()- )-- # Initialize agent- agent = BaseAgent(config)--Class Documentation-^^^^^^^^^^^^^^^^^--.. py:class:: BaseAgent-- .. py:method:: __init__(config: BaseAgentConfig)-- Initializes a new BaseAgent instance.-- :param config: Configuration object containing client, model, memory, and other settings- :type config: BaseAgentConfig-- Example:-- .. code-block:: python-- # Initialize with custom memory and system prompt- from atomic_agents.lib.components.system_prompt_generator import SystemPromptGenerator-- agent = BaseAgent(- BaseAgentConfig(- client=client,- model="gpt-4o-mini",- memory=AgentMemory(),- system_prompt_generator=SystemPromptGenerator(- background=["You are a helpful AI assistant"],- steps=["1. Understand the user's request", "2. Provide a clear response"],- )- )- )-- # Print agent configuration- print(f"Model: {agent.model}")- print(f"Memory: {type(agent.memory).__name__}")- print(f"System Prompt: {agent.system_prompt_generator.generate_prompt()}")-- .. py:method:: run(user_input: Optional[BaseIOSchema] = None) -> BaseIOSchema-- Runs the chat agent with the given user input synchronously.-- :param user_input: The input from the user- :type user_input: Optional[BaseIOSchema]- :return: The response from the chat agent- :rtype: BaseIOSchema-- Example:-- .. code-block:: python-- # Basic synchronous interaction- user_input = agent.input_schema(chat_message="Tell me about quantum computing")- response = agent.run(user_input)-- # Print the response- print("\nUser: Tell me about quantum computing")- print(f"Assistant: {response.chat_message}")-- .. py:method:: run_async(user_input: Optional[BaseIOSchema] = None)-- Runs the chat agent with streaming output asynchronously.-- :param user_input: The input from the user- :type user_input: Optional[BaseIOSchema]- :return: An async generator yielding partial responses- :rtype: AsyncGenerator[BaseIOSchema, None]-- Example:-- .. code-block:: python-- import asyncio- import json-- async def stream_chat():- # Initialize with AsyncOpenAI for streaming- client = instructor.from_openai(AsyncOpenAI())- agent = BaseAgent(BaseAgentConfig(client=client, model="gpt-4o-mini"))-- # Create input and stream response- user_input = agent.input_schema(chat_message="Explain streaming")- print("\nUser: Explain streaming")- print("Assistant: ", end="", flush=True)-- async for partial_response in agent.run_async(user_input):- # Print each new token as it arrives- if hasattr(partial_response, "chat_message"):- print(partial_response.chat_message, end="", flush=True)- print() # New line at end-- asyncio.run(stream_chat())-- .. py:method:: reset_memory()-- Resets the agent's memory to its initial state.-- Example:-- .. code-block:: python-- # Use agent for a conversation- response1 = agent.run(agent.input_schema(chat_message="Hello!"))- print(f"First response: {response1.chat_message}")-- response2 = agent.run(agent.input_schema(chat_message="How are you?"))- print(f"Second response: {response2.chat_message}")-- # Reset memory to start fresh- agent.reset_memory()- print("Memory reset to initial state")-- .. py:method:: get_context_provider(provider_name: str) -> Type[SystemPromptContextProviderBase]-- Retrieves a context provider by name.-- :param provider_name: The name of the context provider- :type provider_name: str- :return: The context provider if found- :rtype: SystemPromptContextProviderBase- :raises KeyError: If the context provider is not found-- Example:-- .. code-block:: python-- # Get a specific context provider- try:- provider = agent.get_context_provider("my_provider")- print(f"Found provider: {provider}")- except KeyError:- print("Provider not found")-- .. py:method:: register_context_provider(provider_name: str, provider: SystemPromptContextProviderBase)-- Registers a new context provider.-- :param provider_name: The name of the context provider- :type provider_name: str- :param provider: The context provider instance- :type provider: SystemPromptContextProviderBase-- Example:-- .. code-block:: python-- from atomic_agents.lib.components.system_prompt_generator import SystemPromptContextProviderBase-- # Create and register a custom context provider- class MyContextProvider(SystemPromptContextProviderBase):- def get_context(self) -> str:- return "Custom context for the agent"-- agent.register_context_provider("my_provider", MyContextProvider())- print("Custom context provider registered")-- .. py:method:: unregister_context_provider(provider_name: str)-- Unregisters an existing context provider.-- :param provider_name: The name of the context provider to remove- :type provider_name: str- :raises KeyError: If the context provider is not found-- Example:-- .. code-block:: python-- # Remove a context provider- try:- agent.unregister_context_provider("my_provider")- print("Provider unregistered")- except KeyError:- print("Provider not found")--Advanced Usage-^^^^^^^^^^^^--Here's a complete example showing how to create an interactive chat interface with streaming support:--.. code-block:: python-- import asyncio- from openai import AsyncOpenAI, OpenAI- import instructor- from atomic_agents.agents.base_agent import BaseAgent, BaseAgentConfig-- async def chat_loop(streaming: bool = False):- """Interactive chat loop with the AI agent."""- # Initialize agent based on streaming mode- if streaming:- client = instructor.from_openai(AsyncOpenAI())- else:- client = instructor.from_openai(OpenAI())-- agent = BaseAgent(BaseAgentConfig(client=client, model="gpt-4o-mini"))- print("Chat initialized. Type 'exit' to quit.")-- while True:- # Get user input- user_message = input("\nYou: ")- if user_message.lower() == "exit":- break-- # Process message- user_input = agent.input_schema(chat_message=user_message)- print("\nAssistant: ", end="", flush=True)-- if streaming:- # Stream response token by token- async for partial_response in agent.run_async(user_input):- if hasattr(partial_response, "chat_message"):- print(partial_response.chat_message, end="", flush=True)- print() # New line after response- else:- # Get complete response- response = agent.run(user_input)- print(response.chat_message)-- # Run interactive chat with streaming- asyncio.run(chat_loop(streaming=True))--Input/Output Schemas-^^^^^^^^^^^^^^^^^--The BaseAgent uses Pydantic models for input and output validation. You can use the default schemas or create custom ones.--Default Schemas-"""""""""""""--.. py:class:: BaseAgentInputSchema-- Schema for user input to the agent.-- .. py:attribute:: chat_message- :type: str-- The chat message sent by the user to the assistant.--.. py:class:: BaseAgentOutputSchema-- Schema for agent responses.-- .. py:attribute:: chat_message- :type: str-- The chat message generated by the agent, with markdown support.--Custom Schema Example-"""""""""""""""""""--Here's an example of a custom input/output schema pair for an agent that provides suggested follow-up questions:--.. code-block:: python-- from typing import List- from pydantic import Field- from atomic_agents.lib.base.base_io_schema import BaseIOSchema-- class CustomInputSchema(BaseIOSchema):- """Schema for user input with context."""- chat_message: str = Field(- ...,- description="The chat message sent by the user."- )- context: str = Field(- "",- description="Optional context for the message."- )-- class CustomOutputSchema(BaseIOSchema):- """Schema for responses with suggested questions."""- chat_message: str = Field(- ...,- description="The chat message from the agent."- )- suggested_questions: List[str] = Field(- ...,- description="Follow-up questions the user could ask."- )-- # Use custom schemas with agent- agent = BaseAgent(- config=BaseAgentConfig(- client=client,- model="gpt-4o-mini",- input_schema=CustomInputSchema,- output_schema=CustomOutputSchema- )- )-- # Example usage- response = agent.run(- CustomInputSchema(- chat_message="Tell me about quantum computing",- context="The user is a beginner"- )- )- print(f"Response: {response.chat_message}")- print("\nSuggested questions:")- for question in response.suggested_questions:- print(f"- {question}")--Configuration-^^^^^^^^^^^--.. py:class:: BaseAgentConfig-- Configuration class for BaseAgent initialization.-- .. py:attribute:: client- :type: instructor.client.Instructor-- Client for interacting with the language model.-- .. py:attribute:: model- :type: str-- The model to use for generating responses.-- .. py:attribute:: memory- :type: Optional[AgentMemory]-- Memory component for storing chat history.-- .. py:attribute:: system_prompt_generator- :type: Optional[SystemPromptGenerator]-- Component for generating system prompts.-- .. py:attribute:: temperature- :type: Optional[float]-- Temperature for response generation (0 to 1).-- .. py:attribute:: max_tokens- :type: Optional[int]-- Maximum number of tokens in responses.diff --git a/docs/api/components.rst b/docs/api/components.mdsimilarity index 80%rename from docs/api/components.rstrename to docs/api/components.mdindex f8c7675..a3a8c60 100644--- a/docs/api/components.rst+++ b/docs/api/components.md@@ -1,33 +1,37 @@-Components-==========+# Components-Agent Memory-------------+## Agent Memory+```{eval-rst}.. automodule:: atomic_agents.lib.components.agent_memory:members::undoc-members::show-inheritance::no-index: Message.role Message.content Message.turn_id+```-System Prompt Generator------------------------+## System Prompt Generator+```{eval-rst}.. automodule:: atomic_agents.lib.components.system_prompt_generator:members::undoc-members::show-inheritance:+```-Base Components----------------+## Base Components+```{eval-rst}.. automodule:: atomic_agents.lib.base.base_tool:members::undoc-members::show-inheritance::no-index: BaseToolConfig.title BaseToolConfig.description BaseTool.input_schema BaseTool.output_schema+```+```{eval-rst}.. automodule:: atomic_agents.lib.base.base_io_schema:members::undoc-members::show-inheritance:+```diff --git a/docs/api/index.md b/docs/api/index.mdnew file mode 100644index 0000000..05f3635--- /dev/null+++ b/docs/api/index.md@@ -0,0 +1,57 @@+# API Reference++This section contains the API reference for all public modules and classes in Atomic Agents.++```{toctree}+:maxdepth: 2+:caption: API Reference++agents+components+utils+```++## Core Components++The Atomic Agents framework is built around several core components that work together to provide a flexible and powerful system for building AI agents.++### Agents++The agents module provides the base classes for creating AI agents:++- `BaseAgent`: The foundational agent class that handles interactions with LLMs+- `BaseAgentConfig`: Configuration class for customizing agent behavior+- `BaseAgentInputSchema`: Standard input schema for agent interactions+- `BaseAgentOutputSchema`: Standard output schema for agent responses++[Learn more about agents](agents.md)++### Components++The components module contains building blocks for extending agent functionality:++- `AgentMemory`: Manages conversation history and context+- `SystemPromptGenerator`: Creates dynamic system prompts+- `SystemPromptContextProvider`: Provides contextual information for prompts++[Learn more about components](components.md)++### Utils++The utils module provides helper functions and utilities:++- Message formatting+- Tool response handling+- Schema validation+- Error handling++[Learn more about utilities](utils.md)++## Getting Started++For practical examples and guides on using these components, see:++- [Quickstart Guide](../guides/quickstart.md)+- [Basic Concepts](../guides/basic_concepts.md)+- [Tools Guide](../guides/tools.md)+- [Advanced Usage](../guides/advanced_usage.md)diff --git a/docs/api/index.rst b/docs/api/index.rstdeleted file mode 100644index 73efa32..0000000--- a/docs/api/index.rst+++ /dev/null@@ -1,28 +0,0 @@-API Reference-=============--This section contains the API reference for all public modules and classes in Atomic Agents.--.. note::- Use the sidebar to navigate between different sections of the API reference.- You can return to the main documentation using the navigation menu on the left.--.. toctree::- :maxdepth: 2- :caption: API Sections-- agents- components- utils--Core Components------------------.. automodule:: atomic_agents- :members:- :undoc-members:- :show-inheritance:--.. seealso::- - :doc:`/guides/index` - Browse the user guides- - :doc:`/index` - Return to main documentationdiff --git a/docs/api/utils.rst b/docs/api/utils.mdsimilarity index 63%rename from docs/api/utils.rstrename to docs/api/utils.mdindex 5f9c71d..50907c3 100644--- a/docs/api/utils.rst+++ b/docs/api/utils.md@@ -1,10 +1,10 @@-Utilities-=========+# Utilities-Tool Message Formatting------------------------+## Tool Message Formatting+```{eval-rst}.. automodule:: atomic_agents.lib.utils.format_tool_message:members::undoc-members::show-inheritance:+```diff --git a/docs/contributing.md b/docs/contributing.mdnew file mode 100644index 0000000..a64bafa--- /dev/null+++ b/docs/contributing.md@@ -0,0 +1,157 @@+# Contributing Guide++Thank you for your interest in contributing to Atomic Agents! This guide will help you get started with contributing to the project.++## Ways to Contribute++There are many ways to contribute to Atomic Agents:++1. **Report Bugs**: Submit bug reports on our [Issue Tracker](https://github.com/BrainBlend-AI/atomic-agents/issues)+2. **Suggest Features**: Share your ideas for new features or improvements+3. **Improve Documentation**: Help us make the documentation clearer and more comprehensive+4. **Submit Code**: Fix bugs, add features, or create new tools+5. **Share Examples**: Create example projects that showcase different use cases+6. **Write Tests**: Help improve our test coverage and reliability++## Development Setup++1. Fork and clone the repository:+ ```bash+ git clone https://github.com/YOUR_USERNAME/atomic-agents.git+ cd atomic-agents+ ```++2. Install dependencies:+ ```bash+ poetry install+ ```++3. Set up pre-commit hooks:+ ```bash+ pre-commit install+ ```++4. Create a new branch:+ ```bash+ git checkout -b feature/your-feature-name+ ```++## Code Style++We follow these coding standards:++- Use [Black](https://black.readthedocs.io/) for code formatting+- Follow [PEP 8](https://www.python.org/dev/peps/pep-0008/) style guide+- Write docstrings in [Google style](https://google.github.io/styleguide/pyguide.html#38-comments-and-docstrings)+- Add type hints to function signatures+- Keep functions focused and modular+- Write clear commit messages++## Creating Tools++When creating new tools:++1. Use the tool template:+ ```bash+ atomic-assembler create-tool my-tool+ ```++2. Implement the required interfaces:+ ```python+ from pydantic import BaseModel+ from atomic_agents.lib.tools import BaseTool++ class MyToolInputs(BaseModel):+ # Define input schema+ pass++ class MyToolOutputs(BaseModel):+ # Define output schema+ pass++ class MyTool(BaseTool):+ name = "my_tool"+ description = "Tool description"+ inputs_schema = MyToolInputs+ outputs_schema = MyToolOutputs++ def run(self, inputs: MyToolInputs) -> MyToolOutputs:+ # Implement tool logic+ pass+ ```++3. Add comprehensive tests:+ ```python+ def test_my_tool():+ tool = MyTool()+ inputs = MyToolInputs(...)+ result = tool.run(inputs)+ assert isinstance(result, MyToolOutputs)+ # Add more assertions+ ```++4. Document your tool:+ - Add a README.md with usage examples+ - Include configuration instructions+ - Document any dependencies+ - Explain error handling++## Testing++Run tests with pytest:++```bash+poetry run pytest+```++Include tests for:+- Normal operation+- Edge cases+- Error conditions+- Async functionality+- Integration with other components++## Documentation++When adding documentation:++1. Follow the existing structure+2. Include code examples+3. Add type hints and docstrings+4. Update relevant guides+5. Build and verify locally:+ ```bash+ cd docs+ poetry run sphinx-build -b html . _build/html+ ```++## Submitting Changes++1. Commit your changes:+ ```bash+ git add .+ git commit -m "feat: add new feature"+ ```++2. Push to your fork:+ ```bash+ git push origin feature/your-feature-name+ ```++3. Create a Pull Request:+ - Describe your changes+ - Reference any related issues+ - Include test results+ - Add documentation updates++## Getting Help++If you need help:++- Join our [Reddit community](https://www.reddit.com/r/AtomicAgents/)+- Check the [documentation](https://atomic-agents.readthedocs.io/)+- Ask questions on [GitHub Discussions](https://github.com/BrainBlend-AI/atomic-agents/discussions)++## Code of Conduct++Please note that this project is released with a Code of Conduct. By participating in this project you agree to abide by its terms. You can find the full text in our [GitHub repository](https://github.com/BrainBlend-AI/atomic-agents/blob/main/CODE_OF_CONDUCT.md).diff --git a/docs/examples/index.md b/docs/examples/index.mdnew file mode 100644index 0000000..03d4e5a--- /dev/null+++ b/docs/examples/index.md@@ -0,0 +1,98 @@+# Example Projects++This section contains detailed examples of using Atomic Agents in various scenarios.++## Quickstart Examples++Simple examples to get started with the framework:++- Basic chatbot with memory+- Custom chatbot with personality+- Streaming responses+- Custom input/output schemas+- Multiple provider support++[View Quickstart Examples](https://github.com/BrainBlend-AI/atomic-agents/tree/main/atomic-examples/quickstart)++## Basic Multimodal++Examples of working with images and text:++- Image analysis with text descriptions+- Image-based question answering+- Visual content generation+- Multi-image comparisons++[View Basic Multimodal Examples](https://github.com/BrainBlend-AI/atomic-agents/tree/main/atomic-examples/basic-multimodal)++## RAG Chatbot++Build context-aware chatbots with retrieval-augmented generation:++- Document indexing and embedding+- Semantic search integration+- Context-aware responses+- Source attribution+- Follow-up suggestions++[View RAG Chatbot Examples](https://github.com/BrainBlend-AI/atomic-agents/tree/main/atomic-examples/rag-chatbot)++## Web Search Agent++Create agents that can search and analyze web content:++- Web search integration+- Content extraction+- Result synthesis+- Multi-source research+- Citation tracking++[View Web Search Examples](https://github.com/BrainBlend-AI/atomic-agents/tree/main/atomic-examples/web-search-agent)++## Deep Research++Perform comprehensive research tasks:++- Multi-step research workflows+- Information synthesis+- Source validation+- Structured output generation+- Citation management++[View Deep Research Examples](https://github.com/BrainBlend-AI/atomic-agents/tree/main/atomic-examples/deep-research)++## YouTube Summarizer++Extract and analyze information from videos:++- Transcript extraction+- Content summarization+- Key point identification+- Timestamp linking+- Chapter generation++[View YouTube Summarizer Examples](https://github.com/BrainBlend-AI/atomic-agents/tree/main/atomic-examples/youtube-summarizer)++## YouTube to Recipe++Convert cooking videos into structured recipes:++- Video analysis+- Recipe extraction+- Ingredient parsing+- Step-by-step instructions+- Time and temperature conversion++[View YouTube Recipe Examples](https://github.com/BrainBlend-AI/atomic-agents/tree/main/atomic-examples/youtube-to-recipe)++## Orchestration Agent++Coordinate multiple agents for complex tasks:++- Agent coordination+- Task decomposition+- Progress tracking+- Error handling+- Result aggregation++[View Orchestration Examples](https://github.com/BrainBlend-AI/atomic-agents/tree/main/atomic-examples/orchestration-agent)diff --git a/docs/guides/advanced_usage.md b/docs/guides/advanced_usage.mdnew file mode 100644index 0000000..b5534ba--- /dev/null+++ b/docs/guides/advanced_usage.md@@ -0,0 +1,241 @@+# Advanced Usage++This guide covers advanced features and patterns in Atomic Agents.++## Custom Schemas++You can create custom input/output schemas for specialized agents:++```python+from typing import List+from pydantic import Field+from atomic_agents.lib.base.base_io_schema import BaseIOSchema+from atomic_agents.agents.base_agent import BaseAgent, BaseAgentConfig++# Custom output schema+class CustomOutputSchema(BaseIOSchema):+ """Schema for responses with suggested follow-up questions."""++ chat_message: str = Field(+ ...,+ description="The chat message exchanged between the user and the chat agent.",+ )+ suggested_user_questions: List[str] = Field(+ ...,+ description="A list of suggested follow-up questions the user could ask the agent.",+ )++# Initialize memory with custom schema+initial_message = CustomOutputSchema(+ chat_message="Hello! How can I assist you today?",+ suggested_user_questions=[+ "What can you do?",+ "Tell me a joke",+ "Tell me about how you were made"+ ]+)+memory.add_message("assistant", initial_message)++# Create agent with custom schema+agent = BaseAgent(+ config=BaseAgentConfig(+ client=client,+ model="gpt-4o-mini",+ memory=memory,+ output_schema=CustomOutputSchema+ )+)+```++## RAG Implementation++Here's how to implement a Retrieval-Augmented Generation (RAG) system with two specialized agents:++```python+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++# Query Agent for generating semantic search queries+class RAGQueryAgentInputSchema(BaseIOSchema):+ """Input schema for the RAG query agent."""+ user_message: str = Field(+ ...,+ description="The user's question or message to generate a semantic search query for"+ )++class RAGQueryAgentOutputSchema(BaseIOSchema):+ """Output schema for the RAG query agent."""+ query: str = Field(+ ...,+ description="The semantic search query to use for retrieving relevant chunks"+ )++query_agent = BaseAgent(+ BaseAgentConfig(+ client=client,+ model="gpt-4o-mini",+ system_prompt_generator=SystemPromptGenerator(+ background=[+ "You are an expert at formulating semantic search queries for RAG systems.",+ "Your role is to convert user questions into effective semantic search queries that will retrieve the most relevant text chunks.",+ ],+ steps=[+ "1. Analyze the user's question to identify key concepts and information needs",+ "2. Reformulate the question into a semantic search query that will match relevant content",+ "3. Ensure the query captures the core meaning while being general enough to match similar content",+ ],+ output_instructions=[+ "Generate a clear, concise semantic search query",+ "Focus on key concepts and entities from the user's question",+ "Avoid overly specific details that might miss relevant matches",+ "Include synonyms or related terms when appropriate",+ "Explain your reasoning for the query formulation",+ ],+ ),+ input_schema=RAGQueryAgentInputSchema,+ output_schema=RAGQueryAgentOutputSchema,+ )+)++# QA Agent for answering questions using retrieved context+class RAGQuestionAnsweringAgentInputSchema(BaseIOSchema):+ """Input schema for the RAG QA agent."""+ question: str = Field(+ ...,+ description="The user's question to answer"+ )++class RAGQuestionAnsweringAgentOutputSchema(BaseIOSchema):+ """Output schema for the RAG QA agent."""+ answer: str = Field(+ ...,+ description="The answer to the user's question based on the retrieved context"+ )++qa_agent = BaseAgent(+ BaseAgentConfig(+ client=client,+ model="gpt-4o-mini",+ system_prompt_generator=SystemPromptGenerator(+ background=[+ "You are an expert at answering questions using retrieved context chunks from a RAG system.",+ "Your role is to synthesize information from the chunks to provide accurate, well-supported answers.",+ "You must explain your reasoning process before providing the answer.",+ ],+ steps=[+ "1. Analyze the question and available context chunks",+ "2. Identify the most relevant information in the chunks",+ "3. Explain how you'll use this information to answer the question",+ "4. Synthesize information into a coherent answer",+ ],+ output_instructions=[+ "First explain your reasoning process clearly",+ "Then provide a clear, direct answer based on the context",+ "If context is insufficient, state this in your reasoning",+ "Never make up information not present in the chunks",+ "Focus on being accurate and concise",+ ],+ ),+ input_schema=RAGQuestionAnsweringAgentInputSchema,+ output_schema=RAGQuestionAnsweringAgentOutputSchema,+ )+)+```++## Streaming with Rich Display++Handle streaming responses with rich formatting:++```python+from rich.live import Live+from rich.text import Text+from typing import List++async def process_stream():+ with Live("", refresh_per_second=10, auto_refresh=True) as live:+ current_response = ""+ current_questions: List[str] = []++ async for partial_response in agent.run_async(input_schema):+ if hasattr(partial_response, "chat_message") and partial_response.chat_message:+ # Update message if changed+ if partial_response.chat_message != current_response:+ current_response = partial_response.chat_message++ # Update questions if available+ if hasattr(partial_response, "suggested_user_questions"):+ current_questions = partial_response.suggested_user_questions++ # Build display text+ display_text = Text.assemble(+ ("Agent: ", "bold green"),+ (current_response, "green")+ )++ # Add questions if we have them+ if current_questions:+ display_text.append("\n\n")+ display_text.append(+ "Suggested questions you could ask:\n",+ style="bold cyan"+ )+ for i, question in enumerate(current_questions, 1):+ display_text.append(f"{i}. {question}\n", style="cyan")++ live.update(display_text)++# Run with asyncio+import asyncio+asyncio.run(process_stream())+```++## Best Practices++### Error Handling++```python+try:+ response = agent.run(input_schema)+except openai.APIError as e:+ console.print(f"[red]API Error:[/red] {e}")+ # Handle API-specific errors+except Exception as e:+ console.print(f"[red]Error:[/red] {e}")+ # Handle other errors appropriately+```++### Memory Management++```python+# Initialize memory with context+memory = AgentMemory()++# Add system context+memory.add_message(+ "system",+ "Important context or instructions for the agent..."+)++# Add initial message+memory.add_message("assistant", initial_message)++# Clear memory if needed+memory.clear()+```++### Security++```python+# Use environment variables for sensitive data+API_KEY = os.getenv("OPENAI_API_KEY")+if not API_KEY:+ raise ValueError(+ "API key is not set. Please set the API key as a static variable "+ "or in the environment variable OPENAI_API_KEY."+ )+```++## Troubleshootingdiff --git a/docs/guides/advanced_usage.rst b/docs/guides/advanced_usage.rstdeleted file mode 100644index 7a815d5..0000000--- a/docs/guides/advanced_usage.rst+++ /dev/null@@ -1,273 +0,0 @@-Advanced Usage-=============--This guide covers advanced features and patterns in Atomic Agents.--Custom Schemas---------------You can create custom input/output schemas for specialized agents:--.. code-block:: python-- from typing import List- from pydantic import Field- from atomic_agents.lib.base.base_io_schema import BaseIOSchema- from atomic_agents.agents.base_agent import BaseAgent, BaseAgentConfig-- # Custom output schema- class CustomOutputSchema(BaseIOSchema):- """Schema for responses with suggested follow-up questions."""-- chat_message: str = Field(- ...,- description="The chat message exchanged between the user and the chat agent.",- )- suggested_user_questions: List[str] = Field(- ...,- description="A list of suggested follow-up questions the user could ask the agent.",- )-- # Initialize memory with custom schema- initial_message = CustomOutputSchema(- chat_message="Hello! How can I assist you today?",- suggested_user_questions=[- "What can you do?",- "Tell me a joke",- "Tell me about how you were made"- ]- )- memory.add_message("assistant", initial_message)-- # Create agent with custom schema- agent = BaseAgent(- config=BaseAgentConfig(- client=client,- model="gpt-4o-mini",- memory=memory,- output_schema=CustomOutputSchema- )- )--RAG Implementation-------------------Here's how to implement a Retrieval-Augmented Generation (RAG) system with two specialized agents:--.. code-block:: python-- 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-- # Query Agent for generating semantic search queries- class RAGQueryAgentInputSchema(BaseIOSchema):- """Input schema for the RAG query agent."""- user_message: str = Field(- ...,- description="The user's question or message to generate a semantic search query for"- )-- class RAGQueryAgentOutputSchema(BaseIOSchema):- """Output schema for the RAG query agent."""- query: str = Field(- ...,- description="The semantic search query to use for retrieving relevant chunks"- )-- query_agent = BaseAgent(- BaseAgentConfig(- client=client,- model="gpt-4o-mini",- system_prompt_generator=SystemPromptGenerator(- background=[- "You are an expert at formulating semantic search queries for RAG systems.",- "Your role is to convert user questions into effective semantic search queries that will retrieve the most relevant text chunks.",- ],- steps=[- "1. Analyze the user's question to identify key concepts and information needs",- "2. Reformulate the question into a semantic search query that will match relevant content",- "3. Ensure the query captures the core meaning while being general enough to match similar content",- ],- output_instructions=[- "Generate a clear, concise semantic search query",- "Focus on key concepts and entities from the user's question",- "Avoid overly specific details that might miss relevant matches",- "Include synonyms or related terms when appropriate",- "Explain your reasoning for the query formulation",- ],- ),- input_schema=RAGQueryAgentInputSchema,- output_schema=RAGQueryAgentOutputSchema,- )- )-- # QA Agent for answering questions using retrieved context- class RAGQuestionAnsweringAgentInputSchema(BaseIOSchema):- """Input schema for the RAG QA agent."""- question: str = Field(- ...,- description="The user's question to answer"- )-- class RAGQuestionAnsweringAgentOutputSchema(BaseIOSchema):- """Output schema for the RAG QA agent."""- answer: str = Field(- ...,- description="The answer to the user's question based on the retrieved context"- )-- qa_agent = BaseAgent(- BaseAgentConfig(- client=client,- model="gpt-4o-mini",- system_prompt_generator=SystemPromptGenerator(- background=[- "You are an expert at answering questions using retrieved context chunks from a RAG system.",- "Your role is to synthesize information from the chunks to provide accurate, well-supported answers.",- "You must explain your reasoning process before providing the answer.",- ],- steps=[- "1. Analyze the question and available context chunks",- "2. Identify the most relevant information in the chunks",- "3. Explain how you'll use this information to answer the question",- "4. Synthesize information into a coherent answer",- ],- output_instructions=[- "First explain your reasoning process clearly",- "Then provide a clear, direct answer based on the context",- "If context is insufficient, state this in your reasoning",- "Never make up information not present in the chunks",- "Focus on being accurate and concise",- ],- ),- input_schema=RAGQuestionAnsweringAgentInputSchema,- output_schema=RAGQuestionAnsweringAgentOutputSchema,- )- )--Streaming with Rich Display---------------------------Handle streaming responses with rich formatting:--.. code-block:: python-- from rich.live import Live- from rich.text import Text- from typing import List-- async def process_stream():- with Live("", refresh_per_second=10, auto_refresh=True) as live:- current_response = ""- current_questions: List[str] = []-- async for partial_response in agent.run_async(input_schema):- if hasattr(partial_response, "chat_message") and partial_response.chat_message:- # Update message if changed- if partial_response.chat_message != current_response:- current_response = partial_response.chat_message-- # Update questions if available- if hasattr(partial_response, "suggested_user_questions"):- current_questions = partial_response.suggested_user_questions-- # Build display text- display_text = Text.assemble(- ("Agent: ", "bold green"),- (current_response, "green")- )-- # Add questions if we have them- if current_questions:- display_text.append("\n\n")- display_text.append(- "Suggested questions you could ask:\n",- style="bold cyan"- )- for i, question in enumerate(current_questions, 1):- display_text.append(f"{i}. {question}\n", style="cyan")-- live.update(display_text)-- # Run with asyncio- import asyncio- asyncio.run(process_stream())--Best Practices---------------Error Handling-^^^^^^^^^^^^--.. code-block:: python-- try:- response = agent.run(input_schema)- except openai.APIError as e:- console.print(f"[red]API Error:[/red] {e}")- # Handle API-specific errors- except Exception as e:- console.print(f"[red]Error:[/red] {e}")- # Handle other errors appropriately--Memory Management-^^^^^^^^^^^^^^^--.. code-block:: python-- # Initialize memory with context- memory = AgentMemory()-- # Add system context- memory.add_message(- "system",- "Important context or instructions for the agent..."- )-- # Add initial message- memory.add_message("assistant", initial_message)-- # Clear memory if needed- memory.clear()--Security-^^^^^^^--.. code-block:: python-- # Use environment variables for sensitive data- API_KEY = os.getenv("OPENAI_API_KEY")- if not API_KEY:- raise ValueError(- "API key is not set. Please set the API key as a static variable "- "or in the environment variable OPENAI_API_KEY."- )--Troubleshooting----------------Common issues and solutions:--Schema Validation-^^^^^^^^^^^^^^^--- Ensure all required fields are provided in schemas-- Use proper Pydantic Field descriptions-- Check that schema types match expected values--Memory Issues-^^^^^^^^^^^--- Clear memory when needed using ``memory.clear()``-- Use streaming for large responses-- Monitor memory usage in long conversations--API Issues-^^^^^^^^^--- Handle rate limits with exponential backoff-- Use proper async/await patterns-- Verify API key and model availabilitydiff --git a/docs/guides/basic_concepts.md b/docs/guides/basic_concepts.mdnew file mode 100644index 0000000..27dcc8e--- /dev/null+++ b/docs/guides/basic_concepts.md@@ -0,0 +1,237 @@+# Basic Concepts++This guide introduces the core concepts of Atomic Agents.++## What is an Agent?++In Atomic Agents, an agent is an autonomous entity that can:++- Process input using natural language+- Make decisions based on its configuration and context+- Execute actions through defined tools and capabilities+- Maintain state and history of interactions++## Core Components++### BaseAgent++The `BaseAgent` class is the foundation of all agents in the framework. It provides:++- Input/output schema handling+- Memory management+- System prompt generation+- Streaming capabilities+- Tool integration++### Components++Components are modular pieces that can be added to agents to extend their functionality:++#### AgentMemory++Manages conversation history and state:++```python+from atomic_agents.lib.components.agent_memory import AgentMemory+from atomic_agents.agents.base_agent import BaseAgentOutputSchema+from rich.console import Console++# Initialize console for pretty outputs+console = Console()++# Initialize memory+memory = AgentMemory()++# Initialize with a greeting+initial_message = BaseAgentOutputSchema(+ chat_message="Hello! How can I assist you today?"+)+memory.add_message("assistant", initial_message)++# Add system context if needed+memory.add_message(+ "system",+ "This agent has access to specific tools and capabilities..."+)++# Access conversation history+for message in memory.get_messages():+ console.print(f"{message.role}: {message.content}")+```++#### SystemPromptGenerator++Customizes agent behavior through prompts:++```python+from atomic_agents.lib.components.system_prompt_generator import SystemPromptGenerator++generator = SystemPromptGenerator(+ background=[+ "This assistant is a knowledgeable AI designed to be helpful, friendly, and informative.",+ "It specializes in providing clear explanations and step-by-step guidance.",+ "It maintains a professional yet approachable tone.",+ ],+ steps=[+ "1. Carefully analyze the user's input to understand their needs and context.",+ "2. Consider any relevant background information or previous conversation context.",+ "3. Formulate a clear, structured response that directly addresses the query.",+ "4. Include examples or analogies when they would help clarify the explanation.",+ ],+ output_instructions=[+ "Always provide clear, actionable information.",+ "Use markdown formatting for code blocks and technical terms.",+ "Break down complex concepts into digestible parts.",+ "Maintain a helpful and encouraging tone.",+ ]+)++# Use in agent configuration+agent = BaseAgent(+ config=BaseAgentConfig(+ client=client,+ model="gpt-4o-mini",+ memory=memory,+ system_prompt_generator=generator+ )+)+```++## Basic Usage Patterns++### Creating an Agent++```python+import os+import instructor+import openai+from rich.console import Console+from rich.panel import Panel+from atomic_agents.agents.base_agent import BaseAgent, BaseAgentConfig++# Initialize console for pretty outputs+console = Console()++# API Key setup+API_KEY = os.getenv("OPENAI_API_KEY")+if not API_KEY:+ raise ValueError(+ "API key is not set. Please set the API key as a static variable "+ "or in the environment variable OPENAI_API_KEY."+ )++# OpenAI client setup+client = instructor.from_openai(openai.OpenAI(api_key=API_KEY))++# Create agent with custom configuration+agent = BaseAgent(+ config=BaseAgentConfig(+ client=client,+ model="gpt-4o-mini",+ memory=memory,+ system_prompt_generator=generator+ )+)++# Display the system prompt+default_system_prompt = agent.system_prompt_generator.generate_prompt()+console.print(Panel(default_system_prompt, width=console.width, style="bold cyan"))+```++### Running Commands++```python+from atomic_agents.agents.base_agent import BaseAgentInputSchema+from rich.text import Text+from rich.live import Live++# Simple command+input_schema = BaseAgentInputSchema(chat_message="What is the weather?")+response = agent.run(input_schema)+console.print(Text("Agent:", style="bold green"), end=" ")+console.print(Text(response.chat_message, style="green"))++# Streaming response+async def process_stream():+ with Live("", refresh_per_second=10, auto_refresh=True) as live:+ current_response = ""+ async for partial_response in agent.run_async(input_schema):+ if hasattr(partial_response, "chat_message") and partial_response.chat_message:+ if partial_response.chat_message != current_response:+ current_response = partial_response.chat_message+ display_text = Text.assemble(+ ("Agent: ", "bold green"),+ (current_response, "green")+ )+ live.update(display_text)++# Run with asyncio+import asyncio+asyncio.run(process_stream())+```++## Next Steps++After understanding these basic concepts, you can:++1. Explore [advanced usage patterns](advanced_usage)+2. Check out the [API Reference](/api/index) for detailed documentation+3. Try building your own custom agents++## Implementation Patterns++Atomic Agents supports several common implementation patterns for different use cases:++### Chatbots and Assistants++Create conversational agents with various capabilities:++```python+from atomic_agents.lib.components.agent_memory import AgentMemory+from atomic_agents.lib.components.system_prompt_generator import SystemPromptGenerator++# Create memory for conversation history+memory = AgentMemory()++# Create personality+generator = SystemPromptGenerator(+ background=["You are a helpful assistant specializing in technical support."],+ steps=[+ "1. Understand the technical issue",+ "2. Ask clarifying questions if needed",+ "3. Provide step-by-step solutions"+ ]+)++# Create agent+support_agent = BaseAgent(+ config=BaseAgentConfig(+ client=client,+ model="gpt-4o-mini",+ memory=memory,+ system_prompt_generator=generator+ )+)+```++### RAG Systems++Build Retrieval-Augmented Generation systems:++```python+from atomic_agents.lib.components.rag import RAGComponent+from atomic_agents.lib.components.embeddings import EmbeddingsManager++# Initialize RAG components+embeddings = EmbeddingsManager(client=client)+rag = RAGComponent(embeddings=embeddings)++# Create RAG agent+rag_agent = BaseAgent(+ config=BaseAgentConfig(+ client=client,+ model="gpt-4o-mini",+ components={"rag": rag}+ )+)+```diff --git a/docs/guides/basic_concepts.rst b/docs/guides/basic_concepts.rstdeleted file mode 100644index 8c630dc..0000000--- a/docs/guides/basic_concepts.rst+++ /dev/null@@ -1,190 +0,0 @@-Basic Concepts-=============--This guide introduces the core concepts of Atomic Agents.--What is an Agent?------------------In Atomic Agents, an agent is an autonomous entity that can:--- Process input using natural language-- Make decisions based on its configuration and context-- Execute actions through defined tools and capabilities-- Maintain state and history of interactions--Core Components----------------BaseAgent-^^^^^^^^--The ``BaseAgent`` class is the foundation of all agents in the framework. It provides:--- Input/output schema handling-- Memory management-- System prompt generation-- Streaming capabilities-- Tool integration--Components-^^^^^^^^^--Components are modular pieces that can be added to agents to extend their functionality:--AgentMemory-""""""""""--Manages conversation history and state:--.. code-block:: python-- from atomic_agents.lib.components.agent_memory import AgentMemory- from atomic_agents.agents.base_agent import BaseAgentOutputSchema- from rich.console import Console-- # Initialize console for pretty outputs- console = Console()-- # Initialize memory- memory = AgentMemory()-- # Initialize with a greeting- initial_message = BaseAgentOutputSchema(- chat_message="Hello! How can I assist you today?"- )- memory.add_message("assistant", initial_message)-- # Add system context if needed- memory.add_message(- "system",- "This agent has access to specific tools and capabilities..."- )-- # Access conversation history- for message in memory.get_messages():- console.print(f"{message.role}: {message.content}")--SystemPromptGenerator-"""""""""""""""""""--Customizes agent behavior through prompts:--.. code-block:: python-- from atomic_agents.lib.components.system_prompt_generator import SystemPromptGenerator-- generator = SystemPromptGenerator(- background=[- "This assistant is a knowledgeable AI designed to be helpful, friendly, and informative.",- "It specializes in providing clear explanations and step-by-step guidance.",- "It maintains a professional yet approachable tone.",- ],- steps=[- "1. Carefully analyze the user's input to understand their needs and context.",- "2. Consider any relevant background information or previous conversation context.",- "3. Formulate a clear, structured response that directly addresses the query.",- "4. Include examples or analogies when they would help clarify the explanation.",- ],- output_instructions=[- "Always provide clear, actionable information.",- "Use markdown formatting for code blocks and technical terms.",- "Break down complex concepts into digestible parts.",- "Maintain a helpful and encouraging tone.",- ]- )-- # Use in agent configuration- agent = BaseAgent(- config=BaseAgentConfig(- client=client,- model="gpt-4o-mini",- memory=memory,- system_prompt_generator=generator- )- )--Basic Usage Patterns---------------------Creating an Agent-^^^^^^^^^^^^^^^--.. code-block:: python-- import os- import instructor- import openai- from rich.console import Console- from rich.panel import Panel- from atomic_agents.agents.base_agent import BaseAgent, BaseAgentConfig-- # Initialize console for pretty outputs- console = Console()-- # API Key setup- API_KEY = os.getenv("OPENAI_API_KEY")- if not API_KEY:- raise ValueError(- "API key is not set. Please set the API key as a static variable "- "or in the environment variable OPENAI_API_KEY."- )-- # OpenAI client setup- client = instructor.from_openai(openai.OpenAI(api_key=API_KEY))-- # Create agent with custom configuration- agent = BaseAgent(- config=BaseAgentConfig(- client=client,- model="gpt-4o-mini",- memory=memory,- system_prompt_generator=generator- )- )-- # Display the system prompt- default_system_prompt = agent.system_prompt_generator.generate_prompt()- console.print(Panel(default_system_prompt, width=console.width, style="bold cyan"))--Running Commands-^^^^^^^^^^^^^--.. code-block:: python-- from atomic_agents.agents.base_agent import BaseAgentInputSchema- from rich.text import Text- from rich.live import Live-- # Simple command- input_schema = BaseAgentInputSchema(chat_message="What is the weather?")- response = agent.run(input_schema)- console.print(Text("Agent:", style="bold green"), end=" ")- console.print(Text(response.chat_message, style="green"))-- # Streaming response- async def process_stream():- with Live("", refresh_per_second=10, auto_refresh=True) as live:- current_response = ""- async for partial_response in agent.run_async(input_schema):- if hasattr(partial_response, "chat_message") and partial_response.chat_message:- if partial_response.chat_message != current_response:- current_response = partial_response.chat_message- display_text = Text.assemble(- ("Agent: ", "bold green"),- (current_response, "green")- )- live.update(display_text)-- # Run with asyncio- import asyncio- asyncio.run(process_stream())--Next Steps------------After understanding these basic concepts, you can:--1. Explore :doc:`advanced usage patterns <advanced_usage>`-2. Check out the :doc:`API Reference </api/index>` for detailed documentation-3. Try building your own custom agentsdiff --git a/docs/guides/index.rst b/docs/guides/index.mdsimilarity index 62%rename from docs/guides/index.rstrename to docs/guides/index.mdindex 00ae55c..a4cb55c 100644--- a/docs/guides/index.rst+++ b/docs/guides/index.md@@ -1,26 +1,22 @@-User Guide-==========+# User GuideThis section contains detailed guides for working with Atomic Agents.-.. toctree::- :maxdepth: 2- :caption: Guide Sections+```{toctree}+:maxdepth: 2+:caption: Guides- basic_concepts- advanced_usage+quickstart+basic_concepts+tools+advanced_usage+```-.. note::- Use the sidebar to navigate between different sections of the guides.- You can return to the main documentation using the navigation menu on the left.--Implementation Patterns----------------------+## Implementation PatternsThe framework supports various implementation patterns and use cases:-Chatbots and Assistants-^^^^^^^^^^^^^^^^^^^^^^+### Chatbots and Assistants- Basic chat interfaces with any LLM provider- Streaming responses@@ -29,8 +25,7 @@ Chatbots and Assistants- Memory management and context retention- Multi-turn conversations-RAG Systems-^^^^^^^^^^+### RAG Systems- Query generation and optimization- Context-aware responses@@ -39,8 +34,7 @@ RAG Systems- Custom embedding and retrieval strategies- Hybrid search approaches-Specialized Agents-^^^^^^^^^^^^^^^^+### Specialized Agents- YouTube video summarization and analysis- Web search and deep research@@ -49,80 +43,70 @@ Specialized Agents- Custom tool integration- Task orchestration-Provider Integration Guide-------------------------+## Provider Integration GuideAtomic Agents is designed to be provider-agnostic. Here's how to work with different providers:-Provider Selection-^^^^^^^^^^^^^^^+### Provider Selection- Choose any provider supported by Instructor- Configure provider-specific settings- Handle rate limits and quotas- Implement fallback strategies-Local Development-^^^^^^^^^^^^^^^+### Local Development- Use Ollama for local testing- Mock responses for development- Debug provider interactions- Test provider switching-Production Deployment-^^^^^^^^^^^^^^^^^^+### Production Deployment- Load balancing between providers- Failover configurations- Cost optimization strategies- Performance monitoring-Custom Provider Integration-^^^^^^^^^^^^^^^^^^^^^^^^+### Custom Provider Integration- Extend Instructor for new providers- Implement custom client wrappers- Add provider-specific features- Handle unique response formats-Best Practices-------------+## Best Practices-Error Handling-^^^^^^^^^^^^+### Error Handling- Implement proper exception handling- Add retry mechanisms- Log provider errors- Handle rate limits gracefully-Performance Optimization-^^^^^^^^^^^^^^^^^^^^^+### Performance Optimization- Use streaming for long responses- Implement caching strategies- Optimize prompt lengths- Batch operations when possible-Security-^^^^^^^+### Security- Secure API key management- Input validation and sanitization- Output filtering- Rate limiting and quotas-Getting Help------------+## Getting HelpIf you need help, you can:-1. Check our `GitHub Issues <https://github.com/BrainBlend-AI/atomic-agents/issues>`_-2. Join our `Reddit community <https://www.reddit.com/r/AtomicAgents/>`_+1. Check our [GitHub Issues](https://github.com/BrainBlend-AI/atomic-agents/issues)+2. Join our [Reddit community](https://www.reddit.com/r/AtomicAgents/)3. Read through our examples in the repository-4. Review the example projects in ``atomic-examples/``+4. Review the example projects in `atomic-examples/`-.. seealso::- - :doc:`/api/index` - Browse the API reference- - :doc:`/index` - Return to main documentation+**See also**:+- [API Reference](/api/index) - Browse the API reference+- [Main Documentation](/index) - Return to main documentationdiff --git a/docs/guides/quickstart.md b/docs/guides/quickstart.mdnew file mode 100644index 0000000..4e43e8d--- /dev/null+++ b/docs/guides/quickstart.md@@ -0,0 +1,160 @@+# Quickstart Guide++This guide will help you get started with Atomic Agents quickly through practical examples.++## Installation++1. Clone the Atomic Agents repository:++ ```bash+ git clone https://github.com/BrainBlend-AI/atomic-agents+ ```++2. Install dependencies using Poetry:++ ```bash+ cd atomic-agents+ poetry install+ ```++## Basic Examples++### 1. Basic Chatbot++This example demonstrates a simple chatbot using the Atomic Agents framework:++```python+import os+import instructor+from openai import OpenAI+from atomic_agents.agents.base_agent import BaseAgent, BaseAgentConfig++# Initialize OpenAI client+client = instructor.from_openai(OpenAI())++# Create basic configuration+config = BaseAgentConfig(+ client=client,+ model="gpt-4o-mini"+)++# Initialize agent+agent = BaseAgent(config)++# Start chat loop+while True:+ user_input = input("You: ")+ if user_input.lower() == "exit":+ break++ response = agent.run({"chat_message": user_input})+ print(f"Assistant: {response.chat_message}")+```++### 2. Custom Chatbot++This example shows how to create a custom chatbot with a specific personality:++```python+from atomic_agents.lib.components.system_prompt_generator import SystemPromptGenerator++# Create custom system prompt+generator = SystemPromptGenerator(+ background=[+ "You are a friendly assistant that always responds in rhyming verse.",+ "You maintain a playful and poetic tone while being helpful.",+ ],+ steps=[+ "1. Understand the user's question or request",+ "2. Formulate your response in rhyming verse",+ "3. Ensure the response is both helpful and entertaining"+ ],+ output_instructions=[+ "Always respond in rhyming verse",+ "Keep responses concise but informative",+ "Maintain a playful tone"+ ]+)++# Create agent with custom configuration+agent = BaseAgent(+ config=BaseAgentConfig(+ client=client,+ model="gpt-4o-mini",+ system_prompt_generator=generator+ )+)+```++### 3. Custom Schema++This example demonstrates using a custom output schema:++```python+from pydantic import BaseModel+from typing import List++class CustomResponseSchema(BaseModel):+ chat_message: str+ follow_up_questions: List[str]++# Create agent with custom schema+agent = BaseAgent(+ config=BaseAgentConfig(+ client=client,+ model="gpt-4o-mini",+ output_schema=CustomResponseSchema+ )+)+```++### 4. Multiple Providers++This example shows how to use different AI providers:++```python+# OpenAI+openai_client = instructor.from_openai(OpenAI())++# Groq+from groq import Groq+groq_client = instructor.from_openai(Groq())++# Ollama (for local development)+from atomic_agents.lib.providers.ollama import OllamaClient+ollama_client = instructor.from_openai(OllamaClient())++# Use any provider+agent = BaseAgent(+ config=BaseAgentConfig(+ client=openai_client, # or groq_client, or ollama_client+ model="gpt-4o-mini" # adjust model name based on provider+ )+)+```++## Running the Examples++To run any of these examples:++1. Save the code in a Python file (e.g., `chatbot.py`)+2. Set your API key as an environment variable:++ ```bash+ export OPENAI_API_KEY="your-api-key"+ ```++3. Run the script:++ ```bash+ poetry run python chatbot.py+ ```++## Next Steps++After trying these examples, you can:++1. Explore [basic concepts](basic_concepts) for deeper understanding+2. Learn about [tools and their integration](tools.md)+3. Check out [advanced usage patterns](advanced_usage)+4. Review the [API reference](../api/index) for detailed documentationdiff --git a/docs/guides/tools.md b/docs/guides/tools.mdnew file mode 100644index 0000000..cc933df--- /dev/null+++ b/docs/guides/tools.md@@ -0,0 +1,225 @@+# Tools Guide++Atomic Agents provides a collection of tools through the Atomic Forge that extend agent capabilities.++## Installing Tools++Tools are managed using the Atomic Assembler CLI:++```bash+# Install a specific tool+atomic-assembler install calculator++# List available tools+atomic-assembler list++# Update installed tools+atomic-assembler update+```++## Available Tools++### Calculator++A tool for performing mathematical calculations:++```python+from atomic_agents.agents.base_agent import BaseAgent, BaseAgentConfig++agent = BaseAgent(+ config=BaseAgentConfig(+ client=client,+ model="gpt-4o-mini",+ tools=["calculator"]+ )+)++# The agent can now perform calculations+response = agent.run({+ "chat_message": "What is the square root of 144 plus 50?"+})+```++### SearxNG Search++A privacy-focused web search tool:++```python+# Configure with your SearxNG instance+agent = BaseAgent(+ config=BaseAgentConfig(+ client=client,+ model="gpt-4o-mini",+ tools=["searxng_search"],+ tool_configs={+ "searxng_search": {+ "instance_url": "https://your-searxng-instance.com"+ }+ }+ )+)+```++### Tavily Search++An AI-optimized search engine:++```python+import os++# Set your Tavily API key+os.environ["TAVILY_API_KEY"] = "your-api-key"++agent = BaseAgent(+ config=BaseAgentConfig(+ client=client,+ model="gpt-4o-mini",+ tools=["tavily_search"]+ )+)+```++### YouTube Transcript Scraper++Extract transcripts from YouTube videos:++```python+import os++# Set your YouTube API key+os.environ["YOUTUBE_API_KEY"] = "your-api-key"++agent = BaseAgent(+ config=BaseAgentConfig(+ client=client,+ model="gpt-4o-mini",+ tools=["youtube_transcript"]+ )+)++# The agent can now analyze YouTube videos+response = agent.run({+ "chat_message": "Summarize this video: https://youtube.com/watch?v=..."+})+```++### Webpage Scraper++Extract content from web pages:++```python+agent = BaseAgent(+ config=BaseAgentConfig(+ client=client,+ model="gpt-4o-mini",+ tools=["webpage_scraper"]+ )+)++# The agent can now analyze web pages+response = agent.run({+ "chat_message": "What are the main points from this article: https://..."+})+```++## Creating Custom Tools++You can create your own tools by following these steps:++### 1. Create Tool Structure++Create a new directory with the required files:++```+my_tool/+├── __init__.py+├── README.md+├── pyproject.toml+└── my_tool/+ ├── __init__.py+ └── tool.py+```++### 2. Implement Tool Logic++Create your tool implementation:++```python+from pydantic import BaseModel+from atomic_agents.lib.tools import BaseTool++class MyToolInputs(BaseModel):+ param1: str+ param2: int++class MyToolOutputs(BaseModel):+ result: str++class MyTool(BaseTool):+ name = "my_tool"+ description = "Description of what my tool does"+ inputs_schema = MyToolInputs+ outputs_schema = MyToolOutputs++ def run(self, inputs: MyToolInputs) -> MyToolOutputs:+ # Implement your tool logic here+ result = f"Processed {inputs.param1} {inputs.param2} times"+ return MyToolOutputs(result=result)+```++### 3. Configure Package++Create a pyproject.toml:++```toml+[tool.poetry]+name = "my-tool"+version = "0.1.0"+description = "My custom tool for Atomic Agents"+authors = ["Your Name <[email protected]>"]++[tool.poetry.dependencies]+python = "^3.11"+atomic-agents = "^0.1.0"+```++### 4. Document Usage++Create a README.md with:++* Installation instructions+* Configuration requirements+* Usage examples+* Any environment variables needed++## Best Practices++### 1. Error Handling++* Implement proper error handling in tools+* Return meaningful error messages+* Handle rate limits and retries++### 2. Configuration++* Use environment variables for sensitive data+* Make configuration flexible but with sensible defaults+* Document all configuration options++### 3. Testing++* Write unit tests for your tools+* Include integration tests if applicable+* Test error cases and edge conditions++### 4. Documentation++* Keep README up to date+* Include example code+* Document any breaking changes++## Next Steps++* Check out the [example projects](../examples/index.md)+* Learn about [advanced usage patterns](advanced_usage.md)+* Contribute your own tools to the [Atomic Forge](../contributing.md)diff --git a/docs/index.md b/docs/index.mdnew file mode 100644index 0000000..e4c34bc--- /dev/null+++ b/docs/index.md@@ -0,0 +1,121 @@+# Welcome to Atomic Agents Documentation++```{toctree}+:maxdepth: 2+:caption: Documentation++guides/index+api/index+examples/index+contributing+```++# A Lightweight and Modular Framework for Building AI Agents++++The Atomic Agents framework is designed around the concept of atomicity to be an extremely lightweight and modular framework for building Agentic AI pipelines and applications without sacrificing developer experience and maintainability. The framework provides a set of tools and agents that can be combined to create powerful applications. It is built on top of [Instructor](https://github.com/jxnl/instructor) and leverages the power of [Pydantic](https://docs.pydantic.dev/latest/) for data and schema validation and serialization.++All logic and control flows are written in Python, enabling developers to apply familiar best practices and workflows from traditional software development without compromising flexibility or clarity.++## Key Features++- **Modularity**: Build AI applications by combining small, reusable components+- **Predictability**: Define clear input and output schemas using Pydantic+- **Extensibility**: Easily swap out components or integrate new ones+- **Control**: Fine-tune each part of the system individually+- **Provider Agnostic**: Works with various LLM providers through Instructor+- **Built for Production**: Robust error handling and async support++## Installation++You can install Atomic Agents using pip:++```bash+pip install atomic-agents+```++Or using Poetry (recommended):++```bash+poetry add atomic-agents+```++Make sure you also install the provider you want to use. For example, to use OpenAI and Groq:++```bash+pip install openai groq+```++This also installs the CLI *Atomic Assembler*, which can be used to download Tools (and soon also Agents and Pipelines).++```{note}+The framework supports multiple providers through Instructor, including **OpenAI**, **Anthropic**, **Groq**, **Ollama** (local models), **Gemini**, and more!+For a full list of all supported providers and their setup instructions, have a look at the [Instructor Integrations documentation](https://python.useinstructor.com/integrations/).+```++## Quick Example++Here's a glimpse of how easy it is to create an agent:++```python+import instructor+import openai+from atomic_agents.lib.components.agent_memory import AgentMemory+from atomic_agents.agents.base_agent import BaseAgent, BaseAgentConfig, BaseAgentInputSchema+++# Set up your API key (either in environment or pass directly)+# os.environ["OPENAI_API_KEY"] = "your-api-key"+# or pass it to the client: openai.OpenAI(api_key="your-api-key")++# Initialize agent with memory+memory = AgentMemory()++# Set up client with your preferred provider+client = instructor.from_openai(openai.OpenAI()) # Pass your API key here if not in environment++# Create an agent+agent = BaseAgent(+ config=BaseAgentConfig(+ client=client,+ model="gpt-4o-mini", # Use your provider's model+ memory=memory+ )+)++# Interact with your agent (using the agent's input schema)+response = agent.run(agent.input_schema(chat_message="Tell me about quantum computing"))++# Or more explicitly:+response = agent.run(+ BaseAgentInputSchema(chat_message="Tell me about quantum computing")+)++print(response)+```++## Example Projects++Check out our example projects in our [GitHub repository](https://github.com/BrainBlend-AI/atomic-agents/tree/main/atomic-examples):++- [Quickstart Examples](https://github.com/BrainBlend-AI/atomic-agents/tree/main/atomic-examples/quickstart): Simple examples to get started+- [Basic Multimodal](https://github.com/BrainBlend-AI/atomic-agents/tree/main/atomic-examples/basic-multimodal): Analyze images with text+- [RAG Chatbot](https://github.com/BrainBlend-AI/atomic-agents/tree/main/atomic-examples/rag-chatbot): Build context-aware chatbots+- [Web Search Agent](https://github.com/BrainBlend-AI/atomic-agents/tree/main/atomic-examples/web-search-agent): Create agents that perform web searches+- [Deep Research](https://github.com/BrainBlend-AI/atomic-agents/tree/main/atomic-examples/deep-research): Perform deep research tasks+- [YouTube Summarizer](https://github.com/BrainBlend-AI/atomic-agents/tree/main/atomic-examples/youtube-summarizer): Extract knowledge from videos+- [YouTube to Recipe](https://github.com/BrainBlend-AI/atomic-agents/tree/main/atomic-examples/youtube-to-recipe): Convert cooking videos into structured recipes+- [Orchestration Agent](https://github.com/BrainBlend-AI/atomic-agents/tree/main/atomic-examples/orchestration-agent): Coordinate multiple agents for complex tasks++## Community & Support++- [GitHub Repository](https://github.com/BrainBlend-AI/atomic-agents)+- [Issue Tracker](https://github.com/BrainBlend-AI/atomic-agents/issues)+- [Reddit Community](https://www.reddit.com/r/AtomicAgents/)++## Indices and References++* {ref}`genindex`+* {ref}`modindex`+* {ref}`search`diff --git a/docs/index.rst b/docs/index.rstdeleted file mode 100644index 282c83a..0000000--- a/docs/index.rst+++ /dev/null@@ -1,128 +0,0 @@-Welcome to Atomic Agents Documentation-======================================--.. toctree::- :maxdepth: 2- :caption: Documentation-- self- User Guide <guides/index>- API Reference <api/index>--A Lightweight and Modular Framework for Building AI Agents-==========================================================--.. image:: _static/logo.png- :width: 350- :alt: Atomic Agents--The Atomic Agents framework is designed around the concept of atomicity to be an extremely lightweight and modular framework for building Agentic AI pipelines and applications without sacrificing developer experience and maintainability. The framework provides a set of tools and agents that can be combined to create powerful applications. It is built on top of `Instructor <https://github.com/jxnl/instructor>`_ and leverages the power of `Pydantic <https://docs.pydantic.dev/latest/>`_ for data and schema validation and serialization.--All logic and control flows are written in Python, enabling developers to apply familiar best practices and workflows from traditional software development without compromising flexibility or clarity.--Key Features---------------- **Modularity**: Build AI applications by combining small, reusable components-- **Predictability**: Define clear input and output schemas using Pydantic-- **Extensibility**: Easily swap out components or integrate new ones-- **Control**: Fine-tune each part of the system individually-- **Provider Agnostic**: Works with various LLM providers through Instructor-- **Built for Production**: Robust error handling and async support--Installation---------------You can install Atomic Agents using pip:--.. code-block:: bash-- pip install atomic-agents--Or using Poetry (recommended):--.. code-block:: bash-- poetry add atomic-agents--Make sure you also install the provider you want to use. For example, to use OpenAI and Groq:--.. code-block:: bash-- pip install openai groq--This also installs the CLI *Atomic Assembler*, which can be used to download Tools (and soon also Agents and Pipelines).--.. note::- The framework supports multiple providers through Instructor, including **OpenAI**, **Anthropic**, **Groq**, **Ollama** (local models), **Gemini**, and more!- For a full list of all supported providers and their setup instructions, have a look at the `Instructor Integrations documentation <https://python.useinstructor.com/integrations/>`_.--Quick Example----------------Here's a glimpse of how easy it is to create an agent:--.. code-block:: python-- import instructor- import openai- from atomic_agents.lib.components.agent_memory import AgentMemory- from atomic_agents.agents.base_agent import BaseAgent, BaseAgentConfig, BaseAgentInputSchema--- # Set up your API key (either in environment or pass directly)- # os.environ["OPENAI_API_KEY"] = "your-api-key"- # or pass it to the client: openai.OpenAI(api_key="your-api-key")-- # Initialize agent with memory- memory = AgentMemory()-- # Set up client with your preferred provider- client = instructor.from_openai(openai.OpenAI()) # Pass your API key here if not in environment-- # Create an agent- agent = BaseAgent(- config=BaseAgentConfig(- client=client,- model="gpt-4o-mini", # Use your provider's model- memory=memory- )- )-- # Interact with your agent (using the agent's input schema)- response = agent.run(agent.input_schema(chat_message="Tell me about quantum computing"))-- # Or more explicitly:- response = agent.run(- BaseAgentInputSchema(chat_message="Tell me about quantum computing")- )-- print(response)--Example Projects------------------Check out our example projects in our `GitHub repository <https://github.com/BrainBlend-AI/atomic-agents/tree/main/atomic-examples>`_:--- `Quickstart Examples <https://github.com/BrainBlend-AI/atomic-agents/tree/main/atomic-examples/quickstart>`_: Simple examples to get started-- `Basic Multimodal <https://github.com/BrainBlend-AI/atomic-agents/tree/main/atomic-examples/basic-multimodal>`_: Analyze images with text-- `RAG Chatbot <https://github.com/BrainBlend-AI/atomic-agents/tree/main/atomic-examples/rag-chatbot>`_: Build context-aware chatbots-- `Web Search Agent <https://github.com/BrainBlend-AI/atomic-agents/tree/main/atomic-examples/web-search-agent>`_: Create agents that perform web searches-- `Deep Research <https://github.com/BrainBlend-AI/atomic-agents/tree/main/atomic-examples/deep-research>`_: Perform deep research tasks-- `YouTube Summarizer <https://github.com/BrainBlend-AI/atomic-agents/tree/main/atomic-examples/youtube-summarizer>`_: Extract knowledge from videos-- `YouTube to Recipe <https://github.com/BrainBlend-AI/atomic-agents/tree/main/atomic-examples/youtube-to-recipe>`_: Convert cooking videos into structured recipes-- `Orchestration Agent <https://github.com/BrainBlend-AI/atomic-agents/tree/main/atomic-examples/orchestration-agent>`_: Coordinate multiple agents for complex tasks--Community & Support----------------------- `GitHub Repository <https://github.com/BrainBlend-AI/atomic-agents>`_-- `Issue Tracker <https://github.com/BrainBlend-AI/atomic-agents/issues>`_-- `Reddit Community <https://www.reddit.com/r/AtomicAgents/>`_--Indices and References-======================--* :ref:`genindex`-* :ref:`modindex`-* :ref:`search`