Official docs - https://platform.openai.com/docs/api-reference/chat
- types included
- docs included
- Stream included
npm i chatgpt-wrapper
or
yarn add chatgpt-wrapper
const { ChatGPT } = require('chatgpt-wrapper');
import { ChatGPT } from 'chatgpt-wrapper';
with Types
import { ChatGPT, Message, ReqBody, ResBody } from 'chatgpt-wrapper';
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)
});
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.
try {
const answer = await chat.send('question');
// ...
} catch (err) {
// handle error
}
chat.send('question')
.then((answer) => { /* ... */ })
.catch((err) => { /* handle error */ });
Use this method to send request to ChatGPT API
Raw string equals to
{
model: 'gpt-3.5-turbo',
messages: [{
role: 'user',
content: 'YOUR STRING',
}],
}
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);
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);
})();
Message in chat format
Source: index.ts#L4
Request body
Source: index.ts#L21
Response body
Source: index.ts#L120
OpenAI API error
Source: index.ts#L195