we're actually calling openai
This commit is contained in:
27
src/server/utils/fillTemplate.ts
Normal file
27
src/server/utils/fillTemplate.ts
Normal file
@@ -0,0 +1,27 @@
|
||||
export type JSONSerializable =
|
||||
| string
|
||||
| number
|
||||
| boolean
|
||||
| null
|
||||
| JSONSerializable[]
|
||||
| { [key: string]: JSONSerializable };
|
||||
|
||||
export type VariableMap = Record<string, string>;
|
||||
|
||||
export default function fillTemplate<T extends JSONSerializable>(
|
||||
template: T,
|
||||
variables: VariableMap
|
||||
): T {
|
||||
if (typeof template === "string") {
|
||||
return template.replace(/{{\s*(\w+)\s*}}/g, (_, key: string) => variables[key] || "") as T;
|
||||
} else if (Array.isArray(template)) {
|
||||
return template.map((item) => fillTemplate(item, variables)) as T;
|
||||
} else if (typeof template === "object" && template !== null) {
|
||||
return Object.keys(template).reduce((acc, key) => {
|
||||
acc[key] = fillTemplate(template[key] as JSONSerializable, variables);
|
||||
return acc;
|
||||
}, {} as { [key: string]: JSONSerializable } & T);
|
||||
} else {
|
||||
return template;
|
||||
}
|
||||
}
|
||||
19
src/server/utils/openai.ts
Normal file
19
src/server/utils/openai.ts
Normal file
@@ -0,0 +1,19 @@
|
||||
import { JSONSerializable } from "./fillTemplate";
|
||||
|
||||
export async function getChatCompletion(payload: JSONSerializable, apiKey: string) {
|
||||
const response = await fetch("https://api.openai.com/v1/chat/completions", {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
Authorization: `Bearer ${apiKey}`,
|
||||
},
|
||||
body: JSON.stringify(payload),
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(`OpenAI API request failed with status ${response.status}`);
|
||||
}
|
||||
|
||||
const data = (await response.json()) as JSONSerializable;
|
||||
return data;
|
||||
}
|
||||
Reference in New Issue
Block a user