Claude Chat Completion API 申請及使用
Anthropic Claude 是一款非常強大的 AI 對話系統,只要輸入提示詞,就能在短短幾秒內生成流暢自然的回覆。Claude 以其出色的語言理解和生成能力在業界獨樹一幟,如今,Claude 早已在各個產業和領域廣泛應用,其影響力愈發顯著。無論是日常對話、創意寫作,還是專業諮詢、程式編寫,Claude 都能提供令人驚嘆的智慧協助,極大地提高了人類的工作效率和創造力。
本文檔主要介紹 Claude Chat Completion API 操作的使用流程,利用它我們可以輕鬆使用官方 Claude 的對話功能。
¶ Claude Fable 5.2
使用完整型號 claude-fable-5-2。該型號適合複雜推理和長程任務;需要原生思考內容區塊與工具互動時,優先使用 Messages。自適應思考持續開啟,省略 temperature、top_p、top_k,工具選擇使用 auto,不要強制指定工具。max_tokens 同時涵蓋思考和最終文字。目前不提供此型號的 Responses 和 Count Tokens 介面。
按目前最大方案(142,800 Credits/$13,584)換算,Fable 5.2 一般輸入為 $3.20、輸出為 $16/百萬 token;快取讀取為 $0.08,5 分鐘/1 小時快取寫入分別為 $4/$6.40/百萬 token。上述價格為官方標準 API 單價的 40%(便宜 60%);其他方案及帳戶額外優惠請以模型定價頁和帳單為準。
¶ 申請流程
要使用 Claude Chat Completion API,首先到 AI 聚合控制台 取得您的 API Token,留作備用。

如果你尚未登入或註冊,會自動跳轉到登入頁面邀請你註冊和登入,完成後會自動返回目前頁面。
通用應用程式的 API Key 可用於帳號已開放的服務;專用應用程式的 Key 按該應用程式的服務範圍使用。請檢查 Key 的權限、有效期和限額,並確認應用程式餘額足以支付本次請求。可用試用額度以帳號顯示為準,餘額不足時點擊「儲值」按鈕即可。
📘 完整文件:Claude Chat Completion API →
¶ 基本使用
接下來就可以在介面上填寫對應的內容,如圖所示:

在第一次使用該介面時,我們至少需要填寫三個內容,一個是 authorization,直接在下拉式選單裡面選擇即可。另一個參數是 model,可選 claude-opus-5-5、claude-fable-5-1 等公開型號;原 claude-fable-5 仍可繼續呼叫。最後一個參數是 messages,它是提問詞陣列,每個元素包含 role 和 content;role 支援 user、assistant、system,content 是具體內容。需要完整的 Claude 思考內容區塊、簽章與原生工具語意時,仍請使用 Messages API。
同時您可以注意到右側有對應的呼叫程式碼生成,您可以複製程式碼直接執行,也可以直接點擊「Try」按鈕進行測試。
常用選用參數:
max_tokens:限制單次回覆的最大 token 數。temperature:生成隨機性,介於 0-2 之間,值越大越發散。n:一次生成多少條候選回覆。response_format:返回格式設定。
claude-opus-5-5 支援一般與串流式 Chat Completions;該型號只允許 n=1。不要為它設定低於 1 的 temperature 或非預設 top_p,工具呼叫請使用 tool_choice: "auto",不要強制指定工具。Chat 相容介面不會返回原生思考內容區塊。

呼叫之後,我們發現返回結果如下:
{
"id": "msg_bdrk_01Q6WN27v95ypCa1kbanAQ6K",
"model": "claude-opus-4-8",
"object": "chat.completion",
"created": 1768619365,
"choices": [
{
"index": 0,
"message": {
"role": "assistant",
"content": "Hello! How can I help you today?"
},
"finish_reason": "stop"
}
],
"usage": {
"prompt_tokens": 8,
"completion_tokens": 12,
"total_tokens": 20,
"prompt_tokens_details": {
"cached_tokens": 0,
"cache_write_tokens": 0
},
"completion_tokens_details": {
"reasoning_tokens": 0
}
}
}
返回結果一共有多個欄位,介紹如下:
id,生成此次對話任務的 ID,用於唯一標識此次對話任務。model,選擇的 Claude 官網模型。choices,Claude 針對提問詞給予的回答資訊。usage:針對本次問答的 token 統計資訊。
在 Chat Completions 格式中,usage.prompt_tokens 是輸入總量;prompt_tokens_details.cached_tokens 與 prompt_tokens_details.cache_write_tokens 分別記錄快取讀取和寫入明細。completion_tokens_details.reasoning_tokens 是 completion_tokens 的子集,計算總量或費用時不要再次相加。非串流式回應還可能返回 usage.cost 物件,其中 amount 是實際額度消耗、currency 是計量單位,list_amount 是折扣前金額(如有)。
Chat-compatible 的欄位名稱是 reasoning_tokens;原生 Messages API 使用 output_tokens_details.thinking_tokens。兩種協定的傳輸結構不同,用戶端不應混用欄位名稱。
其中 choices 包含了 Claude 的回答資訊,它裡面的 choices 是 Claude 回答的具體資訊,可以發現如圖所示。

可以看到,choices 裡面的 content 欄位包含了 Claude 回覆的具體內容。
¶ 串流式回應
該介面也支援串流式回應,這對網頁串接十分有用,可以讓網頁實現逐字顯示效果。
如果想串流式返回回應,可以更改請求標頭裡面的 stream 參數,修改為 true。
修改如圖所示,不過呼叫程式碼需要有對應的更改才能支援串流式回應。

Python 範例呼叫程式碼:
import requests
url = "https://api.yxai-tech.top/v1/chat/completions"
headers = {
"accept": "application/json",
"authorization": "Bearer {token}",
"content-type": "application/json"
}
payload = {
"model": "claude-opus-4-20250514",
"messages": [{"role":"user","content":"Hello"}],
"stream": True
}
response = requests.post(url, json=payload, headers=headers)
print(response.text)
輸出效果如下:
data: {"id": "msg_bdrk_01LPPqDjLKMgfSwTRMRty9VT", "object": "chat.completion.chunk", "created": 1768619445, "model": "claude-opus-4-20250514", "system_fingerprint": null, "choices": [{"delta": {"content": "", "role": "assistant"}, "logprobs": null, "finish_reason": null, "index": 0}], "usage": null}
data: {"id": "msg_bdrk_01LPPqDjLKMgfSwTRMRty9VT", "object": "chat.completion.chunk", "created": 1768619445, "model": "claude-opus-4-20250514", "system_fingerprint": null, "choices": [{"delta": {"content": ""}, "logprobs": null, "finish_reason": null, "index": 0}], "usage": null}
data: {"id": "msg_bdrk_01LPPqDjLKMgfSwTRMRty9VT", "object": "chat.completion.chunk", "created": 1768619445, "model": "claude-opus-4-20250514", "system_fingerprint": null, "choices": [{"delta": {"content": "Hello!"}, "logprobs": null, "finish_reason": null, "index": 0}], "usage": null}
data: {"id": "msg_bdrk_01LPPqDjLKMgfSwTRMRty9VT", "object": "chat.completion.chunk", "created": 1768619445, "model": "claude-opus-4-20250514", "system_fingerprint": null, "choices": [{"delta": {"content": " How can I help you"}, "logprobs": null, "finish_reason": null, "index": 0}], "usage": null}
data: {"id": "msg_bdrk_01LPPqDjLKMgfSwTRMRty9VT", "object": "chat.completion.chunk", "created": 1768619445, "model": "claude-opus-4-20250514", "system_fingerprint": null, "choices": [{"delta": {"content": " today?"}, "logprobs": null, "finish_reason": null, "index": 0}], "usage": null}
data: {"id": "msg_bdrk_01LPPqDjLKMgfSwTRMRty9VT", "object": "chat.completion.chunk", "created": 1768619445, "model": "claude-opus-4-20250514", "system_fingerprint": null, "choices": [{"delta": {}, "logprobs": null, "finish_reason": "stop", "index": 0}], "usage": null}
data: {"id": "msg_bdrk_01LPPqDjLKMgfSwTRMRty9VT", "object": "chat.completion.chunk", "created": 1768619445, "model": "claude-opus-4-20250514", "system_fingerprint": null, "choices": [], "usage": {"prompt_tokens": 8, "completion_tokens": 12, "total_tokens": 20, "prompt_tokens_details": {"cached_tokens": 0, "cache_write_tokens": 0}, "completion_tokens_details": {"reasoning_tokens": 0}}}
data: [DONE]
可以看到,回應裡面有許多 data,data 裡面的 choices 即為最新的回答內容,與上文介紹的內容一致。choices 是新增的回答內容,您可以根據結果來對接到您的系統中。同時串流回應的結束是根據 data 的內容來判斷的,如果內容為 [DONE],則表示串流回應回答已經全部結束。回傳的 data 結果一共有多個欄位,介紹如下:
id,產生此次對話任務的 ID,用於唯一識別此次對話任務。model,選擇的 Claude 官網模型。choices,Claude 針對提問詞給予的回答資訊。
JavaScript 也是支援的,例如 Node.js 的串流呼叫程式碼如下:
const options = {
method: "post",
headers: {
accept: "application/json",
authorization: "Bearer {token}",
"content-type": "application/json",
},
body: JSON.stringify({
model: "claude-opus-4-20250514",
messages: [{ role: "user", content: "Hello" }],
stream: true,
}),
};
fetch("https://api.yxai-tech.top/v1/chat/completions", options)
.then((response) => response.json())
.then((response) => console.log(response))
.catch((err) => console.error(err));
Java 範例程式碼:
JSONObject jsonObject = new JSONObject();
jsonObject.put("model", "claude-opus-4-20250514");
jsonObject.put("messages", [{"role":"user","content":"Hello"}]);
jsonObject.put("stream", true);
MediaType mediaType = "application/json; charset=utf-8".toMediaType();
RequestBody body = jsonObject.toString().toRequestBody(mediaType);
Request request = new Request.Builder()
.url("https://api.yxai-tech.top/v1/chat/completions")
.post(body)
.addHeader("accept", "application/json")
.addHeader("authorization", "Bearer {token}")
.addHeader("content-type", "application/json")
.build();
OkHttpClient client = new OkHttpClient();
Response response = client.newCall(request).execute();
System.out.print(response.body!!.string())
其他語言可以另外自行改寫,原理都是一樣的。
¶ 多輪對話
如果您想要對接多輪對話功能,需要對 messages 欄位上傳多個提問詞,多個提問詞的具體範例如下圖所示:

Python 範例呼叫程式碼:
import requests
url = "https://api.yxai-tech.top/v1/chat/completions"
headers = {
"accept": "application/json",
"authorization": "Bearer {token}",
"content-type": "application/json"
}
payload = {
"model": "claude-opus-4-20250514",
"messages": [{"role":"user","content":"Hello"},{"role":"assistant","content":"Hello! How can I help you today?"},{"role":"user","content":"What I say just now?"}]
}
response = requests.post(url, json=payload, headers=headers)
print(response.text)
透過上傳多個提問詞,就可以輕鬆實現多輪對話,可以得到如下回答:
{
"id": "msg_bdrk_01Y1wfQmd89g968TVbFu57Yc",
"model": "claude-opus-4-20250514",
"object": "chat.completion",
"created": 1768619674,
"choices": [
{
"index": 0,
"message": {
"role": "assistant",
"content": "You said \"Hello\" - that was your first message to me in our conversation."
},
"finish_reason": "stop"
}
],
"usage": {
"prompt_tokens": 29,
"completion_tokens": 20,
"total_tokens": 49,
"prompt_tokens_details": {
"cached_tokens": 0,
"cache_write_tokens": 0
},
"completion_tokens_details": {
"reasoning_tokens": 0
}
}
}
可以看到,choices 包含的資訊與基本使用的內容是一致的,這個包含了 Claude 針對多個對話進行回覆的具體內容,這樣就可以根據多個對話內容來回答對應的問題了。
¶ 深度思考
新一代 Claude 模型可能按模型預設策略進行推理,不需要透過 -thinking 模型後綴觸發。Chat-compatible 回應使用 OpenAI 相容的 usage 欄位 completion_tokens_details.reasoning_tokens。reasoning_tokens 已包含在 completion_tokens 中,請勿重複相加。推理與可見正文共用輸出 token 上限,因此 max_tokens 較小時可能出現正文為空或被截斷;遇到這種情況請提高輸出預算,或在所用模型支援時選擇較低推理投入。
如果需要原生 thinking、output_config.effort、thinking 內容區塊及簽章回傳,請使用 /v1/messages。Messages 對應的 usage 欄位是 output_tokens_details.thinking_tokens,不要與 Chat-compatible 的 completion_tokens_details.reasoning_tokens 混用。
¶ 視覺模型
claude-sonnet-4-20250514 是 Claude 開發的多模態大型語言模型,它在 claude-4 的基礎上增加了視覺理解能力。這個模型可以同時處理文字和影像輸入,實現了跨模態的理解和生成。
使用 claude-sonnet-4-20250514 模型的文字處理是與上文的基本使用內容一致的,下面將簡要介紹一下如何使用模型的影像處理能力。
使用 claude-sonnet-4-20250514 模型的影像處理能力主要是透過在原有的 content 內容基礎上新增一個 type 欄位,透過該欄位可以知道上傳的是文字還是圖片,從而使用 claude-sonnet-4-20250514 模型的影像處理能力,下面主要講述採用 Curl 和 Python 兩種方式來呼叫該功能。
- Curl 指令碼方式
curl -X POST 'https://api.yxai-tech.top/v1/chat/completions' \
-H 'accept: application/json' \
-H 'authorization: Bearer {token}' \
-H 'content-type: application/json' \
-d '{
"model": "claude-sonnet-4-20250514",
"messages": [
{
"role": "user",
"content": [
{
"type": "text",
"text": "What'\''s in this image?"
},
{
"type": "image_url",
"image_url": {
"url": "https://cdn.acedata.cloud/ueugot.png"
}
}
]
}
]
}'
- Python 指令碼方式
import requests
url = "https://api.yxai-tech.top/v1/chat/completions"
headers = {
"accept": "application/json",
"authorization": "Bearer {token}",
"content-type": "application/json"
}
payload = {
"model": "claude-sonnet-4-20250514",
"messages": [
{
"role": "user",
"content": [
{
"type": "text", "text": "What's in this image?"
},
{
"type": "image_url",
"image_url": {
"url": "https://cdn.acedata.cloud/ueugot.png"
}
},
],
}
]
}
response = requests.post(url, json=payload, headers=headers)
print(response.text)
然後可以得到下面的結果,結果裡面的欄位資訊是與上文一致的,具體如下:
{
"id": "msg_bdrk_01NCrxpZmV17bhQJJRQEFEb9",
"model": "claude-sonnet-4-20250514",
"object": "chat.completion",
"created": 1768628904,
"choices": [
{
"index": 0,
"message": {
"role": "assistant",
"content": "This image shows an API request configuration interface for what appears to be an AI chat completion service. Here are the key elements:\n\n**Request Body Parameters:**\n\n1. **model** (required string) - Set to \"claude-opus-4-202505...\" - specifies which AI model to use\n\n2. **messages** (required array) - Contains the conversation history with:\n - **role** (required string) - Set to \"user\" \n - **content** (required string) - Contains \"Hello\" as the message content\n\n3. **stream** (boolean) - Set to \"true\" - enables partial message deltas like in ChatGPT\n\n4. **max_tokens** (number) - Field for setting maximum tokens that can be generated in the response\n\n5. **n** (number) - Specifies how many chat completion choices to generate for each input\n\nThe interface has a dark theme with white text on black/dark gray backgrounds. There's a \"Fill Example\" button at the bottom right and various dropdown menus and input fields for configuring the API request parameters. A red trash/delete icon is visible, likely for removing message entries."
},
"finish_reason": "stop"
}
],
"usage": {
"prompt_tokens": 1570,
"completion_tokens": 252,
"total_tokens": 1822,
"prompt_tokens_details": {
"cached_tokens": 0,
"cache_write_tokens": 0
},
"completion_tokens_details": {
"reasoning_tokens": 0
}
}
}
可以看到回答的內容是基於圖片進行回答的,因此透過上述兩種方式可以輕鬆使用 claude-3-7-sonnet-20250219 模型的文字和影像處理能力。
¶ 錯誤處理
在呼叫 API 時,如果遇到錯誤,API 會回傳相應的錯誤代碼和資訊。例如:
400 token_mismatched:錯誤的請求,可能是因為缺少參數或參數無效。400 api_not_implemented:錯誤的請求,可能是因為缺少參數或參數無效。401 invalid_token:未經授權,授權 token 無效或缺失。429 too_many_requests:請求過多,您已超出速率限制。500 api_error:伺服器內部錯誤,伺服器發生問題。
¶ 錯誤回應範例
{
"success": false,
"error": {
"code": "api_error",
"message": "fetch failed"
},
"trace_id": "2cf86e86-22a4-46e1-ac2f-032c0f2a4e89"
}
¶ 結論
透過本文件,您已經了解了如何使用 Claude Chat Completion API 輕鬆實現官方 Claude 的對話功能。希望本文件能幫助您更好地對接和使用該 API。如有任何問題,請隨時聯絡我們的技術支援團隊。

