谷歌生成式AI聊天
Google GenAI API 允许开发者通过 Gemini 开发者 API 或 Vertex AI 利用谷歌的 Gemini 模型构建生成式 AI 应用。 Google GenAI API 支持多模态提示作为输入和输出文本或代码。 多模态模型能够处理来自多种模态的信息,包括图像、视频和文本。例如,你可以给模特发一张饼干盘的照片,让它给你一份饼干的Recipes。
Gemini 是由 Google DeepMind 开发的一系列生成式人工智能模型,专为多模态应用场景设计。Gemini API 为您提供 Gemini 2.0 Flash、Gemini 2.0 Flash-Lite 和 Gemini Pro 型号的访问权限。
该实现提供了两种认证模式:
-
Gemini开发者API:使用API密钥进行快速原型设计和开发
-
Vertex AI:使用Google Cloud凭证进行带有企业功能的生产部署
前提条件
请选择以下认证方法之一:
选项1:Gemini开发者API(API密钥)
-
从 Google AI Studio 获取 API 密钥
-
把API密钥设置为环境变量或应用属性中
选项二:Vertex AI(谷歌云)
-
安装适合你作系统的gcloud自定义集成链接。
-
通过执行以下命令进行认证。 取代
PROJECT_ID与你的 Google Cloud 项目 ID 以及帐户用你的Google Cloud用户名。
gcloud config set project <PROJECT_ID> &&
gcloud auth application-default login <ACCOUNT>
自动配置
|
春季AI自动配置、起始模块的工件名称发生了重大变化。 更多信息请参阅升级说明。 |
Spring AI 为 Google GenAI 聊天客户端提供 Spring Boot 自动配置。
要启用它,请在项目的Maven中添加以下依赖pom.xml或者Gradlebuild.gradle构建文件:
-
Maven
-
Gradle
<dependency>
<groupId>org.springframework.ai</groupId>
<artifactId>spring-ai-starter-model-google-genai</artifactId>
</dependency>
dependencies {
implementation 'org.springframework.ai:spring-ai-starter-model-google-genai'
}
| 请参考依赖管理部分,将Spring AI的物料清单添加到你的构建文件中。 |
聊天属性
|
现在,启用和禁用聊天自动配置通过带有前缀的顶层属性进行配置 启用时,spring.ai.model.chat=google-genai(默认启用) 要禁用,可以选择 spring.ai.model.chat=none(或任何与 google-genai 不匹配的值)。 此改动旨在允许配置多个模型。 |
连接性质
前缀spring.ai.google.genai作为属性前缀,允许你连接到 Google GenAI。
| 属性 | 描述 | 默认值 |
|---|---|---|
spring.ai.model.chat |
启用聊天模型客户端 |
谷歌生成AI(Google Genai) |
spring.ai.google.genai.api-key。 |
Gemini 开发者 API 的 API 密钥。客户端提供时,使用Gemini开发者API而非Vertex AI。 |
- |
spring.ai.google.genai.project-id |
Google Cloud Platform 项目 ID(顶点 AI 模式必备) |
- |
spring.ai.google.genai.location |
Google Cloud 区域(Vertex AI 模式必备) |
- |
spring.ai.google.genai.credentials-uri |
URI到Google Cloud凭证。当它被提供时,用于创建 |
- |
聊天模型属性
前缀spring.ai.google.genai.chat是属性前缀,允许你配置 Google GenAI Chat 的聊天模型实现。
| 属性 | 描述 | 默认值 |
|---|---|---|
spring.ai.google.genai.chat.options.model |
支持使用的谷歌生成式AI聊天模型包括 |
双子座2.0闪光灯 |
spring.ai.google.genai.chat.options.response-mime-type |
输出响应模拟生成候选文本的类型。 |
|
spring.ai.google.genai.chat.options.google-search-retrieval |
使用谷歌搜索接地功能 |
|
spring.ai.google.genai.chat.options.temperature. |
控制输出的随机性。数值范围可超过[0.0,1.0],包括。接近1.0的值会产生更多样化的响应,而接近0.0的值通常导致生成反应的意外性降低。 |
0.7 |
spring.ai.google.genai.chat.options.top-k |
抽样时应考虑的最大Tokens数量。生成式结合了Top-k和核采样。顶K抽样考虑topK最可能的符号集合。 |
- |
spring.ai.google.genai.chat.options.top-p |
抽样时需要考虑的Tokens的最大累计概率。生成式结合了Top-k和核采样。核抽样考虑概率和至少为topP的最小标记集。 |
- |
spring.ai.google.genai.chat.options.candidate-count |
需要返回的生成响应消息数量。该值必须介于[1, 8]之间,包含。默认为1。 |
1 |
spring.ai.google.genai.chat.options.max-输出-标记 |
最多可生成的Tokens数。 |
- |
spring.ai.google.genai.chat.options.frequency-penalty |
减少重复的频率惩罚。 |
- |
spring.ai.google.genai.chat.options.presence-penalty |
减少重复时的在场惩罚。 |
- |
spring.ai.google.genai.chat.options.thinking-budget |
思考过程的预算。 |
- |
spring.ai.google.genai.chat.options.tool-names |
列出了工具,按名称标识,用于在一次提示请求中实现函数调用。带有这些名称的工具必须存在于 ToolCallback 注册表中。 |
- |
spring.ai.google.genai.chat.options.tool-callbacks |
工具回调以注册到聊天模型。 |
- |
spring.ai.google.genai.chat.options.internal-tool-execution-enabled |
如果为真,则应执行工具执行,否则模型的响应将返回给用户。默认是空,但如果是空, |
- |
spring.ai.google.genai.chat.options.safety-settings |
根据谷歌生成式人工智能安全设置定义的安全设置列表。每个安全设置可以有方法、阈值和类别。 |
- |
所有以spring.ai.google.genai.chat.options可以通过在运行时为 请求添加特定的运行时选项来覆盖提示叫。 |
运行时选项
GoogleGenAiChatOptions.java提供模型配置,如温度、topK等。
启动时,默认选项可以配置为GoogleGenAiChatModel(client, options)构造者或spring.ai.google.genai.chat.options.*性能。
运行时,你可以通过添加新的、针对请求的选项来覆盖默认选项提示叫。
例如,要覆盖特定请求的默认温度:
ChatResponse response = chatModel.call(
new Prompt(
"Generate the names of 5 famous pirates.",
GoogleGenAiChatOptions.builder()
.temperature(0.4)
.build()
));
除了型号本身谷歌生成人工智能聊天选项你可以使用一个用ChatOptions#builder()创建的便携式ChatOptions实例。 |
工具调用
谷歌生成式AI模型支持工具调用(函数调用)功能,使模型在对话中能够使用工具。
这里有一个定义和使用的示例@Tool基于工具:
public class WeatherService {
@Tool(description = "Get the weather in location")
public String weatherByLocation(@ToolParam(description= "City or state name") String location) {
...
}
}
String response = ChatClient.create(this.chatModel)
.prompt("What's the weather like in Boston?")
.tools(new WeatherService())
.call()
.content();
你也可以用java.util.function 豆子作为工具:
@Bean
@Description("Get the weather in location. Return temperature in 36°F or 36°C format.")
public Function<Request, Response> weatherFunction() {
return new MockWeatherService();
}
String response = ChatClient.create(this.chatModel)
.prompt("What's the weather like in Boston?")
.toolNames("weatherFunction")
.inputType(Request.class)
.call()
.content();
更多信息请参见工具文档。
模 态
多模态指的是模型能够同时理解和处理来自多个(输入)来源的信息,包括文本,PDF格式,图像,音频以及其他数据格式。
图像、音频、视频
谷歌的Gemini AI模型支持这一能力,能够理解并整合文本、代码、音频、图像和视频。 更多细节请参见博客文章《介绍双子座》。
春季 AI消息界面通过引入媒体类型支持多模态 AI 模型。
这种类型包含关于消息中媒体附件的数据和信息,使用 Spring 的org.springframework.util.MimeType以及一个java.lang.Object对于原始媒体数据。
下面是一个从GoogleGenAiChatModelIT.java提取的简单代码示例,演示了用户文本与图片的组合。
byte[] data = new ClassPathResource("/vertex-test.png").getContentAsByteArray();
var userMessage = UserMessage.builder()
.text("Explain what do you see o this picture?")
.media(List.of(new Media(MimeTypeUtils.IMAGE_PNG, data)))
.build();
ChatResponse response = chatModel.call(new Prompt(List.of(this.userMessage)));
PDF格式
Google GenAI 支持 PDF 输入类型。
使用该申请表/PDF将PDF文件附加到消息后,媒体类型:
var pdfData = new ClassPathResource("/spring-ai-reference-overview.pdf");
var userMessage = UserMessage.builder()
.text("You are a very professional document summarization specialist. Please summarize the given document.")
.media(List.of(new Media(new MimeType("application", "pdf"), pdfData)))
.build();
var response = this.chatModel.call(new Prompt(List.of(userMessage)));
采样控制器
创建一个新的 Spring Boot 项目并添加Spring-AI-Starter-Model-Google-Genai对你的POM(或Gradle)依赖。
添加一个application.properties文件,在src/主/资源目录,用于启用和配置 Google GenAI 聊天模型:
使用 Gemini 开发者 API(API 密钥)
spring.ai.google.genai.api-key=YOUR_API_KEY
spring.ai.google.genai.chat.options.model=gemini-2.0-flash
spring.ai.google.genai.chat.options.temperature=0.5
使用 Vertex AI
spring.ai.google.genai.project-id=PROJECT_ID
spring.ai.google.genai.location=LOCATION
spring.ai.google.genai.chat.options.model=gemini-2.0-flash
spring.ai.google.genai.chat.options.temperature=0.5
替换项目标识附带您的 Google Cloud Project ID 和位置是谷歌云区域
喜欢美国中部1,欧洲-西方1等。。。 |
|
每个模型都有自己的支持区域集合,你可以在模型页面找到支持区域列表。 |
这将产生谷歌GenAiChatModel你可以把这些实现注入到你的类里。
这里有一个简单的例子@Controller使用聊天模式生成文本的课程。
@RestController
public class ChatController {
private final GoogleGenAiChatModel chatModel;
@Autowired
public ChatController(GoogleGenAiChatModel chatModel) {
this.chatModel = chatModel;
}
@GetMapping("/ai/generate")
public Map generate(@RequestParam(value = "message", defaultValue = "Tell me a joke") String message) {
return Map.of("generation", this.chatModel.call(message));
}
@GetMapping("/ai/generateStream")
public Flux<ChatResponse> generateStream(@RequestParam(value = "message", defaultValue = "Tell me a joke") String message) {
Prompt prompt = new Prompt(new UserMessage(message));
return this.chatModel.stream(prompt);
}
}
手动配置
GoogleGenAiChatModel 实现了聊天模型并且使用com.google.genai.客户端连接谷歌生成式人工智能服务。
添加Spring-ai-google-genai对你项目Maven的依赖pom.xml文件:
<dependency>
<groupId>org.springframework.ai</groupId>
<artifactId>spring-ai-google-genai</artifactId>
</dependency>
或者去你的Gradlebuild.gradle构建文件。
dependencies {
implementation 'org.springframework.ai:spring-ai-google-genai'
}
| 请参考依赖管理部分,将Spring AI的物料清单添加到你的构建文件中。 |
接下来,创建一个谷歌GenAiChatModel并用于文本生成:
使用 API 密钥
Client genAiClient = Client.builder()
.apiKey(System.getenv("GOOGLE_API_KEY"))
.build();
var chatModel = new GoogleGenAiChatModel(genAiClient,
GoogleGenAiChatOptions.builder()
.model(ChatModel.GEMINI_2_0_FLASH)
.temperature(0.4)
.build());
ChatResponse response = this.chatModel.call(
new Prompt("Generate the names of 5 famous pirates."));
使用 Vertex AI
Client genAiClient = Client.builder()
.project(System.getenv("GOOGLE_CLOUD_PROJECT"))
.location(System.getenv("GOOGLE_CLOUD_LOCATION"))
.vertexAI(true)
.build();
var chatModel = new GoogleGenAiChatModel(genAiClient,
GoogleGenAiChatOptions.builder()
.model(ChatModel.GEMINI_2_0_FLASH)
.temperature(0.4)
.build());
ChatResponse response = this.chatModel.call(
new Prompt("Generate the names of 5 famous pirates."));
这谷歌生成人工智能聊天选项提供聊天请求的配置信息。
这谷歌GenAiChatOptions.Builder是流利期权构建器。
从 Vertex AI Gemini 迁移
如果你目前正在使用 Vertex AI Gemini 实现 (春-艾-顶点-艾-双子),你可以以最小的改动迁移到 Google GenAI: