Skip to main content

Documentation Index

Fetch the complete documentation index at: https://nvd-54.mintlify.app/llms.txt

Use this file to discover all available pages before exploring further.

推理 Token 揭示了高级模型(如 OpenAI 的 o1/o3 和 Anthropic 的 Claude 扩展思考功能)的内部思考过程。这些模型生成结构化的内容块,将推理与最终答案分离,让你能够构建展示模型如何得出响应的 UI 界面。

什么是推理 Token?

当具有推理能力的模型处理提示时,它们会生成两种不同类型的内容:
  1. 推理块:模型的内部思维链、问题分解和逐步分析
  2. 文本块:呈现给用户的最终、经过打磨的响应
这些内容作为类型化的内容块在 AIMessage 中传递,可通过 contentBlocks 属性访问:
// 推理块
{ type: "reasoning", reasoning: "Let me think about this step by step..." }

// 文本块
{ type: "text", text: "The answer is 42." }
并非所有模型都会产生推理 Token。此模式仅适用于支持扩展思考或思维链输出的模型。标准聊天模型仅返回文本块。

使用场景

  • 透明度:向用户展示模型的推理过程,以建立对其答案的信任
  • 调试:检查模型的思维过程,以识别出错的地方
  • 教育工具:通过揭示 AI 如何处理问题来教授学生解题方法
  • 决策支持:让领域专家验证建议背后的推理
  • 质量保证:在受监管行业中审计推理链以确保合规

提取推理和文本块

AIMessage 上的 contentBlocks 数组包含按生成顺序排列的所有块。按 type 过滤以分离推理和文本:
import { AIMessage } from "@langchain/core/messages";

function extractBlocks(msg: AIMessage) {
  const reasoningBlocks = msg.contentBlocks
    .filter((b) => b.type === "reasoning")
    .map((b) => b.reasoning);

  const textBlocks = msg.contentBlocks
    .filter((b) => b.type === "text")
    .map((b) => b.text);

  return {
    reasoning: reasoningBlocks.join(""),
    text: textBlocks.join(""),
  };
}
单条消息可能包含多个推理块(例如,当模型暂停推理、生成部分文本,然后继续推理时)。将它们连接起来可以获得完整的思考过程。

useStream 访问消息

导入你的智能体并将 typeof myAgent 作为类型参数传递给 useStream,以获得对状态值的类型安全访问:
import type { myAgent } from "./agent";
import { useStream } from "@langchain/react";
import { AIMessage, HumanMessage } from "@langchain/core/messages";

function Chat() {
  const stream = useStream<typeof myAgent>({
    apiUrl: "http://localhost:2024",
    assistantId: "reasoning",
  });

  return (
    <div className="messages">
      {stream.messages.map((msg, i) => {
        if (HumanMessage.isInstance(msg)) {
          return <HumanBubble key={i} text={msg.content} />;
        }
        if (AIMessage.isInstance(msg)) {
          return (
            <AIResponse
              key={i}
              message={msg}
              isStreaming={stream.isLoading && i === stream.messages.length - 1}
            />
          );
        }
        return null;
      })}
    </div>
  );
}

构建 ThinkingBubble 组件

ThinkingBubble 将推理 Token 呈现在一个视觉上有区分度的可折叠容器中。用户可以展开它查看完整的思考过程,或折叠它专注于最终答案。
import { useState } from "react";

function ThinkingBubble({
  reasoning,
  isStreaming,
}: {
  reasoning: string;
  isStreaming: boolean;
}) {
  const [isExpanded, setIsExpanded] = useState(false);

  const charCount = reasoning.length;
  const previewLength = 120;
  const preview =
    reasoning.length > previewLength
      ? reasoning.slice(0, previewLength) + "..."
      : reasoning;

  return (
    <div className="thinking-bubble">
      <button
        className="thinking-header"
        onClick={() => setIsExpanded(!isExpanded)}
      >
        <span className="thinking-icon">
          {isStreaming ? (
            <span className="thinking-spinner" />
          ) : (
            "💭"
          )}
        </span>
        <span className="thinking-label">
          {isStreaming ? "思考中..." : `思考过程(${charCount} 个字符)`}
        </span>
        <span className={`chevron ${isExpanded ? "expanded" : ""}`}></span>
      </button>

      {isExpanded && (
        <div className="thinking-content">
          <pre>{reasoning}</pre>
        </div>
      )}

      {!isExpanded && !isStreaming && (
        <div className="thinking-preview">{preview}</div>
      )}
    </div>
  );
}

ThinkingBubble 样式

使用独特的视觉处理方式将推理块与常规消息区分开来:
.thinking-bubble {
  background-color: #f8f5ff;
  border: 1px solid #e2d9f3;
  border-radius: 8px;
  padding: 12px;
  margin: 8px 0;
  font-size: 0.9em;
}

.thinking-header {
  display: flex;
  align-items: center;
  gap: 8px;
  cursor: pointer;
  background: none;
  border: none;
  width: 100%;
  text-align: left;
  color: #6b21a8;
  font-weight: 500;
}

.thinking-content {
  margin-top: 8px;
  padding-top: 8px;
  border-top: 1px solid #e2d9f3;
  white-space: pre-wrap;
  color: #4a4a4a;
  line-height: 1.5;
}

.thinking-preview {
  margin-top: 4px;
  color: #9ca3af;
  font-style: italic;
  font-size: 0.85em;
}

.chevron {
  margin-left: auto;
  transition: transform 0.2s;
}

.chevron.expanded {
  transform: rotate(90deg);
}

推理的流式输出指示器

当模型仍在生成推理 Token 时,显示动画指示器以传达思考正在进行中:
.thinking-spinner {
  display: inline-block;
  width: 16px;
  height: 16px;
  border: 2px solid #e2d9f3;
  border-top-color: #6b21a8;
  border-radius: 50%;
  animation: spin 0.8s linear infinite;
}

@keyframes spin {
  to { transform: rotate(360deg); }
}
在流式输出期间,默认保持 ThinkingBubble 折叠状态并仅显示加载动画。在流式输出过程中展开可能会因为新 Token 到达而导致布局抖动。让用户在推理阶段完成后再展开。

渲染完整的 AI 响应

ThinkingBubble 和标准文本气泡组合成一个 AIResponse 组件:
function AIResponse({
  message,
  isStreaming,
}: {
  message: AIMessage;
  isStreaming: boolean;
}) {
  const reasoningBlocks = message.contentBlocks
    .filter((b) => b.type === "reasoning")
    .map((b) => b.reasoning)
    .join("");

  const textBlocks = message.contentBlocks
    .filter((b) => b.type === "text")
    .map((b) => b.text)
    .join("");

  const hasReasoning = reasoningBlocks.length > 0;
  const hasText = textBlocks.length > 0;

  const isReasoningPhase = isStreaming && !hasText;
  const isTextPhase = isStreaming && hasText;

  return (
    <div className="ai-response">
      {hasReasoning && (
        <ThinkingBubble
          reasoning={reasoningBlocks}
          isStreaming={isReasoningPhase}
        />
      )}
      {hasText && (
        <div className="ai-text-bubble">
          <p>{textBlocks}</p>
          {isTextPhase && <span className="cursor-blink"></span>}
        </div>
      )}
    </div>
  );
}

处理边界情况

没有推理的消息

并非每条 AI 消息都包含推理块。当 contentBlocks 只有文本块时,渲染标准消息气泡而不显示 ThinkingBubble。

空推理块

某些模型会生成空的推理块作为占位符。将它们过滤掉:
const meaningfulReasoning = message.contentBlocks
  .filter((b) => b.type === "reasoning" && b.reasoning.trim().length > 0);

多轮推理-文本循环

单条消息可以在推理块和文本块之间交替。如果你需要保留这种交错顺序,按顺序遍历 contentBlocks 而不是按类型分组:
message.contentBlocks.forEach((block) => {
  if (block.type === "reasoning") {
    // 渲染 ThinkingBubble
  } else if (block.type === "text") {
    // 渲染文本段落
  }
});

最佳实践

  • 默认折叠:按需显示推理,而非默认显示
  • 显示字符数:让用户快速了解模型在响应中投入了多少思考
  • 视觉区分:使用不同的颜色、边框或背景,使推理永远不会与实际答案混淆
  • 过渡动画:平滑的展开/折叠动画提升感知质量
  • 考虑无障碍:在切换按钮上使用适当的 ARIA 属性(aria-expandedaria-controls
  • 预览时截断:折叠时显示推理的简短预览,让用户决定是否展开