forked from ferrislucas/promptr
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgpt3Service.js
49 lines (44 loc) · 1.5 KB
/
gpt3Service.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
import { Configuration, OpenAIApi } from "openai"
import CliState from "./cliState.js";
import ConfigService from "./configService.js"
import { encode } from "gpt-3-encoder"
export default class Gpt3Service {
static async call(prompt) {
const configuration = new Configuration({
apiKey: process.env.OPENAI_API_KEY
})
const verbose = CliState.verbose()
const openai = new OpenAIApi(configuration)
const config = await ConfigService.retrieveConfig();
const encoded = encode(prompt)
if (verbose) console.log(`Prompt token count: ${encoded.length}`)
const promptLength = encoded.length
const apiConfig = {
...config.api,
prompt: prompt,
max_tokens: (4096 - promptLength),
}
if (verbose) console.log(`GPT-3 apiConfig: ${JSON.stringify(apiConfig)}`)
const response = await openai.createCompletion(apiConfig)
if (!response?.data?.choices) return null
let result = response.data.choices
.map((d) => d?.text?.trim())
.join()
if (verbose) console.log(`--Response--\n${result}`)
const output = this.extractSourceCode(result)
return output
}
static extractSourceCode(input) {
const lines = input.split("\n")
if (lines.length > 0 && lines[0].startsWith("Updated source code:")) {
lines.shift()
}
if (lines.length > 0 && lines[0].startsWith("// Your code")) {
lines.shift()
}
if (lines.length > 0 && lines[0].startsWith("-------")) {
lines.shift()
}
return lines.join("\n")
}
}