Chat - 추론(Reasoning)
LLM의 chain-of-thought 추론 흔적(trace)을 스트리밍 채팅 응답과 함께 표시할 수 있어요.
본문
많은 대규모 언어 모델은 최종 응답과 함께 "thinking"이나 "reasoning" 흔적을 노출해요. Chat 컴포넌트는 전용 청크 타입과 전용 메시지 파트를 통해 이 추론 콘텐츠를 스트리밍하고 표시할 수 있어요. Reasoning 파트는 접을 수 있는 "Thinking…" 섹션으로 자동 렌더링되며, 별도 설정이 필요 없어요.
기본 렌더링
Reasoning 파트는 자동으로 렌더링돼요. 표시하기 위해 렌더러를 등록할 필요가 없어요.
내장 렌더러는 네이티브 <details>/<summary> 디스클로저(disclosure)로, state가 'streaming'인 동안은 열린 상태로 유지되고("Thinking…" 라벨 표시), 추론이 'done'이 되면 클릭 가능한 "Reasoning" 요약으로 접혀요.
'use client';
import { ChatBox } from '@mui/x-chat';
import type { ChatAdapter } from '@mui/x-chat/headless';
import { createChunkStream } from 'docs/data/chat/core/examples/shared/demoUtils';
const CONVERSATION_ID = 'reasoning-demo';
const initialConversations = [{ id: CONVERSATION_ID, title: 'Reasoning' }];
const initialMessages = [
{
id: 'seed',
conversationId: CONVERSATION_ID,
role: 'assistant' as const,
status: 'sent' as const,
parts: [
{
type: 'reasoning' as const,
text: 'The user greeted me. A short, friendly reply is enough — no tools needed.',
state: 'done' as const,
},
{
type: 'text' as const,
text: 'Hi! Send a message and watch the reasoning stream in above this reply.',
},
],
},
];
const adapter: ChatAdapter = {
async sendMessage({ message }) {
const messageId = `reply-${message.id}`;
// Emit one chunk at a time, with a small delay, so the disclosure visibly streams.
return createChunkStream(
[
{ type: 'start', messageId },
// Reasoning section — auto-expanded and labelled "Thinking…" while streaming.
{ type: 'reasoning-start', id: 'r1' },
{
type: 'reasoning-delta',
id: 'r1',
delta: 'Let me think about how to answer this. ',
},
{
type: 'reasoning-delta',
id: 'r1',
delta: 'The question is straightforward, ',
},
{
type: 'reasoning-delta',
id: 'r1',
delta: 'so a concise reply works best.',
},
{ type: 'reasoning-end', id: 'r1' },
// Final answer — the reasoning collapses to a "Reasoning" summary as this streams.
{ type: 'text-start', id: 't1' },
{ type: 'text-delta', id: 't1', delta: 'Here is the answer, now that ' },
{ type: 'text-delta', id: 't1', delta: 'the reasoning above has finished.' },
{ type: 'text-end', id: 't1' },
{ type: 'finish', messageId },
],
{ delayMs: 100 },
);
},
};
export default function ReasoningStreamingDemo() {
return (
<ChatBox
adapter={adapter}
initialActiveConversationId={CONVERSATION_ID}
initialConversations={initialConversations}
initialMessages={initialMessages}
sx={{
height: 500,
border: '1px solid',
borderColor: 'divider',
borderRadius: 1,
}}
/>
);
}
라벨
요약 텍스트는 두 개의 localeText 키에서 옵니다: messageReasoningStreamingLabel(스트리밍 중 표시되는 'Thinking…')과 messageReasoningLabel(완료되면 표시되는 'Reasoning').
localeText prop으로 로컬라이즈하거나 덮어쓸 수 있어요.
Material 계층은 디스클로저의 세 슬롯 — root, summary, content — 을 스타일링하며, 요약 아이콘은 MuiChatMessage-ReasoningIcon 클래스를 갖습니다.
Reasoning 파트 구조
스트리밍 중 추론 청크가 도착하면 런타임이 어시스턴트 메시지에 ChatReasoningMessagePart를 생성해요:
interface ChatReasoningMessagePart {
type: 'reasoning';
text: string;
state?: ChatMessagePartStatus; // 'streaming' | 'done'
}
| 필드 | 타입 | 설명 |
|---|---|---|
type |
'reasoning' |
이것을 reasoning 파트로 식별 |
text |
string |
누적된 reasoning 텍스트 |
state |
'streaming' | 'done' |
reasoning이 아직 스트리밍 중인지 여부 |
state 필드는 델타가 도착하는 동안 'streaming'에서, reasoning 섹션이 완료되면 'done'으로 전환돼요.
내장 렌더러는 이 값을 사용해서 델타가 도착하는 동안 디스클로저를 펼쳐진 상태로 유지하고 실시간 "Thinking…" 라벨을 보여줍니다. 커스텀 UI에서도 state(또는 슬롯의 streaming ownerState 플래그)를 같은 방식으로 사용하세요.
Reasoning 슬롯 커스터마이징
내장 렌더러는 응답 텍스트 위에 접을 수 있는 섹션으로 reasoning을 이미 표시해요.
모양을 바꾸려면 디스클로저를 다시 구현하는 대신 reasoning 슬롯 — root, summary, content — 을 덮어쓰세요.
Material ChatBox에서는 slotProps.messageContent로 슬롯을 지정할 수 있어요:
slotProps={{
messageContent: {
partProps: { reasoning: { slots: { summary: MySummary } } },
},
}}
조합 가능한 레이아웃에서는 ChatMessage.Content(또는 ChatMessageContent)에 partProps를 직접 전달하세요.
슬롯 컴포넌트는 ownerState: ReasoningPartOwnerState({ messageId, role, streaming })를 받아요. 모델이 생각하는 동안 펄스나 실시간 효과를 위해 ownerState.streaming을 읽으세요.
타입은 @mui/x-chat/headless에서 가져옵니다:
import type { ReasoningPartOwnerState } from '@mui/x-chat/headless';
슬롯 맵이 병합되므로 부분 덮어쓰기는 나머지 Material 기본값을 유지해요: summary만 덮어써도 기본 root와 content를 계속 사용합니다.
'use client';
import * as React from 'react';
import { ChatBox } from '@mui/x-chat';
import type { ChatAdapter, ReasoningPartOwnerState } from '@mui/x-chat/headless';
import AutoAwesomeOutlinedIcon from '@mui/icons-material/AutoAwesomeOutlined';
import { createChunkStream } from 'docs/data/chat/core/examples/shared/demoUtils';
const CONVERSATION_ID = 'reasoning-slots-demo';
const initialConversations = [{ id: CONVERSATION_ID, title: 'Reasoning slots' }];
const initialMessages = [
{
id: 'seed',
conversationId: CONVERSATION_ID,
role: 'assistant' as const,
status: 'sent' as const,
parts: [
{
type: 'reasoning' as const,
text: 'The user greeted me. A short, friendly reply is enough — no tools needed.',
state: 'done' as const,
},
{
type: 'text' as const,
text: 'Hi! Send a message to see the restyled reasoning disclosure stream.',
},
],
},
];
const adapter: ChatAdapter = {
async sendMessage({ message }) {
const messageId = `reply-${message.id}`;
// Emit one chunk at a time, with a small delay, so the disclosure visibly streams.
return createChunkStream(
[
{ type: 'start', messageId },
{ type: 'reasoning-start', id: 'r1' },
{
type: 'reasoning-delta',
id: 'r1',
delta: 'Let me think about how to answer this. ',
},
{
type: 'reasoning-delta',
id: 'r1',
delta: 'The question is straightforward, ',
},
{
type: 'reasoning-delta',
id: 'r1',
delta: 'so a concise reply works best.',
},
{ type: 'reasoning-end', id: 'r1' },
{ type: 'text-start', id: 't1' },
{ type: 'text-delta', id: 't1', delta: 'Here is the answer, now that ' },
{ type: 'text-delta', id: 't1', delta: 'the reasoning above has finished.' },
{ type: 'text-end', id: 't1' },
{ type: 'finish', messageId },
],
{ delayMs: 100 },
);
},
};
// Custom `root` slot — a tinted disclosure container.
const CustomRoot = React.forwardRef(function CustomRoot(
props: React.HTMLAttributes<HTMLDetailsElement> & {
ownerState?: ReasoningPartOwnerState;
},
ref: React.Ref<HTMLDetailsElement>,
) {
const { ownerState, style, ...other } = props;
return (
<details
ref={ref}
style={{
margin: '6px 0',
padding: '6px 10px',
borderRadius: 8,
background: 'rgba(99, 102, 241, 0.08)',
...style,
}}
{...other}
/>
);
});
// Custom `summary` slot — uses `ownerState.streaming` for a live affordance.
const CustomSummary = React.forwardRef(function CustomSummary(
props: React.HTMLAttributes<HTMLElement> & {
ownerState?: ReasoningPartOwnerState;
},
ref: React.Ref<HTMLElement>,
) {
const { ownerState, children, style, ...other } = props;
const streaming = ownerState?.streaming;
return (
<summary
ref={ref}
style={{
cursor: 'pointer',
display: 'flex',
alignItems: 'center',
gap: 6,
listStyle: 'none',
fontSize: 13,
fontWeight: 500,
color: '#6366f1',
...style,
}}
{...other}
>
<AutoAwesomeOutlinedIcon style={{ fontSize: 14 }} />
{children}
{streaming ? (
<span
aria-hidden
style={{
width: 6,
height: 6,
borderRadius: '50%',
background: '#6366f1',
animation: 'reasoning-pulse 1s ease-in-out infinite',
}}
/>
) : null}
<style>
{
'@keyframes reasoning-pulse { 0%, 100% { opacity: 0.3; } 50% { opacity: 1; } }'
}
</style>
</summary>
);
});
export default function ReasoningSlotsDemo() {
return (
<ChatBox
adapter={adapter}
initialActiveConversationId={CONVERSATION_ID}
initialConversations={initialConversations}
initialMessages={initialMessages}
slotProps={{
messageContent: {
partProps: {
reasoning: {
slots: { root: CustomRoot, summary: CustomSummary },
},
},
},
}}
sx={{
height: 500,
border: '1px solid',
borderColor: 'divider',
borderRadius: 1,
}}
/>
);
}
전체 partProps 구조는 ChatMessageContent API를 참고하세요.
렌더러 교체하기
내장 디스클로저를 다시 스타일링하는 대신 렌더링을 완전히 교체하려면 partRenderers.reasoning 렌더러를 등록하세요.
partRenderers는 <ChatBox />가 직접 받으므로 Material 사용자는 ChatProvider가 필요 없어요:
import { ChatProvider, type ChatPartRendererMap } from '@mui/x-chat-headless';
import Accordion from '@mui/material/Accordion';
import AccordionSummary from '@mui/material/AccordionSummary';
import AccordionDetails from '@mui/material/AccordionDetails';
import ExpandMoreIcon from '@mui/icons-material/ExpandMore';
import Typography from '@mui/material/Typography';
const renderers: ChatPartRendererMap = {
reasoning: ({ part }) => (
<Accordion
defaultExpanded={part.state === 'streaming'}
sx={{ my: 1, bgcolor: 'action.hover' }}
>
<AccordionSummary expandIcon={<ExpandMoreIcon />}>
<Typography variant="caption" color="text.secondary">
{part.state === 'streaming' ? 'Thinking…' : 'Reasoning'}
</Typography>
</AccordionSummary>
<AccordionDetails>
<Typography variant="body2" sx={{ whiteSpace: 'pre-wrap' }}>
{part.text}
</Typography>
</AccordionDetails>
</Accordion>
),
};
<ChatProvider adapter={adapter} partRenderers={renderers}>
{/* your chat UI */}
</ChatProvider>;
open 상태를 제어하고 reasoning이 끝나면 자동으로 접는 내장 렌더러와 달리, 이 비제어 Accordion은 스트림 중간에 마운트될 때만 확장된 상태로 시작해요.
:::warning
기본 렌더러는 키보드로 조작 가능하고 메시지 목록의 roving focus와 통합되는 네이티브 <details>/<summary> 디스클로저를 사용해요.
교체한다면 동등한 접근 가능한 디스클로저 패턴을 유지하세요.
자세한 내용은 접근성(Accessibility)을 참고하세요.
:::
Reasoning 표시/숨기기
렌더러에서 파트를 필터링해서 reasoning을 사용자에게 보여줄지 제어할 수 있어요. 토글에는 prop, 컨텍스트 값, 또는 애플리케이션 상태를 사용할 수 있어요.
렌더러는 { part, message, index, onToolCall }을 받아요. 여기서 showReasoning은 런타임이 주입하는 prop이 아니라 렌더러가 클로저로 감싸는 애플리케이션 상태예요.
null을 반환하면 파트를 숨기고, 내보낸 ReasoningPart에 위임하면 보일 때 내장 디스클로저를 유지해요:
import * as React from 'react';
import { ChatBox } from '@mui/x-chat';
import { ReasoningPart, type ChatPartRendererMap } from '@mui/x-chat/headless';
function MyChat() {
const [showReasoning, setShowReasoning] = React.useState(true);
const renderers: ChatPartRendererMap = React.useMemo(
() => ({
reasoning: (props) => (showReasoning ? <ReasoningPart {...props} /> : null),
}),
[showReasoning],
);
return (
<ChatBox
adapter={adapter}
partRenderers={renderers} /* + a toggle for setShowReasoning */
/>
);
}
Reasoning 스트림 청크
Reasoning 콘텐츠는 텍스트 청크와 같은 패턴을 따르는 세 개의 청크 셋으로 스트리밍돼요:
| 청크 타입 | 필드 | 설명 |
|---|---|---|
reasoning-start |
id |
reasoning 파트 시작 |
reasoning-delta |
id, delta |
reasoning 콘텐츠 추가 |
reasoning-end |
id |
reasoning 파트 마무리 |
청크가 파트가 되는 방법
reasoning-start는state: 'streaming'인 새ChatReasoningMessagePart를 생성해요.reasoning-delta는 기존 reasoning 파트에delta텍스트를 추가해요.reasoning-end는state: 'done'으로 설정해요.
여러 reasoning-delta 청크는 텍스트 델타처럼 streamFlushInterval에 따라 배치된 뒤 스토어에 적용돼요.
스트리밍 예시
const adapter: ChatAdapter = {
async sendMessage({ message }) {
return new ReadableStream({
start(controller) {
controller.enqueue({ type: 'start', messageId: 'msg-1' });
// Reasoning section
controller.enqueue({ type: 'reasoning-start', id: 'reasoning-1' });
controller.enqueue({
type: 'reasoning-delta',
id: 'reasoning-1',
delta: 'The user is asking about weather in Paris. ',
});
controller.enqueue({
type: 'reasoning-delta',
id: 'reasoning-1',
delta: 'I should check the current forecast data.',
});
controller.enqueue({ type: 'reasoning-end', id: 'reasoning-1' });
// Text response
controller.enqueue({ type: 'text-start', id: 'text-1' });
controller.enqueue({
type: 'text-delta',
id: 'text-1',
delta: 'The weather in Paris is currently 22 degrees and sunny.',
});
controller.enqueue({ type: 'text-end', id: 'text-1' });
controller.enqueue({ type: 'finish', messageId: 'msg-1' });
controller.close();
},
});
},
};
툴 호출과 함께 있는 Reasoning
Reasoning 청크는 같은 스트림에서 툴 호출 앞, 사이, 뒤에 나타날 수 있어요. 런타임은 인터리빙을 올바르게 처리합니다. 각 청크 타입은 도착 순서대로 자신만의 메시지 파트를 만들어요:
// Stream order:
// 1. reasoning-start -> reasoning-delta -> reasoning-end (thinking)
// 2. tool-input-start -> tool-input-available (tool call)
// 3. reasoning-start -> reasoning-delta -> reasoning-end (thinking about result)
// 4. tool-output-available (tool result)
// 5. text-start -> text-delta -> text-end (final answer)
결과 메시지는 순서대로 다섯 개의 파트를 갖습니다: reasoning, tool, reasoning, tool(업데이트됨), text.
함께 보기
- 툴 호출 라이프사이클의 자세한 내용은 툴 호출(Tool calling)을 참고하세요.
- 다단계 에이전트 진행의 자세한 내용은 단계 추적(Step tracking)을 참고하세요.
- reasoning 청크를 포함한 전체 청크 프로토콜 참조는 스트리밍(Streaming)을 참고하세요.
ChatMessageContent API
데모
이 React 컴포넌트의 사용에 대한 예시와 자세한 내용은 컴포넌트 데모 페이지를 방문하세요:
- Chat - Reasoning
- Chat - Step Tracking
- Chat - Tool calling
- Chat - Messages
- Chat - Custom parts
- Chat - Files and images
- Chat - Sources and citations
- Chat - Text and markdown
가져오기(Import)
import { ChatMessageContent } from '@mui/x-chat/ChatMessage';
// or
import { ChatMessageContent } from '@mui/x-chat';
Props
| Name | Type | Default | Required | Description |
|---|---|---|---|---|
| afterContent | node |
- | No | |
| partProps | { dynamic-tool?: { className?: string, defaultExpanded?: object, slotProps?: object, slots?: object, toolSlotProps?: object, toolSlots?: object }, file?: { className?: string, slotProps?: object, slots?: object }, reasoning?: { className?: string, slotProps?: object, slots?: object }, source-document?: { className?: string, slotProps?: object, slots?: object }, source-url?: { className?: string, slotProps?: object, slots?: object }, text?: { renderText?: func }, tool?: { className?: string, defaultExpanded?: object, slotProps?: object, slots?: object, toolSlotProps?: object, toolSlots?: object } } |
- | No |
참고:
ref는 루트 요소로 전달됩니다.
제공되는 다른 prop은 모두 루트 요소(네이티브 요소)에 제공됩니다.
소스 코드
이 페이지에서 정보를 찾지 못했다면 컴포넌트의 구현을 살펴보세요.