Spring Boot整合Google Bard - Web接口访问Google AI聊天机器人
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;
import com.google.gson.Gson;
@SpringBootApplication
public class BardApplication {
public static void main(String[] args) {
SpringApplication.run(BardApplication.class, args);
}
}
@RestController
class BardController {
private static final String BARD_URL = "https://europe-west3-dialogflow-bard-222313.cloudfunctions.net/bard/";
private final RestTemplate restTemplate;
private final Gson gson;
public BardController(RestTemplate restTemplate, Gson gson) {
this.restTemplate = restTemplate;
this.gson = gson;
}
@PostMapping("/converse")
public ResponseEntity<String> converse(@RequestBody String message) {
String response = restTemplate.postForObject(BARD_URL, message, String.class);
return ResponseEntity.ok(response);
}
}
这个代码示例展示了如何在Spring Boot应用程序中创建一个简单的HTTP接口来与Google Bard聊天机器人进行交流。它使用了RestTemplate
来发送POST请求到Bard服务的URL,并返回机器人的响应。这个例子简单且直接,适合作为初学者学习如何与Web服务进行交互的示范。
评论已关闭