# Core API Reference

This document provides detailed information about the core components of the Multi-Swarm Framework.

## Agency

The `Agency` class is the main coordinator for multi-agent systems.

### Class Definition

```python
class Agency:
    def __init__(
        self,
        name: str,
        description: str,
        agents: List[Agent],
        flows: List[Tuple[Agent, Agent]],
        storage_path: Optional[str] = None,
        shared_instructions: Optional[str] = None,
        use_code_interpreter: bool = False,
        use_rag: bool = False,
        use_file_storage: bool = False
    ):
        """
        Initialize an agency.
        
        Args:
            name: Name of the agency
            description: Description of the agency's purpose
            agents: List of agents in the agency
            flows: List of communication flows between agents
            storage_path: Optional path for persistent storage
            shared_instructions: Optional path to shared instructions file
            use_code_interpreter: Whether to enable code interpreter
            use_rag: Whether to enable RAG capabilities
            use_file_storage: Whether to enable file storage
        """
```

### Key Methods

#### Knowledge Management
```python
def add_to_shared_knowledge(
    self,
    content: str,
    metadata: Dict = None,
    target_agents: List[str] = None
) -> List[Document]:
    """
    Add content to the shared knowledge base.
    
    Args:
        content: Content to add
        metadata: Additional metadata
        target_agents: Optional list of specific agents to receive the knowledge
        
    Returns:
        List of created documents
    """

def search_knowledge_with_coordination(
    self,
    query: str,
    k: int = 5,
    coordinating_agents: List[str] = None
) -> Dict[str, Any]:
    """
    Search knowledge with multi-agent coordination.
    
    Args:
        query: Search query
        k: Number of results per agent
        coordinating_agents: Optional list of specific agents to coordinate with
        
    Returns:
        Combined and validated knowledge from all sources
    """
```

#### Communication
```python
def send_message(
    self,
    source: str,
    target: str,
    content: str,
    metadata: Dict = None
) -> Message:
    """
    Send a message from one agent to another.
    
    Args:
        source: Name of the source agent
        target: Name of the target agent
        content: Message content
        metadata: Additional metadata
        
    Returns:
        The created Message instance
    """

def broadcast_message(
    self,
    source: str,
    content: str,
    metadata: Dict = None
) -> List[Message]:
    """
    Broadcast a message to all connected agents.
    
    Args:
        source: Name of the source agent
        content: Message content
        metadata: Additional metadata
        
    Returns:
        List of created Message instances
    """
```

#### State Management
```python
def save_state(self, path: Optional[str] = None) -> None:
    """
    Save the agency state to a file.
    
    Args:
        path: Optional path to save state (default: agency_state.json)
    """

def load_state(self, path: Optional[str] = None) -> None:
    """
    Load the agency state from a file.
    
    Args:
        path: Optional path to load state from (default: agency_state.json)
    """
```

## Agent

The `Agent` class represents individual agents within an agency.

### Class Definition

```python
class Agent:
    def __init__(
        self,
        name: str,
        description: str,
        llm_provider: str = "claude",
        provider_config: Dict[str, Any] = None,
        temperature: float = 0.7,
        max_prompt_tokens: int = 25000
    ):
        """
        Initialize an agent.
        
        Args:
            name: The agent's name
            description: Description of the agent's role
            llm_provider: LLM provider to use ("claude" or "gemini")
            provider_config: Provider-specific configuration
            temperature: Temperature for responses
            max_prompt_tokens: Maximum tokens in prompt context
        """
```

### Task-Specific Configurations

```python
# Claude Configurations
CLAUDE_CONFIG = {
    "default": {
        "model": "claude-3-5-sonnet-latest",
        "max_tokens": 4096,
        "api_version": "2024-03"
    },
    "code": {
        "model": "claude-3-5-sonnet-latest",
        "temperature": 0.1
    },
    "research": {
        "model": "claude-3-5-opus-latest",
        "temperature": 0.7
    }
}

# Gemini Configurations
GEMINI_CONFIG = {
    "default": {
        "model": "gemini-2.0-flash-exp",
        "max_tokens": 4096,
        "api_version": "2024-01"
    },
    "data": {
        "model": "gemini-2.0-flash-exp",
        "temperature": 0.3
    },
    "realtime": {
        "model": "gemini-2.0-flash-exp",
        "max_tokens": 2048,
        "temperature": 0.5
    }
}
```

## RAGAgent

The `RAGAgent` class specializes in knowledge retrieval and coordination.

### Class Definition

```python
class RAGAgent(Agent):
    def __init__(
        self,
        name: str,
        description: str = "Research and knowledge gathering specialist",
        storage_path: Optional[str] = None,
        model_name: str = RAGSystem.DEFAULT_MODEL
    ):
        """
        Initialize a RAG agent.
        
        Args:
            name: The agent's name
            description: Description of the agent's role
            storage_path: Optional path for storage
            model_name: Name of the embedding model to use
        """
```

### Key Methods

```python
def add_knowledge(
    self,
    content: str,
    metadata: Dict = None
) -> Document:
    """
    Add knowledge to the RAG system.
    
    Args:
        content: Content to add
        metadata: Additional metadata
        
    Returns:
        Created Document instance
    """

def search_with_coordination(
    self,
    query: str,
    collaborating_agents: List[Any],
    k: int = 5
) -> Dict[str, Any]:
    """
    Search knowledge with coordination across agents.
    
    Args:
        query: Search query
        collaborating_agents: List of agents to coordinate with
        k: Number of results per agent
        
    Returns:
        Dict containing results and synthesis
    """
```

## Document

The `Document` class represents a document in the RAG system.

### Class Definition

```python
class Document(BaseModel):
    id: str = Field(default_factory=lambda: str(uuid.uuid4()))
    content: str
    metadata: Optional[Dict[str, Any]] = Field(default_factory=dict)
    embedding: Optional[List[float]] = None
    created_at: datetime = Field(default_factory=lambda: datetime.now(UTC))
```

### Methods

```python
def to_dict(self) -> Dict[str, Any]:
    """Convert the document to a dictionary."""

@classmethod
def from_dict(cls, data: Dict[str, Any]) -> "Document":
    """Create a document from a dictionary."""
```

## SearchResult

The `SearchResult` class represents a search result from the RAG system.

### Class Definition

```python
class SearchResult(BaseModel):
    document: Document
    score: float
    metadata: Dict = Field(default_factory=dict)
    reflection: Optional[str] = None
```

## RAGSystem

The `RAGSystem` class provides advanced retrieval capabilities.

### Class Definition

```python
class RAGSystem:
    def __init__(
        self,
        model_name: str = DEFAULT_MODEL,
        storage_path: Optional[Union[str, Path]] = None,
        device: str = None,
        use_gpu: bool = None
    ):
        """
        Initialize the RAG system.
        
        Args:
            model_name: Name of the embedding model
            storage_path: Path for persistent storage
            device: Device to use for computations
            use_gpu: Whether to use GPU acceleration
        """
```

### Key Methods

```python
def add_document(
    self,
    content: str,
    metadata: Dict = None,
    compute_embedding: bool = True
) -> Document:
    """Add a document to the system."""

def search(
    self,
    query: str,
    k: int = 5,
    threshold: float = None,
    filter_fn: callable = None
) -> List[SearchResult]:
    """Search for relevant documents."""

def search_with_reflection(
    self,
    query: str,
    k: int = 5
) -> List[SearchResult]:
    """Search with reflection on results."""
```

## Error Handling

The framework includes comprehensive error handling:

```python
try:
    # Agency operations
    agency.search_knowledge_with_coordination(query="search")
except RuntimeError as e:
    if "RAG not enabled" in str(e):
        # Handle RAG-related errors
        pass
except ProviderError as e:
    if isinstance(e, RateLimitError):
        # Handle rate limiting
        pass
    elif isinstance(e, AuthenticationError):
        # Handle authentication issues
        pass
except Exception as e:
    # Handle other errors
    pass
```

## Best Practices

1. **Agency Configuration**
   - Enable only needed features
   - Use appropriate storage paths
   - Configure proper communication flows

2. **Agent Design**
   - Use task-specific configurations
   - Enable appropriate features
   - Set suitable temperature values

3. **Knowledge Management**
   - Add comprehensive metadata
   - Use coordinated search for complex queries
   - Monitor knowledge quality

4. **Resource Management**
   - Clean up temporary files
   - Monitor resource usage
   - Implement proper error handling

## Usage Example

```python
from multi_swarm import Agency, Agent

# Create custom agent
class DevelopmentAgent(Agent):
    def __init__(self):
        super().__init__(
            name="Developer",
            description="Code generation and review specialist",
            instructions="instructions.md",
            tools_folder="./tools",
            # Let the framework choose between Claude and Gemini
            temperature=0.7,
            use_code_interpreter=True
        )

# Create agency
dev_agent = DevelopmentAgent()
qa_agent = QAAgent()

agency = Agency(
    name="Development Team",
    description="Software development team simulation",
    agents=[dev_agent, qa_agent],
    flows=[
        (dev_agent.name, qa_agent.name),
        (qa_agent.name, dev_agent.name)
    ],
    shared_instructions="manifesto.md",
    use_code_interpreter=True
)

# Run interactive demo
agency.run_demo()
```

## Learn More

- [Agent API](agents.md)
- [Tool API](tools.md)
- [Agency API](agency.md)
- [User Guide](../user-guide/creating-agents.md) 