GPT-5.6 Series is now live on CometAPI →

如何使用 Claude Sonnet 5 API

CometAPI
AnnaJul 3, 2026
如何使用 Claude Sonnet 5 API

快速解答

Claude Sonnet 5 API 是 Anthropic 全新的 Sonnet 級別模型,面向編碼代理、長上下文推理、工具使用與專業知識工作。Anthropic 於 2026 年 6 月 30 日發佈 Claude Sonnet 5,將其定位為迄今最具行動能力的 Sonnet 模型,並相較 Claude Sonnet 4.6 帶來重大升級。開發者可透過 CometAPI 使用模型 ID claude-sonnet-5,經由 Anthropic 原生 Messages 端點 POST /v1/messages 或 OpenAI 相容端點 POST /v1/chat/completions 調用。

為何現在 Claude Sonnet 5 尤其重要

Anthropic 於 2026 年 6 月 30 日推出 Claude Sonnet 5,目標直指構建代理系統的開發者。公司將 Sonnet 5 描述為迄今最具行動能力的 Sonnet 模型,具備更強的規劃、工具使用、編碼、瀏覽器操作、終端操作與專業推理能力。最重要的定位在於,Sonnet 5 在保持 Sonnet 等級更快、更具成本效益的同時,縮小了與 Claude Opus 4.8 的差距。

這一點之所以重要,是因為市場已經超越了單純的聊天補全。生產級 AI 應用愈發需要模型能閱讀大量上下文、呼叫工具、編寫程式碼、檢視文件、使用瀏覽器、執行終端命令、從錯誤中恢復,並完成多步驟流程。Claude Sonnet 系列一直以來在編碼與代理工作流程中廣受歡迎,而 Sonnet 5 正是為此類場景而生。

此次發佈也改變了開發者對 API 控制的思維方式。Claude Sonnet 5 預設採用自適應思考。針對此模型,手動擴展思考配額已被移除;Anthropic 的遷移說明指出,temperaturetop_ptop_k 等非預設採樣參數可能會返回 400 錯誤。換言之,從 Sonnet 4.6 遷移並不只是更改模型名稱。

什麼是 Claude Sonnet 5 API?

Claude Sonnet 5 API 是面向開發者的 Sonnet 5 模型程式化介面,設計用於文本生成、編碼、工具使用、文件推理、圖像理解與長上下文工作流程。在 CometAPI 上,其模型 ID 為:

claude-sonnet-5

你可以透過兩種主要方式調用:

  1. 當你需要 Claude 原生行為、自適應思考、努力程度控制、提示快取、工具、網頁搜尋、串流與 Anthropic 響應結構時,使用 CometAPI 的 Anthropic Messages 端點。
  2. 當你的應用已採用 OpenAI 風格的聊天補全,並希望在 Claude、GPT、Gemini 與其他模型家族間更容易路由時,使用 CometAPI 的 OpenAI 相容聊天端點。

對大多數生產團隊而言,原生 Messages 端點是 Claude 特定代理工作流程的最佳首選。當可攜性、模型比較或最小化遷移工作更重要時,則可選擇 OpenAI 相容端點。

Claude Sonnet 5 速覽規格

SpecificationClaude Sonnet 5 API detailPractical note
ProviderAnthropicAvailable through Anthropic and supported platforms such as CometAPI
CometAPI model IDclaude-sonnet-5Use this exact ID in CometAPI requests
CometAPI provider codeanthropicUseful for catalog filtering and routing
Native CometAPI endpointPOST /v1/messagesBest for Claude-native features
OpenAI-compatible endpointPOST /v1/chat/completionsBest for portable chat-completion integrations
Input typesText and image; CometAPI catalog also lists PDF-to-textGood fit for coding, documents, screenshots, charts, and multimodal review
Output typeTextUse separate tools for file generation, browser actions, or code execution
Context window1M tokens in Anthropic docsRecount prompts because of the new tokenizer
Maximum outputUp to 128k output tokens on the synchronous Messages APIAdaptive thinking tokens share the response budget
Thinking behaviorAdaptive thinking on by defaultDo not send old manual extended-thinking budgets
Effort controlSupported via output_config.effort on the Messages APIUse higher effort for hard reasoning and lower effort for speed/cost
Sampling controlsNon-default temperature, top_p, and top_k rejected in migration notesRemove old creativity knobs during migration

Claude Sonnet 5 API 有哪些新特性:關鍵創新

Anthropic 將 Sonnet 5 定位為相較 Sonnet 4.6 的大幅升級,聚焦於真實世界代理的可靠性。

1. 全新分詞器與 Token 效率

Sonnet 5 採用更新的分詞器(類似於 Opus 4.7)。相同輸入文本視內容類型而定,約會映射為 1.0–1.35 倍的 tokens,平均約增加 30%。

影響:啟動定價(至 2026/8/31,輸入/輸出每百萬 tokens 分別為 $2/$10)使過渡在成本上大致持平。之後標準定價為 $3/$15,與 Sonnet 4.6 的每 token 價格相同,但由於 token 膨脹,單次任務成本可能更高。務必使用新模型重新計算 tokens。

2. 能力提升

相較 Sonnet 4.6,Sonnet 5 在多項基準上有顯著提升:

  • 編碼與代理任務:在類 SWE-bench、代理式搜尋(BrowseComp)與電腦操作(OSWorld-Verified)上更接近 Opus 4.8。
  • 推理與知識工作:更好的持續專注、自我驗證,以及處理棕地程式碼或多步驟專業任務。
  • 多模態與工具使用:更強的並行工具呼叫與視覺能力。

效能會隨「努力等級」(low/medium/high/xhigh)而擴展,允許更精細的成本–效能取捨。在較高努力等級下,於多數任務上可達到或接近 Opus。

早期使用者反饋指出,複雜任務的完成速度更快、幻覺更少、真實世界執行更好。

如何使用 Claude Sonnet 5 API

3. 資安防護與安全性

  • 整體不良行為低於 4.6。
  • 相較 Opus 降低了網路攻擊利用能力(在 Firefox 漏洞測試中完整利用得分為 0%)。
  • 預設啟用「網安防護」——對危險用法進行即時偵測與阻擋(與 Opus 4.7/4.8 相同,較部分更高等級模型寬鬆)。

這使得 Sonnet 5 更適合用於對資安敏感的生產級代理。

如何使用 Claude Sonnet 5 API

Claude Sonnet 5 在與資安相關的推理能力上強於 Sonnet 4.6,但不如 Opus 4.8,並在所評估的資安任務上明顯低於 Mythos 5。

對 API 而言,重點在於防護會隨模型能力而擴展。Anthropic 描述了基於分類器的全流量防護,涵蓋「禁止用途」「高風險雙重用途」與「雙重用途」等類別。禁止用途與高風險雙重用途的互動預設會被封鎖,而一般雙重用途的安全任務,如漏洞檢測,預設不會被阻擋。

對合法的資安團隊而言,這意味著 Sonnet 5 可用於防禦性工作,例如程式碼審查、安全配置指引、漏洞分類、事件文件化與修補方案規劃。

Claude Sonnet 5 的自適應思考

自適應思考是 Claude Sonnet 5 最重要的面向開發者變更之一。它不再要求開發者為每次呼叫手動設定思考配額,而是讓 Claude 能根據任務動態分配推理投入。

自適應思考是 Sonnet 5 的亮點功能之一。它會動態調整推理深度:

  • 努力等級:Low(快速/低成本)、Medium、High(更深入分析),並提供自適應選項。
  • 預設值:在 API/Claude Code 上對 Sonnet 5 預設為 High。
  • 好處:在品質與成本/延遲之間取得平衡。較高努力在複雜任務上表現更佳,但會消耗更多 tokens。

提示範例:

Use adaptive thinking for this task: Quick overview first, then detailed analysis and code if critical issues are found.

在舊版 Claude 整合中,團隊常使用如下的擴展思考控制:

{
  "thinking": {
    "type": "enabled",
    "budget_tokens": 32000
  }
}

對於 Claude Sonnet 5,請勿再發送上述舊模式。Anthropic 的 Sonnet 5 遷移說明指出,手動擴展思考配額已移除,可能導致 400 錯誤。請改用自適應思考與努力程度控制。

努力程度控制如何運作

effort 參數為開發者提供了一種更簡單的方式,影響模型投入的工作量。Anthropic 目前的努力等級包含 lowmediumhighxhighmaxhigh 為預設值,等同於省略該參數。實務上的生產策略如下:

Effort levelUse whenAvoid when
lowShort answers, extraction, classification, routing, simple transformationsThe task requires multi-step reasoning or high reliability
mediumNormal coding help, document summaries, support investigations, business analysisThe task is trivial or latency-sensitive
highComplex reasoning, difficult coding problems, and agentic tasksYou are running high-volume low-value traffic
xhighLong-running coding agents, repeated tool calling, web search, and large knowledge-base searchThe task has a short context and obvious answer
maxGenuinely frontier problems where marginal quality mattersMost routine production traffic

整體架構模式穩定:將困難任務路由至較高努力等級,簡單任務則使用較低努力等級。

為何透過 CometAPI 使用 Claude Sonnet 5 API?

當團隊希望以單一整合層接入多個模型家族時,CometAPI 很有用。開發者無需為每個模型建立各自的供應商整合,即可在同一帳號與應用架構下,路由 Claude、GPT、Gemini、影像模型、影音模型、嵌入模型與其他 API。

對於 Claude Sonnet 5,CometAPI 提供三個實際優勢:

其一,CometAPI 同時透過 Anthropic 原生 Messages 端點與 OpenAI 相容端點提供 Claude Sonnet 5。這意味著團隊可以在嚴肅的代理工作流程中使用 Claude 原生特性,同時也能在已採用 OpenAI 風格聊天補全的應用中測試 Sonnet 5。

其二,CometAPI 的目錄讓模型比較更簡單。你可以用同一套提示對 Sonnet 5、Sonnet 4.6、Opus 等級模型、GPT 系列、Gemini 系列與專用模型進行對比。這很重要,因為最適合編碼的模型未必最適合文件抽取、客服、延遲敏感聊天或成本敏感批次處理。

其三,CometAPI 有助於生產級路由。你可以先以 Sonnet 5 作為編碼與代理推理的預設模型,再基於可用性、預算、延遲或拒絕行為添加後備規則。一個成熟的 AI 系統不應永遠綁定於單一模型名稱。

如何透過 CometAPI 使用 Claude Sonnet 5 API

以下示例使用伺服器端程式碼。切勿在瀏覽器 JavaScript、行動應用、公開儲存庫或用戶端日誌中暴露你的 CometAPI 金鑰。

第 1 步:建立並儲存你的 CometAPI 金鑰

將你的 API 金鑰存為環境變數:

export COMETAPI_KEY="your_cometapi_key"

在 Windows PowerShell:

$env:COMETAPI_KEY="your_cometapi_key"

第 2 步:選擇合適的端點

當你需要 Claude 原生行為時,使用 POST /v1/messages

https://api.cometapi.com/v1/messages

當你需要 OpenAI 相容聊天時,使用 POST /v1/chat/completions

https://api.cometapi.com/v1/chat/completions

建議:對新的 Claude Sonnet 5 代理系統,先從 /v1/messages 開始。當你已經有基於聊天補全構建的 OpenAI SDK 封裝、模型路由器或多模型評測工具時,使用 /v1/chat/completions

第 3 步:使用 cURL 調用 Claude Sonnet 5

以下是最簡單的原生 Messages API 範例:

curl https://api.cometapi.com/v1/messages \  -H "Authorization: Bearer $COMETAPI_KEY" \  -H "Content-Type: application/json" \  -d '{    "model": "claude-sonnet-5",    "max_tokens": 1200,    "messages": [      {        "role": "user",        "content": "Write a concise migration checklist for moving a Node.js API from Express 4 to Express 5."      }    ]  }'

對於 Sonnet 5,除非當前文件明確支援,否則請避免加入舊有的採樣覆蓋或手動思考配額。讓自適應思考處理推理,並在支援的情況下使用努力程度控制。

第 4 步:搭配 Anthropic SDK 的 Python 範例

許多 Anthropic SDK 工作流程可透過設定 base URL 與 API 金鑰指向 CometAPI。

import osimport anthropic​client = anthropic.Anthropic(    base_url="https://api.cometapi.com",    api_key=os.environ["COMETAPI_KEY"],)​message = client.messages.create(    model="claude-sonnet-5",    max_tokens=1500,    messages=[        {            "role": "user",            "content": (                "Review this deployment plan for a payments API. "                "Return the top risks, missing tests, and rollout checklist."            ),        }    ],)​for block in message.content:    if getattr(block, "type", None) == "text":        print(block.text)

若你的 CometAPI 路徑以與 Anthropic 當前文件相同的格式支援努力程度控制,則可在較困難的任務上添加努力設定:

message = client.messages.create(    model="claude-sonnet-5",    max_tokens=3000,    thinking={"type": "adaptive"},    output_config={"effort": "high"},    messages=[        {            "role": "user",            "content": "Analyze this incident report and propose a root-cause investigation plan.",        }    ],)

由於供應商與聚合器的綱要可能演進,請先在測試環境驗證努力參數,再移至生產環境。若某路徑拒絕 output_config,請移除該欄位或使用當前 CometAPI 文件記載的參數格式。

第 5 步:OpenAI 相容聊天補全範例

若你的應用已使用 OpenAI 相容的聊天補全,請採用此路徑。

curl https://api.cometapi.com/v1/chat/completions \
  -H "Authorization: Bearer $COMETAPI_KEY" \
  -H "Content-Type": "application/json" \
  -d '{
    "model": "claude-sonnet-5",
    "messages": [
      {
        "role": "system",
        "content": "You are a senior backend engineer. Be precise and practical."
      },
      {
        "role": "user",
        "content": "Design a retry strategy for a webhook delivery service. Include database fields and failure states."
      }
    ],
    "max_completion_tokens": 1800,
    "stream": false
  }'

OpenAI 相容路徑在可攜性方面表現出色,但請不要假設每個 Claude 原生功能都能完美對應聊天補全。針對進階 Claude 工作流程,優先使用 Messages 端點。

第 6 步:串流範例

串流可改善聊天、編碼助理與長報告的感知延遲。

const response = await fetch("https://api.cometapi.com/v1/messages", {
  method: "POST",
  headers: {
    Authorization: `Bearer ${process.env.COMETAPI_KEY}`,
    "Content-Type": "application/json",
  },
  body: JSON.stringify({
    model: "claude-sonnet-5",
    max_tokens: 2500,
    stream: true,
    messages: [
      {
        role: "user",
        content: "Write a production runbook for investigating elevated API error rates.",
      },
    ],
  }),
});

if (!response.ok) {
  throw new Error(`Stream failed: ${response.status} ${await response.text()}`);
}

for await (const chunk of response.body) {
  process.stdout.write(Buffer.from(chunk).toString("utf8"));
}

在生產環境中,請解析伺服器傳送事件(SSE),而非直接輸出原始資料塊。同時處理網路斷線、部分回應、重試等冪等性,以及用戶取消。

電腦操作/代理流程:結合工具進行瀏覽器/終端控制。Sonnet 5 在這方面表現出色。

CometAPI 最佳實踐

  • 監控用量儀表板與成本。
  • 進行 A/B 測試(例如 Sonnet 5 vs. Opus 4.8)。
  • 設定預算警報。
  • 透過指向 CometAPI 端點,應用於 Claude Code 整合。

Claude Sonnet 5 的提示撰寫建議

當任務明確且成功標準清楚時,Claude Sonnet 5 的表現最佳。

用於編碼與代理任務的結構:

Goal: [what should be achieved]
Context: [repo, system, constraints, known facts]
Inputs: [files, logs, tickets, data]
Rules: [must not change, security requirements, output format]
Success criteria: [tests pass, plan quality, risk list, exact schema]
Output: [what you want returned]

例如:

Goal: Find likely causes of increased checkout API latency.
Context: The service is Node.js, PostgreSQL, Redis, and Stripe webhooks.
Inputs: I will provide logs, traces, recent deploy notes, and database metrics.
Rules: Do not invent metrics. Separate evidence from hypotheses.
Success criteria: Return the top 5 likely causes, what evidence supports each one, and the next query or dashboard to check.
Output: A table followed by a 30-minute investigation plan.

CometAPI 上的 Claude Sonnet 5 定價

此文撰寫時查詢的 CometAPI 目錄顯示 claude-sonnet-5 的價格為:

Price itemCometAPI catalog value checked
Input tokens$1.60 per 1M tokens
Output tokens$8.00 per 1M tokens
Model IDclaude-sonnet-5
Availabilityupcoming: false in the live catalog

在對外發佈價格前,請始終於 CometAPI 儀表板驗證當前定價。模型價格可能變更,企業協議也可能與公開目錄不同。

成本估算範例

def estimate_sonnet5_cost(input_tokens, output_tokens):
    input_price_per_million = 1.60
    output_price_per_million = 8.00

    input_cost = (input_tokens / 1_000_000) * input_price_per_million
    output_cost = (output_tokens / 1_000_000) * output_price_per_million
    return round(input_cost + output_cost, 6)


print(estimate_sonnet5_cost(input_tokens=120_000, output_tokens=8_000))
print("Expected output: 0.256")

若一次長上下文分析使用 120,000 個輸入 tokens 與 8,000 個輸出 tokens,則按查詢的 CometAPI 目錄價格估算,成本約為 $0.256。此估算未包含任何額外平台費用、折扣、稅費或未來價格變動。

對代理工作流程,也請衡量「每個完成任務的成本」。若高努力等級的 Sonnet 5 能在一次執行中完成工單,可能比低成本模型多次重試與人工更正後的總成本更低。

Claude Sonnet 4.6 遷移指南

遷移並不複雜,但需要注意不相容變更。

Sonnet 4.6 與 Sonnet 5 有哪些差異?

AreaClaude Sonnet 4.6Claude Sonnet 5Migration recommendation
Model IDExisting Sonnet 4.6 routeclaude-sonnet-5 on CometAPIDo not switch all traffic at once; stage rollout
ContextSmaller than Sonnet 5 in current docs1M-token contextRebuild context packing and retrieval tests
TokenizerPrevious tokenizerNew tokenizer; about 30% more tokens for same text in migration notesRecount prompts, cached prefixes, chunks, and cost forecasts
Thinking controlManual extended thinking patterns may existAdaptive thinking on by default; manual budgets removedRemove thinking.budget_tokens style payloads
EffortLess central in older workflowsUse effort for reasoning intensityAdd route policy by task difficulty
SamplingSome workflows may use temperature/top-p/top-kNon-default sampling parameters can return 400Remove unsupported sampling overrides
Coding performanceStrong previous baselineBetter on key agentic coding and terminal benchmarksRe-run internal coding evals before default migration
Safety behaviorOlder refusal and safeguard profileUpdated refusal and cyber safeguard behaviorTest support, security, and policy-sensitive prompts

遷移檢查清單:

  1. 更新模型名稱:將 "claude-sonnet-4-6" 改為 "claude-sonnet-5"
  2. 分詞器與成本:重新測試提示並重新計算 tokens。預期約增加 30%。
  3. 思考設定:以自適應(thinking: {type: "adaptive"})+ 努力等級取代舊的擴展思考。手動 budget_tokens 已棄用/移除。
  4. 採樣參數:移除 temperaturetop_ptop_k——它們已不再受支援(使用 system prompt 控制風格)。
  5. 充分測試:對代理流程、工具使用與輸出解析進行回歸測試,並驗證成本。
  6. 速率限制:可用更高的限制;請檢查你的等級。
  7. 在自適應思考可能需要更多預算時,提高 max_tokens

具後相容性的遷移程式碼

async function runClaudeTask({ prompt, taskType, useSonnet5 = true }) {
  const model = useSonnet5 ? "claude-sonnet-5" : "claude-sonnet-4-6";
  const effort =
    taskType === "coding_agent" || taskType === "security_review"
      ? "high"
      : "medium";

  const body = {
    model,
    max_tokens: taskType === "coding_agent" ? 5000 : 1800,
    thinking: useSonnet5 ? { type: "adaptive" } : undefined,
    messages: [{ role: "user", content: prompt }],
  };

  if (useSonnet5) {
    body.output_config = { effort };
  }

  const response = await fetch("https://api.cometapi.com/v1/messages", {
    method: "POST",
    headers: {
      Authorization: `Bearer ${process.env.COMETAPI_KEY}`,
      "Content-Type": "application/json",
    },
    body: JSON.stringify(body),
  });

  if (response.status === 400 && useSonnet5) {
    // Retry once without optional Sonnet 5-only controls in case the route schema changed.
    delete body.output_config;
    const retry = await fetch("https://api.cometapi.com/v1/messages", {
      method: "POST",
      headers: {
        Authorization: `Bearer ${process.env.COMETAPI_KEY}`,
        "Content-Type": "application/json",
      },
      body: JSON.stringify(body),
    });

    if (!retry.ok) {
      throw new Error(`Retry failed: ${retry.status} ${await retry.text()}`);
    }

    return retry.json();
  }

  if (!response.ok) {
    throw new Error(`Claude request failed: ${response.status} ${await response.text()}`);
  }

  return response.json();
}

此模式可讓你在不讓應用變得脆弱的情況下測試 Sonnet 5。你可以保留後備模型、在發生綱要錯誤時移除可選欄位,並將困難工作負載路由至較高努力等級。

是否有免費的 Claude Sonnet 5 API?

目前沒有可靠的公開證據顯示 Anthropic 提供無限制的免費 Claude Sonnet 5 API。但開發者可透過 CometAPI 的免費試用額度開始測試 Claude Sonnet 5。建立 CometAPI 帳號後,新用戶可獲得 $1 的免費額度,用於探索支援的模型並進行初步 API 測試,之後再增加預算。

關於 Claude Sonnet 5 API 的常見問題

什麼是 Claude Sonnet 5 API?

Claude Sonnet 5 API 是 Anthropic 的 Sonnet 5 模型開發介面,一個面向編碼、代理、工具使用、長上下文推理、文件分析與專業工作的高效能 AI 模型。

如何透過 CometAPI 使用 Claude Sonnet 5 API?

使用 CometAPI 模型 ID claude-sonnet-5。若需 Claude 原生行為,將請求發送至 POST https://api.cometapi.com/v1/messages。若需 OpenAI 相容聊天,使用 POST https://api.cometapi.com/v1/chat/completions

Claude Sonnet 5 有哪些新特性?

Claude Sonnet 5 在代理編碼與工具使用上更強,提供 1M-token 上下文視窗、預設自適應思考、努力程度控制、新分詞器,以及針對資安相關與高風險請求的更新防護。

Claude Sonnet 5 是否支援自適應思考?

是的。Claude Sonnet 5 預設開啟自適應思考。開發者不應再使用舊的手動擴展思考配額;請改用努力程度控制(在支援的路徑上)。

為何新的 Claude Sonnet 5 分詞器很重要?

新分詞器對相同文本可產生約比 Claude Sonnet 4.6 多 30% 的 tokens。這會影響成本、上下文打包、提示快取、切塊與 max_tokens 規劃。

CometAPI vs. 直接使用 Anthropic:哪個更好

CometAPI 提供統一存取、更低價格與更容易的多模型實驗——對大多數開發者而言是理想選擇。

我應該立即從 Claude Sonnet 4.6 遷移到 Claude Sonnet 5 嗎?

分階段遷移。移除不受支援的參數、重新計算 tokens、運行內部評測、監控成本與拒絕行為、保留 Sonnet 4.6 作為後備,然後逐步將更多生產流量導向 Sonnet 5。

最終結語

Claude Sonnet 5 API 是 2026 年最重要的開發者模型發佈之一,因為它將 Sonnet 級模型推得更深入代理工作。最強的使用場景包括編碼代理、終端工作流程、長上下文分析、工具使用、多模態文件推理與專業自動化。此次遷移也不僅是更改模型名稱:Sonnet 5 帶來新的分詞器、預設自適應思考、基於努力的控制、變更的採樣行為與更新的資安防護。

建議:今天就從 CometAPI 開始,無縫存取 Sonnet 5(以及 500+ 其他模型),享有免費額度、更低成本與統一管理。在 CometAPI 註冊,數分鐘內完成整合,並自信擴展。

準備好將 AI 開發成本降低 20% 了嗎?

幾分鐘內免費開始。包含免費試用點數。無需信用卡。

閱讀更多