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

# Backend Module Reference

> Complete API reference for the Backend module including runtime argument resolution and framework integration

## Environment Variable Support

The Backend module supports automatic agent ID detection from environment variables, eliminating the need to explicitly provide the agent ID in many scenarios.

### Supported Environment Variables

* **`XPANDER_AGENT_ID`**: The agent identifier that will be used when no `agent_id` or `agent` parameter is provided to the methods.

### Environment Variable Usage

```python theme={"dark"}
import os
from xpander_sdk import Backend

# Set the environment variable
os.environ["XPANDER_AGENT_ID"] = "agent-123"

backend = Backend()

# No need to specify agent_id - it will be auto-detected
args = await backend.aget_args()
print(f"Arguments resolved for agent: {args}")
```

**Note**: If both an environment variable and explicit parameters are provided, the explicit parameters take precedence.

## Introduction

The **Backend Module** provides comprehensive functionality for retrieving agent runtime arguments for execution within the xpander.ai platform. This module supports multiple AI frameworks and dispatches agent arguments accordingly.

## Overview

In this module, you can:

* Resolve runtime arguments for agents with framework-specific configurations
* Support multiple AI frameworks through intelligent dispatching
* Handle both asynchronous and synchronous argument resolution
* Override default configurations with custom parameters
* Integrate with tasks for context-aware argument generation
* Monitor task execution in real-time with event callbacks

## Examples

### Basic Agent Arguments Resolution

This example demonstrates how to resolve runtime arguments for an agent in both asynchronous and synchronous styles.

#### Asynchronous Example

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

backend = Backend()

# Resolve arguments by agent ID
args = await backend.aget_args(agent_id="agent-123")
print(f"Resolved arguments: {args}")

# Use resolved arguments with your framework
# For example, with Agno framework:
from agno import Agent as AgnoAgent
agent = AgnoAgent(**args)
```

#### Synchronous Example

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

backend = Backend()

# Resolve arguments by agent ID
args = backend.get_args(agent_id="agent-123")
print(f"Resolved arguments: {args}")

# Use resolved arguments with your framework
from agno import Agent as AgnoAgent
agent = AgnoAgent(**args)
```

### Using Pre-loaded Agent Instance

When you already have an Agent instance, you can use it directly for more efficient argument resolution.

#### Asynchronous Example

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

agents = Agents()
backend = Backend()

# Load agent first
agent = await agents.aget("agent-123")

# Resolve arguments using the loaded agent
args = await backend.aget_args(agent=agent)
print(f"Agent: {agent.name}")
print(f"Arguments: {args}")
```

#### Synchronous Example

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

agents = Agents()
backend = Backend()

# Load agent first
agent = agents.get("agent-123")

# Resolve arguments using the loaded agent
args = backend.get_args(agent=agent)
print(f"Agent: {agent.name}")
print(f"Arguments: {args}")
```

### Task Context Integration

Include task context for runtime-aware argument resolution.

#### Asynchronous Example

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

agents = Agents()
backend = Backend()

# Load agent and create task
agent = await agents.aget("agent-123")
task = await agent.acreate_task(
    prompt="Analyze this dataset",
    output_format="json"
)

# Resolve arguments with task context
args = await backend.aget_args(
    agent=agent,
    task=task
)

# Arguments will include task-specific configurations
print(f"Task-aware arguments: {args}")
```

#### Synchronous Example

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

agents = Agents()
backend = Backend()

# Load agent and create task
agent = agents.get("agent-123")
task = agent.create_task(
    prompt="Analyze this dataset",
    output_format="json"
)

# Resolve arguments with task context
args = backend.get_args(
    agent=agent,
    task=task
)

print(f"Task-aware arguments: {args}")
```

### Custom Overrides

Override default configurations with custom parameters.

#### Asynchronous Example

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

backend = Backend()

# Define custom overrides
custom_overrides = {
    "model": "gpt-4",
    "temperature": 0.7,
    "max_tokens": 2000,
    "show_tool_calls": False
}

# Resolve arguments with overrides
args = await backend.aget_args(
    agent_id="agent-123",
    override=custom_overrides
)

print(f"Custom arguments: {args}")
```

#### Synchronous Example

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

backend = Backend()

# Define custom overrides
custom_overrides = {
    "model": "claude-3-sonnet",
    "temperature": 0.3,
    "use_json_mode": True
}

# Resolve arguments with overrides
args = backend.get_args(
    agent_id="agent-123",
    override=custom_overrides
)

print(f"Custom arguments: {args}")
```

### Authentication Events Callback

Handle authentication events in real-time by providing an event callback function. This callback is triggered **only** for authentication flows (e.g., MCP OAuth requiring user login).

**You can use both approaches simultaneously** - decorated handlers are auto-registered and always invoked, and you can also pass an explicit callback for additional per-call handling.

#### Option 1: Direct Callback (Per-call)

```python theme={"dark"}
from xpander_sdk import Backend, Agent, Task
from xpander_sdk.models.tasks.task_update_event import TaskUpdateEvent

backend = Backend()

# Define async event callback
async def my_event_callback(agent: Agent, task: Task, event: TaskUpdateEvent):
    # event.type will always be "auth_event"
    print(f"Authentication required: {event.data}")
    # Display login URL or handle OAuth flow

# Pass callback to aget_args
args = await backend.aget_args(
    agent_id="agent-123",
    auth_events_callback=my_event_callback
)
```

#### Option 2: Decorator (Auto-registered)

```python theme={"dark"}
from xpander_sdk import Backend, on_auth_event, Agent, Task
from xpander_sdk.models.tasks.task_update_event import TaskUpdateEvent

backend = Backend()

# Use decorator - auto-registers globally
@on_auth_event
async def handle_auth(agent: Agent, task: Task, event: TaskUpdateEvent):
    # event.type will always be "auth_event"
    print(f"Authentication required: {event.data}")

# Decorated handler is automatically invoked - no need to pass it
args = await backend.aget_args(
    agent_id="agent-123"
)
```

#### Option 3: Combine Both

```python theme={"dark"}
from xpander_sdk import Backend, on_auth_event

# Global handler for all auth events
@on_auth_event
async def log_all_auth(agent, task, event):
    print(f"[GLOBAL] Auth event")

# Additional one-time handler
async def custom_handler(agent, task, event):
    print(f"[CUSTOM] Specific handling")

# Both handlers will be invoked
args = await backend.aget_args(
    agent_id="agent-123",
    auth_events_callback=custom_handler
)
```

**Callback Parameters:**

* **`agent`**: The Agent object associated with the task
* **`task`**: The Task object being executed
* **`event`**: A TaskUpdateEvent containing:
  * `type`: Event type (always "auth\_event" for authentication flows)
  * `time`: Timestamp of the event
  * `data`: Authentication-specific data (e.g., OAuth login URL, token status)

### Framework-Specific Usage

The Backend module automatically detects the agent's framework and provides appropriate arguments.

#### Agno Framework Example

```python theme={"dark"}
from xpander_sdk import Backend
from agno import Agent as AgnoAgent

backend = Backend()

# Resolve arguments for Agno framework agent
args = await backend.aget_args(agent_id="agno-agent-123")

# Create Agno agent with resolved arguments
agno_agent = AgnoAgent(**args)

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

***

Continue to the \[Backend API Reference] for detailed documentation on classes and methods.

## Related Documentation

<CardGroup cols={2}>
  <Card title="Agents Module" icon="robot" href="/API reference/agents">
    Agent management and interaction
  </Card>

  <Card title="Tasks Module" icon="play" href="/API reference/tasks">
    Task execution and management
  </Card>

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

  <Card title="Types" icon="code" href="/API reference/types">
    Data types and models
  </Card>
</CardGroup>

## Support

For additional help:

* Full [SDK Documentation](https://docs.xpander.ai)
* Email: [dev@xpander.ai](mailto:dev@xpander.ai)
