Spring Boot 集成 AI 可以有多种形式,具体取决于你想要使用哪种 AI 功能(例如:大语言模型对话、图像识别、推荐系统等),以及你打算调用哪种 AI(如 OpenAI、Hugging Face、私有模型等)。
下面我给出一个通用的场景示例:Spring Boot 调用 OpenAI 的 ChatGPT 接口,返回 AI 回答给前端页面(支持 SSE 流式输出)。
✅ 示例:Spring Boot + OpenAI API + SSE 流式输出
1. 添加依赖(pom.xml
)
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-webflux</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
2. 创建 Controller,支持 SSE 输出 AI 回答
@RestController
@RequestMapping("/api/chat")
public class ChatController {
private final WebClient webClient;
public ChatController(WebClient.Builder builder) {
this.webClient = builder.baseUrl("https://api.openai.com").build();
}
@GetMapping(value = "/stream", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
public Flux<String> streamChat(@RequestParam String prompt) {
return webClient.post()
.uri("/v1/chat/completions")
.header("Authorization", "Bearer YOUR_OPENAI_API_KEY")
.header("Content-Type", "application/json")
.bodyValue(buildRequest(prompt))
.retrieve()
.bodyToFlux(String.class);
}
private Map<String, Object> buildRequest(String prompt) {
Map<String, Object> req = new HashMap<>();
req.put("model", "gpt-3.5-turbo");
req.put("stream", true);
req.put("messages", List.of(
Map.of("role", "user", "content", prompt)
));
return req;
}
}
3. WebClient 配置类(可选)
@Configuration
public class WebClientConfig {
@Bean
public WebClient.Builder webClientBuilder() {
return WebClient.builder();
}
}
4. 前端 HTML 示例(用于接收 SSE 流)
<!DOCTYPE html>
<html>
<head>
<title>AI 流式对话</title>
</head>
<body>
<h2>AI 回答:</h2>
<div id="response"></div>
<script>
const eventSource = new EventSource("/api/chat/stream?prompt=介绍一下Java");
eventSource.onmessage = function(event) {
document.getElementById("response").innerHTML += event.data;
};
</script>
</body>
</html>
✅ 效果:
- 前端输入 prompt(如“介绍一下Java”)
- 后端请求 OpenAI 接口,开启
stream=true
模式 - 使用 Spring Boot 的
WebClient
和Flux
将流式内容直接返回给前端 - 前端使用
EventSource
接收逐步返回的内容,实时展示
✅ 支持的 AI 平台扩展方向:
平台 | 说明 |
---|---|
OpenAI | GPT-4 / GPT-3.5,大语言模型、DALL·E 图像生成 |
Hugging Face | 提供多种模型,支持文本生成、翻译、语音识别等 |
百度千帆、讯飞星火 | 国内大模型替代方案 |
本地部署 | 使用 LLM (如 llama.cpp, Ollama, RWKV 等) |
发表回复