Error AI_TypeValidationError while using gemini-2.0-flash-lite-preview-02-05
Description
After 7 or 8 interactions in the same session in a chat with the Gemini 2.0 Flash Lite model, I get this error. I have tried using fallbacks to switch models, added security filters to the Gemini models, and also used TypeValidationError to catch this type of error, but it still appears both in the console and on the frontend. However, I can continue interacting with the model in the chat. As seen at the end of the log, the model displays the result correctly, but I keep getting an AI_TypeValidationError in the console and frontend, which I can't get rid of.
Stream error occurred: {
error: [Error [AI_TypeValidationError]: Type validation failed: Value: {"candidates":[{"content":{"role":"model"},"finishReason":"STOP","index":0}],"usageMetadata":{"promptTokenCount":7208,"candidatesTokenCount":30,"totalTokenCount":7238},"modelVersion":"gemini-2.0-flash-lite-preview-02-05"}.
Error message: [
{
"code": "invalid_type",
"expected": "array",
"received": "undefined",
"path": [
"candidates",
0,
"content",
"parts"
],
"message": "Required"
}
]] {
value: {
candidates: [Array],
usageMetadata: [Object],
modelVersion: 'gemini-2.0-flash-lite-preview-02-05'
},
[cause]: [Error [ZodError]: [
{
"code": "invalid_type",
"expected": "array",
"received": "undefined",
"path": [
"candidates",
0,
"content",
"parts"
],
"message": "Required"
}
]] {
issues: [ [Object] ],
addIssue: [Function (anonymous)],
addIssues: [Function (anonymous)]
}
}
}
Stream finished {
id: 'aitxt-A4CF2atIQPaD4Xe39hdvLrBE',
timestamp: 2025-02-18T16:40:32.058Z,
modelId: 'gemini-2.0-flash-lite-preview-02-05',
headers: {
'alt-svc': 'h3=":443"; ma=2592000,h3-29=":443"; ma=2592000',
'content-disposition': 'attachment',
'content-type': 'text/event-stream',
date: 'Tue, 18 Feb 2025 16:40:31 GMT',
server: 'scaffolding on HTTPServer2',
'server-timing': 'gfet4t7; dur=278',
'transfer-encoding': 'chunked',
vary: 'Origin, X-Origin, Referer',
'x-content-type-options': 'nosniff',
'x-frame-options': 'SAMEORIGIN',
'x-xss-protection': '0'
},
messages: [
{
role: 'assistant',
content: [Array],
id: 'msg-JLHrX8vXcIM2wXtetezBVL4K'
},
{
role: 'tool',
id: 'msg-gnszRCPWM0DIGIUj2LnJUAlY',
content: [Array]
},
{
role: 'assistant',
content: [Array],
id: 'msg-gp0xXx1WNcepO1G6UBnxKl1m'
}
]
}
Code example
return streamText({
model: createFallback({
models: [
provider.languageModel("gemini-2-flash-lite"),
provider.languageModel("gemini-2-flash"),
provider.languageModel("gpt-4o-mini"),
],
shouldRetryThisError: (error: Error) => {
if (TypeValidationError.isInstance(error)) {
return true;
}
const defaultHandler = error.message.toLowerCase();
if (defaultHandler.includes('api key') ||
defaultHandler.includes('no such') ||
error.name === 'AI_APICallError' ||
error.name === 'AI_NoSuchModelError') {
console.log('Retrying due to API or model error');
return true;
}
return false;
},
onError: (error, modelId) => {
if (!(error.name === 'AI_TypeValidationError' &&
error.message.includes('candidates') &&
error.message.includes('content.parts'))) {
console.error(`\nError with model ${modelId}:`, error, "\n");
}
},
retryAfterOutput: false,
modelResetInterval: 120000,
}),
system: agent(),
messages: convertToCoreMessages(messages),
maxSteps: 5,
temperature: 0,
experimental_telemetry: { isEnabled: true },
experimental_transform: smoothStream({ chunking: "word" }),
experimental_activeTools: ALL_TOOLS,
tools: {
behavior,
event,
form,
media,
report,
navigation,
},
experimental_repairToolCall: async ({
toolCall,
tools,
parameterSchema,
error,
}) => {
if (NoSuchToolError.isInstance(error)) {
return null;
}
const tool = tools[toolCall.toolName as keyof typeof tools];
const { object: repairedArgs } = await generateObject({
model: openai('gpt-4o-mini', { structuredOutputs: true }),
schema: tool.parameters,
prompt: [
`The model tried to call the tool "${toolCall.toolName}"` +
` with the following arguments:`,
JSON.stringify(toolCall.args),
`The tool accepts the following schema:`,
JSON.stringify(parameterSchema(toolCall)),
'Please fix the arguments.',
].join('\n'),
});
return { ...toolCall, args: JSON.stringify(repairedArgs) };
},
}).toDataStreamResponse();
AI provider
No response
Additional context
No response
Identify issue type
Identified as Bug
Confidence: High
Rationale
The issue reports a concrete runtime validation failure during existing streaming behavior, where an otherwise completed Gemini response unexpectedly produces a user-visible SDK error.
Evidence
- After several chat turns, streaming with Gemini 2.0 Flash Lite emits an
AI_TypeValidationErrorbecausecandidates[0].content.partsis absent. - The stream still finishes with a valid-looking result, but the validation error is surfaced in both the console and frontend.
- The reporter provides the response payload, validation path, and a reproducible
streamTextconfiguration.