JSPM

@iskasec/openai

1.1.0
    • ESM via JSPM
    • ES Module Entrypoint
    • Export Map
    • Keywords
    • License
    • Repository URL
    • TypeScript Types
    • README
    • Created
    • Published
    • Downloads 5
    • Score
      100M100P100Q57766F
    • License UNLICENSED

    OpenAI SDK drop-in replacement with automatic Iska logging

    Package Exports

    • @iskasec/openai

    Readme

    @iskasec/openai

    Drop-in replacement for the OpenAI SDK with automatic Iska logging. Zero code changes required!

    Installation

    npm install @iskasec/openai openai
    # or
    yarn add @iskasec/openai openai
    # or
    bun add @iskasec/openai openai

    Quick Start

    Simply replace your OpenAI import with @iskasec/openai and add your Iska API key:

    // Before:
    // import OpenAI from 'openai';
    // const openai = new OpenAI({ apiKey: process.env.OPENAI_API_KEY });
    
    // After:
    import OpenAI from "@iskasec/openai";
    const openai = new OpenAI({
      apiKey: process.env.OPENAI_API_KEY,
      iskaApiKey: process.env.ISKA_API_KEY,
    });
    
    // Use exactly as before - no other code changes needed!
    const completion = await openai.chat.completions.create({
      model: "gpt-4",
      messages: [{ role: "user", content: "Hello world!" }],
    });

    Features

    100% API Compatible - Works with all existing OpenAI code
    Automatic Logging - Every request and response logged to Iska
    Streaming Support - Full support for streaming responses
    TypeScript Support - Complete type preservation
    Zero Performance Impact - Async logging with <1ms overhead
    Error Resilient - OpenAI calls continue even if logging fails

    Compatibility

    Supported OpenAI SDK Versions

    @iskasec/openai is tested and compatible with OpenAI Node SDK versions 4.0.0 through 5.x.

    @iskasec/openai Version OpenAI SDK Version Status
    0.1.x 5.0.0 - 5.x ✅ Fully Supported
    0.1.x 4.0.0 - 4.x ✅ Supported
    0.1.x 6.x ⚠️ Untested

    Runtime Requirements

    • Node.js: 18.0.0 or higher
    • TypeScript: 4.9.0 or higher (if using TypeScript)
    • Bun: Latest version supported

    Version Warnings

    The SDK will warn you at runtime if you're using an unsupported OpenAI SDK version, but will still attempt to function. For best results, use a supported version listed above.

    Configuration

    import { IskaOpenAI } from "@iskasec/openai";
    
    const openai = new IskaOpenAI({
      // OpenAI configuration
      apiKey: process.env.OPENAI_API_KEY,
      organization: "org-...",
      baseURL: "https://api.openai.com/v1",
    
      // Iska configuration
      iskaApiKey: process.env.ISKA_API_KEY, // Required
      iskaEndpoint: "https://custom.iska.ai", // Optional
      verbose: true, // Optional: Enable debug logs
      disableLogging: false, // Optional: Disable Iska logging
    
      // PII Detection configuration (only checks prompts, not responses)
      piiMode: "flag", // Optional: "off" | "flag" | "block" | "redact" (default: "off")
      piiRedactionChar: "*", // Optional: Character for redaction (default: "*")
      piiBlockMessage: "Request blocked due to PII", // Optional: Custom block message
    });

    Examples

    Basic Chat Completion

    const completion = await openai.chat.completions.create({
      model: "gpt-4",
      messages: [
        { role: "system", content: "You are a helpful assistant." },
        { role: "user", content: "What is the capital of France?" },
      ],
      temperature: 0.7,
      max_tokens: 100,
    });
    
    console.log(completion.choices[0].message.content);
    // Automatically logged to Iska with token usage, latency, and metadata

    Streaming Responses

    const stream = await openai.chat.completions.create({
      model: "gpt-4",
      messages: [{ role: "user", content: "Write a poem about AI" }],
      stream: true,
    });
    
    for await (const chunk of stream) {
      process.stdout.write(chunk.choices[0]?.delta?.content || "");
    }
    // Full streaming response automatically logged to Iska

    Function Calling

    const response = await openai.chat.completions.create({
      model: "gpt-4",
      messages: [{ role: "user", content: "What's the weather in Boston?" }],
      tools: [
        {
          type: "function",
          function: {
            name: "get_weather",
            description: "Get the weather in a location",
            parameters: {
              type: "object",
              properties: {
                location: { type: "string" },
              },
              required: ["location"],
            },
          },
        },
      ],
    });
    // Function calls are logged with full tool interaction details

    Graceful Shutdown

    // Ensure all logs are flushed before exit
    await openai.shutdown();

    Health Check

    // Check if Iska logging is operational
    const isHealthy = await openai.healthCheck();
    console.log(`Iska logging status: ${isHealthy ? "healthy" : "unhealthy"}`);

    PII Detection

    Iska can automatically detect and handle personally identifiable information (PII) in your prompts using Microsoft Presidio. Note: PII detection only applies to prompts (user input), not responses, ensuring your input data is protected while maintaining visibility into AI outputs.

    // Configure PII detection
    const openai = new IskaOpenAI({
      apiKey: process.env.OPENAI_API_KEY,
      iskaApiKey: process.env.ISKA_API_KEY,
      piiMode: "flag", // Detect and log PII but don't block
    });
    
    // Example with different PII modes:
    
    // 1. Flag mode - Detects and logs PII but allows the request
    const flagMode = new IskaOpenAI({
      iskaApiKey: process.env.ISKA_API_KEY,
      piiMode: "flag",
    });
    
    // 2. Block mode - Blocks requests containing PII
    const blockMode = new IskaOpenAI({
      iskaApiKey: process.env.ISKA_API_KEY,
      piiMode: "block",
      piiBlockMessage: "Request contains sensitive data",
    });
    
    // 3. Redact mode - Automatically redacts PII before sending to OpenAI
    const redactMode = new IskaOpenAI({
      iskaApiKey: process.env.ISKA_API_KEY,
      piiMode: "redact",
      piiRedactionChar: "X",
    });
    
    // Example usage with PII
    try {
      const response = await blockMode.chat.completions.create({
        model: "gpt-4",
        messages: [
          {
            role: "user",
            content: "My SSN is 123-45-6789 and email is john@example.com",
          },
        ],
      });
    } catch (error) {
      if (error.name === "PiiBlockedError") {
        console.log("Request blocked due to PII:", error.entities);
      }
    }

    How It Works

    • Only the last user message in the conversation is checked for PII (not the entire conversation history)
    • System prompts are checked once when provided
    • Detection happens before sending to OpenAI
    • Powered by Microsoft Presidio for accurate detection

    Supported PII Types

    Iska detects the following PII entity types using Microsoft Presidio:

    • Personal Identifiers: SSN, Driver's License, Passport
    • Financial: Credit Cards, Bank Accounts, Routing Numbers
    • Contact: Email Addresses, Phone Numbers, Physical Addresses
    • Medical (HIPAA): Medical Record Numbers, Health Insurance IDs, Medicare IDs
    • Technical: IP Addresses, API Keys, AWS Keys
    • Other: Date of Birth, URLs with PII

    What Gets Logged?

    Every API call automatically logs:

    • Prompt & Response - Full conversation content
    • Token Usage - Prompt, completion, and total tokens
    • Model Details - Model name, temperature, and other parameters
    • Performance - Request latency
    • Metadata - Completion ID, finish reason, system fingerprint
    • Streaming - Full reconstructed responses from streams

    Migration Guide

    From OpenAI SDK

    1. Install @iskasec/openai alongside your existing OpenAI SDK:

      npm install @iskasec/openai openai@^5.0.0
    2. Change your import:

      // From:
      import OpenAI from "openai";
      
      // To:
      import OpenAI from "@iskasec/openai";
    3. Add your Iska API key:

      const openai = new OpenAI({
        apiKey: process.env.OPENAI_API_KEY,
        iskaApiKey: process.env.ISKA_API_KEY, // Add this line
      });

    That's it! All your existing code continues to work exactly as before.

    Upgrading from OpenAI SDK v4 to v5

    If you're currently using OpenAI SDK v4, you'll need to upgrade to v5 first before using @iskasec/openai. Key changes in v5:

    • Import changes: Default export instead of named export
    • Client initialization: new OpenAI() instead of new OpenAIApi()
    • Method names: Some methods have been renamed or restructured

    See the OpenAI SDK v5 migration guide for detailed upgrade instructions.

    Version-Specific Notes

    Using with OpenAI SDK 5.x

    No additional configuration needed. All features work out of the box.

    Future Compatibility

    When OpenAI SDK v6 is released, we'll test compatibility and update this package accordingly. Check our GitHub releases for updates.

    Environment Variables

    # Required
    OPENAI_API_KEY=sk-...
    ISKA_API_KEY=iska_live_...
    
    # Optional
    ISKA_ENDPOINT=https://custom.iska.ai
    ISKA_VERBOSE=true
    ISKA_PII_MODE=flag  # Set PII detection mode
    ISKA_PII_REDACTION_CHAR=#  # Set redaction character
    ISKA_PII_BLOCK_MESSAGE="Contains sensitive information"  # Set block message

    TypeScript

    Full TypeScript support with all OpenAI types preserved:

    import { IskaOpenAI } from "@iskasec/openai";
    import type {
      ChatCompletion,
      ChatCompletionMessage,
      ChatCompletionCreateParams,
    } from "@iskasec/openai";
    
    const openai = new IskaOpenAI({
      apiKey: process.env.OPENAI_API_KEY!,
      iskaApiKey: process.env.ISKA_API_KEY!,
    });
    
    const params: ChatCompletionCreateParams = {
      model: "gpt-4",
      messages: [{ role: "user", content: "Hello!" }],
    };
    
    const completion: ChatCompletion = await openai.chat.completions.create(params);

    Error Handling

    Iska logging failures never interrupt your OpenAI calls:

    const openai = new IskaOpenAI({
      apiKey: process.env.OPENAI_API_KEY,
      iskaApiKey: "invalid-key", // Even with invalid Iska key
      verbose: true,
    });
    
    // OpenAI call still works!
    const completion = await openai.chat.completions.create({
      model: "gpt-4",
      messages: [{ role: "user", content: "Hello!" }],
    });
    // Logs: "[Iska-OpenAI] Failed to log completion: ..."
    // But completion is still returned successfully