`safeValidateUIMessages`
safeValidateUIMessages
safeValidateUIMessages는 validateUIMessages처럼 UI 메시지를 검증하는 비동기 함수이지만, throw하는 대신 success 키와 data 또는 error를 가진 객체를 반환합니다.
출처: 문서
본문
기본 사용법
커스텀 스키마 없는 간단한 검증:
import { safeValidateUIMessages } from 'ai';
const messages = [
{
id: '1',
role: 'user',
parts: [{ type: 'text', text: 'Hello!' }],
},
];
const result = await safeValidateUIMessages({
messages,
});
if (!result.success) {
console.error(result.error.message);
} else {
const validatedMessages = result.data;
}
deprecated된 rawInput 필드
이전 버전과의 호환성을 위해 검증은 여전히 output-error 상태의 툴 파트에서 rawInput을 허용합니다. 정의된 rawInput 값이 발견되면 safeValidateUIMessages는 AI_SDK_LOG_WARNINGS를 통해 AI SDK deprecation 경고를 발생시킵니다.
저장된 메시지를 마이그레이션하여 툴 인자를 input에 저장하고 rawInput을 제거하세요. 이전 버전과의 호환성을 위해 변환은 input이 null 또는 undefined일 때 rawInput을 폴백으로 사용합니다. rawInput은 다음 메이저 버전에서 제거될 예정입니다.
고급 사용법
커스텀 메타데이터, 데이터 파트, 툴이 있는 포괄적인 검증:
import { safeValidateUIMessages, 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 result = await safeValidateUIMessages({
messages,
metadataSchema,
dataSchemas,
tools,
});
if (!result.success) {
console.error(result.error.message);
} else {
const validatedMessages = result.data;
}