buddy-ai 1.0.6
A comprehensive Python framework for building and deploying AI agents with multi-model support and advanced capabilities
Requires Python: >=3.10
Keywords: ai, agents, llm, chatbot, artificial-intelligence, machine-learning, nlp, openai, anthropic, rag, multi-agent, workflow, automation, ai-framework, conversational-ai, intelligent-agents, ai-assistant

# 🤖 Buddy AI - Comprehensive Documentation

## Table of Contents

1. [Getting Started](#getting-started)
2. [Agent System](#agent-system)  
3. [Model Providers](#model-providers)
4. [Tools System](#tools-system)
5. [Memory & Knowledge](#memory--knowledge)
6. [Team Collaboration](#team-collaboration)
7. [Workflows](#workflows)
8. [Training System](#training-system)
9. [CLI Interface](#cli-interface)
10. [Deployment Options](#deployment-options)
11. [API Reference](#api-reference)

---

## Getting Started

### Installation

Install Buddy AI from PyPI:

```bash
pip install buddy-ai
```

### Quick Start - Your First Agent

```python
from buddy import Agent
from buddy.models.openai import OpenAIChat

# Create an agent with OpenAI
agent = Agent(
    name="MyBot",
    model=OpenAIChat(),
    instructions="You are a helpful assistant."
)

# Basic conversation
response = agent.run("Hello! What can you do?")
print(response.content)

# Follow-up conversation (memory preserved)  
response = agent.run("What did I just ask you?")
print(response.content)
```

### Environment Setup

Set up your API keys in environment variables:

```bash
# OpenAI
export OPENAI_API_KEY="your-key-here"

# Anthropic
export ANTHROPIC_API_KEY="your-key-here"

# Google
export GOOGLE_API_KEY="your-key-here"

# Azure OpenAI
export AZURE_OPENAI_API_KEY="your-key-here"
export AZURE_OPENAI_ENDPOINT="your-endpoint"

# AWS Bedrock
export AWS_ACCESS_KEY_ID="your-key"
export AWS_SECRET_ACCESS_KEY="your-secret"
export AWS_DEFAULT_REGION="us-east-1"
```

### Installation with Optional Dependencies

```bash
# Install with all providers
pip install buddy-ai[all]

# Install specific providers
pip install buddy-ai[openai,anthropic]
pip install buddy-ai[google,aws]
pip install buddy-ai[azure,cohere]

# Install for development
pip install buddy-ai[dev]
```

### CLI Quick Start

```bash
# Initialize a workspace
buddy init my-agent-project

# Create an agent interactively  
buddy agent create

# Chat with your agent
buddy chat --agent my-bot

# Train a custom model
buddy train /path/to/data --name my-model
```

---

## Agent System

The **Agent** class is the core of Buddy AI. It represents an intelligent AI agent with memory, tools, knowledge, and conversation capabilities.

### Basic Agent Creation

```python
from buddy import Agent
from buddy.models.openai import OpenAIChat

# Minimal agent
agent = Agent(
    model=OpenAIChat(),
    instructions="You are a helpful assistant"
)

# Detailed agent configuration
agent = Agent(
    name="DataAnalyst", 
    model=OpenAIChat(model="gpt-4"),
    description="An expert data analyst and visualization specialist",
    instructions=[
        "Analyze data thoroughly and provide insights",
        "Create visualizations when helpful",
        "Explain technical concepts clearly"
    ],
    markdown=True,  # Format output as markdown
    debug_mode=True  # Enable detailed logging
)
```

### Agent Configuration Options

#### Basic Settings
```python
agent = Agent(
    name="MyAgent",           # Agent name
    agent_id="unique-id",     # Optional unique identifier
    model=OpenAIChat(),       # Language model to use
    description="Brief description of the agent",
    introduction="Hi! I'm your assistant.",  # Intro message
    user_id="user123",        # Default user ID
    session_id="session123"   # Default session ID
)
```

#### Instructions & Behavior
```python
agent = Agent(
    instructions="You are a helpful assistant",  # String
    instructions=[  # List of instructions
        "Be helpful and informative",
        "Ask clarifying questions when needed",
        "Provide examples in your explanations"
    ],
    instructions=lambda: f"Today is {datetime.now()}",  # Dynamic function
    
    goal="Help users with their questions",
    expected_output="Clear, helpful responses",
    additional_context="Company: Acme Corp",
    
    markdown=True,  # Format responses in markdown
    add_datetime_to_instructions=True,  # Include current time
    add_location_to_instructions=True   # Include location context
)
```

#### Memory Configuration
```python
from buddy.memory.agent import AgentMemory

agent = Agent(
    memory=AgentMemory(),  # Enable conversation memory
    add_history_to_messages=True,  # Include chat history in context
    num_history_runs=5,  # Number of previous conversations to include
    
    # Advanced memory features
    enable_agentic_memory=True,  # Let agent manage its own memories
    enable_user_memories=True,   # Store user-specific information
    enable_session_summaries=True,  # Create session summaries
    cache_session=True           # Cache session in memory for faster access
)
```

### Running Agents

#### Basic Conversation
```python
# Single message
response = agent.run("What's the weather like?")
print(response.content)

# Streaming response
for chunk in agent.run("Tell me a story", stream=True):
    print(chunk.content, end="", flush=True)

# Async execution  
async def chat():
    response = await agent.arun("Hello!")
    print(response.content)
```

#### Advanced Run Options
```python
# Run with additional context
response = agent.run(
    "Analyze this data",
    context={"dataset": "sales_data.csv", "year": 2024}
)

# Run with specific session
response = agent.run(
    "Continue our conversation",
    session_id="important-session"
)

# Run with retries and error handling
response = agent.run(
    "Complex task",
    retries=3,
    delay_between_retries=2,
    exponential_backoff=True
)
```

### Agent Response Objects

```python
response = agent.run("Hello!")

# Response properties
print(response.content)          # Main response text
print(response.role)             # Response role (assistant)
print(response.model)            # Model used
print(response.metrics)          # Performance metrics
print(response.session_id)       # Session identifier
print(response.citations)        # Knowledge citations if any
print(response.references)       # Reference materials

# Tool calls (if any)
if response.tool_calls:
    for tool_call in response.tool_calls:
        print(f"Tool: {tool_call.function_name}")
        print(f"Args: {tool_call.function_args}")

# Events (streaming responses)
if hasattr(response, 'events'):
    for event in response.events:
        print(f"Event: {event.type} - {event.data}")
```

### Agent with Custom Context

```python
# Static context
agent = Agent(
    context={
        "company": "Acme Corp",
        "department": "Engineering", 
        "year": 2024
    },
    add_context=True  # Include context in prompts
)

# Dynamic context with functions
def get_current_user():
    return {"name": "John", "role": "Developer"}

agent = Agent(
    context={"user": get_current_user},
    resolve_context=True  # Execute functions in context
)

# Context in run calls
response = agent.run(
    "Create a report",
    context={"format": "PDF", "deadline": "tomorrow"}
)
```

### System Messages

```python
# String system message
agent = Agent(
    system_message="You are a senior software engineer with 10+ years experience"
)

# Dynamic system message
def create_system_message():
    return f"Current time: {datetime.now()}, be helpful!"

agent = Agent(system_message=create_system_message)

# Disable default system message creation
agent = Agent(
    system_message="Custom message only",
    create_default_system_message=False
)
```

### Error Handling & Debugging

```python
# Enable debug mode
agent = Agent(
    debug_mode=True,
    debug_level=2  # 1 = basic, 2 = detailed
)

# Error handling in runs
try:
    response = agent.run("Complex request")
except Exception as e:
    print(f"Agent run failed: {e}")

# Monitoring and telemetry
agent = Agent(
    monitoring=True,  # Log to buddy.com for monitoring
    telemetry=True    # Anonymous usage analytics
)
```

---

## Model Providers

Buddy AI supports 25+ LLM providers with consistent APIs. Choose the best model for your needs while maintaining the same code interface.

### OpenAI Models

```python
from buddy.models.openai import OpenAIChat

# GPT-4 models
model = OpenAIChat(id="gpt-4o")              # GPT-4 Omni
model = OpenAIChat(id="gpt-4o-mini")         # Faster, cheaper
model = OpenAIChat(id="gpt-4-turbo")         # Legacy GPT-4

# GPT-3.5 models  
model = OpenAIChat(id="gpt-3.5-turbo")       # Fast and affordable

# Specialized models
model = OpenAIChat(id="o1-preview")          # Reasoning model
model = OpenAIChat(id="o1-mini")             # Faster reasoning

# With custom parameters
model = OpenAIChat(
    id="gpt-4o",
    temperature=0.7,
    max_tokens=1000,
    frequency_penalty=0.5,
    presence_penalty=0.3,
    top_p=0.9
)

agent = Agent(model=model, instructions="You are an expert coder")
```

### Anthropic Claude

```python
from buddy.models.anthropic import Claude

# Claude 3.5 models
model = Claude(id="claude-3-5-sonnet-20241022")   # Most capable
model = Claude(id="claude-3-5-haiku-20241022")    # Fast and affordable

# Claude 3 models
model = Claude(id="claude-3-opus-20240229")       # Most capable 3.0
model = Claude(id="claude-3-sonnet-20240229")     # Balanced
model = Claude(id="claude-3-haiku-20240307")      # Fast

# With configuration
model = Claude(
    id="claude-3-5-sonnet-20241022",
    temperature=0.3,
    max_tokens=4096,
    top_p=0.9
)

agent = Agent(model=model, instructions="You are Claude, a helpful assistant")
```

### Google Gemini

```python
from buddy.models.google import Gemini

# Gemini models
model = Gemini(id="gemini-1.5-pro")          # Most capable
model = Gemini(id="gemini-1.5-flash")        # Fast and efficient
model = Gemini(id="gemini-1.0-pro")          # Original Gemini

# With safety settings
model = Gemini(
    id="gemini-1.5-pro",
    temperature=0.4,
    top_p=0.8,
    top_k=40,
    safety_settings={
        "HARM_CATEGORY_HARASSMENT": "BLOCK_MEDIUM_AND_ABOVE",
        "HARM_CATEGORY_HATE_SPEECH": "BLOCK_MEDIUM_AND_ABOVE"
    }
)

agent = Agent(model=model, instructions="You are Gemini, Google's AI assistant")
```

### AWS Bedrock

```python
from buddy.models.aws import AWSBedrock

# Amazon Titan
model = AWSBedrock(id="amazon.titan-text-express-v1")

# Anthropic Claude on Bedrock
model = AWSBedrock(id="anthropic.claude-3-5-sonnet-20241022-v2:0")

# Meta Llama on Bedrock  
model = AWSBedrock(id="meta.llama3-2-90b-instruct-v1:0")

# With AWS configuration
model = AWSBedrock(
    id="anthropic.claude-3-5-sonnet-20241022-v2:0",
    region_name="us-west-2",
    aws_access_key_id="your-key",
    aws_secret_access_key="your-secret"
)

agent = Agent(model=model, instructions="You are powered by AWS Bedrock")
```

### Azure OpenAI

```python
from buddy.models.azure import AzureOpenAIChat

model = AzureOpenAIChat(
    deployment_name="gpt-4o",
    azure_endpoint="https://your-resource.openai.azure.com/",
    api_version="2024-02-15-preview"
)

# With Azure AD authentication
model = AzureOpenAIChat(
    deployment_name="gpt-4o",  
    azure_endpoint="https://your-resource.openai.azure.com/",
    api_version="2024-02-15-preview",
    azure_ad_token="your-token"
)

agent = Agent(model=model, instructions="You are powered by Azure OpenAI")
```

### Ollama (Local Models)

```python
from buddy.models.ollama import OllamaChat

# Run local models
model = OllamaChat(id="llama3.2")            # Meta Llama 3.2
model = OllamaChat(id="mistral")             # Mistral 7B
model = OllamaChat(id="codellama")           # Code Llama
model = OllamaChat(id="phi3")                # Microsoft Phi-3

# With custom Ollama server
model = OllamaChat(
    id="llama3.2",
    host="http://localhost:11434",
    timeout=30
)

agent = Agent(model=model, instructions="You are running locally via Ollama")
```

### Additional Providers

```python
# Cohere
from buddy.models.cohere import CohereChat
model = CohereChat(id="command-r-plus")

# Groq (Fast inference)
from buddy.models.groq import GroqChat  
model = GroqChat(id="mixtral-8x7b-32768")

# Mistral AI
from buddy.models.mistral import MistralChat
model = MistralChat(id="mistral-large-2407")

# Perplexity
from buddy.models.perplexity import PerplexityChat
model = PerplexityChat(id="llama-3.1-sonar-huge-128k-online")

# Together AI
from buddy.models.together import TogetherChat
model = TogetherChat(id="meta-llama/Llama-3-70b-chat-hf")

# Fireworks AI
from buddy.models.fireworks import FireworksChat
model = FireworksChat(id="accounts/fireworks/models/llama-v3p1-405b-instruct")

# Hugging Face
from buddy.models.huggingface import HuggingFaceChat
model = HuggingFaceChat(id="microsoft/DialoGPT-large")

# xAI Grok
from buddy.models.xai import XAIChat
model = XAIChat(id="grok-beta")

# DeepSeek
from buddy.models.deepseek import DeepSeekChat
model = DeepSeekChat(id="deepseek-chat")
```

### Model Configuration Examples

#### Temperature Control
```python
# Creative writing (high temperature)
creative_model = OpenAIChat(id="gpt-4o", temperature=0.9)
creative_agent = Agent(model=creative_model, instructions="Write creative stories")

# Factual responses (low temperature)  
factual_model = OpenAIChat(id="gpt-4o", temperature=0.1)
factual_agent = Agent(model=factual_model, instructions="Provide accurate information")

# Balanced (medium temperature)
balanced_model = OpenAIChat(id="gpt-4o", temperature=0.5)
```

#### Token Limits
```python
# Short responses
short_model = OpenAIChat(id="gpt-4o", max_tokens=100)

# Long-form content
long_model = OpenAIChat(id="gpt-4o", max_tokens=4000)

# Streaming for long responses
streaming_agent = Agent(model=long_model, stream=True)
```

#### Cost Optimization
```python
# Use cheaper models for simple tasks
cheap_model = OpenAIChat(id="gpt-3.5-turbo")
simple_agent = Agent(model=cheap_model, instructions="Answer basic questions")

# Use powerful models for complex tasks
powerful_model = OpenAIChat(id="gpt-4o")  
complex_agent = Agent(model=powerful_model, instructions="Perform complex analysis")
```

### Multi-Model Agents

```python
# Primary model with fallback
primary_model = Claude(id="claude-3-5-sonnet-20241022")
fallback_model = OpenAIChat(id="gpt-4o")

agent = Agent(
    model=primary_model,
    instructions="Try Claude first, fallback to GPT-4 if needed"
)

# Reasoning model for complex problems
reasoning_model = OpenAIChat(id="o1-preview") 
regular_model = OpenAIChat(id="gpt-4o")

agent = Agent(
    model=regular_model,
    reasoning=True,
    reasoning_model=reasoning_model,
    instructions="Use reasoning for complex problems"
)
```

### Environment Variables

```bash
# OpenAI
export OPENAI_API_KEY="sk-..."

# Anthropic  
export ANTHROPIC_API_KEY="sk-ant-..."

# Google
export GOOGLE_API_KEY="AI..."

# Azure
export AZURE_OPENAI_API_KEY="..."
export AZURE_OPENAI_ENDPOINT="https://..."

# AWS
export AWS_ACCESS_KEY_ID="..."
export AWS_SECRET_ACCESS_KEY="..."
export AWS_DEFAULT_REGION="us-east-1"

# Cohere
export COHERE_API_KEY="..."

# Groq
export GROQ_API_KEY="gsk_..."

# Mistral
export MISTRAL_API_KEY="..."
```

---

## Tools System

Buddy AI provides a powerful tools ecosystem that enables agents to perform actions, access APIs, manipulate data, and interact with external services. Tools extend agent capabilities beyond text generation.

### Built-in Tool Categories

#### 🧮 **Calculation & Math**
```python
from buddy.tools.calculator import CalculatorTools

# Basic calculator
calc = CalculatorTools()
agent = Agent(
    model=OpenAIChat(),
    tools=[calc],
    instructions="You can perform mathematical calculations"
)

response = agent.run("What is 25 * 37 + 891?")
# Agent will use calculator tools automatically

# Advanced calculator with all functions
calc = CalculatorTools(
    enable_all=True,  # Includes factorial, prime checking, etc.
    exponentiate=True,
    square_root=True,
    factorial=True,
    is_prime=True
)
```

#### 🌐 **Web & API Tools**
```python
from buddy.tools.googlesearch import GoogleSearch
from buddy.tools.website import WebsiteTools
from buddy.tools.api import APITools

# Google search capability
search = GoogleSearch()
web = WebsiteTools()

agent = Agent(
    model=OpenAIChat(),
    tools=[search, web],
    instructions="You can search the web and read websites"
)

response = agent.run("Find the latest news about AI and summarize the top article")

# Generic API tool
api = APITools()
agent = Agent(
    model=OpenAIChat(),
    tools=[api],
    instructions="You can make HTTP requests to APIs"
)
```

#### 📧 **Communication Tools**
```python
from buddy.tools.email import EmailTools
from buddy.tools.slack import SlackTools
from buddy.tools.whatsapp import WhatsAppTools

# Email capabilities
email = EmailTools()
agent = Agent(
    model=OpenAIChat(),
    tools=[email],
    instructions="You can send and manage emails"
)

response = agent.run("Send an email to team@company.com about the project update")

# Slack integration
slack = SlackTools(bot_token="xoxb-your-token")
agent = Agent(
    model=OpenAIChat(), 
    tools=[slack],
    instructions="You can send Slack messages and manage channels"
)
```

#### 📊 **Data & Analytics Tools**
```python
from buddy.tools.pandas import PandasTools
from buddy.tools.csv_toolkit import CSVTools
from buddy.tools.sql import SQLTools

# Data analysis with pandas
pandas_tools = PandasTools()
agent = Agent(
    model=OpenAIChat(),
    tools=[pandas_tools],
    instructions="You are a data analyst with pandas capabilities"
)

response = agent.run("Load data.csv, clean it, and create a summary report")

# SQL database interactions
sql = SQLTools(connection_string="postgresql://user:pass@localhost/db")
agent = Agent(
    model=OpenAIChat(),
    tools=[sql], 
    instructions="You can query and analyze database data"
)
```

#### 🎨 **Creative & Media Tools**
```python
from buddy.tools.dalle import DalleTools
from buddy.tools.eleven_labs import ElevenLabsTools
from buddy.tools.visualization import VisualizationTools

# AI image generation
dalle = DalleTools()
agent = Agent(
    model=OpenAIChat(),
    tools=[dalle],
    instructions="You can create images with DALL-E"
)

response = agent.run("Create an image of a futuristic city at sunset")

# Text-to-speech
tts = ElevenLabsTools()
agent = Agent(
    model=OpenAIChat(),
    tools=[tts],
    instructions="You can generate audio from text"
)

# Data visualization
viz = VisualizationTools()
agent = Agent(
    model=OpenAIChat(),
    tools=[viz],
    instructions="You can create charts and graphs"
)
```

### Custom Function Tools

#### Simple Function Tool
```python
from buddy.tools import Function

def get_weather(city: str) -> str:
    """Get current weather for a city.
    
    Args:
        city: The name of the city
        
    Returns:
        Weather description
    """
    # Your weather API logic here
    return f"The weather in {city} is sunny, 72°F"

# Convert function to tool
weather_tool = Function.from_callable(get_weather)

agent = Agent(
    model=OpenAIChat(),
    tools=[weather_tool],
    instructions="You can check weather for any city"
)

response = agent.run("What's the weather in New York?")
```

#### Decorator-based Tools
```python
from buddy.tools import tool

@tool
def calculate_tip(bill_amount: float, tip_percentage: float = 15.0) -> dict:
    """Calculate tip and total amount.
    
    Args:
        bill_amount: The bill amount in dollars
        tip_percentage: Tip percentage (default 15%)
        
    Returns:
        Dictionary with tip and total amounts
    """
    tip = bill_amount * (tip_percentage / 100)
    total = bill_amount + tip
    
    return {
        "bill_amount": bill_amount,
        "tip_percentage": tip_percentage,
        "tip_amount": round(tip, 2),
        "total_amount": round(total, 2)
    }

agent = Agent(
    model=OpenAIChat(),
    tools=[calculate_tip],
    instructions="You can help calculate tips and totals"
)

response = agent.run("Calculate tip for a $85 dinner with 20% tip")
```

#### Class-based Tools
```python
from buddy.tools import Toolkit

class DatabaseTools(Toolkit):
    def __init__(self, connection_string: str):
        self.connection_string = connection_string
        super().__init__()
    
    def get_user_count(self) -> int:
        """Get total number of users in database."""
        # Database query logic
        return 1250
    
    def get_recent_orders(self, days: int = 7) -> list:
        """Get recent orders from the database.
        
        Args:
            days: Number of days to look back (default 7)
            
        Returns:
            List of recent orders
        """
        # Database query logic
        return [
            {"id": 1, "amount": 99.99, "date": "2024-01-01"},
            {"id": 2, "amount": 149.50, "date": "2024-01-02"}
        ]

db_tools = DatabaseTools("postgresql://localhost/mydb")
agent = Agent(
    model=OpenAIChat(),
    tools=[db_tools],
    instructions="You can query the database for user and order information"
)
```

### Tool Control & Configuration

#### Tool Selection
```python
# Control which tools are available
agent = Agent(
    model=OpenAIChat(),
    tools=[calc, search, email],
    tool_choice="auto",  # Let model choose which tools to use
    instructions="You have calculator, search, and email capabilities"
)

# Force specific tool usage
agent = Agent(
    model=OpenAIChat(),
    tools=[calc],
    tool_choice={"type": "function", "function": {"name": "add"}},  # Force calculator
    instructions="Always use the calculator"
)

# Disable tools
agent = Agent(
    model=OpenAIChat(),
    tools=[calc, search],
    tool_choice="none",  # No tools allowed, text only
    instructions="Answer without using any tools"
)
```

#### Tool Call Limits & Display
```python
agent = Agent(
    model=OpenAIChat(),
    tools=[calc, search, email],
    tool_call_limit=3,      # Maximum 3 tool calls per response
    show_tool_calls=True,   # Show tool calls in response
    instructions="Use tools efficiently within the limit"
)

# Hide tool calls from user
agent = Agent(
    model=OpenAIChat(),
    tools=[calc],
    show_tool_calls=False,  # Hide tool calls, show only results
    instructions="Use tools silently"
)
```

#### Tool Hooks & Middleware
```python
def tool_audit_hook(tool_call):
    """Log all tool calls for auditing."""
    print(f"Tool called: {tool_call.function_name}")
    print(f"Arguments: {tool_call.function_args}")
    return tool_call

def tool_security_hook(tool_call):
    """Security check before tool execution."""
    if "delete" in tool_call.function_name.lower():
        raise Exception("Delete operations not allowed")
    return tool_call

agent = Agent(
    model=OpenAIChat(),
    tools=[db_tools],
    tool_hooks=[tool_audit_hook, tool_security_hook],
    instructions="Database operations with security and auditing"
)
```

### File & System Tools

#### File Operations
```python
from buddy.tools.file import FileTools
from buddy.tools.local_file_system import LocalFileSystemTools

# Basic file tools
file_tools = FileTools()

# Advanced local file system
fs_tools = LocalFileSystemTools(
    base_directory="/path/to/work/directory",
    read_enabled=True,
    write_enabled=True,
    delete_enabled=False  # Safety: disable delete
)

agent = Agent(
    model=OpenAIChat(),
    tools=[fs_tools],
    instructions="You can read, write, and manage files in the work directory"
)

response = agent.run("Read the config.json file and update the database URL")
```

#### Shell & System Tools
```python
from buddy.tools.shell import ShellTools
from buddy.tools.python import PythonTools

# Safe shell access
shell = ShellTools(
    allowed_commands=["ls", "pwd", "cat", "grep"],  # Whitelist commands
    working_directory="/safe/path"
)

# Python code execution
python_tools = PythonTools(
    timeout=30,  # 30 second timeout
    allowed_imports=["pandas", "numpy", "matplotlib"]  # Restrict imports
)

agent = Agent(
    model=OpenAIChat(),
    tools=[python_tools],
    instructions="You can write and execute Python code for data analysis"
)

response = agent.run("Load data.csv and create a histogram of the sales column")
```

### External Service Tools

#### Cloud & DevOps
```python
from buddy.tools.aws_tools import AWSTools
from buddy.tools.docker import DockerTools
from buddy.tools.kubernetes_tools import KubernetesTools

# AWS operations
aws = AWSTools(
    region="us-east-1",
    services=["s3", "ec2", "lambda"]  # Enable specific services
)

# Docker management
docker = DockerTools()

# Kubernetes cluster management
k8s = KubernetesTools(config_path="~/.kube/config")

agent = Agent(
    model=OpenAIChat(),
    tools=[aws, docker, k8s],
    instructions="You can manage AWS resources, Docker containers, and Kubernetes clusters"
)
```

#### Productivity & Project Management
```python
from buddy.tools.jira import JiraTools
from buddy.tools.github import GithubTools
from buddy.tools.linear import LinearTools

# Project management
jira = JiraTools(server="company.atlassian.net", token="your-token")
github = GithubTools(token="github-token")
linear = LinearTools(api_key="linear-key")

agent = Agent(
    model=OpenAIChat(),
    tools=[jira, github, linear],
    instructions="You can manage projects across Jira, GitHub, and Linear"
)

response = agent.run("Create a new issue in Jira for the login bug and link it to the GitHub PR")
```

### Tool Error Handling

```python
from buddy.tools import Function
import logging

def risky_operation(value: int) -> str:
    """A tool that might fail."""
    if value < 0:
        raise ValueError("Value cannot be negative")
    return f"Processed {value}"

risky_tool = Function.from_callable(risky_operation)

agent = Agent(
    model=OpenAIChat(),
    tools=[risky_tool],
    instructions="Handle tool errors gracefully",
    retries=2,  # Retry on failures
    debug_mode=True  # See detailed error logs
)

# Agent will handle tool errors and retry automatically
try:
    response = agent.run("Process the value -5")
except Exception as e:
    print(f"Agent run failed: {e}")
```

### Creating Tool Ecosystems

```python
# Combine related tools into ecosystems
data_analysis_tools = [
    PandasTools(),
    CSVTools(), 
    VisualizationTools(),
    SQLTools(connection_string="postgresql://localhost/analytics")
]

web_research_tools = [
    GoogleSearch(),
    WebsiteTools(), 
    WikipediaTools()
]

communication_tools = [
    EmailTools(),
    SlackTools(bot_token="xoxb-token"),
    WhatsAppTools()
]

# Data analyst agent
data_agent = Agent(
    name="DataAnalyst",
    model=OpenAIChat(id="gpt-4o"),
    tools=data_analysis_tools,
    instructions="You are an expert data analyst with full analytics capabilities"
)

# Research agent
research_agent = Agent(
    name="Researcher", 
    model=Claude(id="claude-3-5-sonnet-20241022"),
    tools=web_research_tools,
    instructions="You are a research specialist who can find and analyze information"
)

# Communication agent
comm_agent = Agent(
    name="Communicator",
    model=OpenAIChat(id="gpt-4o"),
    tools=communication_tools,
    instructions="You handle all communication and outreach tasks"
)
```

### Advanced Planning Tools

#### 🧠 **PlanningTools - Hierarchical Task Decomposition**

The PlanningTools toolkit provides sophisticated planning capabilities for breaking down complex goals into structured, executable plans with dependency tracking and adaptive replanning.

```python
from buddy.tools.planning import PlanningTools

# Create agent with planning capabilities
planning_agent = Agent(
    name="ProjectManager",
    model=OpenAIChat(id="gpt-4o"),
    tools=[PlanningTools()],
    instructions="""
    You are an expert project manager with advanced planning capabilities.
    Use planning tools to break down complex projects into manageable steps.
    Always validate plans before execution and monitor progress actively.
    """
)

# Example 1: Product Launch Planning
response = planning_agent.run("""
Create a comprehensive execution plan for launching a new mobile app.
Context:
- Development team: 8 people
- Timeline: 3 months
- Budget: $150K
- Platforms: iOS and Android
- Requirements: App store approval, beta testing

Include constraints like approval times and resource availability.
Available resources: Dev team, QA team, Marketing team, UI/UX designers.
""")

# The agent will automatically:
# 1. Create hierarchical execution plan with steps
# 2. Auto-generate todos for each plan step
# 3. Validate plan for feasibility and dependencies
# 4. Store plan in session for monitoring
# 5. Provide detailed breakdown with timeline

# Example 2: Working with Auto-Generated Todos
todo_response = planning_agent.run("""
List all todos created from the mobile app launch plan.
Mark the first two high-priority todos as completed.
Create a new manual todo for 'Schedule team kickoff meeting'.
""")

# The agent can now manage todos alongside planning:
# - List todos by priority or status
# - Complete todos and track progress
# - Create additional manual todos
# - Link todos back to plan steps

# Example 2: Event Planning with Optimization
event_response = planning_agent.run("""
Plan a corporate annual meeting:
- 200 attendees
- 2-day hybrid format (in-person + virtual)
- Budget: $75K
- Need keynote speakers and technical setup

Create the plan, validate it, and optimize for cost-effectiveness.
""")

# Example 3: Adaptive Replanning
replan_response = planning_agent.run("""
The mobile app launch plan needs updating due to:
- Team size increased to 12 people
- Budget increased to $200K
- New requirement: Web version needed

Update the existing plan with these changes.
""")

# Example 4: Advanced Todo Management
todo_management = planning_agent.run("""
Show me a complete todo workflow:

1. Create a plan for 'Organize company retreat'
2. List all auto-generated todos
3. Complete the planning phase todos
4. Create a manual todo for 'Book catering service' with high priority
5. Show only high-priority pending todos
6. Update one todo's deadline to 'next Friday'
""")

# The agent will demonstrate:
# - Auto-todo generation from plans
# - Todo filtering and status management  
# - Manual todo creation with priorities
# - Todo updates and deadline management
# - Integration between planning and execution
```

#### **Available Planning Tools:**

**🎯 create_plan**: Generate hierarchical execution plans
```python
# Creates detailed plans with:
# - Step-by-step decomposition
# - Dependency tracking
# - Resource allocation
# - Timeline estimation
# - Constraint validation
```

**✅ validate_plan**: Check plan feasibility and constraints
```python
# Validates plans for:
# - Circular dependencies
# - Resource availability
# - Constraint satisfaction
# - Timeline feasibility
```

**📊 monitor_plan**: Track execution progress and status
```python
# Monitors:
# - Step completion status
# - Progress percentages
# - Failed steps identification
# - Timeline adherence
```

**🔄 replan**: Adapt plans based on new context
```python
# Adaptive replanning for:
# - Changed requirements
# - Failed steps
# - Resource changes
# - Timeline adjustments
```

**⚡ optimize_plan**: Improve efficiency and resource usage
```python
# Optimizes plans by:
# - Removing redundant steps
# - Parallel execution opportunities
# - Resource utilization
# - Complexity reduction
```

**🎯 create_todo**: Create actionable todos from plans or tasks
```python
# Creates todos with:
# - Priority levels (high/medium/low)
# - Deadlines and dependencies
# - Plan and step linking
# - Auto-generation from plans
```

**📋 manage_todos**: Complete todo lifecycle management
```python
# Todo operations:
# - List and filter todos
# - Complete and update todos
# - Track status and progress
# - Delete and organize todos
```

#### **Planning Features:**

- **Hierarchical Decomposition**: Breaks complex goals into manageable sub-tasks
- **Dependency Management**: Tracks and validates step dependencies
- **Session Persistence**: Plans stored in agent memory for continued access
- **Strategy Selection**: Multiple planning strategies (hierarchical, reactive, deliberative)
- **Real-time Monitoring**: Progress tracking and status reporting
- **Adaptive Replanning**: Dynamic plan updates based on changing context
- **Constraint Handling**: Budget, timeline, and resource constraint validation
- **Optimization Engine**: Automatic plan efficiency improvements
- **Todo Integration**: Automatic todo generation from plan steps
- **Todo Management**: Complete todo lifecycle with status tracking
- **Dependency Linking**: Connects todos to plans and steps
- **Priority System**: High/medium/low priority classification
- **Progress Tracking**: Links todo completion to plan progress

#### **Use Cases:**

- **Project Management**: Software development, product launches
- **Event Planning**: Conferences, meetings, corporate events
- **Process Design**: Workflow optimization, business processes
- **Strategic Planning**: Business initiatives, goal achievement
- **Resource Allocation**: Team coordination, budget planning
- **Crisis Management**: Response planning, recovery strategies

#### **Integration with Other Tools:**

```python
from buddy.tools.planning import PlanningTools
from buddy.tools.thinking import ThinkingTools
from buddy.tools.reasoning import ReasoningTools

# Comprehensive planning agent
advanced_planner = Agent(
    name="AdvancedPlanner",
    model=OpenAIChat(id="o1-preview"),  # Reasoning model
    tools=[
        PlanningTools(),    # Hierarchical planning
        ThinkingTools(),    # Internal reasoning
        ReasoningTools()    # Structured thinking
    ],
    instructions="""
    You are an advanced planning specialist combining structured thinking,
    detailed reasoning, and comprehensive planning capabilities.
    
    Use thinking tools to explore ideas, reasoning tools for logical analysis,
    and planning tools to create actionable execution plans.
    """
)

# Complex strategic planning
strategic_response = advanced_planner.run("""
Our company needs to expand into the European market within 18 months.
Current situation:
- 50 employees in US
- $5M annual revenue
- SaaS product with 10K users
- $2M budget for expansion

Think through the challenges, reason about the best approach,
and create a comprehensive expansion plan.
""")
```

---

## Memory & Knowledge System

Buddy AI provides sophisticated memory and knowledge management capabilities, enabling agents to learn, remember, and access vast amounts of information through conversation history and RAG (Retrieval-Augmented Generation).

### Agent Memory

#### Basic Memory Configuration
```python
from buddy.memory.agent import AgentMemory

# Enable basic conversation memory
agent = Agent(
    model=OpenAIChat(),
    memory=AgentMemory(),
    instructions="You have memory of our conversations"
)

# First conversation
response = agent.run("My name is Alice and I'm a data scientist")
print(response.content)

# Later conversation - agent remembers
response = agent.run("What's my profession?")  
print(response.content)  # Will remember Alice is a data scientist
```

#### Advanced Memory Features
```python
# Memory with session summaries
memory = AgentMemory(
    create_session_summary=True,           # Generate conversation summaries
    update_session_summary_after_run=True, # Update after each interaction
    create_user_memories=True,             # Store user-specific info
    update_user_memories_after_run=True    # Update user memories
)

agent = Agent(
    model=OpenAIChat(),
    memory=memory,
    enable_agentic_memory=True,    # Let agent manage its own memories
    enable_user_memories=True,     # Store personalized user information
    enable_session_summaries=True, # Create session summaries
    instructions="Learn and remember information about users"
)
```

#### Memory with History Control
```python
agent = Agent(
    model=OpenAIChat(),
    memory=AgentMemory(),
    add_history_to_messages=True,  # Include chat history in context
    num_history_runs=5,            # Include last 5 conversations
    search_previous_sessions_history=True, # Search across sessions
    num_history_sessions=10,       # Search last 10 sessions
    instructions="Use conversation history to provide better responses"
)
```

### Custom Memory Databases

#### SQLite Memory (Default)
```python
from buddy.memory.db import SQLiteMemoryDb

sqlite_db = SQLiteMemoryDb(
    db_path="agent_memory.db",
    table_name="memories"
)

memory = AgentMemory(db=sqlite_db)
agent = Agent(model=OpenAIChat(), memory=memory)
```

#### PostgreSQL Memory
```python
from buddy.memory.db import PostgreSQLMemoryDb

postgres_db = PostgreSQLMemoryDb(
    host="localhost",
    port=5432,
    user="buddy",
    password="password",
    database="agent_memory"
)

memory = AgentMemory(db=postgres_db)
agent = Agent(model=OpenAIChat(), memory=memory)
```

#### MongoDB Memory
```python
from buddy.memory.db import MongoDBMemoryDb

mongo_db = MongoDBMemoryDb(
    host="mongodb://localhost:27017/",
    database="buddy_memory",
    collection="agent_memories"
)

memory = AgentMemory(db=mongo_db)
agent = Agent(model=OpenAIChat(), memory=memory)
```

### Knowledge Management (RAG)

#### Enhanced iRAG System

**iRAG (Intelligent Retrieval and Generation)** is Buddy AI's advanced knowledge system that provides 100% accurate question-answering through intelligent document retrieval and NLP-based ontology mapping.

```python
from buddy.knowledge.irag import irag

# Enhanced iRAG with 100% accuracy goal
knowledge = irag(
    data_dir="./company_docs",           # Directory with documents
    db_path="./knowledge.db",            # SQLite database path
    accuracy_threshold=0.9,              # High accuracy requirement
    enable_ontology_mapping=True,        # NLP entity extraction
    enable_comprehensive_search=True,    # Multiple search strategies
    chunk_size=1000,                     # Document chunk size
    chunk_overlap=100                    # Overlap for context preservation
)

agent = Agent(
    model=OpenAIChat(),
    knowledge=knowledge,
    instructions="Answer questions with 100% accuracy using the iRAG knowledge base"
)

response = agent.run("What is our company's refund policy?")
print(response.content)      # Accurate answer from documents
print(response.references)   # Source document references
```

#### iRAG vs Traditional RAG

**Traditional RAG limitations:**
- May miss relevant documents
- Inconsistent retrieval quality
- Limited context understandin