链载Ai
标题: 接入SpringAI实现流式对话 [打印本页]
作者: 链载Ai 时间: 2 小时前
标题: 接入SpringAI实现流式对话
前面有讲到Python对接DeepSeek实现对话,但基于现状,从事后端开发,侧重于Java,此次演示以SpringAI技术实现。一定要引入SpringAI的管理依赖,可以方便的使用其他模型及Client!<dependencyManagement><dependencies><!--SpringAI的管理依赖--><dependency><groupId>org.springframework.ai</groupId><artifactId>spring-ai-bom</artifactId><version>${spring-ai.version}</version><type>pom</type><scope>import</scope></dependency></dependencies></dependencyManagement><dependency><groupId>org.springframework.ai</groupId><artifactId>spring-ai-openai-spring-boot-starter</artifactId><version>${spring-ai.version}</version></dependency>此次基于SpringBoot工程演示,没有用到框架,一键启动,真方便。<properties><java.version>17</java.version><spring-ai.version>1.0.0-M5</spring-ai.version></properties>
server:port:8080spring:application:name:ai-demoai
penai:base-url:https://api.deepseek.comapi-key:个人keychat
ptions:model:deepseek-chattemperature:0.7
API接口文档:https://api-docs.deepseek.com/zh-cn/由于需要使用SpringAI自带的ChatClient,如果没有添加配置或用构造方法初始化,会报以下错误。@ComponentpublicclassChatConfig{ /** * 默认形式 *@parammodel *@return */ @Bean publicChatClientchatClient(OpenAiChatModel model) { returnChatClient.builder(model).build(); }}
@RequiredArgsConstructor@RestController@RequestMapping("/ai")@Slf4jpublicclassChatController{ privatefinalChatClient chatClient;
/** * 聊天对话-阻塞式 *@parammessage *@return */ @RequestMapping("/chat") publicString chat(@RequestParam("message")String message) { returnchatClient.prompt() .user(message) .call() .content();
}}
/** * 聊天对话-流式 * *@parammessage *@return */ @RequestMapping(value ="/stream",produces ="text/html;charset=utf-8") publicFlux<String>chatStream(@RequestParam("message")Stringmessage) { log.info("流式测试..."); returnchatClient.prompt() .user(message) .stream() .content();
}
/***添加提示词已通过*@parammodel*@return*/@BeanpublicChatClientchatClient(OpenAiChatModelmodel){returnChatClient.builder(model).defaultSystem("你的名字是小明,身份为学生,请以学生的语气回答问题.").build();} /** * 会话日志 *@parammodel *@return */ @Bean publicChatClientchatClient(OpenAiChatModel model, ChatMemory chatMemory) { returnChatClient .builder(model) .defaultSystem("你的名字是小明,身份为学生,请以学生的语气回答问题.") .defaultAdvisors( newSimpleLoggerAdvisor(), newMessageChatMemoryAdvisor(chatMemory) ) .build(); }
/** * 会话记忆 基于内存-缓存 *@return */ @Bean publicChatMemorychatMemory() { returnnewInMemoryChatMemory(); }
/** * 会话记忆 已通过 *@parammessage *@paramchatId *@return */ @RequestMapping(value ="/memoryChat",produces ="text/html;charset=utf-8") publicFlux<String>memoryChat(@RequestParam("message")Stringmessage,StringchatId) { log.info("流式测试..."); returnchatClient.prompt() .user(message) .advisors(a-> a.param(CHAT_MEMORY_CONVERSATION_ID_KEY, chatId)) .stream() .content();
}
此次新增chatId字段,目的是为一次会话添加唯一标识,基于该标识存储会话记忆,目前使用的内存记忆功能,可以尝试使用向量数据库,永久有效。至此,java对接SpringAI的基本功能已实现。
| 欢迎光临 链载Ai (https://www.lianzai.com/) |
Powered by Discuz! X3.5 |