OpenAi最简洁的Java流式返回接入方式,没有第三方依赖,只需要使用Spring Boot即可!轻松构建你的带有聊天记忆、画图功能的chatgpt!
预览
模型:GPT-3.5-turbo
记忆功能
GPT-3.5-turbo本身不带有记忆功能需要每次把上下文传递过去
int currentToken = (int) (content.length() / TOKEN_CONVERSION_RATE); List 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 openAiResponse = openAiWebClient.getChatResponse(sessionId, prompt, null, null, null); openAiResponse.subscribe(subscriber); emitter.onDispose(subscriber); });
帮忙star噢 您的支持就是我的动力
来源地址:https://blog.csdn.net/qq_41389354/article/details/129732571