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

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

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

添加依赖

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


    
        org.springframework.boot
        spring-boot-starter-web
    
    
        com.pkslow
        google-bard
        0.0.3
    

创建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?

Spring Boot整合Google Bard - Web接口访问Google AI聊天机器人_第1张图片

Queston 2: what is pkslow.com?

Spring Boot整合Google Bard - Web接口访问Google AI聊天机器人_第2张图片

Log:

代码

整合的代码在GitHub.


References:

你可能感兴趣的:(Spring Boot整合Google Bard - Web接口访问Google AI聊天机器人)