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,首先到 Ace Data Cloud 控制台 获取您的 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。两种协议的 wire schema 不同,客户端不应混用字段名。

其中 choices 是包含了 Claude 的回答信息,它里面的 choices 是 Claude回答的具体信息,可以发现如图所示。

可以看到,choices 里面的 content 字段包含了 Claude 回复的具体内容。

流式响应

该接口也支持流式响应,这对网页对接十分有用,可以让网页实现逐字显示效果。

如果想流式返回响应,可以更改请求头里面的 stream 参数,修改为 true。

修改如图所示,不过调用代码需要有对应的更改才能支持流式响应。

将 stream 修改为 true 之后,API 将逐行返回对应的 JSON 数据,在代码层面我们需要做相应的修改来获得逐行的结果。

Python 样例调用代码:

import requests

url = "https://api.acedata.cloud/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.acedata.cloud/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.acedata.cloud/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.acedata.cloud/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.acedata.cloud/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.acedata.cloud/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:Bad request, possibly due to missing or invalid parameters.
  • 400 api_not_implemented:Bad request, possibly due to missing or invalid parameters.
  • 401 invalid_token:Unauthorized, invalid or missing authorization token.
  • 429 too_many_requests:Too many requests, you have exceeded the rate limit.
  • 500 api_error:Internal server error, something went wrong on the server.

错误响应示例

{
  "success": false,
  "error": {
    "code": "api_error",
    "message": "fetch failed"
  },
  "trace_id": "2cf86e86-22a4-46e1-ac2f-032c0f2a4e89"
}

结论

通过本文档,您已经了解了如何使用 Claude Chat Completion API 轻松实现官方 Claude 的对话功能。希望本文档能帮助您更好地对接和使用该 API。如有任何问题,请随时联系我们的技术支持团队。