ai icon indicating copy to clipboard operation
ai copied to clipboard

Add support for validating UIMessage[]

Open nick-rackauckas opened this issue 1 year ago • 12 comments

Description

Background

Currently, the AI SDK v5 exports Zod schemas for core/model message types (userModelMessageSchema, assistantModelMessageSchema, etc.) but does not provide equivalent validation schemas for UI message types.

Request

Please expose a Zod schema for UIMessage and its related types (UIMessagePart, TextUIPart, ToolUIPart, etc.) to enable runtime validation of UI messages.

Use Case

This would be useful for:

  • Type-safe deserialization of data persisted in the UI Message interfaces

Current Workaround

Currently, developers need to create their own validation schemas or manual type guards

Proposed Solution

Export schemas similar to the existing model message schemas:

  • uiMessageSchema
  • uiMessagePartSchema
  • textUIPartSchema
  • toolUIPartSchema
  • etc.

AI SDK Version

ai: 5.0.0-alpha.13 @ai-sdk/react: 5.0.0-alpha.13

nick-rackauckas avatar Jun 16 '25 17:06 nick-rackauckas

Do you know how to extend the UIMessage type for now?

0Chan-smc avatar Jun 27 '25 01:06 0Chan-smc

@0Chan-smc https://github.com/vercel/ai/blob/v5/examples/next-openai/app/api/use-chat-tools/route.ts#L62 is an example. you use generics

lgrammel avatar Jun 27 '25 05:06 lgrammel

@0Chan-smc https://github.com/vercel/ai/blob/v5/examples/next-openai/app/api/use-chat-tools/route.ts#L62 is an example. you use generics

Thanks for the response! I think the original issue was misunderstood by the first comment, so I can elaborate.

Type information already exists. The UIMessage, UIMessagePart, TextUIPart, etc. TypeScript interfaces are great for compile-time safety.

What’s missing is the run-time equivalent – a Zod schema that I can parse() persisted data with, exactly like the runtime validators that are already exported for core/model messages (userModelMessageSchema, assistantModelMessageSchema, …).

Why a runtime schema matters

I’m storing chat history (including tool calls) in a database so it can be re-hydrated later. On reload I need to be sure the JSON I pull out actually conforms to the SDK’s idea of a UI message. Right now I have to hand-roll a schema or a bunch of type-guards, and every SDK release risks drift.

Ex:

// Proposed – exported by the SDK
export const uiMessageSchema = z.object({
  id: z.string(),
  role: z.enum(['user','assistant','system']),
  parts: z.array(uiMessagePartSchema),
  /* …other fields that already exist in UIMessage … */
});

export const uiMessagePartSchema = z.discriminatedUnion('type', {
  text : textUIPartSchema,
  tool : toolUIPartSchema,
  /* … */
});

// Then consumers can do
const raw = JSON.parse(row.json);
const msg = uiMessageSchema.parse(raw);  // runtime-safe 🎉

Unless I'm missing something, not sure that generics would help in this case. Let me know if this clears things up or if I can provide any more detail!

nick-rackauckas avatar Jun 27 '25 18:06 nick-rackauckas

+ 1 on this. Suprised that there is not a happy path to handle validation in the route before passing to streamText.

Lermatroid avatar Jul 02 '25 23:07 Lermatroid

This would be extremely useful to have so we can validate incoming request messages and not have to assume the type is correct.

chris-keyplay avatar Jul 24 '25 05:07 chris-keyplay

Unofficial version. Improvements welcome!

import z from "zod";
import { type UIMessage } from "ai";

/**
 * @see https://github.com/vercel/ai/blob/main/packages/provider/src/shared/v2/shared-v2-provider-metadata.ts#L24
 */
const providerMetadata = z
  .record(z.string(), z.record(z.string(), z.json()))
  .optional();

/**
 * @see https://github.com/vercel/ai/issues/6763
 * @see https://github.com/vercel/ai/blob/90d212f244a400b3660dd76b2fc183859cb2c5cc/packages/ai/src/ui/ui-messages.ts#L258
 */
export const uiMessageSchema: z.ZodType<UIMessage> = z.object({
  id: z.string(),
  metadata: z.unknown().optional(),
  role: z.enum(["user", "assistant", "system"]),
  parts: z.array(
    // cannot use z.discriminatedUnion because of z.templateLiteral
    z.union([
      z.object({
        type: z.literal("text"),
        text: z.string(),
        state: z.enum(["streaming", "done"]).optional(),
        providerMetadata,
      }),
      z.object({
        type: z.literal("reasoning"),
        text: z.string(),
        state: z.enum(["streaming", "done"]).optional(),
        providerMetadata,
      }),
      z.object({
        type: z.literal("source-url"),
        sourceId: z.string(),
        url: z.string(),
        title: z.string().optional(),
        providerMetadata,
      }),
      z.object({
        type: z.literal("source-document"),
        sourceId: z.string(),
        mediaType: z.string(),
        title: z.string(),
        filename: z.string().optional(),
        providerMetadata,
      }),
      z.object({
        type: z.literal("file"),
        mediaType: z.string(),
        filename: z.string().optional(),
        url: z.string(),
        providerMetadata,
      }),
      z.object({
        type: z.literal("step-start"),
      }),
      z.object({
        type: z.templateLiteral(["data-", z.string()]),
        id: z.string().optional(),
        data: z.unknown(),
      }),
      createToolStates(
        z.object({
          type: z.templateLiteral(["tool-", z.string()]),
          toolCallId: z.string(),
        }),
      ),
      createToolStates(
        z.object({
          type: z.literal("dynamic-tool"),
          toolName: z.string(),
          toolCallId: z.string(),
        }),
      ),
    ]),
  ),
});

/**
 * Nested discriminated unions for tool states
 * @see https://zod.dev/api#discriminated-unions
 */
function createToolStates<T extends z.ZodRawShape>(baseSchema: z.ZodObject<T>) {
  return z.discriminatedUnion("state", [
    z.object({
      ...baseSchema.shape,
      state: z.literal("input-streaming"),
      input: z.unknown(),
    }),
    z.object({
      ...baseSchema.shape,
      state: z.literal("input-available"),
      input: z.unknown(),
      providedExecuted: z.boolean().optional(),
      callProviderMetadata: providerMetadata,
    }),
    z.object({
      ...baseSchema.shape,
      state: z.literal("output-available"),
      input: z.unknown(),
      output: z.unknown(),
      providedExecuted: z.boolean().optional(),
      callProviderMetadata: providerMetadata,
    }),
    z.object({
      ...baseSchema.shape,
      state: z.literal("output-error"),
      input: z.unknown(),
      errorText: z.string(),
      providedExecuted: z.boolean().optional(),
      callProviderMetadata: providerMetadata,
    }),
  ]);
}

bestickley avatar Aug 05 '25 14:08 bestickley

@bestickley i have not added this yet because ideally it should also validate data part, metadata, and tool call input/output structure, which is generic. what are your thoughts on that part?

lgrammel avatar Aug 05 '25 14:08 lgrammel

@lgrammel, I'm ok with coarse grained zod schema for UIMessage that doesn't have generics so that I can simply have schema validation on each endpoint / API route. But in TS for each tool (after validation) I do want fine-grained type safety which the current type (UIMessage) provides.

I think it will be difficult for zod schema to provide parity with complex TS type (hope I'm wrong about that though).

bestickley avatar Aug 05 '25 14:08 bestickley

It is strange that AI SDK v5 recommends saving UIMessage to database, so that means having it as input in an endpoint.

But there is no built in Zod type for validating the input...

raress96 avatar Aug 10 '25 11:08 raress96

+1

juliangoetze avatar Aug 11 '25 03:08 juliangoetze

This issue is actually way more complex than it seems. We need to support zod3, zod4, and custom validation for data parts, tool schemas etc.

Is the use case just validation?

Then my preferred solution would be to add a validateUIMessages function that makes less assumptions on the validation libraries and also supports validating user defined types to some degree.

lgrammel avatar Aug 13 '25 13:08 lgrammel

Identify issue type

Identified as Feature
Confidence: High

Rationale

This asks for a new runtime-validation capability for UI messages rather than reporting broken existing behavior.

Evidence

  • The SDK provides TypeScript UI message types but no exported runtime validators for them.
  • The request proposes new schemas such as uiMessageSchema and uiMessagePartSchema for validating persisted or incoming data.
  • A maintainer suggests adding a new validateUIMessages function that could support custom data parts, tool schemas, Zod versions, and other validation libraries.

lgrammel avatar Jul 22 '26 14:07 lgrammel