41 lines
1.0 KiB
TypeScript
41 lines
1.0 KiB
TypeScript
import OpenAI from 'openai';
|
|
import { OPENAI_API_KEY } from '$env/static/private';
|
|
|
|
const openai = new OpenAI({
|
|
apiKey: OPENAI_API_KEY,
|
|
});
|
|
|
|
function processChatGptResult(resultString: string) {
|
|
// Split the string by newline
|
|
const lines: string[] = resultString.split('\n');
|
|
|
|
// Remove enumeration at the beginning of each line
|
|
const processedLines: string[] = lines.map(line => line.replace(/^\s*[\d.-]+\s*/, ''));
|
|
|
|
return processedLines.filter(line => line.length > 0);
|
|
}
|
|
|
|
export async function chat(prompt: string, { isList, temperature }: { isList?: boolean, temperature?: number } = {}) {
|
|
|
|
const chatCompletion = await openai.chat.completions.create({
|
|
model: "gpt-4",
|
|
temperature: temperature ?? 0.9,
|
|
messages: [
|
|
{
|
|
"role": "system",
|
|
"content": prompt,
|
|
},
|
|
],
|
|
});
|
|
|
|
const res = chatCompletion.choices[0].message.content;
|
|
|
|
if (res && isList) return processChatGptResult(res);
|
|
|
|
return res;
|
|
}
|
|
|
|
export function image(prompt: string) {
|
|
return openai.images.generate({ model: "dall-e-3", prompt });
|
|
}
|