从 Claude Sonnet 4 中提取结果:代码、可视化与报告
现在,让我们复用并审阅 Claude 生成的代码与输出。
步骤 5:从 Claude 的响应中下载可视化结果
为了在 Markdown 报告中包含 Claude 实际执行的 Python 代码:
def extract_code_blocks(self, response) -> List[str]:
"""Extract all code blocks from the response."""
code_blocks = []
for item in response.content:
if item.type == "server_tool_use" and item.name == "code_execution":
if (
hasattr(item, "input")
and isinstance(item.input, dict)
and "code" in item.input
):
code_blocks.append(item.input["code"])
return code_blocks
该方法查找名为 server_tool_use 的项且名称为 "code_execution",并从 input 字段中提取 Python 代码。这能得到 Claude 实际编写并执行的代码。
步骤 6:提取 Claude 的代码以便复用与审计
我们的报告生成器将为每次解题创建完整的文档。
首先,提取内容并搭建报告结构:
def generate_markdown_report(self, result: Dict[str, Any], downloaded_files: List[str]) -> str:
"""Generate a comprehensive markdown report of the solution."""
response = result["response"]
question = result["question"]
timestamp = result["timestamp"]
# Extract text content and code blocks
text_content = []
code_blocks = self.extract_code_blocks(response)
for item in response.content:
if item.type == "text":
text_content.append(item.text)
接着,生成带时间戳的安全文件名:
# Generate filename with timestamp
safe_question = "".join(
c for c in question[:50] if c.isalnum() or c in (" ", "-", "_")
).strip()
filename = f"{datetime.datetime.now().strftime('%Y%m%d_%H%M%S')}_{safe_question.replace(' ', '_')}.md"
filepath = self.reports_dir / filename
构建包含标题与问题陈述的 Markdown 内容:
# Create markdown content
markdown_content = f"""# Math Problem Solution Report
**Generated:** {timestamp}
**Question:** {question}
---
## Problem Statement
{question}
---
## Solution
"""
Add the solution explanation and code blocks:
# Add the main explanation
for text in text_content:
markdown_content += f"{text}\n\n"
# Add code sections
if code_blocks:
markdown_content += "---\n\n## Code Used\n\n"
for i, code in enumerate(code_blocks, 1):
markdown_content += f"### Code Block {i}\n\n```python\n{code}\n```\n\n"
包含所有生成的可视化:
# Add images section
if downloaded_files:
markdown_content += "---\n\n## Generated Visualizations\n\n"
for file_path in downloaded_files:
filename = Path(file_path).name
relative_path = f"../images/{filename}"
markdown_content += f"\n\n"
Finally, add metadata and save the report:
# Add footer
markdown_content += f"""---
## Report Details
- **Generated by:** Claude 4 Math Solver
- **Model:** claude-sonnet-4-20250514
- **Timestamp:** {timestamp}
- **Files created:** {len(downloaded_files)} visualization(s)
---
*This report was automatically generated using Claude's code execution capabilities.*
"""
# Save the report
with open(filepath, "w", encoding="utf-8") as f:
f.write(markdown_content)
return str(filepath)
该报告生成器将创建结构化的 Markdown 文档,包含:
- 问题陈述与元数据
- Claude 文本响应中的解题说明
- 展示实际执行的 Python 代码的代码块
- 使用相对路径嵌入的可视化图像
- 用于追踪与引用的报告元数据
文件名生成逻辑会创建安全且带时间戳的文件名,避免与现有文件冲突。
以交互方式运行数学解题器
接下来,关注用户交互循环、演示工具与测试。
步骤 7:管理交互式会话
交互式会话循环用于处理用户输入并协调各组件。
首先进行会话设置并显示欢迎信息:
def run_interactive_session(self):
"""Run the main interactive session loop."""
print("🧮 Interactive Math Problem Solver with Claude 4")
print("=" * 60)
print("Ask me any math question and I'll solve it step by step!")
print("I can handle algebra, calculus, statistics, geometry, and more.")
print("Type 'quit', 'exit', or 'q' to end the session.")
print("=" * 60)
session_count = 0
主循环处理用户输入与退出条件:
while True:
try:
# Get user input
question = input(f"\n📝 Question #{session_count + 1}: ").strip()
if question.lower() in ["quit", "exit", "q"]:
print("\n👋 Thanks for using the Math Solver! Goodbye!")
break
if not question:
print("Please enter a question.")
continue
session_count += 1
对每个有效问题,按完整流程处理:
# Solve the problem
result = self.solve_problem(question)
if not result:
continue
# Extract and download any files created
file_ids = self.extract_files_from_response(result["response"])
downloaded_files = []
if file_ids:
print(f"📥 Downloading {len(file_ids)} file(s)...")
downloaded_files = self.download_files(file_ids)
最后生成报告并反馈给用户:
# Generate markdown report
print(f"📝 Generating report...")
report_path = self.generate_markdown_report(result, downloaded_files)
print(f"\n✅ Solution complete!")
print(f"📄 Report saved: {report_path}")
if downloaded_files:
print(f"🖼️ Visualizations: {len(downloaded_files)} file(s) saved")
except KeyboardInterrupt:
print("\n\n👋 Session interrupted. Goodbye!")
break
except Exception as e:
print(f"❌ An error occurred: {e}")
print("Please try again with a different question.")
该循环展示了完整的工作流:
- 用户交互:提示问题并处理退出命令
- 问题求解:调用
solve_problem()方法 - 文件处理:提取并下载生成的文件
- 报告生成:创建完整的 Markdown 报告
- 错误处理:优雅地处理中断与错误
步骤 8:编写应用入口
最后,我们需要一个 main() 函数来初始化并启动应用:
def main():
"""Main entry point for the application."""
try:
solver = MathSolver()
solver.run_interactive_session()
except Exception as e:
print(f"❌ Failed to initialize Math Solver: {e}")
print("Make sure you have set the ANTHROPIC_API_KEY environment variable.")
return 1
return 0
if __name__ == "__main__":
exit(main())
这个简洁的入口会处理初始化错误(如缺失 API 密钥)并提供有用的错误信息。
步骤 9:添加演示问题生成器
为帮助用户上手,我们创建一个包含示例问题的独立脚本。新建 demo_problems.py。
首先,定义问题类别:
# demo_problems.py
#!/usr/bin/env python3
"""
Demo problems for the Interactive Math Problem Solver
"""
# Sample problems organized by difficulty and topic
DEMO_PROBLEMS = {
"Beginner": [
"What is 15% of 240?",
"Solve for x: 3x + 7 = 22",
"Find the area of a circle with radius 5",
"Convert 45 degrees to radians",
"Calculate the hypotenuse of a right triangle with legs 3 and 4",
],
加入中级与高级问题集:
"Intermediate": [
"Solve the quadratic equation: 2x^2 + 5x - 3 = 0",
"Graph y = x^2 - 4x + 3 and find its vertex",
"Calculate mean, median, and standard deviation of [12, 15, 18, 22, 25, 28]",
"Find where f(x) = x^3 - 3x^2 + 2 crosses the x-axis",
"Solve the system of equations: 2x + 3y = 7, x - y = 1",
],
"Advanced": [
"Find the derivative of sin(x) * e^x and plot both functions",
"Calculate the integral of x^2 from 0 to 5",
"Use Newton's method to find the root of x^3 - 2x - 5 = 0",
"Perform linear regression on data points and plot the results",
"Solve the differential equation dy/dx = x*y with initial condition y(0) = 1",
],
}
创建用于随机选择与展示的辅助函数:
def get_random_problem(category=None):
"""Get a random problem from a specific category or all categories."""
import random
if category and category in DEMO_PROBLEMS:
return random.choice(DEMO_PROBLEMS[category])
else:
# Pick from all problems
all_problems = []
for problems in DEMO_PROBLEMS.values():
all_problems.extend(problems)
return random.choice(all_problems)
添加函数以显示所有可用问题:
def print_demo_problems():
"""Print all demo problems organized by category."""
print("🧮 Demo Problems for Interactive Math Solver")
print("=" * 60)
print("Here are example problems you can try, organized by difficulty:\n")
for category, problems in DEMO_PROBLEMS.items():
print(f"### {category}")
print("-" * (len(category) + 4))
for i, problem in enumerate(problems, 1):
print(f"{i:2d}. {problem}")
print()
print("💡 Tips:")
print(" • Copy and paste any question into the math solver")
print(" • All visualizations and reports will be saved automatically")
print("\n🚀 Start the solver with: python math_solver.py")
if __name__ == "__main__":
print_demo_problems()
该演示脚本提供:
- 分类题目,从初级到高级
- 随机题目选择,便于测试
- 使用指引,面向新用户
步骤 10:运行并测试应用
现在测试完整应用!运行数学解题器:
python math_solver.py
尝试一些示例问题:
- 基础计算:“What is 15% of 240?”
- 代数:“Solve for x: 3x + 7 = 22”
- 可视化:“Graph y = x² — 4x + 3 and find its vertex”
- 高等数学:“Find the derivative of sin(x) * e^x and plot both functions”
每个问题都会:
- 在 Claude 工作时显示实时流式输出
- 按需生成可视化
- 保存完整的 Markdown 报告
- 将图表文件下载到 images 目录
您也可以运行演示问题脚本查看所有示例:
python demo_problems.py
我们用 Claude Sonnet 4 构建了什么
我们的数学解题器展示了 Claude 4 及其新 API 功能的多项强大特性:
- 代码执行:Claude 能编写并运行 Python 代码以解决数学问题、迭代优化方案并处理复杂计算。
- 文件生成与管理:应用通过 Files API 自动处理文件创建、下载与组织。
- 流式交互:实时反馈让体验更流畅、更具参与感。
- 完整文档化:每个解答都以包含代码与可视化的详细 Markdown 报告形式保存。
- 友好的界面:基于终端的界面简单高效,适合数学问题求解。
该项目展示了如何将 Claude 4 的新能力结合起来,打造超越简单聊天交互的复杂应用。代码执行工具结合合适的文件处理与流式机制,为数学探索与分析提供了强大的平台。
您还可以通过参加 Developing AI Systems with the OpenAI API 课程,学习如何在其他平台上构建类似代理。
结语与后续步骤
通过构建这个数学解题器,我们看到 Claude 4 的新能力如何重塑 AI 应用的可能性。
我们的应用覆盖了从基础计算到复杂数学可视化的全流程,展示了这些 API 功能如何协同工作,带来优质的用户体验。尤其是代码执行工具,它让 Claude 能迭代求解并生成可视化,以前这些需要独立工具与复杂集成才能实现。
接下来,您可以将该解题器扩展到网页界面,通过 MCP 集成外部数据源,或将类似模式应用到其他领域,构建面向特定领域的助手,如数据分析、科学计算或教学工具。
- 如果您是开发者并希望认证自己的 AI 工程能力,请考虑 Associate AI Engineer(开发者)学习路径,其重点在于此类可用于生产的实现方式。
- 数据科学家若希望将 LLM 投入生产,可参考 Associate AI Engineer(数据科学家)学习路径,连接分析与 AI 部署。
FAQs
Claude 4 与之前版本相比有何不同?
Claude 4 引入了原生代码执行、结合工具的扩展思考、并行工具执行、改进的记忆能力,以及对数小时连续任务执行的支持。这些特性使其在软件工程任务上表现尤为出色。
Claude 4 能在对话中实际运行 Python 代码吗?
是的,Claude 4 可通过新的代码执行工具在安全沙盒环境中运行 Python 代码。它能进行计算、使用 matplotlib 生成可视化,并基于执行结果迭代优化方案。
Claude 的代码执行环境有哪些限制?
沙盒无法访问互联网,计算资源有限,且无法访问您的本地文件系统。它预装了 numpy、pandas、matplotlib 等常用库,但无法安装额外包。
新的 Files API 如何与代码执行配合工作?
Files API 允许您将文档上传一次,并在多次对话中引用。当 Claude 在代码执行期间创建文件(如图表)时,您可以通过 API 提取其文件 ID 并下载到本地。
使用 Claude 4 的代码执行功能是否需要特殊 API 访问?
您需要在 API 请求中包含 beta 头 "anthropic-beta": "code-execution-2025-05-22",并使用 claude-sonnet-4-20250514 模型。代码执行工具需在 tools 数组中指定为 "code_execution_20250522"。

我是一名数据科学内容创作者,拥有超过 2 年的经验,并在 Medium 上拥有较大的读者群。我喜欢用略带讽刺的笔调撰写有关 AI 和机器学习的深度文章——毕竟总得想点办法让这些内容不那么枯燥。我已发表 130 多篇文章,并制作了一门 DataCamp 课程,另有一门正在筹备中。我的内容已被超过 500 万人次阅读,其中有 2 万人在 Medium 和 LinkedIn 上成为关注者。
Anthropic 近日发布了更新版的 Claude Sonnet 4.5、Claude Agents SDK,以及 Imagine with Claude。
随着Claude Sonnet 4 的发布,开发者如今可使用更强大的新能力——包括原生代码执行、灵活的 Files API,以及动态工具调用。这些功能为构建超越简单文本交互的 AI 应用带来了新的可能性。
在本教程中,我将通过构建一个基于 Python 的代理,带您上手这些新功能,它能直接在终端中解决高阶数学问题。您将学习使用新引入的 原生代码执行工具和Files API。
完成后,您将拥有一个由 Claude Sonnet 4 驱动的工作代理,能分析问题、编写并运行 Python 代码,并渲染如下图所示的可视化结果。
欢迎查看本项目的 GitHub 仓库,以获取构建应用所需的全部代码。
如果您刚开始使用类似 Claude 的大语言模型进行构建,这份 AI 开发者路线图概述了上手所需的关键工具、技能和学习路径。
Anthropic API 的新变化
在进入教程之前,我们先看看 Anthropic API 新近发布的特性。如果您已了解,可直接跳过。
我认为整个Claude 4 公告可以用这张图来概括:
Claude 4 模型(Opus 与 Sonnet 4)在经验证的软件工程任务上大幅领先。Anthropic 通过对模型行为进行几项重要改进实现了这一点:
此外,作为 Claude 4 模型家族公告的一部分,Anthropic 还新增了四项构建代理的新功能:代码执行工具、Files API、MCP 连接器,以及扩展提示缓存。这些工具将改变开发者构建 AI 应用的方式。
代码执行工具:安全运行 Python 代码
代码执行工具允许Claude 在安全的沙盒环境中运行 Python 代码。不再只是给出代码建议,Claude 现在可以执行代码、分析结果,并迭代求解。
要使用代码执行工具,请将其加入
tools数组,并包含所需的 beta 头:当 Claude 执行代码时,响应将同时包含生成的代码与其执行结果。以下是如何解析各组件:
沙盒限制:代码执行环境内置多项安全约束。Claude 在隔离容器中运行,无互联网访问,计算资源受限(1 GB 内存、5 GB 磁盘与 1 个 CPU),且无法访问您的本地文件系统。环境预装了
numpy、pandas、matplotlib、scipy等常用库,但执行期间无法再安装额外包。Files API:为复杂任务提供持久文件上下文
Files API 允许您将文档上传一次,并在多次对话中引用,无需在每次 API 请求中重复包含大型文档。
首先,将文件上传至 Anthropic 服务器:
上传后,通过
container_upload内容类型在 API 调用中引用该文件:当 Claude 在代码执行期间创建文件(如图表或处理后的数据)时,您可以提取并下载它们:
MCP 连接器:将 Claude 接入任意工作流
MCP 连接器将模型上下文协议(Model Context Protocol)的支持直接带到 API。借助 MCP,Claude 可连接到外部服务,如数据库、API 和效率工具,而无需自定义集成代码。
此前,连接 MCP 服务器需要自行构建客户端基础设施。现在,您只需在 API 请求中提供远程 MCP 服务器 URL,Claude 将自动发现可用工具、管理连接并处理认证。
这为您打开了接入日益增长的 MCP 服务器生态的大门,例如来自 Zapier 和 Asana 的服务,使您可以构建能读取日程、更新项目管理工具,或整合数百种其他服务的代理。
从 Claude Sonnet 4 起步:项目概览与环境搭建
在了解新 API 特性后,我们来构建交互式数学解题器。它将结合 Claude 的代码执行能力与文件处理,打造一个完整的数学助手。
我们的应用将接收自然语言数学问题,通过执行 Python 代码求解、生成可视化,并保存完整报告。
若想以结构化方式学习构建此类项目,请查看 Developing AI Applications 学习路径。
> 注意:由于我们会在长代码块中穿插讲解,片段中的缩进可能不完全准确。建议在阅读时另开标签页打开本项目的 GitHub 仓库。
步骤 0:设置 Claude Sonnet 4 项目环境
在编写任何代码前,我们先搭建开发环境与依赖。
为项目创建新目录并准备所需文件:
创建
requirements.txt文件并写入必要依赖:安装依赖:
将您的 Anthropic API 密钥设置为环境变量:
步骤 1:设计应用结构
我们先创建
MathSolver类的基本结构。它将负责核心功能:API 通信、文件管理与用户交互。首先,设置导入与基础结构:
接着定义主类结构:
最后,添加会话管理与入口点:
该结构为我们提供了清晰的路线图:初始化、求解问题、文件处理、报告生成与用户交互。每个方法都在数学求解流水线上承担特定职责。
使用 Claude Sonnet 4 代码执行构建数学解题器
现在,我们用 Claude 的代码执行工具与流式响应来实现核心功能。
步骤 2:使用安全 API 头初始化 Claude
实现
__init__()方法以完成 API 客户端配置与目录创建。首先,处理 API 密钥管理:
然后,使用所需的 beta 头设置 Anthropic 客户端:
最后,创建输出目录结构:
该初始化完成三项关键工作:
步骤 3:编写核心求解函数
solve_problem()是应用的核心。它以流式方式向 Claude 发送请求。先编写函数签名与初始设置:
我们处理不同类型的流式事件:
最后,返回结果或处理错误:
该函数展示了几项重要概念:
client.messages.stream()而非client.messages.create(),以实时查看 Claude 解题进度。content_block_start:当 Claude 开始写文本或使用工具时content_block_delta:内容生成过程中content_block_stop:当一个内容块完成时message_delta:当整条消息完成时tools数组中加入代码执行工具,类型为"code_execution_20250522"。步骤 4:通过流式代码执行求解数学问题
当 Claude 在代码执行过程中创建文件(如 matplotlib 图表)时,我们需要提取其文件 ID 并下载到本地。
文件提取方法将遍历响应结构:
随后在内容中搜索文件 ID:
下载流程将检索文件并保存到本地:
我们跟踪已下载文件并处理错误:
extract_files_from_response()方法遍历响应结构以寻找文件 ID。代码执行结果以特定格式嵌套,文件出现在content数组中。download_files()方法: