ai icon indicating copy to clipboard operation
ai copied to clipboard

google: schemas with several array .max() bounds fail with a bare 400 since responseJsonSchema switch

Open silverstein opened this issue 2 months ago • 6 comments

Summary

Since @ai-sdk/google began sending the schema as responseJsonSchema (#20757, merged 2026-09-14), structured-output calls whose Zod schema contains several z.array(...).max(n) fail against Gemini with

AI_APICallError: Request contains an invalid argument.

HTTP 400, status: INVALID_ARGUMENT, no field named. The same schemas worked on the previous provider version, which converted to the OpenAPI dialect and dropped keywords Gemini does not take.

I am not arguing #20757 was wrong — it fixed a real silent-widening bug (#19662). But it exposes a Gemini limit that the provider does not account for, and the resulting error is impossible to attribute from the client side.

Why it is hard to diagnose

Gemini returns that identical bare message for a document it cannot parse (a corrupt or password-protected PDF). A schema-level request defect and a bad input are indistinguishable, so the failure reads as a data problem. In our case it cost two rounds of fixes aimed at the wrong layer before we suspected the schema.

What it actually is: a budget, not an unsupported keyword

Measured against gemini-3.8-flash via the REST API directly, five identical calls per case, verdicts fully deterministic:

case result
each JSON Schema keyword alone, maxItems included accepted
a real 15-property schema, 118 constraint keywords, 15 maxItems rejected 5/5
the same schema minus maxItems accepted 5/5
the same schema keeping any 3 of the 15 maxItems rejected
flat schema, 20 arrays each with maxItems accepted
flat schema, 40 arrays each with maxItems rejected
the same 40 arrays with no maxItems accepted

So maxItems is accepted in isolation and refused in aggregate: Gemini enforces a complexity budget on responseJsonSchema, and maxItems on an array of objects consumes far more of it than on an array of strings. A keyword allowlist would not describe this.

parametersJsonSchema (tool schemas) does not show the same limit: 30 capped object arrays are accepted there.

Reproduction

import { createGoogleGenerativeAI } from '@ai-sdk/google';
import { Output, generateText } from 'ai';
import { z } from 'zod';

const google = createGoogleGenerativeAI({ apiKey: process.env.GOOGLE_GENERATIVE_AI_API_KEY! });

// 40 capped arrays of objects: over budget.
const shape: Record<string, z.ZodTypeAny> = {};
for (let i = 0; i < 40; i++) {
  shape[`list${i}`] = z.array(z.object({ name: z.string() })).max(12);
}

await generateText({
  model: google('gemini-3.8-flash'),
  prompt: 'Return an example object.',
  output: Output.object({ schema: z.object(shape) }),
});
// AI_APICallError: Request contains an invalid argument.
// Remove the .max(12) calls and the identical request succeeds.

Versions

[email protected], @ai-sdk/[email protected]. Re-checked against 4.0.76: sanitizeResponseJsonSchema still only rewrites const, so the behavior is unchanged on the latest release.

Possible directions

  1. Attach the schema to the error, or note the responseJsonSchema change in the message, so a 400 is attributable. This alone would have saved us the whole investigation.
  2. Document the budget, ideally with the metric, so callers can design schemas against it.
  3. Consider dropping the highest-cost keywords when a schema is over budget, the way the Bedrock provider does for keywords that provider rejects (#17558), given they are advisory to the model and the SDK validates the output locally anyway.

We work around it today by stripping maxItems from the JSON Schema sent to Gemini only, keeping validation against the original Zod schema so the bound is still enforced locally.

silverstein avatar Sep 20 '26 05:09 silverstein

Identify issue type

Identified as Bug
Confidence: High

Rationale

This is a concrete regression in existing Google provider behavior: generated response schemas can exceed Gemini's schema complexity budget and fail with an uninformative API error.

Evidence

  • Structured-output requests with multiple Zod array .max() constraints now fail with Gemini HTTP 400 INVALID_ARGUMENT.
  • The same schemas worked before the provider switched to responseJsonSchema, and removing maxItems makes the requests succeed.
  • The report includes a reproducible example and confirms the behavior on current versions @ai-sdk/[email protected] and [email protected].

ai-sdk-factory[bot] avatar Sep 20 '26 05:09 ai-sdk-factory[bot]

Bug Reproduction - AI SDK 7

Bug is outside the AI SDK codebase scope.

Target branch: main

  • examples/ai-functions/src/reproduction/google-response-json-schema-max-items-budget.ts reproduced the reported outcome: generateText received HTTP 400 INVALID_ARGUMENT for 40 object arrays with maxItems, while one capped array and the same 40 arrays without bounds succeeded.
  • The artifact confirmed @ai-sdk/google sent responseJsonSchema containing all 40 maxItems: 12 constraints; packages/google/src/google-language-model.ts and packages/google/src/sanitize-response-json-schema.ts preserve this documented keyword.
  • Replaying the captured request body directly against the Gemini REST endpoint produced the identical bare HTTP 400, establishing the failure at the Google Gemini API boundary rather than in AI SDK response handling.
  • Google documents maxItems as supported but warns that complex schemas can be rejected and recommends reducing constraints; silently removing the bounds in AI SDK would widen the requested schema.
  • The meaningful fix for accepting this exact schema belongs to the Google Gemini API; callers can currently simplify the provider-facing schema while retaining local validation.
  • The report's unspecified 15-property production schema and its separate flat-array and tool-schema matrices could not be independently evaluated without their exact payloads; this does not affect the exact published reproduction or ownership boundary.

Relevant Documentation

  • https://ai.google.dev/api/generate-content
  • https://ai.google.dev/gemini-api/docs/structured-output
  • https://ai.google.dev/gemini-api/docs/generate-content/structured-output
  • https://ai.google.dev/gemini-api/docs/models/gemini-3.8-flash

ai-sdk-factory[bot] avatar Sep 20 '26 05:09 ai-sdk-factory[bot]

One correction to my own framing, since I have measured it since filing: in our codebase only a single schema was actually over the budget (15 maxItems, 8.3 KB). Three other schemas that also cap arrays, at 2-3 maxItems and roughly a quarter the size, were accepted unchanged both before and after. So the practical impact is narrower than "any schema with array bounds" and depends on total schema complexity, which is the part I think is worth documenting upstream.

silverstein avatar Sep 20 '26 19:09 silverstein

Google documents that "very large or deeply nested schemas may be rejected." I'm checking with the Gemini team to see what that exactly means. Ideally, if a schema is too complex, AI SDK would strip it or simplify it before sending the request.

n1ckoates avatar Sep 21 '26 17:09 n1ckoates

Thank you!

silverstein avatar Sep 21 '26 21:09 silverstein

I checked with the Gemini team and unfortunately, there isn’t a reliable way for AI SDK to detect this ahead of time, nor reliably simplify the schema automatically.

I’ve added this error to the Google provider troubleshooting documentation with a link Google’s documentation on schema complexity.

The recommended workaround is to simplify the schema sent to Gemini. For example by removing maxItems or other unnecessary constraints, and optionally keeping stricter client-side validation. You can provide a simplified JSON Schema to the model and a separate validation function:

import { google } from '@ai-sdk/google';
import {
  generateText,
  jsonSchema,
  Output,
  zodSchema,
} from 'ai';
import { z } from 'zod';

const userSchema = z.object({
  name: z.string(),
});

// Simplified schema sent to Gemini:
const baseSchema = z.object({
  users: z.array(userSchema),
});

// Stricter schema used for client-side validation:
const strictSchema = baseSchema.extend({
  users: baseSchema.shape.users.max(12),
});

const modelSchema = zodSchema(baseSchema);
const validationSchema = zodSchema(strictSchema);

const schema = jsonSchema<z.infer<typeof strictSchema>>(
  modelSchema.jsonSchema,
  {
    validate: validationSchema.validate,
  },
);

const { output } = await generateText({
  model: google('gemini-3.8-flash'),
  output: Output.object({ schema }),
  prompt: 'Generate some users.',
});

This allows Gemini to use the simpler schema during generation while AI SDK still enforces the original constraint locally.

Since this is an upstream Gemini complexity limit and AI SDK can't workaround it, I’m closing this issue.

Feel free to open a new issue if you have a solution to workaround this problem better!

n1ckoates avatar Sep 28 '26 19:09 n1ckoates