`validateUIMessages`
validateUIMessages
메타데이터, 데이터 파트, 툴에 대한 스키마로 UI 메시지를 검증하는 비동기 함수예요.
출처: 문서
본문
validateUIMessages는 UI 메시지를 메타데이터, 데이터 파트, 툴에 대한 스키마로 검증하는 비동기 함수예요. 처리하거나 렌더링하기 전에 메시지 배열의 타입 안전성과 데이터 무결성을 보장해 줘요.
기본 사용법
커스텀 스키마 없이 간단하게 검증하기:
import { validateUIMessages } from 'ai';
const messages = [
{
id: '1',
role: 'user',
parts: [{ type: 'text', text: 'Hello!' }],
},
];
const validatedMessages = await validateUIMessages({
messages,
});
고급 사용법
커스텀 메타데이터, 데이터 파트, 툴로 종합적인 검증하기:
import { validateUIMessages, tool } from 'ai';
import { z } from 'zod';
// Define schemas
const metadataSchema = z.object({
timestamp: z.string().datetime(),
userId: z.string(),
});
const dataSchemas = {
chart: z.object({
data: z.array(z.number()),
labels: z.array(z.string()),
}),
image: z.object({
url: z.string().url(),
caption: z.string(),
}),
};
const tools = {
weather: tool({
description: 'Get weather info',
inputSchema: z.object({
location: z.string(),
}),
execute: async ({ location }) => `Weather in ${location}: sunny`,
}),
};
// Messages with custom parts
const messages = [
{
id: '1',
role: 'user',
metadata: { timestamp: '2024-01-01T00:00:00Z', userId: 'user123' },
parts: [
{ type: 'text', text: 'Show me a chart' },
{
type: 'data-chart',
data: { data: [1, 2, 3], labels: ['A', 'B', 'C'] },
},
],
},
{
id: '2',
role: 'assistant',
parts: [
{
type: 'tool-weather',
toolCallId: 'call_123',
state: 'output-available',
input: { location: 'San Francisco' },
output: 'Weather in San Francisco: sunny',
},
],
},
];
// Validate with all schemas
const validatedMessages = await validateUIMessages({
messages,
metadataSchema,
dataSchemas,
tools,
});
experimental_refineToolInput로 만들어진 승인(approval) 메시지를 검증할 때는 같은 refine 함수를 전달해서 validateUIMessages가 승인된 입력을 재구성하고 검증할 수 있게 해요:
const experimental_refineToolInput = {
weather: (input: { location: string }) => ({
location: input.location.trim(),
}),
};
const validatedMessages = await validateUIMessages({
messages,
tools,
experimental_refineToolInput,
});
더 이상 사용하지 않는 rawInput 필드
하위 호환성을 위해, 검증은 여전히 output-error 상태의 툴 파트에서 rawInput을 받아들여요. 정의된 rawInput 값이 발견되면 validateUIMessages는 AI_SDK_LOG_WARNINGS를 통해 AI SDK 사용 중단(deprecation) 경고를 내보내요.
저장된 메시지를 input에 툴 인자를 저장하도록 마이그레이션하고 rawInput을 제거하세요. 하위 호환성을 위해 변환은 input이 null 또는 undefined일 때 rawInput을 대체로 사용해요. rawInput은 다음 메이저 버전에서 제거될 예정이에요.
더 알아보기 (Learn more)
- generateText
- streamText
- embed
- embedMany
- rerank
- generateImage
- experimental_streamTranscribe
- experimental_streamTranslate
- transcribe
- generateSpeech
- experimental_generateVideo
- experimental_evaluate
- uploadFile
- uploadSkill
- Agent (Interface)
- ToolLoopAgent
- createAgentUIStream
- createAgentUIStreamResponse
- pipeAgentUIStreamToResponse
- experimental_startBatch
- tool
- experimental_getBatchStatus
- dynamicTool
- experimental_getBatchResults
- experimental_cancelBatch
- createMCPClient
- experimental_getRealtimeToolDefinitions
- toolSearch
- experimental_listBatches
- MCP Apps
- Experimental_StdioMCPTransport
- jsonSchema
- zodSchema
- valibotSchema
- Output
- filterActiveTools
- ModelMessage
- UIMessage
- validateUIMessages
- safeValidateUIMessages
- Experimental_SandboxSession
- createProviderRegistry
- customProvider
- cosineSimilarity
- wrapLanguageModel
- wrapImageModel
- LanguageModelV4Middleware
- extractReasoningMiddleware
- simulateStreamingMiddleware
- defaultInstructionsMiddleware
- defaultSettingsMiddleware
- addToolInputExamplesMiddleware
- extractJsonMiddleware
- isStepCount
- hasToolCall
- isLoopFinished
- simulateReadableStream
- smoothStream
- generateId
- createIdGenerator
- DefaultGeneratedFile