全部產品
Search
文件中心

Alibaba Cloud Model Studio:Anthropic相容-Messages

更新時間:Jun 25, 2026

通過相容 Anthropic 格式的 Messages API 呼叫模型,查看輸入輸出參數說明及調用樣本。

通過修改以下配置,即可將原有的 Anthropic 應用遷移至阿里雲百鍊:

  • api_key:替換為百鍊 API Key

  • base_url:替換為百鍊的相容端點地址(見下方接入資訊)。

  • model:替換為百鍊支援的模型名稱(例如 qwen3.7-plus)。

重要

百鍊為華北2(北京)、新加坡、中國香港地區推出了業務空間專屬網域名稱,能夠為推理請求提供卓越的效能和更高的穩定性,建議遷移至新網域名稱:

  • 華北2(北京)地區:從 https://dashscope.aliyuncs.com 遷移至 https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com

  • 新加坡地區:從 https://dashscope-intl.aliyuncs.com 遷移至 https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com

  • 中國香港地區:從 https://cn-hongkong.dashscope.aliyuncs.com 遷移至 https://{WorkspaceId}.cn-hongkong.maas.aliyuncs.com

其中 {WorkspaceId} 為您的業務空間 ID,可在百鍊控制台的業務空間詳情頁面查看。現有網域名稱仍可正常使用。

新加坡

SDK 調用配置的 base_urlhttps://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/apps/anthropic

HTTP 要求地址:POST https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/apps/anthropic/v1/messages

調用時請將WorkspaceId替換為真實的業務空間ID

華北2(北京)

SDK 調用配置的 base_urlhttps://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/apps/anthropic

HTTP 要求地址:POST https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/apps/anthropic/v1/messages

調用時請將WorkspaceId替換為真實的業務空間ID

美國(維吉尼亞)

SDK 調用配置的 base_urlhttps://dashscope-us.aliyuncs.com/apps/anthropic

HTTP 要求地址:POST https://dashscope-us.aliyuncs.com/apps/anthropic/v1/messages

德國(法蘭克福)

SDK 調用配置的 base_urlhttps://{WorkspaceId}.eu-central-1.maas.aliyuncs.com/apps/anthropic

HTTP 要求地址:POST https://{WorkspaceId}.eu-central-1.maas.aliyuncs.com/apps/anthropic/v1/messages

調用時請將 {WorkspaceId} 替換為真實的 Workspace ID。

日本(東京)

SDK 調用配置的 base_urlhttps://{WorkspaceId}.ap-northeast-1.maas.aliyuncs.com/apps/anthropic

HTTP 要求地址:POST https://{WorkspaceId}.ap-northeast-1.maas.aliyuncs.com/apps/anthropic/v1/messages

調用時請將WorkspaceId替換為真實的業務空間ID

認證方式:通過 x-api-key 要求標頭或 Authorization: Bearer 要求標頭傳入百鍊 API Key,二者選其一即可。

請求體

基礎調用

Python

import anthropic
import os

client = anthropic.Anthropic(
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    # 請將{WorkspaceId}替換為真實的業務空間ID,各地區URL不同。
    base_url="https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/apps/anthropic",
)

message = client.messages.create(
    model="qwen3.7-plus",
    max_tokens=1024,
    system="You are a helpful assistant",
    messages=[
        {
            "role": "user",
            "content": "你是誰?"
        }
    ],
    thinking={"type": "disabled"},
)

print(message.content[0].text)

TypeScript

import Anthropic from "@anthropic-ai/sdk";

const anthropic = new Anthropic({
  apiKey: process.env.DASHSCOPE_API_KEY,
  // 請將{WorkspaceId}替換為真實的業務空間ID,各地區URL不同。
  baseURL: "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/apps/anthropic",
});

async function main() {
  const message = await anthropic.messages.create({
    model: "qwen3.7-plus",
    max_tokens: 1024,
    system: "You are a helpful assistant",
    messages: [{
      role: "user",
      content: "你是誰?"
    }],
    thinking: { type: "disabled" },
  });

  console.log(message.content[0].text);
}

main().catch(console.error);

curl

curl -X POST "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/apps/anthropic/v1/messages" \
  -H "Content-Type: application/json" \
  -H "x-api-key: $DASHSCOPE_API_KEY" \
  -d '{
    "model": "qwen3.7-plus",
    "max_tokens": 1024,
    "system": "You are a helpful assistant",
    "messages": [
        {
            "role": "user",
            "content": "你是誰?"
        }
    ],
    "thinking": {"type": "disabled"}
}'

流式輸出

Python

import anthropic
import os

client = anthropic.Anthropic(
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    # 請將{WorkspaceId}替換為真實的業務空間ID,各地區URL不同。
    base_url="https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/apps/anthropic",
)

stream = client.messages.create(
    model="qwen3.7-plus",
    max_tokens=1024,
    stream=True,
    messages=[
        {
            "role": "user",
            "content": "請簡單介紹一下人工智慧。"
        }
    ],
    thinking={"type": "disabled"},
)

for chunk in stream:
    if chunk.type == "content_block_delta":
        if hasattr(chunk.delta, 'text'):
            print(chunk.delta.text, end="", flush=True)

TypeScript

import Anthropic from "@anthropic-ai/sdk";

async function main() {
  const anthropic = new Anthropic({
    apiKey: process.env.DASHSCOPE_API_KEY,
    // 請將{WorkspaceId}替換為真實的業務空間ID,各地區URL不同。
    // 請將{WorkspaceId}替換為真實的業務空間ID,各地區URL不同。
  baseURL: "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/apps/anthropic",
  });

  const stream = await anthropic.messages.create({
    model: "qwen3.7-plus",
    max_tokens: 1024,
    stream: true,
    messages: [{
      role: "user",
      content: "請簡單介紹一下人工智慧。"
    }],
    thinking: { type: "disabled" },
  });

  for await (const chunk of stream) {
    if (chunk.type === "content_block_delta" && 'text' in chunk.delta) {
      process.stdout.write(chunk.delta.text);
    }
  }
}

main().catch(console.error);

curl

curl -X POST "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/apps/anthropic/v1/messages" \
  -H "Content-Type: application/json" \
  -H "x-api-key: $DASHSCOPE_API_KEY" \
  --no-buffer \
  -d '{
    "model": "qwen3.7-plus",
    "max_tokens": 1024,
    "stream": true,
    "messages": [
        {
            "role": "user",
            "content": "請簡單介紹一下人工智慧。"
        }
    ],
    "thinking": {"type": "disabled"}
}'

深度思考

Python

import anthropic
import os

client = anthropic.Anthropic(
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    # 請將{WorkspaceId}替換為真實的業務空間ID,各地區URL不同。
    base_url="https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/apps/anthropic",
)

stream = client.messages.create(
    model="qwen3.7-plus",
    max_tokens=2048,
    stream=True,
    thinking={
        "type": "enabled",
        "budget_tokens": 1024
    },
    messages=[
        {
            "role": "user",
            "content": "分析一下量子計算的發展前景。"
        }
    ]
)

for chunk in stream:
    if chunk.type == "content_block_delta":
        if hasattr(chunk.delta, 'thinking'):
            print(chunk.delta.thinking, end="", flush=True)
        elif hasattr(chunk.delta, 'text'):
            print(chunk.delta.text, end="", flush=True)

TypeScript

import Anthropic from "@anthropic-ai/sdk";

async function main() {
  const anthropic = new Anthropic({
    apiKey: process.env.DASHSCOPE_API_KEY,
    // 請將{WorkspaceId}替換為真實的業務空間ID,各地區URL不同。
    // 請將{WorkspaceId}替換為真實的業務空間ID,各地區URL不同。
  baseURL: "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/apps/anthropic",
  });

  const stream = await anthropic.messages.create({
    model: "qwen3.7-plus",
    max_tokens: 2048,
    stream: true,
    thinking: { type: "enabled", budget_tokens: 1024 },
    messages: [{
      role: "user",
      content: "分析一下量子計算的發展前景。"
    }]
  });

  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) {
        process.stdout.write(chunk.delta.text);
      }
    }
  }
}

main().catch(console.error);

curl

curl -X POST "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/apps/anthropic/v1/messages" \
  -H "Content-Type: application/json" \
  -H "x-api-key: $DASHSCOPE_API_KEY" \
  -d '{
    "model": "qwen3.7-plus",
    "max_tokens": 2048,
    "stream": true,
    "thinking": {
        "type": "enabled",
        "budget_tokens": 1024
    },
    "messages": [
        {
            "role": "user",
            "content": "分析一下量子計算的發展前景。"
        }
    ]
}'

圖片理解

Python

import anthropic
import os

client = anthropic.Anthropic(
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    # 請將{WorkspaceId}替換為真實的業務空間ID,各地區URL不同。
    base_url="https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/apps/anthropic",
)

stream = client.messages.create(
    model="qwen3.7-plus",
    max_tokens=1024,
    stream=True,
    messages=[
        {
            "role": "user",
            "content": [
                {
                    "type": "image",
                    "source": {
                        "type": "url",
                        "url": "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20250414/mqqmiy/animal_01.jpg",
                    },
                },
                {
                    "type": "text",
                    "text": "描述這張圖片的內容。"
                },
            ],
        }
    ],
    thinking={"type": "disabled"},
)

for chunk in stream:
    if chunk.type == "content_block_delta":
        if hasattr(chunk.delta, 'text'):
            print(chunk.delta.text, end="", flush=True)

TypeScript

import Anthropic from "@anthropic-ai/sdk";

async function main() {
  const anthropic = new Anthropic({
    apiKey: process.env.DASHSCOPE_API_KEY,
    // 請將{WorkspaceId}替換為真實的業務空間ID,各地區URL不同。
    // 請將{WorkspaceId}替換為真實的業務空間ID,各地區URL不同。
  baseURL: "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/apps/anthropic",
  });

  const stream = await anthropic.messages.create({
    model: "qwen3.7-plus",
    max_tokens: 1024,
    stream: true,
    messages: [{
      role: "user",
      content: [
        {
          type: "image",
          source: {
            type: "url",
            url: "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20250414/mqqmiy/animal_01.jpg",
          },
        },
        { type: "text", text: "描述這張圖片的內容。" },
      ],
    }],
    thinking: { type: "disabled" },
  });

  for await (const chunk of stream) {
    if (chunk.type === "content_block_delta" && 'text' in chunk.delta) {
      process.stdout.write(chunk.delta.text);
    }
  }
}

main().catch(console.error);

curl

curl -X POST "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/apps/anthropic/v1/messages" \
  -H "Content-Type: application/json" \
  -H "x-api-key: $DASHSCOPE_API_KEY" \
  -d '{
    "model": "qwen3.7-plus",
    "max_tokens": 1024,
    "stream": true,
    "messages": [
        {
            "role": "user",
            "content": [
                {
                    "type": "image",
                    "source": {
                        "type": "url",
                        "url": "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20250414/mqqmiy/animal_01.jpg"
                    }
                },
                {
                    "type": "text",
                    "text": "描述這張圖片的內容。"
                }
            ]
        }
    ],
    "thinking": {"type": "disabled"}
}'

視頻理解

Python

import anthropic
import os

client = anthropic.Anthropic(
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    # 請將{WorkspaceId}替換為真實的業務空間ID,各地區URL不同。
    base_url="https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/apps/anthropic",
)

stream = client.messages.create(
    model="qwen3.7-plus",
    max_tokens=1024,
    stream=True,
    messages=[
        {
            "role": "user",
            "content": [
                {
                    "type": "video",
                    "source": {
                        "type": "url",
                        "url": "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20251208/zpupby/3e81ef38-98f0-4d55-bbb6-259334ca18d0.mp4",
                    },
                },
                {
                    "type": "text",
                    "text": "描述這段視頻的內容。"
                },
            ],
        }
    ],
    thinking={"type": "disabled"},
)

for chunk in stream:
    if chunk.type == "content_block_delta":
        if hasattr(chunk.delta, 'text'):
            print(chunk.delta.text, end="", flush=True)

TypeScript

import Anthropic from "@anthropic-ai/sdk";

async function main() {
  const anthropic = new Anthropic({
    apiKey: process.env.DASHSCOPE_API_KEY,
    // 請將{WorkspaceId}替換為真實的業務空間ID,各地區URL不同。
    // 請將{WorkspaceId}替換為真實的業務空間ID,各地區URL不同。
  baseURL: "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/apps/anthropic",
  });

  const stream = await anthropic.messages.create({
    model: "qwen3.7-plus",
    max_tokens: 1024,
    stream: true,
    messages: [{
      role: "user",
      content: [
        {
          type: "video",
          source: {
            type: "url",
            url: "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20251208/zpupby/3e81ef38-98f0-4d55-bbb6-259334ca18d0.mp4",
          },
        },
        { type: "text", text: "描述這段視頻的內容。" },
      ],
    }],
    thinking: { type: "disabled" },
  });

  for await (const chunk of stream) {
    if (chunk.type === "content_block_delta" && 'text' in chunk.delta) {
      process.stdout.write(chunk.delta.text);
    }
  }
}

main().catch(console.error);

curl

curl -X POST "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/apps/anthropic/v1/messages" \
  -H "Content-Type: application/json" \
  -H "x-api-key: $DASHSCOPE_API_KEY" \
  -d '{
    "model": "qwen3.7-plus",
    "max_tokens": 1024,
    "stream": true,
    "messages": [
        {
            "role": "user",
            "content": [
                {
                    "type": "video",
                    "source": {
                        "type": "url",
                        "url": "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20251208/zpupby/3e81ef38-98f0-4d55-bbb6-259334ca18d0.mp4"
                    }
                },
                {
                    "type": "text",
                    "text": "描述這段視頻的內容。"
                }
            ]
        }
    ],
    "thinking": {"type": "disabled"}
}'

Function Call

Python

import anthropic
import os

client = anthropic.Anthropic(
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    # 請將{WorkspaceId}替換為真實的業務空間ID,各地區URL不同。
    base_url="https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/apps/anthropic",
)

tools = [
    {
        "name": "get_weather",
        "description": "擷取指定城市的天氣資訊",
        "input_schema": {
            "type": "object",
            "properties": {
                "city": {
                    "type": "string",
                    "description": "城市名稱"
                }
            },
            "required": ["city"]
        }
    }
]

message = client.messages.create(
    model="qwen3.7-plus",
    max_tokens=1024,
    tools=tools,
    messages=[
        {
            "role": "user",
            "content": "杭州今天天氣怎麼樣?"
        }
    ]
)

print(message.content)

TypeScript

import Anthropic from "@anthropic-ai/sdk";

async function main() {
  const anthropic = new Anthropic({
    apiKey: process.env.DASHSCOPE_API_KEY,
    // 請將{WorkspaceId}替換為真實的業務空間ID,各地區URL不同。
    // 請將{WorkspaceId}替換為真實的業務空間ID,各地區URL不同。
  baseURL: "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/apps/anthropic",
  });

  const message = await anthropic.messages.create({
    model: "qwen3.7-plus",
    max_tokens: 1024,
    tools: [
      {
        name: "get_weather",
        description: "擷取指定城市的天氣資訊",
        input_schema: {
          type: "object",
          properties: {
            city: { type: "string", description: "城市名稱" }
          },
          required: ["city"],
        },
      },
    ],
    messages: [{
      role: "user",
      content: "杭州今天天氣怎麼樣?"
    }],
  });

  console.log(JSON.stringify(message.content, null, 2));
}

main().catch(console.error);

curl

curl -X POST "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/apps/anthropic/v1/messages" \
  -H "Content-Type: application/json" \
  -H "x-api-key: $DASHSCOPE_API_KEY" \
  -d '{
    "model": "qwen3.7-plus",
    "max_tokens": 1024,
    "tools": [
        {
            "name": "get_weather",
            "description": "擷取指定城市的天氣資訊",
            "input_schema": {
                "type": "object",
                "properties": {
                    "city": {
                        "type": "string",
                        "description": "城市名稱"
                    }
                },
                "required": ["city"]
            }
        }
    ],
    "messages": [
        {
            "role": "user",
            "content": "杭州今天天氣怎麼樣?"
        }
    ]
}'

顯式緩衝

Python

import anthropic
import os

client = anthropic.Anthropic(
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    # 請將{WorkspaceId}替換為真實的業務空間ID,各地區URL不同。
    base_url="https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/apps/anthropic",
)

# 類比代碼倉庫內容,需達到最小可緩衝長度(1024 Token)
long_text_content = "<Your Code Here>" * 400


def get_completion(user_input):
    response = client.messages.create(
        # 選擇支援顯式緩衝的模型
        model="qwen3.7-plus",
        max_tokens=1024,
        system=[
            {
                "type": "text",
                "text": long_text_content,
                # 在 text 塊上添加 cache_control 即標記緩衝斷點;也可放在 messages 數組的 content 塊上
                "cache_control": {"type": "ephemeral"},
            }
        ],
        messages=[
            {"role": "user", "content": user_input},
        ],
    )
    return response


# 第一次請求:建立緩衝
first = get_completion("這段代碼的內容是什麼")
print(f"建立緩衝 Token:{first.usage.cache_creation_input_tokens}")
print(f"命中緩衝 Token:{first.usage.cache_read_input_tokens}")
print("=" * 20)
# 第二次請求:長內容相同,僅修改提問 → 命中緩衝
second = get_completion("這段代碼可以怎麼最佳化")
print(f"建立緩衝 Token:{second.usage.cache_creation_input_tokens}")
print(f"命中緩衝 Token:{second.usage.cache_read_input_tokens}")

TypeScript

import Anthropic from "@anthropic-ai/sdk";

const client = new Anthropic({
  apiKey: process.env.DASHSCOPE_API_KEY,
  // 請將{WorkspaceId}替換為真實的業務空間ID,各地區URL不同。
  baseURL: "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/apps/anthropic",
});

// 類比代碼倉庫內容,需達到最小可緩衝長度(1024 Token)
const longTextContent = "<Your Code Here>".repeat(400);

async function getCompletion(userInput) {
  return client.messages.create({
    // 選擇支援顯式緩衝的模型
    model: "qwen3.7-plus",
    max_tokens: 1024,
    system: [
      {
        type: "text",
        text: longTextContent,
        // 在 text 塊上添加 cache_control 即標記緩衝斷點;也可放在 messages 數組的 content 塊上
        cache_control: { type: "ephemeral" },
      },
    ],
    messages: [{ role: "user", content: userInput }],
  });
}

// 第一次請求:建立緩衝
const first = await getCompletion("這段代碼的內容是什麼");
console.log(`建立緩衝 Token:${first.usage.cache_creation_input_tokens}`);
console.log(`命中緩衝 Token:${first.usage.cache_read_input_tokens}`);
console.log("=".repeat(20));
// 第二次請求:長內容相同,僅修改提問 → 命中緩衝
const second = await getCompletion("這段代碼可以怎麼最佳化");
console.log(`建立緩衝 Token:${second.usage.cache_creation_input_tokens}`);
console.log(`命中緩衝 Token:${second.usage.cache_read_input_tokens}`);

curl

curl -X POST "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/apps/anthropic/v1/messages" \
  -H "Content-Type: application/json" \
  -H "x-api-key: $DASHSCOPE_API_KEY" \
  -d '{
    "model": "qwen3.7-plus",
    "max_tokens": 1024,
    "system": [
      {
        "type": "text",
        "text": "<請在此處放置長度 ≥ 1024 Token 的可緩衝內容>",
        "cache_control": {"type": "ephemeral"}
      }
    ],
    "messages": [
      {"role": "user", "content": "這段代碼的內容是什麼"}
    ]
}'

結構化輸出

Python

import anthropic
import os

client = anthropic.Anthropic(
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    # 請將{WorkspaceId}替換為真實的業務空間ID,各地區URL不同。
    base_url="https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/apps/anthropic",
)

message = client.messages.create(
    model="deepseek-v4-pro",
    max_tokens=1024,
    messages=[
        {
            "role": "user",
            "content": "提取以下郵件的關鍵資訊:張三 (zhangsan@example.com) 對企業版方案感興趣,希望預約下周二下午 2 點的示範。"
        }
    ],
    output_config={
        "format": {
            "type": "json_schema",
            "schema": {
                "type": "object",
                "properties": {
                    "name": {"type": "string"},
                    "email": {"type": "string"},
                    "plan_interest": {"type": "string"},
                    "demo_requested": {"type": "boolean"}
                },
                "required": ["name", "email", "plan_interest", "demo_requested"],
                "additionalProperties": False
            }
        }
    },
)

print(message.content[0].text)

TypeScript

import Anthropic from "@anthropic-ai/sdk";

const anthropic = new Anthropic({
  apiKey: process.env.DASHSCOPE_API_KEY,
  // 請將{WorkspaceId}替換為真實的業務空間ID,各地區URL不同。
  baseURL: "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/apps/anthropic",
});

async function main() {
  const message = await anthropic.messages.create({
    model: "deepseek-v4-pro",
    max_tokens: 1024,
    messages: [{
      role: "user",
      content: "提取以下郵件的關鍵資訊:張三 (zhangsan@example.com) 對企業版方案感興趣,希望預約下周二下午 2 點的示範。"
    }],
    output_config: {
      format: {
        type: "json_schema",
        schema: {
          type: "object",
          properties: {
            name: { type: "string" },
            email: { type: "string" },
            plan_interest: { type: "string" },
            demo_requested: { type: "boolean" }
          },
          required: ["name", "email", "plan_interest", "demo_requested"],
          additionalProperties: false
        }
      }
    }
  });

  console.log(message.content[0].text);
}

main().catch(console.error);

curl

curl -X POST "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/apps/anthropic/v1/messages" \
  -H "Content-Type: application/json" \
  -H "x-api-key: $DASHSCOPE_API_KEY" \
  -d '{
    "model": "deepseek-v4-pro",
    "max_tokens": 1024,
    "messages": [
        {
            "role": "user",
            "content": "提取以下郵件的關鍵資訊:張三 (zhangsan@example.com) 對企業版方案感興趣,希望預約下周二下午 2 點的示範。"
        }
    ],
    "output_config": {
        "format": {
            "type": "json_schema",
            "schema": {
                "type": "object",
                "properties": {
                    "name": {"type": "string"},
                    "email": {"type": "string"},
                    "plan_interest": {"type": "string"},
                    "demo_requested": {"type": "boolean"}
                },
                "required": ["name", "email", "plan_interest", "demo_requested"],
                "additionalProperties": false
            }
        }
    }
}'

model string (必選)

模型名稱,支援範圍如下。

支援的模型列表

千問Max:qwen3.7-max、qwen3.7-max-2026-05-20、qwen3.7-max-2026-06-08、qwen3.6-max-preview、qwen3-max、qwen3-max-2026-01-23、qwen3-max-preview

千問Plus:qwen3.7-plus、qwen3.7-plus-2026-05-26、qwen3.6-plus、qwen3.6-plus-2026-04-02、qwen3.5-plus、qwen3.5-plus-2026-04-20、qwen3.5-plus-2026-02-15、qwen-plus、qwen-plus-latest、qwen-plus-2025-09-11

千問Flash:qwen3.6-flash、qwen3.6-flash-2026-04-16、qwen3.5-flash、qwen3.5-flash-2026-02-23、qwen-flash、qwen-flash-2025-07-28

千問Turbo:qwen-turbo

千問Coder:qwen3-coder-next、qwen3-coder-plus、qwen3-coder-plus-2025-09-23、qwen3-coder-flash

千問VL:qwen3-vl-plus、qwen3-vl-flash、qwen-vl-max、qwen-vl-plus

千問開源模型:qwen3.6-27b、qwen3.5-397b-a17b、qwen3.5-122b-a10b、qwen3.5-27b、qwen3.5-35b-a3b

第三方模型

deepseek-v4-pro、deepseek-v4-flash、deepseek-v3.2、kimi-k2.6、kimi-k2.5、kimi-k2-thinking、glm-5.2、glm-5.1、glm-5、glm-4.7、glm-4.6、MiniMax-M2.5、MiniMax-M2.1

max_tokens integer (必選)

回複內容的最大 Token 數。若產生內容超過此值,產生將提前停止,stop_reasonmax_tokens

max_tokens 不限制思考過程的長度。開啟深度思考時,思考部分的 Token 數由 thinking.budget_tokens 單獨控制。

system string 或 array (可選)

系統提示詞,用於設定模型的角色或行為。system 通過頂層參數傳入,messages 數組中不接受 system 角色。

傳入字串等價於單個 type="text" 的內容塊。當需要為系統提示詞標記顯式緩衝斷點(參見右側"顯式緩衝"樣本)時,必須傳入數組形式。

屬性

type string (必選)

固定為 text

text string (必選)

系統提示詞文本。

cache_control object (可選)

在該內容塊上標記顯式緩衝斷點(參見右側"顯式緩衝"樣本),命中後第二次及之後的請求按緩衝讀取計費。僅包含欄位 type,取值固定為 ephemeral

messages array (必選)

訊息數組,按 user / assistant 交替輪次排列。

messages 數組元素

role string (必選)

訊息角色,可選值:userassistant

content string 或 array (必選)

訊息內容。可以是純文字字串,也可以是結構化內容數組。content 為字串時,等價於單個 type="text" 的內容塊。

content 數組元素類型

文本資訊

屬性

type string (必選)

固定為 text

text string (必選)

常值內容。

cache_control object (可選)

在該文字區塊上標記顯式緩衝斷點(參見右側"顯式緩衝"樣本)。僅包含欄位 type,取值固定為 ephemeral

圖片資訊(需使用視覺模型)

屬性

type string (必選)

固定為 image

source object (必選)

圖片資料來源。

屬性

type string (必選)

取值:url(公網圖片地址)、base64(Base 64 編碼)。

url string

圖片的公網地址。當 typeurl 時必填。

media_type string

圖片的 MIME 類型,如 image/jpeg。當 typebase64 時必填。

data string

Base 64 編碼的圖片資料。當 typebase64 時必填。

視頻資訊(需使用視覺模型)

屬性

type string (必選)

固定為 video

source object (必選)

視頻資料來源。

屬性

type string (必選)

取值:url(公網視頻地址)、base64(Base 64 編碼)。

url string

視頻的公網地址。當 typeurl 時必填。

media_type string

視頻的 MIME 類型,如 video/mp4。當 typebase64 時必填。

data string

Base 64 編碼的視頻資料。當 typebase64 時必填。

工具調用資訊(assistant 角色,模型返回的工具調用指令)

屬性

type string (必選)

固定為 tool_use

id string (必選)

工具調用的唯一標識,用於在後續 tool_result 中關連接果。

name string (必選)

被調用的工具名稱。

input object (必選)

工具調用的入參,結構由 tools 中對應工具的 input_schema 決定。

cache_control object (可選)

在該塊上標記顯式緩衝斷點(參見右側"顯式緩衝"樣本)。僅包含欄位 type,取值固定為 ephemeral。工具調用內容本身會參與緩衝首碼。

工具結果資訊(user 角色,工具執行結果回傳給模型)

屬性

type string (必選)

固定為 tool_result

tool_use_id string (必選)

對應 tool_use 資訊中的 id

content string (必選)

工具執行返回的內容。

cache_control object (可選)

在該工具結果塊上標記顯式緩衝斷點(參見右側"顯式緩衝"樣本)。僅包含欄位 type,取值固定為 ephemeral

stream boolean (可選)

是否啟用流式輸出,預設為 false

temperature number (可選)

控制產生文本的多樣性,取值範圍 [0, 2)。值越大,產生結果越隨機。

說明

該範圍與 Anthropic 官方的 [0.0, 1.0] 不同,從 Anthropic 遷移時請確認該參數取值。

top_p number (可選)

核採樣的機率閾值,控制產生文本的多樣性。

temperaturetop_p 均可控制產生文本的多樣性,建議只設定其中一個值。更多說明請參見概述

top_k integer (可選)

產生過程中採樣候選集的大小。

stop_sequences array (可選)

指定停止產生的文本序列。模型產生到該序列前會停止輸出,且不包含該序列本身。

說明

命中後,響應的 stop_reason 仍為 end_turn,響應不會回填命中的序列。

thinking object (可選)

深度思考配置。開啟後,模型會在產生回複前先進行推理,以提升回答準確度。開啟後,響應會包含 thinking 類型的內容塊。部分模型不支援思考模式。

屬性

type string (必選)

可選值:enabled(開啟思考模式)、disabled(關閉思考模式)。

budget_tokens integer (可選)

思考過程可使用的最大 Token 數,與 max_tokens 互不重疊:本參數限制思考,max_tokens 限制最終回複。預算越大,在複雜問題上的分析越充分。當 typeenabled 時生效。

reasoning_effort string (可選)

控制模型的推理強度。可選值:highmax,預設為 max。支援的模型:deepseek-v4-pro、deepseek-v4-flash。

說明

設為 lowmedium 時會映射為 high,設為 xhigh 時會映射為 max

tools array (可選)

工具定義數組,用於 Function Call 情境。

tools 數組元素

name string (必選)

工具名稱。

description string (可選)

工具的功能描述。

input_schema object (必選)

工具輸入參數的 JSON Schema 定義。

tool_choice object (可選)

工具選擇策略。支援以下值:

  • {"type": "auto"}:模型自行決定是否調用工具(預設)。

  • {"type": "any"}:強制模型調用任意一個工具。

  • {"type": "none"}:禁止模型調用工具。

  • {"type": "tool", "name": "tool_name"}:強制模型調用指定工具。

output_config object (可選)

結構化輸出配置。開啟後,模型將輸出 JSON 字串。不同模型的支援力度不同:

  • 嚴格結構化輸出:適用於 deepseek 系列、glm 系列模型。模型嚴格按照傳入的 JSON Schema 進行強約束輸出,確保欄位類型與層級完全一致。

  • 普通結構化輸出:適用於上述以外的其他模型。Schema 的具體欄位約束預設不生效,API 會自動將其轉換為普通 JSON 模式(僅保證輸出為合法的 JSON 字串)。觸發普通 JSON 模式時,請求必須同時滿足以下兩點約束:1、顯式傳入 output_config 參數;2、systemmessages 的內容中必須包含不區分大小寫 "JSON" 關鍵詞。若提示詞中未包含 "JSON" 關鍵詞,API將拋出異常:'messages' must contain the word 'json' in some form

屬性

format object (必選)

輸出格式定義。

屬性

type string (必選)

取值固定為 json_schema

schema object (必選)

JSON Schema 對象,遵循標準 JSON Schema 規範。需包含 type(資料類型)、properties(欄位定義)、required(必要欄位名數組)、additionalProperties(必須設為 false)等欄位。

非流式響應

響應樣本

{
  "id": "msg_e2898f19-fc0e-4cb3-bd9b-5b7dc4ea3bc9",
  "type": "message",
  "role": "assistant",
  "model": "qwen3.7-plus",
  "content": [
    {
      "type": "thinking",
      "thinking": "讓我分析一下這個問題...",
      "signature": ""
    },
    {
      "type": "text",
      "text": "你好!我是通義千問..."
    }
  ],
  "stop_reason": "end_turn",
  "stop_sequence": null,
  "usage": {
    "input_tokens": 22,
    "output_tokens": 223,
    "cache_creation_input_tokens": 0,
    "cache_read_input_tokens": 0
  }
}

id string

訊息的唯一標識。

type string

固定為 message

role string

固定為 assistant

model string

使用的模型名稱。

content array

內容數組。

content 數組元素類型

文本資訊

屬性

type string

固定為 text

text string

模型產生的文本回複。

思考資訊(開啟深度思考時返回)

屬性

type string

固定為 thinking

thinking string

模型在產生最終回複前的思考過程。

signature string

當前固定為空白字串。

工具調用資訊(Function Call 情境)

屬性

type string

固定為 tool_use

id string

工具調用的唯一標識,用於在後續 tool_result 中關連接果。

name string

被調用的工具名稱。

input object

工具調用的入參。

stop_reason string

停止原因。可選值:end_turn(正常結束)、max_tokens(達到 Token 上限)、tool_use(工具調用)。

stop_sequence string

固定為 null

usage object

Token 用量統計。

說明

流式調用中,message_start 事件的 usage 僅包含 input_tokensoutput_tokens;完整 4 個欄位在 message_delta 事件中返回。

屬性

input_tokens integer

輸入 Token 數量。

output_tokens integer

輸出 Token 數量。

cache_creation_input_tokens integer

緩衝建立消耗的輸入 Token 數量。

cache_read_input_tokens integer

緩衝讀取消耗的輸入 Token 數量。

流式響應

流式響應樣本

{"type":"message_start","message":{"id":"msg_xxx","type":"message","role":"assistant","model":"qwen3.7-plus","content":[],"usage":{"input_tokens":15,"output_tokens":0}}}
{"type":"content_block_start","index":0,"content_block":{"type":"thinking","thinking":"","signature":""}}
{"type":"content_block_delta","index":0,"delta":{"type":"thinking_delta","thinking":"Here's a thinking process:\n\n1. **Analyze User Input:**\n   - **Topic:** 人工智慧 (Artificial Intelligence / AI)\n   - **Request:** 請簡單介紹一下人工智慧。"}}
{"type":"content_block_delta","index":0,"delta":{"type":"signature_delta","signature":""}}
{"type":"content_block_stop","index":0}
{"type":"content_block_start","index":1,"content_block":{"type":"text","text":""}}
{"type":"content_block_delta","index":1,"delta":{"type":"text_delta","text":"人工智慧(Artificial Intelligence,簡稱AI)是電腦科學的重要分支..."}}
{"type":"content_block_stop","index":1}
{"type":"message_delta","delta":{"stop_reason":"end_turn","stop_sequence":null},"usage":{"input_tokens":15,"output_tokens":1078,"cache_creation_input_tokens":0,"cache_read_input_tokens":0}}
{"type":"message_stop"}

message_start

流的第一個事件,標記訊息開始。

屬性

type string

固定為 message_start

message object

初始訊息對象,content 為空白數組,usage 僅含 input_tokensoutput_tokens

content_block_start

每個內容塊開始時發送,標記新內容塊的索引和類型。

屬性

type string

固定為 content_block_start

index integer

內容塊索引,從 0 開始,對應該訊息 content 數組中的位置。

content_block object

內容塊的初始對象。type 取值為 textthinkingtool_usetool_use 類型在此事件中 input 為空白對象,完整入參由後續 content_block_delta 增量拼接。

content_block_delta

內容塊的累加式更新事件。同一內容塊會發送多個該事件。

屬性

type string

固定為 content_block_delta

index integer

所屬內容塊索引。

delta object

增量對象,type 取值:

  • text_delta:文本增量,含 text 欄位。

  • thinking_delta:思考增量,含 thinking 欄位。

  • signature_delta:簽名增量,含 signature 欄位(當前固定為空白字串)。

  • input_json_delta:工具調用入參增量,含 partial_json 欄位。

content_block_stop

內容塊結束事件。

屬性

type string

固定為 content_block_stop

index integer

結束的內容塊索引。

message_delta

訊息級更新事件,在所有內容塊結束後發送,包含停止原因和完整的 Token 用量統計。

屬性

type string

固定為 message_delta

delta object

包含 stop_reasonstop_sequence,取值參見上方非流式響應表格。

usage object

完整的 Token 用量統計,包含 input_tokensoutput_tokenscache_creation_input_tokenscache_read_input_tokens

message_stop

流的最後一個事件,標記訊息結束。

屬性

type string

固定為 message_stop

此外,流式響應還會定期發送 ping 事件({"type":"ping"})用於保持串連活躍,用戶端可忽略。