Agentlify SDK
JavaScript/TypeScript SDK for Router and Agent workflows.
Quick Example
javascript
const Agentlify = require('agentlify-js');
const client = new Agentlify({
apiKey: process.env.AGENTLIFY_API_KEY,
routerId: process.env.AGENTLIFY_ROUTER_ID
});
const completion = await client.chat.create({
messages: [{ role: 'user', content: 'Hello!' }]
});
console.log(completion.choices[0].message.content);
console.log('Cost:', completion._meta?.cost);Installation
bash
npm install agentlify-jsInitialization
Configuration Options
apiKeyrequiredAgentlify API key (must start with mp_)routerIdrequiredRouter ID used by client.chat.create()timeoutoptionalRequest timeout in milliseconds (default: 30000)maxRetriesoptionalRetry attempts for retryable failures (default: 3)baseURLoptionalDefaults to https://modelpilot.co/apijavascript
const client = new Agentlify({
apiKey: process.env.AGENTLIFY_API_KEY,
routerId: process.env.AGENTLIFY_ROUTER_ID,
timeout: 30000,
maxRetries: 3
});Chat Completions
Basic Request
javascript
const completion = await client.chat.create({
messages: [
{ role: 'system', content: 'You are a helpful assistant.' },
{ role: 'user', content: 'What is 2+2?' }
],
temperature: 0.7,
max_tokens: 150
});
console.log(completion.choices[0].message.content);
console.log('Model used:', completion._meta?.modelUsed);
console.log('Cost:', completion._meta?.cost);
console.log('Latency:', completion._meta?.latency);Streaming
javascript
const stream = await client.chat.create({
messages: [{ role: 'user', content: 'Tell me a story' }],
stream: true
});
for await (const chunk of stream) {
const content = chunk.choices[0]?.delta?.content || '';
process.stdout.write(content);
}Agents API
Automatic Tool Callback Loop
client.agents.run() executes local callbacks and automatically resumes the agent.javascript
const response = await client.agents.run({
agentId: 'support-assistant',
messages: [{ role: 'user', content: 'Check order status for 12345' }],
tools: [
{
type: 'function',
function: {
name: 'get_order_status',
description: 'Get order status',
parameters: {
type: 'object',
properties: { orderId: { type: 'string' } },
required: ['orderId']
}
},
callback: async ({ orderId }) => ({ orderId, status: 'shipped' })
}
]
});Checkpoints & Resume
When an agent pauses for external tool calls or human approvals, the server checkpoints the full workflow state. The SDK handles tool call checkpoints automatically via agents.run(). For manual control, use agents.resume().
Manual Resume (Tool Calls)
Use
client.agents.execute() + client.agents.resume() for full control over the checkpoint loop.javascript
// Step 1: Execute (returns immediately on tool call pause)
const response = await client.agents.execute({
agentId: 'my-agent',
messages: [{ role: 'user', content: 'Look up order #123' }],
tools: [{ type: 'function', function: { name: 'get_order', ... } }]
});
// Step 2: Check if paused for tool calls
if (response.choices[0].finish_reason === 'tool_calls') {
const toolCalls = response.choices[0].message.tool_calls;
// Step 3: Execute tools locally, then resume
const resumed = await client.agents.resume({
resumeId: response.resume_id,
toolResults: [{
toolCallId: toolCalls[0].id,
output: JSON.stringify({ status: 'shipped' })
}]
});
console.log(resumed.output);
}Manual Resume (Approvals)
javascript
// The agent paused for human approval
// response.status === 'approval_required'
const resumed = await client.agents.resume({
resumeId: response.resume_id,
decision: 'approved', // 'approved' | 'rejected' | 'timed_out'
reason: 'Verified by manager'
});See the Checkpoints & Resume guide for the full deep dive.
TypeScript Support
Bundled Type Definitions
Types are included with
agentlify-js.typescript
import Agentlify from 'agentlify-js';
import type { ChatMessage, ChatCompletionResponse } from 'agentlify-js';
const client = new Agentlify({
apiKey: process.env.AGENTLIFY_API_KEY!,
routerId: process.env.AGENTLIFY_ROUTER_ID!
});
const messages: ChatMessage[] = [{ role: 'user', content: 'Hello!' }];
const completion: ChatCompletionResponse = await client.chat.create({
messages
}) as ChatCompletionResponse;Error Handling
Try-Catch Pattern
javascript
try {
const completion = await client.chat.create({
messages: [{ role: 'user', content: 'Hello!' }]
});
console.log(completion.choices[0].message.content);
} catch (error) {
if (error.status === 429) {
console.error('Rate limit exceeded');
} else if (error.status === 401) {
console.error('Invalid API key');
} else {
console.error('Error:', error.message);
}
}Best Practices
Do This
- • Keep API keys in environment variables
- • Handle retryable API errors
- • Track usage using completion metadata
- • Use streaming for long responses
- • Use `agents.run` for callback-based tools
Avoid This
- • Hardcoding API keys
- • Using `chat.completions.create` with this SDK
- • Ignoring error status codes
- • Skipping timeout/retry settings in production
- • Leaving routerId unset