OpenAi最简洁的Java流式返回接入方式,没有第三方依赖,只需要使用Spring Boot即可!轻松构建你的带有聊天记忆、画图功能的chatgpt!
OpenAi最简洁的Java流式返回接入方式,没有第三方依赖,只需要使用Spring Boot即可!轻松构建你的带有聊天记忆、画图功能的chatgpt!
预览
模型:GPT-3.5-turbo
记忆功能
GPT-3.5-turbo本身不带有记忆功能需要每次把上下文传递过去
int currentToken = (int) (content.length() / TOKEN_CONVERSION_RATE);
List<Message> history = userSessionUtil.getHistory(sessionId, MessageType.TEXT, (int) ((MAX_TOKEN / TOKEN_CONVERSION_RATE) - currentToken));
log.info("history:{}", history);
String historyDialogue = history.stream().map(e -> String.format(e.getUserType().getCode(), e.getMessage())).collect(Collectors.joining());
String prompt = StringUtils.hasLength(historyDialogue) ? String.format("%sQ:%s\n\n", historyDialogue, content) : content;
流式返回
基于WebFlux+SSE实现
接口需要返回 text/event-stream类型
@GetMapping(value = "/completions/stream", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
返回响应式数据
log.info("prompt:{}", prompt);
return Flux.create(emitter -> {
OpenAISubscriber subscriber = new OpenAISubscriber(emitter, sessionId, this, userMessage);
Flux<String> openAiResponse =
openAiWebClient.getChatResponse(sessionId, prompt, null, null, null);
openAiResponse.subscribe(subscriber);
emitter.onDispose(subscriber);
});
帮忙star噢 您的支持就是我的动力
正文到此结束
- 本文链接: https://refblogs.com/article/353
- 版权声明: 本文由老牛原创发布,转载请遵循《署名-非商业性使用-相同方式共享 4.0 国际 (CC BY-NC-SA 4.0)》许可协议授权
热门推荐
相关文章
评论插件初始化中...