前面有讲到Python对接DeepSeek实现对话,但基于现状,从事后端开发,侧重于Java,此次演示以SpringAI技术实现。
一定要引入SpringAI的管理依赖,可以方便的使用其他模型及Client!
<dependencyManagement> <dependencies> <!-- Spring AI的管理依赖 --> <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-demo ai: openai: base-url: https://api.deepseek.com api-key: 个人key chat: options: model: deepseek-chat temperature: 0.7
API接口文档:https://api-docs.deepseek.com/zh-cn/
由于需要使用SpringAI自带的ChatClient,如果没有添加配置或用构造方法初始化,会报以下错误。
@Component
public class ChatConfig {
* 默认形式
* @param model
* @return
*/
@Bean
public ChatClient chatClient(OpenAiChatModel model) {
return ChatClient.builder(model).build();
}
}
@RequiredArgsConstructor
@RestController
@RequestMapping("/ai")
@Slf4j
public class ChatController {
private final ChatClient chatClient;
* 聊天对话-阻塞式
* @param message
* @return
*/
@RequestMapping("/chat")
public String chat(@RequestParam("message") String message) {
return chatClient.prompt()
.user(message)
.call()
.content();
}
}
* 聊天对话-流式
*
* @param message
* @return
*/
@RequestMapping(value = "/stream",produces = "text/html;charset=utf-8")
public Flux<String> chatStream(@RequestParam("message") String message) {
log.info("流式测试...");
return chatClient.prompt()
.user(message)
.stream()
.content();
}
/** * 添加提示词 已通过 * @param model * @return */ @Bean public ChatClient chatClient(OpenAiChatModel model) { return ChatClient .builder(model) .defaultSystem("你的名字是小明,身份为学生,请以学生的语气回答问题.") .build(); }
* 会话日志
* @param model
* @return
*/
@Bean
public ChatClient chatClient(OpenAiChatModel model, ChatMemory chatMemory) {
return ChatClient
.builder(model)
.defaultSystem("你的名字是小明,身份为学生,请以学生的语气回答问题.")
.defaultAdvisors(
new SimpleLoggerAdvisor(),
new MessageChatMemoryAdvisor(chatMemory)
)
.build();
}
* 会话记忆 基于内存-缓存
* @return
*/
@Bean
public ChatMemory chatMemory() {
return new InMemoryChatMemory();
}
* 会话记忆 已通过
* @param message
* @param chatId
* @return
*/
@RequestMapping(value = "/memoryChat",produces = "text/html;charset=utf-8")
public Flux<String> memoryChat(@RequestParam("message") String message, String chatId) {
log.info("流式测试...");
return chatClient.prompt()
.user(message)
.advisors(a-> a.param(CHAT_MEMORY_CONVERSATION_ID_KEY, chatId))
.stream()
.content();
}
此次新增chatId字段,目的是为一次会话添加唯一标识,基于该标识存储会话记忆,目前使用的内存记忆功能,可以尝试使用向量数据库,永久有效。
至此,java对接SpringAI的基本功能已实现。