-
-
Notifications
You must be signed in to change notification settings - Fork 12
/
Copy pathapi.js
52 lines (44 loc) · 1.43 KB
/
api.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
51
52
import fetch from "isomorphic-fetch";
import dotenv from "dotenv";
dotenv.config();
import debug from "debug";
const error = debug("minecraft-openai.api:error");
const log = debug("minecraft-openai.api:log");
const STOP_WORD = "//";
const EOL = "\n";
/**
* Call the OpenAI API with the previous context and the new user input.
*
* @param {string} input The user's input from the Minecraft chat.
* @param {string} context The previous context to be sent to the OpenAI API
* @returns {Pormise<{ id: string, object: string, created: number, mode: string, choices: Array<{ text: string, index: number, logprobs: any, finish_reason: text }> }>}
*/
export async function callOpenAI(input, context) {
const openAIkey = process.env.CODEX_API_KEY;
if (!openAIkey) {
error("ERROR: CODEX_API_KEY is required.");
process.exit(1);
}
const body = {
prompt: `${context}${EOL}${STOP_WORD} ${input}${EOL}`,
max_tokens: 300,
temperature: 0,
stop: STOP_WORD,
n: 1,
};
log("payload %o", body);
log("context:\n", body.prompt);
const response = await fetch("https://api.openai.com/v1/engines/davinci-codex/completions", {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${openAIkey}`,
},
body: JSON.stringify(body),
});
if (!response.ok) {
error("api response failed with statis %s", response.statusText);
return;
}
return await response.json();
}