Vertex AI Gemini API 允许开发者使用 Gemini 模型构建生成式人工智能应用。Vertex AI Gemini API 支持多模态提示词作为输入,并输出文本或代码。多模态模型能够处理来自多种模态的信息,包括图像、视频和文本。例如,你可以向模型发送一盘饼干的照片,并让它为你提供这些饼干的配方。
Gemini 是由谷歌 DeepMind 开发的生成式人工智能模型系列,专为多模态场景设计。通过 Gemini API,你可以使用 Gemini 2.0 Flash 和 Gemini 2.0 Flash-Lite 模型。有关 Vertex AI Gemini API 模型的规格说明,请参阅模型信息文档。
前提条件
安装适用于你操作系统的 gcloud 命令行工具。
运行以下命令进行认证,将 PROJECT_ID 替换为你的谷歌云项目 ID,ACCOUNT 替换为你的谷歌云账号。
gcloud config set project <PROJECT_ID> && gcloud auth application-default login <ACCOUNT>
自动配置
Spring AI 自动配置、启动器模块的构件名称发生了重大变更。更多信息请参考升级说明。
Spring AI 为 Vertex AI Gemini 对话客户端提供 Spring Boot 自动配置。要启用该功能,请在项目的 Maven pom.xml 或 Gradle build.gradle 构建文件中添加以下依赖:
<dependency> <groupId>org.springframework.ai</groupId> <artifactId>spring-ai-starter-model-vertex-ai-gemini</artifactId> </dependency>
参考依赖管理章节,将 Spring AI 物料清单(BOM)添加到你的构建文件中。
对话属性配置
现在通过顶级属性 spring.ai.model.chat 启用或禁用对话自动配置:
启用:spring.ai.model.chat=vertexai(默认启用)
禁用:spring.ai.model.chat=none(或任何不等于 vertexai 的值)
此修改支持在应用中配置多个模型。
连接属性
spring.ai.vertex.ai.gemini 前缀用于配置 Vertex AI 连接参数。
| 属性 | 描述 | 默认值 |
|---|---|---|
| spring.ai.model.chat | 启用对话模型客户端 | vertexai |
| spring.ai.vertex.ai.gemini.project-id | 谷歌云平台项目 ID | - |
| spring.ai.vertex.ai.gemini.location | 区域 | - |
| spring.ai.vertex.ai.gemini.credentials-uri | Vertex AI Gemini 凭证 URI,配置后用于创建认证用的 GoogleCredentials 实例 | - |
| spring.ai.vertex.ai.gemini.api-endpoint | Vertex AI Gemini API 端点 | - |
| spring.ai.vertex.ai.gemini.scopes | API 权限范围 | - |
| spring.ai.vertex.ai.gemini.transport | API 传输协议:GRPC 或 REST | GRPC |
模型配置属性
spring.ai.vertex.ai.gemini.chat 前缀用于配置 Vertex AI Gemini 对话模型实现。
| 属性 | 描述 | 默认值 |
|---|---|---|
| spring.ai.vertex.ai.gemini.chat.options.model | 支持的模型:gemini-2.0-flash、gemini-2.0-flash-lite、gemini-2.5-pro-preview-03-25、gemini-2.5-flash-preview-04-17 | gemini-2.0-flash |
| spring.ai.vertex.ai.gemini.chat.options.response-mime-type | 输出响应类型:text/plain(默认)或 application/json | text/plain |
| spring.ai.vertex.ai.gemini.chat.options.response-schema | OpenAPI 格式的输出响应 schema 字符串 | - |
| spring.ai.vertex.ai.gemini.chat.options.google-search-retrieval | 启用谷歌搜索基础功能 | false |
| spring.ai.vertex.ai.gemini.chat.options.temperature | 输出随机性,0.0~1.0,值越高越随机 | 0.7 |
| spring.ai.vertex.ai.gemini.chat.options.top-k | 采样时考虑的最大令牌数 | - |
| spring.ai.vertex.ai.gemini.chat.options.top-p | 采样时考虑的最大累积概率 | - |
| spring.ai.vertex.ai.gemini.chat.options.candidate-count | 返回的生成结果数量,1~8 | 1 |
| spring.ai.vertex.ai.gemini.chat.options.max-output-tokens | 最大生成令牌数 | - |
| spring.ai.vertex.ai.gemini.chat.options.tool-names | 单次提示请求启用的工具名称列表 | - |
| spring.ai.vertex.ai.gemini.chat.options.tool-callbacks | 向对话模型注册的工具回调 | - |
| spring.ai.vertex.ai.gemini.chat.options.internal-tool-execution-enabled | 是否内部执行工具调用 | - |
| spring.ai.vertex.ai.gemini.chat.options.safety-settings | 安全设置列表 | - |
所有 spring.ai.vertex.ai.gemini.chat.options 前缀的属性,均可在运行时通过为 Prompt 添加请求级运行时选项覆盖。
运行时选项
VertexAiGeminiChatOptions.java 提供模型、温度、topK 等配置。
启动时可通过 VertexAiGeminiChatModel(api, options) 构造方法或 spring.ai.vertex.ai.chat.options.* 属性配置默认选项。
运行时可覆盖默认配置,示例:
ChatResponse response = chatModel.call( new Prompt( "生成5位著名海盗的名字。", VertexAiGeminiChatOptions.builder() .temperature(0.4) .build() ));
除了模型专用的 VertexAiGeminiChatOptions,也可使用通用 ChatOptions。
工具调用
Vertex AI Gemini 模型支持工具调用(在 Gemini 中称为函数调用)功能,允许模型在对话中使用工具。以下是 @Tool 定义和使用工具的示例:
public class WeatherService {
@Tool(description = "获取指定地点的天气")
public String weatherByLocation(@ToolParam(description= "城市或州名称") String location) {
...
}
}
String response = ChatClient.create(this.chatModel)
.prompt("波士顿的天气如何?")
.tools(new WeatherService())
.call()
.content();也可使用 java.util.function Bean 作为工具:
@Bean
@Description("获取指定地点的天气,返回温度格式为36°F或36°C")
public Function<Request, Response> weatherFunction() {
return new MockWeatherService();
}
String response = ChatClient.create(this.chatModel)
.prompt("波士顿的天气如何?")
.toolNames("weatherFunction")
.inputType(Request.class)
.call()
.content();更多内容查看工具文档。
多模态
多模态指模型同时理解和处理文本、PDF、图片、音频等多种输入信息的能力。
图片/音频/视频
byte[] data = new ClassPathResource("/vertex-test.png").getContentAsByteArray();
var userMessage = new UserMessage("描述图片内容",
List.of(new Media(MimeTypeUtils.IMAGE_PNG, data)));
ChatResponse response = chatModel.call(new Prompt(List.of(userMessage)));var pdfData = new ClassPathResource("/spring-ai-reference-overview.pdf");
var userMessage = new UserMessage(
"总结这份文档",
List.of(new Media(new MimeType("application", "pdf"), pdfData)));
var response = chatModel.call(new Prompt(List.of(userMessage)));安全设置与安全评级
Vertex AI Gemini API 提供安全过滤能力,用于控制提示词和响应中的有害内容。
配置安全设置
支持的有害类别:仇恨言论、危险内容、骚扰内容、性暴露内容、公民诚信内容。
支持的拦截阈值:拦截低风险及以上、拦截中风险及以上、仅拦截高风险、不拦截。
List<VertexAiGeminiSafetySetting> safetySettings = List.of(
VertexAiGeminiSafetySetting.builder()
.withCategory(VertexAiGeminiSafetySetting.HarmCategory.HARM_CATEGORY_HARASSMENT)
.withThreshold(VertexAiGeminiSafetySetting.HarmBlockThreshold.BLOCK_LOW_AND_ABOVE)
.build(),
VertexAiGeminiSafetySetting.builder()
.withCategory(VertexAiGeminiSafetySetting.HarmCategory.HARM_CATEGORY_HATE_SPEECH)
.withThreshold(VertexAiGeminiSafetySetting.HarmBlockThreshold.BLOCK_MEDIUM_AND_ABOVE)
.build());
ChatResponse response = chatModel.call(new Prompt("你的提示词",
VertexAiGeminiChatOptions.builder()
.safetySettings(safetySettings)
.build()));在响应中获取安全评级
List<VertexAiGeminiSafetyRating> safetyRatings =
(List<VertexAiGeminiSafetyRating>) response.getResult()
.getOutput()
.getMetadata()
.get("safetyRatings");示例控制器
创建 Spring Boot 项目,添加 spring-ai-starter-model-vertex-ai-gemini 依赖。
配置文件:
spring.ai.vertex.ai.gemini.project-id=PROJECT_ID spring.ai.vertex.ai.gemini.location=us-central1 spring.ai.vertex.ai.gemini.chat.options.model=gemini-2.0-flash spring.ai.vertex.ai.gemini.chat.options.temperature=0.5
控制器代码:
@RestController
public class ChatController {
private final VertexAiGeminiChatModel chatModel;
@Autowired
public ChatController(VertexAiGeminiChatModel chatModel) {
this.chatModel = chatModel;
}
@GetMapping("/ai/generate")
public Map generate(@RequestParam(value = "message", defaultValue = "讲个笑话") String message) {
return Map.of("generation", chatModel.call(message));
}
@GetMapping("/ai/generateStream")
public Flux<ChatResponse> generateStream(@RequestParam(value = "message", defaultValue = "讲个笑话") String message) {
Prompt prompt = new Prompt(new UserMessage(message));
return chatModel.stream(prompt);
}
}手动配置
添加依赖:
<dependency> <groupId>org.springframework.ai</groupId> <artifactId>spring-ai-vertex-ai-gemini</artifactId> </dependency>
创建 VertexAiGeminiChatModel:
VertexAI vertexApi = new VertexAI(projectId, location);
var chatModel = new VertexAiGeminiChatModel(vertexApi,
VertexAiGeminiChatOptions.builder()
.model(ChatModel.GEMINI_2_0_FLASH)
.temperature(0.4)
.build());
ChatResponse response = chatModel.call(
new Prompt("生成5位著名海盗的名字。"));