- 新增 CorsConfig 类实现 WebMvcConfigurer 接口 - 配置允许所有域名、方法和请求头的跨域访问- 支持发送 Cookie 凭证信息- 设置预检请求有效期为 1 小时 fix(controller): 修正流式响应的内容类型- 将 OpenAIController 的 generateStream 接口返回类型改为 TEXT_EVENT_STREAM_VALUE - 使用 MediaType.TEXT_EVENT_STREAM_VALUE 替代硬编码字符串 - 确保服务端推送事件(SSE)能正确被客户端接收
54 lines
1.7 KiB
Java
54 lines
1.7 KiB
Java
package com.hanserwei.airobot.controller;
|
|
|
|
import jakarta.annotation.Resource;
|
|
import org.springframework.ai.chat.messages.UserMessage;
|
|
import org.springframework.ai.chat.model.Generation;
|
|
import org.springframework.ai.chat.prompt.Prompt;
|
|
import org.springframework.ai.openai.OpenAiChatModel;
|
|
import org.springframework.http.MediaType;
|
|
import org.springframework.web.bind.annotation.GetMapping;
|
|
import org.springframework.web.bind.annotation.RequestMapping;
|
|
import org.springframework.web.bind.annotation.RequestParam;
|
|
import org.springframework.web.bind.annotation.RestController;
|
|
import reactor.core.publisher.Flux;
|
|
|
|
import java.util.Objects;
|
|
|
|
@RestController
|
|
@RequestMapping("/v5/ai")
|
|
public class OpenAIController {
|
|
|
|
@Resource
|
|
private OpenAiChatModel chatModel;
|
|
|
|
/**
|
|
* 普通对话
|
|
* @param message 对话输入内容
|
|
* @return 对话结果
|
|
*/
|
|
@GetMapping("/generate")
|
|
public String generate(@RequestParam(value = "message", defaultValue = "你是谁?") String message) {
|
|
// 一次性返回结果
|
|
return chatModel.call(message);
|
|
}
|
|
|
|
/**
|
|
* 流式对话
|
|
* @param message 对话输入内容
|
|
* @return 对话结果
|
|
*/
|
|
@GetMapping(value = "/generateStream", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
|
|
public Flux<String> generateStream(@RequestParam(value = "message", defaultValue = "你是谁?") String message) {
|
|
// 构建提示词
|
|
Prompt prompt = new Prompt(new UserMessage(message));
|
|
|
|
// 流式输出
|
|
return chatModel.stream(prompt)
|
|
.mapNotNull(chatResponse -> {
|
|
Generation generation = chatResponse.getResult();
|
|
return generation.getOutput().getText();
|
|
});
|
|
|
|
}
|
|
|
|
} |