You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Java中使用Google Vertex AI的Gemini模型并集成Google Search工具?

如何在Java中使用Google Vertex AI的Gemini模型并集成Google Search工具?

我完全懂这种找不到Java相关实操文档的憋屈!之前折腾Vertex AI的Gemini工具调用时,也对着JavaDoc抓了好一阵头,总算摸出了能跑通的路子,给你一步步拆解:

第一步:先搞定依赖

首先得把Vertex AI的Gemini Java SDK加到你的项目里,Maven的话在pom.xml里加这段(记得用最新版本号,SDK更新挺快的):

<dependency>
    <groupId>com.google.cloud</groupId>
    <artifactId>vertexai-gemini</artifactId>
    <version>0.1.0</version> <!-- 去Maven仓库查最新版本替换 -->
</dependency>

Gradle的话就加:

implementation 'com.google.cloud:vertexai-gemini:0.1.0'

第二步:配置Google Cloud认证

Gemini模型跑在Vertex AI上,得先过认证这关:

  • 最简单的方式是设置环境变量GOOGLE_APPLICATION_CREDENTIALS,值指向你的Google Cloud服务账号密钥文件路径(.json格式)
  • 如果你是在Google Cloud的虚拟机/函数里运行,会自动用默认服务账号,不用手动配置

第三步:核心代码实现(带Search工具调用)

这里的逻辑是:先告诉模型有个Google Search工具,模型判断用户问题需要实时信息时,会返回要搜索的查询词,我们执行搜索后把结果喂回模型,生成最终回答。

import com.google.cloud.vertexai.VertexAI;
import com.google.cloud.vertexai.api.GenerateContentResponse;
import com.google.cloud.vertexai.generativeai.GenerativeModel;
import com.google.cloud.vertexai.generativeai.Tool;
import com.google.cloud.vertexai.generativeai.FunctionDeclaration;
import com.google.cloud.vertexai.generativeai.FunctionParameter;
import com.google.cloud.vertexai.generativeai.SchemaType;
import java.util.List;

public class GeminiSearchIntegration {
    public static void main(String[] args) throws Exception {
        // 替换成你的项目ID和Vertex AI区域(比如us-central1、europe-west4)
        String projectId = "your-gcp-project-id";
        String location = "us-central1";
        String modelName = "gemini-1.5-pro-001"; // 用支持工具调用的模型,比如1.5 Pro/Ultra

        try (VertexAI vertexAI = new VertexAI(projectId, location)) {
            // 1. 定义Google Search工具的元数据,告诉模型这个工具能干嘛、要什么参数
            FunctionParameter searchQueryParam = FunctionParameter.newBuilder()
                    .setName("query")
                    .setDescription("需要搜索的关键词或问题语句")
                    .setType(SchemaType.STRING)
                    .setRequired(true) // 标记这个参数是必填的
                    .build();

            FunctionDeclaration searchFunction = FunctionDeclaration.newBuilder()
                    .setName("googleSearch")
                    .setDescription("获取实时公开信息,用于回答需要最新数据的问题(比如当前事件、版本更新等)")
                    .addParameters(searchQueryParam)
                    .build();

            // 把工具绑定到模型配置里
            Tool searchTool = Tool.newBuilder()
                    .addFunctionDeclarations(searchFunction)
                    .build();

            // 2. 初始化带工具支持的生成模型
            GenerativeModel model = new GenerativeModel(modelName, vertexAI)
                    .withTools(List.of(searchTool));

            // 3. 发送用户的原始问题
            String userQuestion = "2024年全球最受欢迎的Java框架排名是怎样的?";
            GenerateContentResponse firstResponse = model.generateContent(userQuestion);

            // 4. 处理模型的工具调用请求
            if (firstResponse.getCandidates(0).getContent().getParts(0).hasFunctionCall()) {
                // 提取模型要求搜索的查询词
                String requiredSearchQuery = firstResponse.getCandidates(0).getContent().getParts(0)
                        .getFunctionCall().getArgs().getFieldsOrDefault("query", null).getStringValue();
                
                // 执行实际的搜索(这里是模拟,实际项目里替换成Google Search API的调用)
                String searchResult = runGoogleSearch(requiredSearchQuery);

                // 5. 把搜索结果喂回模型,让它基于实时信息生成最终回答
                GenerateContentResponse finalAnswer = model.generateContent(
                        "以下是搜索到的实时信息:\n" + searchResult + "\n请基于这些内容回答用户的问题:" + userQuestion);

                // 输出最终结果
                System.out.println("模型最终回答:\n" + finalAnswer.getCandidates(0).getContent().getParts(0).getText());
            } else {
                // 模型不需要搜索,直接返回了回答
                System.out.println("模型回答:\n" + firstResponse.getCandidates(0).getContent().getParts(0).getText());
            }
        }
    }

    // 模拟Google Search的执行逻辑,实际开发中替换为真实的Search API调用
    private static String runGoogleSearch(String query) {
        // 这里只是示例,实际要集成Google Custom Search JSON API或者其他搜索服务
        if (query.contains("2024 Java框架排名")) {
            return "根据2024年Stack Overflow开发者调查,最受欢迎的Java框架排名:1. Spring Boot;2. Spring Framework;3. Quarkus;4. Micronaut;5. Jakarta EE。其中Spring Boot的使用率超过70%,是企业级开发的首选。";
        }
        return "未找到与查询相关的有效信息";
    }
}

关键细节说明

  • 工具定义:FunctionDeclaration是给模型的“工具说明书”,必须写清楚工具的功能和参数,模型才知道什么时候该调用它
  • 工具调用判断:模型会自动分析用户问题,如果是需要实时/外部数据的问题(比如当前排名、最新版本),就会返回FunctionCall;如果是常识性问题,会直接回答
  • 搜索逻辑:示例里用了模拟搜索,实际项目中你需要集成Google的Custom Search API(或者其他搜索服务),拿到结果后格式化成清晰的文本传给模型就行
  • 权限检查:确保你的服务账号有Vertex AI Generative AI User的权限,不然会报认证错误

小提示

别小看JavaDoc!比如点进GenerativeModel的withTools方法,能看到工具绑定的底层逻辑;如果遇到奇怪的报错,去Google Cloud的Vertex AI控制台看日志,能帮你快速定位问题。

内容来源于stack exchange

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.08 12:38:06