ai icon indicating copy to clipboard operation
ai copied to clipboard

useChat to support streamText with structured output

Open mrasoahaingo opened this issue 1 year ago • 10 comments

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

mrasoahaingo avatar Jan 05 '25 00:01 mrasoahaingo

Would useObject work w/ your use case?

lgrammel avatar Jan 05 '25 10:01 lgrammel

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

mrasoahaingo avatar Jan 05 '25 14:01 mrasoahaingo

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

mrasoahaingo avatar Jan 09 '25 15:01 mrasoahaingo

Actually my workaround completely break the tool calls and other type of message

mrasoahaingo avatar Jan 09 '25 15:01 mrasoahaingo

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 avatar Jan 09 '25 23:01 mrasoahaingo

@mrasoahaingo do you have full sample code for the API route and your frontend implementation of parsePartialJson? I can't figure em out.

benjaminalgreen avatar Jan 13 '25 18:01 benjaminalgreen

@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)

mrasoahaingo avatar Jan 15 '25 07:01 mrasoahaingo

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

BrandiATMuhkuh avatar Mar 18 '25 06:03 BrandiATMuhkuh

use assistant has been removed in ai sdk 5. you can use useChat with different backends now, including openai assistants.

lgrammel avatar Jun 26 '25 08:06 lgrammel

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 useChat handling for structured output from streamText, rather than receiving incomplete stringified JSON in message.content.
  • The reporter proposes changing useChat so text chunks append while object chunks replace the current object or populate message data.
  • Although parsePartialJson provides a client-side workaround, it does not add native structured-object semantics to useChat; a later comment separately suggests documenting that workaround.

lgrammel avatar Jul 22 '26 16:07 lgrammel