You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
46 lines
1.3 KiB
46 lines
1.3 KiB
9 months ago
|
const { OpenAI } = require("openai");
|
||
|
require("dotenv").config({
|
||
|
path: require("os").homedir() + "/.config/fabric/.env",
|
||
|
});
|
||
|
|
||
9 months ago
|
let openaiClient = null;
|
||
|
|
||
|
// Function to initialize and get the OpenAI client
|
||
|
function getOpenAIClient() {
|
||
|
if (!process.env.OPENAI_API_KEY) {
|
||
|
throw new Error(
|
||
|
"The OPENAI_API_KEY environment variable is missing or empty."
|
||
|
);
|
||
|
}
|
||
|
return new OpenAI({ apiKey: process.env.OPENAI_API_KEY });
|
||
|
}
|
||
9 months ago
|
|
||
|
async function queryOpenAI(system, user, callback) {
|
||
9 months ago
|
const openai = getOpenAIClient(); // Ensure the client is initialized here
|
||
9 months ago
|
const messages = [
|
||
|
{ role: "system", content: system },
|
||
|
{ role: "user", content: user },
|
||
|
];
|
||
|
try {
|
||
|
const stream = await openai.chat.completions.create({
|
||
9 months ago
|
model: "gpt-4-1106-preview", // Adjust the model as necessary.
|
||
9 months ago
|
messages: messages,
|
||
|
temperature: 0.0,
|
||
|
top_p: 1,
|
||
|
frequency_penalty: 0.1,
|
||
|
presence_penalty: 0.1,
|
||
|
stream: true,
|
||
|
});
|
||
|
|
||
|
for await (const chunk of stream) {
|
||
|
const message = chunk.choices[0]?.delta?.content || "";
|
||
|
callback(message); // Process each chunk of data
|
||
|
}
|
||
|
} catch (error) {
|
||
|
console.error("Error querying OpenAI:", error);
|
||
|
callback("Error querying OpenAI. Please try again.");
|
||
|
}
|
||
|
}
|
||
|
|
||
|
module.exports = { queryOpenAI };
|