Spring Boot整合Google Bard - Web接口訪問Google AI聊天機器人
之前開發了一個關于Google Bard
的Java庫,可以幫助我們簡單的提問并獲得答案?,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
- F12
- 找到Cookie并復制
- Session: Go to Application → Cookies →
__Secure-1PSID
.
- Session: Go to Application → Cookies →
通過Postman測試
Question 1: How to be a good father?
Queston 2: what is pkslow.com?
Log:
代碼
整合的代碼在GitHub.
References: