forked from CopilotKit/CopilotKit
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathjson-schema.ts
More file actions
402 lines (369 loc) · 11.2 KB
/
Copy pathjson-schema.ts
File metadata and controls
402 lines (369 loc) · 11.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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
import { z } from "zod";
import { Parameter } from "../types";
export type JSONSchemaString = {
type: "string";
description?: string;
enum?: string[];
};
export type JSONSchemaNumber = {
type: "number";
description?: string;
};
export type JSONSchemaBoolean = {
type: "boolean";
description?: string;
};
export type JSONSchemaObject = {
type: "object";
properties?: Record<string, JSONSchema>;
required?: string[];
description?: string;
};
export type JSONSchemaArray = {
type: "array";
items: JSONSchema;
description?: string;
};
export type JSONSchema =
| JSONSchemaString
| JSONSchemaNumber
| JSONSchemaBoolean
| JSONSchemaObject
| JSONSchemaArray;
export function actionParametersToJsonSchema(
actionParameters: Parameter[],
): JSONSchema {
// Create the parameters object based on the argumentAnnotations
let parameters: { [key: string]: any } = {};
for (let parameter of actionParameters || []) {
parameters[parameter.name] = convertAttribute(parameter);
}
let requiredParameterNames: string[] = [];
for (let arg of actionParameters || []) {
if (arg.required !== false) {
requiredParameterNames.push(arg.name);
}
}
// Create the ChatCompletionFunctions object
return {
type: "object",
properties: parameters,
required: requiredParameterNames,
};
}
// Convert JSONSchema to Parameter[]
export function jsonSchemaToActionParameters(
jsonSchema: JSONSchema,
): Parameter[] {
if (jsonSchema.type !== "object" || !jsonSchema.properties) {
return [];
}
const parameters: Parameter[] = [];
const requiredFields = jsonSchema.required || [];
for (const [name, schema] of Object.entries(jsonSchema.properties)) {
const parameter = convertJsonSchemaToParameter(
name,
schema,
requiredFields.includes(name),
);
parameters.push(parameter);
}
return parameters;
}
// Convert JSONSchema property to Parameter
function convertJsonSchemaToParameter(
name: string,
schema: JSONSchema,
isRequired: boolean,
): Parameter {
const baseParameter: Parameter = {
name,
description: schema.description,
};
if (!isRequired) {
baseParameter.required = false;
}
// Handle null-union types like ["string", "null"] by picking the non-null type
if (Array.isArray(schema.type)) {
const types = schema.type as string[];
const hasNull = types.includes("null");
const nonNullTypes = types.filter((t: string) => t !== "null");
const resolvedType = nonNullTypes.length > 0 ? nonNullTypes[0] : "string";
return convertJsonSchemaToParameter(
name,
{ ...schema, type: resolvedType } as JSONSchema,
hasNull ? false : isRequired,
);
}
switch (schema.type) {
case "string":
return {
...baseParameter,
type: "string",
...(schema.enum && { enum: schema.enum }),
};
case "number":
case "boolean":
return {
...baseParameter,
type: schema.type,
};
case "object":
if (schema.properties) {
const attributes: Parameter[] = [];
const requiredFields = schema.required || [];
for (const [propName, propSchema] of Object.entries(
schema.properties,
)) {
attributes.push(
convertJsonSchemaToParameter(
propName,
propSchema,
requiredFields.includes(propName),
),
);
}
return {
...baseParameter,
type: "object",
attributes,
};
}
return {
...baseParameter,
type: "object",
};
case "array":
if (schema.items.type === "object" && "properties" in schema.items) {
const attributes: Parameter[] = [];
const requiredFields = schema.items.required || [];
for (const [propName, propSchema] of Object.entries(
schema.items.properties || {},
)) {
attributes.push(
convertJsonSchemaToParameter(
propName,
propSchema,
requiredFields.includes(propName),
),
);
}
return {
...baseParameter,
type: "object[]",
attributes,
};
} else if (schema.items.type === "array") {
throw new Error("Nested arrays are not supported");
} else {
return {
...baseParameter,
type: `${schema.items.type}[]`,
};
}
default:
return {
...baseParameter,
type: "string",
};
}
}
function convertAttribute(attribute: Parameter): JSONSchema {
switch (attribute.type) {
case "string":
return {
type: "string",
description: attribute.description,
...(attribute.enum && { enum: attribute.enum }),
};
case "number":
case "boolean":
return {
type: attribute.type,
description: attribute.description,
};
case "object":
case "object[]":
const properties = attribute.attributes?.reduce(
(acc, attr) => {
acc[attr.name] = convertAttribute(attr);
return acc;
},
{} as Record<string, any>,
);
const required = attribute.attributes
?.filter((attr) => attr.required !== false)
.map((attr) => attr.name);
if (attribute.type === "object[]") {
return {
type: "array",
items: {
type: "object",
...(properties && { properties }),
...(required && required.length > 0 && { required }),
},
description: attribute.description,
};
}
return {
type: "object",
description: attribute.description,
...(properties && { properties }),
...(required && required.length > 0 && { required }),
};
default:
// Handle arrays of primitive types and undefined attribute.type
if (attribute.type?.endsWith("[]")) {
const itemType = attribute.type.slice(0, -2);
return {
type: "array",
items: { type: itemType as any },
description: attribute.description,
};
}
// Fallback for undefined type or any other unexpected type
return {
type: "string",
description: attribute.description,
};
}
}
export function convertJsonSchemaToZodSchema(
jsonSchema: any,
required: boolean,
definitions?: Record<string, any>,
visitedRefs?: Set<string>,
): z.ZodSchema {
// Resolve $ref references
if (jsonSchema.$ref && definitions) {
const refPath = jsonSchema.$ref.replace(
/^#\/\$defs\/|^#\/definitions\//,
"",
);
// Detect circular $ref cycles
const refs = visitedRefs ?? new Set<string>();
if (refs.has(refPath)) {
console.warn(
`[CopilotKit] Circular $ref detected for "${refPath}" — falling back to z.any()`,
);
let schema = z.any();
if (jsonSchema.description) {
schema = schema.describe(jsonSchema.description);
}
return required ? schema : schema.optional();
}
const resolved = definitions[refPath];
if (resolved) {
// Clone the set so sibling branches don't see each other's visited refs
const nextRefs = new Set(refs);
nextRefs.add(refPath);
return convertJsonSchemaToZodSchema(
resolved,
required,
definitions,
nextRefs,
);
}
}
// Collect top-level definitions for $ref resolution
const defs = definitions ?? jsonSchema.$defs ?? jsonSchema.definitions;
// Handle null-union types like ["string", "null"]
if (Array.isArray(jsonSchema.type)) {
const types = jsonSchema.type as string[];
const hasNull = types.includes("null");
const nonNullTypes = types.filter((t: string) => t !== "null");
const resolvedType = nonNullTypes.length > 0 ? nonNullTypes[0] : "string";
const innerSchema = convertJsonSchemaToZodSchema(
{ ...jsonSchema, type: resolvedType },
true,
defs,
visitedRefs,
);
let schema = hasNull ? z.union([innerSchema, z.null()]) : innerSchema;
if (jsonSchema.description) {
schema = schema.describe(jsonSchema.description);
}
return required ? schema : schema.optional();
}
// Handle anyOf / oneOf as z.union
const unionVariants = jsonSchema.anyOf ?? jsonSchema.oneOf;
if (Array.isArray(unionVariants) && unionVariants.length > 0) {
if (unionVariants.length === 1) {
return convertJsonSchemaToZodSchema(
unionVariants[0],
required,
defs,
visitedRefs,
);
}
const schemas = unionVariants.map((v: any) =>
convertJsonSchemaToZodSchema(v, true, defs, visitedRefs),
);
let schema = z.union(
schemas as [z.ZodSchema, z.ZodSchema, ...z.ZodSchema[]],
);
if (jsonSchema.description) {
schema = schema.describe(jsonSchema.description);
}
return required ? schema : schema.optional();
}
if (jsonSchema.type === "object") {
const spec: { [key: string]: z.ZodSchema } = {};
if (!jsonSchema.properties || !Object.keys(jsonSchema.properties).length) {
return !required ? z.object(spec).optional() : z.object(spec);
}
for (const [key, value] of Object.entries(jsonSchema.properties)) {
spec[key] = convertJsonSchemaToZodSchema(
value,
jsonSchema.required ? jsonSchema.required.includes(key) : false,
defs,
visitedRefs,
);
}
let schema = z.object(spec).describe(jsonSchema.description);
return required ? schema : schema.optional();
} else if (jsonSchema.type === "string") {
if (jsonSchema.enum && jsonSchema.enum.length > 0) {
let schema = z
.enum(jsonSchema.enum as [string, ...string[]])
.describe(jsonSchema.description);
return required ? schema : schema.optional();
}
let schema = z.string().describe(jsonSchema.description);
return required ? schema : schema.optional();
} else if (jsonSchema.type === "number" || jsonSchema.type === "integer") {
let schema = z.number().describe(jsonSchema.description);
return required ? schema : schema.optional();
} else if (jsonSchema.type === "boolean") {
let schema = z.boolean().describe(jsonSchema.description);
return required ? schema : schema.optional();
} else if (jsonSchema.type === "array") {
let itemSchema = convertJsonSchemaToZodSchema(
jsonSchema.items,
true,
defs,
visitedRefs,
);
let schema = z.array(itemSchema).describe(jsonSchema.description);
return required ? schema : schema.optional();
} else if (jsonSchema.type === "null") {
let schema = z.null().describe(jsonSchema.description);
return required ? schema : schema.optional();
}
// Fallback: accept any value rather than throwing
console.warn(
`[CopilotKit] Unsupported JSON schema type "${jsonSchema.type ?? "unknown"}" — falling back to z.any()`,
);
let schema = z.any();
if (jsonSchema.description) {
schema = schema.describe(jsonSchema.description);
}
return required ? schema : schema.optional();
}
export function getZodParameters<T extends [] | Parameter[] | undefined>(
parameters: T,
): any {
if (!parameters) return z.object({});
const jsonParams = actionParametersToJsonSchema(parameters);
return convertJsonSchemaToZodSchema(jsonParams, true);
}