Spring Boot整合Google Bard - Web介面訪問Google AI聊天機器人

南瓜慢說發表於2023-04-01

Spring Boot整合Google Bard - Web介面訪問Google AI聊天機器人

之前開發了一個關於Google BardJava庫,可以幫助我們簡單的提問並獲得答案。現在我把它整合到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.0.3</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.


References:

相關文章