Spaces:
Running
on
CPU Upgrade
Running
on
CPU Upgrade
File size: 985 Bytes
e4e0e54 |
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 |
import { ChatCompletionRequestMessage } from "openai"
import { parse } from "yaml"
import { createChatCompletion } from "./createChatCompletion.mts"
export const generateYAML = async <T,>(messages: ChatCompletionRequestMessage[] = [], defaultValue?: T): Promise<T> => {
const defaultResult = defaultValue || ({} as T)
if (!messages.length) {
return defaultResult
}
const output = await createChatCompletion(messages)
let raw = ""
// cleanup any remains of the markdown response
raw = output.split("```")[0]
// remove any remaining `
const input = raw.replaceAll("`", "")
try {
const obj = parse(input) as T
if (obj === null || typeof obj === undefined) {
throw new Error("couldn't parse YAML")
}
return obj
} catch (err) {
// just in case, we also try JSON!
const obj = JSON.parse(input) as T
if (obj === null || typeof obj === undefined) {
throw new Error("couldn't parse JSON")
}
return obj
}
} |