Integration Examples
This page provides practical examples for integrating with the Agent Controller API.
JavaScript/Node.js Examples
Basic REST API Integration
const API_BASE_URL = 'https://data-services.aui.io/api/ia-controller';
const API_KEY = 'your-network-api-key';
// Create a new task
async function createTask(userId) {
const response = await fetch(`${API_BASE_URL}/api/v1/external/tasks`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'x-network-api-key': API_KEY
},
body: JSON.stringify({
user_id: userId
})
});
return await response.json();
}
// Send a message via REST
async function sendMessage(taskId, text, context = {}) {
const response = await fetch(`${API_BASE_URL}/api/v1/external/message`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'x-network-api-key': API_KEY
},
body: JSON.stringify({
task_id: taskId,
text: text,
context: context
})
});
return await response.json();
}
// Get task messages
async function getTaskMessages(taskId) {
const response = await fetch(`${API_BASE_URL}/api/v1/external/tasks/${taskId}/messages`, {
headers: {
'x-network-api-key': API_KEY
}
});
return await response.json();
}
// Example usage
async function example() {
try {
// Create a task
const task = await createTask('user123');
console.log('Created task:', task);
// Send a message
const message = await sendMessage(
task.id,
'I am looking for a built-in microwave with at least 20 liters capacity',
{
url: 'https://example.com/products',
lead_details: {
customer_type: 'residential',
budget_range: '300-500'
}
}
);
console.log('Received response:', message);
// Get all messages for the task
const messages = await getTaskMessages(task.id);
console.log('All messages:', messages);
} catch (error) {
console.error('Error:', error);
}
}
WebSocket Integration
class AgentControllerWebSocket {
constructor(apiKey, baseUrl = 'wss://data-services.aui.io/api/ia-controller') {
this.apiKey = apiKey;
this.baseUrl = baseUrl;
this.ws = null;
this.messageHandlers = [];
}
connect() {
return new Promise((resolve, reject) => {
this.ws = new WebSocket(`${this.baseUrl}/api/v1/external/session?network_api_key=${this.apiKey}`);
this.ws.onopen = () => {
console.log('Connected to Agent Controller WebSocket');
resolve();
};
this.ws.onmessage = (event) => {
const response = JSON.parse(event.data);
this.handleMessage(response);
};
this.ws.onerror = (error) => {
console.error('WebSocket error:', error);
reject(error);
};
this.ws.onclose = (event) => {
console.log('WebSocket connection closed:', event.code, event.reason);
};
});
}
sendMessage(taskId, text, context = {}) {
if (!this.ws || this.ws.readyState !== WebSocket.OPEN) {
throw new Error('WebSocket is not connected');
}
const message = {
task_id: taskId,
text: text,
context: context
};
this.ws.send(JSON.stringify(message));
}
handleMessage(response) {
if (response.channel?.event_name === 'thread-message-text-content-updated') {
// Handle streaming text
this.onTextUpdate(response.data.text);
} else if (response.id) {
// Handle final message
this.onFinalMessage(response);
}
}
onTextUpdate(text) {
console.log('Streaming text:', text);
// Update UI with streaming text
}
onFinalMessage(message) {
console.log('Final message:', message);
// Handle final message with options
if (message.options && message.options.length > 0) {
this.displayProductOptions(message.options);
}
if (message.followup_suggestions && message.followup_suggestions.length > 0) {
this.displayFollowupSuggestions(message.followup_suggestions);
}
}
displayProductOptions(options) {
options.forEach(option => {
const productName = option.widget_parameters.find(p => p.title === 'Product name')?.value;
const price = option.widget_parameters.find(p => p.title === 'Price')?.value;
const rating = option.widget_parameters.find(p => p.title === 'Rating')?.value;
console.log(`Product: ${productName}, Price: ${price}, Rating: ${rating}`);
});
}
displayFollowupSuggestions(suggestions) {
console.log('Follow-up suggestions:', suggestions);
}
disconnect() {
if (this.ws) {
this.ws.close();
}
}
}
// Example usage
async function websocketExample() {
const agent = new AgentControllerWebSocket('your-network-api-key');
try {
await agent.connect();
// Send a message
agent.sendMessage(
'68e78d0dc5a4b19a030d03d6',
'I am looking for a built-in microwave with at least 20 liters capacity',
{
url: 'https://example.com/products',
lead_details: {
customer_type: 'residential'
}
}
);
} catch (error) {
console.error('WebSocket error:', error);
}
}
Python Examples
Basic REST API Integration
import requests
import json
class AgentControllerClient:
def __init__(self, api_key, base_url='https://data-services.aui.io/api/ia-controller'):
self.api_key = api_key
self.base_url = base_url
self.headers = {
'Content-Type': 'application/json',
'x-network-api-key': api_key
}
def create_task(self, user_id):
"""Create a new task for a user"""
url = f"{self.base_url}/api/v1/external/tasks"
data = {"user_id": user_id}
response = requests.post(url, headers=self.headers, json=data)
response.raise_for_status()
return response.json()
def send_message(self, task_id, text, context=None):
"""Send a message to the agent controller"""
url = f"{self.base_url}/api/v1/external/message"
data = {
"task_id": task_id,
"text": text,
"context": context or {}
}
response = requests.post(url, headers=self.headers, json=data)
response.raise_for_status()
return response.json()
def get_task_messages(self, task_id):
"""Get all messages for a task"""
url = f"{self.base_url}/api/v1/external/tasks/{task_id}/messages"
headers = {'x-network-api-key': self.api_key}
response = requests.get(url, headers=headers)
response.raise_for_status()
return response.json()
def list_tasks(self, user_id, page=1, size=10):
"""List tasks for a user"""
url = f"{self.base_url}/api/v1/external/tasks"
params = {
'user_id': user_id,
'page': page,
'size': size
}
headers = {'x-network-api-key': self.api_key}
response = requests.get(url, headers=headers, params=params)
response.raise_for_status()
return response.json()
# Example usage
def main():
client = AgentControllerClient('your-network-api-key')
try:
# Create a task
task = client.create_task('user123')
print(f"Created task: {task['id']}")
# Send a message
message = client.send_message(
task['id'],
'I am looking for a built-in microwave with at least 20 liters capacity',
{
'url': 'https://example.com/products',
'lead_details': {
'customer_type': 'residential',
'budget_range': '300-500'
}
}
)
print(f"Received response: {message['text']}")
# Display product options
if message.get('options'):
for option in message['options']:
product_name = next(
(p['value'] for p in option['widget_parameters'] if p['title'] == 'Product name'),
'Unknown Product'
)
price = next(
(p['value'] for p in option['widget_parameters'] if p['title'] == 'Price'),
'Price not available'
)
print(f"Product: {product_name}, Price: {price}")
# Display follow-up suggestions
if message.get('followup_suggestions'):
print("Follow-up suggestions:")
for suggestion in message['followup_suggestions']:
print(f"- {suggestion}")
except requests.exceptions.RequestException as e:
print(f"Error: {e}")
WebSocket Integration with Python
import asyncio
import websockets
import json
class AgentControllerWebSocket:
def __init__(self, api_key, base_url='wss://data-services.aui.io/api/ia-controller'):
self.api_key = api_key
self.base_url = base_url
self.websocket = None
async def connect(self):
"""Connect to the WebSocket"""
uri = f"{self.base_url}/api/v1/external/session?network_api_key={self.api_key}"
self.websocket = await websockets.connect(uri)
print("Connected to Agent Controller WebSocket")
async def send_message(self, task_id, text, context=None):
"""Send a message through the WebSocket"""
if not self.websocket:
raise Exception("WebSocket not connected")
message = {
"task_id": task_id,
"text": text,
"context": context or {}
}
await self.websocket.send(json.dumps(message))
async def listen(self):
"""Listen for messages from the WebSocket"""
if not self.websocket:
raise Exception("WebSocket not connected")
async for message in self.websocket:
response = json.loads(message)
await self.handle_message(response)
async def handle_message(self, response):
"""Handle incoming messages"""
if response.get('channel', {}).get('event_name') == 'thread-message-text-content-updated':
# Handle streaming text
text = response.get('data', {}).get('text', '')
print(f"Streaming: {text}")
elif response.get('id'):
# Handle final message
print(f"Final message: {response['text']}")
# Display product options
if response.get('options'):
for option in response['options']:
product_name = next(
(p['value'] for p in option['widget_parameters'] if p['title'] == 'Product name'),
'Unknown Product'
)
price = next(
(p['value'] for p in option['widget_parameters'] if p['title'] == 'Price'),
'Price not available'
)
print(f"Product: {product_name}, Price: {price}")
# Display follow-up suggestions
if response.get('followup_suggestions'):
print("Follow-up suggestions:")
for suggestion in response['followup_suggestions']:
print(f"- {suggestion}")
async def disconnect(self):
"""Disconnect from the WebSocket"""
if self.websocket:
await self.websocket.close()
# Example usage
async def websocket_example():
agent = AgentControllerWebSocket('your-network-api-key')
try:
await agent.connect()
# Send a message
await agent.send_message(
'68e78d0dc5a4b19a030d03d6',
'I am looking for a built-in microwave with at least 20 liters capacity',
{
'url': 'https://example.com/products',
'lead_details': {
'customer_type': 'residential'
}
}
)
# Listen for responses
await agent.listen()
except Exception as e:
print(f"Error: {e}")
finally:
await agent.disconnect()
# Run the example
if __name__ == "__main__":
asyncio.run(websocket_example())
cURL Examples
Create a Task
curl -X POST "https://data-services.aui.io/api/ia-controller/api/v1/external/tasks" \
-H "Content-Type: application/json" \
-H "x-network-api-key: your-network-api-key" \
-d '{
"user_id": "user123"
}'
Send a Message
curl -X POST "https://data-services.aui.io/api/ia-controller/api/v1/external/message" \
-H "Content-Type: application/json" \
-H "x-network-api-key: your-network-api-key" \
-d '{
"task_id": "68e78d0dc5a4b19a030d03d6",
"text": "I am looking for a built-in microwave with at least 20 liters capacity",
"context": {
"url": "https://example.com/products",
"lead_details": {
"customer_type": "residential",
"budget_range": "300-500"
}
}
}'
Get Task Messages
curl -X GET "https://data-services.aui.io/api/ia-controller/api/v1/external/tasks/68e78d0dc5a4b19a030d03d6/messages" \
-H "x-network-api-key: your-network-api-key"