|
import { ChatCompletionRequestMessage } from "openai" |
|
import { GPTTokens } from "gpt-tokens" |
|
|
|
import { openai } from "./openai.mts" |
|
import { runModerationCheck } from "./runModerationCheck.mts" |
|
import { getUserContent } from "./getUserContent.mts" |
|
import { getTextPrompt } from "./getTextPrompt.mts" |
|
|
|
export const createChatCompletion = async ( |
|
messages: ChatCompletionRequestMessage[], |
|
model = "gpt-4" |
|
): Promise<string> => { |
|
|
|
const userContent = getUserContent(messages) |
|
|
|
const check = await runModerationCheck(userContent) |
|
|
|
if (check.flagged) { |
|
console.error("Thoughtcrime: content flagged by the AI police", { |
|
userContent, |
|
moderationResult: check, |
|
}) |
|
return "Thoughtcrime: content flagged by the AI police" |
|
} |
|
|
|
const rawPrompt = getTextPrompt(messages) |
|
|
|
|
|
|
|
const usageInfo = new GPTTokens({ |
|
|
|
plus : false, |
|
model : "gpt-4", |
|
messages: messages as any, |
|
}) |
|
|
|
console.table({ |
|
"Tokens prompt": usageInfo.promptUsedTokens, |
|
"Tokens completion": usageInfo.completionUsedTokens, |
|
"Tokens total": usageInfo.usedTokens, |
|
}) |
|
|
|
|
|
console.log("Price USD: ", usageInfo.usedUSD) |
|
|
|
|
|
|
|
const maxTokens = 4000 - usageInfo.promptUsedTokens |
|
|
|
console.log("maxTokens:", maxTokens) |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
console.log("query:", { |
|
model, |
|
|
|
user: "Anonymous User", |
|
temperature: 0.7, |
|
max_tokens: maxTokens, |
|
|
|
}) |
|
|
|
const response = await openai.createChatCompletion({ |
|
model, |
|
messages, |
|
|
|
user: "Anonymous User", |
|
temperature: 0.7, |
|
|
|
|
|
|
|
max_tokens: maxTokens, |
|
|
|
}) |
|
|
|
const { choices } = response.data |
|
|
|
if (!choices.length) { |
|
console.log("createChatCompletion(): no choice found in the LLM response..") |
|
return "" |
|
} |
|
const firstChoice = choices[0] |
|
|
|
if (firstChoice?.message?.role !== "assistant") { |
|
console.log( |
|
"createChatCompletion(): something went wrong, the model imagined the user response?!" |
|
) |
|
return "" |
|
} |
|
|
|
console.log("createChatCompletion(): response", firstChoice.message.content) |
|
|
|
return firstChoice.message.content || "" |
|
} |