chat - 聊天会话(对话)的记忆与持久化
大语言模型的接口是无状态的服务,如果需要形成有记忆的会话窗口。需要使用“多消息”提示语,把历史对话都输入。
1、使用“聊天会话”接口(ChatSession)
ChatSession 可以记录消息,还可以作为提示语的参数使用(直接输给 chatModel 的提示语,先输给 chatSession)。起到会话记忆的作用。
public void case3() throws IOException {
//聊天会话
ChatSession chatSession = InMemoryChatSession.builder().maxMessages(10).sessionId("session-1").build(); //安排个会话id
//1.
chatSession.addMessage(ChatMessage.ofUser("hello")); //添加请求消息
chatModel.prompt(chatSession).call(); //(把 chatSession 作为参数)AI消息自动记录到会话里
//2.
chatSession.addMessage(ChatMessage.ofUser("Who are you?")); //添加请求消息
chatModel.prompt(chatSession).stream(); //(把 chatSession 作为参数)AI消息自动汇总并记录到会话里
}
2、基于 Web 的聊天会话记忆参考
import org.noear.solon.ai.chat.ChatModel;
import org.noear.solon.ai.chat.ChatSession;
import org.noear.solon.ai.chat.message.ChatMessage;
import org.noear.solon.ai.chat.session.InMemoryChatSession;
import org.noear.solon.annotation.Controller;
import org.noear.solon.annotation.Header;
import org.noear.solon.annotation.Inject;
import org.noear.solon.annotation.Mapping;
import org.noear.solon.web.sse.SseEvent;
import reactor.core.publisher.Flux;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
@Controller
public class DemoController {
@Inject
ChatModel chatModel;
final Map<String, ChatSession> sessionMap = new ConcurrentHashMap<>();
//手动转为 sse
@Mapping("case3")
public Flux<SseEvent> case3(@Header("sessionId") String sessionId, String prompt) throws IOException {
ChatSession chatSession = sessionMap.computeIfAbsent(sessionId, k -> InMemoryChatSession.builder().build());
chatSession.addMessage(ChatMessage.ofUser(prompt));
//注意提示语的参数:chatSession
return Flux.from(chatModel.prompt(chatSession).stream())
.filter(resp -> resp.hasContent())
.map(resp -> new SseEvent().data(resp.getContent()));
}
}
3、ChatSession 的持久化定制
InMemoryChatSession 只适合开发测试用。一般需要与业务结合,定制需要的聊天会话实现(比如用 Redis 性能就会比较好)。也可以用 JDBC(Mybql、PgSQL、MongoDb),假如有个 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());
}
}
4、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));
}
}
}
}
}