Anthropic兼容-Messages

阿里云百炼的通义千问系列模型支持 Anthropic API 兼容接口。您只需修改以下三个参数,即可将原有的 Anthropic 应用无缝迁移至阿里云百炼。

  • ANTHROPIC_API_KEY(或 ANTHROPIC_AUTH_TOKEN):替换为百炼 API Key

  • ANTHROPIC_BASE_URL:替换为百炼的兼容端点地址 https://dashscope.aliyuncs.com/apps/anthropic。

  • 模型名称:替换为百炼支持的模型名称(例如 qwen-plus),详情请参考支持的模型

快速接入

import anthropic
import os

client = anthropic.Anthropic(
    api_key=os.getenv("ANTHROPIC_API_KEY"),
    base_url=os.getenv("ANTHROPIC_BASE_URL"),
)
# 迁移至百炼:需配置环境变量 ANTHROPIC_API_KEY 和 ANTHROPIC_BASE_URL,并修改下方的 model 参数。
# 参数兼容性请参考 Anthropic API 兼容性详情
message = client.messages.create(
    model="qwen-plus",   # 设置模型为 qwen-plus
    max_tokens=1024,
    messages=[
        {
            "role": "user",
            "content": [
                {
                    "type": "text",
                    "text": "你是谁?"
                }
            ]
        }
    ]
)
print(message.content[0].text)

支持的模型

百炼提供的 Anthropic API 兼容服务支持通义千问系列的部分模型:

模型系列

支持的模型名称(model)

通义千问Max(不支持思考模式)

qwen3-max-previewqwen-maxqwen-max-latest

更多历史快照模型

qwen-max-0125qwen-max-0919qwen-max-0428qwen-max-0403

通义千问Plus

qwen-plusqwen-plus-latestqwen-plus-2025-09-11qwen-plus-0728qwen-plus-0714qwen-plus-0428

更多历史快照模型

qwen-plus-0125qwen-plus-0112qwen-plus-1220qwen-plus-1127qwen-plus-1125qwen-plus-0919qwen-plus-0806qwen-plus-0723

通义千问Flash

qwen-flashqwen-flash-2025-07-28

通义千问Turbo

qwen-turboqwen-turbo-latestqwen-turbo-0715qwen-turbo-0428

更多历史快照模型

qwen-turbo-0211qwen-turbo-1101qwen-turbo-0919qwen-turbo-0624

通义千问Coder(不支持思考模式)

qwen3-coder-plusqwen3-coder-plus-2025-07-22qwen3-coder-flashqwen3-coder-flash-2025-07-28

模型参数及计费规则请参考模型列表与价格

详细步骤

开通阿里云百炼

如果您是首次访问阿里云百炼服务平台,请按照以下步骤进行开通。

  1. 登录阿里云百炼大模型服务平台

  2. 若页面顶部显示image,需开通阿里云百炼的模型服务,并获得免费额度。如果未显示该消息,则表示您已经开通。

首次开通百炼后,您可领取新人免费额度(有效期:百炼开通后90天内),用于模型推理服务。免费额度领取方法和详情,请查看新人免费额度页面。
说明

超出额度或期限将产生费用,开启免费额度用完即停功能将避免此情况下产生费用,具体费用请以控制台的实际报价和最终账单为准。

配置环境变量

要通过兼容 Anthropic API 的方式,来接入阿里云百炼的模型服务,需要配置以下两个环境变量。

  1. ANTHROPIC_BASE_URL:设置为 https://dashscope.aliyuncs.com/apps/anthropic

  2. ANTHROPIC_API_KEYANTHROPIC_AUTH_TOKEN:设置为阿里云百炼API Key

    ANTHROPIC_API_KEYANTHROPIC_AUTH_TOKEN均可作为接入认证,只需要设置其一即可。本文以ANTHROPIC_API_KEY为例。

macOS

  1. 在终端中执行以下命令,查看默认 Shell 类型。

    echo $SHELL
  2. 根据 Shell 类型设置环境变量,命令如下:

    Zsh

    # 用百炼API KEY代替YOUR_DASHSCOPE_API_KEY
    echo 'export ANTHROPIC_BASE_URL="https://dashscope.aliyuncs.com/apps/anthropic"' >> ~/.zshrc
    echo 'export ANTHROPIC_API_KEY="YOUR_DASHSCOPE_API_KEY"' >> ~/.zshrc

    Bash

    # 用您的百炼API Key代替YOUR_DASHSCOPE_API_KEY
    echo 'export ANTHROPIC_BASE_URL="https://dashscope.aliyuncs.com/apps/anthropic"' >> ~/.bash_profile
    echo 'export ANTHROPIC_API_KEY="YOUR_DASHSCOPE_API_KEY"' >> ~/.bash_profile
  3. 在终端中执行下列命令,使环境变量生效。

    Zsh

    source ~/.zshrc

    Bash

    source ~/.bash_profile
  4. 打开一个新的终端,执行下列命令,查看环境变量是否生效。

    echo $ANTHROPIC_BASE_URL
    echo $ANTHROPIC_API_KEY

Windows

  1. 在 Windows 中,可以通过 CMD 或 PowerShell 将阿里云百炼提供的 Base URL 和API Key设置为环境变量。

    CMD

    1. 在 CMD 中运行以下命令,设置环境变量。

      # 用您的百炼 API Key代替 YOUR_DASHSCOPE_API_KEY
      setx ANTHROPIC_API_KEY "YOUR_DASHSCOPE_API_KEY"
      setx ANTHROPIC_BASE_URL "https://dashscope.aliyuncs.com/apps/anthropic"
    2. 打开一个新的 CMD 窗口,运行以下命令,检查环境变量是否生效。

      echo %ANTHROPIC_API_KEY%
      echo %ANTHROPIC_BASE_URL%

    PowerShell

    1. 在 PowerShell 中运行以下命令,设置环境变量。

      # 用您的百炼 API Key代替 YOUR_DASHSCOPE_API_KEY
      [Environment]::SetEnvironmentVariable("ANTHROPIC_API_KEY", "YOUR_DASHSCOPE_API_KEY", [EnvironmentVariableTarget]::User)
      [Environment]::SetEnvironmentVariable("ANTHROPIC_BASE_URL", "https://dashscope.aliyuncs.com/apps/anthropic", [EnvironmentVariableTarget]::User)
    2. 打开一个新的 PowerShell 窗口,运行以下命令,检查环境变量是否生效。

      echo $env:ANTHROPIC_API_KEY
      echo $env:ANTHROPIC_BASE_URL

API 调用

cURL

curl -X POST "https://dashscope.aliyuncs.com/apps/anthropic/v1/messages" \
  -H "Content-Type: application/json" \
  -H "x-api-key: $ANTHROPIC_API_KEY" \
  -d '{
    "model": "qwen-plus",
    "max_tokens": 1024,
    "stream": true,
    "thinking": {
      "type": "enabled",
      "budget_tokens": 1024
    },
    "system": "You are a helpful assistant",
    "messages": [
        {
            "role": "user",
            "content": [
                {
                    "type": "text",
                    "text": "你是谁?"
                }
            ]
        }
    ]
}'

Python

  1. 安装 Anthropic SDK

    pip install anthropic
  2. 代码示例

    import anthropic
    import os
    
    client = anthropic.Anthropic(
        api_key=os.getenv("ANTHROPIC_API_KEY"),
        base_url=os.getenv("ANTHROPIC_BASE_URL"),
    )
    
    message = client.messages.create(
        model="qwen-plus",
        max_tokens=1024,
        stream=True,
        system="you are a helpful assistant",
        # thinking 参数不支持通义千问-Max 和 通义千问-Coder系列模型
        thinking={
            "type": "enabled",
            "budget_tokens": 1024
        },
        messages=[
            {
                "role": "user",
                "content": [
                    {
                        "type": "text",
                        "text": "你是谁?"
                    }
                ]
            }
        ]
    )
    
    print("=== 思考过程 ===")
    first_text = True
    for chunk in message:
        if chunk.type == "content_block_delta":
            if hasattr(chunk.delta, 'thinking'):
                print(chunk.delta.thinking, end="", flush=True)
            elif hasattr(chunk.delta, 'text'):
                if first_text:
                    print("\n\n=== 回答 ===")
                    first_text = False
                print(chunk.delta.text, end="", flush=True)
    

TypeScript

  1. 安装 Anthropic TypeScript SDK

    npm install @anthropic-ai/sdk
  2. 代码示例

    import Anthropic from "@anthropic-ai/sdk";
    
    async function main() {
      const anthropic = new Anthropic({
        apiKey: process.env.ANTHROPIC_API_KEY,
        baseURL: process.env.ANTHROPIC_BASE_URL,
      });
    
      const stream = await anthropic.messages.create({
        model: "qwen-plus",
        max_tokens: 1024,
        stream: true,
        // thinking 参数不支持通义千问-Max 和 通义千问-Coder系列模型
        thinking: { type: "enabled", budget_tokens: 1024 },
        system: "You are a helpful assistant",
        messages: [{ 
          role: "user", 
          content: [
            {
              type: "text",
              text: "你是谁?"
            }
          ]
        }]
      });
    
      console.log("=== 思考过程 ===");
      let firstText = true;
    
      for await (const chunk of stream) {
        if (chunk.type === "content_block_delta") {
          if ('thinking' in chunk.delta) {
            process.stdout.write(chunk.delta.thinking);
          } else if ('text' in chunk.delta) {
            if (firstText) {
              console.log("\n\n=== 回答 ===");
              firstText = false;
            }
            process.stdout.write(chunk.delta.text);
          }
        }
      }
      console.log();
    }
    
    main().catch(console.error);
    

Anthropic API 兼容性详情

HTTP Header

字段

是否支持

x-api-key

支持

Authorization Bearer

支持

anthropic-beta/anthropic-version

不支持

基础字段

字段

是否支持

说明

示例值

model

支持

模型名称,支持范围见支持的模型

qwen-plus

max_tokens

支持

生成 token 的最大数量

1024

container

不支持

-

-

mcp_servers

不支持

-

-

metadata

不支持

-

-

service_tier

不支持

-

-

stop_sequences

支持

会引发模型停止生成的自定义文本序列

["}"]

stream

支持

流式输出

True

system

支持

系统提示词

You are a helpful assistant

temperature

支持

温度系数,用于控制模型生成文本的多样性,取值范围为 [0,2)

1.0

thinking

支持

思考模式(Qwen-max、Qwen-Coder 系列模型不支持思考模式)

{"type": "enabled", "budget_tokens": 1024}

top_k

支持

生成过程中采样候选集的大小

10

top_p

支持

核采样的概率阈值,控制模型生成文本的多样性,取值范围为 [0,1)

0.1

由于 temperature 与 top_p 均可以控制生成文本的多样性,因此建议只设置其中一个值。更多说明,请参见Temperature 和 top_p

Tool 字段

tools

字段

是否支持

name

支持

input_schema

支持

description

支持

cache_control

支持

tool_choice

是否支持

none

支持

auto

支持

any

支持

tool

支持

Message 字段

字段

类型

子字段

是否支持

content

string

-

支持

array, type="text"

text

支持

cache_control

支持

citations

不支持

array, type="image"

-

不支持

array, type = "document"

-

不支持

array, type = "search_result"

-

不支持

array, type = "thinking"

-

不支持

array, type="redacted_thinking"

-

不支持

array, type = "tool_use"

id

支持

input

支持

name

支持

cache_control

支持

array, type = "tool_result"

tool_use_id

支持

content

支持

cache_control

支持

is_error

不支持

array, type = "server_tool_use"

-

不支持

array, type = "web_search_tool_result"

-

不支持

array, type = "code_execution_tool_result"

-

不支持

array, type = "mcp_tool_use"

-

不支持

array, type = "mcp_tool_result"

-

不支持

array, type = "container_upload"

-

不支持

错误码

HTTP状态码

接口错误码

说明

400

invalid_request_error

请求格式或内容存在问题。下面未列出的其他 4XX 状态代码也可能是此错误类型

401

authentication_error

API Key 存在问题

403

permission_error

API Key 没有使用指定资源的权限

404

not_found_error

未找到请求的资源

413

request_too_large

请求超过了允许的最大字节数。标准 API 端点的最大请求大小为 32 MB

429

rate_limit_error

账户达到了速率限制

500

api_error

系统内部发生了意外错误

529

overloaded_error

API 暂时过载