主题
Google Vertex AI Anthropic
Google Vertex AI 通过 Google Cloud Platform 提供对 Anthropic Claude 模型的访问。本集成让你能使用 Claude 先进的语言能力,同时借助 Google Cloud 的基础设施与安全特性。
开始使用
创建 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 模型
Claude 模型需要在你的 Google Cloud 项目中启用:
- 前往 Vertex AI Model Garden
- 搜索 "Claude" 模型
- 启用你想使用的 Claude 模型(例如 Claude 3.5 Sonnet、Claude 3 Opus)
选择 Google Cloud 认证策略
你的应用向 Google Cloud 服务与 API 认证的方式有几种。例如,你可以创建一个 服务账号,并将环境变量 GOOGLE_APPLICATION_CREDENTIALS 设为指向包含你凭据的 JSON 文件路径。
你可以在这里了解所有认证策略。但为了本地测试的简便,我们将通过 gcloud 工具进行认证。
安装 Google Cloud CLI(可选)
要在本地访问你的云项目,你可以按安装说明安装 gcloud 工具。对于 GNU/Linux 操作系统,安装步骤如下:
- 下载 SDK:
bash
curl -O https://dl.google.com/dl/cloudsdk/channels/rapid/downloads/google-cloud-cli-467.0.0-linux-x86_64.tar.gz- 解压归档:
bash
tar -xf google-cloud-cli-467.0.0-linux-x86_64.tar.gz- 运行安装脚本:
bash
cd google-cloud-sdk/
./install.sh- 运行以下命令以设置默认项目与认证凭据:
bash
gcloud auth application-default login该认证方式与 langchain4j-vertex-ai-anthropic 包兼容。
添加依赖
要开始使用,将以下依赖添加到你的项目的 pom.xml:
xml
<dependency>
<groupId>dev.langchain4j</groupId>
<artifactId>langchain4j-vertex-ai-anthropic</artifactId>
<version>1.22.0-beta32</version>
</dependency>或添加到项目的 build.gradle:
groovy
implementation 'dev.langchain4j:langchain4j-vertex-ai-anthropic:1.22.0-beta32'试用示例代码
PROJECT_ID 字段代表你在创建新的 Google Cloud 项目时所设置的变量。
java
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 类,流式也受支持:
java
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():
java
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 模型文档中了解这些模型。
配置
java
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(...) 的值决定使用哪一类:
| 位置取值 | 类别 | 作用 |
|---|---|---|
"global" | 全局 | 将每个请求路由到任一有空闲容量的区域。可用性最佳,无价格溢价。除非你有数据驻留要求,否则推荐。 |
"us"、"eu" | 多区域 | 将每个请求路由到该地域内的某个区域,兼顾数据驻留与高可用。 |
"us-east5"、"europe-west1"…… | 区域级 | 让每个请求都经由某一个特定区域。单区域数据驻留以及预留吞吐需要它。 |
java
ChatModel model = VertexAiAnthropicChatModel.builder()
.project(PROJECT_ID)
.location("global")
.modelName(MODEL_NAME)
.build();请注意,模型可用性因位置而异,且多区域与区域级位置相较全局位置带有价格溢价。细节参见全局、多区域与区域级端点。
更多示例
Claude 是一个强大的多模态模型,接受文本与图像作为输入。
视觉能力
java
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());工具调用
java
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,附带聊天记忆与计算器工具。
java
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?");提示词缓存
Claude 支持提示词缓存,以在重复或较长的提示词上降低成本并改善响应时间:
java
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());提示词缓存提供:
- 成本降低:缓存内容最多便宜 90%
- 延迟改善:响应时间最多快 85%
- 自动优化:无需手动管理缓存
自定义认证
你可以提供自定义的 Google Cloud 凭据:
java
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();