Gemini「too many states for serving」錯誤的觸發原因與兩種修復方法
Gemini's "too many states for serving" error: what triggered it for us, and two fixes
作者發現,Gemini 的 responseSchema 在 fields 陣列設定 maxItems: 300、minItems: 1 時會觸發 400 INVALID_ARGUMENT;移除兩項界限後,Gemini 約兩秒內生成有效的六欄表單。
If you landed here from a search, this is probably the error you're looking at:
The specified schema produces a constraint that has too many states for serving.
It comes back as a 400 INVALID_ARGUMENT when you pass a responseSchema to Gemini. We hit it with the schema we use to generate forms, and the uncomfortable part is how long it went unnoticed.
How it hid
Gemini wasn't our primary model. It sat second in a fallback chain, behind a faster provider. So the error only mattered on the rare call where the primary timed out, and then the whole chain failed and a user saw "something went wrong". In 120 days of logs, Gemini never once served a form. Nobody noticed, because the primary usually worked.
It also passes every check you'd write without calling the live API. Gemini accepts the schema when it parses the request. The refusal comes later, when it tries to compile the schema into the constraint it decodes with. A unit test that only builds the request will stay green.
Finding the cause
The schema is not huge: a fields array of objects with 14 properties each, a 20-value enum for the field type, and a nested logic array. Google's error message lists the usual suspects: long property or enum names, long array length limits (especially nested ones), and numeric bounds or complex string formats.
Rather than guess, we sent variants of the same schema to gemini-2.5-flash, one feature removed at a time:
| Variant | Result |
|---|---|
| Original | Rejected |
Without description strings |
Rejected |
Without the nested logic array |
Rejected |
Without minItems / maxItems |
Accepted |
| Without bounds and descriptions | Accepted |
The culprit was one line: maxItems: 300 (with minItems: 1) on the fields array. A length bound on an array of rich objects was enough on its own. Long descriptions and nesting weren't the problem.
Fix 1: send the bounds to your validator, not to Gemini
The bounds still matter. A form with zero fields is useless. But they don't have to be enforced during decoding. We validate every model response with Zod anyway, so the limit lives there:
// Sent to Gemini: no array bounds.
export const FormGeminiResponseSchema = {
type: "object",
properties: {
fields: {
type: "array",
items: { /* ...field object... */ },
},
},
required: ["fields"],
} as const;
// Checked after generation: the bounds live here.
export const FormSchema = z.object({
fields: z.array(FormField).min(1).max(300),
});
With that change Gemini accepted the schema and returned a valid six-field form in about two seconds. We pinned it with a test that walks the schema and fails if minItems or maxItems ever comes back.
Fix 2: when it happens anyway, retry without the constraint
Schemas grow, and the next one to trip the limit might not be an array bound. So we also catch this specific error and retry once in plain JSON mode, with the schema in the prompt instead of in the decoder:
let response;
try {
response = await client.models.generateContent({
model,
contents,
config: { ...baseConfig, responseSchema },
});
} catch (err) {
if (!isSchemaTooComplexError(err)) throw err;
response = await client.models.generateContent({
model,
contents,
config: {
...baseConfig, // still responseMimeType: "application/json"
systemInstruction:
`${system}\n\nReturn ONLY valid JSON matching this schema.\n` +
JSON.stringify(responseSchema, null, 2),
},
});
}
function isSchemaTooComplexError(err: unknown): boolean {
const msg = err instanceof Error ? err.message : String(err);
return /too many states/i.test(msg);
}
Two details matter:
-
Match on the message, not the status.
INVALID_ARGUMENTalso covers a bad API key or a malformed request, which must not be retried. - Validate the retry like any other response. Without the constraint, the model can drift from the schema. A Zod parse plus one repair pass catches that.
Takeaways
- Strip
minItems/maxItems(and numeric bounds and string formats, if you can) from schemas you send to Gemini, and enforce them in your own validation. - Call the live API with your real schemas at least once in CI or in a smoke script. Request-building tests can't see this failure.
- If a provider is a fallback, test it as if it were the primary. Fallbacks fail exactly when you need them, and nobody watches them the rest of the time.
We found this in DodoForm, an AI form builder that turns a one-sentence description into a form. You can try its extractor without an account on the homepage.
來源:DEV Community · dev.to