-
Notifications
You must be signed in to change notification settings - Fork 14
/
Copy pathresponse-model.ts
73 lines (60 loc) · 2.03 KB
/
response-model.ts
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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
import {
OAIBuildFunctionParams,
OAIBuildJsonModeParams,
OAIBuildJsonSchemaParams,
OAIBuildMessageBasedParams,
OAIBuildThinkingMessageBasedParams,
OAIBuildToolFunctionParams
} from "@/oai/params"
import OpenAI from "openai"
import { z } from "zod"
import zodToJsonSchema from "zod-to-json-schema"
import { MODE } from "@/constants/modes"
import { Mode, ModeParamsReturnType, ResponseModel } from "./types"
export function withResponseModel<
T extends z.AnyZodObject,
M extends Mode,
P extends OpenAI.ChatCompletionCreateParams
>({
response_model: { name, schema, description = "" },
mode,
params
}: {
response_model: ResponseModel<T>
mode: M
params: P
}): ModeParamsReturnType<P, M> {
const safeName = name.replace(/[^a-zA-Z0-9]/g, "_").replace(/\s/g, "_")
const { definitions } = zodToJsonSchema(schema, {
name: safeName,
errorMessages: true
})
if (!definitions || !definitions?.[safeName]) {
console.warn("Could not extract json schema definitions from your schema", schema)
throw new Error("Could not extract json schema definitions from your schema")
}
const definition = {
name: safeName,
description,
...definitions[safeName]
}
if (mode === MODE.FUNCTIONS) {
return OAIBuildFunctionParams<P>(definition, params) as ModeParamsReturnType<P, M>
}
if (mode === MODE.TOOLS) {
return OAIBuildToolFunctionParams<P>(definition, params) as ModeParamsReturnType<P, M>
}
if (mode === MODE.JSON) {
return OAIBuildJsonModeParams<P>(definition, params) as ModeParamsReturnType<P, M>
}
if (mode === MODE.JSON_SCHEMA) {
return OAIBuildJsonSchemaParams<P>(definition, params) as ModeParamsReturnType<P, M>
}
if (mode === MODE.MD_JSON) {
return OAIBuildMessageBasedParams<P>(definition, params) as ModeParamsReturnType<P, M>
}
if (mode === MODE.THINKING_MD_JSON) {
return OAIBuildThinkingMessageBasedParams<P>(definition, params) as ModeParamsReturnType<P, M>
}
return OAIBuildMessageBasedParams<P>(definition, params) as ModeParamsReturnType<P, M>
}