forked from memochou1993/gpt-ai-assistant
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgenerate-completion.js
50 lines (44 loc) · 1.24 KB
/
generate-completion.js
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
import config from '../config/index.js';
import { MOCK_TEXT_OK } from '../constants/mock.js';
import {
createChatCompletion, createTextCompletion, FINISH_REASON_STOP, MODEL_GPT_3_5_TURBO,
} from '../services/openai.js';
class Completion {
text;
finishReason;
constructor({
text,
finishReason,
}) {
this.text = text;
this.finishReason = finishReason;
}
get isFinishReasonStop() {
return this.finishReason === FINISH_REASON_STOP;
}
}
/**
* @param {Object} param
* @param {Prompt} param.prompt
* @returns {Promise<Completion>}
*/
const generateCompletion = async ({
prompt,
}) => {
if (config.APP_ENV !== 'production') return new Completion({ text: MOCK_TEXT_OK });
if (config.OPENAI_COMPLETION_MODEL.includes(MODEL_GPT_3_5_TURBO)) {
const { data } = await createChatCompletion({ messages: prompt.messages });
const [choice] = data.choices;
return new Completion({
text: choice.message.content.trim(),
finishReason: choice.finish_reason,
});
}
const { data } = await createTextCompletion({ prompt: prompt.toString() });
const [choice] = data.choices;
return new Completion({
text: choice.text.trim(),
finishReason: choice.finish_reason,
});
};
export default generateCompletion;