API Reference

Complete reference for all PromptCompose SDK methods, types, and configurations

SDK API Reference

This comprehensive reference covers all PromptCompose SDK classes, methods, types, and configuration options.

PromptCompose Class

The main SDK class for interacting with the PromptCompose API.

Constructor

new PromptCompose(apiKey: string, projectId: string, options?: PromptComposeOptions)

Creates a new PromptCompose SDK instance.

Parameters:

  • apiKey (string) - Your API key from PromptCompose console
  • projectId (string) - Your project ID
  • options (PromptComposeOptions, optional) - Configuration options

Example:

const promptCompose = new PromptCompose(
  'pc_abc123',
  'proj_xyz789',
  { debug: true }
);

Configuration Options

interface PromptComposeOptions {
  debug?: boolean;          // Enable debug logging (default: false)
  timeout?: number;         // Request timeout in ms (default: 30000)
  retries?: number;         // Number of retry attempts (default: 3)
  apiUrl?: string;          // Custom API URL (optional)
}

Core Methods

init()

async init(): Promise<{ message: string }>

Initializes the SDK and verifies connection to PromptCompose API.

Returns: Promise resolving to connection confirmation Throws: APIError if connection fails

Example:

try {
  const result = await promptCompose.init();
  console.log(result.message); // "Connection successful"
} catch (error) {
  console.error('Connection failed:', error.message);
}

resolvePrompt()

async resolvePrompt(
  promptId: string,
  config?: PromptConfig,
  variables?: Record<string, string | number | boolean>
): Promise<ResolvedPrompt>

Resolves a prompt with variable interpolation and A/B testing.

Parameters:

  • promptId (string) - The public ID of the prompt
  • config (PromptConfig, optional) - Resolution configuration
  • variables (Record, optional) - Variables to interpolate

Returns: Promise resolving to resolved prompt data Throws: ValidationError for missing variables, APIError for API failures

Example:

const result = await promptCompose.resolvePrompt(
  'prompt-123',
  {
    config: {
      versionId: 'v1.0',
      abTesting: { sessionId: 'user-456' }
    }
  },
  {
    customerName: 'John Doe',
    productName: 'Widget Pro'
  }
);

console.log(result.content); // Resolved prompt content
console.log(result.variant?.name); // A/B test variant (if applicable)

listPrompts()

async listPrompts(): Promise<Prompt[]>

Retrieves all prompts in the project.

Returns: Promise resolving to array of prompt objects Throws: APIError if request fails

Example:

const prompts = await promptCompose.listPrompts();
prompts.forEach(prompt => {
  console.log(`${prompt.name}: ${prompt.versions.length} versions`);
});

getPrompt()

async getPrompt(promptId: string): Promise<Prompt>

Retrieves a specific prompt by ID.

Parameters:

  • promptId (string) - The public ID of the prompt

Returns: Promise resolving to prompt object Throws: APIError if prompt not found

Example:

const prompt = await promptCompose.getPrompt('prompt-123');
console.log(`Prompt: ${prompt.name}`);
console.log(`Variables: ${prompt.versions[0].variables.length}`);

A/B Testing Methods

listABTests()

async listABTests(): Promise<ABTest[]>

Retrieves all A/B tests in the project.

Returns: Promise resolving to array of A/B test objects

Example:

const tests = await promptCompose.listABTests();
tests.forEach(test => {
  console.log(`${test.name}: ${test.status} (${test.variants.length} variants)`);
});

getABTest()

async getABTest(testId: string): Promise<ABTest>

Retrieves a specific A/B test by ID.

Parameters:

  • testId (string) - The unique ID of the A/B test

Returns: Promise resolving to A/B test object

reportABResult()

async reportABResult(
  testId: string,
  result: ReportABResult
): Promise<ReportABResult>

Reports the result of an A/B test execution.

Parameters:

  • testId (string) - The unique ID of the A/B test
  • result (ReportABResult) - The result data to report

Returns: Promise resolving to confirmed report data Throws: ValidationError for invalid data

Example:

await promptCompose.reportABResult('test-123', {
  variantId: 'variant-abc',
  status: 'success',
  sessionId: 'user-456'
});

Type Definitions

PromptConfig

Configuration for prompt resolution:

interface PromptConfig {
  config: {
    versionId?: string;           // Specific version to use
    abTesting?: {
      enabled?: boolean;          // Enable A/B testing (default: true)
      sessionId?: string;         // Session ID for consistency
      variantId?: string;         // Manual variant selection
    };
  };
}

ResolvedPrompt

The result of prompt resolution:

interface ResolvedPrompt {
  content: string;              // Final rendered content
  source: 'version' | 'variant'; // Source of the content
  prompt: {
    publicId: string;
    name: string;
  };
  version?: {
    publicId: string;
    title: string;
    variables: Variable[];
  };
  variant?: {
    publicId: string;
    name: string;
    content: string;
  };
  abTest?: {
    publicId: string;
    name: string;
    status: string;
  };
}

Prompt

Prompt object structure:

interface Prompt {
  publicId: string;
  name: string;
  description: string;
  tags: string[];
  createdAt: string;
  updatedAt: string;
  versions: PromptVersion[];
}

PromptVersion

Prompt version structure:

interface PromptVersion {
  publicId: string;
  title: string;
  content: string;
  deployedAt: string;
  variables: Variable[];
}

Variable

Variable definition:

interface Variable {
  name: string;
  label: string;
  description: string;
  type: 'text' | 'select' | 'number' | 'boolean';
  required: boolean;
  defaultValue?: string | number | boolean;
  options?: string[];           // For select variables
  validation?: {
    minLength?: number;
    maxLength?: number;
    pattern?: string;
    min?: number;
    max?: number;
  };
}

ABTest

A/B test structure:

interface ABTest {
  publicId: string;
  name: string;
  description: string;
  status: 'active' | 'paused' | 'completed';
  rolloutStrategy: 'weighted' | 'sequential' | 'manual';
  startDate: string;
  endDate: string;
  prompt: {
    publicId: string;
    name: string;
  };
  variants: ABTestVariant[];
}

ABTestVariant

A/B test variant structure:

interface ABTestVariant {
  publicId: string;
  name: string;
  content: string;
  weight: number;               // For weighted strategy
  variables: Variable[];
  metrics: {
    impressions: number;
    conversions: number;
    conversionRate: number;
  };
}

ReportABResult

A/B test result reporting:

interface ReportABResult {
  variantId: string;
  status: 'success' | 'fail' | 'skipped' | 'timeout' | 'error';
  sessionId?: string;
  metadata?: Record<string, any>;
}

Error Classes

APIError

Thrown when API requests fail:

class APIError extends Error {
  status: number;               // HTTP status code
  code: string;                 // Error code
  details?: any;                // Additional error details
}

Example:

try {
  await promptCompose.resolvePrompt('invalid-id');
} catch (error) {
  if (error instanceof APIError) {
    console.error(`API Error ${error.status}: ${error.message}`);
    console.error('Error code:', error.code);
  }
}

ValidationError

Thrown when input validation fails:

class ValidationError extends Error {
  field?: string;               // Field that failed validation
  value?: any;                  // Invalid value
  constraints?: string[];       // Validation constraints
}

Example:

try {
  await promptCompose.resolvePrompt('prompt-123', undefined, {
    // Missing required variable
  });
} catch (error) {
  if (error instanceof ValidationError) {
    console.error(`Validation Error: ${error.message}`);
    console.error('Field:', error.field);
  }
}

Configuration Examples

Basic Configuration

const promptCompose = new PromptCompose(
  process.env.PROMPT_COMPOSE_API_KEY,
  process.env.PROMPT_COMPOSE_PROJECT_ID
);

Development Configuration

const promptCompose = new PromptCompose(
  process.env.DEV_API_KEY,
  process.env.DEV_PROJECT_ID,
  {
    debug: true,
    timeout: 10000,
    apiUrl: 'http://localhost:8080/api/v1'
  }
);

Production Configuration

const promptCompose = new PromptCompose(
  process.env.PROMPT_COMPOSE_API_KEY,
  process.env.PROMPT_COMPOSE_PROJECT_ID,
  {
    debug: false,
    timeout: 30000,
    retries: 3
  }
);

Advanced Usage Patterns

Error Handling

async function safeResolvePrompt(promptId: string, variables: any) {
  try {
    return await promptCompose.resolvePrompt(promptId, undefined, variables);
  } catch (error) {
    if (error instanceof ValidationError) {
      console.error('Missing or invalid variables:', error.message);
      // Provide fallback content
      return { content: 'Default message' };
    } else if (error instanceof APIError) {
      console.error('API request failed:', error.message);
      // Retry logic or fallback
      throw error;
    } else {
      console.error('Unexpected error:', error);
      throw error;
    }
  }
}

Caching Implementation

class CachedPromptCompose {
  private cache = new Map();
  private cacheTimeout = 5 * 60 * 1000; // 5 minutes

  constructor(private sdk: PromptCompose) {}

  async resolvePrompt(promptId: string, config?: any, variables?: any) {
    const cacheKey = this.getCacheKey(promptId, config, variables);
    const cached = this.cache.get(cacheKey);

    if (cached && Date.now() - cached.timestamp < this.cacheTimeout) {
      return cached.result;
    }

    const result = await this.sdk.resolvePrompt(promptId, config, variables);
    this.cache.set(cacheKey, { result, timestamp: Date.now() });

    return result;
  }

  private getCacheKey(promptId: string, config?: any, variables?: any): string {
    return `${promptId}-${JSON.stringify({ config, variables })}`;
  }
}

Batch Operations

async function resolveManyPrompts(
  promptIds: string[],
  variables: Record<string, any>
) {
  const promises = promptIds.map(id => 
    promptCompose.resolvePrompt(id, undefined, variables)
  );

  const results = await Promise.allSettled(promises);
  
  return results.map((result, index) => ({
    promptId: promptIds[index],
    success: result.status === 'fulfilled',
    data: result.status === 'fulfilled' ? result.value : null,
    error: result.status === 'rejected' ? result.reason : null
  }));
}

A/B Testing with Conversion Tracking

class ABTestManager {
  private conversions = new Map();

  async servePrompt(promptId: string, userId: string, variables: any) {
    const result = await promptCompose.resolvePrompt(promptId, {
      config: { abTesting: { sessionId: userId } }
    }, variables);

    // Store test info for conversion tracking
    if (result.variant && result.abTest) {
      this.conversions.set(userId, {
        testId: result.abTest.publicId,
        variantId: result.variant.publicId,
        servedAt: Date.now()
      });
    }

    return result;
  }

  async reportConversion(userId: string, success: boolean) {
    const conversion = this.conversions.get(userId);
    if (!conversion) return;

    await promptCompose.reportABResult(conversion.testId, {
      variantId: conversion.variantId,
      status: success ? 'success' : 'fail',
      sessionId: userId
    });

    this.conversions.delete(userId);
  }
}

Rate Limiting and Quotas

Understanding Rate Limits

Rate limits vary by plan:

  • Free: 1,000 requests/hour
  • Pro: 10,000 requests/hour
  • Enterprise: Custom limits

Handling Rate Limits

async function resolveWithRetry(promptId: string, variables: any, maxRetries = 3) {
  for (let attempt = 1; attempt <= maxRetries; attempt++) {
    try {
      return await promptCompose.resolvePrompt(promptId, undefined, variables);
    } catch (error) {
      if (error instanceof APIError && error.status === 429) {
        const delay = Math.pow(2, attempt) * 1000; // Exponential backoff
        console.log(`Rate limited, retrying in ${delay}ms...`);
        await new Promise(resolve => setTimeout(resolve, delay));
      } else {
        throw error;
      }
    }
  }
  
  throw new Error('Max retries exceeded');
}

Environment Variables

Common environment variables for SDK configuration:

# Required
PROMPT_COMPOSE_API_KEY=pc_your_api_key_here
PROMPT_COMPOSE_PROJECT_ID=proj_your_project_id_here

# Optional
PROMPT_COMPOSE_API_URL=https://api.promptcompose.io/api/v1
PROMPT_COMPOSE_DEBUG=true
PROMPT_COMPOSE_TIMEOUT=30000
PROMPT_COMPOSE_RETRIES=3

Migration Guide

From v1.x to v2.x

Key changes in v2.0:

  • Async/await required for all methods
  • New error classes for better error handling
  • Enhanced A/B testing configuration options
// v1.x (deprecated)
promptCompose.resolvePrompt('id', variables, (err, result) => {
  // callback style
});

// v2.x
const result = await promptCompose.resolvePrompt('id', undefined, variables);

Debugging and Logging

Enable Debug Mode

const promptCompose = new PromptCompose(apiKey, projectId, { 
  debug: true 
});

Debug mode outputs:

  • Request/response details
  • Variable interpolation steps
  • A/B test assignment logic
  • Error context information

Custom Logging

class LoggedPromptCompose {
  constructor(private sdk: PromptCompose, private logger: any) {}

  async resolvePrompt(promptId: string, config?: any, variables?: any) {
    const startTime = Date.now();
    
    try {
      this.logger.info('Resolving prompt', { promptId, variables });
      const result = await this.sdk.resolvePrompt(promptId, config, variables);
      
      this.logger.info('Prompt resolved successfully', {
        promptId,
        duration: Date.now() - startTime,
        variant: result.variant?.name,
        test: result.abTest?.name
      });
      
      return result;
    } catch (error) {
      this.logger.error('Prompt resolution failed', {
        promptId,
        duration: Date.now() - startTime,
        error: error.message
      });
      throw error;
    }
  }
}

For additional help and examples, see: