AI-Quickstart/demo/openai.js
2024-06-13 13:22:17 -07:00

40 lines
1.2 KiB
JavaScript

import { Configuration, OpenAIApi } from "openai";
const configuration = new Configuration({
organization: process.env.OPENAI_ORG_ID,
apiKey: process.env.OPENAI_API_KEY,
});
const openai = new OpenAIApi(configuration);
export default async function (transactions, categories) {
if (!configuration.organization) {
return "OpenAI Organization Not Set";
}
if (!configuration.apiKey) {
return "OpenAI API key not configured";
}
try {
const completion = await openai.createCompletion({
model: process.env.OPENAI_MODEL,
prompt: generatePrompt(transactions, categories),
temperature: 0.0,
max_tokens: 2000,
});
return completion.data.choices[0].text;
} catch (error) {
// Consider adjusting the error handling logic for your use case
if (error.response) {
console.error(error.response.status, error.response.data);
} else {
console.error(`Error with OpenAI API request: ${error.message}`);
}
return "Failed to sort transactions"
}
}
function generatePrompt(transactions, categories) {
return `Add one of the following categories to each transaction: ${categories}
${transactions}`;
}