npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

openai-enhanced-sdk

v1.0.2

Published

An advanced TypeScript SDK for OpenAI API with built-in context management, proxy support, streaming, and enhanced error handling. Includes logging, retry mechanism, and fully typed responses for seamless AI integration.

Downloads

30

Readme

npm version Build Status License

OpenAI TypeScript Enhanced SDK

OpenAI Enhanced SDK is a fully typed TypeScript SDK that facilitates integration with the OpenAI API. It offers features that the official SDK does not have, such as context management for conversations, proxy support, automatic request retry mechanism, detailed logging system, among others. Additionally, the SDK implements most of the functionalities provided by the OpenAI API. Note: This is an unofficial SDK and is not affiliated with OpenAI.

Table of Contents

Features

  • Complete API Coverage: Implements all major OpenAI API endpoints.
  • Context Management: Manage conversation context easily for chat completions.
  • Streaming Support: Supports streaming for completions and chat completions.
  • Robust Error Handling: Provides custom error classes for different error types.
  • TypeScript Support: Includes comprehensive type definitions.
  • Logging: Configurable logging using Winston.
  • Retry Mechanism: Built-in retry logic using axios-retry.
  • Proxy Support: Enhanced proxy configuration for flexible network setups.
  • Extensible: Easily extendable for future API endpoints.

Installation

Install the package via npm:

npm install openai-enhanced-sdk

Getting Started

Initialization

import OpenAIClient from '../src/openai-client';
import { HttpsProxyAgent } from 'https-proxy-agent';

const apiKey = process.env.OPENAI_API_KEY;

// Proxy agent configuration
const proxyAgent = new HttpsProxyAgent('http://proxy.example.com:8080');

const client = new OpenAIClient(apiKey, {
  baseURL: 'https://api.openai.com/v1',
  timeout: 10000,
  proxyConfig: proxyAgent,
  axiosConfig: {
    headers: {
      'Custom-Header': 'custom-value',
    },
  },
  axiosRetryConfig: {
    retries: 5,
    retryDelay: 2000,
  },
  loggingOptions: {
    logLevel: 'info',
    logToFile: true,
    logFilePath: 'logs/openai-client.log',
  },
});

Authentication

Ensure you have your OpenAI API key stored securely, preferably in an environment variable:

export OPENAI_API_KEY=your_api_key_here

Usage Examples

Context Management

Add a single entry to context

client.addToContext({
  role: 'system',
  content: 'You are a helpful assistant.',
});

Add multiple entries to context

const contextEntries = [
  {
    role: 'user',
    content: 'Tell me a joke.',
  },
  {
    role: 'assistant',
    content: 'Why did the chicken cross the road? To get to the other side!',
  },
];
client.addBatchToContext(contextEntries);

Get current context

const context = client.getContext();
console.log(context);

Clear context

client.clearContext();

Use context in chat completion

const response = await client.createChatCompletion({
  model: 'gpt-3.5-turbo',
  messages: [{ role: 'user', content: 'Do I need an umbrella today?' }],
});
console.log(response);

Proxy Configuration

Using Proxy with Custom HTTPS Agent

import HttpsProxyAgent from 'https-proxy-agent';

const proxyAgent = new HttpsProxyAgent('http://localhost:8080');

const proxyClient = new OpenAIClient(apiKey, {
  proxyConfig: proxyAgent,
});

List Models

const models = await client.listModels();
console.log(models);

Create Completion

const completion = await client.createCompletion({
  model: 'text-davinci-003',
  prompt: 'Once upon a time',
  max_tokens: 5,
});
console.log(completion);

Create Chat Completion

const chatCompletion = await client.createChatCompletion({
  model: 'gpt-3.5-turbo',
  messages: [{ role: 'user', content: 'Hello, how are you?' }],
});
console.log(chatCompletion);

Create Embedding

const embedding = await client.createEmbedding({
  model: 'text-embedding-ada-002',
  input: 'OpenAI is an AI research lab.',
});
console.log(embedding);

Create Image

const image = await client.createImage({
  prompt: 'A sunset over the mountains',
  n: 1,
  size: '512x512',
});
console.log(image);

Error Handling

try {
  const completion = await client.createCompletion({
    model: 'text-davinci-003',
    prompt: 'Hello, world!',
  });
} catch (error) {
  if (error instanceof AuthenticationError) {
    console.error('Authentication Error:', error.message);
  } else if (error instanceof ValidationError) {
    console.error('Validation Error:', error.message);
  } else if (error instanceof RateLimitError) {
    console.error('Rate Limit Exceeded:', error.message);
  } else if (error instanceof APIError) {
    console.error('API Error:', error.message);
  } else {
    console.error('Unknown Error:', error);
  }
}

Configuration

You can customize the client using the OpenAIClientOptions interface:

import HttpsProxyAgent from 'https-proxy-agent';

const proxyAgent = new HttpsProxyAgent('http://localhost:8080');

const client = new OpenAIClient(apiKey, {
  baseURL: 'https://api.openai.com/v1',
  timeout: 10000, // 10 seconds timeout
  proxyConfig: proxyAgent,
  loggingOptions: {
    logLevel: 'debug',
    logToFile: true,
    logFilePath: './logs/openai-sdk.log',
  },
  axiosRetryConfig: {
    retries: 5,
    retryDelay: axiosRetry.exponentialDelay,
  },
});

Logging

The SDK uses Winston for logging. You can configure logging levels and outputs:

loggingOptions: {
  logLevel: 'info', // 'error' | 'warn' | 'info' | 'debug'
  logToFile: true,
  logFilePath: './logs/openai-sdk.log',
}

Testing

The SDK includes comprehensive unit tests using Jest. To run the tests:

npm run test

Documentation

For more detailed information, please refer to the OpenAI Enhanced SDK Documentation.

Contributing

Contributions are welcome! Please open an issue or submit a pull request on GitHub.

License

This project is licensed under the MIT License.


If you have any questions or need assistance, feel free to reach out!