Installation

Complete guide to installing and configuring the PromptCompose SDK

SDK Installation

The PromptCompose SDK enables developers to integrate prompt resolution, A/B testing, and analytics directly into their applications. This guide covers everything you need to install and configure the SDK.

Requirements

System Requirements

  • Node.js: Version 14.0.0 or higher
  • Package Manager: npm, yarn, or pnpm
  • TypeScript: Version 4.5+ (for TypeScript projects)

PromptCompose Account

  • Active PromptCompose account
  • Project with API access enabled
  • API key and Project ID (get these from Platform Integrations)

Installation

Using npm

npm install @promptcompose/sdk

Using yarn

yarn add @promptcompose/sdk

Using pnpm

pnpm add @promptcompose/sdk

Verify Installation

Check that the SDK installed correctly:

npm list @promptcompose/sdk

You should see the package version in the output.

Basic Setup

1. Import the SDK

Choose the import method that matches your project setup:

TypeScript/ES6 Modules

import { PromptCompose } from '@promptcompose/sdk';

CommonJS

const { PromptCompose } = require('@promptcompose/sdk');

2. Get Your Credentials

From your PromptCompose platform:

  1. Go to Integrations in your project
  2. Click β€œCreate API Key”
  3. Copy your API Key (starts with pc_)
  4. Copy your Project ID (starts with proj_)

3. Initialize the SDK

Create a new PromptCompose instance:

const promptCompose = new PromptCompose(
  'pc_your_api_key_here',      // Your API key
  'proj_your_project_id_here', // Your project ID
  { debug: true }              // Optional: enable debug logging
);

4. Test the Connection

Verify your setup works:

async function testConnection() {
  try {
    const result = await promptCompose.init();
    console.log('βœ… Connected successfully:', result.message);
    return true;
  } catch (error) {
    console.error('❌ Connection failed:', error.message);
    return false;
  }
}

// Test the connection
const isConnected = await testConnection();

Environment Configuration

Environment Variables

For security and flexibility, use environment variables:

Create .env File

# PromptCompose Configuration
PROMPT_COMPOSE_API_KEY=pc_your_api_key_here
PROMPT_COMPOSE_PROJECT_ID=proj_your_project_id_here
PROMPT_COMPOSE_API_URL=https://api.promptcompose.io/api/v1

# Optional: Environment-specific settings
NODE_ENV=development
DEBUG=true

Use in Your Application

import { PromptCompose } from '@promptcompose/sdk';
import dotenv from 'dotenv';

// Load environment variables
dotenv.config();

const promptCompose = new PromptCompose(
  process.env.PROMPT_COMPOSE_API_KEY!,
  process.env.PROMPT_COMPOSE_PROJECT_ID!,
  { debug: process.env.NODE_ENV === 'development' }
);

Environment-Specific Configuration

Configure different environments:

// config/promptcompose.ts
interface PromptComposeConfig {
  apiKey: string;
  projectId: string;
  debug: boolean;
  apiUrl?: string;
}

function getConfig(): PromptComposeConfig {
  const env = process.env.NODE_ENV || 'development';
  
  const configs = {
    production: {
      apiKey: process.env.PROMPT_COMPOSE_API_KEY!,
      projectId: process.env.PROMPT_COMPOSE_PROJECT_ID!,
      debug: false,
      apiUrl: 'https://api.promptcompose.io/api/v1'
    },
    staging: {
      apiKey: process.env.STAGING_PROMPT_COMPOSE_API_KEY!,
      projectId: process.env.STAGING_PROMPT_COMPOSE_PROJECT_ID!,
      debug: true,
      apiUrl: 'https://staging-api.promptcompose.io/api/v1'
    },
    development: {
      apiKey: process.env.DEV_PROMPT_COMPOSE_API_KEY!,
      projectId: process.env.DEV_PROMPT_COMPOSE_PROJECT_ID!,
      debug: true,
      apiUrl: 'http://localhost:8080/api/v1'
    }
  };
  
  return configs[env] || configs.development;
}

export const config = getConfig();

TypeScript Configuration

tsconfig.json Setup

Ensure your TypeScript configuration supports the SDK:

{
  "compilerOptions": {
    "target": "ES2018",
    "module": "ESNext",
    "moduleResolution": "node",
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    "strict": true,
    "skipLibCheck": true,
    "forceConsistentCasingInFileNames": true
  }
}

Type Imports

Import types for better development experience:

import { 
  PromptCompose,
  PromptConfig,
  ResolvedPrompt,
  ABTest,
  ReportABResult,
  ValidationError,
  APIError
} from '@promptcompose/sdk';

// Use types for better IDE support
const config: PromptConfig = {
  config: {
    versionId: 'v1',
    abTesting: { enabled: true, sessionId: 'user-123' }
  }
};

const result: ResolvedPrompt = await promptCompose.resolvePrompt(
  'prompt-id', 
  config, 
  { name: 'John' }
);

Framework Integration

Next.js Integration

API Route Setup

// pages/api/prompts/[id].ts (Pages Router)
// or app/api/prompts/[id]/route.ts (App Router)

import { PromptCompose } from '@promptcompose/sdk';

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

export default async function handler(req, res) {
  if (req.method !== 'POST') {
    return res.status(405).json({ error: 'Method not allowed' });
  }

  try {
    const { promptId, variables, config } = req.body;
    
    const result = await promptCompose.resolvePrompt(
      promptId,
      config,
      variables
    );
    
    res.status(200).json(result);
  } catch (error) {
    console.error('Prompt resolution failed:', error);
    res.status(500).json({ error: error.message });
  }
}

Client-Side Hook

// hooks/usePrompts.ts
import { useState, useCallback } from 'react';

interface UsePromptsReturn {
  resolvePrompt: (id: string, variables?: any) => Promise<string>;
  loading: boolean;
  error: string | null;
}

export function usePrompts(): UsePromptsReturn {
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);

  const resolvePrompt = useCallback(async (
    promptId: string, 
    variables?: any
  ): Promise<string> => {
    setLoading(true);
    setError(null);
    
    try {
      const response = await fetch(`/api/prompts/${promptId}`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ promptId, variables })
      });
      
      if (!response.ok) {
        throw new Error(`HTTP ${response.status}`);
      }
      
      const result = await response.json();
      return result.content;
    } catch (err) {
      const errorMessage = err instanceof Error ? err.message : 'Unknown error';
      setError(errorMessage);
      throw err;
    } finally {
      setLoading(false);
    }
  }, []);

  return { resolvePrompt, loading, error };
}

React Integration

// hooks/usePromptCompose.ts
import { useState, useEffect } from 'react';
import { PromptCompose } from '@promptcompose/sdk';

export function usePromptCompose() {
  const [sdk, setSdk] = useState<PromptCompose | null>(null);
  const [isConnected, setIsConnected] = useState(false);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    const initSDK = async () => {
      try {
        const promptCompose = new PromptCompose(
          process.env.REACT_APP_PROMPT_COMPOSE_API_KEY!,
          process.env.REACT_APP_PROMPT_COMPOSE_PROJECT_ID!
        );
        
        await promptCompose.init();
        setSdk(promptCompose);
        setIsConnected(true);
      } catch (err) {
        const errorMessage = err instanceof Error ? err.message : 'Initialization failed';
        setError(errorMessage);
        console.error('Failed to initialize SDK:', err);
      }
    };

    initSDK();
  }, []);

  return { sdk, isConnected, error };
}

Express.js Integration

// server.ts
import express from 'express';
import { PromptCompose } from '@promptcompose/sdk';

const app = express();
app.use(express.json());

// Initialize SDK
const promptCompose = new PromptCompose(
  process.env.PROMPT_COMPOSE_API_KEY!,
  process.env.PROMPT_COMPOSE_PROJECT_ID!
);

// Initialize on server startup
promptCompose.init().then(() => {
  console.log('PromptCompose SDK initialized');
}).catch(console.error);

// Prompt resolution endpoint
app.post('/api/prompts/:id/resolve', async (req, res) => {
  try {
    const { id } = req.params;
    const { variables, config } = req.body;
    
    const result = await promptCompose.resolvePrompt(id, config, variables);
    res.json(result);
  } catch (error) {
    console.error('Prompt resolution failed:', error);
    res.status(500).json({ 
      error: error instanceof Error ? error.message : 'Unknown error' 
    });
  }
});

app.listen(3000, () => {
  console.log('Server running on port 3000');
});

Advanced Configuration

Custom API URL

Override the default API endpoint:

// Set via environment variable
process.env.PROMPT_COMPOSE_API_URL = 'https://custom-api.yourcompany.com/api/v1';

// Or configure per instance
const promptCompose = new PromptCompose(
  apiKey,
  projectId,
  { 
    debug: true,
    apiUrl: 'https://custom-api.yourcompany.com/api/v1'
  }
);

Request Timeout Configuration

const promptCompose = new PromptCompose(
  apiKey,
  projectId,
  { 
    timeout: 10000, // 10 seconds
    retries: 3,
    debug: true
  }
);

Proxy Configuration

For environments behind corporate proxies:

// Using axios config (if SDK supports it)
const promptCompose = new PromptCompose(
  apiKey,
  projectId,
  {
    proxy: {
      host: 'proxy.company.com',
      port: 8080,
      auth: {
        username: 'user',
        password: 'pass'
      }
    }
  }
);

Verification and Testing

Complete Installation Test

Create a test script to verify everything works:

// test-installation.ts
import { PromptCompose } from '@promptcompose/sdk';
import dotenv from 'dotenv';

dotenv.config();

async function testInstallation() {
  console.log('πŸ§ͺ Testing PromptCompose SDK Installation...\n');

  // 1. Test SDK Import
  console.log('1. βœ… SDK imported successfully');

  // 2. Test Configuration
  const apiKey = process.env.PROMPT_COMPOSE_API_KEY;
  const projectId = process.env.PROMPT_COMPOSE_PROJECT_ID;

  if (!apiKey || !projectId) {
    console.error('❌ Missing API key or project ID in environment variables');
    process.exit(1);
  }
  
  console.log('2. βœ… Environment variables loaded');

  // 3. Test SDK Initialization
  const sdk = new PromptCompose(apiKey, projectId, { debug: true });
  console.log('3. βœ… SDK instance created');

  // 4. Test Connection
  try {
    const connection = await sdk.init();
    console.log('4. βœ… Connection successful:', connection.message);
  } catch (error) {
    console.error('4. ❌ Connection failed:', error.message);
    process.exit(1);
  }

  // 5. Test API Access
  try {
    const prompts = await sdk.listPrompts();
    console.log(`5. βœ… API access working - Found ${prompts.length} prompts`);
  } catch (error) {
    console.error('5. ❌ API access failed:', error.message);
    process.exit(1);
  }

  console.log('\nπŸŽ‰ Installation test completed successfully!');
  console.log('\nNext steps:');
  console.log('- Read the Getting Started guide: /sdk/getting-started');
  console.log('- Explore API Reference: /sdk/api-reference');
  console.log('- Try example implementations: /sdk/examples');
}

testInstallation().catch(console.error);

Run the test:

npx ts-node test-installation.ts

Troubleshooting

Common Installation Issues

Module Not Found

Error: Cannot find module '@promptcompose/sdk'

Solution: Reinstall the package

npm uninstall @promptcompose/sdk
npm install @promptcompose/sdk

TypeScript Compilation Errors

Error: Cannot find name 'PromptCompose'

Solutions:

  • Check import statement syntax
  • Verify tsconfig.json configuration
  • Ensure TypeScript version compatibility

API Connection Errors

Error: Failed to initialize SDK

Solutions:

  • Verify API key and project ID are correct
  • Check network connectivity
  • Confirm API URL is accessible
  • Review environment variable loading

Environment Variable Issues

Error: API key and project ID are required

Solutions:

  • Ensure .env file exists and is properly formatted
  • Verify dotenv is installed and configured
  • Check variable names match exactly
  • Confirm variables are loaded before SDK initialization

Debug Mode

Enable debug logging for troubleshooting:

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

This will output:

  • API request/response details
  • Variable interpolation steps
  • Error context information
  • Performance metrics

Getting Help

If installation issues persist:

  1. Check the Troubleshooting Guide
  2. Review FAQ for common solutions
  3. Verify your PromptCompose account and project settings
  4. Contact support with your error details

Next Steps

With the SDK successfully installed:

  1. Start with the basics: Getting Started Guide
  2. Explore the API: API Reference
  3. Learn A/B testing: A/B Testing Guide
  4. Follow best practices: Best Practices Guide
  5. See examples: Implementation Examples

The PromptCompose SDK is now ready to power your AI prompt integration. Start building with confidence!