# Spring Boot整合Google Bard - Web接口访问Google AI聊天机器人

之前开发了一个关于Google BardJava库 (opens new window),可以帮助我们简单的提问并获得答案。现在我把它整合到Spring Boot应用中,通过Web API让大家可以访问。

# 添加依赖

pkslow google bard添加到Spring Boot项目中去:

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>com.pkslow</groupId>
        <artifactId>google-bard</artifactId>
        <version>0.1.0</version>
    </dependency>
</dependencies>

# 创建GoogleBardClient

在使用它之前,我们需要创建一个对应的GoogleBardClient Bean:

@Configuration
public class GoogleBardConfig {

    @Bean
    public GoogleBardClient googleBardClient(@Value("${ai.google-bard.token}") String token) {
        return new GoogleBardClient(token);
    }
}

# BardController

GoogleBardClient对象注入,通过HTTP GET方法来提问。所以Controller要从GET请求中获取问题,并向Google Bard提问:

@RestController
@RequestMapping("/google-bard")
public class BardController {
    private final GoogleBardClient client;

    public BardController(GoogleBardClient client) {
        this.client = client;
    }


    @GetMapping("/ask")
    public BardAnswer ask(@RequestParam("q") String question) {
        Answer answer = client.ask(question);
        if (answer.status() == AnswerStatus.OK) {
            return new BardAnswer(answer.chosenAnswer(), answer.draftAnswers());
        }

        if (answer.status() == AnswerStatus.NO_ANSWER) {
            return new BardAnswer("No Answer", null);
        }

        throw new RuntimeException("Can't access to Google Bard");

    }
}

获取到答案后,我们返回一个对应的DTO对象。

# 配置

需要配置一个用于鉴权的Token:

server.port=8088
ai.google-bard.token=UgiXYPjpaIYuE9K_3BSqCWnT2W**********************

# 如何获取token

访问: https://bard.google.com/

  • F12
  • 找到Cookie并复制
    • Session: Go to Application → Cookies → __Secure-1PSID.

# 通过Postman测试

Question 1: How to be a good father?

Queston 2: what is pkslow.com?

Log:

# 代码

整合的代码在GitHub (opens new window).


References:

上次更新: 2023/8/18 23:39:36