The XpanderClient is the main entry point for the xpander.ai SDK, providing access to agents, tools, and other resources on the xpander.ai platform.

Initialization

from xpander_sdk import XpanderClient

# Initialize with an API key
client = XpanderClient(api_key="your-xpander-api-key")

# Or, using an environment variable
import os
from dotenv import load_dotenv

load_dotenv()  # Load environment variables from .env file
client = XpanderClient(api_key=os.environ.get("XPANDER_API_KEY"))

Parameters

ParameterTypeRequiredDescription
api_keystringYesYour xpander.ai API key

Working with Agents

agents.list()

Lists all agents in your workspace.

# List all available agents
agents = client.agents.list()

print(f"Found {len(agents)} agents:")
for agent in agents:
    print(f"- {agent.name} ({agent.id})")

Returns

Returns an array of Agent objects.

agents.get()

Retrieves a specific agent by ID.

# Get an agent by ID
agent = client.agents.get(agent_id="agent-1234")

print(f"Retrieved agent: {agent.name}")
print(f"Instructions: {agent.instructions[:100]}...")  # Print first 100 chars

Parameters

ParameterTypeRequiredDescription
agent_idstringYesID of the agent

Returns

Returns an Agent object.

agents.create()

Creates a new agent.

# Create a new agent
agent = client.agents.create(
    name="Research Assistant",
    description="AI assistant for research tasks",
    instructions="You are a helpful research assistant. Your task is to help users find information, summarize content, and analyze data related to their research questions."
)

print(f"Created agent: {agent.name} ({agent.id})")

Parameters

ParameterTypeRequiredDescription
namestringYesName of the agent
descriptionstringNoDescription of the agent’s purpose
instructionsstringYesSystem instructions for the agent

Returns

Returns the newly created Agent object.

agents.update()

Updates an existing agent.

# Update an agent
updated_agent = client.agents.update(
    agent_id="agent-1234",
    name="Enhanced Research Assistant",
    description="Improved AI assistant for advanced research tasks",
    instructions="You are an expert research assistant with advanced capabilities..."
)

print(f"Updated agent: {updated_agent.name}")

Parameters

ParameterTypeRequiredDescription
agent_idstringYesID of the agent to update
namestringNoNew name for the agent
descriptionstringNoNew description
instructionsstringNoNew system instructions

Returns

Returns the updated Agent object.

agents.delete()

Deletes an agent.

# Delete an agent
result = client.agents.delete(agent_id="agent-1234")

if result:
    print("Agent deleted successfully")
else:
    print("Failed to delete agent")

Parameters

ParameterTypeRequiredDescription
agent_idstringYesID of the agent to delete

Returns

Returns a boolean indicating success (true) or failure (false).

Working with Operations

Operations are pre-built tools that can be attached to agents.

operations.list()

Lists all available operations.

# List all available operations
operations = client.operations.list()

print(f"Found {len(operations)} operations:")
for op in operations:
    print(f"- {op.name} ({op.id})")
    print(f"  Description: {op.description}")

Returns

Returns an array of Operation objects.

operations.get()

Retrieves a specific operation by ID.

# Get an operation by ID
operation = client.operations.get(operation_id="op-1234")

print(f"Retrieved operation: {operation.name}")
print(f"Description: {operation.description}")
print(f"Function: {operation.function}")

Parameters

ParameterTypeRequiredDescription
operation_idstringYesID of the operation

Returns

Returns an Operation object.

Static Methods

extract_tool_calls() / extractToolCalls()

Static method to extract tool calls from an LLM response.

from xpander_sdk import XpanderClient, LLMProvider
from openai import OpenAI

# Initialize OpenAI client
openai_client = OpenAI(api_key="your-openai-api-key")

# Get a response from OpenAI with tool calls
response = openai_client.chat.completions.create(
    model="gpt-4o",
    messages=[{"role": "user", "content": "Search for information about AI safety"}],
    tools=[{
        "type": "function",
        "function": {
            "name": "web_search",
            "description": "Search the web for information",
            "parameters": {
                "type": "object",
                "properties": {
                    "query": {
                        "type": "string",
                        "description": "The search query"
                    }
                },
                "required": ["query"]
            }
        }
    }],
    tool_choice="auto"
)

# Extract tool calls
tool_calls = XpanderClient.extract_tool_calls(
    llm_response=response.model_dump(),
    llm_provider=LLMProvider.OPEN_AI
)

print(f"Extracted {len(tool_calls)} tool calls")
for tc in tool_calls:
    print(f"Tool: {tc.name}")
    print(f"Payload: {tc.payload}")
    print(f"Type: {tc.type}")

Parameters

ParameterTypeRequiredDescription
llm_responseobjectYesThe LLM response object
llm_providerLLMProviderYesThe provider used to generate response

Returns

Returns an array of ToolCall objects extracted from the LLM response.

retrieve_pending_local_tool_calls() / retrievePendingLocalToolCalls()

Static method to filter tool calls and retrieve only the local ones.

from xpander_sdk import XpanderClient, LLMProvider

# Assuming we already have some tool calls extracted
# Extract local tool calls
local_tool_calls = XpanderClient.retrieve_pending_local_tool_calls(
    tool_calls=tool_calls
)

print(f"Found {len(local_tool_calls)} local tool calls")
for tc in local_tool_calls:
    print(f"Local tool: {tc.name}")
    print(f"Payload: {tc.payload}")

Parameters

ParameterTypeRequiredDescription
tool_callsList/Array[ToolCall]YesList of tool calls to filter

Returns

Returns a filtered list/array containing only local ToolCall objects.

Complete Example

from xpander_sdk import XpanderClient, LLMProvider
from openai import OpenAI
import os
from dotenv import load_dotenv

# Load environment variables
load_dotenv()
XPANDER_API_KEY = os.environ["XPANDER_API_KEY"]
OPENAI_API_KEY = os.environ["OPENAI_API_KEY"]

# Initialize clients
xpander_client = XpanderClient(api_key=XPANDER_API_KEY)
openai_client = OpenAI(api_key=OPENAI_API_KEY)

# List all agents
agents = xpander_client.agents.list()
print(f"Found {len(agents)} existing agents")

# Create a new agent if none exist
if not agents:
    print("Creating a new agent...")
    agent = xpander_client.agents.create(
        name="Web Research Assistant",
        description="An agent that helps with web research",
        instructions="You are a helpful research assistant. Your task is to find accurate information from the web to answer user queries."
    )
else:
    # Get the first agent
    agent = xpander_client.agents.get(agent_id=agents[0].id)
    print(f"Using existing agent: {agent.name}")

# List all operations
operations = xpander_client.operations.list()

# Find web search operation
web_search_op = next((op for op in operations if "web" in op.name.lower()), None)

# Attach web search operation if found
if web_search_op:
    print(f"Attaching web search operation: {web_search_op.name}")
    agent.attach_operations(operation_ids=[web_search_op.id])

# Add a task to the agent
agent.add_task(input="What are the latest developments in quantum computing?")

# Initialize memory
agent.memory.init_messages(
    input=agent.execution.input_message,
    instructions=agent.instructions
)

# Run the agent loop
while not agent.is_finished():
    # Get next action from LLM
    response = openai_client.chat.completions.create(
        model="gpt-4o",
        messages=agent.messages,
        tools=agent.get_tools(llm_provider=LLMProvider.OPEN_AI),
        tool_choice="auto",
        temperature=0.0
    )
    
    # Add LLM response to memory
    agent.add_messages(messages=response.model_dump())
    
    # Extract tool calls
    tool_calls = XpanderClient.extract_tool_calls(
        llm_response=response.model_dump(),
        llm_provider=LLMProvider.OPEN_AI
    )
    
    # Execute tools if any
    if tool_calls:
        results = agent.run_tools(tool_calls=tool_calls)
        print(f"Executed {len(results)} tools")

# Get the final result
result = agent.retrieve_execution_result()
print("\nRESEARCH FINDINGS:")
print("=" * 50)
print(result.result)