Chat - 어댑터 만들기
ChatAdapter를 단계별로 구현해서 어떤 백엔드든 Chat 런타임에 연결해 봐요.
최소 동작 어댑터(sendMessage만)로 시작해서, 점진적으로 히스토리 로딩과 대화 관리를 추가하며 ChatAdapter를 처음부터 만들어 봐요.
이 페이지는 실습 튜토리얼이에요—완전한 인터페이스 참조는 어댑터를 참고하세요.
본문
1단계: 최소 어댑터 만들기
유일하게 필수인 메서드는 sendMessage예요.
이 메서드는 사용자 메시지를 받아서 타입이 지정된 청크(chunk)의 ReadableStream을 반환해야 해요.
message 인자는 ChatMessage예요—그 내용은 일반 문자열이 아니라 parts 배열(텍스트, 파일, 기타 파트 타입들)에 들어 있어요. 전체 구조는 메시지를 참고하세요.
import { ChatBox } from '@mui/x-chat';
import type { ChatAdapter } from '@mui/x-chat/headless';
const adapter: ChatAdapter = {
async sendMessage({ message, signal }) {
const res = await fetch('/api/chat', {
method: 'POST',
body: JSON.stringify({ message }),
signal,
});
return res.body!; // ReadableStream<ChatMessageChunk>
},
};
export default function App() {
return <ChatBox adapter={adapter} sx={{ height: 500 }} />;
}
런타임이 스트리밍, 메시지 정규화, 오류 표시, 상태 업데이트를 처리해요. 어댑터는 백엔드와 어떻게 대화할지만 알면 돼요.
2단계: 스트리밍을 처음부터 구현하기
백엔드가 네이티브 ReadableStream을 반환하지 않는다면(예: WebSocket이나 커스텀 프로토콜 사용), 스트림을 직접 구성할 수 있어요.
스트림은 start 청크로 시작해서 finish 또는 abort로 끝나야 해요.
텍스트는 text-start / text-delta / text-end 세 쌍으로 도착해요.
이것들은 텍스트 청크일 뿐이에요. (reasoning, tools, sources, files 등을 포함한) 전체 청크 타입 목록은 청크 타입 참조를 참고하세요.
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();
},
});
},
};
messageId는 스트리밍 중인 어시스턴트 메시지를 식별하며 메시지마다 고유해야 해요—다음 예시는 요청마다 하나씩 생성해요.
실제 통합에서는 start 콜백 안에서 백엔드로부터 읽고 청크가 도착할 때마다 enqueue하세요—여기서 어댑터는 post하기 전에 메시지의 첫 parts 항목에서 일반 텍스트를 추출해요.
const adapter: ChatAdapter = {
async sendMessage({ message, signal }) {
return new ReadableStream({
async start(controller) {
const response = await fetch('/api/chat', {
method: 'POST',
body: JSON.stringify({
text: message.parts[0]?.type === 'text' ? message.parts[0].text : '',
}),
signal,
});
const reader = response.body!.getReader();
const decoder = new TextDecoder();
const messageId = `msg-${Date.now()}`;
controller.enqueue({ type: 'start', messageId });
controller.enqueue({ type: 'text-start', id: 'text-1' });
try {
while (true) {
const { done, value } = await reader.read();
if (done) break;
const text = decoder.decode(value, { stream: true });
controller.enqueue({ type: 'text-delta', id: 'text-1', delta: text });
}
controller.enqueue({ type: 'text-end', id: 'text-1' });
controller.enqueue({ type: 'finish', messageId });
} catch (error) {
controller.enqueue({ type: 'text-end', id: 'text-1' });
controller.enqueue({ type: 'abort', messageId });
} finally {
controller.close();
}
},
});
},
};
3단계: 중단 신호 연결하기
signal 인자는 스트리밍이 취소될 때 발생하는 AbortSignal이에요—예를 들어 useChat()의 헤드리스 stopStreaming() 액션이 호출될 때 그렇죠. (ChatBox는 기본적으로 중지 버튼을 렌더링하지 않아요. 스트리밍 중에는 전송 버튼이 비활성화돼요.)
이것을 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!;
},
백엔드가 명시적 취소를 요구한다면(예: 별도의 취소 요청 전송), signal과 함께 선택적 stop() 메서드를 구현하세요.
stop() {
fetch('/api/chat/cancel', { method: 'POST' });
},
stop()은 인자를 받지 않고 아무것도 반환하지 않아요. 런타임은 signal을 중단하는 것에 더해 이것을 호출해요—대신이 아니라요—그러니 계속 signal을 요청에 전달해야 해요.
다음 데모는 2단계와 3단계를 결합해요. 미리 준비된 답변을 청크 단위로 스트리밍하는 수제(hand-rolled) 어댑터예요. ChatBox는 자체 중지 버튼을 렌더링하지 않으므로, 데모는 헤드리스 stopStreaming() 액션으로 버튼 하나를 추가해요—스트리밍 중간에 누르면 중단 신호가 발생해요.
'use client';
import * as React from 'react';
import { ChatBox } from '@mui/x-chat';
import { useChat } from '@mui/x-chat/headless';
import type { ChatAdapter, ChatMessageChunk } from '@mui/x-chat/headless';
import Button from '@mui/material/Button';
const CONVERSATION_ID = 'build-adapter-demo';
const initialConversations = [{ id: CONVERSATION_ID, title: 'Hand-rolled adapter' }];
const initialMessages = [
{
id: 'welcome',
conversationId: CONVERSATION_ID,
role: 'assistant' as const,
status: 'sent' as const,
parts: [
{
type: 'text' as const,
text: 'Send a message to watch a hand-built ReadableStream stream the reply. Press Stop mid-stream to see the abort signal in action.',
},
],
},
];
const REPLY =
'Here is a reply streamed one word at a time by a hand-rolled adapter. ' +
'Each word arrives as its own text-delta chunk. ' +
'Press Stop at any point to fire the abort signal and halt the stream.';
const adapter: ChatAdapter = {
async sendMessage({ signal }) {
const messageId = `assistant-${Date.now()}`;
const textId = `${messageId}-text`;
const words = REPLY.split(' ');
return new ReadableStream<ChatMessageChunk>({
start(controller) {
controller.enqueue({ type: 'start', messageId });
controller.enqueue({ type: 'text-start', id: textId });
let index = 0;
let closed = false;
const interval = setInterval(() => {
if (closed) {
return;
}
if (index < words.length) {
const delta = index === 0 ? words[index] : ` ${words[index]}`;
controller.enqueue({ type: 'text-delta', id: textId, delta });
index += 1;
return;
}
clearInterval(interval);
closed = true;
controller.enqueue({ type: 'text-end', id: textId });
controller.enqueue({ type: 'finish', messageId });
controller.close();
}, 40);
signal.addEventListener('abort', () => {
if (closed) {
return;
}
clearInterval(interval);
closed = true;
controller.enqueue({ type: 'text-end', id: textId });
controller.enqueue({ type: 'abort', messageId });
controller.close();
});
},
});
},
};
function StopStreamingButton() {
const { isStreaming, stopStreaming } = useChat();
return (
<Button
size="small"
variant="outlined"
disabled={!isStreaming}
onClick={() => stopStreaming()}
sx={{ position: 'absolute', top: 8, right: 8, zIndex: 1 }}
>
Stop
</Button>
);
}
export default function ManualStreamAdapterDemo() {
return (
<ChatBox
adapter={adapter}
initialActiveConversationId={CONVERSATION_ID}
initialConversations={initialConversations}
initialMessages={initialMessages}
sx={{
position: 'relative',
height: 500,
border: '1px solid',
borderColor: 'divider',
borderRadius: 1,
}}
>
<StopStreamingButton />
</ChatBox>
);
}
4단계: 메시지 히스토리 추가하기
사용자가 대화를 열 때 히스토리를 로드하려면 listMessages를 구현하세요.
런타임은 활성 대화가 아직 스토어에 메시지가 없는 대화로 바뀔 때마다 이것을 호출해요.
const adapter: ChatAdapter = {
async sendMessage(input) {
/* ... from Step 1 ... */
},
async listMessages({ conversationId, cursor }) {
const params = new URLSearchParams({ cursor: cursor ?? '' });
const res = await fetch(
`/api/conversations/${conversationId}/messages?${params}`,
);
const { messages, nextCursor, hasMore } = await res.json();
return { messages, cursor: nextCursor, hasMore };
},
};
hasMore가 true이면, ChatBox는 사용자가 목록 맨 위로 스크롤할 때 이전 메시지를 자동으로 로드하면서 이전 커서로 listMessages를 다시 호출해요. 히스토리와 페이지네이션을 참고하세요.
5단계: 대화 목록 가져오기
ChatBox가 마운트될 때 대화 상태를 로드하려면 listConversations를 구현하세요.
features={{ conversationList: true }}가 활성화되면, 같은 데이터가 내장 대화 사이드바에도 힘을 실어요.
런타임은 사용자 상호작용 전에 시작 시 한 번 호출해요.
const adapter: ChatAdapter = {
async sendMessage(input) {
/* ... from Step 1 ... */
},
async listMessages(input) {
/* ... from Step 4 ... */
},
async listConversations() {
const res = await fetch('/api/conversations');
const { conversations } = await res.json();
return { conversations };
},
};
페이지네이션된 대화 목록을 위해 cursor와 hasMore을 반환하세요.
async listConversations({ cursor }) {
const params = new URLSearchParams();
if (cursor) params.set('cursor', cursor);
const res = await fetch(`/api/conversations?${params}`);
const { conversations, nextCursor, hasMore } = await res.json();
return { conversations, cursor: nextCursor, hasMore };
},
6단계: 스트림 재연결 처리하기
중단된 스트림을 재개하려면 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을 반환하세요.
완전한 어댑터
다음 어댑터는 모든 단계를 결합해요.
import type { ChatAdapter } from '@mui/x-chat/headless';
const adapter: ChatAdapter = {
async sendMessage({ message, signal }) {
const res = await fetch('/api/chat', {
method: 'POST',
body: JSON.stringify({ message }),
signal,
});
return res.body!;
},
stop() {
fetch('/api/chat/cancel', { method: 'POST' });
},
async listMessages({ conversationId, cursor }) {
const params = new URLSearchParams({ cursor: cursor ?? '' });
const res = await fetch(
`/api/conversations/${conversationId}/messages?${params}`,
);
const { messages, nextCursor, hasMore } = await res.json();
return { messages, cursor: nextCursor, hasMore };
},
async listConversations() {
const res = await fetch('/api/conversations');
const { conversations } = await res.json();
return { conversations };
},
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;
return res.body!;
},
};
오류 처리 (Error handling)
:::info 어댑터 메서드 안에서 오류를 잡을 필요는 없어요—런타임이 대신 처리해 줘요. :::
어댑터 메서드가 throw하면 런타임은 ChatError를 기록하고, 내장 오류 UI와 onError 콜백을 통해 그것을 표시하며, 해당할 때 오류를 recoverable 또는 retryable로 표시해요.
retryable로 표시된 오류는 내장 오류 UI에서 재시도 동작을 노출해요. 전체 오류 모델과 커스터마이징 옵션은 오류 처리를 참고하세요.
애플리케이션 레벨에서 오류를 처리하려면:
<ChatBox
adapter={adapter}
onError={(error) => {
console.error('[Chat error]', error.source, error.message);
}}
/>
함께 보기 (See also)
- 전체
ChatAdapter인터페이스 참조와 페이지네이션 커서 타이핑은 어댑터를 참고하세요. - 스트림 수명주기, 엔벨로프, 청크 타입 참조는 스트리밍을 참고하세요.
subscribe(),setTyping(),markRead()로 푸시 기반 업데이트를 하려면 실시간 어댑터를 참고하세요.ChatError모델과 오류 UI는 오류 처리를 참고하세요.
API
ChatBox API
데모
이 React 컴포넌트의 사용 예시와 자세한 내용은 컴포넌트 데모 페이지에서 확인하세요.
- Chat - Building an adapter
- Chat - Controlled state
- Chat - ChatBox
- Chat - Variants and density
- Chat - Error handling
- Chat - Streaming
- Chat - Look and feel
- Chat - Customization overview
- Chat - Structure
- Chat - Customization
- Chat - Slot overrides
- Chat - Real-time sync
- MUI X Chat
- Chat - Quickstart
- Chat - Events and callbacks
- Chat - Performance
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. |
소스 코드
이 페이지에서 원하는 정보를 찾지 못했다면, 컴포넌트 구현을 살펴보는 것도 좋아요.
더 알아보기
더 자세한 내용은 MUI X Chat 문서를 참고하세요.