chat - 聊天会话的记忆与持久化
大语言模型的接口是无状态的服务,如果需要形成有记忆的会话窗口。需要使用“多消息”提示语,把历史对话都输入。
1、使用“聊天会话”接口(ChatSession)
ChatSession 可以记录消息,还可以作为提示语的参数使用(直接输给 chatModel 的提示语,先输给 chatSession)。起到会话记忆的作用。
public void case3() throws IOException {
//聊天会话
ChatSession chatSession = new ChatSessionDefault("session-1"); //安排个会话id
//1.
chatSession.addMessage(ChatMessage.ofUser("hello")); //添加请求消息
ChatResponse resp = chatModel.prompt(chatSession).call(); //AI消息自动记录到会话里
log.info("{}", resp.getMessage()));
//2.
chatSession.addMessage(ChatMessage.ofUser("Who are you?")); //添加请求消息
resp = chatModel.prompt(chatSession).call(); //AI消息自动记录到会话里
log.info("{}", resp.getMessage());
}
2、ChatSession 的持久化定制
假如有个 SessionJdbcService 服务,是用于会话的消息执久化管理的。通过定制直接同步数据(仅供参考)
public class JdbcChatSession implements ChatSession {
private SessionJdbcService sessionService;
private String sessionId;
public JdbcChatSession(String sessionId) {
this.sessionId = sessionId;
}
@Override
public String getSessionId(){
return sessionId;
}
@Override
public List<ChatMessage> getMessages() {
//设计时,可以通过时间限制消息,或者具体的数量
return sessionService.getMessages(getSessionId(), 100); //只取100条
}
@Override
public void addMessage(ChatMessage... messages) {
sessionService.addMessages(getSessionId(), messages);
}
@Override
public void clear() {
sessionService.clearMessages(getSessionId());
}
}
3、ChatSession 的接口字典
public interface ChatSession {
/**
* 获取会话id
*/
String getSessionId();
/**
* 获取所有消息
*/
List<ChatMessage> getMessages();
/**
* 添加消息
*/
void addMessage(ChatMessage... messages);
/**
* 清空消息
*/
void clear();
/// //////////////////////////////////////
/**
* 转为 ndjson
*/
default String toNdjson() throws IOException {
ByteArrayOutputStream out = new ByteArrayOutputStream();
toNdjson(out);
return new String(out.toByteArray(), Solon.encoding());
}
/**
* 转为 ndjson
*/
default void toNdjson(OutputStream out) throws IOException {
for (ChatMessage msg : getMessages()) {
out.write(ChatMessage.toJson(msg).getBytes(Solon.encoding()));
out.write("\n".getBytes(Solon.encoding()));
out.flush();
}
}
/**
* 加载 ndjson
*/
default void loadNdjson(String ndjson) throws IOException {
loadNdjson(new ByteArrayInputStream(ndjson.getBytes(Solon.encoding())));
}
/**
* 加载 ndjson
*/
default void loadNdjson(InputStream ins) throws IOException {
try (BufferedReader reader = new BufferedReader(new InputStreamReader(ins))) {
while (true) {
String json = reader.readLine();
if (Utils.isEmpty(json)) {
break;
} else {
addMessage(ChatMessage.fromJson(json));
}
}
}
}
}