跳到主要内容

Google Vertex AI Anthropic

Google Vertex AI 通过 Google Cloud Platform 提供对 Anthropic Claude 模型的访问。该集成使你能够在利用 Google Cloud 基础设施与安全特性的同时,使用 Claude 的高级语言能力。

快速开始​

创建 Google Cloud 账号​

如果你是 Google Cloud 新用户,可在以下页面的 Get set up on Google Cloud 下拉菜单中点击 [create an account] 按钮创建新账号:

创建账号

在 Google Cloud Platform 账号中创建项目​

在 Google Cloud 账号中创建新项目并启用 Vertex AI API,请按以下步骤操作:

创建新项目

请记下你的 PROJECT_ID,后续 API 调用需要用到。

在 Vertex AI Model Garden 中启用 Claude 模型​

需要在你的 Google Cloud 项目中启用 Claude 模型:

  1. 前往 Vertex AI Model Garden
  2. 搜索 "Claude" 模型
  3. 启用你想使用的 Claude 模型(例如 Claude 3.5 Sonnet、Claude 3 Opus)

选择 Google Cloud 认证策略​

应用向 Google Cloud 服务与 API 进行认证的方式有多种。例如,你可以创建 服务账号,并将环境变量 GOOGLE_APPLICATION_CREDENTIALS 设置为包含凭据的 JSON 文件路径。

你可以在此处了解所有认证策略。但为简化本地测试,我们将使用通过 gcloud 工具进行认证。

安装 Google Cloud CLI(可选)​

要在本地访问云项目,可按安装说明安装 gcloud 工具。对于 GNU/Linux 操作系统,安装步骤如下:

  1. 下载 SDK:
curl -O https://dl.google.com/dl/cloudsdk/channels/rapid/downloads/google-cloud-cli-467.0.0-linux-x86_64.tar.gz
  1. 解压归档:
tar -xf google-cloud-cli-467.0.0-linux-x86_64.tar.gz
  1. 运行安装脚本:
cd google-cloud-sdk/
./install.sh
  1. 运行以下命令设置默认项目与认证凭据:
gcloud auth application-default login

此认证方法与 langchain4j-vertex-ai-anthropic 包兼容。

添加依赖​

首先,将以下依赖添加到项目的 pom.xml:

<dependency>
<groupId>dev.langchain4j</groupId>
<artifactId>langchain4j-vertex-ai-anthropic</artifactId>
<version>1.18.1-beta28</version>
</dependency>

或项目的 build.gradle:

implementation 'dev.langchain4j:langchain4j-vertex-ai-anthropic:1.18.1-beta28'

试用示例代码​

PROJECT_ID 字段表示你在创建新 Google Cloud 项目时设置的变量。

import dev.langchain4j.data.message.UserMessage;
import dev.langchain4j.model.chat.ChatModel;
import dev.langchain4j.model.chat.request.ChatRequest;
import dev.langchain4j.model.chat.response.ChatResponse;
import dev.langchain4j.model.vertexai.anthropic.VertexAiAnthropicChatModel;

public class VertexAiAnthropicExample {

private static final String PROJECT_ID = "YOUR-PROJECT-ID";
private static final String LOCATION = "us-central1";
private static final String MODEL_NAME = "claude-3-5-sonnet-v2@20241022";

public static void main(String[] args) {
ChatModel model = VertexAiAnthropicChatModel.builder()
.project(PROJECT_ID)
.location(LOCATION)
.modelName(MODEL_NAME)
.maxTokens(1000)
.temperature(0.7)
.build();

ChatResponse response = model.chat(ChatRequest.builder()
.messages(List.of(UserMessage.from("Hello, Claude!")))
.build());

System.out.println(response.aiMessage().text());
}
}

流式输出也通过 VertexAiAnthropicStreamingChatModel 类得到支持:

import dev.langchain4j.model.vertexai.anthropic.VertexAiAnthropicStreamingChatModel;
import dev.langchain4j.model.chat.StreamingChatResponseHandler;

var model = VertexAiAnthropicStreamingChatModel.builder()
.project(PROJECT_ID)
.location(LOCATION)
.modelName(MODEL_NAME)
.build();

model.

chat(ChatRequest.builder()
.

messages(List.of(UserMessage.from("Tell me a story")))
.

build(), new

StreamingChatResponseHandler() {

@Override
public void onPartialResponse (String partialResponse){
System.out.print(partialResponse);
}

@Override
public void onCompleteResponse (ChatResponse completeResponse){
System.out.println("\nDone!");
}

@Override
public void onError (Throwable error){
error.printStackTrace();
}
});

你可以使用 LambdaStreamingResponseHandler 中的快捷工具函数 onPartialResponse() 与 onPartialResponseAndError():

import static dev.langchain4j.model.chat.response.streaming.LambdaStreamingResponseHandler.onPartialResponse;
import static dev.langchain4j.model.chat.response.streaming.LambdaStreamingResponseHandler.onPartialResponseAndError;

model.chat(ChatRequest.builder()
.messages(List.of(UserMessage.from("Why is the sky blue?")))
.build(), onPartialResponse(System.out::print));

model.chat(ChatRequest.builder()
.messages(List.of(UserMessage.from("Why is the sky blue?")))
.build(), onPartialResponseAndError(System.out::print, Throwable::printStackTrace));

可用模型​

Vertex AI 可用模型列表。 你可以在 Claude 模型文档 中了解这些模型。

配置​

ChatModel model = VertexAiAnthropicChatModel.builder()
.project(PROJECT_ID) // your Google Cloud project ID
.location(LOCATION) // where inference takes place, see "Locations" below
.modelName(MODEL_NAME) // the Claude model used
.maxTokens(4096) // the maximum number of tokens to generate
.temperature(0.7) // temperature (between 0 and 1)
.topP(0.95) // topP (between 0 and 1) — cumulative probability
.topK(40) // topK (positive integer) — pick from top K tokens
.stopSequences(Arrays.asList("Human:", "Assistant:")) // stop sequences
.enablePromptCaching(true) // enable prompt caching for cost/latency optimization
.credentials(credentials) // custom Google Cloud credentials
.logRequests(true) // log input requests
.logResponses(true) // log output responses
.build();

流式聊天模型也提供相同的参数。

位置(Locations)​

location 决定请求在何处处理。Vertex AI 提供三种位置类型, 你传给 .location(...) 的值决定使用哪一种:

location 值类型作用
"global"全球将每个请求路由到任意有可用容量的区域。可用性最佳,无额外价格溢价。除非有数据驻留要求,否则推荐使用。
"us"、"eu"多区域将每个请求路由到该地理范围内的某个区域,兼顾数据驻留与高可用。
"us-east5"、"europe-west1" 等区域将每个请求都路由到一个特定区域。单区域数据驻留与预配吞吐量时必需。
ChatModel model = VertexAiAnthropicChatModel.builder()
.project(PROJECT_ID)
.location("global")
.modelName(MODEL_NAME)
.build();

请注意,模型可用性因位置而异,且多区域与区域位置相对全球端点会有价格溢价。详见 全球、多区域与区域端点。

更多示例​

Claude 是强大的多模态模型,可同时接受文本与图像作为输入。

视觉能力​

import dev.langchain4j.data.image.Image;
import dev.langchain4j.data.message.ImageContent;
import dev.langchain4j.data.message.TextContent;
import dev.langchain4j.data.message.UserMessage;

ChatModel model = VertexAiAnthropicChatModel.builder()
.project(PROJECT_ID)
.location(LOCATION)
.modelName("claude-3-5-sonnet-v2@20241022")
.build();

Image image = Image.builder()
.base64Data("base64-encoded-image-data")
.mimeType("image/jpeg")
.build();

UserMessage userMessage = UserMessage.from(
ImageContent.from(image),
TextContent.from("What do you see in this image?")
);

ChatResponse response = model.chat(ChatRequest.builder()
.messages(List.of(userMessage))
.build());

System.out.println(response.aiMessage().text());

工具调用​

import dev.langchain4j.agent.tool.ToolSpecification;
import dev.langchain4j.data.message.ToolExecutionResultMessage;
import dev.langchain4j.model.output.structured.JsonObjectSchema;

ChatModel model = VertexAiAnthropicChatModel.builder()
.project(PROJECT_ID)
.location(LOCATION)
.modelName("claude-3-5-sonnet-v2@20241022")
.build();

ToolSpecification weatherToolSpec = ToolSpecification.builder()
.name("getWeatherForecast")
.description("Get the weather forecast for a location")
.parameters(JsonObjectSchema.builder()
.addStringProperty("location", "the location to get the weather forecast for")
.required("location")
.build())
.build();

ChatRequest request = ChatRequest.builder()
.messages(List.of(UserMessage.from("What is the weather in Paris?")))
.toolSpecifications(List.of(weatherToolSpec))
.build();

ChatResponse response = model.chat(request);

模型将以工具执行请求(而非文本消息)进行回复。 你的职责是向模型提供该执行请求的结果, 通过向模型发送 ToolExecutionResultMessage。 随后模型即可用文本响应进行回复。

通过 AiServices 使用工具​

你可以使用 AiServices 创建由工具驱动的助手。 以下示例展示了一个用于数学计算的 Calculator 工具、 一个用于定义助手契约的 Assistant 接口, 然后配置 AiServices 使用 Claude、聊天记忆以及计算器工具。

import dev.langchain4j.service.AiServices;
import dev.langchain4j.agent.tool.Tool;
import dev.langchain4j.memory.chat.MessageWindowChatMemory;

static class Calculator {
@Tool("Adds two given numbers")
double add(double a, double b) {
return a + b;
}

@Tool("Multiplies two given numbers")
String multiply(double a, double b) {
return String.valueOf(a * b);
}
}

interface Assistant {
String chat(String userMessage);
}

Calculator calculator = new Calculator();

Assistant assistant = AiServices.builder(Assistant.class)
.chatModel(model)
.chatMemory(MessageWindowChatMemory.withMaxMessages(10))
.tools(calculator)
.build();

String answer = assistant.chat("How much is 74589613588 + 4786521789?");

Prompt 缓存​

Claude 支持 prompt 缓存,以降低成本并改善重复或冗长 prompt 的响应时间:

import dev.langchain4j.data.message.SystemMessage;

ChatModel model = VertexAiAnthropicChatModel.builder()
.project(PROJECT_ID)
.location(LOCATION)
.modelName("claude-3-5-sonnet-v2@20241022")
.enablePromptCaching(true)
.build();

SystemMessage systemMessage = SystemMessage.from(
"You are an expert software engineer with deep knowledge of Java, " +
"Spring Boot, microservices architecture, and cloud-native development. " +
"Always provide detailed, production-ready code examples with proper " +
"error handling, logging, and best practices."
);

UserMessage userMessage = UserMessage.from("How do I implement JWT authentication?");

ChatResponse response = model.chat(ChatRequest.builder()
.messages(List.of(systemMessage, userMessage))
.build());

Prompt 缓存可提供:

  • 降低成本:缓存内容最高可便宜约 90%
  • 降低延迟:响应时间最高可快约 85%
  • 自动优化:无需手动管理缓存

自定义认证​

你可以提供自定义的 Google Cloud 凭据:

import com.google.auth.oauth2.GoogleCredentials;
import java.io.FileInputStream;

GoogleCredentials credentials = GoogleCredentials.fromStream(
new FileInputStream("path/to/service-account-key.json"));

ChatModel model = VertexAiAthropicChatModel.builder()
.project(PROJECT_ID)
.location(LOCATION)
.modelName("claude-3-5-sonnet-v2@20241022")
.credentials(credentials)
.build();

参考资料​

可用位置

Claude 模型文档

Vertex AI Model Garden