Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

openai-api

Package Overview
Dependencies
Maintainers
1
Versions
31
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

openai-api - npm Package Compare versions

Comparing version 1.1.2 to 1.2.0

.prettierrc

44

config.js
const DEFAULT_ENGINE = 'davinci';
const ENGINE_LIST = ['ada', 'babbage', 'curie', 'davinci', 'davinci-instruct-beta','curie-instruct-beta'];
const ENGINE_LIST = ['ada', 'babbage', 'curie', 'davinci', 'davinci-instruct-beta', 'curie-instruct-beta'];
const ORIGIN = 'https://api.openai.com';
const API_VERSION = 'v1';
const OPEN_AI_URL = `${ORIGIN}/${API_VERSION}`
module.exports = {
completionURL: (engine) => {
if (!engine) {
engine = DEFAULT_ENGINE;
}
return `https://api.openai.com/v1/engines/${engine}/completions`;
},
searchURL: (engine) => {
if (!engine) {
engine = DEFAULT_ENGINE;
}
return `https://api.openai.com/v1/engines/${engine}/search`;
completionURL(engine) {
if (!ENGINE_LIST.includes(engine)) {
engine = DEFAULT_ENGINE;
}
}
return `${OPEN_AI_URL}/engines/${engine}/completions`;
},
searchURL(engine) {
if (!ENGINE_LIST.includes(engine)) {
engine = DEFAULT_ENGINE;
}
return `${OPEN_AI_URL}/engines/${engine}/search`;
},
enginesUrl() {
return `${OPEN_AI_URL}/engines`;
},
engineUrl(engine) {
return `${OPEN_AI_URL}/engines/${engine}`;
},
classificationsUrl() {
return `${OPEN_AI_URL}/classifications`
},
filesUrl() {
return `${OPEN_AI_URL}/files`
},
answersUrl() {
return `${OPEN_AI_URL}/answers`
}
};
"use strict";
const config = require('./config'),
axios = require('axios');
const config = require('./config');
const axios = require('axios');
class OpenAI {
constructor(api_key) {
this._api_key = api_key;
}
constructor(api_key) {
this._api_key = api_key;
}
_safe_cast(number) {
return isNaN(Number(number)) ? null : Number(number);
_send_request(url, method, opts = {}) {
let camelToUnderscore = (key) => {
let result = key.replace(/([A-Z])/g, " $1");
return result.split(' ').join('_').toLowerCase();
}
_construct_parameter(name, value) {
return (typeof value === 'undefined' || value === null) ? null : { [name]: value };
const data = {};
for (const key in opts) {
data[camelToUnderscore(key)] = opts[key];
}
_send_request(opts) {
const url = config.completionURL(opts.engine);
const reqOpts = {
headers: {
'Authorization': `Bearer ${this._api_key}`,
'Content-Type': 'application/json'
}
};
const data = Object.assign({},
this._construct_parameter("prompt", opts.prompt),
this._construct_parameter("stream", opts.stream),
this._construct_parameter("stop", opts.stop),
this._construct_parameter("max_tokens", this._safe_cast(opts.maxTokens)),
this._construct_parameter("temperature", this._safe_cast(opts.temperature)),
this._construct_parameter("top_p", this._safe_cast(opts.topP)),
this._construct_parameter("presence_penalty", this._safe_cast(opts.presencePenalty)),
this._construct_parameter("frequency_penalty", this._safe_cast(opts.frequencyPenalty)),
this._construct_parameter("best_of", this._safe_cast(opts.bestOf)),
this._construct_parameter("n", this._safe_cast(opts.n)),
this._construct_parameter("logprobs", this._safe_cast(opts.logprobs)),
this._construct_parameter("echo", opts.echo),
);
return axios.post(url, data, reqOpts);
}
return axios({
url,
headers: {
'Authorization': `Bearer ${this._api_key}`,
'Content-Type': 'application/json'
},
data: Object.keys(data).length ? data : '',
method,
});
}
complete(opts) {
return this._send_request(opts);
}
complete(opts) {
const url = config.completionURL(opts.engine);
delete opts.engine;
encode(str) {
// This method is no longer supported in Node>=v14. See
return Promise.resolve(new Array(2047).fill(""));
}
return this._send_request(url, 'post', opts);
}
search(opts) {
const url = config.searchURL(opts.engine);
const reqOpts = {
headers: {
'Authorization': `Bearer ${this._api_key}`,
'Content-Type': 'application/json'
}
};
const data = {
documents: opts.documents,
query: opts.query
};
return axios.post(url, data, reqOpts);
}
encode() {
// This method is no longer supported in Node>=v14. See
return Promise.resolve(new Array(2047).fill(""));
}
search(opts) {
const url = config.searchURL(opts.engine)
delete opts.engine;
return this._send_request(url, 'post', opts);
}
answers(opts) {
const url = config.answersUrl();
return this._send_request(url, 'post', opts);
}
engines() {
const url = config.enginesUrl();
return this._send_request(url, 'get')
}
engine(engine) {
const url = config.engineUrl(engine);
return this._send_request(url, 'get');
}
}
module.exports = OpenAI;
{
"name": "openai-api",
"version": "1.1.2",
"version": "1.2.0",
"description": "A tiny client module for the openAI API",

@@ -19,2 +19,31 @@ "main": "index.js",

"author": "Nikita Jerschow",
"contributors": [
{
"url": "https://github.com/Njerschow"
},
{
"url": "https://github.com/uvafan"
},
{
"url": "https://github.com/AlbertGozzi"
},
{
"url": "https://github.com/LauraWartschinski"
},
{
"url": "https://github.com/kian-g"
},
{
"url": "https://github.com/timconnorz"
},
{
"url": "https://github.com/schnerd"
},
{
"url": "https://github.com/anonrose"
},
{
"url": "https://github.com/Cormanz"
}
],
"license": "ISC",

@@ -26,3 +55,4 @@ "repository": {

"dependencies": {
"axios": "^0.21.1"
"axios": "^0.21.1",
"dotenv": "^8.2.0"
},

@@ -29,0 +59,0 @@ "devDependencies": {

@@ -46,3 +46,3 @@ # openai-api

});
console.log(gptResponse.data);

@@ -79,3 +79,3 @@ })();

});
console.log(gptResponse.data);

@@ -85,2 +85,32 @@ })();

### Answers API call
```js
(async () => {
const gptResponse = await openai.answers({
"documents": ["Puppy A is happy.", "Puppy B is sad."],
"question": "which puppy is happy?",
"search_model": "ada",
"model": "curie",
"examples_context": "In 2017, U.S. life expectancy was 78.6 years.",
"examples": [["What is human life expectancy in the United States?", "78 years."]],
"max_tokens": 5,
"stop": ["\n", "<|endoftext|>"],
});
console.log(gptResponse.data);
})();
```
### Engines API call
```js
(async () => {
const gptResponse = await openai.engines();
console.log(gptResponse.data);
})();
```
### Get number of tokens for string

@@ -87,0 +117,0 @@ #### Not supported as of 4/21. See issue #20

@@ -0,3 +1,3 @@

require('dotenv').config();
const api_key = process.env.OPENAI_TEST_API_KEY;
const expect = require('chai').expect;

@@ -7,55 +7,61 @@ const OpenAI = require('../index');

if (!api_key) {
throw 'api key is needed to run testsuite: set environment variable: OPENAI_TEST_API_KEY'
throw new Error('api key is needed to run testsuite: set environment variable: OPENAI_TEST_API_KEY');
}
describe('basic openai api methods', function () {
this.timeout(4000);
this.timeout(8000);
const openai = new OpenAI(api_key);
const openai = new OpenAI(api_key);
it ('should handle simple completion', function (done) {
openai.complete({
engine: 'ada',
prompt: "this is a test",
maxTokens: 5,
temperature: 0.9,
frequencyPenalty: 0,
bestOf: 1,
stop: ["\n", "lol"]
}).then((result) => {
expect(result).to.be.ok;
done();
})
.catch(err => {
console.error(err);
expect.fail();
});
it('should handle simple completion', async function () {
const result = await openai.complete({
engine: 'ada',
prompt: "this is a test",
maxTokens: 5,
temperature: 0.9,
frequencyPenalty: 0,
bestOf: 1,
stop: ["\n", "lol"]
});
expect(result).to.be.ok;
});
it ('should handle search', function (done) {
openai.search({
engine: 'ada',
documents: ["White House", "hospital", "school"],
query: "the president"
}).then((result) => {
expect(result).to.be.ok;
done();
})
.catch(err => {
console.error(err);
expect.fail();
})
it('should handle search', async function () {
const result = await openai.search({
engine: 'ada',
documents: ["White House", "hospital", "school"],
query: "the president"
});
expect(result).to.be.ok;
});
it ('should return a default value from the encode function', function (done) {
openai.encode('this is a string').then((result) => {
expect(result).to.be.ok;
expect(result.length).to.be.eql(2047);
done();
})
.catch(err => {
console.error(err);
expect.fail();
})
it('should handle answers', async function () {
const result = await openai.answers({
"documents": ["Puppy A is happy.", "Puppy B is sad."],
"question": "which puppy is happy?",
"search_model": "ada",
"model": "curie",
"examples_context": "In 2017, U.S. life expectancy was 78.6 years.",
"examples": [["What is human life expectancy in the United States?", "78 years."]],
"max_tokens": 5,
"stop": ["\n", "<|endoftext|>"],
});
expect(result).to.be.ok;
});
it('should handle engines', async function () {
const result = await openai.engines();
expect(result).to.be.ok;
});
it('should handle engine', async function () {
const result = await openai.engine('ada');
expect(result).to.be.ok;
});
it('should return a default value from the encode function', async function () {
const result = await openai.encode('this is a string')
expect(result).to.be.ok;
expect(result.length).to.be.eql(2047);
});
});
SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc