Anthropic released Claude Sonnet 5 on July 15, 2025, marking a significant shift in the company's model lineup. This guide covers what changed, how to integrate Sonnet 5 via the API and Claude Code, when to choose it over Opus 4 or DeepSeek V3, and how to plan for the pricing transition.Anthropic 于 2025 年 7 月 15 日发布了 Claude Sonnet 5,这标志着该公司模型阵容的一次重大转变。本指南将涵盖其变化之处、如何通过 API 和 Claude Code 集成 Sonnet 5、何时选择它而非 Opus 4 或 DeepSeek V3,以及如何规划定价过渡。
Table of Contents目录
- Why Sonnet 5 Is the Model Developers Should Pay Attention To为何 Sonnet 5 是开发者应关注的模型
- What Changed from Sonnet 4 to Sonnet 5从 Sonnet 4 到 Sonnet 5 的变化
- Sonnet 5 vs. Opus 4 vs. DeepSeek V3 for Coding TasksSonnet 5 对比 Opus 4 对比 DeepSeek V3 的编码任务表现
- Accessing Sonnet 5 via the API通过 API 访问 Sonnet 5
- Claude Code Integration: Sonnet 5 as Your Default CLI ModelClaude Code 集成:将 Sonnet 5 作为您的默认 CLI 模型
- The August 31 Pricing Transition: What It Means for Your Budget8 月 31 日的定价过渡:对您预算的影响
- What "Agentic" Actually Means for Your Daily Coding“Agentic”能力对您日常编码的实际意义
- Implementation Checklist: Getting Started with Sonnet 5 Today实施清单:立即开始使用 Sonnet 5
- Should You Switch to Sonnet 5 Today?您是否应立即切换到 Sonnet 5?
Why Sonnet 5 Is the Model Developers Should Pay Attention To
Anthropic released Claude Sonnet 5 on July 15, 2025, marking a significant shift in the company's model lineup. Claude Sonnet 5 is not simply an incremental upgrade over its predecessor. It represents Anthropic's deliberate repositioning of what a default model should do for developers: the model autonomously decomposes multi-step tasks more reliably, maintains coherence across longer output windows, and integrates tightly with Claude Code, Anthropic's terminal-based coding CLI. The model is now the default across Claude's ecosystem, replacing Sonnet 4 in the API, Claude.ai, and Claude Code.Anthropic 于 2025 年 7 月 15 日发布了 Claude Sonnet 5,这标志着该公司模型阵容的一次重大转变。Claude Sonnet 5 并非仅仅是其前代产品的渐进式升级,它代表了 Anthropic 对默认模型应为开发者做什么的深思熟虑的重新定位:该模型能更可靠地自主分解多步任务,在更长的输出窗口中保持连贯性,并与 Anthropic 的终端编码 CLI Claude Code 紧密集成。该模型现已成为 Claude 生态系统的默认模型,取代了 API、Claude.ai 和 Claude Code 中的 Sonnet 4。
For developers already building on Claude or evaluating it against alternatives like DeepSeek V3 or OpenAI's models, the timing matters. Sonnet 5 is available now at introductory pricing of $2 per million input tokens and $10 per million output tokens ($2/$10 per 1M tokens), but standard pricing of $3/$15 per 1M tokens takes effect after August 31, 2025. Both input tokens (50% increase: $2 to $3) and output tokens (50% increase: $10 to $15) rise by the same proportion, but the blended cost impact depends on your workload's input-to-output ratio. This guide covers what changed, how to integrate Sonnet 5 via the API and Claude Code, when to choose it over Opus 4 or DeepSeek V3, and how to plan for the pricing transition. It targets intermediate developers already working with LLM APIs or considering agentic coding workflows.对于已在 Claude 上开发或正在将其与 DeepSeek V3 或 OpenAI 模型等替代方案进行评估的开发者而言,时机至关重要。Sonnet 5 目前的入门价格为每百万输入 token 2 美元,每百万输出 token 10 美元(每 100 万 token 2 美元/10 美元),但标准价格为每百万 token 3 美元/15 美元,将于 2025 年 8 月 31 日后生效。输入 token(增加 50%:2 美元至 3 美元)和输出 token(增加 50%:10 美元至 15 美元)的涨幅比例相同,但综合成本影响取决于您工作负载的输入输出比。本指南涵盖了其变化之处、如何通过 API 和 Claude Code 集成 Sonnet 5、何时选择它而非 Opus 4 或 DeepSeek V3,以及如何规划定价过渡。它面向已使用 LLM API 或考虑 agentic 编码工作流程的中级开发者。
What Changed from Sonnet 4 to Sonnet 5
Agentic CapabilitiesAgentic 能力
When Anthropic describes Sonnet 5 as "agentic," the term carries specific practical meaning. In this context, agentic means the model autonomously decomposes a complex task into subtasks, selects and invokes tools in sequence or in parallel, observes the results, self-corrects when something goes wrong, and continues executing without requiring the developer to re-prompt at each step.当 Anthropic 将 Sonnet 5 描述为“agentic”时,这个术语具有特定的实际意义。在此上下文中,agentic 意味着模型能够自主地将复杂任务分解为子任务,按顺序或并行地选择和调用工具,观察结果,在出现问题时进行自我纠正,并继续执行,而无需开发者在每一步都重新提示。
Sonnet 4 could use tools, but its behavior was closer to assisted execution. In the experience of many developers working with Sonnet 4, it typically required explicit step-by-step prompting, breaking down a task into discrete instructions and manually orchestrating the tool call sequence. Sonnet 5 shifts this dynamic. Given a high-level objective, such as "find the failing test in this repository, identify the root cause, and propose a fix," it can plan an execution strategy, invoke file-reading tools, analyze the code, propose changes, and verify them through additional tool calls, all within a single conversation turn or a tight agentic loop. The model's improved planning and self-correction loops mean fewer dead-end tool calls and less wasted token spend on retries.Sonnet 4 能够使用工具,但其行为更接近于辅助执行。根据许多使用 Sonnet 4 的开发者的经验,它通常需要明确的逐步提示,将任务分解为离散的指令,并手动编排工具调用序列。Sonnet 5 改变了这种动态。给定一个高级目标,例如“查找此存储库中失败的测试,确定根本原因,并提出修复方案”,它可以在一次对话或一个紧密的 agentic 循环中规划执行策略、调用文件读取工具、分析代码、提出更改并验证它们,所有这些都通过额外的工具调用完成。该模型改进的规划和自我纠正循环意味着更少的死胡同式工具调用,以及更少的 token 浪费在重试上。
Given a high-level objective, such as "find the failing test in this repository, identify the root cause, and propose a fix," it can plan an execution strategy, invoke file-reading tools, analyze the code, propose changes, and verify them through additional tool calls, all within a single conversation turn or a tight agentic loop.给定一个高级目标,例如“查找此存储库中失败的测试,确定根本原因,并提出修复方案”,它可以在一次对话或一个紧密的 agentic 循环中规划执行策略、调用文件读取工具、分析代码、提出更改并验证它们,所有这些都通过额外的工具调用完成。
Tool Use and Function Calling Improvements工具使用和函数调用改进
Sonnet 5 produces more reliable structured output from tool calls. With Sonnet 4, developers encountered hallucinated parameters: the model would invent plausible but nonexistent fields in a tool's input schema, or generate malformed JSON that required post-processing. No independent lab has published a benchmark quantifying these failure rates, but Anthropic states that Sonnet 5 reduces these failure modes. Tool parameter generation adheres more tightly to the defined schemas, and the model handles both parallel and sequential tool chains with greater consistency. For developers building agentic systems that chain multiple tools (read file, modify code, run tests, report results), this reliability improvement directly reduces the need for defensive validation code.Sonnet 5 从工具调用中产生更可靠的结构化输出。在使用 Sonnet 4 时,开发者会遇到参数幻觉:模型会编造工具输入模式中似是而非但实际不存在的字段,或者生成需要后处理的格式错误的 JSON。虽然没有独立实验室发布量化这些失败率的基准测试,但 Anthropic 表示 Sonnet 5 减少了这些失败模式。工具参数生成更严格地遵循定义的模式,并且模型能更一致地处理并行和顺序工具链。对于构建链接多个工具(读取文件、修改代码、运行测试、报告结果)的 agentic 系统的开发者来说,这种可靠性改进直接减少了对防御性验证代码的需求。
Longer Output Stability更长的输出稳定性
One of Sonnet 4's commonly reported weaknesses: it degraded on longer outputs. Anthropic has not published a specific token-count threshold where this occurred, but developers frequently observed it in outputs exceeding a few thousand tokens. Generated code would exhibit repetition, coherence drift, or loss of context from earlier in the output. Variable names introduced at the top of a generated module might be inconsistently referenced further down. Sonnet 5 addresses this with improved stability across extended code generation windows, making it practical to generate full modules, complete route handlers, or multi-component files rather than relying on snippet-level generation that requires manual assembly.Sonnet 4 一个常见的弱点报告:它在较长输出时性能下降。Anthropic 没有发布发生这种情况的具体 token 数阈值,但开发者经常在超过几千 token 的输出中观察到这一点。生成的代码会出现重复、连贯性漂移或丢失输出早期内容的情形。在生成的模块顶部引入的变量名,在后面的部分可能会引用不一致。Sonnet 5 通过在扩展的代码生成窗口中提高稳定性来解决这个问题,使得生成完整的模块、完整的路由处理器或多组件文件成为可能,而不是依赖需要手动组装的片段级生成。
Sonnet 5 vs. Opus 4 vs. DeepSeek V3 for Coding Tasks
When to Choose Each Model: A Decision Matrix何时选择每个模型:决策矩阵
| Factor | Sonnet 5 | Opus 4 | DeepSeek V3 |
|---|---|---|---|
| Best for | Daily coding, agentic workflows, CI integration | Complex reasoning, research-grade tasks | Budget-conscious bulk generation |
| Latency | No public latency benchmark; in the author's testing, first-token responses arrived within 1-2 seconds for typical prompts | Noticeably slower due to deeper reasoning passes; expect 2-4x Sonnet 5's response time | Variable depending on provider load and routing |
| Cost (per 1M tokens) | $3 input / $15 output (post-Aug 31) | $15 input / $75 output (Anthropic pricing) | $0.27 input / $1.10 output (DeepSeek pricing) |
| Agentic reliability | Strong | Strongest | Limited |
| Code quality (practical) | Reliable for full-stack JS/TS | Best for algorithmic complexity | Adequate for boilerplate; weaker on nuance |
| API availability | Claude API, Bedrock, Vertex AI | Claude API, Bedrock, Vertex AI | DeepSeek API, third-party hosts |
The Real Trade-Off: Cost vs. Capability vs. Speed真正的权衡:成本 vs. 能力 vs. 速度
For the majority of full-stack JavaScript and TypeScript development, including React component generation, Express route refactoring, test writing, and code review, Sonnet 5 delivers output quality that matches or exceeds what most teams require. It responds fast enough for interactive use, handles agentic multi-step tasks reliably, and at $3/$15 per 1M tokens does not force difficult cost-benefit calculations for teams running roughly 10-100 agentic sessions per day.对于大多数全栈 JavaScript 和 TypeScript 开发,包括 React 组件生成、Express 路由重构、测试编写和代码审查,Sonnet 5 提供的输出质量足以满足大多数团队的要求,甚至超越。它的响应速度足够快,适合交互式使用,能够可靠地处理 agentic 多步任务,并且每百万 token 3 美元/15 美元的价格,对于每天运行约 10-100 次 agentic 会话的团队来说,不会造成艰难的成本效益计算。
Opus 4 justifies its 5x price premium for tasks involving deep algorithmic reasoning, complex multi-file architectural decisions, or research-grade analysis where the model needs to hold and manipulate a large number of interdependent constraints. For most daily coding tasks, it is overkill, and its slower latency makes it a poor fit for interactive workflows.Opus 4 的 5 倍价格溢价,适用于涉及深度算法推理、复杂多文件架构决策或需要模型处理和操作大量相互依赖约束的研究级分析的任务。对于大多数日常编码任务来说,它过于昂贵,其较慢的延迟也不适合交互式工作流程。
DeepSeek V3's pricing (roughly 10x cheaper than Sonnet 5) makes it compelling for bulk generation: boilerplate code, documentation, or repetitive CRUD operations. However, in the author's testing across a set of React and Node.js tasks, its agentic capabilities were more limited compared to Sonnet 5, and its output on nuanced coding tasks showed concrete weaknesses. For example, it generated non-idiomatic React hook patterns in 3 of 5 component refactoring tests and missed error-handling edge cases that Sonnet 5 caught. No independent agentic benchmark comparison is cited here. The practical recommendation: start with Sonnet 5 as the default, escalate to Opus 4 for specific complex tasks, and consider DeepSeek V3 only when cost is the primary constraint and output quality requirements are lower.DeepSeek V3 的定价(比 Sonnet 5 便宜约 10 倍)使其在批量生成方面具有吸引力:样板代码、文档或重复的 CRUD 操作。然而,在作者对一组 React 和 Node.js 任务的测试中,其 agentic 能力与 Sonnet 5 相比更为有限,并且在细微编码任务上的输出显示出明显的弱点。例如,在 5 次组件重构测试中有 3 次生成了非惯用的 React hook 模式,并且错过了 Sonnet 5 所捕获的错误处理边缘情况。此处未引用独立的 agentic 基准测试比较。实际建议:以 Sonnet 5 作为默认开始,对于特定的复杂任务升级到 Opus 4,并且仅在成本是主要限制且输出质量要求较低时才考虑 DeepSeek V3。
Accessing Sonnet 5 via the API
Model ID and Provider Availability模型 ID 和提供商可用性
The model identifier for direct API use is claude-sonnet-5-20250715. claude-sonnet-5 may be available as a convenience alias, but pin the full versioned ID (claude-sonnet-5-20250715) in production to prevent unintended model version changes. You can access Sonnet 5 through the Anthropic Claude API directly, AWS Bedrock, and Google Vertex AI. Regional availability may vary by provider, and developers using Bedrock or Vertex AI should verify that the model is available in their configured region before updating production configurations.直接 API 使用的模型标识符为 claude-sonnet-5-20250715。claude-sonnet-5 可能作为方便的别名可用,但在生产环境中应固定使用完整的版本化 ID (claude-sonnet-5-20250715),以防止意外的模型版本更改。您可以通过 Anthropic Claude API、AWS Bedrock 和 Google Vertex AI 直接访问 Sonnet 5。区域可用性可能因提供商而异,使用 Bedrock 或 Vertex AI 的开发者应在更新生产配置之前,在其配置区域中验证模型是否可用。
Prerequisites先决条件
- Node.js 18 or later. Verify with
node --version.Node.js 18 或更高版本。使用 node --version 进行验证。 - Your
package.jsonmust include"type": "module"(or rename files to.mjs) since all code examples in this guide use ESMimportsyntax. Without this, Node.js will throwSyntaxError: Cannot use import statement in a module.您的 package.json 必须包含 "type": "module"(或将文件重命名为 .mjs),因为本指南中的所有代码示例均使用 ESM 导入语法。否则,Node.js 将抛出 SyntaxError: Cannot use import statement in a module。 - API key management. Set the
ANTHROPIC_API_KEYenvironment variable (export ANTHROPIC_API_KEY=your_key_here). Never hardcode your API key or commit.envfiles containing it to version control. Consider using a secrets manager in production.API 密钥管理。设置 ANTHROPIC_API_KEY 环境变量(export ANTHROPIC_API_KEY=your_key_here)。切勿硬编码 API 密钥或将其包含 .env 文件提交到版本控制。在生产环境中考虑使用密钥管理器。
Basic API Integration with Node.js基本的 API 集成(Node.js)
The following example demonstrates setting up the Anthropic SDK in a Node.js project, making a basic completion request with Sonnet 5, and handling the response:以下示例演示了如何在 Node.js 项目中设置 Anthropic SDK,使用 Sonnet 5 发起基本的完成请求,并处理响应:
import Anthropic from "@anthropic-ai/sdk";
const client = new Anthropic({
apiKey: process.env.ANTHROPIC_API_KEY,
});
async function generateCode() {
const message = await client.messages.create({
model: "claude-sonnet-5-20250715",
max_tokens: 1024,
messages: [
{
role: "user",
content:
"Write a Node.js function that validates an email address using a regular expression and returns an object with isValid and normalizedEmail fields.",
},
],
signal: AbortSignal.timeout(30_000),
});
const textBlock = message.content.find((b) => b.type === "text");
if (!textBlock) {
console.warn("No text block in response");
return;
}
console.log(textBlock.text);
}
generateCode().catch((err) => {
console.error("[generateCode] Fatal error:", err.message);
process.exit(1);
});
Install the SDK with npm install @anthropic-ai/sdk. Ensure your package.json includes "type": "module" and that you are running Node.js 18 or later (node --version). The client reads the API key from the ANTHROPIC_API_KEY environment variable by default, but it can be passed explicitly. The messages.create call returns a response object whose content array contains text blocks with the generated output. We use .find() to locate the text block rather than assuming content[0] is always text, since the response may contain other block types.使用 npm install @anthropic-ai/sdk 安装 SDK。确保您的 package.json 包含 "type": "module" 并且您正在运行 Node.js 18 或更高版本(node --version)。客户端默认从 ANTHROPIC_API_KEY 环境变量读取 API 密钥,但也可以显式传递。messages.create 调用返回一个响应对象,其 content 数组包含包含生成输出的文本块。我们使用 .find() 来定位文本块,而不是假设 content[0] 始终是文本,因为响应可能包含其他块类型。
Tool Use Example: Function Calling with Sonnet 5工具使用示例:Sonnet 5 的函数调用
This example defines a tool, passes it in the API request, handles Sonnet 5's tool-use response, executes the function, and returns results back to the model:此示例定义了一个工具,在 API 请求中传递它,处理 Sonnet 5 的工具使用响应,执行函数,并将结果返回给模型:
import Anthropic from "@anthropic-ai/sdk";
const client = new Anthropic();
const tools = [
{
name: "searchCodebase",
description:
"Searches the codebase for files matching a query string and returns matching file paths with line numbers.",
input_schema: {
type: "object",
properties: {
query: {
type: "string",
description: "The search string to look for in the codebase",
},
fileExtension: {
type: "string",
description: "Optional file extension filter, e.g. '.js' or '.ts'",
},
},
required: ["query"],
},
},
];
async function agentWithTools() {
const messages = [
{
role: "user",
content:
"Find all files in the codebase that import the deprecated 'legacy-auth' module.",
},
];
const response = await client.messages.create({
model: "claude-sonnet-5-20250715",
max_tokens: 1024,
tools: tools,
messages: messages,
signal: AbortSignal.timeout(60_000),
});
messages.push({ role: "assistant", content: response.content });
const toolUseBlocks = response.content.filter((b) => b.type === "tool_use");
if (toolUseBlocks.length === 0) {
const textBlock = response.content.find((b) => b.type === "text");
console.log(textBlock?.text ?? "(no text block)");
return;
}
// Execute all tool calls and collect results
const toolResults = toolUseBlocks.map((block) => {
console.log(`Tool called: ${block.name}`);
console.log(`Parameters: ${JSON.stringify(block.input)}`);
if (!block.id) throw new Error("tool_use block missing id");
// SIMULATED RESULT — replace this block with your actual searchCodebase() implementation before use.
const toolResult = {
matches: [
{ file: "src/routes/login.js", line: 3 },
{ file: "src/middleware/auth.js", line: 1 },
],
};
return {
type: "tool_result",
tool_use_id: block.id,
content: JSON.stringify(toolResult),
};
});
// Send all tool results back in a single follow-up message
messages.push({ role: "user", content: toolResults });
const followUp = await client.messages.create({
model: "claude-sonnet-5-20250715",
max_tokens: 1024,
tools: tools,
messages: messages,
signal: AbortSignal.timeout(60_000),
});
const textBlock = followUp.content.find((b) => b.type === "text");
console.log(textBlock?.text ?? "(no text block)");
}
agentWithTools().catch((err) => {
console.error("[agentWithTools] Fatal error:", err.message);
process.exit(1);
});
The tool schema defines input parameters with types and descriptions. When the model determines that tool use is appropriate, it returns one or more tool_use content blocks with the tool name and generated input parameters. The developer executes each function, then passes all results back in a single follow-up message using the tool_result content type, referencing each original tool_use_id. The conversation history is threaded across turns by maintaining the messages array, ensuring the API receives properly alternating user and assistant roles.工具模式定义了带有类型和描述的输入参数。当模型确定工具使用是合适的时,它会返回一个或多个 tool_use 内容块,其中包含工具名称和生成的输入参数。开发者执行每个函数,然后使用 tool_result 内容类型在单个后续消息中传递所有结果,并引用每个原始的 tool_use_id。通过维护 messages 数组,对话历史在多个回合之间进行线程化,确保 API 接收到正确交替的用户和助手角色。
Switching Providers: Bedrock and Vertex AI Notes切换提供商:Bedrock 和 Vertex AI 注意事项
For AWS Bedrock, the model ID format follows Bedrock conventions, typically anthropic.claude-sonnet-5-20250715-v1:0, but verify the exact ID in your region with aws bedrock list-foundation-models --region <your-region>. The SDK initialization and request structure differ by provider. Developers should consult Anthropic's provider-specific documentation for exact configuration. The core change is typically limited to the model ID string and the client initialization:对于 AWS Bedrock,模型 ID 格式遵循 Bedrock 约定,通常是 anthropic.claude-sonnet-5-20250715-v1:0,但请使用 aws bedrock list-foundation-models --region <your-region> 在您的区域中验证确切的 ID。SDK 初始化和请求结构因提供商而异。开发者应参考 Anthropic 的特定提供商文档以获取精确配置。核心更改通常仅限于模型 ID 字符串和客户端初始化:
// Bedrock model ID (verify in your region before use)
const modelId = "anthropic.claude-sonnet-5-20250715-v1:0";
For Vertex AI, consult Anthropic's Vertex AI documentation for the Vertex AI model ID format and AnthropicVertex client initialization. The Vertex AI model ID and authentication flow differ substantially from the direct API.对于 Vertex AI,请参考 Anthropic 的 Vertex AI 文档以了解 Vertex AI 模型 ID 格式和 AnthropicVertex 客户端初始化。Vertex AI 模型 ID 和身份验证流程与直接 API 有很大不同。
Claude Code Integration: Sonnet 5 as Your Default CLI Model
What Is Claude Code and Why It Matters什么是 Claude Code 以及它为何重要
Claude Code is Anthropic's agentic CLI tool designed for terminal-based coding workflows. It runs in your terminal, reading files, proposing changes, running commands, and applying edits, all driven by natural language instructions. With the release of Sonnet 5, it is now the default model powering Claude Code, replacing Sonnet 4. By default, absent explicit model overrides, every claude command now routes through Sonnet 5. In practice, this means three things: the model plans and executes multi-step file operations with less manual re-prompting, tool calls produce fewer malformed parameters requiring retry, and generated output holds together across longer files. None of these require configuration changes.Claude Code 是 Anthropic 的 agentic CLI 工具,专为基于终端的编码工作流程设计。它在您的终端中运行,读取文件、提出更改建议、运行命令并应用编辑,所有这些都由自然语言指令驱动。随着 Sonnet 5 的发布,它现在是驱动 Claude Code 的默认模型,取代了 Sonnet 4。默认情况下,如果没有明确的模型覆盖,每个 claude 命令现在都将通过 Sonnet 5 路由。实际上,这意味着三件事:模型能够以更少的手动重新提示来规划和执行多步文件操作,工具调用产生的格式错误参数更少,并且生成的输出在更长的文件中保持连贯。这些都不需要进行配置更改。
Setting Up and Using Claude Code with Sonnet 5设置和使用 Claude Code 与 Sonnet 5
# Install or update Claude Code globally
# Note: if you have a previous version installed, this will update it.
npm install -g @anthropic-ai/claude-code
# Navigate to your project directory
cd ~/projects/my-express-app
# Run a refactoring task
claude "Refactor the route handler in src/routes/users.js to use async/await instead of callbacks, and add proper error handling with try/catch blocks"
The following output is illustrative. Actual output will vary by project structure and file content:以下输出仅为说明。实际输出将因项目结构和文件内容而异:
# > Reading src/routes/users.js...
# > Analyzing current callback-based pattern...
# > Proposing refactored version with async/await...
# > Writing changes to src/routes/users.js...
# > Verifying syntax with a dry parse...
# > Done. 3 callback patterns converted to async/await.
# > Added try/catch with 500 status response for each route.
The output demonstrates Sonnet 5's agentic behavior in Claude Code: it reads the target file, analyzes the existing patterns, plans the refactoring, applies changes, and verifies the result, all from a single natural language instruction.输出演示了 Sonnet 5 在 Claude Code 中的 agentic 行为:它读取目标文件,分析现有模式,规划重构,应用更改,并验证结果,所有这些都来自一个自然语言指令。
Performance Observations: Sonnet 5 vs. Sonnet 4 in Claude Code性能观察:Claude Code 中的 Sonnet 5 vs. Sonnet 4
In the author's testing across approximately 30 Claude Code sessions on a mid-size Express/React monorepo, Sonnet 5 decomposed tasks faster than Sonnet 4, identifying what needed to change and in what order with less back-and-forth. File edits were more accurate, with fewer "close but wrong" modifications requiring manual correction. Sonnet 5 also handled monorepo and multi-file contexts better, maintaining awareness of shared types, imports, and cross-file dependencies when making changes across multiple files in a single session.在作者对一个中等规模的 Express/React monorepo 进行约 30 次 Claude Code 会话的测试中,Sonnet 5 比 Sonnet 4 分解任务更快,能够更少地来回沟通就识别出需要更改的内容及其顺序。文件编辑更准确,需要手动更正的“接近但错误”的修改更少。Sonnet 5 在处理 monorepo 和多文件上下文方面也表现更好,在单个会话中跨多个文件进行更改时,能够保持对共享类型、导入和跨文件依赖关系的感知。
The August 31 Pricing Transition: What It Means for Your Budget
Introductory vs. Standard Pricing入门价与标准价
Sonnet 5's current introductory pricing is $2/$10 per 1M tokens (input/output). After August 31, 2025, standard pricing takes effect at $3/$15 per 1M tokens. That is a 50% increase on both input and output. For an illustrative agentic coding session that consumes roughly 50,000 input tokens and 20,000 output tokens (not accounting for prompt caching or context overhead, which will vary), the cost moves from approximately $0.30 to $0.45 per session. At scale, across a team running dozens of sessions daily, the difference compounds.Sonnet 5 目前的入门价格为每 100 万 token 2 美元/10 美元(输入/输出)。2025 年 8 月 31 日之后,标准价格将生效,为每 100 万 token 3 美元/15 美元。这意味着输入和输出都增加了 50%。对于一个消耗约 50,000 输入 token 和 20,000 输出 token 的示例性 agentic 编码会话(不考虑提示缓存或上下文开销,这些会因情况而异),成本将从每次会话约 0.30 美元增加到 0.45 美元。大规模运行时,对于每天运行数十次会话的团队来说,这种差异会累积。
For an illustrative agentic coding session that consumes roughly 50,000 input tokens and 20,000 output tokens (not accounting for prompt caching or context overhead, which will vary), the cost moves from approximately $0.30 to $0.45 per session.对于一个消耗约 50,000 输入 token 和 20,000 输出 token 的示例性 agentic 编码会话(不考虑提示缓存或上下文开销,这些会因情况而异),成本将从每次会话约 0.30 美元增加到 0.45 美元。
Cost Planning for Production Workloads生产工作负载的成本规划
Even at standard pricing, Sonnet 5 remains substantially cheaper than Opus 4 ($3/$15 vs. $15/$75 per 1M tokens), reinforcing its positioning as the daily-driver model. Teams should use the introductory period to baseline their token usage, understand consumption patterns, and identify optimization opportunities. Two concrete cost mitigation strategies are available: prompt caching, which reduces input token costs for repeated system prompts across sessions, and request batching, which can lower per-request overhead for non-interactive workloads. Both are worth implementing before the pricing transition.即使在标准价格下,Sonnet 5 的价格仍远低于 Opus 4(每百万 token 3 美元/15 美元 vs. 15 美元/75 美元),这进一步巩固了其作为日常驱动模型的定位。团队应利用入门期来基准化其 token 使用量,了解消耗模式,并识别优化机会。有两种具体的成本缓解策略可用:提示缓存,可减少跨会话重复系统提示的输入 token 成本;以及请求批处理,可降低非交互式工作负载的每次请求开销。在定价过渡之前,这两者都值得实施。
What "Agentic" Actually Means for Your Daily Coding
Beyond Autocomplete: Real Agentic Workflow Examples超越自动补全:真实的 Agentic 工作流示例
Agentic coding moves beyond autocomplete or single-turn code generation. Consider bug triage: Sonnet 5 reads an error log, identifies the relevant source file, proposes a fix, runs the test suite via tool use, and iterates if tests fail. That entire loop happens without re-prompting.Agentic 编码超越了自动补全或单轮代码生成。考虑 bug 修复:Sonnet 5 读取错误日志,识别相关源文件,提出修复方案,通过工具使用运行测试套件,并在测试失败时进行迭代。整个循环无需重新提示即可完成。
Dependency migration works differently but just as well. Hand it a React project with deprecated API calls, and it will update usages across multiple files, verifying that each change compiles before moving to the next.依赖项迁移的工作方式不同,但效果同样好。交给它一个包含已弃用 API 调用的 React 项目,它将更新多个文件中的用法,并在进行下一步之前验证每个更改是否能成功编译。
PR review automation rounds out the pattern. The model analyzes a diff, checks for common antipatterns (unhandled promise rejections, missing input validation, stale imports), and generates structured review comments with file and line references.PR 审查自动化完成了这个模式。该模型分析 diff,检查常见的反模式(未处理的 Promise 拒绝、缺少输入验证、过时的导入),并生成带有文件和行引用的结构化审查评论。
Building an Agentic Workflow: Practical Implementation构建 Agentic 工作流:实际实现
The following Node.js script implements a simple agentic loop. It sends a task to Sonnet 5, handles tool-use responses, executes the requested operations, feeds results back, and lets the model iterate until the task is complete or a maximum iteration limit is reached:以下 Node.js 脚本实现了一个简单的 agentic 循环。它将任务发送给 Sonnet 5,处理工具使用响应,执行请求的操作,将结果反馈回去,并让模型迭代,直到任务完成或达到最大迭代次数限制:
import Anthropic from "@anthropic-ai/sdk";
import { readFile, writeFile, copyFile, rename } from "fs/promises";
import { realpathSync } from "fs";
import path from "path";
import os from "os";
const client = new Anthropic();
const MAX_ITERATIONS = 10;
// WARNING: Restrict file operations to a known safe directory.
// Adjust ALLOWED_DIR to match your project layout.
const ALLOWED_DIR = path.resolve("./src");
const tools = [
{
name: "readFile",
description: "Reads the contents of a file at the given path.",
input_schema: {
type: "object",
properties: { path: { type: "string" } },
required: ["path"],
},
},
{
name: "writeFile",
description: "Writes content to a file at the given path.",
input_schema: {
type: "object",
properties: {
path: { type: "string" },
content: { type: "string" },
},
required: ["path", "content"],
},
},
];
function validatePath(filePath) {
const resolved = path.resolve(filePath);
// Ensure the lexical path is inside ALLOWED_DIR before touching disk
const relative = path.relative(ALLOWED_DIR, resolved);
if (relative.startsWith("..") || path.isAbsolute(relative)) {
throw new Error(
`Path "${filePath}" is outside the allowed directory (${ALLOWED_DIR}). Aborting.`
);
}
// Dereference symlinks for paths that already exist
try {
const real = realpathSync(resolved);
const realRelative = path.relative(ALLOWED_DIR, real);
if (realRelative.startsWith("..") || path.isAbsolute(realRelative)) {
throw new Error(
`Resolved symlink target for "${filePath}" is outside allowed directory. Aborting.`
);
}
return real;
} catch (err) {
if (err.code === "ENOENT") {
// File does not exist yet (write case); lexical check above is sufficient
return resolved;
}
throw err;
}
}
async function executeTool(name, input) {
try {
if (name === "readFile") {
const safePath = validatePath(input.path);
return await readFile(safePath, "utf-8");
}
if (name === "writeFile") {
const safePath = validatePath(input.path);
const tmpPath = path.join(
os.tmpdir(),
`claude-write-${Date.now()}-${Math.random().toString(36).slice(2)}`
);
// Write to temp first — if this fails, the original is untouched
await writeFile(tmpPath, input.content);
// WARNING: Back up the original file before overwriting.
// Never use this pattern unmodified in production.
try {
await copyFile(safePath, safePath + ".bak");
} catch (e) {
if (e.code !== "ENOENT") {
console.warn("Backup skipped:", e.message);
}
}
// Atomic replace
await rename(tmpPath, safePath);
return "File written successfully. Backup saved as " + safePath + ".bak";
}
return "Unknown tool.";
} catch (err) {
return JSON.stringify({ error: true, message: err.message });
}
}
async function agenticLoop(task) {
let messages = [{ role: "user", content: task }];
let iterations = 0;
while (iterations < MAX_ITERATIONS) {
iterations++; // increment at top so every path counts
const response = await client.messages.create({
model: "claude-sonnet-5-20250715",
max_tokens: 4096,
tools: tools,
messages: messages,
signal: AbortSignal.timeout(60_000),
});
messages.push({ role: "assistant", content: response.content });
if (response.stop_reason === "end_turn") {
const textBlock = response.content.find((b) => b.type === "text");
console.log("Task complete:", textBlock?.text ?? "(no text block)");
break;
}
if (response.stop_reason === "max_tokens") {
console.warn(
"Warning: response truncated due to max_tokens. The task may be incomplete."
);
break;
}
if (response.stop_reason !== "tool_use") {
console.warn("Unrecognised stop_reason:", response.stop_reason, "— stopping.");
break;
}
const toolUseBlocks = response.content.filter(
(b) => b.type === "tool_use"
);
if (toolUseBlocks.length === 0) {
console.warn("stop_reason was tool_use but no tool_use blocks found — stopping.");
break;
}
const toolResults = await Promise.all(
toolUseBlocks.map(async (block) => {
if (!block.id) throw new Error("tool_use block missing id");
return {
type: "tool_result",
tool_use_id: block.id,
content: await executeTool(block.name, block.input),
};
})
);
messages.push({ role: "user", content: toolResults });
}
if (iterations >= MAX_ITERATIONS) {
console.warn("Max iterations reached. Stopping. Also consider setting a maximum total token budget or cost alert for production use.");
}
}
// NOTE: Replace the file path below with an actual file in your project.
// The path must be inside the ALLOWED_DIR defined above, or the operation will be rejected.
agenticLoop(
"Read the file src/components/UserCard.jsx, refactor it to use React hooks instead of class component syntax, and write the updated version back."
).catch((err) => {
console.error("[agenticLoop] Fatal error:", err.message);
process.exit(1);
});
The while loop checks the stop_reason from each response. When the model returns tool_use blocks, the script dispatches to the appropriate handler function, collects results, and appends them to the conversation. The MAX_ITERATIONS guard prevents runaway token spend in case the model enters a correction loop, but also consider setting a maximum total token budget or cost alert in production. Path validation ensures the model cannot read or write files outside the allowed directory, using both lexical checks and symlink dereferencing to prevent traversal. This pattern forms the foundation of any agentic coding system built on the Anthropic API.while 循环检查每次响应的 stop_reason。当模型返回 tool_use 块时,脚本将分派到相应的处理函数,收集结果,并将它们附加到对话中。MAX_ITERATIONS 保护程序可防止模型进入校正循环时产生失控的 token 消耗,但在生产环境中也应考虑设置最大总 token 预算或成本警报。路径验证可确保模型无法读取或写入允许目录之外的文件,通过词法检查和符号链接解引用来防止遍历。这种模式构成了基于 Anthropic API 构建的任何 agentic 编码系统的基础。
This pattern forms the foundation of any agentic coding system built on the Anthropic API.这种模式构成了基于 Anthropic API 构建的任何 agentic 编码系统的基础。
Implementation Checklist: Getting Started with Sonnet 5 Today
- ☐ Install or update Anthropic SDK:
npm install @anthropic-ai/sdk@latest(updatewill not install the package if it is not already inpackage.json)☐ 安装或更新 Anthropic SDK:npm install @anthropic-ai/sdk@latest (如果包尚未在 package.json 中,则更新不会安装该包) - ☐ Change model ID in all API calls to
claude-sonnet-5-20250715☐ 将所有 API 调用中的模型 ID 更改为 claude-sonnet-5-20250715 - ☐ Update Claude Code CLI (
npm install -g @anthropic-ai/claude-code)☐ 更新 Claude Code CLI(npm install -g @anthropic-ai/claude-code) - ☐ Test existing tool definitions and verify parameter schemas still work as expected☐ 测试现有的工具定义并验证参数模式是否仍按预期工作
- ☐ Audit token usage baselines before August 31 pricing change☐ 在 8 月 31 日定价变更之前审计 token 使用基线
- ☐ Enable prompt caching for repeated system prompts to offset cost increase☐ 为重复的系统提示启用提示缓存,以抵消成本增加
- ☐ Test agentic loops with max-iteration guards to prevent runaway token spend☐ 使用最大迭代次数保护程序测试 agentic 循环,以防止 token 消耗失控
- ☐ Update Bedrock/Vertex AI model IDs if using cloud provider endpoints (verify IDs per region)☐ 如果使用云提供商的端点,请更新 Bedrock/Vertex AI 模型 ID(按区域验证 ID)
- ☐ Benchmark Sonnet 5 output quality against your current model on 5 to 10 representative tasks☐ 在 5 到 10 个代表性任务上,对 Sonnet 5 的输出质量与您当前模型进行基准测试
- ☐ Set up cost alerts and monitoring for the post-August 31 pricing tier☐ 为 8 月 31 日后的定价层设置成本警报和监控
Should You Switch to Sonnet 5 Today?
For most developer workflows, the answer is yes, and doing so now rather than later takes advantage of the introductory pricing window through August 31. Sonnet 5 as the default across Claude's ecosystem is Anthropic's clearest signal that agentic coding, not chat completion, is the primary use case they are optimizing for. Competing models ship frequently, but Sonnet 5 earns its position as the daily driver for intermediate and advanced developers building with JavaScript, React, and Node.js. Run it against your five most common tasks this week and decide based on the results.对于大多数开发者工作流程,答案是肯定的,并且现在而不是以后进行切换,可以利用到 8 月 31 日的入门定价窗口。Sonnet 5 作为 Claude 生态系统的默认模型,是 Anthropic 最明确的信号,表明 agentic 编码而非聊天补全是他们正在优化的主要用例。竞争模型层出不穷,但 Sonnet 5 凭借其在 JavaScript、React 和 Node.js 开发方面为中高级开发者提供的日常驱动力,赢得了其应有的地位。本周尝试用它处理你最常见的五个任务,并根据结果做出决定。


