7.2 结构化输出解析与校验
7.2.1 核心问题
7.2.2 Claude 的消息类型系统
from dataclasses import dataclass
from enum import Enum
from typing import Optional, List, Any
class ContentBlockType(Enum):
TEXT = "text"
TOOL_USE = "tool_use"
THINKING = "thinking"
@dataclass
class TextBlock:
"""文本内容块"""
type: str = "text"
text: str = ""
@dataclass
class ToolUseBlock:
"""工具调用块"""
type: str = "tool_use"
id: str = ""
name: str = ""
input: dict = None # JSON 输入参数
@dataclass
class ThinkingBlock:
"""思考过程块(Adaptive Thinking)"""
type: str = "thinking"
thinking: str = ""
ContentBlock = TextBlock | ToolUseBlock | ThinkingBlock
@dataclass
class ParsedMessage:
"""解析后的完整消息"""
content_blocks: List[ContentBlock]
stop_reason: str # "end_turn", "tool_use", "max_tokens"
tokens_used: int
def text_content(self) -> str:
"""提取所有文本内容"""
texts = [
block.text for block in self.content_blocks
if isinstance(block, TextBlock)
]
return "".join(texts)
def tool_calls(self) -> List[ToolUseBlock]:
"""提取所有工具调用"""
return [
block for block in self.content_blocks
if isinstance(block, ToolUseBlock)
]
def thinking_content(self) -> Optional[str]:
"""提取思考过程"""
for block in self.content_blocks:
if isinstance(block, ThinkingBlock):
return block.thinking
return None非流式解析
流式解析
使用流式解析器
Pydantic 校验
解析管道
输出解析管道架构
总结
最后更新于
