TypeScript SDK
@enprompta/sdk
Full-featured TypeScript SDK with middleware support, automatic retries, and comprehensive type definitions.
Type Safe
Full TypeScript support with comprehensive type definitions.
Auto Retry
Built-in retry strategies with exponential backoff.
Middleware
Extensible middleware system for custom logic.
Subscription Required
The SDK requires an API key from a Pro, Team, or Enterprise subscription. Free tier users cannot access the API programmatically. View pricing →
On this page
Installation
npm
npm install @enprompta/sdkyarn
yarn add @enprompta/sdkpnpm
pnpm add @enprompta/sdkQuick Start
TypeScript
import { Enprompta } from '@enprompta/sdk'
// Initialize with API key
const client = new Enprompta({
apiKey: process.env.ENPROMPTA_API_KEY
})
// Or with OAuth2 credentials
const client = new Enprompta({
clientId: process.env.ENPROMPTA_CLIENT_ID,
clientSecret: process.env.ENPROMPTA_CLIENT_SECRET
})
// List all prompts
const { data: prompts } = await client.prompts.list()
console.log(prompts)
// Create a new prompt
const prompt = await client.prompts.create({
title: 'Email Assistant',
content: 'Write a professional email about {{topic}} to {{recipient}}',
visibility: 'PRIVATE',
variables: [
{ name: 'topic', type: 'text', required: true },
{ name: 'recipient', type: 'text', required: true }
]
})
// Execute the prompt
const result = await client.prompts.execute(prompt.id, {
variables: {
topic: 'project deadline extension',
recipient: 'the project manager'
},
provider: 'openai',
model: 'gpt-4'
})
console.log(result.output)Authentication
The SDK supports both API key and OAuth2 client credentials authentication.
API Key Authentication
const client = new Enprompta({
apiKey: 'ep_your_api_key',
// Optional: custom base URL
baseUrl: 'https://enprompta.com/api/v1'
})OAuth2 Client Credentials
const client = new Enprompta({
clientId: 'your_client_id',
clientSecret: 'your_client_secret',
scopes: ['prompts:read', 'prompts:write', 'executions:write']
})
// Tokens are automatically managed and refreshedWorking with Prompts
List Prompts
// List with pagination
const { data, pagination } = await client.prompts.list({
limit: 20,
visibility: 'PRIVATE',
search: 'email'
})
// Iterate through all pages
for await (const prompt of client.prompts.listAll()) {
console.log(prompt.title)
}Create Prompt
const prompt = await client.prompts.create({
title: 'Code Reviewer',
content: `Review the following {{language}} code and provide feedback:
\`\`\`{{language}}
{{code}}
\`\`\`
Focus on: {{focus_areas}}`,
description: 'AI-powered code review assistant',
category: 'development',
tags: ['code', 'review', 'development'],
visibility: 'TEAM',
teamId: 'team_abc123',
variables: [
{ name: 'language', type: 'select', options: ['javascript', 'python', 'go'] },
{ name: 'code', type: 'text', required: true },
{ name: 'focus_areas', type: 'text', defaultValue: 'best practices, performance' }
]
})Update Prompt
const updated = await client.prompts.update('prompt_abc123', {
title: 'Updated Title',
content: 'New prompt content with {{variable}}',
visibility: 'PUBLIC'
})Delete Prompt
await client.prompts.delete('prompt_abc123')Executions
Execute a Prompt
const result = await client.prompts.execute('prompt_abc123', {
variables: {
topic: 'quarterly review',
tone: 'professional'
},
provider: 'openai',
model: 'gpt-4-turbo',
temperature: 0.7,
maxTokens: 1000
})
console.log(result.output) // Generated text
console.log(result.tokensUsed) // Token count
console.log(result.cost) // Estimated cost
console.log(result.latencyMs) // Response timeList Executions
// Get execution history
const { data: executions } = await client.executions.list({
promptId: 'prompt_abc123',
provider: 'openai',
startDate: '2024-01-01',
endDate: '2024-01-31'
})
// Get aggregated statistics
const stats = await client.executions.getStats({
groupBy: 'day'
})Teams
// List teams
const { data: teams } = await client.teams.list()
// Create a team
const team = await client.teams.create({
name: 'Engineering',
description: 'Engineering team prompts'
})
// Get team details
const teamDetails = await client.teams.get('team_abc123')
// Update team
await client.teams.update('team_abc123', {
name: 'Engineering Team'
})Webhooks
// Create a webhook
const webhook = await client.webhooks.create({
name: 'Slack Notifications',
url: 'https://your-server.com/webhooks/enprompta',
events: ['prompt.created', 'prompt.updated', 'execution.completed'],
secret: 'whsec_your_webhook_secret'
})
// List webhooks
const { data: webhooks } = await client.webhooks.list()
// Get delivery history
const deliveries = await client.webhooks.getDeliveries('webhook_abc123')Available Events
prompt.createdprompt.updatedprompt.deletedworkflow.createdworkflow.updatedworkflow.deletedexecution.startedexecution.completedexecution.failedteam.member_addedMiddleware
The SDK includes a powerful middleware system for request/response processing.
Built-in Middleware
import { Enprompta, LoggingMiddleware, CacheMiddleware, RetryMiddleware } from '@enprompta/sdk'
const client = new Enprompta({
apiKey: 'ep_your_api_key',
middleware: [
// Log all requests and responses
new LoggingMiddleware({ level: 'debug' }),
// Cache GET requests for 5 minutes
new CacheMiddleware({ ttl: 300000 }),
// Retry failed requests
new RetryMiddleware({ maxRetries: 3 })
]
})Custom Middleware
import { Middleware, RequestContext, NextFunction } from '@enprompta/sdk'
class TimingMiddleware implements Middleware {
name = 'timing'
priority = 100
async handle(ctx: RequestContext, next: NextFunction) {
const start = Date.now()
const response = await next(ctx)
const duration = Date.now() - start
console.log(`Request took ${duration}ms`)
return response
}
}
const client = new Enprompta({
apiKey: 'ep_your_api_key',
middleware: [new TimingMiddleware()]
})Error Handling
The SDK provides typed error classes for different failure scenarios.
import {
EnpromptaError,
AuthenticationError,
RateLimitError,
ValidationError,
NotFoundError,
NetworkError,
TimeoutError
} from '@enprompta/sdk'
try {
await client.prompts.get('invalid_id')
} catch (error) {
if (error instanceof NotFoundError) {
console.log('Prompt not found')
} else if (error instanceof AuthenticationError) {
console.log('Invalid API key')
} else if (error instanceof RateLimitError) {
console.log(`Rate limited. Retry after ${error.retryAfter}s`)
} else if (error instanceof ValidationError) {
console.log('Validation errors:', error.errors)
} else if (error instanceof NetworkError) {
console.log('Network error:', error.message)
} else if (error instanceof TimeoutError) {
console.log('Request timed out')
} else if (error instanceof EnpromptaError) {
console.log(`API error ${error.code}: ${error.message}`)
}
}Retry Strategies
Built-in retry strategies for handling transient failures.
import { Enprompta, RetryStrategies } from '@enprompta/sdk'
const client = new Enprompta({
apiKey: 'ep_your_api_key',
retry: {
// Built-in strategies
strategy: RetryStrategies.exponential, // 1s, 2s, 4s, 8s...
// strategy: RetryStrategies.linear, // 1s, 2s, 3s, 4s...
// strategy: RetryStrategies.fixed, // Always same delay
// strategy: RetryStrategies.aggressive, // Quick retries
// strategy: RetryStrategies.conservative, // Long delays
// strategy: RetryStrategies.rateLimitAware, // Respects 429
maxRetries: 3,
baseDelay: 1000,
maxDelay: 30000
}
})| Strategy | Delays | Use Case |
|---|---|---|
exponential | 1s, 2s, 4s, 8s... | General purpose (default) |
linear | 1s, 2s, 3s, 4s... | Predictable backoff |
fixed | 1s, 1s, 1s... | Consistent retry timing |
aggressive | 100ms, 200ms... | Quick recovery |
conservative | 5s, 10s... | Resource-constrained |
rateLimitAware | Uses Retry-After header | Rate limit handling |