谷歌生成式AI聊天

Google GenAI API 允许开发者通过 Gemini 开发者 API 或 Vertex AI 利用谷歌的 Gemini 模型构建生成式 AI 应用。 Google GenAI API 支持多模态提示作为输入和输出文本或代码。 多模态模型能够处理来自多种模态的信息,包括图像、视频和文本。例如,你可以给模特发一张饼干盘的照片,让它给你一份饼干的Recipes。spring-doc.cadn.net.cn

Gemini 是由 Google DeepMind 开发的一系列生成式人工智能模型,专为多模态应用场景设计。Gemini API 为您提供 Gemini 2.0 FlashGemini 2.0 Flash-LiteGemini Pro 型号的访问权限。spring-doc.cadn.net.cn

该实现提供了两种认证模式:spring-doc.cadn.net.cn

前提条件

请选择以下认证方法之一:spring-doc.cadn.net.cn

选项1:Gemini开发者API(API密钥)

选项二:Vertex AI(谷歌云)

gcloud config set project <PROJECT_ID> &&
gcloud auth application-default login <ACCOUNT>

自动配置

春季AI自动配置、起始模块的工件名称发生了重大变化。 更多信息请参阅升级说明spring-doc.cadn.net.cn

Spring AI 为 Google GenAI 聊天客户端提供 Spring Boot 自动配置。 要启用它,请在项目的Maven中添加以下依赖pom.xml或者Gradlebuild.gradle构建文件:spring-doc.cadn.net.cn

<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.spring-doc.cadn.net.cn

启用时,spring.ai.model.chat=google-genai(默认启用)spring-doc.cadn.net.cn

要禁用,可以选择 spring.ai.model.chat=none(或任何与 google-genai 不匹配的值)。spring-doc.cadn.net.cn

此改动旨在允许配置多个模型。spring-doc.cadn.net.cn

连接性质

前缀spring.ai.google.genai作为属性前缀,允许你连接到 Google GenAI。spring-doc.cadn.net.cn

属性 描述 默认值

spring.ai.model.chatspring-doc.cadn.net.cn

启用聊天模型客户端spring-doc.cadn.net.cn

谷歌生成AI(Google Genai)spring-doc.cadn.net.cn

spring.ai.google.genai.api-key。spring-doc.cadn.net.cn

Gemini 开发者 API 的 API 密钥。客户端提供时,使用Gemini开发者API而非Vertex AI。spring-doc.cadn.net.cn

-spring-doc.cadn.net.cn

spring.ai.google.genai.project-idspring-doc.cadn.net.cn

Google Cloud Platform 项目 ID(顶点 AI 模式必备)spring-doc.cadn.net.cn

-spring-doc.cadn.net.cn

spring.ai.google.genai.locationspring-doc.cadn.net.cn

Google Cloud 区域(Vertex AI 模式必备)spring-doc.cadn.net.cn

-spring-doc.cadn.net.cn

spring.ai.google.genai.credentials-urispring-doc.cadn.net.cn

URI到Google Cloud凭证。当它被提供时,用于创建谷歌凭证用于认证实例。spring-doc.cadn.net.cn

-spring-doc.cadn.net.cn

聊天模型属性

前缀spring.ai.google.genai.chat是属性前缀,允许你配置 Google GenAI Chat 的聊天模型实现。spring-doc.cadn.net.cn

属性 描述 默认值

spring.ai.google.genai.chat.options.modelspring-doc.cadn.net.cn

支持使用的谷歌生成式AI聊天模型包括双子座2.0闪光灯,Gemini-2.0-Flash-Lite,双子座专业版双子座1.5闪光.spring-doc.cadn.net.cn

双子座2.0闪光灯spring-doc.cadn.net.cn

spring.ai.google.genai.chat.options.response-mime-typespring-doc.cadn.net.cn

输出响应模拟生成候选文本的类型。spring-doc.cadn.net.cn

文本/纯文字:(默认)文本输出或application/json: JSON 回复。spring-doc.cadn.net.cn

spring.ai.google.genai.chat.options.google-search-retrievalspring-doc.cadn.net.cn

使用谷歌搜索接地功能spring-doc.cadn.net.cn

truefalse默认值false.spring-doc.cadn.net.cn

spring.ai.google.genai.chat.options.temperature.spring-doc.cadn.net.cn

控制输出的随机性。数值范围可超过[0.0,1.0],包括。接近1.0的值会产生更多样化的响应,而接近0.0的值通常导致生成反应的意外性降低。spring-doc.cadn.net.cn

0.7spring-doc.cadn.net.cn

spring.ai.google.genai.chat.options.top-kspring-doc.cadn.net.cn

抽样时应考虑的最大Tokens数量。生成式结合了Top-k和核采样。顶K抽样考虑topK最可能的符号集合。spring-doc.cadn.net.cn

-spring-doc.cadn.net.cn

spring.ai.google.genai.chat.options.top-pspring-doc.cadn.net.cn

抽样时需要考虑的Tokens的最大累计概率。生成式结合了Top-k和核采样。核抽样考虑概率和至少为topP的最小标记集。spring-doc.cadn.net.cn

-spring-doc.cadn.net.cn

spring.ai.google.genai.chat.options.candidate-countspring-doc.cadn.net.cn

需要返回的生成响应消息数量。该值必须介于[1, 8]之间,包含。默认为1。spring-doc.cadn.net.cn

1spring-doc.cadn.net.cn

spring.ai.google.genai.chat.options.max-输出-标记spring-doc.cadn.net.cn

最多可生成的Tokens数。spring-doc.cadn.net.cn

-spring-doc.cadn.net.cn

spring.ai.google.genai.chat.options.frequency-penaltyspring-doc.cadn.net.cn

减少重复的频率惩罚。spring-doc.cadn.net.cn

-spring-doc.cadn.net.cn

spring.ai.google.genai.chat.options.presence-penaltyspring-doc.cadn.net.cn

减少重复时的在场惩罚。spring-doc.cadn.net.cn

-spring-doc.cadn.net.cn

spring.ai.google.genai.chat.options.thinking-budgetspring-doc.cadn.net.cn

思考过程的预算。spring-doc.cadn.net.cn

-spring-doc.cadn.net.cn

spring.ai.google.genai.chat.options.tool-namesspring-doc.cadn.net.cn

列出了工具,按名称标识,用于在一次提示请求中实现函数调用。带有这些名称的工具必须存在于 ToolCallback 注册表中。spring-doc.cadn.net.cn

-spring-doc.cadn.net.cn

spring.ai.google.genai.chat.options.tool-callbacksspring-doc.cadn.net.cn

工具回调以注册到聊天模型。spring-doc.cadn.net.cn

-spring-doc.cadn.net.cn

spring.ai.google.genai.chat.options.internal-tool-execution-enabledspring-doc.cadn.net.cn

如果为真,则应执行工具执行,否则模型的响应将返回给用户。默认是空,但如果是空,ToolCallingChatOptions.DEFAULT_TOOL_EXECUTION_ENABLED这点是真的,将考虑在内spring-doc.cadn.net.cn

-spring-doc.cadn.net.cn

spring.ai.google.genai.chat.options.safety-settingsspring-doc.cadn.net.cn

根据谷歌生成式人工智能安全设置定义的安全设置列表。每个安全设置可以有方法、阈值和类别。spring-doc.cadn.net.cn

-spring-doc.cadn.net.cn

所有以spring.ai.google.genai.chat.options可以通过在运行时为 请求添加特定的运行时选项来覆盖提示叫。

运行时选项

GoogleGenAiChatOptions.java提供模型配置,如温度、topK等。spring-doc.cadn.net.cn

启动时,默认选项可以配置为GoogleGenAiChatModel(client, options)构造者或spring.ai.google.genai.chat.options.*性能。spring-doc.cadn.net.cn

运行时,你可以通过添加新的、针对请求的选项来覆盖默认选项提示叫。 例如,要覆盖特定请求的默认温度:spring-doc.cadn.net.cn

ChatResponse response = chatModel.call(
    new Prompt(
        "Generate the names of 5 famous pirates.",
        GoogleGenAiChatOptions.builder()
            .temperature(0.4)
        .build()
    ));
除了型号本身谷歌生成人工智能聊天选项你可以使用一个用ChatOptions#builder()创建的便携式ChatOptions实例。

工具调用

谷歌生成式AI模型支持工具调用(函数调用)功能,使模型在对话中能够使用工具。 这里有一个定义和使用的示例@Tool基于工具:spring-doc.cadn.net.cn

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 豆子作为工具:spring-doc.cadn.net.cn

@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();

更多信息请参见工具文档。spring-doc.cadn.net.cn

模 态

多模态指的是模型能够同时理解和处理来自多个(输入)来源的信息,包括文本,PDF格式,图像,音频以及其他数据格式。spring-doc.cadn.net.cn

图像、音频、视频

谷歌的Gemini AI模型支持这一能力,能够理解并整合文本、代码、音频、图像和视频。 更多细节请参见博客文章《介绍双子座》。spring-doc.cadn.net.cn

春季 AI消息界面通过引入媒体类型支持多模态 AI 模型。 这种类型包含关于消息中媒体附件的数据和信息,使用 Spring 的org.springframework.util.MimeType以及一个java.lang.Object对于原始媒体数据。spring-doc.cadn.net.cn

下面是一个从GoogleGenAiChatModelIT.java提取的简单代码示例,演示了用户文本与图片的组合。spring-doc.cadn.net.cn

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文件附加到消息后,媒体类型:spring-doc.cadn.net.cn

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)依赖。spring-doc.cadn.net.cn

添加一个application.properties文件,在src/主/资源目录,用于启用和配置 Google GenAI 聊天模型:spring-doc.cadn.net.cn

使用 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等。。。

每个模型都有自己的支持区域集合,你可以在模型页面找到支持区域列表。spring-doc.cadn.net.cn

这将产生谷歌GenAiChatModel你可以把这些实现注入到你的类里。 这里有一个简单的例子@Controller使用聊天模式生成文本的课程。spring-doc.cadn.net.cn

@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-doc.cadn.net.cn

添加Spring-ai-google-genai对你项目Maven的依赖pom.xml文件:spring-doc.cadn.net.cn

<dependency>
    <groupId>org.springframework.ai</groupId>
    <artifactId>spring-ai-google-genai</artifactId>
</dependency>

或者去你的Gradlebuild.gradle构建文件。spring-doc.cadn.net.cn

dependencies {
    implementation 'org.springframework.ai:spring-ai-google-genai'
}
请参考依赖管理部分,将Spring AI的物料清单添加到你的构建文件中。

接下来,创建一个谷歌GenAiChatModel并用于文本生成:spring-doc.cadn.net.cn

使用 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是流利期权构建器。spring-doc.cadn.net.cn

从 Vertex AI Gemini 迁移

如果你目前正在使用 Vertex AI Gemini 实现 (春-艾-顶点-艾-双子),你可以以最小的改动迁移到 Google GenAI:spring-doc.cadn.net.cn

主要区别

  1. SDK:谷歌生成式人工智能使用新的com.google.genai.客户端而不是com.google.cloud.vertexai.VertexAIspring-doc.cadn.net.cn

  2. 认证:支持API密钥和Google Cloud凭证spring-doc.cadn.net.cn

  3. 软件包名称:类别已入org.springframework.ai.google.genai而不是org.springframework.ai.vertexai.geminispring-doc.cadn.net.cn

  4. 属性前缀:用途spring.ai.google.genai而不是spring.ai.vertex.ai.geminispring-doc.cadn.net.cn

何时使用谷歌生成人工智能 vs 顶点 AI 双子座

在以下情况下使用 Google GenAI : - 你想快速用 API 密钥做原型 - 你需要开发者API中最新的Gemini功能 - 你需要在API密钥和顶点AI模式之间灵活切换spring-doc.cadn.net.cn

在以下情况下使用 Vertex AI Gemini:- 你已有 Vertex AI 基础设施 - 您需要特定的Vertex AI企业功能 - 您的组织需要仅部署Google Cloud系统spring-doc.cadn.net.cn

低级 Java 客户端

谷歌生成式AI实现基于新的谷歌生成人工智能Java SDK构建,该SDK提供了现代化且简化的API,用于访问双子座模型。spring-doc.cadn.net.cn