Voice Agent Management Examples
Examples for creating, reading, updating, and deleting voice agents.
Create an Agent
JavaScript/TypeScript
Codeconst API_KEY = "your-api-key"; const BASE_URL = "https://api.slng.ai"; async function createAgent() { const response = await fetch(`${BASE_URL}/v1/agents`, { method: "POST", headers: { Authorization: `Bearer ${API_KEY}`, "Content-Type": "application/json", }, body: JSON.stringify({ name: "Sales Outreach Agent", system_prompt: `You are a friendly sales representative for {{company_name}}. You're calling to introduce our {{product_name}} to potential customers. Guidelines: - Be enthusiastic but not pushy - Focus on benefits, not features - Ask qualifying questions - If interested, offer to send more information - Keep calls under 5 minutes`, greeting: "Hi! This is Alex from {{company_name}}. Do you have a quick moment to chat?", language: "en", models: { stt: "deepgram/nova:2", llm: "openai/gpt-4o-mini", tts: "deepgram/aura:2", tts_voice: "aura-2-andromeda-en", llm_kwargs: { temperature: 0.8 }, }, enable_interruptions: true, tools: [ { type: "template", template: "hangup" }, { type: "template", template: "voicemail_detection" }, ], slng_api_key: "your-slng-api-key", livekit_deployment: "production", template_defaults: { company_name: "TechStartup Inc", product_name: "CloudSync Pro", }, }), }); if (!response.ok) { const error = await response.json(); throw new Error(`Failed to create agent: ${error.error}`); } return response.json(); } // Usage const agent = await createAgent(); console.log(`Created agent: ${agent.id}`);
Python
Codeimport requests API_KEY = "your-api-key" BASE_URL = "https://api.slng.ai" def create_agent(): response = requests.post( f"{BASE_URL}/v1/agents", headers={ "Authorization": f"Bearer {API_KEY}", "Content-Type": "application/json" }, json={ "name": "Sales Outreach Agent", "system_prompt": """You are a friendly sales representative for {{company_name}}. You're calling to introduce our {{product_name}} to potential customers. Guidelines: - Be enthusiastic but not pushy - Focus on benefits, not features - Ask qualifying questions - If interested, offer to send more information - Keep calls under 5 minutes""", "greeting": "Hi! This is Alex from {{company_name}}. Do you have a quick moment to chat?", "language": "en", "models": { "stt": "deepgram/nova:2", "llm": "openai/gpt-4o-mini", "tts": "deepgram/aura:2", "tts_voice": "aura-2-andromeda-en", "llm_kwargs": {"temperature": 0.8} }, "enable_interruptions": True, "tools": [ {"type": "template", "template": "hangup"}, {"type": "template", "template": "voicemail_detection"} ], "slng_api_key": "your-slng-api-key", "livekit_deployment": "production", "template_defaults": { "company_name": "TechStartup Inc", "product_name": "CloudSync Pro" } } ) response.raise_for_status() return response.json() # Usage agent = create_agent() print(f"Created agent: {agent['id']}")
cURL
Codecurl -X POST https://api.slng.ai/v1/agents \ -H "Authorization: Bearer YOUR_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "name": "Sales Outreach Agent", "system_prompt": "You are a friendly sales representative...", "greeting": "Hi! This is Alex from {{company_name}}.", "language": "en", "models": { "stt": "deepgram/nova:2", "llm": "openai/gpt-4o-mini", "tts": "deepgram/aura:2", "tts_voice": "aura-2-andromeda-en" }, "slng_api_key": "your-slng-api-key", "livekit_deployment": "production" }'
List All Agents
JavaScript/TypeScript
Codeasync function listAgents() { const response = await fetch(`${BASE_URL}/v1/agents`, { headers: { Authorization: `Bearer ${API_KEY}`, }, }); if (!response.ok) { throw new Error("Failed to list agents"); } return response.json(); } // Usage const agents = await listAgents(); console.log(`Found ${agents.length} agents:`); agents.forEach((agent) => { console.log(`- ${agent.name} (${agent.id})`); });
Python
Codedef list_agents(): response = requests.get( f"{BASE_URL}/v1/agents", headers={"Authorization": f"Bearer {API_KEY}"} ) response.raise_for_status() return response.json() # Usage agents = list_agents() print(f"Found {len(agents)} agents:") for agent in agents: print(f"- {agent['name']} ({agent['id']})")
Get a Single Agent
JavaScript/TypeScript
Codeasync function getAgent(agentId) { const response = await fetch(`${BASE_URL}/v1/agents/${agentId}`, { headers: { Authorization: `Bearer ${API_KEY}`, }, }); if (response.status === 404) { return null; } if (!response.ok) { throw new Error("Failed to get agent"); } return response.json(); } // Usage const agent = await getAgent("550e8400-e29b-41d4-a716-446655440000"); if (agent) { console.log(`Agent: ${agent.name}`); console.log(`Models: STT=${agent.models.stt}, LLM=${agent.models.llm}`); console.log(`Template variables:`, agent.template_variables); }
Python
Codedef get_agent(agent_id): response = requests.get( f"{BASE_URL}/v1/agents/{agent_id}", headers={"Authorization": f"Bearer {API_KEY}"} ) if response.status_code == 404: return None response.raise_for_status() return response.json() # Usage agent = get_agent("550e8400-e29b-41d4-a716-446655440000") if agent: print(f"Agent: {agent['name']}") print(f"Models: STT={agent['models']['stt']}, LLM={agent['models']['llm']}")
Update an Agent (Partial)
Use PATCH to update specific fields without replacing the entire agent.
JavaScript/TypeScript
Codeasync function updateAgent(agentId, updates) { const response = await fetch(`${BASE_URL}/v1/agents/${agentId}`, { method: "PATCH", headers: { Authorization: `Bearer ${API_KEY}`, "Content-Type": "application/json", }, body: JSON.stringify(updates), }); if (!response.ok) { const error = await response.json(); throw new Error(`Failed to update agent: ${error.error}`); } return response.json(); } // Update just the greeting const updated = await updateAgent("550e8400-e29b-41d4-a716-446655440000", { greeting: "Hello! Thank you for your time today.", }); // Update models configuration const updated2 = await updateAgent("550e8400-e29b-41d4-a716-446655440000", { models: { stt: "deepgram/nova:2", llm: "openai/gpt-4o", // Upgraded from gpt-4o-mini tts: "elevenlabs/eleven-flash:2.5", tts_voice: "rachel", llm_kwargs: { temperature: 0.7 }, }, }); // Add a webhook tool const updated3 = await updateAgent("550e8400-e29b-41d4-a716-446655440000", { tools: [ { type: "template", template: "hangup" }, { type: "webhook", name: "schedule_callback", description: "Schedule a callback for the customer", url: "https://api.yourcompany.com/callbacks", parameters: { type: "object", properties: { preferred_time: { type: "string", description: "Preferred callback time", }, phone_number: { type: "string", description: "Phone number to call back", }, }, required: ["preferred_time"], }, }, ], });
Python
Codedef update_agent(agent_id, updates): response = requests.patch( f"{BASE_URL}/v1/agents/{agent_id}", headers={ "Authorization": f"Bearer {API_KEY}", "Content-Type": "application/json" }, json=updates ) response.raise_for_status() return response.json() # Update greeting updated = update_agent("550e8400-e29b-41d4-a716-446655440000", { "greeting": "Hello! Thank you for your time today." }) # Update template defaults updated = update_agent("550e8400-e29b-41d4-a716-446655440000", { "template_defaults": { "company_name": "New Company Name", "product_name": "New Product" } })
Replace an Agent (Full)
Use PUT to completely replace an agent configuration. All required fields must be provided.
JavaScript/TypeScript
Codeasync function replaceAgent(agentId, agentConfig) { const response = await fetch(`${BASE_URL}/v1/agents/${agentId}`, { method: "PUT", headers: { Authorization: `Bearer ${API_KEY}`, "Content-Type": "application/json", }, body: JSON.stringify(agentConfig), }); if (!response.ok) { const error = await response.json(); throw new Error(`Failed to replace agent: ${error.error}`); } return response.json(); } // Full replacement - all required fields must be provided const replaced = await replaceAgent("550e8400-e29b-41d4-a716-446655440000", { name: "Sales Outreach Agent v2", system_prompt: "New and improved system prompt...", greeting: "New greeting!", language: "en", models: { stt: "deepgram/nova:2", llm: "openai/gpt-4o", tts: "elevenlabs/eleven-flash:2.5", tts_voice: "rachel", }, slng_api_key: "your-slng-api-key", livekit_deployment: "production", });
Delete an Agent
JavaScript/TypeScript
Codeasync function deleteAgent(agentId) { const response = await fetch(`${BASE_URL}/v1/agents/${agentId}`, { method: "DELETE", headers: { Authorization: `Bearer ${API_KEY}`, }, }); if (response.status === 204) { return true; // Successfully deleted } if (response.status === 404) { return false; // Agent not found } throw new Error("Failed to delete agent"); } // Usage const deleted = await deleteAgent("550e8400-e29b-41d4-a716-446655440000"); if (deleted) { console.log("Agent deleted successfully"); }
Python
Codedef delete_agent(agent_id): response = requests.delete( f"{BASE_URL}/v1/agents/{agent_id}", headers={"Authorization": f"Bearer {API_KEY}"} ) return response.status_code == 204 # Usage if delete_agent("550e8400-e29b-41d4-a716-446655440000"): print("Agent deleted successfully")
Agent with Webhook Tools
Complete example of an agent with custom webhook integrations:
Codeconst agentWithWebhooks = await createAgent({ name: "Customer Service Agent", system_prompt: `You are a customer service agent for {{company_name}}. You can look up order status, process returns, and escalate issues. Available actions: - Use check_order to look up order status - Use process_return to initiate a return - Use escalate_ticket to escalate to a human agent Always verify the customer's identity before accessing their information.`, greeting: "Thank you for calling {{company_name}} support. How can I help you today?", language: "en", models: { stt: "deepgram/nova:2", llm: "openai/gpt-4o", tts: "deepgram/aura:2", tts_voice: "aura-2-andromeda-en", }, tools: [ { type: "template", template: "hangup" }, { type: "webhook", name: "check_order", description: "Look up the status of a customer order", url: "https://api.yourcompany.com/orders/lookup", parameters: { type: "object", properties: { order_id: { type: "string", description: "The order ID" }, customer_email: { type: "string", description: "Customer email for verification", }, }, required: ["order_id", "customer_email"], }, auth: { type: "bearer", token: process.env.ORDERS_API_TOKEN }, timeout_seconds: 10, }, { type: "webhook", name: "process_return", description: "Initiate a return for an order", url: "https://api.yourcompany.com/returns/create", parameters: { type: "object", properties: { order_id: { type: "string" }, reason: { type: "string", enum: ["defective", "wrong_item", "changed_mind", "other"], }, notes: { type: "string" }, }, required: ["order_id", "reason"], }, auth: { type: "bearer", token: process.env.RETURNS_API_TOKEN }, }, { type: "webhook", name: "escalate_ticket", description: "Escalate the issue to a human agent", url: "https://api.yourcompany.com/tickets/escalate", parameters: { type: "object", properties: { summary: { type: "string", description: "Brief summary of the issue", }, priority: { type: "string", enum: ["low", "medium", "high", "urgent"], }, customer_phone: { type: "string" }, }, required: ["summary", "priority"], }, auth: { type: "hmac", secret: process.env.TICKETS_HMAC_SECRET }, wait_for_response: false, // Fire and forget }, ], slng_api_key: process.env.SLNG_API_KEY, livekit_deployment: "production", template_defaults: { company_name: "Acme Store", }, });
Error Handling
Codeasync function safeCreateAgent(config) { try { const response = await fetch(`${BASE_URL}/v1/agents`, { method: "POST", headers: { Authorization: `Bearer ${API_KEY}`, "Content-Type": "application/json", }, body: JSON.stringify(config), }); if (response.status === 400) { const error = await response.json(); console.error("Validation error:", error.error); return null; } if (response.status === 403) { console.error("Authentication failed - check your API key"); return null; } if (response.status === 409) { console.error("Agent name already exists"); return null; } if (!response.ok) { console.error("Unexpected error:", response.status); return null; } return response.json(); } catch (error) { console.error("Network error:", error.message); return null; } }
Last modified on