-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlib-openai.js
More file actions
49 lines (36 loc) · 1.2 KB
/
lib-openai.js
File metadata and controls
49 lines (36 loc) · 1.2 KB
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 axios from "axios";
import { parseJSON } from "./util.js";
import logger from "./singletons/logger.js";
const OPENAI_ENDPOINT = process.env.OPENAI_ENDPOINT;
// const OPENAI_ORG = process.env.OPENAI_ORG;
const OPENAI_API_KEY = process.env.OPENAI_API_KEY;
async function getGptChatResponse(prompt) {
const response = await axios({
method: "post",
url: OPENAI_ENDPOINT,
headers: {
"Content-Type": "application/json",
// "OpenAI-Organization": OPENAI_ORG,
Authorization: `Bearer ${OPENAI_API_KEY}`,
},
data: {
model: "gpt-3.5-turbo",
messages: [{ role: "user", content: prompt }],
max_tokens: 3000,
},
});
if (response.status != 200) {
throw new Error("Failed to fetch from OpenAI API");
}
const result = response.data;
return result.choices[0]?.message.content;
}
async function generatePostByOpenai(prompt, topic) {
logger.info("Target topic:", topic);
const generatedPrompts = prompt.replace("${topic}", topic);
const results = await getGptChatResponse(generatedPrompts);
logger.info("Fetched getGptChatResponse results:", results);
const json = parseJSON(results.trim());
return json;
}
export { generatePostByOpenai };