Agents
Code Examples
Practical examples for working with agents
Complete Examples
Node.js / JavaScript
const axios = require('axios')
class AgentsAPI {
constructor(keyId, keySecret) {
this.credentials = { keyId, keySecret }
this.baseURL = 'https://api.performchat.com/rest/v1'
}
async listAgents(page = 1, limit = 20) {
const response = await axios.get(`${this.baseURL}/agents`, {
params: { page, limit },
data: this.credentials
})
return response.data
}
async getAgent(agentId) {
const response = await axios.get(`${this.baseURL}/agents/${agentId}`, {
data: this.credentials
})
return response.data
}
async getFirstActiveAgent() {
const result = await this.listAgents(1, 100)
return result.data.find(agent => agent.active)
}
async getAllAgents() {
const allAgents = []
let page = 1
let hasMore = true
while (hasMore) {
const result = await this.listAgents(page, 100)
allAgents.push(...result.data)
hasMore = page < result.pagination.total_pages
page++
}
return allAgents
}
}
// Usage
const api = new AgentsAPI(
process.env.API_KEY_ID,
process.env.API_KEY_SECRET
)
// Get first active agent for token generation
const agent = await api.getFirstActiveAgent()
console.log(`Using agent: ${agent.name}`)
// Get all agents
const allAgents = await api.getAllAgents()
console.log(`Total agents: ${allAgents.length}`)Python
import os
import requests
from typing import List, Optional, Dict
class AgentsAPI:
def __init__(self, key_id: str, key_secret: str):
self.credentials = {
"keyId": key_id,
"keySecret": key_secret
}
self.base_url = "https://api.performchat.com/rest/v1"
def list_agents(self, page: int = 1, limit: int = 20) -> Dict:
response = requests.get(
f"{self.base_url}/agents",
params={"page": page, "limit": limit},
json=self.credentials
)
response.raise_for_status()
return response.json()
def get_agent(self, agent_id: str) -> Dict:
response = requests.get(
f"{self.base_url}/agents/{agent_id}",
json=self.credentials
)
response.raise_for_status()
return response.json()
def get_first_active_agent(self) -> Optional[Dict]:
result = self.list_agents(page=1, limit=100)
for agent in result['data']:
if agent['active']:
return agent
return None
def get_all_agents(self) -> List[Dict]:
all_agents = []
page = 1
while True:
result = self.list_agents(page=page, limit=100)
all_agents.extend(result['data'])
if page >= result['pagination']['total_pages']:
break
page += 1
return all_agents
# Usage
api = AgentsAPI(
os.getenv("API_KEY_ID"),
os.getenv("API_KEY_SECRET")
)
# Get first active agent
agent = api.get_first_active_agent()
if agent:
print(f"Using agent: {agent['name']}")
# Get all agents
all_agents = api.get_all_agents()
print(f"Total agents: {len(all_agents)}")TypeScript
import axios, { AxiosInstance } from 'axios'
interface Agent {
id: string
name: string
prompt_template?: string
active: boolean
created_at: string
updated_at: string
}
interface ListAgentsResponse {
data: Agent[]
pagination: {
page: number
limit: number
total: number
total_pages: number
}
}
class AgentsAPI {
private client: AxiosInstance
private credentials: { keyId: string; keySecret: string }
constructor(keyId: string, keySecret: string) {
this.credentials = { keyId, keySecret }
this.client = axios.create({
baseURL: 'https://api.performchat.com/rest/v1'
})
}
async listAgents(page: number = 1, limit: number = 20): Promise<ListAgentsResponse> {
const response = await this.client.get<ListAgentsResponse>('/agents', {
params: { page, limit },
data: this.credentials
})
return response.data
}
async getAgent(agentId: string): Promise<Agent> {
const response = await this.client.get<Agent>(`/agents/${agentId}`, {
data: this.credentials
})
return response.data
}
async getFirstActiveAgent(): Promise<Agent | null> {
const result = await this.listAgents(1, 100)
return result.data.find(agent => agent.active) || null
}
async getAllAgents(): Promise<Agent[]> {
const allAgents: Agent[] = []
let page = 1
let hasMore = true
while (hasMore) {
const result = await this.listAgents(page, 100)
allAgents.push(...result.data)
hasMore = page < result.pagination.total_pages
page++
}
return allAgents
}
}
// Usage
const api = new AgentsAPI(
process.env.API_KEY_ID!,
process.env.API_KEY_SECRET!
)
const agent = await api.getFirstActiveAgent()
if (agent) {
console.log(`Using agent: ${agent.name}`)
}Common Use Cases
Agent Selection UI
async function getAgentsForUI() {
const agents = await api.getAllAgents()
return agents
.filter(agent => agent.active)
.map(agent => ({
value: agent.id,
label: agent.name,
isActive: agent.active
}))
}
// In your UI framework
const agentOptions = await getAgentsForUI()
// Render dropdown/select with agentOptionsAgent Health Check
async function checkAgentHealth() {
const agents = await api.getAllAgents()
const stats = {
total: agents.length,
active: agents.filter(a => a.active).length,
inactive: agents.filter(a => !a.active).length
}
console.log('Agent Health:')
console.log(`Total: ${stats.total}`)
console.log(`Active: ${stats.active}`)
console.log(`Inactive: ${stats.inactive}`)
return stats
}Token Generation with Agent Selection
async function createUserSession(userId, preferredAgentName = null) {
let agent
if (preferredAgentName) {
// Find agent by name
const agents = await api.getAllAgents()
agent = agents.find(a =>
a.active && a.name.toLowerCase() === preferredAgentName.toLowerCase()
)
}
// Fallback to first active agent
if (!agent) {
agent = await api.getFirstActiveAgent()
}
if (!agent) {
throw new Error('No active agents available')
}
// Generate token with selected agent
return await generateToken(userId, agent.id)
}Export Agents to CSV
async function exportAgentsToCSV() {
const agents = await api.getAllAgents()
const csv = [
['ID', 'Name', 'Active', 'Created', 'Updated'].join(','),
...agents.map(agent =>
[
agent.id,
`"${agent.name}"`,
agent.active,
agent.created_at,
agent.updated_at
].join(',')
)
].join('\n')
return csv
}Error Handling
async function safeGetAgent(agentId) {
try {
return await api.getAgent(agentId)
} catch (error) {
if (error.response?.status === 404) {
console.error(`Agent ${agentId} not found`)
return null
} else if (error.response?.status === 401) {
console.error('Invalid API credentials')
throw new Error('Authentication failed')
} else {
console.error('Unexpected error:', error.message)
throw error
}
}
}Caching Strategy
class CachedAgentsAPI extends AgentsAPI {
constructor(keyId, keySecret) {
super(keyId, keySecret)
this.cache = new Map()
this.cacheExpiry = 5 * 60 * 1000 // 5 minutes
}
async listAgents(page = 1, limit = 20) {
const cacheKey = `list:${page}:${limit}`
const cached = this.cache.get(cacheKey)
if (cached && Date.now() - cached.timestamp < this.cacheExpiry) {
return cached.data
}
const data = await super.listAgents(page, limit)
this.cache.set(cacheKey, { data, timestamp: Date.now() })
return data
}
async getAgent(agentId) {
const cacheKey = `agent:${agentId}`
const cached = this.cache.get(cacheKey)
if (cached && Date.now() - cached.timestamp < this.cacheExpiry) {
return cached.data
}
const data = await super.getAgent(agentId)
this.cache.set(cacheKey, { data, timestamp: Date.now() })
return data
}
clearCache() {
this.cache.clear()
}
}Related Pages
- List Agents - API reference for listing agents
- Get Agent - API reference for getting a specific agent
- Token Generation - Use agents for authentication