Nachasic / chatgpt-wrapper

NodeJS ChatGPT API wrapper

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Help

Rate me

ChatGPT-wrapper

ChatGPT API wrapper

Official docs - https://platform.openai.com/docs/api-reference/chat

Features

  • types included
  • docs included
  • Stream included

Install

npm i chatgpt-wrapper

or

yarn add chatgpt-wrapper

Usage

Import

CommonJS

const { ChatGPT } = require('chatgpt-wrapper');

Modules

import { ChatGPT } from 'chatgpt-wrapper';

with Types

import { ChatGPT, Message, ReqBody, ResBody } from 'chatgpt-wrapper';

New instance

Visit your API Keys page to retrieve the API key

const chat = new ChatGPT({
  API_KEY: '...', // Your API KEY (Required)
  ORG: '...',     // Your organization (Optional)
  URL: '...',     // API endpoint (Optional)
});

Error Handling

Do not forget to catch errors from your requests since OpenAI API sometimes returns error message instead of response.

"API error" errors returns APIError type.

async/await

try {
  const answer = await chat.send('question');
  // ...
} catch (err) {
  // handle error
}

Promise

chat.send('question')
  .then((answer) => { /* ... */ })
  .catch((err) => { /* handle error */ });

Methods

send(content: ReqBody | string): Promise<ResBody>

Use this method to send request to ChatGPT API

Raw string equals to

{
  model: 'gpt-3.5-turbo',
  messages: [{
    role: 'user',
    content: 'YOUR STRING',
  }],
}

⚠️ To use stream option, use .stream() method! ⚠️

Examples:

const answer = await chat.send('what is JavaScript');

console.log(answer.choices[0].message);
chat.send('what is JavaScript').then((answer) => {
  console.log(answer.choices[0].message);
});
const answer = await chat.send({
  model: 'gpt-3.5-turbo-0301',
  messages: [{
    role: 'user',
    content: 'what is JavaScript',
  }],
  max_tokens: 200,
});

console.log(answer.choices[0].message);

stream(content: ReqBody | string): Promise<NodeJS.ReadableStream>

Use this method to send request to ChatGPT API and get steam response back

Raw string equals to

{
  model: 'gpt-3.5-turbo',
  stream: true,
  messages: [{
    role: 'user',
    content: 'YOUR STRING',
  }],
}

Examples:

(async () => {
  const answer = await chat.stream('what is JavaScript in 200 words');

  answer.pipe(process.stdout);
})();

Types

Message

Message in chat format

Source: index.ts#L4

ReqBody

Request body

Source: index.ts#L21

ResBody

Response body

Source: index.ts#L120

APIError

OpenAI API error

Source: index.ts#L195

About

NodeJS ChatGPT API wrapper

License:MIT License


Languages

Language:TypeScript 100.0%