from xpander_sdk import XpanderClient# Initialize with an API keyclient = XpanderClient(api_key="your-xpander-api-key")# Or, using an environment variableimport osfrom dotenv import load_dotenvload_dotenv()# Load environment variables from .env fileclient = XpanderClient(api_key=os.environ.get("XPANDER_API_KEY"))
# Get an agent by IDagent = client.agents.get(agent_id="agent-1234")print(f"Retrieved agent: {agent.name}")print(f"Instructions: {agent.instructions[:100]}...")# Print first 100 chars
# Create a new agentagent = 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})")
# Update an agentupdated_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}")
# List all available operationsoperations = client.operations.list()print(f"Found {len(operations)} operations:")for op in operations:print(f"- {op.name} ({op.id})")print(f" Description: {op.description}")
# Get an operation by IDoperation = client.operations.get(operation_id="op-1234")print(f"Retrieved operation: {operation.name}")print(f"Description: {operation.description}")print(f"Function: {operation.function}")
Static method to extract tool calls from an LLM response.
from xpander_sdk import XpanderClient, LLMProviderfrom openai import OpenAI# Initialize OpenAI clientopenai_client = OpenAI(api_key="your-openai-api-key")# Get a response from OpenAI with tool callsresponse = 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 callstool_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}")
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 callslocal_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}")
from xpander_sdk import XpanderClient, LLMProviderfrom openai import OpenAIimport osfrom dotenv import load_dotenv# Load environment variablesload_dotenv()XPANDER_API_KEY = os.environ["XPANDER_API_KEY"]OPENAI_API_KEY = os.environ["OPENAI_API_KEY"]# Initialize clientsxpander_client = XpanderClient(api_key=XPANDER_API_KEY)openai_client = OpenAI(api_key=OPENAI_API_KEY)# List all agentsagents = xpander_client.agents.list()print(f"Found {len(agents)} existing agents")# Create a new agent if none existifnot 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 operationsoperations = xpander_client.operations.list()# Find web search operationweb_search_op =next((op for op in operations if"web"in op.name.lower()),None)# Attach web search operation if foundif 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 agentagent.add_task(input="What are the latest developments in quantum computing?")# Initialize memoryagent.memory.init_messages(input=agent.execution.input_message, instructions=agent.instructions)# Run the 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)# Execute tools if anyif tool_calls: results = agent.run_tools(tool_calls=tool_calls)print(f"Executed {len(results)} tools")# Get the final resultresult = agent.retrieve_execution_result()print("\nRESEARCH FINDINGS:")print("="*50)print(result.result)