> ## 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

> The Python SDK for running tasks, registering skills and managing knowledge bases on agents that live on xpander

The Python SDK runs tasks, registers skills and manages knowledge bases on agents that live on xpander. With it, an agent loop running in your own process uses the same approved skills as any other agent and leaves the same task record. The Vault attaches credentials at the moment of each call.

## Core Architecture

The SDK is built around these modules:

<CardGroup cols={2}>
  <Card title="Backend" icon="server" href="/developers/sdk-reference/backend">
    **Agents Backend** - Get the arguments your agent loop (for example Agno) needs to run an agent.
  </Card>

  <Card title="Agents" icon="robot" href="/developers/sdk-reference/agents">
    **Agents** - List and load agents; read their skills and knowledge bases; start a task on one.
  </Card>

  <Card title="Tasks" icon="play" href="/developers/sdk-reference/tasks">
    **Tasks** - Create a task, stream its events, read its result and usage.
  </Card>

  <Card title="Skills Repository" icon="wrench" href="/developers/sdk-reference/tools">
    **Skills Integration** - Register local skills, connect outside services, and manage skills served over MCP.
  </Card>

  <Card title="Knowledge Bases" icon="database" href="/developers/sdk-reference/knowledge-bases">
    **Knowledge bases** - Create a knowledge base, add documents, run a semantic search.
  </Card>

  <Card title="Events" icon="bars-progress" href="/developers/sdk-reference/decorators">
    **Events** - The `@on_task`, `@on_boot` and `@on_tool_*` decorators the task handler is built from.
  </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. XPANDER_ORGANIZATION_ID is optional on the cloud
# edition, and required when pointing at a self-hosted Agent Controller.

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

## Key Features

* **🤖 Agent Access**: List and load agents, and work with their skills, sessions, database, and knowledge bases. Creating, updating, and deleting agents is done through the [REST API](/api-reference/v1/agents/create-agent) or Xpander Chat
* **⚡ Task Execution**: Handle complex multi-step workflows with real-time event streaming
* **🔧 Skills Integration**: Register local skills and connect outside services via MCP
* **📚 Knowledge Bases**: Semantic search across document repositories
* **🎯 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**: Independent modules that work 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
from xpander_sdk.modules.events.events_module import 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="/developers/sdk-reference/agents">
    Load, run and manage agents, with their skills and knowledge bases
  </Card>

  <Card title="Tasks Module" icon="play" href="/developers/sdk-reference/tasks">
    Create, stream, stop and read tasks
  </Card>

  <Card title="Skills Repository" icon="wrench" href="/developers/sdk-reference/tools">
    Local skill registration, outside services, and skills served over MCP
  </Card>

  <Card title="Knowledge Bases" icon="database" href="/developers/sdk-reference/knowledge-bases">
    Documents in, semantic search out
  </Card>

  <Card title="Events Module" icon="bars-progress" href="/developers/sdk-reference/decorators">
    The decorators the task handler is built from
  </Card>

  <Card title="Configuration" icon="gear" href="/developers/sdk-reference/overview#configuration">
    `Configuration`: API key, organization id, base URL, self-hosted endpoints
  </Card>

  <Card title="Types" icon="code" href="/developers/sdk-reference/overview#types">
    Data types, enumerations, and models used across the SDK
  </Card>
</CardGroup>

## Authentication

Credentials reach the SDK one of these ways:

<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.module_exception 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="Quickstart" icon="graduation-cap" href="/developers/quickstart">
    Step-by-step guide to a first agent
  </Card>

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


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.