-
Couldn't load subscription status.
- Fork 3.2k
Description
Description
Issue
I encountered this issue when implementing the agent loop following https://ai-sdk.dev/cookbook/node/manual-agent-loop#message-management.
Uncaught AI_InvalidPromptError: Invalid prompt: The messages must be a ModelMessage[]. If you have passed a UIMessage[], you can use convertToModelMessages to convert them.
I noticed that when the tool call results contains field set to undefined it causes this error
This is a simplified code path:
// previous step messages
const messages: ModelMessage[] = [
{
role: "system", content: systemPrompt
},
{
role: "user", content: userPrompt
},
{
role: "assistant",
content: [
{
type: "reasoning",
text: "",
providerOptions: {
openai: {
itemId: "rs_025dc37d353024330068dfe8bf3d9081939cf194d9b4f8c260",
reasoningEncryptedContent: null
}
}
},
{
type: "tool-call",
toolCallId: "call_fVPGEmWa2xTGtMTJ3kVYOFYY",
toolName: "doSomething",
input: {
someParam: "some params"
},
providerOptions: {
openai: {
itemId: "fc_025dc37d353024330068dfe8c3edf481938456f8be119a4b1b"
}
}
}
]
}
];
// after executing the tool call
messages.push({
role: 'tool',
content: [
{
type: 'tool-result',
toolCallId: 'call_fVPGEmWa2xTGtMTJ3kVYOFYY',
toolName: 'doSomething',
output: {
type: 'json',
value: {
a: "xxx",
b: undefined // this causes validation error in the next step
}
},
}
],
});
// execute next step
const result = streamText({
model: openai('gpt-5'),
messages,
tools: toolSet,
})Root Cause
The output schema (code ref) uses jsonValueSchema definition doesn't allow undefined field (code ref), causing message validation to fail when preparing the prompt for the next step
export const jsonValueSchema: z.ZodType<JSONValue> = z.lazy(() =>
z.union([
z.null(),
z.string(),
z.number(),
z.boolean(),
z.record(z.string(), jsonValueSchema),
z.array(jsonValueSchema),
]),
);Suggestion
This is fine as undefined is not part of JSON standard, but then I referred to issue #7610 and the corresponding fix in #7650. This fix supported undefined value as output value by converting undefined to null, so I wonder is it possible to extend this support to field level.
Happy to raise a PR to fix it if this is ok, as I suspect this can be a quite common issue
AI SDK Version
ai: 5.0.56
@ai-sdk/openai: 2.0.27,
Code of Conduct
- I agree to follow this project's Code of Conduct