Commit 1cc303d1 authored by 赵灿灿's avatar 赵灿灿

增加会话记录

parent a54ffe7a
...@@ -18,6 +18,9 @@ import com.infoepoch.pms.dispatchassistant.domain.langchain.chat.chat.ChatReques ...@@ -18,6 +18,9 @@ import com.infoepoch.pms.dispatchassistant.domain.langchain.chat.chat.ChatReques
import com.infoepoch.pms.dispatchassistant.domain.langchain.chat.chat.ChatSuccessResponse; import com.infoepoch.pms.dispatchassistant.domain.langchain.chat.chat.ChatSuccessResponse;
import com.infoepoch.pms.dispatchassistant.domain.langchain.chat.knowledgeBaseChat.KnowledgeBaseChatRequest; import com.infoepoch.pms.dispatchassistant.domain.langchain.chat.knowledgeBaseChat.KnowledgeBaseChatRequest;
import com.infoepoch.pms.dispatchassistant.domain.langchain.chat.knowledgeBaseChat.KnowledgeBaseChatResponse; import com.infoepoch.pms.dispatchassistant.domain.langchain.chat.knowledgeBaseChat.KnowledgeBaseChatResponse;
import com.infoepoch.pms.dispatchassistant.domain.langchain.history.Conversations;
import com.infoepoch.pms.dispatchassistant.domain.langchain.history.IMessagesRepository;
import com.infoepoch.pms.dispatchassistant.domain.langchain.history.Messages;
import com.infoepoch.pms.dispatchassistant.domain.langchain.qwen.QwenLine; import com.infoepoch.pms.dispatchassistant.domain.langchain.qwen.QwenLine;
import com.infoepoch.pms.dispatchassistant.domain.langchain.record.conversation.Conversation; import com.infoepoch.pms.dispatchassistant.domain.langchain.record.conversation.Conversation;
import com.infoepoch.pms.dispatchassistant.domain.langchain.record.conversation.ConversationCriteria; import com.infoepoch.pms.dispatchassistant.domain.langchain.record.conversation.ConversationCriteria;
...@@ -78,6 +81,7 @@ public class LangChainController { ...@@ -78,6 +81,7 @@ public class LangChainController {
@Autowired @Autowired
private RedisTool redisTool; private RedisTool redisTool;
private static final Logger logger = LoggerFactory.getLogger(LangChainController.class); private static final Logger logger = LoggerFactory.getLogger(LangChainController.class);
/** /**
...@@ -375,6 +379,20 @@ public class LangChainController { ...@@ -375,6 +379,20 @@ public class LangChainController {
mes.put("role","user"); mes.put("role","user");
mes.put("content",chatMessage); mes.put("content",chatMessage);
mesList.add(mes); mesList.add(mes);
Conversations conversations=chatService.saveConversations(sessionId,chatMessage,"内部专家");
Messages messagesQusetion=new Messages();
messagesQusetion.setRequestId(sessionId);
messagesQusetion.setContent(chatMessage);
messagesQusetion.setRole("user");
messagesQusetion.setModelName("qwen2.5-72b");
messagesQusetion=chatService.insertQuestionMessage(conversations,messagesQusetion);
Messages messagesContent=new Messages();
messagesContent.setRole("assistant");
messagesContent.setModelName("qwen2.5-72b");
messagesContent.setParentMsgId(messagesQusetion.getId());
messagesContent.setSort(messagesQusetion.getSort()+1);
chatService.insertMessage(conversations,messagesContent);
if(historyList!=null&&historyList.size()>0) { if(historyList!=null&&historyList.size()>0) {
historyList.addAll(mesList); historyList.addAll(mesList);
map.put("messages", historyList); map.put("messages", historyList);
...@@ -401,6 +419,8 @@ public class LangChainController { ...@@ -401,6 +419,8 @@ public class LangChainController {
mapGet.put("role","assistant"); mapGet.put("role","assistant");
mapGet.put("content",contentGet.toString()); mapGet.put("content",contentGet.toString());
finalHistoryList.add(mapGet); finalHistoryList.add(mapGet);
messagesContent.setContent(contentGet.toString());
chatService.updateMessage(messagesContent);
redisTool.put(sessionId, JsonUtils.objectToJson(finalHistoryList), 2, TimeUnit.HOURS); redisTool.put(sessionId, JsonUtils.objectToJson(finalHistoryList), 2, TimeUnit.HOURS);
Thread.sleep(1000); Thread.sleep(1000);
emitter.complete(); emitter.complete();
...@@ -678,4 +698,29 @@ public class LangChainController { ...@@ -678,4 +698,29 @@ public class LangChainController {
String currentDay = DateTool.format(new Date(), "yyyyMMddHHmmssSSS"); String currentDay = DateTool.format(new Date(), "yyyyMMddHHmmssSSS");
return Result.successData(currentDay+randomNum.toString()); return Result.successData(currentDay+randomNum.toString());
} }
/**
* 会话记录列表
*
* @param
* @return
*/
@GetMapping("/conversationHistory")
public Result conversationHistory() {
List<Map<String,Object>> mapList = chatService.conversationHistory();
return Result.successData(mapList);
}
/**
* 会话记录列表
*
* @param
* @return
*/
@GetMapping("/conversationMessages")
public Result conversationMessages(@RequestParam String sessionId) {
List<Map<String,Object>> mapList= chatService.conversationMessages(sessionId);
return Result.successData(mapList);
}
} }
...@@ -17,9 +17,8 @@ import lombok.Data; ...@@ -17,9 +17,8 @@ import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import java.util.Date; import java.text.SimpleDateFormat;
import java.util.List; import java.util.*;
import java.util.Map;
@Service @Service
public class ChatService { public class ChatService {
...@@ -114,13 +113,13 @@ public class ChatService { ...@@ -114,13 +113,13 @@ public class ChatService {
* @param dialogId * @param dialogId
* 新增会话 * 新增会话
*/ */
private Conversations saveConversations(String dialogId,String question,String aiType) { public Conversations saveConversations(String dialogId,String question,String aiType) {
Conversations conversations=null; Conversations conversations=null;
try { try {
ConversationsCriteria conversationsCriteria=new ConversationsCriteria(); ConversationsCriteria conversationsCriteria=new ConversationsCriteria();
conversationsCriteria.setSessionId(dialogId); conversationsCriteria.setSessionId(dialogId);
List<Conversations> conversationsList=iConversationsRepository.selectByCriteria(conversationsCriteria); List<Conversations> conversationsList=iConversationsRepository.selectByCriteria(conversationsCriteria);
if(conversationsList==null) if(conversationsList==null||conversationsList.size()<=0)
{ {
User user= auth.getUserReq(); User user= auth.getUserReq();
conversations=new Conversations(); conversations=new Conversations();
...@@ -128,10 +127,14 @@ public class ChatService { ...@@ -128,10 +127,14 @@ public class ChatService {
conversations.setUserId(user.getId()); conversations.setUserId(user.getId());
conversations.setUserName(user.getUsername()); conversations.setUserName(user.getUsername());
conversations.setName(user.getFullname()); conversations.setName(user.getFullname());
if(question.length()>15000)
conversations.setFirstQuestion(question.substring(0,15000));
else
conversations.setFirstQuestion(question); conversations.setFirstQuestion(question);
conversations.setAiType(aiType); conversations.setAiType(aiType);
conversations.setSessionId(dialogId); conversations.setSessionId(dialogId);
conversations.setRecordTime(new Date()); conversations.setRecordTime(new Date());
conversations.setStatus("1");
iConversationsRepository.insert(conversations); iConversationsRepository.insert(conversations);
}else }else
conversations=conversationsList.get(0); conversations=conversationsList.get(0);
...@@ -142,16 +145,22 @@ public class ChatService { ...@@ -142,16 +145,22 @@ public class ChatService {
} }
//新增问题信息 //新增问题信息
private Messages insertQuestionMessage(Conversations conversations,Messages questionMes) { public Messages insertQuestionMessage(Conversations conversations,Messages questionMes) {
//查找当前对话的父对话 //查找当前对话的父对话
MessagesCriteria messagesCriteria=new MessagesCriteria(); MessagesCriteria messagesCriteria=new MessagesCriteria();
messagesCriteria.setSessionId(conversations.getSessionId()); messagesCriteria.setSessionId(conversations.getSessionId());
messagesCriteria.setCid(conversations.getId()); messagesCriteria.setCid(conversations.getId());
Messages messagesLast=iMessagesRepository.selectOneByCriteria(messagesCriteria); Messages messagesLast=iMessagesRepository.selectOneByCriteria(messagesCriteria);
if(questionMes.getContent().length()>15000)
questionMes.setContent(questionMes.getContent().substring(0,15000));
try { try {
if(messagesLast!=null) if(messagesLast!=null)
{ {
questionMes.setParentMsgId(messagesLast.getId()); questionMes.setParentMsgId(messagesLast.getId());
questionMes.setSort(messagesLast.getSort()+1);
}else
{
questionMes.setSort(1);
} }
String id=SnowFlake.instant().nextId().toString(); String id=SnowFlake.instant().nextId().toString();
questionMes.setId(id); questionMes.setId(id);
...@@ -166,7 +175,7 @@ public class ChatService { ...@@ -166,7 +175,7 @@ public class ChatService {
} }
//新增回答信息 //新增回答信息
private Messages insertMessage(Conversations conversations,Messages contMes) { public Messages insertMessage(Conversations conversations,Messages contMes) {
try { try {
String id=SnowFlake.instant().nextId().toString(); String id=SnowFlake.instant().nextId().toString();
contMes.setId(id); contMes.setId(id);
...@@ -179,4 +188,128 @@ public class ChatService { ...@@ -179,4 +188,128 @@ public class ChatService {
} }
return contMes; return contMes;
} }
//更新回答信息
public Messages updateMessage(Messages contMes) {
try {
if(contMes.getContent().length()>15000)
contMes.setContent(contMes.getContent().substring(0,15000));
iMessagesRepository.update(contMes);
} catch (Exception e) {
e.printStackTrace();
}
return contMes;
}
//查询近7天的会话信息
public List<Map<String,Object>> conversationHistory()
{
List<Map<String,Object>> mapList=new ArrayList<>();
try {
User user= auth.getUserReq();
ConversationsCriteria conversationsCriteria=new ConversationsCriteria();
conversationsCriteria.setUserId(user.getId());
conversationsCriteria.setConversationsDays(7);
List<Conversations> conversationsList=iConversationsRepository.selectByCriteria(conversationsCriteria);
if(conversationsList!=null&&conversationsList.size()>0)
{
Date todayDate=getToday();
Date yesterday=getYesterday();
Map<String,Object> todayMap=new HashMap<>();
Map<String,Object> yesterdayMap=new HashMap<>();
Map<String,Object> sevendayMap=new HashMap<>();
List<Map<String,Object>> todayMapList=new ArrayList<>();
List<Map<String,Object>> yesterdayMapList=new ArrayList<>();
List<Map<String,Object>> sevendayMapList=new ArrayList<>();
todayMap.put("label","今天");
yesterdayMap.put("label","昨天");
sevendayMap.put("label","7天内");
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("HH:mm");
for (Conversations conversations:
conversationsList) {
if(conversations.getRecordTime().after(todayDate))
{
Map<String,Object> td=new HashMap<>();
td.put("id",conversations.getSessionId());
td.put("title",conversations.getFirstQuestion());
td.put("time",simpleDateFormat.format(conversations.getRecordTime()));
td.put("active",false);
td.put("showMenu",false);
todayMapList.add(td);
}else if(conversations.getRecordTime().before(todayDate)&&conversations.getRecordTime().after(yesterday))
{
Map<String,Object> yd=new HashMap<>();
yd.put("id",conversations.getSessionId());
yd.put("title",conversations.getFirstQuestion());
yd.put("time",simpleDateFormat.format(conversations.getRecordTime()));
yd.put("active",true);
yd.put("showMenu",false);
yesterdayMapList.add(yd);
}else
{
Map<String,Object> sd=new HashMap<>();
sd.put("id",conversations.getSessionId());
sd.put("title",conversations.getFirstQuestion());
sd.put("time",simpleDateFormat.format(conversations.getRecordTime()));
sd.put("active",true);
sd.put("showMenu",false);
sevendayMapList.add(sd);
}
}
todayMap.put("items",todayMapList);
yesterdayMap.put("items",yesterdayMapList);
sevendayMap.put("items",sevendayMapList);
mapList.add(todayMap);
mapList.add(yesterdayMap);
mapList.add(sevendayMap);
}
} catch (Exception e) {
e.printStackTrace();
}
return mapList;
}
//查询会话内容通过会话id
public List<Map<String,Object>> conversationMessages(String sessionId)
{
List<Map<String,Object>> mapList=new ArrayList<>();
try {
MessagesCriteria messagesCriteria=new MessagesCriteria();
messagesCriteria.setSessionId(sessionId);
List<Messages> messagesList= iMessagesRepository.selectByCriteria(messagesCriteria);
for (Messages mes:
messagesList) {
Map<String,Object> map=new HashMap<>();
map.put("role",mes.getRole());
map.put("content",mes.getContent());
mapList.add(map);
}
} catch (Exception e) {
e.printStackTrace();
}
return mapList;
}
public Date getToday()
{
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, 0); // 设置小时为 0
calendar.set(Calendar.MINUTE, 0); // 分钟归零
calendar.set(Calendar.SECOND, 0); // 秒归零
calendar.set(Calendar.MILLISECOND, 0); // 毫秒归零
return calendar.getTime();
}
public Date getYesterday()
{
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.DAY_OF_YEAR, -1); // 减 1 天
calendar.set(Calendar.HOUR_OF_DAY, 0); // 小时归零
calendar.set(Calendar.MINUTE, 0); // 分钟归零
calendar.set(Calendar.SECOND, 0); // 秒归零
calendar.set(Calendar.MILLISECOND, 0); // 毫秒归零
return calendar.getTime();
}
} }
...@@ -117,7 +117,7 @@ public class Conversations { ...@@ -117,7 +117,7 @@ public class Conversations {
return updateTime; return updateTime;
} }
public void setUpdateTime(Date updateTime) { public void setUpdateTime(Date updateTime) {
this.recordTime = updateTime; this.updateTime = updateTime;
} }
public String getAiType() { public String getAiType() {
return aiType; return aiType;
......
...@@ -141,4 +141,23 @@ public class ConversationsCriteria extends AbstractCriteria { ...@@ -141,4 +141,23 @@ public class ConversationsCriteria extends AbstractCriteria {
} }
//endregion //endregion
//region 查询近几天会话
public boolean byConversationsDays() {
return this.andMap.containsKey("ConversationsDays");
}
private Integer conversationsDays;
public Integer getConversationsDays() {
if (byConversationsDays())
return conversationsDays;
return null;
}
public void setConversationsDays(Integer value) {
this.conversationsDays = value;
this.andMap.put("ConversationsDays", value);
}
//endregion
} }
\ No newline at end of file
...@@ -53,6 +53,9 @@ public class Messages { ...@@ -53,6 +53,9 @@ public class Messages {
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8") @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
private Date recordTime; private Date recordTime;
/**
* 排序
*/
public String getId() { public String getId() {
return id; return id;
...@@ -118,4 +121,13 @@ public class Messages { ...@@ -118,4 +121,13 @@ public class Messages {
public void setRecordTime(Date recordTime) { public void setRecordTime(Date recordTime) {
this.recordTime = recordTime; this.recordTime = recordTime;
} }
private Integer sort;
public Integer getSort() {
return sort;
}
public void setSort(Integer sort) {
this.sort = sort;
}
} }
\ No newline at end of file
...@@ -274,6 +274,9 @@ public class ConversationsRepository implements IConversationsRepository { ...@@ -274,6 +274,9 @@ public class ConversationsRepository implements IConversationsRepository {
//条件1 //条件1
if (criteria.byCondition1()) if (criteria.byCondition1())
andMap.put(criteria.getCondition1() == null ? " C_CONDITION1 IS NULL " : " C_CONDITION1 = ? ", criteria.getCondition1()); andMap.put(criteria.getCondition1() == null ? " C_CONDITION1 IS NULL " : " C_CONDITION1 = ? ", criteria.getCondition1());
//查询近几天会话
if (criteria.byConversationsDays())
andMap.put(criteria.getConversationsDays() == null ? " C_RECORD_TIME IS NULL " : "C_RECORD_TIME>=sysdate-? ", criteria.getConversationsDays());
return andMap; return andMap;
} }
......
...@@ -46,10 +46,10 @@ public class MessagesRepository implements IMessagesRepository { ...@@ -46,10 +46,10 @@ public class MessagesRepository implements IMessagesRepository {
*/ */
@Override @Override
public boolean insert(Messages entity) { public boolean insert(Messages entity) {
String sql = "INSERT INTO T_MESSAGES(M_ID, M_CID, M_SESSION_ID, M_REQUEST_ID, M_ROLE, M_CONTENT, M_PARENT_MSG_ID, M_KEY_WORDS, M_MODEL_NAME, M_RECORD_TIME) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"; String sql = "INSERT INTO T_MESSAGES(M_ID, M_CID, M_SESSION_ID, M_REQUEST_ID, M_ROLE, M_CONTENT, M_PARENT_MSG_ID, M_KEY_WORDS, M_MODEL_NAME, M_RECORD_TIME,M_SORT) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?,?)";
int result=0; int result=0;
try { try {
result = jdbcTemplate.update(sql, entity.getId(), entity.getCid(), entity.getSessionId(), entity.getRequestId(), entity.getRole(), entity.getContent(), entity.getParentMsgId(), entity.getKeyWords(), entity.getModelName(), entity.getRecordTime()); result = jdbcTemplate.update(sql, entity.getId(), entity.getCid(), entity.getSessionId(), entity.getRequestId(), entity.getRole(), entity.getContent(), entity.getParentMsgId(), entity.getKeyWords(), entity.getModelName(), entity.getRecordTime(),entity.getSort());
} catch (Exception e) { } catch (Exception e) {
LogHelper.info(e.getMessage()); LogHelper.info(e.getMessage());
// throw new ServiceException("新增 数据 失败。"); // throw new ServiceException("新增 数据 失败。");
...@@ -62,10 +62,10 @@ public class MessagesRepository implements IMessagesRepository { ...@@ -62,10 +62,10 @@ public class MessagesRepository implements IMessagesRepository {
*/ */
@Override @Override
public boolean update(Messages entity) { public boolean update(Messages entity) {
String sql = "UPDATE T_MESSAGES SET M_CID = ?, M_SESSION_ID = ?, M_REQUEST_ID = ?, M_ROLE = ?, M_CONTENT = ?, M_PARENT_MSG_ID = ?, M_KEY_WORDS = ?, M_MODEL_NAME = ?, M_RECORD_TIME = ? WHERE M_ID = ?"; String sql = "UPDATE T_MESSAGES SET M_CID = ?, M_SESSION_ID = ?, M_REQUEST_ID = ?, M_ROLE = ?, M_CONTENT = ?, M_PARENT_MSG_ID = ?, M_KEY_WORDS = ?, M_MODEL_NAME = ?, M_RECORD_TIME = ?,M_SORT=? WHERE M_ID = ?";
int result=0; int result=0;
try { try {
result = jdbcTemplate.update(sql, entity.getCid(), entity.getSessionId(), entity.getRequestId(), entity.getRole(), entity.getContent(), entity.getParentMsgId(), entity.getKeyWords(), entity.getModelName(), entity.getRecordTime(), entity.getId()); result = jdbcTemplate.update(sql, entity.getCid(), entity.getSessionId(), entity.getRequestId(), entity.getRole(), entity.getContent(), entity.getParentMsgId(), entity.getKeyWords(), entity.getModelName(), entity.getRecordTime(),entity.getSort(), entity.getId());
} catch (Exception e) { } catch (Exception e) {
LogHelper.info(e.getMessage()); LogHelper.info(e.getMessage());
// throw new ServiceException("更新 数据 失败。"); // throw new ServiceException("更新 数据 失败。");
...@@ -77,7 +77,7 @@ public class MessagesRepository implements IMessagesRepository { ...@@ -77,7 +77,7 @@ public class MessagesRepository implements IMessagesRepository {
* 批量新增 * 批量新增
*/ */
public int[] batchInsert(List<Messages> list) { public int[] batchInsert(List<Messages> list) {
String sql = "INSERT INTO T_MESSAGES(M_ID, M_CID, M_SESSION_ID, M_REQUEST_ID, M_ROLE, M_CONTENT, M_PARENT_MSG_ID, M_KEY_WORDS, M_MODEL_NAME, M_RECORD_TIME) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"; String sql = "INSERT INTO T_MESSAGES(M_ID, M_CID, M_SESSION_ID, M_REQUEST_ID, M_ROLE, M_CONTENT, M_PARENT_MSG_ID, M_KEY_WORDS, M_MODEL_NAME, M_RECORD_TIME,M_SORT) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?,?)";
int[] result = jdbcTemplate.batchUpdate(sql, new BatchPreparedStatementSetter() { int[] result = jdbcTemplate.batchUpdate(sql, new BatchPreparedStatementSetter() {
@Override @Override
public void setValues(PreparedStatement ps, int i) throws SQLException { public void setValues(PreparedStatement ps, int i) throws SQLException {
...@@ -93,6 +93,7 @@ public class MessagesRepository implements IMessagesRepository { ...@@ -93,6 +93,7 @@ public class MessagesRepository implements IMessagesRepository {
ps.setString(++j, item.getKeyWords()); ps.setString(++j, item.getKeyWords());
ps.setString(++j, item.getModelName()); ps.setString(++j, item.getModelName());
ps.setTimestamp(++j, item.getRecordTime() != null ? new Timestamp(item.getRecordTime().getTime()) : null); ps.setTimestamp(++j, item.getRecordTime() != null ? new Timestamp(item.getRecordTime().getTime()) : null);
ps.setInt(++j, item.getSort());
} }
@Override @Override
...@@ -107,7 +108,7 @@ public class MessagesRepository implements IMessagesRepository { ...@@ -107,7 +108,7 @@ public class MessagesRepository implements IMessagesRepository {
* 批量更新 * 批量更新
*/ */
public int[] batchUpdate(List<Messages> list) { public int[] batchUpdate(List<Messages> list) {
String sql = "UPDATE T_MESSAGES SET M_CID = ?, M_SESSION_ID = ?, M_REQUEST_ID = ?, M_ROLE = ?, M_CONTENT = ?, M_PARENT_MSG_ID = ?, M_KEY_WORDS = ?, M_MODEL_NAME = ?, M_RECORD_TIME = ? WHERE M_ID = ? "; String sql = "UPDATE T_MESSAGES SET M_CID = ?, M_SESSION_ID = ?, M_REQUEST_ID = ?, M_ROLE = ?, M_CONTENT = ?, M_PARENT_MSG_ID = ?, M_KEY_WORDS = ?, M_MODEL_NAME = ?, M_RECORD_TIME = ? ,M_SORT=? WHERE M_ID = ? ";
int[] result = jdbcTemplate.batchUpdate(sql, new BatchPreparedStatementSetter() { int[] result = jdbcTemplate.batchUpdate(sql, new BatchPreparedStatementSetter() {
@Override @Override
public void setValues(PreparedStatement ps, int i) throws SQLException { public void setValues(PreparedStatement ps, int i) throws SQLException {
...@@ -122,6 +123,7 @@ public class MessagesRepository implements IMessagesRepository { ...@@ -122,6 +123,7 @@ public class MessagesRepository implements IMessagesRepository {
ps.setString(++j, item.getKeyWords()); ps.setString(++j, item.getKeyWords());
ps.setString(++j, item.getModelName()); ps.setString(++j, item.getModelName());
ps.setTimestamp(++j, item.getRecordTime() != null ? new Timestamp(item.getRecordTime().getTime()) : null); ps.setTimestamp(++j, item.getRecordTime() != null ? new Timestamp(item.getRecordTime().getTime()) : null);
ps.setInt(++j, item.getSort());
ps.setString(++j, item.getId()); ps.setString(++j, item.getId());
} }
...@@ -169,7 +171,7 @@ public class MessagesRepository implements IMessagesRepository { ...@@ -169,7 +171,7 @@ public class MessagesRepository implements IMessagesRepository {
@Override @Override
public Messages selectOneByCriteria(MessagesCriteria criteria) { public Messages selectOneByCriteria(MessagesCriteria criteria) {
StringBuffer buffer = new StringBuffer("SELECT * FROM T_MESSAGES "); StringBuffer buffer = new StringBuffer("SELECT * FROM T_MESSAGES ");
List<Object> list = OracleUtils.combinationSql(buffer, createCriteriaSql(criteria), 1, 1,"M_RECORD_TIME",true); List<Object> list = OracleUtils.combinationSql(buffer, createCriteriaSql(criteria), 1, 1,"M_SORT",true);
try { try {
return jdbcTemplate.queryForObject(buffer.toString(), list.toArray(), new MessagesRowMapper()); return jdbcTemplate.queryForObject(buffer.toString(), list.toArray(), new MessagesRowMapper());
} catch (Exception e) { } catch (Exception e) {
...@@ -184,7 +186,7 @@ public class MessagesRepository implements IMessagesRepository { ...@@ -184,7 +186,7 @@ public class MessagesRepository implements IMessagesRepository {
@Override @Override
public List<Messages> selectByCriteria(MessagesCriteria criteria) { public List<Messages> selectByCriteria(MessagesCriteria criteria) {
StringBuffer buffer = new StringBuffer("SELECT * FROM T_MESSAGES "); StringBuffer buffer = new StringBuffer("SELECT * FROM T_MESSAGES ");
List<Object> list = OracleUtils.combinationSql(buffer, createCriteriaSql(criteria)); List<Object> list = OracleUtils.combinationSql(buffer, createCriteriaSql(criteria),"M_SORT",false);
try { try {
return jdbcTemplate.query(buffer.toString(), list.toArray(), new MessagesRowMapper()); return jdbcTemplate.query(buffer.toString(), list.toArray(), new MessagesRowMapper());
} catch (Exception e) { } catch (Exception e) {
...@@ -236,6 +238,7 @@ public class MessagesRepository implements IMessagesRepository { ...@@ -236,6 +238,7 @@ public class MessagesRepository implements IMessagesRepository {
messages.setKeyWords(rs.getString("M_KEY_WORDS")); messages.setKeyWords(rs.getString("M_KEY_WORDS"));
messages.setModelName( rs.getString("M_MODEL_NAME")); messages.setModelName( rs.getString("M_MODEL_NAME"));
messages.setRecordTime(rs.getTimestamp("M_RECORD_TIME")); messages.setRecordTime(rs.getTimestamp("M_RECORD_TIME"));
messages.setSort(rs.getInt("M_SORT"));
return messages; return messages;
} }
} }
......
...@@ -201,7 +201,7 @@ ...@@ -201,7 +201,7 @@
const messagesDiv = document.getElementById('chat-messages'); const messagesDiv = document.getElementById('chat-messages');
aiMessageDiv.className = 'message ai-message'; aiMessageDiv.className = 'message ai-message';
document.getElementById('chat-messages').appendChild(aiMessageDiv); document.getElementById('chat-messages').appendChild(aiMessageDiv);
const eventSource = new EventSource('../../api/langchain/sseBigTwo?chatMessage='+chatMessage+"&sessionId="+sessionId); const eventSource = new EventSource('../../api/langchain/simulate?chatMessage='+chatMessage+"&sessionId="+sessionId);
eventSource.onmessage = (event) => { eventSource.onmessage = (event) => {
const data = JSON.parse(event.data); const data = JSON.parse(event.data);
const content=data.dataToSend[1].data; const content=data.dataToSend[1].data;
......
...@@ -89,6 +89,7 @@ require(['jquery', 'vue', 'utils','marked','markdown', 'global'], function ($, V ...@@ -89,6 +89,7 @@ require(['jquery', 'vue', 'utils','marked','markdown', 'global'], function ($, V
created: function () { created: function () {
this.currentUser(); this.currentUser();
this.getSessionId(); this.getSessionId();
this.getConversationHistory();
}, },
mounted: function () { mounted: function () {
// 监听输入框的键盘事件 // 监听输入框的键盘事件
...@@ -99,12 +100,12 @@ require(['jquery', 'vue', 'utils','marked','markdown', 'global'], function ($, V ...@@ -99,12 +100,12 @@ require(['jquery', 'vue', 'utils','marked','markdown', 'global'], function ($, V
} }
// 添加全局点击事件以关闭菜单 // 添加全局点击事件以关闭菜单
document.addEventListener('click', (event) => { // document.addEventListener('click', (event) => {
// 检查点击是否在菜单按钮上 // // 检查点击是否在菜单按钮上
if (!event.target.closest('.menu-btn') && !event.target.closest('.menu-dropdown')) { // if (!event.target.closest('.menu-btn') && !event.target.closest('.menu-dropdown')) {
this.closeAllMenus(); // this.closeAllMenus();
} // }
}); // });
}); });
}, },
methods: { methods: {
...@@ -140,6 +141,16 @@ require(['jquery', 'vue', 'utils','marked','markdown', 'global'], function ($, V ...@@ -140,6 +141,16 @@ require(['jquery', 'vue', 'utils','marked','markdown', 'global'], function ($, V
console.error('会话ID获取失败', error); console.error('会话ID获取失败', error);
} }
}, },
async getConversationHistory() {
try {
//const response = await fetch('../../api/langchain/getSessionId');
const response = await fetch('../../api/langchain/conversationHistory');
const dataJson = await response.json();
this.historySections = dataJson.data;
} catch (error) {
console.error('会话获取失败', error);
}
},
// 聊天相关方法 // 聊天相关方法
handleKeyPress(e) { handleKeyPress(e) {
...@@ -306,22 +317,38 @@ require(['jquery', 'vue', 'utils','marked','markdown', 'global'], function ($, V ...@@ -306,22 +317,38 @@ require(['jquery', 'vue', 'utils','marked','markdown', 'global'], function ($, V
}, },
loadChatHistory(chatId) { loadChatHistory(chatId) {
var that=this
// 关闭所有菜单 // 关闭所有菜单
this.historySections.forEach(section => { this.historySections.forEach(section => {
section.items.forEach(item => { section.items.forEach(item => {
item.showMenu = false; item.showMenu = false;
}); });
}); });
//this.addMessage('user', "123456");
// 设置活跃状态 // 设置活跃状态
this.historySections.forEach(section => { this.historySections.forEach(section => {
section.items.forEach(item => { section.items.forEach(item => {
item.active = (item.id === chatId); item.active = (item.id === chatId);
}); });
}); });
//
// 这里添加加载对应对话历史的逻辑 this.sessionId = chatId;
// 实际实现时可以调用API获取历史记录 // this.clearChat();
//这里添加加载对应对话历史的逻辑
//实际实现时可以调用API获取历史记录
$.ajax({
url: "../../api/langchain/conversationMessages?sessionId="+chatId,
type: "get",
dataType: "json",
contentType: "application/json;charset=UTF-8",
async: false,
success: function (data) {
var mes = data.data;
mes.forEach(section => {
that.addMessage(section.role, section.content);
});
}
});
}, },
// 删除对话 // 删除对话
deleteChat(chatId) { deleteChat(chatId) {
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment