使用 Anthropic 中的 Claude 模型

Vertex AI 上的 Anthropic Claude 模型以 API 形式提供全托管式无服务器模型。如需在 Vertex AI 上使用 Claude 模型,请直接向 Vertex AI API 端点发送请求。由于 Anthropic Claude 模型使用托管式 API,因此无需预配或管理基础设施。

您可以流式传输 Claude 回答,以降低对最终用户延迟的感知度。流式回答使用服务器发送的事件 (SSE) 来逐步流式传输回答。

您可以按实际用量(随用随付)或按固定费用(使用预配吞吐量时)为 Claude 模型付费。如需了解随用随付定价,请参阅 Vertex AI 定价页面上的 Anthropic 的 Claude 模型

可用的 Anthropic Claude 模型

Anthropic 提供了以下模型,可在 Vertex AI 中使用。如需访问 Anthropic Claude 模型,请前往其 Model Garden 模型卡片。

Claude 3.5 Sonnet

Claude 3.5 Sonnet 是 Anthropic 最强大的 AI 模型,可维护 Claude 3 Sonnet(中层模型)的速度和成本。Claude 3.5 Sonnet 展示了生成式 AI 的可能性。Claude 3.5 Sonnet 针对以下应用场景进行了优化:

  • 使用复杂的推理和问题排查功能进行编码,例如编写、编辑和运行代码。

  • 了解用户上下文并编排多步骤工作流,处理来自客户服务的复杂查询。

  • 通过浏览非结构化数据并利用多个工具生成数据洞见,来进行数据科学和分析。

  • 视觉处理,例如解释需要视觉理解的图形和图表。

  • 以更自然、更像人类的语气撰写内容。

前往 Claude 3.5 Sonnet 模型卡片

Claude 3 Opus

Anthropic Claude 3 Opus 是 Anthropic 的第二强大的 AI 模型,在高度复杂的任务上具有出色的表现。它能够处理开放式提示和背后可能的方案,具有出色的流利度和真人理解能力。Claude 3 Opus 针对以下应用场景进行了优化:

  • 任务自动化,例如交互式编码和规划,或跨 API 和数据库运行复杂的操作。

  • 研究和开发任务,例如研究审核、头脑风暴和假设生成以及产品测试。

  • 战略任务,例如图表和图形的高级分析、财务和市场趋势以及预测。

  • 视觉任务,例如处理图片以返回文本输出。此外,还可以分析图表、图形、技术图表、报告和其他直观内容。

前往 Claude 3 Opus 模型卡片

Claude 3 Haiku

Anthropic Claude 3 Haiku 是 Anthropic 最快、最紧凑的视觉和文本模型,能够近乎即时地响应简单的查询,旨在打造模仿人类互动的无缝 AI 体验。Claude 3 Haiku 针对以下应用场景进行了优化:

  • 实时的客户互动和翻译。

  • 内容审核,发现可疑行为或客户请求。

  • 节省费用的任务,例如库存管理以及从非结构化数据中提取知识。

  • 视觉任务,例如处理图片以返回文本输出,分析图表、图形、技术图表、报告和其他视觉内容。

前往 Claude 3 Haiku 模型卡片

Claude 3 Sonnet

Anthropic Claude 3 Sonnet 是 Anthropic 可靠的技能和速度组合。旨在在各种应用场景中可靠地进行扩缩 AI 部署。Claude 3 Sonnet 针对以下应用场景进行了优化:

  • 数据处理,包括检索增强生成 (RAG) 和搜索检索。

  • 销售任务,例如产品推荐、预测和精准营销。

  • 节省时间的任务,例如代码生成、质量控制和图片中的光学字符识别 (OCR)。

  • 视觉任务,例如处理图片以返回文本输出。此外,还可以分析图表、图形、技术图表、报告和其他直观内容。

前往 Claude 3 Sonnet 模型卡片

使用 Claude 模型

您可以使用 Anthropic SDK 或 curl 命令通过以下模型名称向 Vertex AI 端点发送请求:

  • 对于 Claude 3.5 Sonnet,请使用 claude-3-5-sonnet@20240620
  • 对于 Claude 3 Opus,请使用 claude-3-opus@20240229
  • 对于 Claude 3 Haiku,请使用 claude-3-haiku@20240307
  • 对于 Claude 3 Sonnet,请使用 claude-3-sonnet@20240229

由于模型版本之间可能存在差异,我们建议使用包含以 @ 符号开头的后缀的 Anthropic Claude 模型版本(例如 claude-3-5-sonnet@20240620claude-3-haiku@20240307)版本。如果未指定模型版本,则始终使用最新版本。当模型版本更改时,这可能会无意中影响您的工作流。

准备工作

如需将 Anthropic Claude 模型与 Vertex AI 搭配使用,您必须执行以下步骤。必须启用 Vertex AI API (aiplatform.googleapis.com) 才能使用 Vertex AI。如果您已有启用了 Vertex AI API 的项目,则可以使用该项目,而无需创建新项目。

确保您拥有启用 Anthropic Claude 模型所需的权限。如需了解详情,请参阅授予所需权限

  1. 登录您的 Google Cloud 账号。如果您是 Google Cloud 新手,请创建一个账号来评估我们的产品在实际场景中的表现。新客户还可获享 $300 赠金,用于运行、测试和部署工作负载。
  2. In the Google Cloud console, on the project selector page, select or create a Google Cloud project.

    Go to project selector

  3. 确保您的 Google Cloud 项目已启用结算功能

  4. 启用 Vertex AI API。

    启用 API

  5. In the Google Cloud console, on the project selector page, select or create a Google Cloud project.

    Go to project selector

  6. 确保您的 Google Cloud 项目已启用结算功能

  7. 启用 Vertex AI API。

    启用 API

  8. 确保您有权启用 Anthropic Claude 模型并发送提示。如需了解详情,请参阅设置启用 Claude 模型并发送提示所需的权限
  9. 转到以下 Model Garden 模型卡片之一,然后点击启用

使用 Anthropic SDK

您可以使用 Anthropic Claude SDK 向 Anthropic Claude 模型发出 API 请求。如需了解详情,请参阅以下内容:

使用 Anthropic Vertex SDK 对 Claude 模型进行流式调用

以下代码示例使用 Anthropic Vertex SDK 对 Anthropic Claude 模型执行流式调用。

Python

如需了解如何安装或更新 Vertex AI SDK for Python,请参阅安装 Vertex AI SDK for Python。 如需了解详情,请参阅 Python API 参考文档

# TODO(developer): Vertex AI SDK - uncomment below & run
# pip3 install --upgrade --user google-cloud-aiplatform
# gcloud auth application-default login
# pip3 install -U 'anthropic[vertex]'

from anthropic import AnthropicVertex

client = AnthropicVertex(region=region, project_id=project_id)
result = []

with client.messages.stream(
    model="claude-3-5-sonnet@20240620",
    max_tokens=1024,
    messages=[
        {
            "role": "user",
            "content": "Send me a recipe for banana bread.",
        }
    ],
) as stream:
    for text in stream.text_stream:
        print(text, end="", flush=True)
        result.append(text)

使用 Anthropic Vertex SDK 对 Claude 模型进行一元调用

以下代码示例使用 Anthropic Vertex SDK 对 Anthropic Claude 模型执行一元调用。

Python

如需了解如何安装或更新 Vertex AI SDK for Python,请参阅安装 Vertex AI SDK for Python。 如需了解详情,请参阅 Python API 参考文档

# TODO(developer): Vertex AI SDK - uncomment below & run
# pip3 install --upgrade --user google-cloud-aiplatform
# gcloud auth application-default login
# pip3 install -U 'anthropic[vertex]'

from anthropic import AnthropicVertex

client = AnthropicVertex(region=region, project_id=project_id)
message = client.messages.create(
    model="claude-3-5-sonnet@20240620",
    max_tokens=1024,
    messages=[
        {
            "role": "user",
            "content": "Send me a recipe for banana bread.",
        }
    ],
)
print(message.model_dump_json(indent=2))

使用 curl 命令

您可以使用 curl 命令向 Vertex AI 端点发出请求。curl 命令指定要使用的受支持的 Anthropic Claude 模型

由于模型版本之间可能存在差异,我们建议使用包含以 @ 符号开头的后缀的 Anthropic Claude 模型版本(例如 claude-3-5-sonnet@20240620claude-3-haiku@20240307)版本。如果未指定模型版本,则始终使用最新版本。当模型版本更改时,这可能会无意中影响您的工作流。

以下主题介绍如何创建 curl 命令并包含示例 curl 命令。

REST

如需使用 Vertex AI API 测试文本提示,请向发布方模型端点发送 POST 请求。

在使用任何请求数据之前,请先进行以下替换:

  • LOCATION:支持 Anthropic Claude 模型的区域。
    Claude 3.5 Sonnet 可在以下区域使用:
    • us-east5 (Ohio)
    • europe-west1 (Belgium)
    Claude 3 Opus 可在以下区域使用:
    • us-east5 (Ohio)
    Claude 3 Haiku 可在以下区域使用:
    • us-central1 (Iowa)
    • us-east5 (Ohio)
    • europe-west1 (Belgium)
    • europe-west4 (Netherlands)
    Claude 3 Sonnet 可在以下区域使用:
    • us-central1 (Iowa)
    • us-east5 (Ohio)
    • asia-southeast1 (Singapore)
  • MODEL:您要使用的模型名称
  • ROLE:与消息关联的角色。您可以指定 userassistant。第一条消息必须使用 user 角色。 Claude 模型使用交替的 userassistant 回合运行。如果最终消息使用 assistant 角色,则回答内容会立即从该消息中的内容继续。您可以使用它来限制模型的部分回答。
  • STREAM:一个布尔值,用于指定是否流式传输回答。流式传输您的回答,以降低对最终使用延迟的感知度。设置为 true 可流式传输回答,设置为 false 可一次性返回所有回答。
  • CONTENTuserassistant 消息的内容(如文本)。
  • MAX_OUTPUT_TOKENS:回答中可生成的词元数量上限。一个词元约为 3.5 个字符。100 个词元对应大约 60-80 个单词。

    指定较低的值可获得较短的回答,指定较高的值可获得可能较长的回答。

  • TOP_P(可选):Top-p 可更改模型选择输出词元的方式。系统会按照概率从最高(见 top-K)到最低的顺序选择词元,直到所选词元的概率总和等于 top-P 的值。例如,如果词元 A、B 和 C 的概率分别为 0.3、0.2 和 0.1,并且 top-P 值为 0.5,则模型将选择 A 或 B 作为下一个词元(通过温度确定),并会排除 C,将其作为候选词元。

    指定较低的值可获得随机程度较低的回答,指定较高的值可获得随机程度较高的回答。

  • TOP_K(可选):Top-K 可更改模型选择输出词元的方式。如果 top-K 设为 1,表示所选词元是模型词汇表的所有词元中概率最高的词元(也称为贪心解码)。如果 top-K 设为 3,则表示系统将从 3 个概率最高的词元(通过温度确定)中选择下一个词元。

    在每个词元选择步骤中,系统都会对概率最高的 top-K 词元进行采样。然后,系统会根据 top-P 进一步过滤词元,并使用温度采样选择最终的词元。

    指定较低的值可获得随机程度较低的回答,指定较高的值可获得随机程度较高的回答。

HTTP 方法和网址:

POST https://LOCATION-aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/publishers/anthropic/models/MODEL:streamRawPredict

请求 JSON 正文:

{
  "anthropic_version": "vertex-2023-10-16",
  "messages": [
   {
    "role": "ROLE",
    "content": "CONTENT"
   }],
  "max_tokens": MAX_TOKENS,
  "stream": STREAM
}

如需发送请求,请选择以下方式之一:

curl

将请求正文保存在名为 request.json 的文件中,然后执行以下命令:

curl -X POST \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
-H "Content-Type: application/json; charset=utf-8" \
-d @request.json \
"https://LOCATION-aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/publishers/anthropic/models/MODEL:streamRawPredict"

PowerShell

将请求正文保存在名为 request.json 的文件中,然后执行以下命令:

$cred = gcloud auth print-access-token
$headers = @{ "Authorization" = "Bearer $cred" }

Invoke-WebRequest `
-Method POST `
-Headers $headers `
-ContentType: "application/json; charset=utf-8" `
-InFile request.json `
-Uri "https://LOCATION-aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/publishers/anthropic/models/MODEL:streamRawPredict" | Select-Object -Expand Content

您应该收到类似以下内容的 JSON 响应。

示例 curl 命令

MODEL_ID="MODEL"
LOCATION="us-central1"
PROJECT_ID="PROJECT_ID"

curl \
-X POST \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
-H "Content-Type: application/json" \
https://${LOCATION}-aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/${LOCATION}/publishers/anthropic/models/${MODEL_ID}:streamRawPredict -d \
'{
  "anthropic_version": "vertex-2023-10-16",
  "messages": [{
    "role": "user",
    "content": "Hello!"
  }],
  "max_tokens": 50,
  "stream": true}'

工具使用(函数调用)

Anthropic Claude 模型支持工具和函数调用,以增强模型的功能。如需了解详情,请参阅 Anthropic 文档中的工具使用概览

以下示例演示了如何通过 Anthropic SDK 或 curl 命令使用工具。这些示例会搜索旧金山附近当前正在营业的餐厅。

Python

如需了解如何安装或更新 Vertex AI SDK for Python,请参阅安装 Vertex AI SDK for Python。 如需了解详情,请参阅 Python API 参考文档

# TODO(developer): Vertex AI SDK - uncomment below & run
# pip3 install --upgrade --user google-cloud-aiplatform
# gcloud auth application-default login
# pip3 install -U 'anthropic[vertex]'

from anthropic import AnthropicVertex


def tool_use(project_id: str, region: str) -> object:
    client = AnthropicVertex(region=region, project_id=project_id)
    message = client.messages.create(
        model="claude-3-5-sonnet@20240620",
        max_tokens=1024,
        tools=[
            {
                "name": "text_search_places_api",
                "description": "returns information about a set of places based on a string",
                "input_schema": {
                    "type": "object",
                    "properties": {
                        "textQuery": {
                            "type": "string",
                            "description": "The text string on which to search",
                        },
                        "priceLevels": {
                            "type": "array",
                            "description": "Price levels to query places, value can be one of [PRICE_LEVEL_INEXPENSIVE, PRICE_LEVEL_MODERATE, PRICE_LEVEL_EXPENSIVE, PRICE_LEVEL_VERY_EXPENSIVE]",
                        },
                        "openNow": {
                            "type": "boolean",
                            "description": "whether those places are open for business.",
                        },
                    },
                    "required": ["textQuery"],
                },
            }
        ],
        messages=[
            {
                "role": "user",
                "content": "What are some affordable and good Italian restaurants open now in San Francisco??",
            }
        ],
    )
    print(message.model_dump_json(indent=2))
    return message

REST

在使用任何请求数据之前,请先进行以下替换:

  • LOCATION:支持 Anthropic Claude 模型的区域。
    Claude 3.5 Sonnet 可在以下区域使用:
    • us-east5 (Ohio)
    • europe-west1 (Belgium)
    Claude 3 Opus 可在以下区域使用:
    • us-east5 (Ohio)
    Claude 3 Haiku 可在以下区域使用:
    • us-central1 (Iowa)
    • us-east5 (Ohio)
    • europe-west1 (Belgium)
    • europe-west4 (Netherlands)
    Claude 3 Sonnet 可在以下区域使用:
    • us-central1 (Iowa)
    • us-east5 (Ohio)
    • asia-southeast1 (Singapore)
  • MODEL:您要使用的模型名称。
    • 对于 Claude 3 Opus,请使用 claude-3-opus@20240229
    • 对于 Claude 3 Sonnet,请使用 claude-3-sonnet@20240229
    • 对于 Claude 3 Haiku,请使用 claude-3-haiku@20240307
  • ROLE:与消息关联的角色。您可以指定 userassistant。第一条消息必须使用 user 角色。 Claude 模型使用交替的 userassistant 回合运行。如果最终消息使用 assistant 角色,则回答内容会立即从该消息中的内容继续。您可以使用它来限制模型的部分回答。
  • STREAM:一个布尔值,用于指定是否流式传输回答。流式传输您的回答,以降低对最终使用延迟的感知度。设置为 true 可流式传输回答,设置为 false 可一次性返回所有回答。
  • CONTENTuserassistant 消息的内容(如文本)。
  • MAX_OUTPUT_TOKENS:响应中可生成的词元数量上限。一个词元约为 3.5 个字符。100 个词元对应大约 60-80 个单词。

    指定较低的值可获得较短的回答,指定较高的值可获得可能较长的回答。

HTTP 方法和网址:

POST https://LOCATION-aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/publishers/anthropic/models/MODEL:rawPredict

请求 JSON 正文:


{
  "anthropic_version": "vertex-2023-10-16",
  "max_tokens": MAX_TOKENS,
  "stream": STREAM,
  "tools": [
    {
      "name": "text_search_places_api",
      "description": "Returns information about a set of places based on a string",
      "input_schema": {
        "type": "object",
        "properties": {
          "textQuery": {
            "type": "string",
            "description": "The text string on which to search"
          },
          "priceLevels": {
            "type": "array",
            "description": "Price levels to query places, value can be one of [PRICE_LEVEL_INEXPENSIVE, PRICE_LEVEL_MODERATE, PRICE_LEVEL_EXPENSIVE, PRICE_LEVEL_VERY_EXPENSIVE]",
          },
          "openNow": {
            "type": "boolean",
            "description": "Describes whether a place is open for business at
            the time of the query."
          },
        },
        "required": ["textQuery"]
      }
    }
  ],
  "messages": [
    {
      "role": "user",
      "content": "What are some affordable and good Italian restaurants that are open now in San Francisco??"
    }
  ]
}

如需发送请求,请选择以下方式之一:

curl

将请求正文保存在名为 request.json 的文件中,然后执行以下命令:

curl -X POST \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
-H "Content-Type: application/json; charset=utf-8" \
-d @request.json \
"https://LOCATION-aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/publishers/anthropic/models/MODEL:rawPredict"

PowerShell

将请求正文保存在名为 request.json 的文件中,然后执行以下命令:

$cred = gcloud auth print-access-token
$headers = @{ "Authorization" = "Bearer $cred" }

Invoke-WebRequest `
-Method POST `
-Headers $headers `
-ContentType: "application/json; charset=utf-8" `
-InFile request.json `
-Uri "https://LOCATION-aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/publishers/anthropic/models/MODEL:rawPredict" | Select-Object -Expand Content

您应该收到类似以下内容的 JSON 响应。

Anthropic Claude 区域可用性

Claude 3.5 Sonnet 可在以下区域使用:
  • us-east5 (Ohio)
  • europe-west1 (Belgium)
Claude 3 Opus 可在以下区域使用:
  • us-east5 (Ohio)
Claude 3 Haiku 可在以下区域使用:
  • us-central1 (Iowa)
  • us-east5 (Ohio)
  • europe-west1 (Belgium)
  • europe-west4 (Netherlands)
Claude 3 Sonnet 可在以下区域使用:
  • us-central1 (Iowa)
  • us-east5 (Ohio)
  • asia-southeast1 (Singapore)

Anthropic Claude 配额和支持的上下文长度

对于 Claude 模型,可用该模型的每个区域都有配额。配额在每分钟查询次数 (QPM) 和每分钟词元数 (TPM) 中指定。TPM 包括输入和输出词元。

Claude 3.5 Sonnet 的默认配额限制和支持的上下文长度如下:

区域 配额系统 支持的上下文长度
us-east5 (Ohio) 支持动态共享配额 200,000 个词元
europe-west1 (Belgium) 支持动态共享配额 200,000 个词元

Claude 3 Opus 的默认配额限制和支持的上下文长度如下:

区域 默认配额限制 支持的上下文长度
us-east5 (Ohio) 240 QPM、100,000 TPM 200,000 个词元

Claude 3 Haiku 的默认配额限制和支持的上下文长度如下:

区域 默认配额限制 支持的上下文长度
us-central1 (Iowa) 240 QPM、100,000 TPM 200,000 个词元
us-east5 (Ohio) 240 QPM、100,000 TPM 200,000 个词元
europe-west1 (Belgium) 240 QPM、100,000 TPM 200,000 个词元
europe-west4 (Netherlands) 240 QPM、100,000 TPM 200,000 个词元

Claude 3 Sonnet 的默认配额限制和支持的上下文长度如下:

区域 默认配额限制 支持的上下文长度
us-central1 (Iowa) 240 QPM、100,000 TPM 200,000 个词元
us-east5 (Ohio) 240 QPM、100,000 TPM 200,000 个词元
asia-southeast1 (Singapore) 240 QPM、100,000 TPM 200,000 个词元

若要增加 Vertex AI 上的生成式 AI 的任何配额,您可以使用 Google Cloud 控制台申请增加配额。如需详细了解配额,请参阅使用配额

为用户启用 Claude 模型

为了让用户能够启用 Anthropic Claude 模型并发出提示请求,管理员必须设置所需权限验证组织政策是否允许使用所需的 API

设置所需权限

使用 Anthropic Claude 模型需要以下角色和权限:

  1. 必须向用户授予 Consumer Procurement Entitlement Manager Identity and Access Management (IAM) 角色。任何被授予此角色的用户都可以在 Model Garden 中启用 Anthropic Claude 模型。

  2. 用户必须获得 aiplatform.endpoints.predict 权限。此权限包含在 Vertex AI User IAM 角色中。如需了解详情,请参阅 Vertex AI User访问权限控制

控制台

  1. 如需向用户授予 Consumer Procurement Entitlement Manager IAM 角色,请转到 IAM 页面。

    进入 IAM

  2. 主账号列中,找到要为其启用 Anthropic Claude 模型访问权限的用户主账号,然后在对应的行中点击  修改主账号

  3. 修改权限窗格中,点击  添加其他角色

  4. 选择角色中,选择 Consumer Procurement Entitlement Manager

  5. 修改权限窗格中,点击  添加其他角色

  6. 选择角色中,选择 Vertex AI User

  7. 点击保存

gcloud

  1. 在 Google Cloud 控制台中,激活 Cloud Shell。

    激活 Cloud Shell

  2. 授予在 Model Garden 中启用 Anthropic Claude 模型所需的 Consumer Procurement Entitlement Manager 角色

    gcloud projects add-iam-policy-binding  PROJECT_ID \
    --member=PRINCIPAL --role=roles/consumerprocurement.entitlementManager
    
  3. 授予包含发出提示请求所需的 aiplatform.endpoints.predict 权限的 Vertex AI User 角色:

    gcloud projects add-iam-policy-binding  PROJECT_ID \
    --member=PRINCIPAL --role=roles/aiplatform.user
    

    PRINCIPAL 替换为主账号的标识符。标识符的格式为 user|group|serviceAccount:emaildomain:domain,例如 user:cloudysanfrancisco@gmail.comgroup:admins@example.comserviceAccount:test123@example.domain.comdomain:example.domain.com

    输出是一个政策绑定列表,其中包含以下内容:

    - members:
      - user:PRINCIPAL
      role: roles/roles/consumerprocurement.entitlementManager
    

    如需了解详情,请参阅授予单个角色和 gcloud projects add-iam-policy-binding

设置组织政策

如需启用 Anthropic Claude 模型,允许使用以下 API 的组织政策:

  • Cloud Commerce Consumer Procurement API - cloudcommerceconsumerprocurement.googleapis.com
  • Commerce Agreement API - commerceagreement.googleapis.com

如果您的组织将组织政策设置为限制服务的使用,则组织管理员必须通过设置组织政策来验证是否允许 cloudcommerceconsumerprocurement.googleapis.comcommerceagreement.googleapis.com