The xpander.ai SDK is a powerful library that allows you to build, manage, and deploy AI agents with function calling capabilities. The SDK provides a clean, intuitive interface for working with the xpander.ai platform, enabling you to create agents that can perform complex tasks by combining LLMs with tools.
from xpander_sdk import XpanderClientfrom dotenv import load_dotenvimport os# Load API key from environmentload_dotenv()XPANDER_API_KEY = os.environ.get("XPANDER_API_KEY")# Initialize clientclient = XpanderClient(api_key=XPANDER_API_KEY)
2
Get or create an agent
Copy
# List your agentsagents = client.agents.list()# Get an existing agentif agents: agent = client.agents.get(agent_id=agents[0].id)else:# Create a new agent agent = client.agents.create( name="Research Assistant", description="An agent that performs research tasks", instructions="You are a helpful research assistant. Provide accurate information and cite sources.")
3
Run a task
Copy
from xpander_sdk import LLMProviderfrom openai import OpenAI# OpenAI client for LLM interactionsopenai_client = OpenAI(api_key=os.environ.get("OPENAI_API_KEY"))# Add a taskagent.add_task(input="What are the environmental benefits of renewable energy?")# Initialize memoryagent.memory.init_messages(input=agent.execution.input_message, instructions=agent.instructions, llm_provider=LLMProvider.OPEN_AI)# Run until completionwhilenot agent.is_finished():# 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")# Get resultsresult = agent.retrieve_execution_result()print(result.result)
Tasks are assigned to agents using the add_task() method (Python) or addTask() method (TypeScript). Each task creates an execution, which represents a single run of the agent with a specific input.
The xpander.ai SDK provides a powerful system for function calling, allowing agents to invoke both remote tools (hosted on the xpander.ai platform) and local tools (functions defined in your application).
from xpander_sdk import XpanderClient, LLMProviderfrom openai import OpenAIfrom dotenv import load_dotenvimport osimport time# Load environment variablesload_dotenv()XPANDER_API_KEY = os.environ.get("XPANDER_API_KEY")OPENAI_API_KEY = os.environ.get("OPENAI_API_KEY")# Initialize clientsxpander_client = XpanderClient(api_key=XPANDER_API_KEY)openai_client = OpenAI(api_key=OPENAI_API_KEY)# Create or get agentagent = xpander_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 from the web, summarize content, and answer questions accurately.")# Add a research taskagent.add_task(input="What are the latest advancements in renewable energy?")# Initialize memoryagent.memory.init_messages(input=agent.execution.input_message, instructions=agent.instructions)# Run until completionwhilenot 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 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")# Short delay to prevent rate limiting time.sleep(0.5)# Get resultsresult = agent.retrieve_execution_result()print(result.result)
from xpander_sdk import XpanderClient, LLMProvider, ToolCallType, ToolCallResultfrom openai import OpenAIfrom dotenv import load_dotenvimport osimport timeimport math# Load environment variablesload_dotenv()XPANDER_API_KEY = os.environ.get("XPANDER_API_KEY")OPENAI_API_KEY = os.environ.get("OPENAI_API_KEY")# Initialize clientsxpander_client = XpanderClient(api_key=XPANDER_API_KEY)openai_client = OpenAI(api_key=OPENAI_API_KEY)# Create a calculator agentagent = xpander_client.agents.create( name="Calculator Assistant", description="An agent that can perform calculations", instructions="You are a helpful assistant that can perform mathematical calculations.")# Define a local tool for calculationsdefcalculate(expression):"""Safely evaluate a mathematical expression."""try:# Define allowed symbols and functions allowed_names ={"abs":abs,"round":round,"min":min,"max":max,"sum":sum,"pow":pow,"math": math}# Evaluate the expression in a safe way result =eval(expression,{"__builtins__":{}}, allowed_names)return ToolCallResult( function_name="calculate", tool_call_id="some_id", is_success=True, result=str(result))except Exception as e:return ToolCallResult( function_name="calculate", tool_call_id="some_id", is_success=False, error=f"Error evaluating expression: {str(e)}")# Register the local tool handleragent.register_local_tool_handler(tool_name="calculate", handler=calculate)# Add a taskagent.add_task(input="I need to calculate the area of a circle with radius 5 cm and also the volume of a sphere with the same radius.")# Initialize memoryagent.memory.init_messages(input=agent.execution.input_message, instructions=agent.instructions)# Run agent loopwhilenot 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)# Filter for local tool calls local_tool_calls = XpanderClient.retrieve_pending_local_tool_calls( tool_calls=tool_calls)# Run local toolsif local_tool_calls: results = agent.run_tools(tool_calls=local_tool_calls)print(f"Executed {len(results)} calculations")# Get resultresult = agent.retrieve_execution_result()print(result.result)