ai icon indicating copy to clipboard operation
ai copied to clipboard

convert model messages to ui messages

Open isaacwasserman opened this issue 1 year ago • 40 comments

Description

According to the docs, there should be a utility function appendResponseMessages (see here), but it doesn't exist in the code. If this has recently been removed from the beta, what will replace it? Currently there is no recommended way to convert ModelMessage to UIMessage.

I'm following the advice of the docs to persist my messages in the DB as UIMessage, but the onStepFinish and onFinish callbacks of streamText only provide messages as ModelMessage. As far as I can tell, the only way to get the output as a UIMessage is to stream it to the client and have the client call a "save message" API route, but that's impractical because of potential interruptions in the stream.

What do the maintainers recommend? I could try to convert the messages on my own, but there's no way of validating the method.

AI SDK Version

  • ai: 5.0.0-beta.12
  • ai-sdk/react: 2.0.0-beta.12

isaacwasserman avatar Jul 09 '25 21:07 isaacwasserman

+1 we're currently persisting the responseMessage in the onFinish callback of createUIMessageStream (which is a UIMessage) but it would be helpful to have a utility function to ensure we're appending them correctly

nikitatome avatar Jul 09 '25 22:07 nikitatome

Yes it has been removed. Recommendation is to store ui messages. docs will be updated accordingly. see an example here for now: https://github.com/vercel/ai/blob/main/examples/next/app/api/chat/route.ts#L71

lgrammel avatar Jul 10 '25 05:07 lgrammel

Is there any example available for a more realistic message persistence scenario? It seems like the SDK assumes that apps are going to save entire chats as monolithic database entries (or in the case of the above example, a file), but this isn't very efficient for large conversations. For example, useChat sends the entire conversation history with every request when it could be ascertained much faster from the server side (where the data is actually stored). Then, the onFinish callback on the server side takes the full conversation history as an argument, so we're forced to de-dupe messages on our own when storing them. Are there plans to introduce utilities/customizations that reliably produce the delta (i.e. the data that has yet to be persisted)?

isaacwasserman avatar Jul 10 '25 19:07 isaacwasserman

@isaacwasserman here is how I deal with it. Hope this helps

Frontend

  const {
    messages: currentSessionMessages,
    status,
    sendMessage,
  } = useChat<UIMessage<ChatMessageMetadata>>({
    transport: new DefaultChatTransport({
      headers: { Authorization: authorizationHeader },
      api: getFullUrl("/chats/message"),
      prepareSendMessagesRequest: (data) => {
        const lastMessage = data.messages[data.messages.length - 1];
        const result = {
          ...data,
          body: { chatId, message: lastMessage }, // This will only send the last user message.
        };
        return result;
      },
    }),
  });

Backend (Nestjs, but you can adapt to Nextjs or whatever frameworks you are using)

import { Body, Controller, Param, Post, Res } from "@nestjs/common";
import { convertToModelMessages, createUIMessageStream, streamText, pipeUIMessageStreamToResponse, stepCountIs } from "ai";
import { Response } from "express";
.....

export interface ChatMessageModel {
  message: UIMessage<ChatMessageMetadata>;
  chatId: string;
  trigger: string;
}
....

@Post("message")
async chat(@Body() model: ChatMessageModel, @Res() res: Response) {
  const currentUserId = "...";
  const { uiChatMessages, chatSession } = await this.chatsService.storeNewMessageAndReturnChatHistory(currentUserId, model); // Simply store user message (UIMessage) and return the full message history: [...oldMessages, newMessage]
  const uiChatMessagesWithFiles = await this.chatsService.attachFilesAsBase64(currentUserId, uiChatMessages); // We don't store base64 in the database, we only store the file id. This method will read the files from the file system and attach them to the message.

  const convertedMessages = convertToModelMessages(uiChatMessagesWithFiles);
  const result = streamText({
    model: openai("gpt-4o"),
    system: "Your prompt here",
    messages: convertedMessages,
    stopWhen: stepCountIs(5),
  });

  const stream = createUIMessageStream({
    execute({ writer }) {
      writer.merge(
        result.toUIMessageStream({
          sendReasoning: true,
        })
      );
    },
    onFinish: (data) => {
      // onFinish does not accept async functions :( ...
      this.chatsService.saveAssistantMessageInANewTransaction(currentUserId, chatSession, data.responseMessage); // data.responseMessage will be your UIMessage
    },
  });
  pipeUIMessageStreamToResponse({ response: res, stream });
}

pavlo-tkhir avatar Jul 13 '25 16:07 pavlo-tkhir

Yes it has been removed. Recommendation is to store ui messages. docs will be updated accordingly. see an example here for now: main/examples/next/app/api/chat/route.ts#L71

This helped. Thanks!

Not sure if this needs fixing or not, but opened an issue: https://github.com/vercel/ai/issues/7288

elie222 avatar Jul 14 '25 14:07 elie222

Yes it has been removed. Recommendation is to store ui messages. docs will be updated accordingly. see an example here for now: https://github.com/vercel/ai/blob/main/examples/next/app/api/chat/route.ts#L71

Out of curiosity, is there a plan to make this async?

Of better, export a toUIMessage function, so that the persistence of messages can be done directly in the onFinish or onStepFinish hooks of the streamText

Mael-Abgrall avatar Jul 15 '25 11:07 Mael-Abgrall

There are other reasons why to have appendResponseMessages. I used it in streamText.onFinish to prepare messages for another call of streamText. Result was that I was able to stream multiple streamText streams to UI while doing some other business logic that was out of scope of LLM. Imagine these steps:

  1. streamText
  2. onFinish: doSomeLogic while faking streaming of function call to UI (write.write({type: 'tool-input-start', toolName: 'doSomeLogic' ...) so user has seamless experience
  3. start another streamText with input messages + response messages from first streamText + result from doSomeLogic

Can we please get this function back? Or create new one - something like ResponseMessagesToUIMessages?

igo avatar Jul 27 '25 19:07 igo

I agree with the others, I was using appendResponseMessages to convert ResponseMessage to UIMessage (Message) in v4. It feels odd that this helper function was completely removed without any prior deprecation notice. 😅

Maybe it would make sense to introduce a toUIMessage helper instead, which takes ResponseMessages and converts them to UIMessages. 🤔

This would be especially useful when implementing a Manual Agent Loop (https://ai-sdk.dev/cookbook/node/manual-agent-loop). In v4, I had my own agent loop where I used appendResponseMessages to handle the conversion from ResponseMessage to UIMessage.

kriszlazar avatar Aug 03 '25 17:08 kriszlazar

@igo you can access the response messages from stream text via (await result.response).messages (or use a promise resolution for async behavior)

@lazakrisz our recommendation is using ui messages throughout for persistence if you have user facing elements; see https://ai-sdk.dev/docs/ai-sdk-ui/chatbot-message-persistence

lgrammel avatar Aug 04 '25 09:08 lgrammel

(await result.response).messages returns ResponseMessage[]. Is there another way to convert that value to UIMessage?

tylerdurrett avatar Aug 05 '25 16:08 tylerdurrett

I was also using appendResponseMessages to convert from ModelMessage to UIMessage.

I get we can use streamText and then .toUIMessageStreamResponse, but I think it would be helpful to have a utility that did the inverse ofconvertToModelMessages so we can use generateText and save the UIMessages for later consumption rather than dealing with the streamables.

tylercraig9332 avatar Aug 05 '25 19:08 tylercraig9332

I'm using the following hack:

// ...

const result = streamText({
  model: openai("gpt-4.1-nano"),
  messages: convertToModelMessages(existingMessages),
});
/// ...

/// 👇 store result messages in a variable.
let messages: UIMessage[] = [];
let convertedResponseMessage: UIMessage | null = null;

const uiMessageStream = result.toUIMessageStream({
  onFinish: ({ messages, responseMessage, isAborted }) => {
    convertedResponseMessage = responseMessage; // 👈 assign newly generated message here
    messages = messages; // 👈 assign all messages here
  },
});

// 👇 iterate over the stream, need to consume the stream + backpressure.
for await (const chunk of uiMessageStream) {
  /// ...
}

// stream is done, we can now update the message

await saveMessage(convertedResponseMessage); // 👈 save the message to the database, etc...

kriszlazar avatar Aug 05 '25 19:08 kriszlazar

@lazakrisz are you using ui messages for e.g. a chatbot? or could everything you do be implemented with model messages?

lgrammel avatar Aug 06 '25 08:08 lgrammel

Hi @lgrammel,

I'm currently using a fully manual agent loop, roughly following this flow:

  1. The user sends a message over WebSocket.
  2. We ping an API, which schedules a message on the event bus for our agent to process.
  3. The agent starts processing the message.
  4. Once processing is complete, we persist the new message and send it back over WebSocket.

The streams generated inside the for await loop (where we consume the UI stream) are piped through our WebSocket server and displayed to the user in the UI.

Since these messages are always rendered in the UI, we want to persist them in our database using the UIMessage schema instead of the ModelMessage schema, as the latter wouldn’t make sense for UI display purposes.

Initially, I looked into using ModelMessage, as that’s the recommended approach for the manual agent loop in the docs (https://ai-sdk.dev/cookbook/node/manual-agent-loop). However, I have a Next.js app and a Chrome extension that both render these messages, and using UIMessage to display them is much more convenient (even though I’m not using useChat, it gives me a good baseline interface).

Since my use case is quite custom - unlike what others have described in this issue thread, I was just sharing my current hacky solution 😅 for getting UIMessages from the streamText. Previously, I would await the response.message, then use appendResponseMessages to get the persistable UIMessages and save them to the database.

kriszlazar avatar Aug 06 '25 12:08 kriszlazar

What if you aren't using streamText and just generateText? How do you get the UIMessages from generateText? There is the response.messages array but seems like we need a way to convert that to a UIMessage array

nickolsen-mainsail avatar Aug 06 '25 17:08 nickolsen-mainsail

Just chiming in here because it seems similar.

I'm looking to unify UI Message persistence, we run headless agents with generateText, as well as running via useChat with streamText. There seems to be no consistent way to get/convert/store the UI Messages from generateText?

An inverse of convertToModelMessages would seem useful? Or outputting parts/message directly from generateText? Or maybe I'm thinking about it the wrong way?

Thanks for the help! @lgrammel

Vochsel avatar Aug 14 '25 13:08 Vochsel

@lgrammel, thanks for your attention on this issue. This may not be the proper venue for such a discussion, but I wanted to share some observations from the past couple of months of using the AI SDK to build production apps with both headless and UI-based flows.

What's working exceptionally well: The AI SDK is an extremely strong framework for building with AI. The developer experience is unmatched, primarily due to how it leverages the TypeScript type system. It's clear that type safety has been a driving force behind not only the implementation but also the opinionated ontology of the framework—and this opinionation is actually a strength when you understand it.

Where friction occurs: New users (including myself and others who have contributed to this issue) often hit roadblocks where we suddenly perceive massive oversights or missing features that seem to make the SDK unusable for our chosen paradigms. In reality, these are often misalignments between our mental models and the framework's intentionally opinionated design.

A suggestion: Since the SDK's power comes from its opinionated nature, it would be helpful if this ontology and the reasoning behind key architectural decisions could be more explicitly documented. A clear articulation of the framework's opinions would help developers:

  • Understand which patterns the SDK is optimized for (and which it intentionally doesn't support)
  • Align their application architecture with the framework's design philosophy from the start
  • Recognize when they're fighting against the framework rather than working with it

This transparency about the SDK's opinions would prevent developers from investing significant time in approaches that conflict with its core design principles, turning what initially feels like "missing features" into conscious trade-offs we can plan around.

isaacwasserman avatar Aug 14 '25 14:08 isaacwasserman

For our use-case, we want to persist each message after each step is finished (with v4, we save to DB in onStepFinish), so some function to convert from Model -> UI messages would be very useful/necessary to switch to v5 (or of course receiving UIMessages directly in onStepFinish).

Erikskogetun avatar Aug 14 '25 16:08 Erikskogetun

I vibe-coded a 'modelMessagesToUiMessage' that might help someone temporarily. Have barely looked at the code, but seems to hold up for our use case at least.

export function modelMessagesToUiMessage(
  modelMessages: ResponseMessage[],
  assistantChatMessageId: string,
): UIMessage {
  const uiMessage: UIMessage = {
    id: assistantChatMessageId,
    role: 'assistant',
    parts: [],
  }

  for (const modelMessage of modelMessages) {
    switch (modelMessage.role) {
      case 'assistant': {
        if (Array.isArray(modelMessage.content)) {
          for (const content of modelMessage.content) {
            switch (content.type) {
              case 'text':
                uiMessage.parts.push({
                  type: 'text',
                  text: content.text,
                  ...(content.providerOptions
                    ? { providerMetadata: content.providerOptions }
                    : {}),
                })
                break
              case 'reasoning':
                uiMessage.parts.push({
                  type: 'reasoning',
                  text: content.text,
                  providerMetadata: content.providerOptions,
                })
                break
              case 'file':
                uiMessage.parts.push({
                  type: 'file',
                  mediaType: content.mediaType,
                  filename: content.filename,
                  url:
                    typeof content.data === 'string'
                      ? content.data
                      : content.data.toString(),
                  ...(content.providerOptions
                    ? { providerMetadata: content.providerOptions }
                    : {}),
                })
                break
              case 'tool-call':
                {
                  const toolPart: DynamicToolUIPart = {
                    type: 'dynamic-tool',
                    toolCallId: content.toolCallId,
                    toolName: content.toolName,
                    input: content.input,
                    state: 'input-available',
                    ...(content.providerOptions
                      ? { callProviderMetadata: content.providerOptions }
                      : {}),
                  }
                  uiMessage.parts.push(toolPart)
                }
                break
              case 'tool-result': {
                // Attach tool results to existing tool-call part in this assistant message if found
                const toolPart = uiMessage.parts.find(
                  (part) =>
                    (part.type === 'dynamic-tool' || isToolUIPart(part)) &&
                    part.toolCallId === content.toolCallId,
                ) as ToolUIPart<UITools> | DynamicToolUIPart | undefined

                if (toolPart) {
                  toolPart.output = content.output.value
                  const outputStr =
                    typeof content.output === 'string'
                      ? content.output
                      : JSON.stringify(content.output)
                  if (
                    outputStr.includes('Error:') ||
                    outputStr.includes('error:')
                  ) {
                    toolPart.state = 'output-error'
                    if ('errorText' in toolPart) {
                      ;(
                        toolPart as DynamicToolUIPart & { errorText?: string }
                      ).errorText = outputStr
                    }
                  } else {
                    toolPart.state = 'output-available'
                  }
                }
                break
              }
            }
          }
        }

        break
      }

      case 'tool': {
        // Tool messages typically contain results that should be associated with previous assistant messages
        // Find the last assistant message and update its tool parts with results
        if (uiMessage && Array.isArray(modelMessage.content)) {
          for (const content of modelMessage.content) {
            if (content.type === 'tool-result') {
              // Find the corresponding tool part in the assistant message
              const toolPart = uiMessage.parts.find(
                (part) =>
                  (part.type === 'dynamic-tool' || isToolUIPart(part)) &&
                  part.toolCallId === content.toolCallId,
              ) as ToolUIPart<UITools> | DynamicToolUIPart | undefined

              if (toolPart) {
                toolPart.output = content.output.value
                // Check if the output indicates an error
                const outputStr =
                  typeof content.output === 'string'
                    ? content.output
                    : JSON.stringify(content.output)
                if (
                  outputStr.includes('Error:') ||
                  outputStr.includes('error:')
                ) {
                  toolPart.state = 'output-error'
                  if ('errorText' in toolPart) {
                    ;(
                      toolPart as DynamicToolUIPart & { errorText?: string }
                    ).errorText = outputStr
                  }
                } else {
                  toolPart.state = 'output-available'
                }
              }
            }
          }
        }
        break
      }
    }
  }

  return uiMessage
}

Erikskogetun avatar Aug 15 '25 15:08 Erikskogetun

The release feels incomplete without the ability to make this conversion. Should be top prio. This isn't a feature request, it's a bug.

desiprisg avatar Aug 29 '25 18:08 desiprisg