@thisispamela/sdk
v1.1.3
Published
Pamela Enterprise Voice API SDK for JavaScript/TypeScript
Readme
Pamela SDK for JavaScript/TypeScript
Official SDK for the Pamela Voice API.
Installation
npm install @thisispamela/sdkUsage
Basic Example
import { PamelaClient } from '@thisispamela/sdk';
const client = new PamelaClient({
apiKey: 'pk_live_your_api_key_here',
baseUrl: 'https://api.thisispamela.com', // Optional
});
// Create a call
const call = await client.createCall({
to: '+1234567890',
task: 'Order a large pizza for delivery',
locale: 'en-US',
max_duration_seconds: 299,
voice: 'female',
agent_name: 'Pamela',
caller_name: 'John from Acme',
});
console.log('Call created:', call.id);
// Get call status
const status = await client.getCall(call.id);
console.log('Call status:', status.status);Webhook Verification
Note: Webhook functions are only available in Node.js environments (not browsers). Import from the /webhooks subpath:
import { PamelaClient } from '@thisispamela/sdk';
import { verifyWebhookSignature, parseToolWebhook } from '@thisispamela/sdk/webhooks';
import express from 'express';
const app = express();
const WEBHOOK_SECRET = 'your_webhook_secret';
app.post('/webhooks/pamela', express.json(), (req, res) => {
const signature = req.headers['x-pamela-signature'] as string;
const payload = req.body;
if (!verifyWebhookSignature(payload, signature, WEBHOOK_SECRET)) {
return res.status(401).send('Invalid signature');
}
// Handle webhook event
console.log('Webhook event:', payload.event);
console.log('Call ID:', payload.call_id);
res.status(200).send('OK');
});Available webhook functions:
verifyWebhookSignature(payload, signature, secret)- Verify webhook signatureparseToolWebhook(payload)- Parse tool execution webhook payload
Getting API Keys
Obtaining Your API Key
API keys are created and managed through the Pamela Partner Portal or via the Partner API:
- Sign up for an API subscription (see Subscription Requirements below)
- Create an API key via one of these methods:
- Developer portal at developer.thisispamela.com: Log in and navigate to the API settings panel
- Partner API:
POST /api/b2b/v1/partner/api-keyscurl -X POST https://api.thisispamela.com/api/b2b/v1/partner/api-keys \ -H "Authorization: Bearer YOUR_B2C_USER_TOKEN" \ -H "Content-Type: application/json" \ -d '{"project_id": "optional-project-id", "key_prefix": "pk_live_"}'
- Save your API key immediately - the full key is only returned once during creation
- Use the key prefix (
pk_live_) to identify keys in your account
Managing API Keys
- List API keys:
GET /api/b2b/v1/partner/api-keys - Revoke API key:
POST /api/b2b/v1/partner/api-keys/{key_id}/revoke - Associate with projects: Optionally link API keys to specific projects for better organization
API Key Format
- Live keys: Start with
pk_live_(all API usage) - Security: Keys are hashed in the database. Store them securely and never commit them to version control.
Subscription Requirements
API Subscription Required
All API access requires an active API subscription. API calls will return 403 Forbidden if:
- No API subscription is active
- Subscription status is
past_dueand grace period has expired - Subscription status is
canceled
Grace Period
API subscriptions have a 1-week grace period when payment fails:
- During grace period: API access is allowed, but usage is still charged
- After grace period expires: API access is blocked until payment is updated
Subscription Status Endpoints
Check subscription status using the partner API:
GET /api/b2b/v1/partner/subscription- Get subscription statusPOST /api/b2b/v1/partner/subscription/checkout- Create checkout sessionPOST /api/b2b/v1/partner/subscription/portal- Access Customer Portal
Error Handling
The SDK provides typed exceptions for all API errors:
import {
PamelaClient,
PamelaError,
AuthenticationError,
SubscriptionError,
RateLimitError,
ValidationError,
CallError,
} from '@thisispamela/sdk';
const client = new PamelaClient({ apiKey: 'pk_live_your_key' });
try {
const call = await client.createCall({ to: '+1234567890', task: 'Test' });
} catch (e) {
if (e instanceof AuthenticationError) {
// 401: Invalid or missing API key
console.log('Auth failed:', e.message);
console.log('Error code:', e.errorCode);
} else if (e instanceof SubscriptionError) {
// 403: Subscription inactive or expired
if (e.errorCode === 7008) {
console.log('Grace period expired - update payment method');
} else {
console.log('Subscription issue:', e.message);
}
} else if (e instanceof RateLimitError) {
// 429: Rate limit exceeded
const retryAfter = e.details?.retry_after ?? 30;
console.log(`Rate limited, retry after ${retryAfter}s`);
} else if (e instanceof ValidationError) {
// 400/422: Invalid request parameters
console.log('Invalid request:', e.message);
console.log('Details:', e.details);
} else if (e instanceof CallError) {
// Call-specific errors
console.log('Call error:', e.message);
} else if (e instanceof PamelaError) {
// All other API errors
console.log(`API error ${e.errorCode}: ${e.message}`);
}
}Exception Hierarchy
All exceptions extend PamelaError:
PamelaError (base)
├── AuthenticationError // 401 errors
├── SubscriptionError // 403 errors (subscription issues)
├── RateLimitError // 429 errors
├── ValidationError // 400/422 errors
└── CallError // Call-specific errorsException Properties
All exceptions have:
message: Human-readable error messageerrorCode?: Numeric error code (e.g., 7008 for subscription expired)details?: Object with additional contextstatusCode?: HTTP status code
Error Codes Reference
Authentication Errors (401)
| Code | Description | |------|-------------| | 1001 | API key required | | 1002 | Invalid API key | | 1003 | API key expired |
Subscription Errors (403)
| Code | Description | |------|-------------| | 1005 | API subscription required | | 7008 | Subscription expired (grace period ended) |
Validation Errors (400)
| Code | Description | |------|-------------| | 2001 | Validation error | | 2002 | Invalid phone number format |
API Errors (7xxx)
| Code | Description | |------|-------------| | 7001 | Partner not found | | 7002 | Project not found | | 7003 | Call not found | | 7004 | No phone number for country | | 7005 | Unsupported country |
Rate Limiting (429)
| Code | Description | |------|-------------| | 6001 | Rate limit exceeded | | 6002 | Quota exceeded |
Usage Limits & Billing
API Usage
- Unlimited API calls (no call count limits)
- All API usage billed at $0.10/minute (10 cents per minute)
- Minimum billing: 1 minute per call (even if call duration < 60 seconds)
- Billing calculation:
billed_minutes = max(ceil(duration_seconds / 60), 1) - Only calls that connect (have
started_at) are billed
Usage Tracking
- Usage is tracked in
b2b_usagecollection withtype: "api_usage"(collection name staysb2b_usage) - Usage is synced to Stripe hourly (at :00 minutes)
- Stripe meter name:
stripe_minutes - Failed syncs are retried with exponential backoff (1s, 2s, 4s, 8s, 16s), max 5 retries
Billing Period
- Billing is based on calendar months (UTC midnight on 1st of each month)
- Calls are billed in the month where
started_atoccurred - Usage sync status:
pending,synced, orfailed
API Methods
Calls
createCall(request)- Create a new callgetCall(callId)- Get call status and detailslistCalls(params?)- List calls with optional filterscancelCall(callId)- Cancel an in-progress callhangupCall(callId)- Force hangup an in-progress call
Tools
registerTool(tool)- Register a toollistTools()- List all toolsdeleteTool(toolId)- Delete a tool
Usage
usage.get(period?)- Get usage statistics
Example:
// Get current month usage
const usage = await client.usage.get();
// Get usage for specific period
const janUsage = await client.usage.get("2024-01");
console.log(`Usage: ${usage.call_count} calls, ${usage.api_minutes} minutes`);
console.log(`Quota: ${usage.quota?.partner_limit || 'Unlimited'}`);Response:
{
partner_id: "partner_123",
project_id?: "project_456",
period: "2024-01",
call_count: 150,
quota?: {
partner_limit?: number,
project_limit?: number
}
}Note: API subscriptions have no quota limits - all usage is billed per-minute.
Browser Compatibility
The main SDK package (@thisispamela/sdk) is browser-compatible. Webhook verification functions (which use Node.js crypto) are available via the /webhooks subpath:
// Browser - main SDK works
import { PamelaClient } from '@thisispamela/sdk';
// Node.js only - webhook verification
import { verifyWebhookSignature } from '@thisispamela/sdk/webhooks';Subpath exports:
@thisispamela/sdk/webhooks- Webhook verification (Node.js only)@thisispamela/sdk/types- TypeScript types@thisispamela/sdk/errors- Error classes
API Reference
See the Pamela API Documentation for full API reference.
