跳至主要内容

Claude Sonnet 4:开发者实操指南

通过构建基于 Python 的数学解题代理,体验 Claude Sonnet 4 的开发者特性——代码执行、Files API 与工具调用。
· 11分钟 阅读

使用 AI 探索

Anthropic 近日发布了更新版的 Claude Sonnet 4.5、Claude Agents SDK,以及 Imagine with Claude。

随着Claude Sonnet 4 的发布,开发者如今可使用更强大的新能力——包括原生代码执行、灵活的 Files API,以及动态工具调用。这些功能为构建超越简单文本交互的 AI 应用带来了新的可能性。

在本教程中,我将通过构建一个基于 Python 的代理,带您上手这些新功能,它能直接在终端中解决高阶数学问题。您将学习使用新引入的 原生代码执行工具和Files API。

完成后,您将拥有一个由 Claude Sonnet 4 驱动的工作代理,能分析问题、编写并运行 Python 代码,并渲染如下图所示的可视化结果。

Claude 4 Sonnet 的原生代码执行工具生成的示例图

欢迎查看本项目的 GitHub 仓库,以获取构建应用所需的全部代码。

如果您刚开始使用类似 Claude 的大语言模型进行构建,这份 AI 开发者路线图概述了上手所需的关键工具、技能和学习路径。

Anthropic API 的新变化

在进入教程之前,我们先看看 Anthropic API 新近发布的特性。如果您已了解,可直接跳过。

我认为整个Claude 4 公告可以用这张图来概括:

一张图显示 Claude 4 模型在 SWE-bench Verified(真实软件工程任务基准)上领先。

Claude 4 模型(Opus 与 Sonnet 4)在经验证的软件工程任务上大幅领先。Anthropic 通过对模型行为进行几项重要改进实现了这一点:

  1. 更长的运行时长:两款模型均支持数小时的连续任务执行,能解决包含数千步的复杂问题。
  2. 结合工具的扩展思考:两款模型现在可在扩展思考过程中使用诸如网页搜索等工具,使 Claude 能在推理与工具调用之间交替,以改进回答质量。
  3. 并行工具执行:模型现在可以同时使用多个工具,而非顺序调用。
  4. 更精准的指令遵循:增强的可控性让用户对实现细节和 Claude 的响应方式拥有更大的掌控。
  5. 改进的记忆能力:在获得本地文件访问权限时,模型可提取并保存关键信息,以保持连续性并随时间积累默会知识。
  6. 更少的“取巧”行为:与先前版本相比,两款模型在使用捷径或漏洞完成任务方面的概率降低了 65%(详见完整公告)。

此外,作为 Claude 4 模型家族公告的一部分,Anthropic 还新增了四项构建代理的新功能:代码执行工具、Files API、MCP 连接器,以及扩展提示缓存。这些工具将改变开发者构建 AI 应用的方式。

代码执行工具:安全运行 Python 代码

代码执行工具允许Claude 在安全的沙盒环境中运行 Python 代码。不再只是给出代码建议,Claude 现在可以执行代码、分析结果,并迭代求解。

要使用代码执行工具,请将其加入 tools 数组,并包含所需的 beta 头:

from anthropic import Anthropic

# Initialize client with the code execution beta header
client = Anthropic(
   default_headers={
       "anthropic-beta": "code-execution-2025-05-22"
   }
)

# Send a request that triggers code execution
response = client.messages.create(
   model="claude-sonnet-4-20250514",
   max_tokens=4096,
   messages=[{
       "role": "user",
       "content": "Solve the quadratic equation 2x² + 5x - 3 = 0 and plot the parabola"
   }],
   tools=[{
       "type": "code_execution_20250522",
       "name": "code_execution"
   }]
)

当 Claude 执行代码时,响应将同时包含生成的代码与其执行结果。以下是如何解析各组件:

# Parse the response to extract code and results
for item in response.content:
   if item.type == "server_tool_use":
       # This contains the actual Python code Claude wrote
       print(f"Code executed:\n{item.input['code']}")
   elif item.type == "code_execution_tool_result":
       # This contains the output from running the code
       print(f"Output:\n{item.content['stdout']}")
       if item.content.get('stderr'):
           print(f"Errors:\n{item.content['stderr']}")

沙盒限制:代码执行环境内置多项安全约束。Claude 在隔离容器中运行,无互联网访问,计算资源受限(1 GB 内存、5 GB 磁盘与 1 个 CPU),且无法访问您的本地文件系统。环境预装了 numpy、pandas、matplotlib、scipy 等常用库,但执行期间无法再安装额外包。

Files API:为复杂任务提供持久文件上下文

Files API 允许您将文档上传一次,并在多次对话中引用,无需在每次 API 请求中重复包含大型文档。

首先,将文件上传至 Anthropic 服务器:

# Upload a file once - this stores it on Anthropic's servers
uploaded_file = client.beta.files.upload(
   file=open("sales_data.csv", "rb"),
   purpose="user_upload"
)
# The uploaded_file.id can now be referenced in multiple conversations

上传后,通过 container_upload 内容类型在 API 调用中引用该文件:

# Reference the uploaded file in a conversation
response = client.messages.create(
   model="claude-sonnet-4-20250514",
   max_tokens=4096,
   messages=[{
       "role": "user",
       "content": [
           {"type": "text", "text": "Create a quarterly sales report from this data"},
           {"type": "container_upload", "file_id": uploaded_file.id}
       ]
   }],
   tools=[{
       "type": "code_execution_20250522",
       "name": "code_execution"
   }]
)

当 Claude 在代码执行期间创建文件(如图表或处理后的数据)时,您可以提取并下载它们:

# Extract file IDs of any files Claude created during execution
def extract_created_files(response):
   file_ids = []
   for item in response.content:
       if item.type == 'code_execution_tool_result':
           content = item.content
           if content.get('type') == 'code_execution_result':
               # Look for file objects in the execution results
               for file_obj in content.get('content', []):
                   if 'file_id' in file_obj:
                       file_ids.append(file_obj['file_id'])
   return file_ids

# Download any files Claude created
created_files = extract_created_files(response)
for file_id in created_files:
   file_content = client.beta.files.download(file_id)
   file_content.write_to_file(f"output_{file_id}.png")

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 项目环境

在编写任何代码前,我们先搭建开发环境与依赖。

为项目创建新目录并准备所需文件:

mkdir math-solver
cd math-solver
touch math_solver.py demo_problems.py requirements.txt README.md

创建 requirements.txt 文件并写入必要依赖:

anthropic>=0.42.0

安装依赖:

pip install -r requirements.txt

将您的 Anthropic API 密钥设置为环境变量:

export ANTHROPIC_API_KEY="your-api-key-here"

步骤 1:设计应用结构

我们先创建 MathSolver 类的基本结构。它将负责核心功能:API 通信、文件管理与用户交互。

首先,设置导入与基础结构:

#!/usr/bin/env python3
"""
Interactive Math Problem Solver using Claude 4 Code Execution Tool

This application allows users to ask math questions in natural language,
gets solutions using Claude's code execution capabilities, and saves
both visualizations and detailed markdown reports.
"""

import os
import json
import datetime
from pathlib import Path
from typing import List, Dict, Any
from anthropic import Anthropic

接着定义主类结构:

class MathSolver:
   def __init__(self, api_key: str = None):
       """Initialize the Math Solver with Anthropic client."""
       # API setup and directory creation will go here
       pass

   def solve_problem(self, question: str) -> Dict[str, Any]:
       """Send a math question to Claude and get solution with code execution."""
       pass
Here are the methods for file and report handling:
def extract_files_from_response(self, response) -> List[str]:
       """Extract file IDs from Claude's response."""
       pass

   def download_files(self, file_ids: List[str]) -> List[str]:
       """Download files created by code execution to local storage."""
       pass

   def extract_code_blocks(self, response) -> List[str]:
       """Extract all code blocks from the response."""
       Pass

最后,添加会话管理与入口点:

def generate_markdown_report(self, result: Dict[str, Any], downloaded_files: List[str]) -> str:
       """Generate a comprehensive markdown report of the solution."""
       pass

   def run_interactive_session(self):
       """Run the main interactive session loop."""
       pass


def main():
   """Main entry point for the application."""
   pass

该结构为我们提供了清晰的路线图:初始化、求解问题、文件处理、报告生成与用户交互。每个方法都在数学求解流水线上承担特定职责。

使用 Claude Sonnet 4 代码执行构建数学解题器

现在,我们用 Claude 的代码执行工具与流式响应来实现核心功能。

步骤 2:使用安全 API 头初始化 Claude

实现 __init__() 方法以完成 API 客户端配置与目录创建。

首先,处理 API 密钥管理:

def __init__(self, api_key: str = None):
   """Initialize the Math Solver with Anthropic client."""
   if not api_key:
       api_key = os.getenv("ANTHROPIC_API_KEY")
       if not api_key:
           raise ValueError(
               "Please set ANTHROPIC_API_KEY environment variable or provide api_key"
           )

然后,使用所需的 beta 头设置 Anthropic 客户端:

# Initialize client with both code execution and files API headers
   self.client = Anthropic(
       api_key=api_key,
       default_headers={
           "anthropic-beta": "code-execution-2025-05-22,files-api-2025-04-14"
       },
   )

最后,创建输出目录结构:

# Create organized output directories
   self.output_dir = Path("math_solver_output")
   self.images_dir = self.output_dir / "images"
   self.reports_dir = self.output_dir / "reports"

   self.output_dir.mkdir(exist_ok=True)
   self.images_dir.mkdir(exist_ok=True)
   self.reports_dir.mkdir(exist_ok=True)

   print(f"📁 Output directories created:")
   print(f"   • Images: {self.images_dir}")
   print(f"   • Reports: {self.reports_dir}")

该初始化完成三项关键工作:

  1. API 密钥管理:优先检查环境变量中的密钥,否则使用参数传入。
  2. 客户端配置:创建带代码执行与 Files API 两个 beta 头的 Anthropic 客户端。
  3. 目录结构:创建用于存放图片与报告的有序文件夹。

步骤 3:编写核心求解函数

solve_problem() 是应用的核心。它以流式方式向 Claude 发送请求。

先编写函数签名与初始设置:

def solve_problem(self, question: str) -> Dict[str, Any]:
   """
   Send a math question to Claude and get solution with code execution.
   """
   print(f"\n🤔 Thinking about: {question}")

   try:
       # Use streaming to show real-time progress
       with self.client.messages.stream(
           model="claude-sonnet-4-20250514",
           max_tokens=4096,
Now we configure the message and tool specification:
messages=[
               {
                   "role": "user",
                   "content": f"""Solve this math problem using code execution:

Problem: {question}

Please:
1. Solve the problem with actual Python code
2. Create visualizations using matplotlib if helpful
3. Save any plots as PNG files using plt.savefig()
4. Show your calculations step by step
5. Use descriptive filenames for saved plots

Execute Python code to solve this problem.""",
               }
           ],
           tools=[{"type": "code_execution_20250522", "name": "code_execution"}],
       ) as stream:
The streaming event processing handles real-time updates:
print("\n💭 Claude is working...")

           # Process streaming events and show progress
           for event in stream:
               if event.type == "content_block_start":
                   if hasattr(event.content_block, "type"):
                       if event.content_block.type == "text":
                           print("\n📝 Response:", end=" ", flush=True)
                       elif event.content_block.type == "server_tool_use":
                           print(f"\n🔧 Using tool: {event.content_block.name}")

我们处理不同类型的流式事件:

	elif event.type == "content_block_delta":
                   if hasattr(event.delta, "text"):
                       print(event.delta.text, end="", flush=True)

               elif event.type == "content_block_stop":
                   print("", flush=True)  # New line

               elif event.type == "message_delta":
                   if hasattr(event.delta, "stop_reason"):
                       print(f"\n✅ Completed: {event.delta.stop_reason}")

最后,返回结果或处理错误:

	# Get the final message
           final_message = stream.get_final_message()

           return {
               "response": final_message,
               "question": question,
               "timestamp": datetime.datetime.now().isoformat(),
           }

   except Exception as e:
       print(f"❌ Error solving problem: {e}")
       return None

该函数展示了几项重要概念:

  • 流式支持:我们使用 client.messages.stream() 而非 client.messages.create(),以实时查看 Claude 解题进度。
  • 事件处理:流式 API 会发送不同事件类型:
    • content_block_start:当 Claude 开始写文本或使用工具时
    • content_block_delta:内容生成过程中
    • content_block_stop:当一个内容块完成时
    • message_delta:当整条消息完成时
  • 工具规范:我们在 tools 数组中加入代码执行工具,类型为 "code_execution_20250522"。
  • 结构化提示:提示明确要求 Claude 使用代码执行并保存可视化结果。

步骤 4:通过流式代码执行求解数学问题

当 Claude 在代码执行过程中创建文件(如 matplotlib 图表)时,我们需要提取其文件 ID 并下载到本地。

文件提取方法将遍历响应结构:

def extract_files_from_response(self, response) -> List[str]:
   """Extract file IDs from Claude's response."""
   file_ids = []

   for item in response.content:
       if item.type == "code_execution_tool_result":
           content_item = item.content
          
           if isinstance(content_item, dict):
               if content_item.get("type") == "code_execution_result":
                   content_list = content_item.get("content", [])

随后在内容中搜索文件 ID:

  for file_item in content_list:
                       if isinstance(file_item, dict) and "file_id" in file_item:
                           file_ids.append(file_item["file_id"])

   return file_ids

下载流程将检索文件并保存到本地:

def download_files(self, file_ids: List[str]) -> List[str]:
   """Download files created by code execution to local storage."""
   downloaded_files = []

   for file_id in file_ids:
       try:
           # Get file metadata and download content
           file_metadata = self.client.beta.files.retrieve_metadata(file_id)
           filename = file_metadata.filename
          
           file_content = self.client.beta.files.download(file_id)
           local_path = self.images_dir / filename
           file_content.write_to_file(str(local_path))

我们跟踪已下载文件并处理错误:

downloaded_files.append(str(local_path))
           print(f"✅ Downloaded: {filename}")

       except Exception as e:
           print(f"❌ Error downloading file {file_id}: {e}")

   return downloaded_files
  • 文件提取逻辑:extract_files_from_response() 方法遍历响应结构以寻找文件 ID。代码执行结果以特定格式嵌套,文件出现在 content 数组中。
  • 文件下载流程:download_files() 方法:
    • 获取每个文件的元数据(含原始文件名)
    • 使用 Files API 下载文件内容
    • 将文件保存到有序目录结构
    • 返回用于后续使用的本地文件路径列表

从 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"![{filename}]({relative_path})\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.")

该循环展示了完整的工作流:

  1. 用户交互:提示问题并处理退出命令
  2. 问题求解:调用 solve_problem() 方法
  3. 文件处理:提取并下载生成的文件
  4. 报告生成:创建完整的 Markdown 报告
  5. 错误处理:优雅地处理中断与错误

步骤 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

尝试一些示例问题:

  1. 基础计算:“What is 15% of 240?”
  2. 代数:“Solve for x: 3x + 7 = 22”
  3. 可视化:“Graph y = x² — 4x + 3 and find its vertex”
  4. 高等数学:“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 集成外部数据源,或将类似模式应用到其他领域,构建面向特定领域的助手,如数据分析、科学计算或教学工具。

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"。

Bexruz (Bex) Tuychiev

作者

Bexruz (Bex) Tuychiev

我是一名数据科学内容创作者,拥有超过 2 年的经验,并在 Medium 上拥有较大的读者群。我喜欢用略带讽刺的笔调撰写有关 AI 和机器学习的深度文章——毕竟总得想点办法让这些内容不那么枯燥。我已发表 130 多篇文章,并制作了一门 DataCamp 课程,另有一门正在筹备中。我的内容已被超过 500 万人次阅读,其中有 2 万人在 Medium 和 LinkedIn 上成为关注者。 

主题