> ## Documentation Index
> Fetch the complete documentation index at: https://docs.xpander.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# Python SDK

> Backend-as-a-Service SDK for building and managing AI agents

A comprehensive Backend-as-a-Service (BaaS) platform for building, deploying, and managing AI agents at scale. It provides five core modules that work together to create powerful AI agent applications.

<Note>
  This is the **Python SDK documentation**. The SDK has been completely refactored to provide a modular, Backend-as-a-Service architecture for enterprise AI agent development.
</Note>

## Core Architecture

The SDK is built around five main modules:

<CardGroup cols={2}>
  <Card title="Backend" icon="server" href="/API reference/backend">
    **Agents Backend** - Get framework specific arguments for AI agents.
  </Card>

  <Card title="Agents" icon="robot" href="/API reference/agents">
    **Agent Management** - Create, configure, and manage AI agents with tools, knowledge bases, and execution capabilities.
  </Card>

  <Card title="Tasks" icon="play" href="/API reference/tasks">
    **Task Execution** - Handle complex task workflows, execution management, and real-time streaming.
  </Card>

  <Card title="Tools Repository" icon="wrench" href="/API reference/tools">
    **Tools Integration** - Register local tools, manage external integrations, and handle MCP servers.
  </Card>

  <Card title="Knowledge Bases" icon="database" href="/API reference/knowledge">
    **Knowledge Management** - Create and search knowledge repositories with semantic search capabilities.
  </Card>

  <Card title="Events" icon="bars-progress" href="/API reference/events">
    **Event Handling** - Event-driven programming with decorators, real-time streaming, and background processing.
  </Card>
</CardGroup>

## Installation

```bash theme={"dark"}
pip install xpander-sdk

# With optional dependencies
pip install xpander-sdk[agno]  # For Agno framework support
pip install xpander-sdk[dev]   # For development
```

```python theme={"dark"}
from xpander_sdk import Agents, Tasks, ToolsRepository, KnowledgeBases

# SDK automatically uses environment variables
# Set XPANDER_API_KEY and XPANDER_ORGANIZATION_ID

# Initialize modules directly
agents = Agents()
tasks = Tasks()
tools = ToolsRepository()
knowledge = KnowledgeBases()
```

## Key Features

* **🤖 Agent Management**: Create, configure, and manage AI agents with comprehensive lifecycle control
* **⚡ Task Execution**: Handle complex multi-step workflows with real-time event streaming
* **🔧 Tools Integration**: Register local tools and integrate with external services via MCP
* **📚 Knowledge Bases**: Semantic search across document repositories with AI-powered insights
* **🎯 Event-Driven**: Event handling with decorators for responsive agent applications
* **🔄 Async/Sync Support**: Both asynchronous and synchronous interfaces for flexibility
* **📊 Real-time Monitoring**: Track agent performance, metrics, and execution in real-time
* **🏗️ Modular Architecture**: Five independent modules that work seamlessly together

## Quick Start Example

### Asynchronous Usage

```python theme={"dark"}
from xpander_sdk import Agents

# Initialize modules (automatically uses environment variables)
agents = Agents()

# List all agents
agent_list = await agents.alist()

# Load a specific agent
agent = await agents.aget("agent-id")

# Create and execute a task
task = await agent.acreate_task(
    prompt="Analyze this data",
    file_urls=["https://example.com/data.csv"],
    events_streaming=True
)

# Stream task events
async for event in task.aevents():
    print(f"Event: {event.type} at {event.time}")
    if event.type == "task_finished":
        print(f"Result: {event.data.result}")
        break
```

### Synchronous Usage

```python theme={"dark"}
from xpander_sdk import Agents

# Initialize modules
agents = Agents()

# List all agents
agent_list = agents.list()

# Load a specific agent
agent = agents.get("agent-id")

# Create and execute a task
task = agent.create_task(
    prompt="Analyze this data",
    file_urls=["https://example.com/data.csv"]
)

# Check task status
print(f"Task Status: {task.status}")
print(f"Task Result: {task.result}")
```

## Event-Driven Development

The SDK supports event-driven programming with decorators for task handling and lifecycle management:

### Asynchronous Usage

```python theme={"dark"}
from xpander_sdk import on_task, Events

# Define task handler using decorator
@on_task
async def handle_task(task):
    print(f"Processing task: {task.id}")
    
    # Your custom logic here
    task.result = "Task processed successfully"
    return task

# Start event listener
events = Events()
await events.start(on_execution_request=handle_task)
```

### Synchronous Usage

```python theme={"dark"}
from xpander_sdk import on_task

# Define task handler using decorator
@on_task
def handle_task(task):
    print(f"Processing task: {task.id}")
    
    # Your custom logic here
    task.result = "Task processed successfully"
    return task
```

### Lifecycle Management

```python theme={"dark"}
from xpander_sdk import on_boot, on_shutdown, on_task

# Initialize resources before task processing
@on_boot
async def initialize_resources():
    print("Setting up database and cache...")
    # Initialization logic here

# Handle tasks with initialized resources
@on_task
async def process_task(task):
    print(f"Processing task: {task.id}")
    task.result = "Task completed"
    return task

# Clean up during shutdown
@on_shutdown
async def cleanup_resources():
    print("Cleaning up resources...")
    # Cleanup logic here
```

## Module Documentation

<CardGroup cols={2}>
  <Card title="Agents Module" icon="robot" href="/API reference/agents">
    Agent creation, management, and execution with tools and knowledge bases
  </Card>

  <Card title="Tasks Module" icon="play" href="/API reference/tasks">
    Task lifecycle management, execution control, and real-time streaming
  </Card>

  <Card title="Tools Repository" icon="wrench" href="/API reference/tools">
    Local tool registration, external integrations, and MCP server management
  </Card>

  <Card title="Knowledge Bases" icon="database" href="/API reference/knowledge">
    Document management and semantic search across knowledge repositories
  </Card>

  <Card title="Events Module" icon="bars-progress" href="/API reference/events">
    Event-driven programming, decorators, and background task processing
  </Card>

  <Card title="Configuration" icon="gear" href="/API reference/configuration">
    SDK configuration, authentication, and environment setup
  </Card>

  <Card title="Types" icon="code" href="/API reference/types">
    Data types, enumerations, and models used across the SDK
  </Card>
</CardGroup>

## Authentication

The SDK supports multiple authentication methods:

<Tabs>
  <Tab title="Environment Variables (Recommended)">
    ```bash theme={"dark"}
    export XPANDER_API_KEY="your-api-key"
    export XPANDER_ORGANIZATION_ID="your-org-id"
    export XPANDER_BASE_URL="https://inbound.xpander.ai"  # Optional
    ```

    ```python theme={"dark"}
    from xpander_sdk import Configuration

    # Automatically reads from environment variables
    config = Configuration()
    ```
  </Tab>

  <Tab title="Explicit Configuration">
    ```python theme={"dark"}
    from xpander_sdk import Configuration

    config = Configuration(
        api_key="your-api-key",
        organization_id="your-org-id",
        base_url="https://inbound.xpander.ai"  # Optional
    )
    ```
  </Tab>

  <Tab title="From File">
    ```bash theme={"dark"}
    # .env file
    XPANDER_API_KEY=your-api-key
    XPANDER_ORGANIZATION_ID=your-org-id
    ```

    ```python theme={"dark"}
    from dotenv import load_dotenv
    from xpander_sdk import Configuration

    load_dotenv()
    config = Configuration()
    ```
  </Tab>
</Tabs>

## Error Handling

```python theme={"dark"}
from xpander_sdk.exceptions import ModuleException

try:
    agent = await agents.aget("invalid-agent-id")
except ModuleException as e:
    print(f"Error {e.status_code}: {e.description}")
```

## Additional Resources

<CardGroup cols={3}>
  <Card title="Getting Started" icon="rocket" href="/overview/what-is-xpander">
    Begin building with xpander.ai
  </Card>

  <Card title="Tutorials" icon="graduation-cap" href="/Examples/index">
    Step-by-step guides and examples
  </Card>

  <Card title="GitHub Repository" icon="github" href="https://github.com/xpander-ai/xpander-sdk">
    View source code and contribute
  </Card>
</CardGroup>
