The xpander.ai SDK provides methods for managing agent executions through the Agent class. An execution represents a task assigned to an agent, along with its status and results.

Task Management

Each execution starts with a task assigned to an agent.

add_task() / addTask()

Assigns a new task to the agent, creating a new execution.

from xpander_sdk import XpanderClient

# Initialize client and get agent
xpander_client = XpanderClient(api_key="your-api-key")
agent = xpander_client.agents.get(agent_id="agent-1234")

# Add a task
agent.add_task(
    input="Research the impact of quantum computing on cryptography",
    use_worker=True
)

print(f"Added task with execution ID: {agent.execution.id}")

Parameters

ParameterTypeRequiredDescription
inputstringYesThe task description or user message
filesList[Dict]NoFiles to attach to the task
use_workerbooleanNoWhether to use a worker for execution (default: True)
thread_idstringNoThread ID for connecting related executions

Returns

The add_task() / addTask() method doesn’t return a value directly, but it initializes the agent’s execution property with the new execution.

Checking Execution Status

is_finished() / isFinished()

Checks if the current execution has finished.

# Check if execution is finished
if agent.is_finished():
    print("The task has been completed")
    result = agent.retrieve_execution_result()
    print(f"Result: {result.result}")
else:
    print("The task is still in progress")
    print(f"Current status: {agent.execution.status}")

Parameters

This method doesn’t require any parameters.

Returns

Returns a boolean value: True if the execution has finished, False otherwise.

get_execution_status() / getExecutionStatus()

Fetches the latest status of the current execution.

# Get the current execution status
status = agent.get_execution_status()

print(f"Execution ID: {status.id}")
print(f"Status: {status.status}")
print(f"Created at: {status.created_at}")
print(f"Updated at: {status.updated_at}")

Parameters

This method doesn’t require any parameters.

Returns

Returns an updated Execution object with the latest status information.

Retrieving Results

retrieve_execution_result() / retrieveExecutionResult()

Retrieves the result of a completed execution.

# Get the result of a completed execution
result = agent.retrieve_execution_result()

print(f"Status: {result.status}")

if result.status == "COMPLETED":
    print(f"Result: {result.result}")
elif result.status == "FAILED":
    print(f"Error: {result.error}")
else:
    print(f"Execution is {result.status}")

Parameters

This method doesn’t require any parameters.

Returns

Returns an ExecutionResult object containing:

  • status: The execution status (“COMPLETED”, “FAILED”, etc.)
  • result: The result content (if completed successfully)
  • error: Error details (if execution failed)

Managing Multiple Executions

list_executions() / listExecutions()

Lists executions for the current agent.

# List executions for the agent
executions = agent.list_executions()

print(f"Found {len(executions)} executions:")
for execution in executions:
    print(f"- {execution.id}: {execution.status} (created: {execution.created_at})")

Parameters

This method doesn’t require any parameters.

Returns

Returns a list of Execution objects.

get_execution() / getExecution()

Gets an execution by ID.

# Get a specific execution
execution_id = "execution-1234"
execution = agent.get_execution(execution_id=execution_id)

print(f"Execution: {execution.id}")
print(f"Status: {execution.status}")
print(f"Input message: {execution.input_message}")

Parameters

ParameterTypeRequiredDescription
execution_idstringYesID of the execution

Returns

Returns an Execution object.

Complete Flow Example

from xpander_sdk import XpanderClient, LLMProvider
from openai import OpenAI
import os
import time

# Initialize clients
xpander_client = XpanderClient(api_key=os.environ["XPANDER_API_KEY"])
openai_client = OpenAI(api_key=os.environ["OPENAI_API_KEY"])

# Get the agent
agent = xpander_client.agents.get(agent_id=os.environ["AGENT_ID"])
print(f"Agent: {agent.name}")

# Add a task
agent.add_task(input="What are the top 3 emerging technologies of 2023?")
print(f"Added task with execution ID: {agent.execution.id}")

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

# Run the agent until the task is complete
max_iterations = 10
current_iteration = 0

while not agent.is_finished() and current_iteration < max_iterations:
    current_iteration += 1
    print(f"\nIteration {current_iteration}")
    
    # Get current status
    status = agent.get_execution_status()
    print(f"Status: {status.status}")
    
    # Get next action from LLM
    response = openai_client.chat.completions.create(
        model="gpt-4o",
        messages=agent.messages,
        tools=agent.get_tools(),
        tool_choice="auto",
        temperature=0.0
    )
    
    # Add LLM response to memory
    agent.add_messages(messages=response.model_dump())
    
    # Extract and run tool calls
    tool_calls = XpanderClient.extract_tool_calls(
        llm_response=response.model_dump(),
        llm_provider=LLMProvider.OPEN_AI
    )
    
    if tool_calls:
        results = agent.run_tools(tool_calls=tool_calls)
        print(f"Executed {len(results)} tools")
    else:
        print("No tools were called in this iteration")
    
    # Short delay to prevent rate limiting
    time.sleep(1)

# Get final result
result = agent.retrieve_execution_result()

if agent.is_finished():
    print("\nFINAL RESULT:")
    print("=" * 50)
    print(result.result)
else:
    print("\nMaximum iterations reached before completion")
    print(f"Current status: {agent.get_execution_status().status}")