springboot调用es:-SpringBoot项目引入本地DeepSeek模型实现上下文对话 - core
记录一次在强大的DeepSeek帮助下,实现SpringBoot项目与本地DeepSeek模型进行连续上下文对话功能。
前提:本地已下载好ollama,且在ollama中下载了deepseek模型。
1、配置类
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;
/**
* 配置类
* @author
*/
@Configuration
public class OllamaConfig {
@Bean
public RestTemplate restTemplate() {
return new RestTemplate();
}
}
2、请求、响应DTO类
Ollama的API通过messages数组传递完整的对话历史,模型会自动维护上下文。每个消息需要包含:
role:标识身份(user/assistant)
content:消息内容
import lombok.Data;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* 请求类DTO
* @author
*/ 拼多多帮助力入口
@Data
public class OllamaChatRequest {
private String model;
private Listmessages; // 消息列表
private boolean stream = false;
private Mapoptions = new HashMap<>();
@Data
public static class Message {
private String role;
private String content;
public Message(String role, String content) {
this.role = role;
this.content = content;
}
}
}
import lombok.Data;
/**
* 响应DTO
*/
@Data
public class OllamaChatResponse {
private Message message;
private String createdAt;
private boolean done;
@Data
public static class Message {
private String role;
private String content;
}
}
3、对话管理类(使用Redis存储对话)
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import java.io.Serializable;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
/**
* 对话管理类
* @author
*/
@Service
public class ConversationService {
private static final String REDIS_KEY_PREFIX = "conversation:";
private static final int MAX_HISTORY = 10; // 保留最近10条对话
private static final long TTL_HOURS = 24; // 数据保留24小时
@Autowired
private RedisTemplateredisTemplate;
// 添加消息到对话历史
public void addMessage(String conversationId, String role, String content) {
String key = getRedisKey(conversationId);
Message newMessage = new Message(role, content);
// 使用Redis List存储
redisTemplate.opsForList().rightPush(key, newMessage);
// 修剪列表长度
redisTemplate.opsForList().trim(key, -MAX_HISTORY, -1);
// 设置过期时间
redisTemplate.expire(key, TTL_HOURS, TimeUnit.HOURS);
}
// 获取对话历史
public ListgetHistory(String conversationId) {
String key = getRedisKey(conversationId);
List