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

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

之前開發了一個關于Google BardJava庫,可以幫助我們簡單的提問并獲得答案?,F在我把它整合到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:

?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容