### Setup Virtual Environment and SDK Source: https://docs.xpander.ai/Examples/01-simple-hello-world Commands to initialize a Python virtual environment and install the necessary xpander-sdk dependencies. This is the prerequisite step for all Xpander agent development. ```bash python3 -m venv .venv source .venv/bin/activate pip install "xpander-sdk[agno]" ``` -------------------------------- ### Quick Setup Guide Source: https://docs.xpander.ai/api-reference/mcp A step-by-step guide to setting up the MCP integration, including obtaining an API key, configuring Claude Desktop, and testing the connection. ```APIDOC ## Quick Setup Follow these steps to quickly set up the MCP integration: 1. **Get Your API Key:** Obtain your API key from [app.xpander.ai](https://app.xpander.ai). 2. **Add to Claude Desktop:** Edit `~/Library/Application Support/Claude/claude_desktop_config.json` with the following configuration, replacing `YOUR_API_KEY`: ```json { "mcpServers": { "xpander.ai": { "command": "npx", "args": [ "-y", "mcp-remote@latest", "https://api.xpander.ai/mcp/", "--header", "x-api-key:YOUR_API_KEY" ] } } } ``` 3. **Restart Claude Desktop:** Close and reopen Claude Desktop to apply the changes. 4. **Test the Connection:** Interact with Claude by asking questions like "What agents are available?" or "List my tools." ``` -------------------------------- ### Install Xpander CLI Source: https://docs.xpander.ai/Examples/00-setup-deployment Installs the Xpander command-line interface globally using npm. This tool is required to manage agents and perform deployments. ```bash npm install -g xpander-cli ``` -------------------------------- ### Initialize New Agent Project Source: https://docs.xpander.ai/Examples/00-setup-deployment Scaffolds a new agent project directory containing the necessary handler files, dependency manifests, and deployment configurations. ```bash xpander agent new ``` -------------------------------- ### Configure Local Development Environment Source: https://docs.xpander.ai/Examples/00-setup-deployment Sets up a Python virtual environment and installs project dependencies. This ensures that the agent runs in an isolated environment. ```bash python3 -m venv .venv source .venv/bin/activate pip install -r requirements.txt ``` -------------------------------- ### Setup Virtual Environment and Project Initialization Source: https://docs.xpander.ai/Examples/05-custom-tools-integration Commands to create a Python virtual environment, install the xpander-sdk, and initialize the project structure including the .env file. ```bash python3 -m venv .venv source .venv/bin/activate pip install "xpander-sdk[agno]" xpander init ``` -------------------------------- ### Setup Python Virtual Environment and Install Dependencies Source: https://docs.xpander.ai/Examples/5-minute-wins/stateful-agents These bash commands set up a Python virtual environment named '.venv', activate it, and then install the project's Python dependencies listed in 'requirements.txt'. It also includes exporting the OpenAI API key, which is necessary for the agent to function. ```bash python3 -m venv .venv && source .venv/bin/activate pip install -r requirements.txt export OPENAI_API_KEY="your-key" ``` -------------------------------- ### Run Python Session Management Example Source: https://docs.xpander.ai/Examples/07-session-management This command executes the Python script for session management. Ensure you have completed the setup steps before running this command. ```bash python session_management_example.py ``` -------------------------------- ### Install and Login to Xpander CLI Source: https://docs.xpander.ai/user-guide/run/agent-containers Installs the Xpander CLI globally using npm and logs the user in. This is the first step to using Xpander AI. ```bash npm install -g xpander-cli && xpander login ``` -------------------------------- ### Deploy Agent to Production Source: https://docs.xpander.ai/Examples/00-setup-deployment Uploads and deploys the configured agent to the Xpander platform. Once deployed, the agent is ready to process tasks via the dashboard or API. ```bash xpander deploy ``` -------------------------------- ### Run Google ADK Agent with Xpander SDK Source: https://docs.xpander.ai/user-guide/build/frameworks This Python example illustrates how to connect Xpander AI with the Google ADK framework. It retrieves agent configuration from Xpander, sets up the ADK agent with a LiteLlm model, and uses a Runner to stream events from the agent for task processing. ```python from xpander_sdk import Task, on_task, Agents, Configuration from google.adk.models.lite_llm import LiteLlm from google.adk.agents import Agent from google.adk.runners import Runner from google.adk.sessions import InMemorySessionService from google.genai import types @on_task( Configuration( api_key="{XPANDER_API_KEY}", organization_id="{XPANDER_ORGANIZATION_ID}", agent_id="{XPANDER_AGENT_ID}" ) ) async def my_agent_handler(task: Task): # Fetch agent configuration from xpander xpander_agent = await Agents(configuration=task.configuration).aget() # Initialize ADK with xpander's configuration adk_agent = Agent( name=xpander_agent.sanitized_name, model=LiteLlm(model=f"{xpander_agent.model_provider}/{xpander_agent.model_name}"), description=xpander_agent.instructions.description, instruction=xpander_agent.instructions.full, tools=xpander_agent.tools.functions, ) session_service = InMemorySessionService() await session_service.create_session( app_name=xpander_agent.sanitized_name, user_id=task.input.user.id if task.input.user else "user_id", session_id=task.id, ) runner = Runner( agent=adk_agent, app_name=xpander_agent.sanitized_name, session_service=session_service, ) content = types.Content( role="user", parts=[types.Part(text=task.to_message())], ) final_answer = "" # Stream events from the agent async for event in runner.run_async( user_id=task.input.user.id if task.input.user else "user_id", new_message=content, session_id=task.id ): if event.is_final_response() and event.content and event.content.parts: ``` -------------------------------- ### Install Xpander SDK Source: https://docs.xpander.ai/api-reference/sdk Installation instructions for the Xpander SDK using pip, including optional dependencies for specific frameworks and development environments. ```bash pip install xpander-sdk # With optional dependencies pip install xpander-sdk[agno] # For Agno framework support pip install xpander-sdk[dev] # For development ``` -------------------------------- ### Initialize Xpander Project Source: https://docs.xpander.ai/Examples/01-simple-hello-world Uses the Xpander CLI to download agent code and pre-configured environment variables. This command ensures the local environment is synced with the platform's configuration. ```bash xpander init ``` -------------------------------- ### Example Task Thread Response - JSON Source: https://docs.xpander.ai/api-reference/v1/tasks/get-thread This is an example of the JSON response returned by the Get Task Thread API. It illustrates the structure of the conversation thread, including message IDs, roles, content, creation timestamps, and token usage metrics. ```json [ { "id": "", "role": "user", "content": "Hi, my name is David and I work at xpander.ai", "metrics": { "input_tokens": 0, "output_tokens": 0, "total_tokens": 0 }, "created_at": 1738945492 }, { "id": "", "role": "assistant", "content": "Hi David! Welcome. I'm here to help you with any questions or support needs. It's great to meet someone from the xpander.ai team!", "metrics": { "input_tokens": 247, "output_tokens": 2102, "total_tokens": 2349 }, "created_at": 1738945495 }, { "id": "", "role": "user", "content": "What is my name and where do I work?", "metrics": { "input_tokens": 0, "output_tokens": 0, "total_tokens": 0 }, "created_at": 1738945500 }, { "id": "", "role": "assistant", "content": "Your name is David and you work at xpander.ai.", "metrics": { "input_tokens": 165, "output_tokens": 2277, "total_tokens": 2442 }, "created_at": 1738945505 } ] ``` -------------------------------- ### Create Stateful AI Agent Source: https://docs.xpander.ai/Examples/01-simple-hello-world Demonstrates how to initialize the Xpander Backend and instantiate an Agno agent. The code shows how to leverage automatic configuration and verify stateful memory by asking follow-up questions. ```python from dotenv import load_dotenv load_dotenv() from xpander_sdk import Backend from agno.agent import Agent # Initialize Xpander Backend backend = Backend() # Create agent with backend configuration agno_agent = Agent(**backend.get_args()) # Test stateful conversation agno_agent.print_response(message="What's your role?") agno_agent.print_response(message="What did I ask you?") ``` -------------------------------- ### Initialize and Run Xpander Agents Source: https://docs.xpander.ai/user-guide/build/system-prompt Demonstrates how to initialize the Xpander SDK for local development and production environments. The local example shows basic agent configuration, while the production example utilizes the @on_task decorator for asynchronous task handling and automatic context injection. ```python from xpander_sdk import Backend, Configuration from agno.agent import Agent backend = Backend(configuration=Configuration(api_key="")) agno_agent = Agent(**backend.get_args(agent_id="")) # View configured instructions print(agno_agent.instructions) # Override instructions if needed agno_agent.instructions = [ "Always respond in JSON format", "Use technical language", "Include code examples" ] agno_agent.print_response(input="Explain async/await") ``` ```python from dotenv import load_dotenv load_dotenv() from xpander_sdk import Task, on_task, Backend, Tokens from agno.agent import Agent @on_task async def my_agent_handler(task: Task): backend = Backend(configuration=task.configuration) agno_args = await backend.aget_args(task=task) agno_agent = Agent(**agno_args) # Run agent with full production system prompt result = await agno_agent.arun( input=task.to_message(), user_id=task.user_id, session_id=task.session_id ) task.result = result.content task.tokens = Tokens( prompt_tokens=result.metrics.input_tokens, completion_tokens=result.metrics.output_tokens ) return task ``` -------------------------------- ### Xpander CLI for Local Agent Development Source: https://docs.xpander.ai/user-guide/build/frameworks This bash snippet shows how to install and run the Xpander CLI for local agent development. The `xpander agent dev [agent-name]` command connects to the Xpander platform, allowing the agent to access tools, prompts, and task handling functionalities locally. It also provides examples of how to invoke the agent via Web UI, API, SDK, and CLI. ```bash # Install the xpander CLI npm install -g xpander-cli # Run agent locally - connects to xpander platform for tools, prompts, and task handling xpander agent dev [agent-name] ``` -------------------------------- ### Define Environment Variables Source: https://docs.xpander.ai/Examples/00-setup-deployment Configures the required API keys and identifiers in the .env file. These credentials are necessary for the agent to authenticate with the Xpander platform. ```bash XPANDER_API_KEY=your_xpander_key_here XPANDER_ORGANIZATION_ID=your_org_id_here XPANDER_AGENT_ID=your_agent_id_here ``` -------------------------------- ### Xpander CLI Command Shortcuts Source: https://docs.xpander.ai/api-reference/cli-reference A reference guide for shorthand commands used in authentication, agent management, local development, and cloud deployment. ```bash # Authentication x l # xpander login x c # xpander configure # Control Plane (Agent Management) x a n # xpander agent new x a e [agent] # xpander agent edit x a del [agent] # xpander agent delete x a invoke [agent] "msg" # xpander agent invoke # Local Development x a i [agent] # xpander agent init # Cloud Deployment x a d [agent] # xpander agent deploy x a l [agent] # xpander agent logs ``` -------------------------------- ### Initialize Agno Agent with Xpander SDK Source: https://docs.xpander.ai/user-guide/build/ai-model Demonstrates how to initialize an Agno agent using the Xpander Backend configuration. It covers both the default Workbench configuration and overriding with a local Ollama model. ```python from xpander_sdk import Backend, Configuration from agno.agent import Agent backend = Backend(configuration=Configuration(api_key="")) agno_agent = Agent(**backend.get_args(agent_id="")) # Agent uses the model configured in Workbench agno_agent.print_response(input='What is xpander?') ``` ```python from xpander_sdk import Backend, Configuration from agno.agent import Agent from agno.models.ollama import Ollama backend = Backend(configuration=Configuration(api_key="")) agno_agent = Agent(**backend.get_args(agent_id="")) # Override to use self-hosted model agno_agent.model = Ollama('llama3:8b') agno_agent.print_response(input="What's your role?") ``` -------------------------------- ### Basic SDK Usage with Self-Hosted Backend Source: https://docs.xpander.ai/api-reference/configuration/self-hosted Demonstrates initializing the SDK with a custom configuration and performing basic agent task creation. ```python from xpander_sdk import Configuration, Agent # Configure for self-hosted config = Configuration( api_key="your-agent-controller-api-key", organization_id="your-org-id", base_url="https://agent-controller.my-company.com" ) # Load agent and create task agent = await Agent.aload("agent-123", configuration=config) task = await agent.acreate_task(prompt="Analyze this dataset") print(f"Task created: {task.id}") ``` -------------------------------- ### Process Small Files with Xpander.ai (Bash) Source: https://docs.xpander.ai/api-reference/v1/agents/invoke-sync This example shows how to pass file URLs directly in the `input.files` array for processing. The agent will download and inject the content of these files into the LLM's context window. This method is suitable for small to medium-sized files that fit within the context limit. ```bash curl -s -X POST "https://api.xpander.ai/v1/agents//invoke" \ -H "Content-Type: application/json" \ -H "x-api-key: " \ -d '{ "input": { "text": "What is the abstract of this paper?", "files": ["https://assets.xpanderai.io/static/pdf/bitcoin.pdf"] } }' ``` -------------------------------- ### Initialize Agent Framework with xpander Source: https://docs.xpander.ai/user-guide/build/frameworks Demonstrates the standard workflow for initializing an agentic framework using the xpander backend. This involves retrieving configuration arguments and using the @on_task decorator to handle incoming tasks. ```python from xpander import Backend # 1. Initialize backend backend = Backend() # 2. Get framework-specific configuration config = backend.aget_args() # 3. Initialize your framework with config # my_framework.init(config) # 4. Handle tasks with the decorator @on_task def handle_incoming_task(task): print(f"Processing task: {task}") ``` -------------------------------- ### Retrieve Agent Task Executions via cURL Source: https://docs.xpander.ai/api-reference/v1/agents/get-agent-tasks Examples of how to fetch task lists for an agent using cURL. Includes basic retrieval, status-based filtering, and user-specific filtering. ```bash curl -X GET -H "x-api-key: " \ "https://api.xpander.ai/v1/agents//tasks?page=1&per_page=2" ``` ```bash curl -X GET -H "x-api-key: " \ "https://api.xpander.ai/v1/agents//tasks?status=completed&page=1&per_page=10" ``` ```bash curl -X GET -H "x-api-key: " \ "https://api.xpander.ai/v1/agents//tasks?user_id=&page=1&per_page=10" ``` -------------------------------- ### Add System Dependencies to Dockerfile Source: https://docs.xpander.ai/user-guide/run/agent-containers Example of how to add system-level packages to the agent's Docker image. This Dockerfile snippet includes commands to update package lists and install 'build-essential', 'libpq-dev', and 'ffmpeg'. ```dockerfile FROM python:3.11-slim WORKDIR /app # Install system dependencies RUN apt-get update && apt-get install -y \ build-essential \ libpq-dev \ ffmpeg \ && rm -rf /var/lib/apt/lists/* COPY requirements.txt . RUN pip install --no-cache-dir -r requirements.txt COPY . . CMD ["python", "-m", "xpander_sdk.agent_worker"] ``` -------------------------------- ### Build Agents with Python SDK Source: https://docs.xpander.ai/api-reference Shows how to initialize the Xpander SDK, define asynchronous task handlers using decorators, and manage agent tasks programmatically. ```python from xpander_sdk import Agents, on_task # Initialize SDK agents = Agents() # Define task handler @on_task async def handle_task(task): print(f"Processing: {task.id}") task.result = "Task completed" return task # List and invoke agents agent = await agents.aget("agent-id") task = await agent.acreate_task(prompt="Analyze data") ``` -------------------------------- ### Fetch Task Thread Conversation - Bash Source: https://docs.xpander.ai/api-reference/v1/tasks/get-thread This example demonstrates how to fetch the conversation thread for a specific task using a cURL command. It requires an API key and the task ID. The response is a JSON array of message objects. ```bash curl -X GET -H "x-api-key: " \ "https://api.xpander.ai/v1/tasks//thread" ``` -------------------------------- ### Configure Reasoning Modes via Xpander SDK Source: https://docs.xpander.ai/user-guide/build/reasoning-mode Demonstrates how to initialize the Backend with different reasoning modes and thinking budgets. These configurations control the depth and computational resources allocated to agent reasoning tasks. ```python from xpander_sdk import Backend # Extended Mode backend = Backend( reasoning_mode="extended", thinking_budget=10000 ) # Standard Mode backend = Backend(reasoning_mode="standard") # Deep Mode backend = Backend( reasoning_mode="deep", thinking_budget=20000, allow_reflection=True ) ``` -------------------------------- ### Parse Task Thread JSON with jq - Bash Source: https://docs.xpander.ai/api-reference/v1/tasks/get-thread These examples show how to use the `jq` command-line JSON processor to parse the task thread response. They cover pretty-printing the conversation, calculating total tokens, and extracting only assistant responses. ```bash curl -s -H "x-api-key: " \ "https://api.xpander.ai/v1/tasks//thread" | \ jq '.[] | "\(.role): \(.content)"' ``` ```bash curl -s -H "x-api-key: " \ "https://api.xpander.ai/v1/tasks//thread" | \ jq '[.[].metrics.total_tokens] | add' ``` ```bash curl -s -H "x-api-key: " \ "https://api.xpander.ai/v1/tasks//thread" | \ jq '.[] | select(.role == "assistant") | .content' ``` -------------------------------- ### Example Toolkit Tools Response (JSON) Source: https://docs.xpander.ai/api-reference/v1/toolkits/get-toolkit-tools This JSON structure represents the expected response when fetching toolkit tools. It's an array of tool definitions, each including a name, description, and a JSON Schema for its parameters, adhering to OpenAI's function calling format. ```json [ { "name": "send_message", "description": "Send a message to a Slack channel or user", "parameters": { "type": "object", "properties": { "channel": { "type": "string", "description": "The Slack channel ID or name to send the message to" }, "message": { "type": "string", "description": "The message content to send" }, "thread_ts": { "type": "string", "description": "Optional thread timestamp to reply in a thread" } }, "required": ["channel", "message"] } }, { "name": "get_channels", "description": "List all Slack channels in the workspace", "parameters": { "type": "object", "properties": { "limit": { "type": "integer", "description": "Maximum number of channels to return (default: 20)" } }, "required": [] } }, { "name": "list_users", "description": "Get list of users in the Slack workspace", "parameters": { "type": "object", "properties": { "include_bot_users": { "type": "boolean", "description": "Whether to include bot users (default: false)" } }, "required": [] } } ] ``` -------------------------------- ### GET /tasks Source: https://docs.xpander.ai/api-reference/v1/agents/get-agent-tasks Retrieves a paginated list of task executions associated with an organization or agent. ```APIDOC ## GET /tasks ### Description Retrieves a paginated list of task executions. This endpoint returns a summary of tasks including their status, timestamps, and associated agent IDs. ### Method GET ### Endpoint /tasks ### Query Parameters - **page** (integer) - Optional - Page number for pagination - **per_page** (integer) - Optional - Number of items per page ### Response #### Success Response (200) - **items** (array) - List of TasksListItem objects - **total** (integer) - Total number of tasks - **page** (integer) - Current page number - **per_page** (integer) - Items per page - **total_pages** (integer) - Total number of pages #### Response Example { "items": [ { "id": "task_123", "agent_id": "agent_abc", "status": "completed", "title": "Data Processing Task", "organization_id": "org_001" } ], "total": 1, "page": 1, "per_page": 10, "total_pages": 1 } ``` -------------------------------- ### Create New Agent Project with Xpander CLI Source: https://docs.xpander.ai/user-guide/run/agent-containers Creates a new agent project directory named 'hello-world' and initializes a new agent within it using the 'agno' framework. This command generates essential project files like the agent handler, Dockerfile, and configuration files. ```bash mkdir hello-world && cd hello-world xpander agent new --name "hello-world" --framework agno --folder . ``` -------------------------------- ### GET /v1/misc/db Source: https://docs.xpander.ai/api-reference/v1/misc/get-database Retrieves the PostgreSQL database connection string associated with the authenticated organization. ```APIDOC ## GET /v1/misc/db ### Description Retrieves the PostgreSQL database connection string for your organization. This endpoint requires API key authentication. ### Method GET ### Endpoint https://api.xpander.ai/v1/misc/db ### Parameters #### Headers - **x-api-key** (string) - Required - API Key for authentication ### Request Example ```http GET /v1/misc/db HTTP/1.1 Host: api.xpander.ai x-api-key: YOUR_API_KEY ``` ### Response #### Success Response (200) - **connection_uri** (string) - The connection URI for the PostgreSQL database. #### Response Example { "connection_uri": "postgresql://user:***@host:5432/dbname?sslmode=require" } ``` -------------------------------- ### Initialize SDK Modules Source: https://docs.xpander.ai/api-reference/sdk Demonstrates how to import and initialize the core modules of the Xpander SDK, which automatically utilizes environment variables for authentication. ```python from xpander_sdk import Agents, Tasks, ToolsRepository, KnowledgeBases # SDK automatically uses environment variables # Set XPANDER_API_KEY and XPANDER_ORGANIZATION_ID # Initialize modules directly agents = Agents() tasks = Tasks() tools = ToolsRepository() knowledge = KnowledgeBases() ``` -------------------------------- ### Execute AI Agent Script Source: https://docs.xpander.ai/Examples/01-simple-hello-world Command to run the Python script containing the agent logic. ```bash python hello_world_example.py ``` -------------------------------- ### GET /v1/knowledge/{kb_id} Source: https://docs.xpander.ai/api-reference/v1/knowledge/get-knowledge-base Retrieves detailed information about a specific knowledge base by its unique identifier. ```APIDOC ## GET /v1/knowledge/{kb_id} ### Description Retrieves the details of a knowledge base, including its name, description, type, and the total number of documents contained within it. ### Method GET ### Endpoint /v1/knowledge/{kb_id} ### Parameters #### Path Parameters - **kb_id** (string) - Required - The unique identifier of the knowledge base. ### Request Example N/A (No request body required) ### Response #### Success Response (200) - **id** (string) - KB unique identifier - **name** (string) - KB name specified by the user - **description** (string/null) - KB description specified by the user - **type** (string) - KB type, managed or external - **organization_id** (string) - Organization ID - **agent_id** (string/null) - Agent ID - **total_documents** (integer) - Total count of embedded documents #### Response Example { "id": "73dc30ca-bdbf-42f7-a39f-93aff4f8522e", "name": "Product Documentation", "description": "Contains product guides and API documentation", "type": "managed", "organization_id": "91fbe9bc-35b3-41e8-b59d-922fb5a0f031", "agent_id": null, "total_documents": 5 } ``` -------------------------------- ### GET /v1/misc/db Source: https://docs.xpander.ai/api-reference/v1/misc/get-database Retrieves the PostgreSQL database connection string and associated metadata for the authenticated organization. ```APIDOC ## GET /v1/misc/db ### Description Retrieve the PostgreSQL database connection details for your organization. This provides direct access to your organization's database instance for custom analytics, integrations, and data management. ### Method GET ### Endpoint https://api.xpander.ai/v1/misc/db ### Parameters #### Headers - **x-api-key** (string) - Required - Your organization's API key for authentication. ### Request Example ```bash curl -X GET -H "x-api-key: " \ https://api.xpander.ai/v1/misc/db ``` ### Response #### Success Response (200) - **id** (string) - Database project identifier - **name** (string) - Database project name - **organization_id** (string) - Your organization UUID - **connection_uri** (object) - Database connection details containing the URI string #### Response Example { "id": "still-meadow-47437464", "name": "org_f47ac10b-58cc-4372-a567-0e02b2c3d479", "organization_id": "", "connection_uri": { "uri": "postgresql://:@/?sslmode=require" } } ``` -------------------------------- ### Agent Override Headers Example Source: https://docs.xpander.ai/user-guide/build/ai-model Example of agent-specific headers set in the Workbench LLM Settings. These headers override organization defaults for a particular agent. ```json { "X-Agent-Type": "customer-support", "X-Priority": "high", "X-Environment": "staging" } ``` -------------------------------- ### Organization Default Headers Example Source: https://docs.xpander.ai/user-guide/build/ai-model Example of organization default headers set in Admin Settings. These headers apply to all agents unless overridden at the agent level. ```json { "X-Organization-ID": "org-12345", "X-Environment": "production", "X-Gateway-Auth": "bearer-token-xyz" } ``` -------------------------------- ### Initialize and Manage Xpander Agent via CLI Source: https://docs.xpander.ai/Examples/5-minute-wins/visual-agent-to-code Commands to install the Xpander CLI, initialize an agent project from the workbench, and manage the local development lifecycle. ```bash # Install CLI npm install -g xpander-cli # Download your agent code xpander agent init "your-agent-name" ``` ```bash # Test locally (routes all requests to your machine) xpander dev # Deploy when ready xpander deploy ``` -------------------------------- ### Example Response Structure Source: https://docs.xpander.ai/api-reference/v1/agents/invoke-sync This is an example of a typical response structure from the agent invocation endpoint, showing various fields including status, timestamps, and execution details. ```APIDOC ## Example Response Structure ### Description Provides an example of the detailed response object returned by the agent invocation endpoint. ### Method POST ### Endpoint `/v1/agents//invoke` (Illustrative) ### Parameters N/A (This is a response example) ### Request Example N/A ### Response #### Success Response (200) - **id** (string) - Unique identifier for the invocation. - **agent_id** (string) - The ID of the agent that was invoked. - **organization_id** (string) - The ID of the organization associated with the agent. - **status** (string) - The current status of the invocation (e.g., "completed"). - **input** (object) - The input provided for the invocation. - **text** (string) - The text input. - **result** (string) - The final result produced by the agent. - **source** (string) - The source of the result (e.g., "api"). - **think_mode** (string) - The thinking mode used by the agent (e.g., "default"). - **disable_attachment_injection** (boolean) - Indicates if attachment injection was disabled. - **created_at** (string) - Timestamp when the invocation was created. - **started_at** (string) - Timestamp when the invocation started processing. - **finished_at** (string) - Timestamp when the invocation finished processing. - **execution_attempts** (integer) - The number of execution attempts made. #### Response Example ```json { "id": "6525177e-06a1-4063-82fe-37382d2302a5", "agent_id": "", "organization_id": "", "status": "completed", "input": { "text": "What is xpander.ai in one sentence?", }, "result": "xpander.ai is a full-stack platform for building, deploying, and running autonomous AI agents in production.", "source": "api", "think_mode": "default", "disable_attachment_injection": false, "created_at": "2026-02-07T10:15:22.100233Z", "started_at": "2026-02-07T10:15:22.500000Z", "finished_at": "2026-02-07T10:15:28.997811Z", "execution_attempts": 1 } ``` ``` -------------------------------- ### CI/CD Pipeline Deployment Source: https://docs.xpander.ai/api-reference/cli-reference Example GitHub Actions workflow to automate the deployment of Xpander agents using environment secrets. ```yaml name: Deploy with Xpander on: push: branches: [ main ] jobs: deploy: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - uses: actions/setup-node@v4 with: node-version: '20' - uses: actions/setup-python@v4 with: python-version: '3.12' - run: npm install -g xpander-cli - run: | xpander deploy --agent-id "${{ secrets.XPANDER_AGENT_ID }}" --api-key "${{ secrets.XPANDER_API_KEY }}" --confirm ``` -------------------------------- ### GET /v1/knowledge/{kb_id} Source: https://docs.xpander.ai/api-reference/v1/knowledge/get-knowledge-base Retrieve detailed information about a specific knowledge base, including configuration, metadata, and document counts. ```APIDOC ## GET /v1/knowledge/{kb_id} ### Description Retrieve detailed information about a specific knowledge base including its configuration, document count, and metadata. ### Method GET ### Endpoint https://api.xpander.ai/v1/knowledge/{kb_id} ### Parameters #### Path Parameters - **kb_id** (string) - Required - Unique identifier of the knowledge base (UUID format) ### Request Example ```bash curl -X GET -H "x-api-key: " \ https://api.xpander.ai/v1/knowledge/ ``` ### Response #### Success Response (200) - **id** (string) - Unique identifier for the knowledge base (UUID) - **name** (string) - Display name of the knowledge base - **description** (string) - Optional description of the knowledge base purpose - **type** (string) - Knowledge base type (e.g., "managed") - **organization_id** (string) - UUID of the organization that owns this knowledge base - **agent_id** (string) - UUID of the agent this knowledge base is attached to - **total_documents** (integer) - Total number of documents in the knowledge base #### Response Example { "id": "73dc30ca-bdbf-42f7-a39f-93aff4f8522e", "name": "Product Catalog", "description": "Complete product information and specifications", "type": "managed", "organization_id": "", "agent_id": null, "total_documents": 12 } ``` -------------------------------- ### Initialize Environment and Resources on Boot (Python) Source: https://docs.xpander.ai/Examples/10-lifecycle-management Validates environment variables, initializes database connections, sets up caches, and starts metrics collection when the application boots. Uses asyncio for asynchronous operations. ```python import os import asyncio # Global resources that need lifecycle management database_connection = None api_cache = {} metrics_collector = None # Mock decorators for demonstration def on_boot(func): def wrapper(*args, **kwargs): return func(*args, **kwargs) return wrapper def on_task(func): def wrapper(*args, **kwargs): return func(*args, **kwargs) return wrapper def on_shutdown(func): def wrapper(*args, **kwargs): return func(*args, **kwargs) return wrapper @on_boot def validate_environment(): """Validate environment variables and configuration.""" print("🔍 Validating environment...") required_vars = ["XPANDER_API_KEY", "XPANDER_ORGANIZATION_ID"] missing = [var for var in required_vars if not os.getenv(var)] if missing: raise EnvironmentError(f"Missing required variables: {missing}") print("✅ Environment validation passed") @on_boot async def initialize_database(): """Initialize database connection.""" global database_connection print("🗄️ Connecting to database...") # Simulate async database connection await asyncio.sleep(0.1) database_connection = {"status": "connected", "pool": "mock_pool"} print("✅ Database connection established") @on_boot def setup_cache(): """Initialize application cache.""" global api_cache print("🧠 Initializing cache...") api_cache = { "user_sessions": {}, "api_responses": {}, "temp_data": {} } print("✅ Cache initialized") @on_boot async def start_metrics_collection(): """Start background metrics collection.""" global metrics_collector print("📊 Starting metrics collection...") await asyncio.sleep(0.05) metrics_collector = {"active": True, "start_time": "now"} print("✅ Metrics collection started") # Mock Backend and Agent classes for demonstration class Backend: def get_args(self): return {} class Agent: def __init__(self, **kwargs): pass def print_response(self, message): print(f"Agent Response: {message}") # Initialize backend and agent backend = Backend() agno_agent = Agent(**backend.get_args()) # The agent is now ready with proper lifecycle management print("🚀 Agent ready with lifecycle management!") print("📋 Try asking: 'Process some sample data'") agno_agent.print_response(message="Process this sample data for analysis") ``` -------------------------------- ### Manage Multiple SDK Configurations in Parallel Source: https://docs.xpander.ai/api-reference/configuration Demonstrates initializing SDK modules with distinct Configuration objects for different environments (e.g., development and production). This allows simultaneous use of multiple, independent configurations. ```python from xpander_sdk import Configuration, Agents # Development environment dev_config = Configuration( api_key="dev-api-key", organization_id="dev-org-id", base_url="https://dev.xpander.ai" ) # Production environment prod_config = Configuration( api_key="prod-api-key", organization_id="prod-org-id" ) # Use different configurations simultaneously dev_agents = Agents(configuration=dev_config) prod_agents = Agents(configuration=prod_config) ``` -------------------------------- ### get(agent_id, version=None) - Synchronous Get Agent Source: https://docs.xpander.ai/api-reference/agents/api-reference Synchronously retrieves a specific agent by its unique ID, optionally specifying a version. ```APIDOC ## get(agent_id, version=None) ### Description Synchronously retrieves a specific agent by its unique ID, optionally specifying a version. ### Method ```python theme={"dark"} def get( agent_id: str, version: Optional[int] = None ) -> Agent ``` ### Endpoint N/A (This is a method of the Agents class) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters #### Path Parameters * **agent_id** (str) - Required - Unique identifier for the agent. * **version** (int) - Optional - Specific version of the agent to retrieve. If not provided, retrieves the latest version. ### Request Example ```python theme={"dark"} # Get latest version agent = agents.get("agent-123") print(f"Agent name: {agent.name}") # Get specific version agent_v2 = agents.get("agent-123", version=2) print(f"Agent version: {agent_v2.version}") ``` ### Response #### Success Response (200) - **agent** (Agent) - An object containing the full configuration of the requested agent. #### Response Example ```json { "id": "agent-123", "name": "Example Agent", "version": 1, "description": "This is an example agent.", "configuration": { "model": "gpt-4" } } ``` ### Error Handling - `ModuleException`: Raised if the agent is not found or access is denied. ```