`createAgentUIStream`
createAgentUIStream
createAgentUIStream 함수는 Agent를 실행하고, UI 메시지 배열을 소비하며, 에이전트의 출력을 비동기 이터러블을 통해 UI 메시지 청크로 스트리밍합니다. 이는 자체 런타임에서 AI 어시스턴트 출력을 실시간으로 증분 렌더링할 수 있게 해 주며, 툴 사용, 중간 추론, 대화형 UI 기능에 완전히 접근할 수 있습니다. 에이전트 기반 채팅 API, 대시보드, 봇을 만드는 데 적합합니다.
출처: 문서
본문
Import
import { createAgentUIStream } from "ai"
Usage (사용법)
import { ToolLoopAgent, createAgentUIStream } from 'ai';
__PROVIDER_IMPORT__;
const agent = new ToolLoopAgent({
model: __MODEL__,
instructions: 'You are a helpful assistant.',
tools: { weather: weatherTool, calculator: calculatorTool },
});
export async function* streamAgent(
uiMessages: unknown[],
abortSignal?: AbortSignal,
) {
const stream = await createAgentUIStream({
agent,
uiMessages,
abortSignal,
// experimental_sandbox, // optional: pass an experimental sandbox through to tool execution
// ...other options (see below)
});
for await (const chunk of stream) {
yield chunk; // Each chunk is a UI message output from the agent.
}
}
Parameters (파라미터)
agent:Agent(필수) — 실행할 에이전트입니다.tools를 정의하고.stream({ prompt, ... })을 구현해야 합니다.uiMessages:unknown[](필수) — 입력 UI 메시지 객체 배열입니다 (예: user/assistant 채팅 기록). 에이전트용으로 검증되고 변환됩니다.abortSignal:AbortSignal(선택) — 스트림을 일찍 취소할 수 있는 선택적 abort 신호입니다 (예: 클라이언트 연결이 끊겼을 때).timeout:number | { totalMs?: number }(선택) — 밀리초 단위 타임아웃입니다. 숫자 또는totalMs속성을 가진 객체로 지정할 수 있습니다. 지정된 타임아웃보다 오래 걸리면 호출이 중단됩니다.abortSignal과 함께 사용할 수 있습니다.experimental_sandbox:Experimental_SandboxSession(선택) — 툴 실행에 전달되는 선택적 실험적 샌드박스 환경입니다. 툴은 실행 컨텍스트에서 접근할 수 있습니다.options:CALL_OPTIONS(선택) — 선택적 에이전트 호출 옵션입니다. 에이전트가 추가 구성(에이전트 제네릭 파라미터 참조)을 기대할 때만 필요합니다.experimental_transform:StreamTextTransform | StreamTextTransform[](선택) — 에이전트 출력 스트림에 적용할 선택적 변환입니다 (실험적).onStepEnd:GenerateTextOnStepEndCallback(선택) — 각 에이전트 스텝(LLM/툴 호출)이 완료된 후 호출되는 콜백입니다. 토큰 사용량, 스텝별 성능 추적, 중간 스텝 로깅에 유용합니다.onStepFinish:GenerateTextOnStepFinishCallback(선택) — deprecated 되었습니다.onStepEnd를 사용하세요. 이 별칭은onStepEnd가 제공되지 않을 때의 폴백으로만 사용됩니다....UIMessageStreamOptions:UIMessageStreamOptions(선택) — sources나 usage 데이터 포함 등 출력 스트림을 제어하는 추가 옵션입니다.
Returns (반환값)
Promise<AsyncIterableStream<UIMessageChunk>>를 반환하며, 각 생성된 청크는 에이전트의 UI 메시지 출력입니다(UIMessage 참고). 모든 비동기 이터레이터 루프로 소비하거나 스트리밍 HTTP 응답, 소켓, 기타 싱크로 파이프할 수 있습니다.
Example (예제)
import { createAgentUIStream } from 'ai';
const controller = new AbortController();
const stream = await createAgentUIStream({
agent,
uiMessages: [{ role: 'user', content: 'What is the weather in SF today?' }],
abortSignal: controller.signal,
// experimental_sandbox, // optional
sendStart: true,
// ...other UIMessageStreamOptions
});
for await (const chunk of stream) {
// Each chunk is a UI message update — stream it to your client, dashboard, logs, etc.
console.log(chunk);
}
// Call controller.abort() to cancel the agent operation early.
How It Works (동작 방식)
- UI 메시지 검증: 입력
uiMessages배열은 에이전트의tools정의를 사용해 검증되고 정규화됩니다. 유효하지 않은 메시지가 있으면 오류가 발생합니다. - 모델 메시지 변환: 검증된 UI 메시지는 에이전트가 요구하는 모델별 메시지 형식으로 변환됩니다.
- 에이전트 스트리밍: 변환된 모델 메시지, 선택적 호출 옵션, abort 신호, experimental_sandbox, 선택적 실험적 transform을 사용해 에이전트의
.stream({ prompt, ... })메서드가 호출됩니다. - UI 메시지 스트림 구축: 결과 스트림은 소비할 수 있게 UI 메시지 청크의 스트리밍 비동기 이터러블로 변환되어 노출됩니다.
Notes (참고)
- 에이전트는 반드시
.stream({ prompt, ... })메서드를 구현하고 지원하는tools속성을 정의해야 합니다. - 이 유틸리티는 최대 스트리밍 유연성을 위해 비동기 이터러블을 반환합니다. HTTP 응답의 경우
createAgentUIStreamResponse(Web) 또는pipeAgentUIStreamToResponse(Node.js)를 참고하세요. uiMessages파라미터 이름은messages가 아니라uiMessages입니다.UIMessageStreamOptions로 고급 옵션을 제공할 수 있습니다 (예: sources나 usage 포함).- 스트림을 취소하려면
abortSignal파라미터로AbortSignal을 전달하세요. - 에이전트 툴이 실행 중 실험적 샌드박스 환경이 필요할 때
experimental_sandbox를 전달하세요.