vercel / ai

Build AI-powered applications with React, Svelte, Vue, and Solid
https://sdk.vercel.ai/docs
Other
9.8k stars 1.45k forks source link

Disable schema references $refs for Google AI API #3325

Open BrianHung opened 2 hours ago

BrianHung commented 2 hours ago

Description

I have a schema where I'm re-using zod objects. By default, the ref strategy used by zod to json schema is to re-use schemas that have been seen before.

https://github.com/StefanTerdell/zod-to-json-schema https://json-schema.org/understanding-json-schema/structuring#dollarref

const CellRange = z.object({
  sheetId: SheetId,
  start: A1Notation,
  end: A1Notation,
});

const getFillRangeContents = z
  .function()
  .args(
    z.object({
      source: CellRange,
      target: CellRange,
    })
  )
"start": {
  "type": "object",
  "properties": {
    "col": {
      "type": "string",
      "description": "Column of the cell, indexed from A-Z."
    },
    "row": {
      "type": "integer",
      "description": "Row of the cell, indexed from 1."
    }
  },
  "required": [
    "col",
    "row"
  ],
  "additionalProperties": false
},
"end": {
  "$ref": "#/items/0/properties/source/properties/start"
}
},

OpenAI is able to accept this json schema, but Google AI is not and errors with

.properties[end].type: must be specified

One possible fix is to set $refsStrategy: 'none' to disable json schema re-use (re-using zod objects works but duplicated in json schema).

Code example

No response

Additional context

No response

BrianHung commented 2 hours ago

Workaround would be to manually do it

import { zodToJsonSchema } from 'zod-to-json-schema';
import { jsonSchema, tool } from 'ai';
import { JSONSchema7 } from 'json-schema';

tool({
  description: value.description,
  parameters: jsonSchema(
    zodToJsonSchema(
      value.parameters().items[0],
      { $refStrategy: 'none' }
    ) as JSONSchema7
  ), 
})