OpenAi最简洁的Java流式返回接入方式,只需要使用Spring Boot!轻松构建你的带有聊天记忆、画图功能的chatgpt!
源码地址:https://github.com/NiuXiangQian/chatgpt-stream
预览
模型: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噢 您的支持就是我的动力
正文到此结束
相关文章
热门推荐
评论插件初始化中...