1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
|
import { Configuration, OpenAIApi } from 'openai';
enum GPTCallType {
SUMMARY = 'summary',
COMPLETION = 'completion',
EDIT = 'edit',
}
type GPTCallOpts = {
model: string;
maxTokens: number;
temp: number;
prompt: string;
};
const callTypeMap: { [type: string]: GPTCallOpts } = {
summary: { model: 'text-davinci-003', maxTokens: 256, temp: 0.5, prompt: 'Summarize this text in simpler terms: ' },
edit: { model: 'text-davinci-003', maxTokens: 256, temp: 0.5, prompt: 'Reword this: ' },
completion: { model: 'text-davinci-003', maxTokens: 256, temp: 0.5, prompt: '' },
};
/**
* Calls the OpenAI API.
*
* @param inputText Text to process
* @returns AI Output
*/
const gptAPICall = async (inputText: string, callType: GPTCallType) => {
if (callType === GPTCallType.SUMMARY) inputText += '.';
const opts: GPTCallOpts = callTypeMap[callType];
try {
const configuration = new Configuration({
apiKey: process.env.OPENAI_KEY,
});
const openai = new OpenAIApi(configuration);
const response = await openai.createCompletion({
model: opts.model,
max_tokens: opts.maxTokens,
temperature: opts.temp,
prompt: `${opts.prompt}${inputText}`,
});
return response.data.choices[0].text;
} catch (err) {
console.log(err);
return 'Error connecting with API.';
}
};
const gptImageCall = async (prompt: string, n?: number) => {
try {
const configuration = new Configuration({
apiKey: process.env.OPENAI_KEY,
});
const openai = new OpenAIApi(configuration);
const response = await openai.createImage({
prompt: prompt,
n: n ?? 1,
size: '1024x1024',
});
return response.data.data.map(data => data.url);
// return response.data.data[0].url;
} catch (err) {
console.error(err);
return;
}
};
export { gptAPICall, gptImageCall, GPTCallType };
|