---
title: 'API Reference'
description: 'Complete API reference for PandaAGI SDK'
---

## Overview

The PandaAGI SDK provides a comprehensive Python API for building and deploying AI agents. This reference covers all classes, methods, and functions available in the SDK.

<CardGroup cols={2}>
  <Card
    title="Agent API"
    icon="robot"
    href="/api-reference/agent"
  >
    Core agent functionality and configuration
  </Card>
  <Card
    title="WebSocket API"
    icon="wifi"
    href="/api-reference/websocket"
  >
    Real-time communication and event streaming
  </Card>
  <Card
    title="Events API"
    icon="bolt"
    href="/api-reference/events"
  >
    Event handling and streaming interfaces
  </Card>
  <Card
    title="Tools API"
    icon="wrench"
    href="/api-reference/tools"
  >
    Built-in tools and custom tool development
  </Card>
</CardGroup>

## Installation

```bash
pip install panda-agi
```

## Quick Start

```python
from panda_agi.client import Agent
from panda_agi.tools.search import WebSearchTool

# Create an agent
agent = Agent(
    name="MyAgent",
    description="A helpful assistant",
    tools=[WebSearchTool()]
)

# Run a query
response = agent.run("What's the weather like today?")
print(response)
```

## Core Modules

### `panda_agi.client`

The main client module containing the core Agent class and configuration options.

```python
from panda_agi.client import Agent, AgentConfig, WebSocketClient
```

**Key Classes:**
- `Agent` - Main agent class for creating and running AI agents
- `AgentConfig` - Configuration options for agent behavior
- `WebSocketClient` - Client for real-time communication

### `panda_agi.tools`

Tools that extend agent capabilities.

```python
from panda_agi.tools.search import WebSearchTool
from panda_agi.tools.navigation import WebNavigationTool
from panda_agi.tools.file_system import FileSystemTool
```

**Tool Categories:**
- `search` - Web search and knowledge retrieval
- `navigation` - Web browsing and API interaction
- `file_system` - File operations and code execution

### `panda_agi.envs`

Environment management for secure agent execution.

```python
from panda_agi.envs import DockerEnvironment, ProcessEnvironment
```

**Environment Types:**
- `DockerEnvironment` - Containerized execution
- `ProcessEnvironment` - Process-based isolation
- `LocalEnvironment` - Direct host execution

### `panda_agi.events`

Event handling and streaming functionality.

```python
from panda_agi.events import EventHandler, EventFilter
```

**Event Components:**
- `EventHandler` - Custom event processing
- `EventFilter` - Event filtering and routing
- `EventStore` - Event persistence

## Authentication

Some tools and features require API keys:

```python
import os

# Set environment variables
os.environ["OPENAI_API_KEY"] = "your-openai-key"
os.environ["ANTHROPIC_API_KEY"] = "your-anthropic-key"

# Or pass directly to agent config
config = AgentConfig(
    api_keys={
        "openai": "your-openai-key",
        "anthropic": "your-anthropic-key"
    }
)
```

## Error Handling

The SDK provides specific exception types for different error conditions:

```python
from panda_agi.exceptions import (
    AgentError,
    ToolError,
    EnvironmentError,
    ConfigurationError
)

try:
    response = agent.run("Complex query")
except AgentError as e:
    print(f"Agent error: {e}")
except ToolError as e:
    print(f"Tool error: {e}")
except Exception as e:
    print(f"Unexpected error: {e}")
```

## Configuration

### Global Configuration

Set global defaults for all agents:

```python
from panda_agi.config import set_global_config

set_global_config({
    "default_model": "gpt-4",
    "default_timeout": 300,
    "log_level": "INFO"
})
```

### Agent Configuration

Configure individual agents:

```python
from panda_agi.client import Agent, AgentConfig

config = AgentConfig(
    model="gpt-4",
    temperature=0.7,
    max_iterations=10,
    timeout=300,
    memory_size=1000
)

agent = Agent(
    name="ConfiguredAgent",
    config=config
)
```

## Logging

The SDK uses Python's standard logging module:

```python
import logging

# Enable debug logging
logging.basicConfig(level=logging.DEBUG)

# Or configure specific loggers
logger = logging.getLogger("panda_agi")
logger.setLevel(logging.INFO)
```

## Type Hints

The SDK is fully typed for better IDE support:

```python
from typing import List, Dict, Optional
from panda_agi.client import Agent
from panda_agi.tools.base import BaseTool

def create_agent(
    name: str,
    tools: List[BaseTool],
    config: Optional[Dict[str, Any]] = None
) -> Agent:
    return Agent(name=name, tools=tools, config=config)
```

## Async Support

Many operations support async/await:

```python
import asyncio
from panda_agi.client import Agent

async def main():
    agent = Agent(name="AsyncAgent")
    
    # Async execution
    response = await agent.run_async("Tell me about quantum computing")
    
    # Async streaming
    async for event in agent.run_stream_async("Research AI trends"):
        print(f"Event: {event.type}")

# Run async function
asyncio.run(main())
```

## Testing

The SDK includes testing utilities:

```python
from panda_agi.testing import MockAgent, MockTool

# Create mock agent for testing
mock_agent = MockAgent()
mock_agent.set_response("Mocked response")

# Test your code
response = mock_agent.run("Test query")
assert response == "Mocked response"
```

## Performance

### Caching

Enable caching for better performance:

```python
from panda_agi.client import Agent
from panda_agi.cache import RedisCache

# Use Redis for caching
cache = RedisCache(host="localhost", port=6379)

agent = Agent(
    name="CachedAgent",
    cache=cache
)
```

### Connection Pooling

For high-throughput applications:

```python
from panda_agi.client import AgentPool

# Create agent pool
pool = AgentPool(
    agent_factory=lambda: Agent(name="PooledAgent"),
    min_size=5,
    max_size=20
)

# Use from pool
async with pool.get_agent() as agent:
    response = await agent.run_async("Query")
```

## Migration Guide

### From v0.x to v1.x

Key changes in the latest version:

```python
# Old way (v0.x)
from panda_agi import PandaAgent
agent = PandaAgent("MyAgent")

# New way (v1.x)
from panda_agi.client import Agent
agent = Agent(name="MyAgent")
```

## Next Steps

<CardGroup cols={2}>
  <Card
    title="Agent API"
    icon="robot"
    href="/api-reference/agent"
  >
    Detailed Agent class documentation
  </Card>
  <Card
    title="WebSocket API"
    icon="wifi"
    href="/api-reference/websocket"
  >
    Real-time communication reference
  </Card>
  <Card
    title="Events API"
    icon="bolt"
    href="/api-reference/events"
  >
    Event handling and streaming
  </Card>
  <Card
    title="Examples"
    icon="play"
    href="/examples/chat-interface"
  >
    See the API in action with examples
  </Card>
</CardGroup> 