Created
February 9, 2025 16:40
-
-
Save tomdevisser/c5d7a58fdb3885b079d4b7ec93960c04 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const { OpenAI: client } = require("openai"); | |
const { config } = require("dotenv"); | |
config(); | |
/** | |
* Class for interacting with OpenAI API. | |
*/ | |
class OpenAI { | |
constructor({ apiKey }) { | |
this.client = new client({ apiKey }); | |
} | |
async createCompletion({ model = "gpt-4o-mini", messages }) { | |
try { | |
const response = await this.client.chat.completions.create({ | |
model, | |
messages, | |
n: 1, | |
}); | |
return response.choices[0].message.content; | |
} catch (error) { | |
console.error(error); | |
throw error; | |
} | |
} | |
async createEmbedding({ model = "text-embedding-ada-002", text }) { | |
try { | |
const response = await this.client.embeddings.create({ | |
model, | |
input: text, | |
}); | |
return response.data[0].embedding; | |
} catch (error) { | |
console.error(error); | |
throw error; | |
} | |
} | |
} | |
module.exports = new OpenAI({ | |
apiKey: process.env.OPENAI_API_KEY, | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment