PromptRails

JavaScript SDK

Official JavaScript/TypeScript SDK for PromptRails with full type safety, ESM and CJS support, and automatic retries.

JavaScript SDK

The official JavaScript/TypeScript SDK for PromptRails provides a fully typed client for interacting with the PromptRails API from Node.js, Deno, or browser environments.

Installation

npm install @promptrails/sdk

Or with other package managers:

yarn add @promptrails/sdk
pnpm add @promptrails/sdk

Supports both ESM and CommonJS module formats.

Current release: v0.3.1 — streaming chat & executions, typed AgentConfig union, VERSION export. See the changelog.

Client Initialization

import { PromptRails } from '@promptrails/sdk'
 
const client = new PromptRails({
  apiKey: 'your-api-key',
  baseUrl: 'https://api.promptrails.ai', // default
  timeout: 30000, // milliseconds, default
  maxRetries: 3, // default
})

Configuration

ParameterTypeDefaultDescription
apiKeystringRequiredPromptRails API key
baseUrlstringhttps://api.promptrails.aiAPI base URL
timeoutnumber30000Request timeout in milliseconds
maxRetriesnumber3Maximum retry attempts

Available Resources

ResourcePropertyDescription
Agentsclient.agentsAgent CRUD, versioning, execution
Promptsclient.promptsPrompt CRUD, versioning, execution
Executionsclient.executionsExecution listing and details
Credentialsclient.credentialsCredential management
Data Sourcesclient.dataSourcesData source CRUD, versioning, execution
Chatclient.chatSend messages to chat sessions
Sessionsclient.sessionsChat session management
Memoriesclient.memoriesAgent memory CRUD and search
Tracesclient.tracesTrace listing and filtering
Costsclient.costsCost analysis and summaries
MCP Toolsclient.mcpToolsMCP tool management
MCP Templatesclient.mcpTemplatesMCP template browsing
Guardrailsclient.guardrailsGuardrail configuration
Approvalsclient.approvalsApproval request management
Scoresclient.scoresScoring and evaluation
Templatesclient.templatesFlow templates
Dashboardclient.dashboardAgent UI deployments
Sessionsclient.sessionsSession management
A2Aclient.a2aAgent-to-Agent protocol
LLM Modelsclient.llmModelsAvailable LLM models
Webhook Triggersclient.webhookTriggersWebhook trigger management

Common Operations

Execute an Agent

const result = await client.agents.execute('agent-id', {
  input: { message: 'Hello, world!' },
  metadata: { source: 'api' },
})
 
console.log(result.data.output)
console.log(`Cost: $${result.data.cost.toFixed(6)}`)

List Agents

const agents = await client.agents.list({ page: 1, limit: 20 })
 
for (const agent of agents.data) {
  console.log(`${agent.name} (${agent.type})`)
}

Create a Prompt

const prompt = await client.prompts.create({
  name: 'Summarizer',
  description: 'Summarizes text',
})
 
const version = await client.prompts.createVersion(prompt.data.id, {
  systemPrompt: 'You are a concise summarizer.',
  userPrompt: 'Summarize: {{ text }}',
  temperature: 0.5,
  message: 'Initial version',
})

Chat

const session = await client.chat.createSession({
  agentId: 'agent-id',
})
 
const response = await client.chat.sendMessage(session.id, {
  content: 'What is PromptRails?',
})
 
console.log(response.content)

Stream a Chat Turn

sendMessageStream posts a user message and yields typed Server-Sent Events on the same HTTP connection — useful for showing the agent's reasoning, tool calls, and token-by-token deltas in the UI.

const session = await client.chat.createSession({ agentId: 'agent-id' })
 
const controller = new AbortController()
 
for await (const event of client.chat.sendMessageStream(
  session.id,
  { content: 'What is PromptRails?' },
  { signal: controller.signal },
)) {
  switch (event.type) {
    case 'execution':
      console.log('execution_id:', event.executionId)
      break
    case 'thinking':
      console.log('[thinking]', event.content)
      break
    case 'tool_start':
      console.log('[tool_start]', event.name)
      break
    case 'tool_end':
      console.log('[tool_end]', event.name, event.summary)
      break
    case 'content':
      process.stdout.write(event.content)
      break
    case 'done':
      console.log('\n[done]', event.tokenUsage)
      break
    case 'error':
      console.error('[error]', event.message)
      break
  }
}

Cancel an in-flight stream with controller.abort(). All event shapes are exported via the StreamEvent discriminated union:

import type { StreamEvent } from '@promptrails/sdk'

Stream an Existing Execution

When an execution was started outside a chat (e.g. client.agents.execute), subscribe to its live event stream with client.executions.stream:

for await (const event of client.executions.stream(executionId)) {
  if (event.type === 'content') process.stdout.write(event.content)
  if (event.type === 'done') break
}

Search Memories

const results = await client.memories.search({
  agentId: 'agent-id',
  query: 'refund policy',
  limit: 5,
})

Create a Score

await client.scores.create({
  traceId: 'trace-id',
  name: 'quality',
  dataType: 'numeric',
  value: 4.5,
  source: 'manual',
})

Approve an Execution

await client.approvals.decide('approval-id', {
  decision: 'approved',
  reason: 'Looks good',
})

Typed Agent Config

createVersion takes a typed AgentConfig — a discriminated union by agent type. The SDK injects the type discriminator automatically, so renames in the backend schema (e.g. prompt_version_idprompt_id) surface as TypeScript errors instead of silent runtime failures.

import {
  SimpleAgentConfig,
  ChainAgentConfig,
  MultiAgentConfig,
  WorkflowAgentConfig,
  CompositeAgentConfig,
  PromptLink,
} from '@promptrails/sdk'
 
// Simple agent — one prompt per execution
const simple: SimpleAgentConfig = {
  type: 'simple',
  prompt_id: 'prompt-id',
  approval_required: false,
}
 
// Chain agent — prompts run sequentially, output of step N feeds step N+1
const chain: ChainAgentConfig = {
  type: 'chain',
  prompt_ids: [
    { prompt_id: 'p1', role: 'step1', sort_order: 0 },
    { prompt_id: 'p2', role: 'step2', sort_order: 1 },
  ],
}
 
await client.agents.createVersion('agent-id', {
  version: '1.0.0',
  config: simple,
  set_current: true,
})

Available variants: SimpleAgentConfig, ChainAgentConfig, MultiAgentConfig, WorkflowAgentConfig, CompositeAgentConfig. Chain and multi-agent configs use PromptLink[]; workflow uses WorkflowNode[]; composite uses CompositeStep[]. See Agent Versioning for the per-type field reference.

SDK Version

import { VERSION } from '@promptrails/sdk'
console.log(VERSION) // "0.3.1"

The SDK also sends User-Agent: promptrails-js/<version> on every request (except in browsers, where fetch ignores the header).

TypeScript Types

The SDK includes full TypeScript type definitions. All request and response types are exported:

import type {
  Agent,
  Prompt,
  Execution,
  Trace,
  Score,
  Credential,
  ChatSession,
} from '@promptrails/sdk'

Error Handling

The SDK throws typed errors for different HTTP status codes:

import {
  PromptRailsError,
  ValidationError,
  UnauthorizedError,
  ForbiddenError,
  NotFoundError,
  RateLimitError,
  ServerError,
} from '@promptrails/sdk'
 
try {
  const result = await client.agents.execute('invalid-id', { input: {} })
} catch (error) {
  if (error instanceof NotFoundError) {
    console.log(`Agent not found: ${error.message}`)
  } else if (error instanceof ValidationError) {
    console.log(`Invalid input: ${error.message}`)
    console.log(`Details:`, error.details)
  } else if (error instanceof RateLimitError) {
    console.log(`Rate limited: ${error.message}`)
  } else if (error instanceof UnauthorizedError) {
    console.log(`Invalid API key: ${error.message}`)
  } else if (error instanceof ForbiddenError) {
    console.log(`Insufficient permissions: ${error.message}`)
  } else if (error instanceof ServerError) {
    console.log(`Server error (${error.statusCode}): ${error.message}`)
  } else if (error instanceof PromptRailsError) {
    console.log(`Unexpected error: ${error.message}`)
  }
}

Error Classes

ExceptionHTTP StatusDescription
ValidationError400Invalid request parameters
UnauthorizedError401Invalid or missing API key
ForbiddenError403Insufficient permissions
NotFoundError404Resource not found
RateLimitError429Rate limit exceeded
ServerError5xxServer-side error
PromptRailsErrorAnyBase class for all errors

All error instances include:

  • message -- Error description
  • statusCode -- HTTP status code
  • code -- Optional error code
  • details -- Optional additional details object

ESM and CJS Support

The SDK ships with both ESM and CommonJS builds:

// ESM
import { PromptRails } from '@promptrails/sdk'
 
// CommonJS
const { PromptRails } = require('@promptrails/sdk')

Pagination

// Page-based pagination
const page1 = await client.agents.list({ page: 1, limit: 20 })
const page2 = await client.agents.list({ page: 2, limit: 20 })