Module Summary

  • Goal: Customize agent loops, add Python tools, and run the agent locally or via cloud event hook
  • Estimated Time: 45–60 minutes
  • Prerequisites: Python 3.12, Node.js v22, completed Modules 1–3

🧭 What You’ll Do in This Module

In this module, you’ll gain full control over your agent’s behavior.

You’ll learn how to:

  • Run your agent locally via Notebook, CLI, or event handler
  • Customize the agent loop, allowing advanced logic or prompt shaping
  • Add your own Python tools to expand what the agent can do
  • Optionally deploy the agent using the xpander.ai CLI for cloud-based execution

By the end, you’ll be able to create and extend fully working agents tailored to your needs - whether you want to explore behavior in a notebook or power up a frontend integration.

Let’s get started.


⚙️ Environment Setup

This setup is required for all run modes (Notebook, CLI, Event-driven):

ToolRequired Version
Python3.12.7
Node.jsv22

Use pyenv and nvm to manage these versions if needed:

python3 --version     # 3.12.7
node --version        # v22.x

🧱 Step 1: Clone the Template Repository

git clone https://github.com/xpander-ai/xpander.ai.git
cd xpander.ai/Getting-Started/hello-world
python3 -m venv .venv
source .venv/bin/activate

🔐 Step 2: CLI Login & Agent Initialization

Install the CLI and initialize your agent:

npm i -g xpander-cli
xpander login
xpander initialize

This creates the following files:

  • xpander_config.json
  • agent_instructions.json
  • requirements.txt


📦 Step 3: Install Agent Dependencies

pip install -r requirements.txt
mv .env.example .env

Fill in the required values in .env:

OPENAI_MODEL_ID=gpt-4.1
OPENAI_API_KEY=sk-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

💬 Step 4: Run the Agent

This mode is ideal for stepping through the agent lifecycle.

▶️ 1. Open the Notebook

Open my_agent.ipynb in VSCode, Jupyter Lab, or any notebook viewer.

🧪 2. Import Libraries

Run this cell first:

from xpander_sdk import XpanderClient, Agent
from my_agent import MyAgent
from dotenv import load_dotenv
import json

🔧 3. Load Configuration

load_dotenv()

with open('xpander_config.json', 'r') as config_file:
    xpander_config = json.load(config_file)

🧠 4. Initialize and Wrap the Agent

xpander_client = XpanderClient(api_key=xpander_config.get("api_key"))
xpander_agent = xpander_client.agents.get(agent_id=xpander_config.get("agent_id"))
agent = MyAgent(xpander_agent)

💬 5. Send a Task to the Agent

thread = await agent.chat("Add a simple, beautiful Shazam-style app (HTML, CSS, JS) to xpander-ai/apps-by-agents.")

📊 6. Retrieve and Display Result

execution_result = xpander_agent.retrieve_execution_result()
print("status:", execution_result.status.value)
print("result:", execution_result.result)

🧾 7. Visualize Message History (Optional)

from tabulate import tabulate

messages = xpander_agent.messages
for msg in messages:
    print(msg["role"], ":", msg["content"][:100])


Option B: CLI Mode

Run the agent directly via:

python app.py

Then send a prompt like:

Create a responsive Agents Directory app (HTML, CSS, JS) with mock agents and PR to xpander-ai/apps-by-agents.


Option C: Event-Driven Mode

Run the event handler script for live frontend integration:

python xpander_handler.py


🔧 Step 5: Add Local Tools

Define a custom tool in tools/local_tools.py:

def say_hello(name: str) -> dict:
    return {"message": f"Hello {name}, welcome to the workshop!"}

local_tools = [
    {
        "declaration": {
            "type": "function",
            "function": {
                "name": "say_hello",
                "description": "Greets the user",
                "parameters": {
                    "type": "object",
                    "properties": {
                        "name": {"type": "string", "description": "User's name"}
                    },
                    "required": ["name"]
                }
            }
        },
        "fn": say_hello
    }
]

Register in my_agent.py:

self.agent.add_local_tools([tool["declaration"] for tool in local_tools])

🧠 Step 6: Customize the Agent Loop

Modify the main loop in my_agent.py:

async def _agent_loop(self):
    # Customize execution, prompt shaping, logging, etc.

Customize:

  • Prompt rewriting
  • Token usage tracking
  • Advanced condition handling
  • Custom logging or retry mechanisms

🚀 Step 7: Deploy to Cloud

Use Xpander CLI to deploy your agent:

xpander deploy

View live logs:

xpander logs

🧯 Troubleshooting

IssueFix
Failed to sync agentRe-check .env and xpander_config.json and re-run init
add_graph_item errorsConfirm a clean tool graph and valid agent ID
BrokenPipe / JSII issuesRestart shell or rebuild .venv
No event triggersOnly run xpander_handler.py after triggering from frontend

✅ Summary

FeatureBenefit
🧠 Custom LogicFull control with _agent_loop()
🛠 ToolingAdd Python tools as callable functions
🧲 Hybrid ModeLocal + Cloud support
📦 One-Line Deployxpander deploy ready
🔍 InsightsBuilt-in metrics and logs