Skip to content
Source
Sign inSign up
TanStack/ai
Open History to see the last commit

toGroqCompatibleSchema.ts

46 lines1.3 KB

1// Groq structured output requires additionalProperties:false on every object, including
2// those nested inside anyOf. The @tanstack/ai-groq adapter only recurses into direct
3// object properties, not anyOf/oneOf/allOf, so we pre-process the JSON Schema here.
4function toGroqCompatibleSchema(
5 schema: Record<string, any>,
6): Record<string, any> {
7 if (typeof schema !== 'object' || Array.isArray(schema)) return schema
8 const result = { ...schema }
9​
10 for (const combiner of ['anyOf', 'oneOf', 'allOf']) {
11 if (Array.isArray(result[combiner])) {
12 result[combiner] = result[combiner].map((s: any) =>
13 toGroqCompatibleSchema(s),
14 )
15 }
16 }
17​
18 if (result.$defs) {
19 result.$defs = Object.fromEntries(
20 Object.entries(result.$defs).map(([k, v]) => [
21 k,
22 toGroqCompatibleSchema(v as any),
23 ]),
24 )
25 }
26​
27 if (result.type === 'object') {
28 const properties = Object.fromEntries(
29 Object.entries(result.properties ?? {}).map(([k, v]) => [
30 k,
31 toGroqCompatibleSchema(v as any),
32 ]),
33 )
34 result.properties = properties
35 result.required = Object.keys(properties)
36 result.additionalProperties = false
37 }
38​
39 if (result.type === 'array' && result.items) {
40 result.items = toGroqCompatibleSchema(result.items)
41 }
42​
43 return result
45​
46export default toGroqCompatibleSchema