객체 생성(Object Generation)
객체 생성(Object Generation)
useObject 훅은 React, Svelte, Vue에서만 사용할 수 있어요. 이 훅을 쓰면 스트리밍되는 구조화된 JSON 객체를 표현하는 인터페이스를 만들 수 있습니다. 이 가이드에서는 useObject 훅을 활용해 구조화된 데이터를 실시간으로 생성하는 UI를 만드는 방법을 배워볼게요.
출처: 공식문서
본문
예시로, 실시간으로 가짜 알림을 생성하는 작은 알림 데모 앱을 만들어 볼게요.
스키마
스키마는 클라이언트와 서버 양쪽에서 가져다 쓸 수 있도록 별도 파일에 설정해 두는 게 좋아요.
import { z } from 'zod';
// 알림 스키마 정의
export const notificationSchema = z.object({
notifications: z.array(
z.object({
name: z.string().describe('Name of a fictional person.'),
message: z.string().describe('Message. Do not use emojis or links.'),
})
),
});
클라이언트
클라이언트는 useObject 훅으로 객체 생성 과정을 스트리밍해요. 결과는 부분적으로 도착하므로 받는 대로 표시합니다. JSX에서 undefined 값을 처리하는 코드에 유의하세요.
'use client';
import { useObject } from '@ai-sdk/react';
import { notificationSchema } from './api/notifications/schema';
export default function Page() {
const { object, submit } = useObject({
api: '/api/notifications',
schema: notificationSchema,
});
return (
<>
<button onClick={() => submit('Messages during finals week.')}>
Generate notifications
</button>
{object?.notifications?.map((notification, index) => (
<div key={index}>
<p>{notification?.name}</p>
<p>{notification?.message}</p>
</div>
))}
</>
);
}
서버
서버에서는 streamText와 Output.object()를 조합해 객체 생성 과정을 스트리밍해요.
import { createTextStreamResponse, Output, streamText, toTextStream } from 'ai';
import { notificationSchema } from './schema';
// 스트리밍 응답 시간을 최대 30초까지 허용
export const maxDuration = 30;
export async function POST(req: Request) {
const context = await req.json();
const result = streamText({
model: "xai/grok-4.5",
output: Output.object({ schema: notificationSchema }),
prompt:
`Generate 3 notifications for a messages app in this context: ` + context,
});
return createTextStreamResponse({
stream: toTextStream({ stream: result.stream }),
});
}
Enum 출력 모드
입력을 미리 정의된 옵션 중 하나로 분류하거나 카테고리화해야 한다면, useObject로 enum 출력 모드를 쓸 수 있어요. 이를 위해선 객체에 enum 키가 있고 그 값이 z.enum(가능한 값들)으로 된 특정 스키마 구조가 필요합니다. 예를 들면 문장을 true/false로 분류하는 텍스트 분류기를 만들 때 유용해요.
더 알아보기
Output.object()— 구조화된 출력 스트리밍의 서버 측 방식.useObject의submit— 클라이언트에서 객체 생성을 시작하는 함수.z.enum— enum 출력 모드에서 가능한 값을 정의하는 방법.