1+ // Package chat 提供聊天记录管理和 AI 模型交互功能
12package chat
23
34import (
@@ -11,21 +12,27 @@ import (
1112 zero "github.com/wdvxdr1123/ZeroBot"
1213)
1314
15+ // SystemPrompt 将 README.md 内容嵌入为默认系统提示词
16+ //
1417//go:embed README.md
1518var SystemPrompt string
1619
20+ // lst 全局聊天记录,每群/每用户独立保存最近 8 条
1721var lst = chat .NewLog (8 , "\n \n " , "自己随机开启新话题" , "【" , "】" , ">>" )
1822
1923func init () {
24+ // 注册 ZeroBot 消息钩子,记录所有非空文本
2025 zero .OnMessage (func (ctx * zero.Ctx ) bool {
2126 txt := ctx .ExtractPlainText ()
2227 ctx .State ["__zbputil_chat_txt__" ] = txt
2328 return txt != ""
2429 }).FirstPriority ().SetBlock (false ).Handle (func (ctx * zero.Ctx ) {
30+ // 计算群组 ID(私聊时使用负的 UserID)
2531 gid := ctx .Event .GroupID
2632 if gid == 0 {
2733 gid = - ctx .Event .UserID
2834 }
35+ // 将用户消息追加到对应群组的聊天记录
2936 lst .Add (
3037 gid , ctx .Event .Sender .Name (),
3138 ctx .State ["__zbputil_chat_txt__" ].(string ),
@@ -34,18 +41,26 @@ func init() {
3441 })
3542}
3643
44+ // Reply 将 AI 回复追加到指定群组的聊天记录
3745func Reply (grp int64 , txt string ) {
3846 lst .Add (grp , "" , txt , true , false )
3947}
4048
49+ // Ask 根据聊天记录构造可执行的 deepinfra 模型请求
4150func Ask (p model.Protocol , grp int64 , sysp string , isusersys bool ) deepinfra.Model {
4251 return lst .Modelize (p , grp , sysp , isusersys )
4352}
4453
54+ // AskCustom 通用日志转换函数,允许自定义每条记录的映射逻辑
4555func AskCustom [T any ](grp int64 , f func (int , string ) T ) []T {
4656 return chat .Modelize (& lst , grp , f )
4757}
4858
59+ // Sanitize 清洗 AI 返回文本:
60+ // 1. 去掉换行后内容
61+ // 2. 去掉发言前缀(如【name】或[name])
62+ // 3. 去掉重复 10 次以上的子串
63+ // 4. 去除首尾空白
4964func Sanitize (msg string ) string {
5065 msg , _ , _ = strings .Cut (msg , "\n " )
5166 msg = strings .TrimSpace (msg )
@@ -69,3 +84,8 @@ func Sanitize(msg string) string {
6984 }
7085 return strings .TrimSpace (msg )
7186}
87+
88+ // Reset 清空全局聊天记录,重新开始
89+ func Reset () {
90+ lst .Reset ()
91+ }
0 commit comments