본문으로 바로가기 본문 바로가기
WIKI 기술 지식 베이스

Chat - 스트리밍(Streaming)

원문 보기 위키 갱신

어댑터에서 어시스턴트 응답을 청크 단위로 Chat UI에 스트리밍해 토큰 단위의 실시간 업데이트를 제공합니다.

본문

스트리밍은 응답을 즉각적으로 느끼게 만듭니다: 전체 완료를 기다리는 대신, 사용자는 모델이 텍스트를 생성하는 대로 화면에 나타나는 것을 보게 됩니다. 이 페이지는 어댑터 작성자를 위한 것입니다 — 런타임이 소비하는 청크 프로토콜과 각 청크가 어떻게 UI 상태가 되는지를 명시합니다.

Chat 컴포넌트는 어시스턴트 응답을 토큰 단위로 스트리밍합니다. 어댑터의 sendMessage() 메서드는 ReadableStream<ChatMessageChunk | ChatStreamEnvelope>를 반환합니다. 런타임은 이 스트림을 읽고 각 청크를 처리한 뒤 정규화된 저장소를 업데이트해 UI 컴포넌트가 점진적으로 다시 렌더링되게 합니다. 아래 데모는 미리 준비된 응답을 토큰 단위로 스트리밍해 청크가 도착하는 모습을 보고 flush 간격을 조정할 수 있습니다.

스트림 수명주기(Stream lifecycle)

모든 스트림은 다음 수명주기를 따라야 합니다:

  1. start — 새 어시스턴트 메시지를 시작합니다. 런타임은 메시지 셸(shell)을 만들고 상태를 'streaming'으로 설정합니다.
  2. 콘텐츠 청크 — 텍스트, 추론, 도구, 소스, 파일, 데이터 또는 메타데이터 청크가 메시지를 채웁니다.
  3. finish 또는 abort — 종료 청크. finish는 메시지를 'sent'로 표시하고, abort는 'cancelled'로 표시합니다.

종료 청크 없이 스트림이 닫히면 런타임은 이를 연결 끊김(disconnect)으로 처리합니다(아래 오류와 연결 끊김 처리 참고).

스트림 구축하기

어댑터를 작성할 때 청크 배열에서 ReadableStream을 구성합니다:

const adapter: ChatAdapter = {
  async sendMessage({ message }) {
    return new ReadableStream({
      start(controller) {
        controller.enqueue({ type: 'start', messageId: 'msg-1' });
        controller.enqueue({ type: 'text-start', id: 'text-1' });
        controller.enqueue({ type: 'text-delta', id: 'text-1', delta: 'Hello!' });
        controller.enqueue({ type: 'text-end', id: 'text-1' });
        controller.enqueue({ type: 'finish', messageId: 'msg-1' });
        controller.close();
      },
    });
  },
};

또는 server-sent event 스트림을 청크로 변환합니다:

async function fromSSE(
  url: string,
  signal: AbortSignal,
): Promise<ReadableStream<ChatMessageChunk>> {
  const response = await fetch(url, { signal });
  const reader = response.body!.getReader();
  const decoder = new TextDecoder();
  let buffer = '';

  return new ReadableStream({
    async pull(controller) {
      const { done, value } = await reader.read();
      if (done) {
        controller.close();
        return;
      }
      buffer += decoder.decode(value, { stream: true });
      const lines = buffer.split('\n');
      buffer = lines.pop() ?? '';
      for (const line of lines) {
        if (line.startsWith('data: ')) {
          const data = line.slice(6).trim();
          if (data && data !== '[DONE]') {
            controller.enqueue(JSON.parse(data));
          }
        }
      }
    },
  });
}

청크 중복 제거 및 정렬

중복 제거와 정렬을 위해 청크를 ChatStreamEnvelope로 감쌉니다:

interface ChatStreamEnvelope {
  eventId?: string; // unique event identifier for deduplication
  sequence?: number; // monotonic ordering number
  chunk: ChatMessageChunk;
}

런타임은 원시 ChatMessageChunk 객체와 감싸진 청크를 같은 스트림에서 모두 허용합니다. Envelope는 청크가 순서를 벗어나 도착하거나 다시 재생될 수 있는 SSE 기반 전송에 유용합니다.

Flush 간격 제어하기

런타임은 빠른 텍스트 및 추론 델타를 저장소에 적용하기 전에 일괄 처리합니다. ChatBox의 streamFlushInterval prop(또는 ChatProvider)이 일괄 처리 창을 제어합니다. 기본값은 16ms(60fps에서 대략 프레임 하나)입니다.

streamFlushInterval prop에 커스텀 간격을 전달해 기본값을 오버라이드합니다:

<ChatBox adapter={adapter} streamFlushInterval={32} />

:::info 값이 낮을수록 시각적 업데이트가 빨라지지만 저장소 변형이 많아집니다. 값이 높을수록 변형 빈도는 줄어들지만 지각된 지연 시간이 늘어납니다. :::

import * as React from 'react';
import Box from '@mui/material/Box';
import Stack from '@mui/material/Stack';
import Typography from '@mui/material/Typography';
import ToggleButton from '@mui/material/ToggleButton';
import ToggleButtonGroup from '@mui/material/ToggleButtonGroup';
import { ChatBox } from '@mui/x-chat';
import type {
  ChatAdapter,
  ChatConversation,
  ChatMessage,
  ChatMessageChunk,
} from '@mui/x-chat/headless';
import { users } from 'docs/src/modules/components/chat-playground/data';

const conversation: ChatConversation = {
  id: 'streaming-playground',
  title: 'Streaming preview',
  participants: [users.me, users.assistant],
};

const greeting: ChatMessage = {
  id: 'streaming-greeting',
  conversationId: conversation.id,
  role: 'assistant',
  author: users.assistant,
  createdAt: '2026-05-03T10:00:00.000Z',
  status: 'sent',
  parts: [
    {
      type: 'text',
      text: 'Ask me anything — I will stream the reply back one word at a time.',
    },
  ],
};

let replyCounter = 0;
function nextReplyId() {
  replyCounter += 1;
  return `streaming-reply-${replyCounter}`;
}

// Mirrors the "Building a stream" snippet: start → text-start → one
// text-delta per word → text-end → finish. Honors cancel() so the composer
// stop button clears pending timers and stops enqueuing mid-stream.
function createStream(text: string, chunkDelay: number) {
  const messageId = nextReplyId();
  const words = text.split(' ');
  const chunks: ChatMessageChunk[] = [
    { type: 'start', messageId, author: users.assistant },
    { type: 'text-start', id: `${messageId}-text` },
    ...words.map((word, index) => ({
      type: 'text-delta' as const,
      id: `${messageId}-text`,
      delta: index === 0 ? word : ` ${word}`,
    })),
    { type: 'text-end', id: `${messageId}-text` },
    { type: 'finish' as const, messageId, finishReason: 'stop' },
  ];

  const timers: ReturnType<typeof setTimeout>[] = [];
  let cancelled = false;

  return new ReadableStream<ChatMessageChunk>({
    start(controller) {
      chunks.forEach((chunk, index) => {
        timers.push(
          setTimeout(
            () => {
              if (cancelled) {
                return;
              }
              controller.enqueue(chunk);
              if (index === chunks.length - 1) {
                controller.close();
              }
            },
            chunkDelay * (index + 1),
          ),
        );
      });
    },
    cancel() {
      cancelled = true;
      timers.forEach((timer) => clearTimeout(timer));
    },
  });
}

const FLUSH_OPTIONS = [
  { label: '0 ms', value: 0 },
  { label: '16 ms (default)', value: 16 },
  { label: '100 ms', value: 100 },
  { label: '300 ms', value: 300 },
];

const DELAY_OPTIONS = [
  { label: '10 ms', value: 10 },
  { label: '40 ms', value: 40 },
  { label: '120 ms', value: 120 },
];

export default function ChatStreamingPlayground() {
  const [flushInterval, setFlushInterval] = React.useState(16);
  const [chunkDelay, setChunkDelay] = React.useState(40);

  // Read the latest chunk delay through a ref so the adapter identity stays
  // stable while still honoring the current selector value on each send.
  const chunkDelayRef = React.useRef(chunkDelay);
  chunkDelayRef.current = chunkDelay;

  const adapter = React.useMemo<ChatAdapter>(
    () => ({
      async listMessages() {
        return { messages: [greeting], hasMore: false };
      },
      async sendMessage({ message }) {
        const prompt = message.parts
          .map((part) => (part.type === 'text' ? part.text : ''))
          .join(' ')
          .trim();
        const reply =
          prompt.length === 0
            ? 'Type a prompt and watch each word arrive as a separate chunk.'
            : `You said: "${prompt}". Here is a streamed reply so you can watch tokens land and feel the flush interval.`;
        return createStream(reply, chunkDelayRef.current);
      },
    }),
    [],
  );

  return (
    <Stack spacing={2}>
      <Stack
        direction={{ xs: 'column', sm: 'row' }}
        spacing={3}
        sx={{ flexWrap: 'wrap' }}
      >
        <Stack spacing={0.5}>
          <Typography variant="caption" color="text.secondary">
            Flush interval
          </Typography>
          <ToggleButtonGroup
            size="small"
            exclusive
            value={flushInterval}
            onChange={(event, value) => {
              if (value !== null) {
                setFlushInterval(value);
              }
            }}
            aria-label="Flush interval"
          >
            {FLUSH_OPTIONS.map((option) => (
              <ToggleButton key={option.value} value={option.value}>
                {option.label}
              </ToggleButton>
            ))}
          </ToggleButtonGroup>
        </Stack>
        <Stack spacing={0.5}>
          <Typography variant="caption" color="text.secondary">
            Chunk delay
          </Typography>
          <ToggleButtonGroup
            size="small"
            exclusive
            value={chunkDelay}
            onChange={(event, value) => {
              if (value !== null) {
                setChunkDelay(value);
              }
            }}
            aria-label="Chunk delay"
          >
            {DELAY_OPTIONS.map((option) => (
              <ToggleButton key={option.value} value={option.value}>
                {option.label}
              </ToggleButton>
            ))}
          </ToggleButtonGroup>
        </Stack>
      </Stack>
      <Box sx={{ height: 420 }}>
        <ChatBox
          adapter={adapter}
          currentUser={users.me}
          members={[users.me, users.assistant]}
          initialConversations={[conversation]}
          activeConversationId={conversation.id}
          streamFlushInterval={flushInterval}
          sx={{ height: '100%' }}
        />
      </Box>
    </Stack>
  );
}

스트리밍 표시기(Streaming indicator)

응답이 진행되는 동안 Chat 컴포넌트는 어시스턴트가 작업 중임을 사용자가 알 수 있도록 애니메이션 점을 표시합니다. 표시기는 두 단계를 다룹니다:

  1. 대기(Waiting) — 사용자가 메시지를 보낸 후 start 청크가 도착하기 전에, 표시기는 마지막 메시지 아래에 들어오는 어시스턴트 행으로 렌더링됩니다: 점을 담은 타이핑 버블 옆에 어시스턴트의 아바타(members 또는 대화의 participants에서 해석 가능한 경우).
  2. 스트리밍(Streaming) — status: 'streaming'인 어시스턴트 메시지가 존재하면, 점이 실제 어시스턴트 버블 안, 스트리밍된 콘텐츠 아래로 이동하며, 스트림이 끝나면 사라집니다.
import * as React from 'react';
import Box from '@mui/material/Box';
import Stack from '@mui/material/Stack';
import Typography from '@mui/material/Typography';
import ToggleButton from '@mui/material/ToggleButton';
import ToggleButtonGroup from '@mui/material/ToggleButtonGroup';
import { ChatBox } from '@mui/x-chat';
import type {
  ChatAdapter,
  ChatConversation,
  ChatMessage,
  ChatMessageChunk,
} from '@mui/x-chat/headless';
import { users } from 'docs/src/modules/components/chat-playground/data';

const conversation: ChatConversation = {
  id: 'streaming-indicator-demo',
  title: 'Streaming indicator preview',
  participants: [users.me, users.assistant],
};

const greeting: ChatMessage = {
  id: 'streaming-indicator-greeting',
  conversationId: conversation.id,
  role: 'assistant',
  author: users.assistant,
  createdAt: '2026-05-03T10:00:00.000Z',
  status: 'sent',
  parts: [
    {
      type: 'text',
      text: 'Send a message — the dots appear while I "think", then follow the reply as it streams.',
    },
  ],
};

let replyCounter = 0;
function nextReplyId() {
  replyCounter += 1;
  return `streaming-indicator-reply-${replyCounter}`;
}

// `thinkingDelay` holds back the `start` chunk to simulate model latency —
// that gap is the indicator's waiting phase. Once `start` lands, the dots
// move inside the assistant bubble until `finish`.
function createStream(text: string, thinkingDelay: number) {
  const messageId = nextReplyId();
  const words = text.split(' ');
  const chunks: ChatMessageChunk[] = [
    { type: 'start', messageId, author: users.assistant },
    { type: 'text-start', id: `${messageId}-text` },
    ...words.map((word, index) => ({
      type: 'text-delta' as const,
      id: `${messageId}-text`,
      delta: index === 0 ? word : ` ${word}`,
    })),
    { type: 'text-end', id: `${messageId}-text` },
    { type: 'finish' as const, messageId, finishReason: 'stop' },
  ];

  const timers: ReturnType<typeof setTimeout>[] = [];
  let cancelled = false;

  return new ReadableStream<ChatMessageChunk>({
    start(controller) {
      chunks.forEach((chunk, index) => {
        timers.push(
          setTimeout(
            () => {
              if (cancelled) {
                return;
              }
              controller.enqueue(chunk);
              if (index === chunks.length - 1) {
                controller.close();
              }
            },
            thinkingDelay + 120 * index,
          ),
        );
      });
    },
    cancel() {
      cancelled = true;
      timers.forEach((timer) => clearTimeout(timer));
    },
  });
}

type IndicatorMode = 'auto' | 'always' | 'never';

const MODE_OPTIONS: Array<{ label: string; value: IndicatorMode }> = [
  { label: "'auto' (default)", value: 'auto' },
  { label: 'true (always)', value: 'always' },
  { label: 'false (never)', value: 'never' },
];

const FEATURE_VALUE: Record<IndicatorMode, boolean | 'auto'> = {
  auto: 'auto',
  always: true,
  never: false,
};

const THINKING_OPTIONS = [
  { label: '1 s', value: 1000 },
  { label: '2.5 s', value: 2500 },
  { label: '5 s', value: 5000 },
];

export default function ChatStreamingIndicatorDemo() {
  const [mode, setMode] = React.useState<IndicatorMode>('auto');
  const [thinkingDelay, setThinkingDelay] = React.useState(2500);

  // Read the latest delay through a ref so the adapter identity stays stable
  // while still honoring the current selector value on each send.
  const thinkingDelayRef = React.useRef(thinkingDelay);
  thinkingDelayRef.current = thinkingDelay;

  const adapter = React.useMemo<ChatAdapter>(
    () => ({
      async listMessages() {
        return { messages: [greeting], hasMore: false };
      },
      async sendMessage({ message }) {
        const prompt = message.parts
          .map((part) => (part.type === 'text' ? part.text : ''))
          .join(' ')
          .trim();
        const reply =
          prompt.length === 0
            ? 'The dots covered the silence while this reply was on its way.'
            : `You said: "${prompt}". The animated dots bridged the wait, and now they trail this reply until it finishes streaming.`;
        return createStream(reply, thinkingDelayRef.current);
      },
    }),
    [],
  );

  return (
    <Stack spacing={2}>
      <Stack
        direction={{ xs: 'column', sm: 'row' }}
        spacing={3}
        sx={{ flexWrap: 'wrap' }}
      >
        <Stack spacing={0.5}>
          <Typography variant="caption" color="text.secondary">
            features.streamingIndicator
          </Typography>
          <ToggleButtonGroup
            size="small"
            exclusive
            value={mode}
            onChange={(event, value) => {
              if (value !== null) {
                setMode(value);
              }
            }}
            aria-label="Streaming indicator mode"
          >
            {MODE_OPTIONS.map((option) => (
              <ToggleButton key={option.value} value={option.value}>
                {option.label}
              </ToggleButton>
            ))}
          </ToggleButtonGroup>
        </Stack>
        <Stack spacing={0.5}>
          <Typography variant="caption" color="text.secondary">
            Thinking delay
          </Typography>
          <ToggleButtonGroup
            size="small"
            exclusive
            value={thinkingDelay}
            onChange={(event, value) => {
              if (value !== null) {
                setThinkingDelay(value);
              }
            }}
            aria-label="Thinking delay"
          >
            {THINKING_OPTIONS.map((option) => (
              <ToggleButton key={option.value} value={option.value}>
                {option.label}
              </ToggleButton>
            ))}
          </ToggleButtonGroup>
        </Stack>
      </Stack>
      <Box sx={{ height: 420 }}>
        <ChatBox
          adapter={adapter}
          currentUser={users.me}
          members={[users.me, users.assistant]}
          initialConversations={[conversation]}
          activeConversationId={conversation.id}
          features={{ streamingIndicator: FEATURE_VALUE[mode] }}
          sx={{ height: '100%' }}
        />
      </Box>
    </Stack>
  );
}

활성화 및 비활성화

표시기는 기본값이 'auto'인 streamingIndicator 기능 플래그로 제어됩니다:

  • 'auto' (기본) — 어시스턴트가 지원하는(assistant-backed) 대화에서만 표시됩니다. 대화는 어시스턴트 멤버 또는 참가자가 구성된 경우(members 또는 대화의 participants에 role: 'assistant'가 있는 ChatUser), 또는 대화에 이미 어시스턴트 메시지가 포함된 경우 어시스턴트 지원으로 간주됩니다. 인간 간 대화에서는 절대 표시되지 않습니다.
  • true — 감지 여부와 무관하게 응답이 진행되는 동안 항상 표시됩니다.
  • false — 절대 표시되지 않습니다.
<ChatBox adapter={adapter} features={{ streamingIndicator: false }} />

:::info 'auto' 모드에서 어시스턴트 멤버나 참가자가 없는 완전히 새로운 대화의 첫 번째 전송은 대기 단계에서 아무것도 표시하지 않습니다 — 아직 어시스턴트 신호가 없기 때문입니다. start 청크가 어시스턴트 메시지를 만들자마자 표시기는 여전히 나타납니다. 첫 전송부터 표시하려면 어시스턴트 멤버/참가자를 구성하거나 streamingIndicator: true를 설정하세요. :::

커스터마이즈

streamingIndicator 슬롯을 사용해 렌더링되는 컴포넌트를 교체하거나, null을 전달해 다른 곳의 커스텀 교체를 위해 기능 시맨틱은 유지하면서 제거할 수 있습니다:

<ChatBox
  adapter={adapter}
  slots={{ streamingIndicator: MyIndicator }}
  slotProps={{ streamingIndicator: { className: 'my-indicator' } }}
/>

커스텀 슬롯 컴포넌트는 스트리밍 어시스턴트 버블 안에서 렌더링될 때 주변의 message를 받고, 끝 행으로 렌더링될 때 해석된 mode와 행 계약(messageId, index, items)을 받습니다. @mui/x-chat/headless의 useStreamingIndicatorVisibility() 훅으로 내장 게이팅을 재사용하세요:

import { useStreamingIndicatorVisibility } from '@mui/x-chat/headless';

function MyIndicator({ mode = 'auto', message }) {
  const { waiting } = useStreamingIndicatorVisibility(mode);
  const streaming = message?.role === 'assistant' && message?.status === 'streaming';
  if (!waiting && !streaming) {
    return null;
  }
  return <LinearProgress sx={{ maxWidth: 120 }} />;
}

:::info 점은 장식적입니다(aria-hidden): 메시지 목록의 상태 라이브 영역이 응답 시작과 완료를 이미 알리므로, 스크린 리더 사용자는 중복 안내 없이 동일한 신호를 받습니다. :::

스트리밍 표시기는 어시스턴트의 응답 생성 상태를 반영합니다. 인간 참가자가 메시지를 작성 중일 때 표시하는 것에 대해서는 Typing indicators를 참고하세요.

스트림 중지 및 취소

sendMessage 입력에는 사용자가 중지 버튼을 클릭할 때 발생하는 AbortSignal이 포함됩니다. 그것을 fetch 호출에 전달하면 런타임이 HTTP 요청을 자동으로 취소합니다:

async sendMessage({ message, signal }) {
  const res = await fetch('/api/chat', {
    method: 'POST',
    body: JSON.stringify({ message }),
    signal, // browser cancels the request when the user stops
  });
  return res.body!;
},

백엔드가 명시적 취소(예: 별도의 취소 요청 보내기)를 요구한다면, 신호와 함께 어댑터에 선택적 stop() 메서드를 구현하세요:

stop() {
  fetch('/api/chat/cancel', { method: 'POST' });
},

useChat() 훅을 사용해 프로그래밍 방식으로 스트리밍을 중지할 수도 있습니다:

const { stopStreaming } = useChat();

// Cancel the active stream
stopStreaming();

스트림에 다시 연결하기

어댑터의 reconnectToStream() 메서드를 구현해 중단된 스트림을 재개하세요 — 예: SSE 연결이 응답 중간에 끊긴 경우:

async reconnectToStream({ conversationId, messageId, signal }) {
  const res = await fetch('/api/chat/reconnect', {
    method: 'POST',
    body: JSON.stringify({ conversationId, messageId }),
    signal,
  });
  if (res.status === 404) return null; // message no longer resumable
  return res.body!;
},

중단된 메시지가 재개될 수 없으면 null을 반환하세요. 런타임은 연결 끊긴 스트림을 감지한 후 reconnectToStream()을 자동으로 호출합니다. 중단된 어시스턴트 messageId에 대해 한 번의 재연결 시도를 하며, null을 반환하면 메시지는 'error' 상태로 유지되고 런타임은 복구 가능한 스트림 오류와 함께 onError를 호출합니다.

오류와 연결 끊김 처리

종료 청크(finish 또는 abort) 없이 스트림이 닫히면 런타임은:

  1. 복구 가능한 스트림 오류를 기록합니다.
  2. 메시지 상태를 'error'로 설정합니다.
  3. isDisconnect: true로 onFinish를 호출합니다.
  4. reconnectToStream()이 구현되어 있으면 재개를 한 번 시도합니다.
  5. 연결 끊김이 복구되지 않은 경우에만 onError를 호출합니다.

어댑터의 sendMessage()가 예외를 던지면, 런타임은 전송 오류를 기록하고 오류 모델을 통해 표면화합니다. 자세한 내용은 Error handling을 참고하세요.

청크 유형 참조

런타임이 허용하는 모든 청크 유형의 전체 참조이며, 계열별로 그룹화했습니다. 필요한 표로 건너뛰세요: lifecycle, text, reasoning, tool, source, file and data, step boundaries, metadata.

수명주기 청크(Lifecycle chunks)

Chunk type Fields 설명
start messageId, author? 새 어시스턴트 메시지를 시작합니다. author는 어시스턴트 메시지 작성자를 설정합니다
finish messageId, finishReason? 어시스턴트 메시지를 완료합니다
abort messageId 어시스턴트 메시지를 취소합니다

선택적 finishReason은 어댑터 정의 문자열입니다(예: 'stop' 또는 'length'). 런타임은 이를 해석하거나 표시하지 않습니다 — 값을 있는 그대로 onFinish 콜백에 전달해 애플리케이션이 응답이 어떻게 끝났는지에 반응할 수 있게 합니다.

텍스트 청크

Chunk type Fields 설명
text-start id 새 텍스트 부분을 시작합니다
text-delta id, delta 텍스트 콘텐츠를 추가합니다
text-end id 텍스트 부분을 마무리합니다

텍스트 청크는 메시지에 ChatTextMessagePart를 만듭니다. 여러 text-delta 청크는 저장소에 적용되기 전에 streamFlushInterval에 따라 일괄 처리됩니다.

추론 청크(Reasoning chunks)

Chunk type Fields 설명
reasoning-start id 추론 부분을 시작합니다
reasoning-delta id, delta 추론 콘텐츠를 추가합니다
reasoning-end id 추론 부분을 마무리합니다

추론 청크는 chain-of-thought 또는 생각 추적 표시에 유용한 ChatReasoningMessagePart를 만듭니다.

도구 청크(Tool chunks)

Chunk type Fields 설명
tool-input-start toolCallId, toolName, dynamic? 도구 호출을 시작합니다
tool-input-delta toolCallId, inputTextDelta 도구 입력 JSON을 스트리밍합니다
tool-input-available toolCallId, toolName, input, dynamic? 도구 입력이 완전히 사용 가능합니다
tool-input-error toolCallId, errorText 도구 입력 파싱 실패
tool-approval-request toolCallId, toolName, input, approvalId?, dynamic? 사용자 승인을 요청합니다
tool-output-available toolCallId, output, preliminary? 도구 출력이 사용 가능합니다
tool-output-error toolCallId, errorText 도구 실행 실패
tool-output-denied toolCallId, reason? 사용자가 도구 호출을 거부했습니다

toolInvocation.state는 도구 수명주기를 추적합니다: 'input-streaming' → 'input-available' → 'approval-requested' → 'output-available'(또는 'output-error' / 'output-denied').

소스, 파일, 데이터 청크(Source, file, and data chunks)

Chunk type Fields 설명
source-url sourceId, url, title? URL 기반 소스
source-document sourceId, title?, text? 문서 기반 소스
file mediaType, url, filename?, id? 인라인 파일
data-* type, data, id?, transient? 커스텀 데이터 페이로드

데이터 청크는 data-* 패턴과 일치하는 유형을 사용합니다(예: data-citations 또는 data-summary). 이는 ChatDataMessagePart 항목을 만들고 onData 콜백도 발생시킵니다. transient가 true이면 부분은 메시지에 유지되지 않습니다.

단계 경계 청크(Step boundary chunks)

Chunk type 설명
start-step 새 처리 단계를 시작합니다
finish-step 현재 단계를 종료합니다

단계 청크는 UI에서 다단계 에이전트 처리를 보여주는 데 유용한 ChatStepStartMessagePart 항목을 만듭니다.

메타데이터 청크(Metadata chunks)

Chunk type Fields 설명
message-metadata metadata 부분 메타데이터를 어시스턴트 메시지에 병합합니다

메타데이터 청크는 메시지 부분을 만들지 않습니다 — 부분 metadata 객체가 ChatMessage.metadata에 얕게 병합됩니다. ChatMessageMetadata 레지스트리 인터페이스를 확장해 페이로드에 타입을 지정하세요(Type augmentation 참고).

청크를 메시지 부분으로 매핑하기

스트림 프로세서는 청크를 ChatMessagePart 항목으로 매핑합니다:

  1. text-start는 state: 'streaming'인 새 ChatTextMessagePart를 만듭니다.
  2. text-delta는 기존 텍스트 부분에 추가합니다.
  3. text-end는 state: 'done'을 설정합니다.
  4. 도구 청크는 각 단계를 통해 toolInvocation.state를 업데이트합니다. 입력이 스트리밍되는 동안 tool-input-delta는 호출을 'input-streaming'으로 유지합니다 — 런타임은 델타에서 부분 input을 조립하지 않으며, 완전하고 파싱된 input은 tool-input-available과 함께 도착합니다.
  5. 소스, 파일, 데이터 청크는 각각 해당 부분 유형을 즉시 만듭니다.
  6. start-step은 ChatStepStartMessagePart 구분자를 만듭니다.
  7. message-metadata는 부분을 만들지 않고 메시지의 metadata 필드에 병합합니다.

메시지의 status 필드도 스트림을 통해 업데이트됩니다:

  • 'sending' — 사용자 메시지가 낙관적으로 추가될 때 설정
  • 'streaming' — start가 도착할 때 설정
  • 'sent' — finish가 도착할 때 설정
  • 'cancelled' — abort가 도착할 때 설정
  • 'error' — 스트림이 실패할 때 설정

더 보기

  • Building an adapter — 이 스트림을 생성하는 단계별 가이드
  • Adapter — 스트림을 생성하는 인터페이스에 대한 자세한 내용
  • Error handling — 오류 모델과 복구에 대한 자세한 내용
  • Scrolling — 자동 스크롤이 스트리밍 콘텐츠를 따르는 방법에 대한 자세한 내용

ChatBox API

데모

이 React 컴포넌트 사용에 대한 예시와 자세한 내용은 컴포넌트 데모 페이지를 방문하세요:

가져오기(Import)

import { ChatBox } from '@mui/x-chat/ChatBox';
// or
import { ChatBox } from '@mui/x-chat';

Props

Name Type Default Required Description
classes object - No Override or extend the styles applied to the component.
currentUser { avatarUrl?: string, displayName?: string, id: string, isOnline?: bool, metadata?: object, role?: 'assistant' | 'system' | 'user' } - No
density 'comfortable' | 'compact' | 'standard' 'standard' No
features { attachments?: { acceptedMimeTypes?: Array<string>, maxFileCount?: number, maxFileSize?: number, onAttachmentReject?: func } | bool, autoScroll?: { buffer?: number } | bool, conversationHeader?: bool, conversationList?: bool, dateDivider?: bool, helperText?: bool, scrollToBottom?: bool, streamingIndicator?: 'auto' | bool, suggestions?: bool, typingSignal?: bool, unreadMarker?: bool } - No
getMessageAuthorAvatarUrl func (message) => message.author?.avatarUrl No
getMessageAuthorDisplayName func (message) => message.author?.displayName No
getMessageAuthorId func (message) => message.author?.id No
initialActiveConversationId string - No
initialComposerValue string - No
initialConversations Array<{ avatarUrl?: string, id: string, lastMessageAt?: string, metadata?: object, participants?: Array<{ avatarUrl?: string, displayName?: string, id: string, isOnline?: bool, metadata?: object, role?: 'assistant' | 'system' | 'user' }>, readState?: 'read' | 'unread', subtitle?: string, title?: string, unreadCount?: number }> - No
initialMessages Array<{ author?: { avatarUrl?: string, displayName?: string, id: string, isOnline?: bool, metadata?: object, role?: 'assistant' | 'system' | 'user' }, conversationId?: string, createdAt?: string, editedAt?: string, id: string, metadata?: object, parts: Array<{ data: any, id?: string, transient?: bool, type: object } | { filename?: string, mediaType: string, type: 'file', url: string } | { sourceId: string, text?: string, title?: string, type: 'source-document' } | { sourceId: string, title?: string, type: 'source-url', url: string } | { state?: 'done' | 'streaming', text: string, type: 'reasoning' } | { state?: 'done' | 'streaming', text: string, type: 'text' } | { toolInvocation: { approval?: object, approvalId?: string, callProviderMetadata?: object, errorText?: string, input?: any, output?: any, preliminary?: bool, providerExecuted?: bool, state: 'approval-requested' | 'approval-responded' | 'input-available' | 'input-streaming' | 'output-available' | 'output-denied' | 'output-error', title?: string, toolCallId: string, toolName: string }, type: 'dynamic-tool' } | { toolInvocation: { approval?: object, approvalId?: string, callProviderMetadata?: object, errorText?: string, input?: any, output?: any, preliminary?: bool, providerExecuted?: bool, state: 'approval-requested' | 'approval-responded' | 'input-available' | 'input-streaming' | 'output-available' | 'output-denied' | 'output-error', title?: string, toolCallId: string, toolName: string }, type: 'tool' } | { type: 'step-start' }>, role: 'assistant' | 'system' | 'user', status?: 'cancelled' | 'error' | 'pending' | 'read' | 'sending' | 'sent' | 'streaming', updatedAt?: string }> - No
layoutMode 'overlay' | 'split' | 'standard' - No
layoutModeBreakpoints { overlay?: number, split?: number } - No
members Array<{ avatarUrl?: string, displayName?: string, id: string, isOnline?: bool, metadata?: object, role?: 'assistant' | 'system' | 'user' }> - No
roleDisplayNames { assistant?: string, system?: string, user?: string } - No
slotProps object - No
slots object - No
storeClass func ChatStore No
streamFlushInterval number 16 No
suggestions Array<{ label?: string, value: string } | string> - No
suggestionsAutoSubmit bool false No
variant 'compact' | 'default' 'default' No

Note: ref는 루트 요소로 전달됩니다.

제공된 다른 모든 props는 루트 요소(네이티브 요소)에 제공됩니다.

Slots

Name Default Class Description
root undefined .MuiChatBox-root The outermost ChatBox container element.
layout undefined .MuiChatBox-layout Wrapper that arranges the conversations pane and the thread pane.
conversationsPane undefined .MuiChatBox-conversationsPane Container for the conversation-list sidebar (or drawer on narrow widths).
threadPane undefined .MuiChatBox-threadPane Container for the active thread — the message list plus the composer.
conversationRoot undefined - Styled root of `` (wrapper-only); the default header, message list and composer continue to render inside it.
conversationList undefined - The conversation-list sidebar component.
conversationHeader undefined - The header bar rendered above the message list.
conversationHeaderInfo undefined - The title + subtitle group inside the header.
conversationTitle undefined - The conversation title element.
conversationSubtitle undefined - The conversation subtitle element (participants, status, etc.).
conversationHeaderActions undefined - The actions area on the trailing side of the header.
messageList undefined - Styled scrollable root element of `` (wrapper-only). The default message rows render inside it, so a plain element such as 'section' wraps the list rather than replacing it.
messageGroup undefined - The per-author group wrapper around consecutive messages.
dateDivider undefined - The date separator rendered between message groups. Only rendered when features.dateDivider is enabled. Pass null to hide it.
unreadMarker undefined - The "new messages" marker. Only rendered when features.unreadMarker is enabled. Pass null to hide it.
streamingIndicator undefined - The animated dots shown while an assistant response is in flight: as a trailing row while waiting for the response to start, then inside the assistant bubble while it streams. Controlled by features.streamingIndicator ('auto' by default). Pass null to hide it.
messageRoot undefined - Styled root of `` (wrapper-only); the default avatar/content/meta tree still renders inside it.
messageAvatar undefined - Avatar component. Pass null to hide the avatar entirely and drop the reserved avatar grid track.
messageContent undefined - The message bubble component.
messageMeta undefined - External meta (compact variant). Pass null to hide.
messageInlineMeta undefined - Inline meta rendered inside the bubble (default variant). Pass null to hide.
messageError undefined - Error card shown under the bubble when the message status is error. Pass null to hide the error surface entirely (no component is mounted).
messageActions undefined - Actions row component (receives { messageId }). Pass null to hide actions entirely; omit to render only the declarative extraActions from slotProps.messageActions if provided.
messageAuthorName undefined - Author name label rendered by the group wrapper (default variant: above the bubble; compact variant: inside the message grid). Pass null to hide.
composerRoot undefined - Styled root of `` (wrapper-only); the default attach/input/send/toolbar render inside it.
composerInput undefined - The auto-resizing text input.
composerSendButton undefined - Send button. Pass null to hide it; the form still submits on Enter.
composerAttachButton undefined - Attach button. Pass null to hide just the button while keeping the rest of the attachment pipeline (drag/drop, paste). Use features.attachments: false to disable attachments entirely.
composerAttachmentList undefined - The pending-attachment preview list.
composerToolbar undefined - The composer toolbar (button row).
composerHelperText undefined - The helper / disclaimer text below the input.
typingIndicator undefined - The animated typing indicator shown while the assistant responds.
scrollToBottom undefined - The floating scroll-to-bottom button.
suggestions undefined - The prompt-suggestion chips.
emptyState undefined - Custom content rendered when the thread has no messages.

소스 코드

이 페이지에서 원하는 정보를 찾지 못했다면, 컴포넌트의 구현을 살펴보는 것도 좋습니다.

ChatStreamingIndicator API

데모

이 React 컴포넌트 사용에 대한 예시와 자세한 내용은 컴포넌트 데모 페이지를 방문하세요:

가져오기(Import)

import { ChatStreamingIndicator } from '@mui/x-chat/ChatIndicators';
// or
import { ChatStreamingIndicator } from '@mui/x-chat';

Props

Name Type Default Required Description
message { author?: { avatarUrl?: string, displayName?: string, id: string, isOnline?: bool, metadata?: object, role?: 'assistant' | 'system' | 'user' }, conversationId?: string, createdAt?: string, editedAt?: string, id: string, metadata?: object, parts: Array<{ data: any, id?: string, transient?: bool, type: object } | { filename?: string, mediaType: string, type: 'file', url: string } | { sourceId: string, text?: string, title?: string, type: 'source-document' } | { sourceId: string, title?: string, type: 'source-url', url: string } | { state?: 'done' | 'streaming', text: string, type: 'reasoning' } | { state?: 'done' | 'streaming', text: string, type: 'text' } | { toolInvocation: { approval?: object, approvalId?: string, callProviderMetadata?: object, errorText?: string, input?: any, output?: any, preliminary?: bool, providerExecuted?: bool, state: 'approval-requested' | 'approval-responded' | 'input-available' | 'input-streaming' | 'output-available' | 'output-denied' | 'output-error', title?: string, toolCallId: string, toolName: string }, type: 'dynamic-tool' } | { toolInvocation: { approval?: object, approvalId?: string, callProviderMetadata?: object, errorText?: string, input?: any, output?: any, preliminary?: bool, providerExecuted?: bool, state: 'approval-requested' | 'approval-responded' | 'input-available' | 'input-streaming' | 'output-available' | 'output-denied' | 'output-error', title?: string, toolCallId: string, toolName: string }, type: 'tool' } | { type: 'step-start' }>, role: 'assistant' | 'system' | 'user', status?: 'cancelled' | 'error' | 'pending' | 'read' | 'sending' | 'sent' | 'streaming', updatedAt?: string } - No
messageId string - No
mode 'auto' | bool 'auto' No

Note: ref는 루트 요소로 전달됩니다.

제공된 다른 모든 props는 루트 요소(네이티브 요소)에 제공됩니다.

CSS

규칙 이름

Global class Rule name Description
- bubble Styles applied to the waiting-phase typing bubble.
- root Styles applied to the root element (the dots).
- row Styles applied to the waiting-phase assistant row wrapper.

소스 코드

이 페이지에서 원하는 정보를 찾지 못했다면, 컴포넌트의 구현을 살펴보는 것도 좋습니다.

더 알아보기

출처: MUI X documentation