useChat to support streamText with structured output
Feature Description
Thanks to the recent version of AI SDK we can now set the experimental_output to streamText function.
According to the docs we can then get the streamed object from experimental_partialOutputStream.
If we implement the useChat response we can do something like this:
export async function POST(request: Request) {
const { messages } = await request.json();
return createDataStreamResponse({
status: 200,
statusText: "OK",
headers: {
"Custom-Header": "value",
},
async execute(dataStream) {
const result = streamText({
experimental_output: Output.object({
schema: z.object({
answer: z.string().describe("The answer of the assistant"),
suggestedUserAnswers: z
.array(z.string())
.describe("The suggested user answers"),
}),
}),
model,
system,
messages: convertToCoreMessages(messages),
tools: {
... // Some tools
},
});
result.mergeIntoDataStream(dataStream);
},
onError: (error: unknown) => `Custom error: ${(error as Error).message}`,
});
}
But in the front, you end by displaying stream stringified json which cannot be parsed because the json is incomplete.
So I found a work around where I can stream the answer text and send the suggestedUserAnswers through annotation...
export async function POST(request: Request) {
const { messages } = await request.json();
return createDataStreamResponse({
status: 200,
statusText: "OK",
headers: {
"Custom-Header": "value",
},
async execute(dataStream) {
const result = streamText({
experimental_output: Output.object({
schema: z.object({
answer: z.string().describe("The answer of the assistant"),
suggestedUserAnswers: z
.array(z.string())
.describe("The suggested user answers"),
}),
}),
model,
system,
messages: convertToCoreMessages(messages),
tools: {
... // Some tools
},
});
const { experimental_partialOutputStream: partialOutputStream } = result;
let previousText = '';
let previousSuggestedUserAnswers: string[] = [];
const stream = new ReadableStream({
async start(controller) {
for await (const chunk of partialOutputStream) {
const { answer, suggestedUserAnswers } = chunk;
const textDiff = getTextDiff(answer ?? '', previousText);
controller.enqueue(formatDataStreamPart('text', textDiff));
previousText = answer ?? '';
previousSuggestedUserAnswers = suggestedUserAnswers?.filter((answer): answer is string => answer !== undefined) ?? [];
}
dataStream.writeMessageAnnotation({
suggestedUserAnswers: previousSuggestedUserAnswers,
});
controller.close();
},
});
dataStream.merge(stream);
},
onError: (error: unknown) => `Custom error: ${(error as Error).message}`,
});
}
It works... but it's very hacky...
Use Cases
No response
Additional context
No response
Would useObject work w/ your use case?
Hello, actually useObject doesn't have messages like useChat.
I also tried to set data on message but it's only possible when you use assistant (with part code = 6)
I don't know if it's possible to improve useChat because currently the message content only receive the deltas that's why I had to create a function getTextDiff
Maybe if it can identify if it's a plain text then it should display the append the chunk (like actual useChat), or if it's an object it should replace the object (like useObject). so the message.content can be a text OR an object? or maybe push into message.data like useAssistant
Actually my workaround completely break the tool calls and other type of message
OMG, I just found that chunked json can be safety parse on front side with import { parsePartialJson } from '@ai-sdk/ui-utils';
Now I can remove all the work around on backend side and simply result.mergeIntoDataStream(dataStream); as usual...
Thanks !
@mrasoahaingo do you have full sample code for the API route and your frontend implementation of parsePartialJson? I can't figure em out.
@benjaminalgreen You only have to parse the message.content of the assistant role (not user) on component (client) side like this:
const parseAssistantMessage = (message: Message): { answer: string | null, suggestedUserAnswers: string[] } => {
const parsedMessage = parsePartialJson(message.content);
const { value, state } = parsedMessage as { value: { answer: string, suggestedUserAnswers: string[] } | null, state: string };
if (value && ["repaired-parse", "successful-parse"].includes(state)) {
return value;
}
return { answer: null, suggestedUserAnswers: [] };
};
{messages.map(message => {
if (message.role === "user") {
return (
<div key={message.id}>
{message.content}
</div>
);
}
const { answer } = parseAssistantMessage(message);
return (
<div key={message.id}>
{answer}
</div>
);
})}
repaired-parse is when the partial object is streaming and you have a repaired valid json
successful-parse is when the whole json is valid (and repaired-parse is null)
Thanks @mrasoahaingo for finding/mentioning import { parsePartialJson } from '@ai-sdk/ui-utils'; I've tried other "json-fixers" but they all make my app flicker.
it think it would be super helpful if the vercel team could add the parsePartialJson to the docs: https://sdk.vercel.ai/docs/ai-sdk-core/generating-structured-data#structured-outputs-with-generatetext-and-streamtext
use assistant has been removed in ai sdk 5. you can use useChat with different backends now, including openai assistants.
Identify issue type
Identified as Feature
Confidence: High
Rationale
The primary request is an API and ergonomics enhancement for useChat to support streamed structured objects. It is not presented as a violation of documented existing behavior, so it is a feature rather than a bug.
Evidence
- The issue requests native
useChathandling for structured output fromstreamText, rather than receiving incomplete stringified JSON inmessage.content. - The reporter proposes changing
useChatso text chunks append while object chunks replace the current object or populate message data. - Although
parsePartialJsonprovides a client-side workaround, it does not add native structured-object semantics touseChat; a later comment separately suggests documenting that workaround.