Merge remote-tracking branch 'upstream/refactor' into refactor

This commit is contained in:
tcmofashi
2025-03-29 23:58:16 +08:00
43 changed files with 615 additions and 690 deletions

101
README.md
View File

@@ -1,82 +1,4 @@
# 关于项目分支调整与贡献指南的重要通知
<details>
<summary>
- 📂 致所有为麦麦提交过贡献,以及想要为麦麦提交贡献的朋友们!</summary>
---
**📢 关于项目分支调整与贡献指南的重要通知**
**致所有关注MaiMBot的开发者与贡献者**
首先我们由衷感谢大家近期的热情参与感谢大家对MaiMBot的喜欢项目突然受到广泛关注让我们倍感惊喜也深深感受到开源社区的温暖力量。为了保障项目长期健康发展我们不得不对开发流程做出重要调整恳请理解与支持。
---
### **📌 本次调整的核心原因**
1. **维护团队精力有限**
核心成员(包括我本人)均为在校学生/在职开发者近期涌入的大量PR和意见已远超我们的处理能力。为确保本职工作与项目质量我们必须优化协作流程。
2. **重构核心架构的紧迫性**
当前我们正与核心团队全力重构项目底层逻辑,这是为未来扩展性、性能提升打下的必要基础,需要高度专注。
3. **保障现有用户的稳定性**
我们深知许多用户已依赖当前版本,因此必须划分清晰的维护边界,确保生产环境可用性。
---
### **🌿 全新分支策略与贡献指南**
为平衡上述目标,即日起启用以下分支结构:
| 分支 | 定位 | 接受PR类型 | 提交对象 |
| ---------- | ---------------------------- | --------------------------------------------- | ---------------- |
| `main` | **稳定版**(供下载使用) | 仅接受来自`main-fix`的合并 | 维护团队直接管理 |
| `main-fix` | 生产环境紧急修复 | 明确的功能缺陷修复(需附带复现步骤/测试用例) | 所有开发者 |
| `refactor` | 重构版(**不兼容当前main** | 仅重构与相关Bug修复 | 重构小组维护 |
---
### **⚠️ 对现有PR的处理说明**
由于分支结构调整,**GitHub已自动关闭所有未合并的PR**这并非否定您的贡献价值如果您认为自己的PR符合以下条件
- 属于`main-fix`明确的**功能性缺陷修复**(非功能增强) 包括非预期行为和严重报错需要发布issue讨论确定。
- 属于`refactor`分支的**重构适配性修复**
**欢迎您重新提交到对应分支**并在PR描述中标注`[Re-submit from closed PR]`我们将优先审查。其他类型PR暂缓受理但您的创意我们已记录在案未来重构完成后将重新评估。
---
### **🙏 致谢与协作倡议**
- 感谢每一位提交Issue、PR、参与讨论的开发者您的每一行代码都是maim吃的
- 特别致敬在交流群中积极答疑的社区成员,你们自发维护的氛围令人感动❤️ maim哭了
- **重构期间的非代码贡献同样珍贵**文档改进、测试用例补充、用户反馈整理等欢迎通过Issue认领任务
---
### **📬 高效协作小贴士**
1. **提交前请先讨论**创建Issue描述问题确认是否符合`main-fix`修复范围
2. **对重构提出您的想法**如果您对重构版有自己的想法欢迎提交讨论issue亟需测试伙伴欢迎邮件联系`team@xxx.org`报名
3. **部分main-fix的功能在issue讨论后经过严格讨论一致决定可以添加功能改动或修复的可以提交pr**
---
**谢谢大家谢谢大家谢谢大家谢谢大家谢谢大家谢谢大家!**
虽然此刻不得不放缓脚步,但这一切都是为了跳得更高。期待在重构完成后与各位共建更强大的版本!
千石可乐 敬上
2025年3月14日
</details>
# 麦麦MaiMBot (编辑中)
# 麦麦MaiMBot-MaiCore (编辑中)
<div align="center">
@@ -88,14 +10,13 @@
## 📝 项目简介
**🍔麦麦是一个基于大语言模型的智能QQ群聊机器人**
**🍔MaiCore是一个基于大语言模型的可交互智能体**
- 基于 nonebot2 框架开发
- LLM 提供对话能力
- MongoDB 提供数据持久化支持
- NapCat 作为QQ协议端支持
- 可扩展
**最新版本: v0.5.15** ([查看更新日志](changelog.md))
**最新版本: v0.6.0-mmc** ([查看更新日志](changelog.md))
> [!WARNING]
> 该版本更新较大,建议单独开文件夹部署,然后转移/data文件数据库可能需要删除messages下的内容不需要删除记忆
@@ -115,17 +36,10 @@
> - 由于持续迭代可能存在一些已知或未知的bug
> - 由于开发中可能消耗较多token
**📚 有热心网友创作的wiki:** https://maimbot.pages.dev/
**📚 由SLAPQ制作的B站教程:** https://www.bilibili.com/opus/1041609335464001545
**😊 其他平台版本**
- (由 [CabLate](https://github.com/cablate) 贡献) [Telegram 与其他平台(未来可能会有)的版本](https://github.com/cablate/MaiMBot/tree/telegram) - [集中讨论串](https://github.com/SengokuCola/MaiMBot/discussions/149)
## ✍如何给本项目报告BUG/提交建议/做贡献
MaiMBot是一个开源项目我们非常欢迎你的参与。你的贡献无论是提交bug报告、功能需求还是代码pr都对项目非常宝贵。我们非常感谢你的支持🎉 但无序的讨论会降低沟通效率,进而影响问题的解决速度,因此在提交任何贡献前,请务必先阅读本项目的[贡献指南](CONTRIBUTE.md)
MaiCore是一个开源项目我们非常欢迎你的参与。你的贡献无论是提交bug报告、功能需求还是代码pr都对项目非常宝贵。我们非常感谢你的支持🎉 但无序的讨论会降低沟通效率,进而影响问题的解决速度,因此在提交任何贡献前,请务必先阅读本项目的[贡献指南](CONTRIBUTE.md)
### 💬交流群
- [五群](https://qm.qq.com/q/JxvHZnxyec) 1022489779开发和建议相关讨论不一定有空回复会优先写文档和代码
@@ -151,10 +65,6 @@ MaiMBot是一个开源项目我们非常欢迎你的参与。你的贡献
- [📦 macOS 手动部署指南 ](docs/manual_deploy_macos.md)
如果你不知道Docker是什么建议寻找相关教程或使用手动部署 **现在不建议使用docker更新慢可能不适配**
- [🐳 Docker部署指南](docs/docker_deploy.md)
- [🖥️群晖 NAS 部署指南](docs/synology_deploy.md)
### 配置说明
@@ -170,7 +80,6 @@ MaiMBot是一个开源项目我们非常欢迎你的参与。你的贡献
<h3>了解麦麦 </h3>
</div>
- [项目架构说明](docs/doc1.md) - 项目结构和核心功能实现细节
## 🎯 功能介绍

53
bot.py
View File

@@ -45,56 +45,25 @@ def init_config():
logger.info("创建config目录")
shutil.copy("template/bot_config_template.toml", "config/bot_config.toml")
logger.info("复制完成请修改config/bot_config.toml和.env.prod中的配置后重新启动")
logger.info("复制完成请修改config/bot_config.toml和.env中的配置后重新启动")
def init_env():
# 初始化.env 默认ENVIRONMENT=prod
# 检测.env文件是否存在
if not os.path.exists(".env"):
with open(".env", "w") as f:
f.write("ENVIRONMENT=prod")
# 检测.env.prod文件是否存在
if not os.path.exists(".env.prod"):
logger.error("检测到.env.prod文件不存在")
shutil.copy("template.env", "./.env.prod")
# 检测.env.dev文件是否存在不存在的话直接复制生产环境配置
if not os.path.exists(".env.dev"):
logger.error("检测到.env.dev文件不存在")
shutil.copy(".env.prod", "./.env.dev")
# 首先加载基础环境变量.env
if os.path.exists(".env"):
load_dotenv(".env", override=True)
logger.success("成功加载基础环境变量配置")
logger.error("检测到.env文件不存在")
shutil.copy("template/template.env", "./.env")
logger.info("已从template/template.env复制创建.env请修改配置后重新启动")
def load_env():
# 使用闭包实现对加载器的横向扩展,避免大量重复判断
def prod():
logger.success("成功加载生产环境变量配置")
load_dotenv(".env.prod", override=True) # override=True 允许覆盖已存在的环境变量
def dev():
logger.success("成功加载开发环境变量配置")
load_dotenv(".env.dev", override=True) # override=True 允许覆盖已存在的环境变量
fn_map = {"prod": prod, "dev": dev}
env = os.getenv("ENVIRONMENT")
logger.info(f"[load_env] 当前的 ENVIRONMENT 变量值:{env}")
if env in fn_map:
fn_map[env]() # 根据映射执行闭包函数
elif os.path.exists(f".env.{env}"):
logger.success(f"加载{env}环境变量配置")
load_dotenv(f".env.{env}", override=True) # override=True 允许覆盖已存在的环境变量
# 直接加载生产环境变量配置
if os.path.exists(".env"):
load_dotenv(".env", override=True)
logger.success("成功加载环境变量配置")
else:
logger.error(f"ENVIRONMENT 配置错误,请检查 .env 文件中的 ENVIRONMENT 变量及对应 .env.{env} 是否存在")
RuntimeError(f"ENVIRONMENT 配置错误,请检查 .env 文件中的 ENVIRONMENT 变量及对应 .env.{env} 是否存在")
logger.error("未找到.env文件,请确保文件存在")
raise FileNotFoundError("未找到.env文件请确保文件存在")
def scan_provider(env_config: dict):

View File

@@ -114,7 +114,7 @@ AI总结
- 优化脚本逻辑
- 修复虚拟环境选项闪退和conda激活问题
- 修复环境检测菜单闪退问题
- 修复.env.prod文件复制路径错误
- 修复.env文件复制路径错误
#### 日志系统改进
- 新增GUI日志查看器

View File

@@ -42,7 +42,7 @@ services:
- napcatCONFIG:/MaiMBot/napcat # 自动根据配置中的 QQ 号创建 ws 反向客户端配置
- ./bot_config.toml:/MaiMBot/config/bot_config.toml # Toml 配置文件映射
- maimbotDATA:/MaiMBot/data # NapCat 和 NoneBot 共享此卷,否则发送图片会有问题
- ./.env.prod:/MaiMBot/.env.prod # Toml 配置文件映射
- ./.env:/MaiMBot/.env # Toml 配置文件映射
image: sengokucola/maimbot:latest
volumes:

View File

@@ -18,15 +18,15 @@ wget https://raw.githubusercontent.com/SengokuCola/MaiMBot/main/docker-compose.y
```
- 若需要启用MongoDB数据库的用户名和密码可进入docker-compose.yml取消MongoDB处的注释并修改变量旁 `=` 后方的值为你的用户名和密码\
修改后请注意在之后配置 `.env.prod` 文件时指定MongoDB数据库的用户名密码
修改后请注意在之后配置 `.env` 文件时指定MongoDB数据库的用户名密码
### 2. 启动服务
- **!!! 请在第一次启动前确保当前工作目录下 `.env.prod``bot_config.toml` 文件存在 !!!**\
- **!!! 请在第一次启动前确保当前工作目录下 `.env``bot_config.toml` 文件存在 !!!**\
由于Docker文件映射行为的特殊性若宿主机的映射路径不存在可能导致意外的目录创建而不会创建文件由于此处需要文件映射到文件需提前确保文件存在且路径正确可使用如下命令:
```bash
touch .env.prod
touch .env
touch bot_config.toml
```
@@ -41,8 +41,8 @@ NAPCAT_UID=$(id -u) NAPCAT_GID=$(id -g) docker-compose up -d
### 3. 修改配置并重启Docker
- 请前往 [🎀 新手配置指南](./installation_cute.md) 或 [⚙️ 标准配置指南](./installation_standard.md) 完成`.env.prod``bot_config.toml`配置文件的编写\
**需要注意`.env.prod`中HOST处IP的填写Docker中部署和系统中直接安装的配置会有所不同**
- 请前往 [🎀 新手配置指南](./installation_cute.md) 或 [⚙️ 标准配置指南](./installation_standard.md) 完成`.env``bot_config.toml`配置文件的编写\
**需要注意`.env`中HOST处IP的填写Docker中部署和系统中直接安装的配置会有所不同**
- 重启Docker容器:

View File

@@ -16,7 +16,7 @@
>
>点击 "新建API密钥" 按钮新建一个给MaiMBot使用的API KEY。不要忘了点击复制。
>
>之后打开MaiMBot在你电脑上的文件根目录使用记事本或者其他文本编辑器打开 [.env.prod](../.env.prod)
>之后打开MaiMBot在你电脑上的文件根目录使用记事本或者其他文本编辑器打开 [.env](../.env)
>这个文件。把你刚才复制的API KEY填入到 `SILICONFLOW_KEY=` 这个等号的右边。
>
>在默认情况下MaiMBot使用的默认Api都是硅基流动的。
@@ -27,9 +27,9 @@
>你需要使用记事本或者其他文本编辑器打开config目录下的 [bot_config.toml](../config/bot_config.toml)
>
>然后修改其中的 `provider = ` 字段。同时不要忘记模仿 [.env.prod](../.env.prod) 文件的写法添加 Api Key 和 Base URL。
>然后修改其中的 `provider = ` 字段。同时不要忘记模仿 [.env](../.env) 文件的写法添加 Api Key 和 Base URL。
>
>举个例子,如果你写了 `provider = "ABC"`,那你需要相应的在 [.env.prod](../.env.prod) 文件里添加形如 `ABC_BASE_URL = https://api.abc.com/v1` 和 `ABC_KEY = sk-1145141919810` 的字段。
>举个例子,如果你写了 `provider = "ABC"`,那你需要相应的在 [.env](../.env) 文件里添加形如 `ABC_BASE_URL = https://api.abc.com/v1` 和 `ABC_KEY = sk-1145141919810` 的字段。
>
>**如果你对AI模型没有较深的了解修改识图模型和嵌入模型的provider字段可能会产生bug因为你从Api网站调用了一个并不存在的模型**
>

View File

@@ -12,7 +12,7 @@
要设置这两个文件才能让机器人跑起来哦:
1. `.env.prod` - 这个文件告诉机器人要用哪些AI服务呢
1. `.env` - 这个文件告诉机器人要用哪些AI服务呢
2. `bot_config.toml` - 这个文件教机器人怎么和你聊天喵
## 🔑 密钥和域名的对应关系
@@ -22,7 +22,7 @@
1. 知道游乐园的地址(这就是域名 base_url
2. 有入场的门票(这就是密钥 key
`.env.prod` 文件里,我们定义了三个游乐园的地址和门票喵:
`.env` 文件里,我们定义了三个游乐园的地址和门票喵:
```ini
# 硅基流动游乐园
@@ -66,7 +66,7 @@ provider = "DEEP_SEEK" # 也去DeepSeek游乐园
### 🎯 简单来说
- `.env.prod` 文件就像是你的票夹,存放着各个游乐园的门票和地址
- `.env` 文件就像是你的票夹,存放着各个游乐园的门票和地址
- `bot_config.toml` 就是告诉机器人:用哪张票去哪个游乐园玩
- 所有模型都可以用同一个游乐园的票,也可以去不同的游乐园玩耍
- 如果用硅基流动的服务,就保持默认配置不用改呢~
@@ -75,7 +75,7 @@ provider = "DEEP_SEEK" # 也去DeepSeek游乐园
## ---让我们开始吧---
### 第一个文件:环境配置 (.env.prod)
### 第一个文件:环境配置 (.env)
这个文件就像是机器人的"身份证"呢告诉它要用哪些AI服务喵~
@@ -158,12 +158,12 @@ ban_user_id = [111222] # 比如不回复QQ号为111222的人的消息
# 模型配置部分的详细说明喵~
#下面的模型若使用硅基流动则不需要更改使用ds官方则改成在.env.prod自己指定的密钥和域名,使用自定义模型则选择定位相似的模型自己填写
#下面的模型若使用硅基流动则不需要更改使用ds官方则改成在.env自己指定的密钥和域名使用自定义模型则选择定位相似的模型自己填写
[model.llm_reasoning] #推理模型R1用来理解和思考的喵
name = "Pro/deepseek-ai/DeepSeek-R1" # 模型名字
# name = "Qwen/QwQ-32B" # 如果想用千问模型,可以把上面那行注释掉,用这个呢
provider = "SILICONFLOW" # 使用在.env.prod里设置的宏,也就是去掉"_BASE_URL"留下来的字喵
provider = "SILICONFLOW" # 使用在.env里设置的宏也就是去掉"_BASE_URL"留下来的字喵
[model.llm_reasoning_minor] #R1蒸馏模型是个轻量版的推理模型喵
name = "deepseek-ai/DeepSeek-R1-Distill-Qwen-32B"
@@ -195,7 +195,7 @@ provider = "SILICONFLOW"
1. **关于模型服务**
- 如果你用硅基流动的服务,这些配置都不用改呢
- 如果用DeepSeek官方API要把provider改成你在.env.prod里设置的宏喵
- 如果用DeepSeek官方API要把provider改成你在.env里设置的宏喵
- 如果要用自定义模型,选择一个相似功能的模型配置来改呢
2. **主要模型功能**

View File

@@ -4,14 +4,14 @@
本项目需要配置两个主要文件:
1. `.env.prod` - 配置API服务和系统环境
1. `.env` - 配置API服务和系统环境
2. `bot_config.toml` - 配置机器人行为和模型
## API配置说明
`.env.prod``bot_config.toml` 中的API配置关系如下
`.env``bot_config.toml` 中的API配置关系如下
### 在.env.prod中定义API凭证
### 在.env中定义API凭证
```ini
# API凭证配置
@@ -30,7 +30,7 @@ CHAT_ANY_WHERE_BASE_URL=https://api.chatanywhere.tech/v1 # ChatAnyWhere API地
```toml
[model.llm_reasoning]
name = "Pro/deepseek-ai/DeepSeek-R1"
provider = "SILICONFLOW" # 引用.env.prod中定义的宏
provider = "SILICONFLOW" # 引用.env中定义的宏
```
如需切换到其他API服务只需修改引用
@@ -43,7 +43,7 @@ provider = "DEEP_SEEK" # 使用DeepSeek密钥
## 配置文件详解
### 环境配置文件 (.env.prod)
### 环境配置文件 (.env)
```ini
# API配置

View File

@@ -224,7 +224,7 @@ python bot.py
```
bot
├─ .env.prod
├─ .env
└─ config
└─ bot_config.toml
```
@@ -236,7 +236,7 @@ bot
本项目需要配置两个主要文件:
1. `.env.prod` - 配置API服务和系统环境
1. `.env` - 配置API服务和系统环境
2. `bot_config.toml` - 配置机器人行为和模型
#### API

View File

@@ -111,7 +111,7 @@ nb run
# 或
python3 bot.py
```
之后你就可以找到`.env.prod``bot_config.toml`这两个文件了
之后你就可以找到`.env``bot_config.toml`这两个文件了
关于文件内容的配置请参考:
- [🎀 新手配置指南](./installation_cute.md) - 通俗易懂的配置教程,适合初次使用的猫娘
- [⚙️ 标准配置指南](./installation_standard.md) - 简明专业的配置说明,适合有经验的用户

View File

@@ -82,7 +82,7 @@ nb run
python3 bot.py
```
之后你就可以找到`.env.prod``bot_config.toml`这两个文件了
之后你就可以找到`.env``bot_config.toml`这两个文件了
关于文件内容的配置请参考:
- [🎀 新手配置指南](./installation_cute.md) - 通俗易懂的配置教程,适合初次使用的猫娘

View File

@@ -87,7 +87,7 @@ pip install -r requirements.txt
### 5⃣ **配置文件设置让麦麦Bot正常工作**
- 修改环境配置文件:`.env.prod`
- 修改环境配置文件:`.env`
- 修改机器人配置文件:`bot_config.toml`
### 6⃣ **启动麦麦机器人**

View File

@@ -22,13 +22,13 @@ bot_config.toml: https://github.com/SengokuCola/MaiMBot/blob/main/template/bot_c
下载后,重命名为 `bot_config.toml`
打开它,按自己的需求填写配置文件
.env.prod: https://github.com/SengokuCola/MaiMBot/blob/main/template.env
下载后,重命名为 `.env.prod`
.env: https://github.com/SengokuCola/MaiMBot/blob/main/template.env
下载后,重命名为 `.env`
`HOST` 修改为 `0.0.0.0`,确保 maimbot 能被 napcat 访问
按下图修改 mongodb 设置,使用 `MONGODB_URI`
![](./pic/synology_.env.prod.png)
![](./pic/synology_.env.png)
`bot_config.toml``.env.prod` 放入之前创建的 `MaiMBot`文件夹
`bot_config.toml``.env` 放入之前创建的 `MaiMBot`文件夹
#### 如何下载?

View File

@@ -53,7 +53,7 @@ if os.path.exists(bot_config_path):
else:
logger.critical(f"没有找到配置文件{bot_config_path}")
exit(1)
env_path = os.path.join(root_dir, ".env.prod")
env_path = os.path.join(root_dir, ".env")
if not os.path.exists(env_path):
logger.critical(f"没有找到环境变量文件{env_path}")
exit(1)

View File

@@ -7,8 +7,8 @@ from pathlib import Path
from dotenv import load_dotenv
# from ..plugins.chat.config import global_config
# 加载 .env.prod 文件
env_path = Path(__file__).resolve().parent.parent.parent / ".env.prod"
# 加载 .env 文件
env_path = Path(__file__).resolve().parent.parent.parent / ".env"
load_dotenv(dotenv_path=env_path)
# 保存原生处理器ID
@@ -245,6 +245,23 @@ SUB_HEARTFLOW_STYLE_CONFIG = {
},
}
WILLING_STYLE_CONFIG = {
"advanced": {
"console_format": (
"<green>{time:YYYY-MM-DD HH:mm:ss}</green> | "
"<level>{level: <8}</level> | "
"<cyan>{extra[module]: <12}</cyan> | "
"<light-blue>意愿</light-blue> | "
"<level>{message}</level>"
),
"file_format": ("{time:YYYY-MM-DD HH:mm:ss} | {level: <8} | {extra[module]: <15} | 意愿 | {message}"),
},
"simple": {
"console_format": ("<green>{time:MM-DD HH:mm}</green> | <light-blue>意愿</light-blue> | <light-blue>{message}</light-blue>"), # noqa: E501
"file_format": ("{time:YYYY-MM-DD HH:mm:ss} | {level: <8} | {extra[module]: <15} | 意愿 | {message}"),
},
}
@@ -259,6 +276,8 @@ RELATION_STYLE_CONFIG = RELATION_STYLE_CONFIG["simple"] if SIMPLE_OUTPUT else RE
SCHEDULE_STYLE_CONFIG = SCHEDULE_STYLE_CONFIG["simple"] if SIMPLE_OUTPUT else SCHEDULE_STYLE_CONFIG["advanced"]
HEARTFLOW_STYLE_CONFIG = HEARTFLOW_STYLE_CONFIG["simple"] if SIMPLE_OUTPUT else HEARTFLOW_STYLE_CONFIG["advanced"]
SUB_HEARTFLOW_STYLE_CONFIG = SUB_HEARTFLOW_STYLE_CONFIG["simple"] if SIMPLE_OUTPUT else SUB_HEARTFLOW_STYLE_CONFIG["advanced"] # noqa: E501
WILLING_STYLE_CONFIG = WILLING_STYLE_CONFIG["simple"] if SIMPLE_OUTPUT else WILLING_STYLE_CONFIG["advanced"]
def is_registered_module(record: dict) -> bool:
"""检查是否为已注册的模块"""

View File

@@ -26,8 +26,8 @@ from src.common.database import db # noqa: E402
if os.path.exists(os.path.join(root_dir, ".env.dev")):
load_dotenv(os.path.join(root_dir, ".env.dev"))
logger.info("成功加载开发环境配置")
elif os.path.exists(os.path.join(root_dir, ".env.prod")):
load_dotenv(os.path.join(root_dir, ".env.prod"))
elif os.path.exists(os.path.join(root_dir, ".env")):
load_dotenv(os.path.join(root_dir, ".env"))
logger.info("成功加载生产环境配置")
else:
logger.error("未找到环境配置文件")

View File

@@ -8,10 +8,8 @@ from .plugins.chat.emoji_manager import emoji_manager
from .plugins.chat.relationship_manager import relationship_manager
from .plugins.willing.willing_manager import willing_manager
from .plugins.chat.chat_stream import chat_manager
from .think_flow_demo.heartflow import heartflow
from .plugins.memory_system.Hippocampus import HippocampusManager
from .plugins.chat import auto_speak_manager
from .think_flow_demo.heartflow import subheartflow_manager
from .think_flow_demo.outer_world import outer_world
from .plugins.chat.message_sender import message_manager
from .plugins.chat.storage import MessageStorage
from .plugins.config.config import global_config
@@ -44,6 +42,7 @@ class MainSystem:
async def _init_components(self):
"""初始化其他组件"""
init_start_time = time.time()
# 启动LLM统计
self.llm_stats.start()
logger.success("LLM统计功能启动成功")
@@ -72,8 +71,8 @@ class MainSystem:
asyncio.create_task(chat_manager._auto_save_task())
# 使用HippocampusManager初始化海马体
self.hippocampus_manager.initialize(global_config=global_config)
# await asyncio.sleep(0.5) #防止logger输出飞了
# 初始化日程
bot_schedule.initialize(
@@ -88,11 +87,12 @@ class MainSystem:
self.app.register_message_handler(chat_bot.message_process)
try:
asyncio.create_task(outer_world.open_eyes())
logger.success("大脑和外部世界启动成功")
# 启动心流系统
asyncio.create_task(subheartflow_manager.heartflow_start_working())
asyncio.create_task(heartflow.heartflow_start_working())
logger.success("心流系统启动成功")
init_time = int(1000*(time.time()- init_start_time))
logger.success(f"初始化完成,神经元放电{init_time}")
except Exception as e:
logger.error(f"启动大脑和外部世界失败: {e}")
raise
@@ -103,9 +103,7 @@ class MainSystem:
tasks = [
self.build_memory_task(),
self.forget_memory_task(),
# self.merge_memory_task(),
self.print_mood_task(),
# self.generate_schedule_task(),
self.remove_recalled_message_task(),
emoji_manager.start_periodic_check(),
self.app.run(),
@@ -128,26 +126,12 @@ class MainSystem:
print("\033[1;32m[记忆遗忘]\033[0m 记忆遗忘完成")
await asyncio.sleep(global_config.forget_memory_interval)
# async def merge_memory_task(self):
# """记忆整合任务"""
# while True:
# logger.info("正在进行记忆整合")
# await asyncio.sleep(global_config.build_memory_interval + 10)
async def print_mood_task(self):
"""打印情绪状态"""
while True:
self.mood_manager.print_mood_status()
await asyncio.sleep(30)
# async def generate_schedule_task(self):
# """生成日程任务"""
# while True:
# await bot_schedule.initialize()
# if not bot_schedule.enable_output:
# bot_schedule.print_schedule()
# await asyncio.sleep(7200)
async def remove_recalled_message_task(self):
"""删除撤回消息任务"""
while True:
@@ -166,8 +150,6 @@ async def main():
system.initialize(),
system.schedule_tasks(),
)
# await system.initialize()
# await system.schedule_tasks()
if __name__ == "__main__":

View File

@@ -10,7 +10,7 @@ from .message_sender import message_manager
from ..moods.moods import MoodManager
from .llm_generator import ResponseGenerator
from src.common.logger import get_module_logger
from src.think_flow_demo.heartflow import subheartflow_manager
from src.think_flow_demo.heartflow import heartflow
from ...common.database import db
logger = get_module_logger("auto_speak")
@@ -42,7 +42,7 @@ class AutoSpeakManager:
while True and global_config.enable_think_flow:
# 获取所有活跃的子心流
active_subheartflows = []
for chat_id, subheartflow in subheartflow_manager._subheartflows.items():
for chat_id, subheartflow in heartflow._subheartflows.items():
if (
subheartflow.is_active and subheartflow.current_state.willing > 0
): # 只考虑活跃且意愿值大于0.5的子心流

View File

@@ -1,7 +1,6 @@
import re
import time
from random import random
import json
from ..memory_system.Hippocampus import HippocampusManager
from ..moods.moods import MoodManager # 导入情绪管理器
@@ -18,10 +17,9 @@ from .storage import MessageStorage
from .utils import is_mentioned_bot_in_message, get_recent_group_detailed_plain_text
from .utils_image import image_path_to_base64
from ..willing.willing_manager import willing_manager # 导入意愿管理器
from ..message import UserInfo, GroupInfo, Seg
from ..message import UserInfo, Seg
from src.think_flow_demo.heartflow import subheartflow_manager
from src.think_flow_demo.outer_world import outer_world
from src.think_flow_demo.heartflow import heartflow
from src.common.logger import get_module_logger, CHAT_STYLE_CONFIG, LogConfig
# 定义日志配置
@@ -58,10 +56,7 @@ class ChatBot:
5. 更新关系
6. 更新情绪
"""
# message_json = json.loads(message_data)
# 哦我嘞个json
# 进入maimbot
message = MessageRecv(message_data)
groupinfo = message.message_info.group_info
userinfo = message.message_info.user_info
@@ -73,57 +68,43 @@ class ChatBot:
chat = await chat_manager.get_or_create_stream(
platform=messageinfo.platform,
user_info=userinfo,
group_info=groupinfo, # 我嘞个gourp_info
group_info=groupinfo,
)
message.update_chat_stream(chat)
# 创建 心流 观察
if global_config.enable_think_flow:
await outer_world.check_and_add_new_observe()
subheartflow_manager.create_subheartflow(chat.stream_id)
await relationship_manager.update_relationship(
chat_stream=chat,
)
await relationship_manager.update_relationship_value(chat_stream=chat, relationship_value=0)
# 创建 心流与chat的观察
heartflow.create_subheartflow(chat.stream_id)
timer1 = time.time()
await message.process()
timer2 = time.time()
logger.info(f"2消息处理时间: {timer2 - timer1}")
# 过滤词
for word in global_config.ban_words:
if word in message.processed_plain_text:
logger.info(
f"[{chat.group_info.group_name if chat.group_info else '私聊'}]"
f"{userinfo.user_nickname}:{message.processed_plain_text}"
)
logger.info(f"[过滤词识别]消息中含有{word}filtered")
return
# 过滤词/正则表达式过滤
if (
self._check_ban_words(message.processed_plain_text, chat, userinfo)
or self._check_ban_regex(message.raw_message, chat, userinfo)
):
return
# 正则表达式过滤
for pattern in global_config.ban_msgs_regex:
if re.search(pattern, message.raw_message):
logger.info(
f"[{chat.group_info.group_name if chat.group_info else '私聊'}]"
f"{userinfo.user_nickname}:{message.raw_message}"
)
logger.info(f"[正则表达式过滤]消息匹配到{pattern}filtered")
return
current_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(messageinfo.time))
# 根据话题计算激活度
topic = ""
await self.storage.store_message(message, chat, topic[0] if topic else None)
await self.storage.store_message(message, chat)
timer1 = time.time()
interested_rate = 0
interested_rate = await HippocampusManager.get_instance().get_activate_from_text(
message.processed_plain_text, fast_retrieval=True
)
timer2 = time.time()
logger.info(f"3记忆激活时间: {timer2 - timer1}")
is_mentioned = is_mentioned_bot_in_message(message)
if global_config.enable_think_flow:
current_willing_old = willing_manager.get_willing(chat_stream=chat)
current_willing_new = (subheartflow_manager.get_subheartflow(chat.stream_id).current_state.willing - 5) / 4
current_willing_new = (heartflow.get_subheartflow(chat.stream_id).current_state.willing - 5) / 4
print(f"旧回复意愿:{current_willing_old},新回复意愿:{current_willing_new}")
current_willing = (current_willing_old + current_willing_new) / 2
else:
@@ -131,6 +112,7 @@ class ChatBot:
willing_manager.set_willing(chat.stream_id, current_willing)
timer1 = time.time()
reply_probability = await willing_manager.change_reply_willing_received(
chat_stream=chat,
is_mentioned_bot=is_mentioned,
@@ -139,161 +121,247 @@ class ChatBot:
interested_rate=interested_rate,
sender_id=str(message.message_info.user_info.user_id),
)
timer2 = time.time()
logger.info(f"4计算意愿激活时间: {timer2 - timer1}")
#神秘的消息流数据结构处理
if chat.group_info:
if chat.group_info.group_name:
mes_name_dict = chat.group_info.group_name
mes_name = mes_name_dict.get('group_name', '无名群聊')
else:
mes_name = '群聊'
else:
mes_name = '私聊'
#打印收到的信息的信息
current_time = time.strftime("%H:%M:%S", time.localtime(messageinfo.time))
logger.info(
f"[{current_time}][{chat.group_info.group_name if chat.group_info else '私聊'}]"
f"[{current_time}][{mes_name}]"
f"{chat.user_info.user_nickname}:"
f"{message.processed_plain_text}[回复意愿:{current_willing:.2f}][概率:{reply_probability * 100:.1f}%]"
)
response = None
if message.message_info.additional_config:
if "maimcore_reply_probability_gain" in message.message_info.additional_config.keys():
reply_probability += message.message_info.additional_config["maimcore_reply_probability_gain"]
# 开始组织语言
if random() < reply_probability:
bot_user_info = UserInfo(
user_id=global_config.BOT_QQ,
user_nickname=global_config.BOT_NICKNAME,
platform=messageinfo.platform,
)
# 开始思考的时间点
thinking_time_point = round(time.time(), 2)
# logger.debug(f"开始思考的时间点: {thinking_time_point}")
think_id = "mt" + str(thinking_time_point)
thinking_message = MessageThinking(
message_id=think_id,
chat_stream=chat,
bot_user_info=bot_user_info,
reply=message,
thinking_start_time=thinking_time_point,
)
message_manager.add_message(thinking_message)
willing_manager.change_reply_willing_sent(chat)
response, raw_content = await self.gpt.generate_response(message)
else:
# 决定不回复时,也更新回复意愿
willing_manager.change_reply_willing_not_sent(chat)
# print(f"response: {response}")
if response:
stream_id = message.chat_stream.stream_id
chat_talking_prompt = ""
if stream_id:
chat_talking_prompt = get_recent_group_detailed_plain_text(
stream_id, limit=global_config.MAX_CONTEXT_SIZE, combine=True
)
if subheartflow_manager.get_subheartflow(stream_id):
await subheartflow_manager.get_subheartflow(stream_id).do_after_reply(response, chat_talking_prompt)
else:
await subheartflow_manager.create_subheartflow(stream_id).do_after_reply(response, chat_talking_prompt)
# print(f"有response: {response}")
container = message_manager.get_container(chat.stream_id)
thinking_message = None
# 找到message,删除
# print(f"开始找思考消息")
for msg in container.messages:
if isinstance(msg, MessageThinking) and msg.message_info.message_id == think_id:
# print(f"找到思考消息: {msg}")
thinking_message = msg
container.messages.remove(msg)
break
# 如果找不到思考消息,直接返回
if not thinking_message:
logger.warning("未找到对应的思考消息,可能已超时被移除")
timer1 = time.time()
response_set, thinking_id = await self._generate_response_from_message(message, chat, userinfo, messageinfo)
timer2 = time.time()
logger.info(f"5生成回复时间: {timer2 - timer1}")
if not response_set:
logger.info("为什么生成回复失败?")
return
# 发送消息
timer1 = time.time()
await self._send_response_messages(message, chat, response_set, thinking_id)
timer2 = time.time()
logger.info(f"7发送消息时间: {timer2 - timer1}")
# 处理表情包
timer1 = time.time()
await self._handle_emoji(message, chat, response_set)
timer2 = time.time()
logger.info(f"8处理表情包时间: {timer2 - timer1}")
timer1 = time.time()
await self._update_using_response(message, chat, response_set)
timer2 = time.time()
logger.info(f"6更新htfl时间: {timer2 - timer1}")
# 更新情绪和关系
# await self._update_emotion_and_relationship(message, chat, response_set)
# 记录开始思考的时间,避免从思考到回复的时间太久
thinking_start_time = thinking_message.thinking_start_time
message_set = MessageSet(chat, think_id)
# 计算打字时间1是为了模拟打字2是避免多条回复乱序
# accu_typing_time = 0
async def _generate_response_from_message(self, message, chat, userinfo, messageinfo):
"""生成回复内容
Args:
message: 接收到的消息
chat: 聊天流对象
userinfo: 用户信息对象
messageinfo: 消息信息对象
Returns:
tuple: (response, raw_content) 回复内容和原始内容
"""
bot_user_info = UserInfo(
user_id=global_config.BOT_QQ,
user_nickname=global_config.BOT_NICKNAME,
platform=messageinfo.platform,
)
thinking_time_point = round(time.time(), 2)
thinking_id = "mt" + str(thinking_time_point)
thinking_message = MessageThinking(
message_id=thinking_id,
chat_stream=chat,
bot_user_info=bot_user_info,
reply=message,
thinking_start_time=thinking_time_point,
)
mark_head = False
for msg in response:
# print(f"\033[1;32m[回复内容]\033[0m {msg}")
# 通过时间改变时间戳
# typing_time = calculate_typing_time(msg)
# logger.debug(f"typing_time: {typing_time}")
# accu_typing_time += typing_time
# timepoint = thinking_time_point + accu_typing_time
message_segment = Seg(type="text", data=msg)
# logger.debug(f"message_segment: {message_segment}")
message_manager.add_message(thinking_message)
willing_manager.change_reply_willing_sent(chat)
response_set = await self.gpt.generate_response(message)
return response_set, thinking_id
async def _update_using_response(self, message, response_set):
# 更新心流状态
stream_id = message.chat_stream.stream_id
chat_talking_prompt = ""
if stream_id:
chat_talking_prompt = get_recent_group_detailed_plain_text(
stream_id, limit=global_config.MAX_CONTEXT_SIZE, combine=True
)
if heartflow.get_subheartflow(stream_id):
await heartflow.get_subheartflow(stream_id).do_after_reply(response_set, chat_talking_prompt)
else:
await heartflow.create_subheartflow(stream_id).do_after_reply(response_set, chat_talking_prompt)
async def _send_response_messages(self, message, chat, response_set, thinking_id):
container = message_manager.get_container(chat.stream_id)
thinking_message = None
logger.info(f"开始发送消息准备")
for msg in container.messages:
if isinstance(msg, MessageThinking) and msg.message_info.message_id == thinking_id:
thinking_message = msg
container.messages.remove(msg)
break
if not thinking_message:
logger.warning("未找到对应的思考消息,可能已超时被移除")
return
logger.info(f"开始发送消息")
thinking_start_time = thinking_message.thinking_start_time
message_set = MessageSet(chat, thinking_id)
mark_head = False
for msg in response_set:
message_segment = Seg(type="text", data=msg)
bot_message = MessageSending(
message_id=thinking_id,
chat_stream=chat,
bot_user_info=UserInfo(
user_id=global_config.BOT_QQ,
user_nickname=global_config.BOT_NICKNAME,
platform=message.message_info.platform,
),
sender_info=message.message_info.user_info,
message_segment=message_segment,
reply=message,
is_head=not mark_head,
is_emoji=False,
thinking_start_time=thinking_start_time,
)
if not mark_head:
mark_head = True
message_set.add_message(bot_message)
logger.info(f"开始添加发送消息")
message_manager.add_message(message_set)
async def _handle_emoji(self, message, chat, response):
"""处理表情包
Args:
message: 接收到的消息
chat: 聊天流对象
response: 生成的回复
"""
if random() < global_config.emoji_chance:
emoji_raw = await emoji_manager.get_emoji_for_text(response)
if emoji_raw:
emoji_path, description = emoji_raw
emoji_cq = image_path_to_base64(emoji_path)
thinking_time_point = round(message.message_info.time, 2)
bot_response_time = thinking_time_point + (1 if random() < 0.5 else -1)
message_segment = Seg(type="emoji", data=emoji_cq)
bot_message = MessageSending(
message_id=think_id,
message_id="mt" + str(thinking_time_point),
chat_stream=chat,
bot_user_info=bot_user_info,
sender_info=userinfo,
bot_user_info=UserInfo(
user_id=global_config.BOT_QQ,
user_nickname=global_config.BOT_NICKNAME,
platform=message.message_info.platform,
),
sender_info=message.message_info.user_info,
message_segment=message_segment,
reply=message,
is_head=not mark_head,
is_emoji=False,
thinking_start_time=thinking_start_time,
is_head=False,
is_emoji=True,
)
if not mark_head:
mark_head = True
message_set.add_message(bot_message)
if len(str(bot_message)) < 1000:
logger.debug(f"bot_message: {bot_message}")
logger.debug(f"添加消息到message_set: {bot_message}")
else:
logger.debug(f"bot_message: {str(bot_message)[:1000]}...{str(bot_message)[-10:]}")
logger.debug(f"添加消息到message_set: {str(bot_message)[:1000]}...{str(bot_message)[-10:]}")
# message_set 可以直接加入 message_manager
# print(f"\033[1;32m[回复]\033[0m 将回复载入发送容器")
message_manager.add_message(bot_message)
logger.debug("添加message_set到message_manager")
async def _update_emotion_and_relationship(self, message, chat, response, raw_content):
"""更新情绪和关系
Args:
message: 接收到的消息
chat: 聊天流对象
response: 生成的回复
raw_content: 原始内容
"""
stance, emotion = await self.gpt._get_emotion_tags(raw_content, message.processed_plain_text)
logger.debug(f"'{response}' 立场为:{stance} 获取到的情感标签为:{emotion}")
await relationship_manager.calculate_update_relationship_value(
chat_stream=chat, label=emotion, stance=stance
)
self.mood_manager.update_mood_from_emotion(emotion, global_config.mood_intensity_factor)
message_manager.add_message(message_set)
bot_response_time = thinking_time_point
if random() < global_config.emoji_chance:
emoji_raw = await emoji_manager.get_emoji_for_text(response)
# 检查是否 <没有找到> emoji
if emoji_raw != None:
emoji_path, description = emoji_raw
emoji_cq = image_path_to_base64(emoji_path)
if random() < 0.5:
bot_response_time = thinking_time_point - 1
else:
bot_response_time = bot_response_time + 1
message_segment = Seg(type="emoji", data=emoji_cq)
bot_message = MessageSending(
message_id=think_id,
chat_stream=chat,
bot_user_info=bot_user_info,
sender_info=userinfo,
message_segment=message_segment,
reply=message,
is_head=False,
is_emoji=True,
)
message_manager.add_message(bot_message)
# 获取立场和情感标签,更新关系值
stance, emotion = await self.gpt._get_emotion_tags(raw_content, message.processed_plain_text)
logger.debug(f"'{response}' 立场为:{stance} 获取到的情感标签为:{emotion}")
await relationship_manager.calculate_update_relationship_value(
chat_stream=chat, label=emotion, stance=stance
)
# 使用情绪管理器更新情绪
self.mood_manager.update_mood_from_emotion(emotion, global_config.mood_intensity_factor)
# willing_manager.change_reply_willing_after_sent(
# chat_stream=chat
# )
def _check_ban_words(self, text: str, chat, userinfo) -> bool:
"""检查消息中是否包含过滤词
Args:
text: 要检查的文本
chat: 聊天流对象
userinfo: 用户信息对象
Returns:
bool: 如果包含过滤词返回True否则返回False
"""
for word in global_config.ban_words:
if word in text:
logger.info(
f"[{chat.group_info.group_name if chat.group_info else '私聊'}]"
f"{userinfo.user_nickname}:{text}"
)
logger.info(f"[过滤词识别]消息中含有{word}filtered")
return True
return False
def _check_ban_regex(self, text: str, chat, userinfo) -> bool:
"""检查消息是否匹配过滤正则表达式
Args:
text: 要检查的文本
chat: 聊天流对象
userinfo: 用户信息对象
Returns:
bool: 如果匹配过滤正则返回True否则返回False
"""
for pattern in global_config.ban_msgs_regex:
if re.search(pattern, text):
logger.info(
f"[{chat.group_info.group_name if chat.group_info else '私聊'}]"
f"{userinfo.user_nickname}:{text}"
)
logger.info(f"[正则表达式过滤]消息匹配到{pattern}filtered")
return True
return False
# 创建全局ChatBot实例
chat_bot = ChatBot()

View File

@@ -23,19 +23,20 @@ logger = get_module_logger("llm_generator", config=llm_config)
class ResponseGenerator:
def __init__(self):
self.model_r1 = LLM_request(
self.model_reasoning = LLM_request(
model=global_config.llm_reasoning,
temperature=0.7,
max_tokens=1000,
stream=True,
request_type="response",
)
self.model_v3 = LLM_request(
model=global_config.llm_normal, temperature=0.7, max_tokens=3000, request_type="response"
)
self.model_r1_distill = LLM_request(
model=global_config.llm_reasoning_minor, temperature=0.7, max_tokens=3000, request_type="response"
self.model_normal = LLM_request(
model=global_config.llm_normal,
temperature=0.7,
max_tokens=3000,
request_type="response"
)
self.model_sum = LLM_request(
model=global_config.llm_summary_by_topic, temperature=0.7, max_tokens=3000, request_type="relation"
)
@@ -45,34 +46,33 @@ class ResponseGenerator:
async def generate_response(self, message: MessageThinking) -> Optional[Union[str, List[str]]]:
"""根据当前模型类型选择对应的生成函数"""
# 从global_config中获取模型概率值并选择模型
rand = random.random()
if rand < global_config.MODEL_R1_PROBABILITY:
if random.random() < global_config.MODEL_R1_PROBABILITY:
self.current_model_type = "深深地"
current_model = self.model_r1
elif rand < global_config.MODEL_R1_PROBABILITY + global_config.MODEL_V3_PROBABILITY:
self.current_model_type = "浅浅的"
current_model = self.model_v3
current_model = self.model_reasoning
else:
self.current_model_type = "又浅又浅的"
current_model = self.model_r1_distill
self.current_model_type = "浅的"
current_model = self.model_normal
logger.info(f"{self.current_model_type}思考:{message.processed_plain_text[:30] + '...' if len(message.processed_plain_text) > 30 else message.processed_plain_text}") # noqa: E501
logger.info(f"{global_config.BOT_NICKNAME}{self.current_model_type}思考中")
model_response = await self._generate_response_with_model(message, current_model)
raw_content = model_response
# print(f"raw_content: {raw_content}")
# print(f"model_response: {model_response}")
print(f"raw_content: {model_response}")
if model_response:
logger.info(f"{global_config.BOT_NICKNAME}的回复是:{model_response}")
model_response = await self._process_response(model_response)
if model_response:
return model_response, raw_content
return None, raw_content
async def _generate_response_with_model(self, message: MessageThinking, model: LLM_request) -> Optional[str]:
return model_response
else:
logger.info(f"{self.current_model_type}思考,失败")
return None
async def _generate_response_with_model(self, message: MessageThinking, model: LLM_request):
"""使用指定的模型生成回复"""
logger.info(f"开始使用生成回复-1")
sender_name = ""
if message.chat_stream.user_info.user_cardname and message.chat_stream.user_info.user_nickname:
sender_name = (
@@ -84,32 +84,18 @@ class ResponseGenerator:
else:
sender_name = f"用户({message.chat_stream.user_info.user_id})"
logger.info(f"开始使用生成回复-2")
# 构建prompt
prompt, prompt_check = await prompt_builder._build_prompt(
timer1 = time.time()
prompt = await prompt_builder._build_prompt(
message.chat_stream,
message_txt=message.processed_plain_text,
sender_name=sender_name,
stream_id=message.chat_stream.stream_id,
)
# 读空气模块 简化逻辑,先停用
# if global_config.enable_kuuki_read:
# content_check, reasoning_content_check = await self.model_v3.generate_response(prompt_check)
# print(f"\033[1;32m[读空气]\033[0m 读空气结果为{content_check}")
# if 'yes' not in content_check.lower() and random.random() < 0.3:
# self._save_to_db(
# message=message,
# sender_name=sender_name,
# prompt=prompt,
# prompt_check=prompt_check,
# content="",
# content_check=content_check,
# reasoning_content="",
# reasoning_content_check=reasoning_content_check
# )
# return None
# 生成回复
timer2 = time.time()
logger.info(f"构建prompt时间: {timer2 - timer1}")
try:
content, reasoning_content, self.current_model_name = await model.generate_response(prompt)
except Exception:
@@ -121,9 +107,7 @@ class ResponseGenerator:
message=message,
sender_name=sender_name,
prompt=prompt,
prompt_check=prompt_check,
content=content,
# content_check=content_check if global_config.enable_kuuki_read else "",
reasoning_content=reasoning_content,
# reasoning_content_check=reasoning_content_check if global_config.enable_kuuki_read else ""
)
@@ -137,7 +121,6 @@ class ResponseGenerator:
message: MessageRecv,
sender_name: str,
prompt: str,
prompt_check: str,
content: str,
reasoning_content: str,
):
@@ -154,7 +137,6 @@ class ResponseGenerator:
"reasoning": reasoning_content,
"response": content,
"prompt": prompt,
"prompt_check": prompt_check,
}
)

View File

@@ -83,7 +83,7 @@ class MessageContainer:
self.max_size = max_size
self.messages = []
self.last_send_time = 0
self.thinking_timeout = 10 # 思考超时时间(秒)
self.thinking_timeout = 10 # 思考等待超时时间(秒)
def get_timeout_messages(self) -> List[MessageSending]:
"""获取所有超时的Message_Sending对象思考时间超过30秒按thinking_start_time排序"""
@@ -192,7 +192,7 @@ class MessageManager:
# print(thinking_time)
if (
message_earliest.is_head
and message_earliest.update_thinking_time() > 20
and message_earliest.update_thinking_time() > 50
and not message_earliest.is_private_message() # 避免在私聊时插入reply
):
logger.debug(f"设置回复消息{message_earliest.processed_plain_text}")
@@ -202,7 +202,7 @@ class MessageManager:
await message_sender.send_message(message_earliest)
await self.storage.store_message(message_earliest, message_earliest.chat_stream, None)
await self.storage.store_message(message_earliest, message_earliest.chat_stream)
container.remove_message(message_earliest)
@@ -219,7 +219,7 @@ class MessageManager:
# print(msg.is_private_message())
if (
msg.is_head
and msg.update_thinking_time() > 25
and msg.update_thinking_time() > 50
and not msg.is_private_message() # 避免在私聊时插入reply
):
logger.debug(f"设置回复消息{msg.processed_plain_text}")
@@ -229,7 +229,7 @@ class MessageManager:
await message_sender.send_message(msg)
await self.storage.store_message(msg, msg.chat_stream, None)
await self.storage.store_message(msg, msg.chat_stream)
if not container.remove_message(msg):
logger.warning("尝试删除不存在的消息")

View File

@@ -12,12 +12,10 @@ from .chat_stream import chat_manager
from .relationship_manager import relationship_manager
from src.common.logger import get_module_logger
from src.think_flow_demo.heartflow import subheartflow_manager
from src.think_flow_demo.heartflow import heartflow
logger = get_module_logger("prompt")
logger.info("初始化Prompt系统")
class PromptBuilder:
def __init__(self):
@@ -28,33 +26,34 @@ class PromptBuilder:
self, chat_stream, message_txt: str, sender_name: str = "某人", stream_id: Optional[int] = None
) -> tuple[str, str]:
# 关系(载入当前聊天记录里部分人的关系)
who_chat_in_group = [chat_stream]
who_chat_in_group += get_recent_group_speaker(
stream_id,
(chat_stream.user_info.user_id, chat_stream.user_info.platform),
limit=global_config.MAX_CONTEXT_SIZE,
)
# who_chat_in_group = [chat_stream]
# who_chat_in_group += get_recent_group_speaker(
# stream_id,
# (chat_stream.user_info.user_id, chat_stream.user_info.platform),
# limit=global_config.MAX_CONTEXT_SIZE,
# )
# outer_world_info = outer_world.outer_world_info
if global_config.enable_think_flow:
current_mind_info = subheartflow_manager.get_subheartflow(stream_id).current_mind
else:
current_mind_info = ""
relation_prompt = ""
for person in who_chat_in_group:
relation_prompt += relationship_manager.build_relationship_info(person)
current_mind_info = heartflow.get_subheartflow(stream_id).current_mind
relation_prompt_all = (
f"{relation_prompt}关系等级越大,关系越好,请分析聊天记录,"
f"根据你和说话者{sender_name}的关系和态度进行回复,明确你的立场和情感。"
)
# relation_prompt = ""
# for person in who_chat_in_group:
# relation_prompt += relationship_manager.build_relationship_info(person)
# relation_prompt_all = (
# f"{relation_prompt}关系等级越大,关系越好,请分析聊天记录,"
# f"根据你和说话者{sender_name}的关系和态度进行回复,明确你的立场和情感。"
# )
# 开始构建prompt
# 心情
mood_manager = MoodManager.get_instance()
mood_prompt = mood_manager.get_prompt()
logger.info(f"心情prompt: {mood_prompt}")
# 日程构建
# schedule_prompt = f'''你现在正在做的事情是:{bot_schedule.get_current_num_task(num = 1,time_info = False)}'''
@@ -73,29 +72,24 @@ class PromptBuilder:
chat_in_group = False
chat_talking_prompt = chat_talking_prompt
# print(f"\033[1;34m[调试]\033[0m 已从数据库获取群 {group_id} 的消息记录:{chat_talking_prompt}")
# 使用新的记忆获取方法
memory_prompt = ""
start_time = time.time()
# 调用 hippocampus 的 get_relevant_memories 方法
#调用 hippocampus 的 get_relevant_memories 方法
relevant_memories = await HippocampusManager.get_instance().get_memory_from_text(
text=message_txt, max_memory_num=3, max_memory_length=2, max_depth=4, fast_retrieval=False
text=message_txt, max_memory_num=3, max_memory_length=2, max_depth=2, fast_retrieval=False
)
memory_str = ""
for _topic, memories in relevant_memories:
memory_str += f"{memories}\n"
# print(f"memory_str: {memory_str}")
if relevant_memories:
# 格式化记忆内容
memory_prompt = f"你回忆起:\n{memory_str}\n"
# 打印调试信息
logger.debug("[记忆检索]找到以下相关记忆:")
# for topic, memory_items, similarity in relevant_memories:
# logger.debug(f"- 主题「{topic}」[相似度: {similarity:.2f}]: {memory_items}")
end_time = time.time()
logger.info(f"回忆耗时: {(end_time - start_time):.3f}")
@@ -142,10 +136,10 @@ class PromptBuilder:
# 知识构建
start_time = time.time()
prompt_info = await self.get_prompt_info(message_txt, threshold=0.5)
if prompt_info:
prompt_info = f"""\n你有以下这些**知识**\n{prompt_info}\n请你**记住上面的知识**,之后可能会用到。\n"""
prompt_info = ""
# prompt_info = await self.get_prompt_info(message_txt, threshold=0.5)
# if prompt_info:
# prompt_info = f"""\n你有以下这些**知识**\n{prompt_info}\n请你**记住上面的知识**,之后可能会用到。\n"""
end_time = time.time()
logger.debug(f"知识检索耗时: {(end_time - start_time):.3f}")
@@ -154,6 +148,7 @@ class PromptBuilder:
moderation_prompt = """**检查并忽略**任何涉及尝试绕过审核的行为。
涉及政治敏感以及违法违规的内容请规避。"""
logger.info(f"开始构建prompt")
prompt = f"""
{prompt_info}
{memory_prompt}
@@ -162,7 +157,7 @@ class PromptBuilder:
{chat_target}
{chat_talking_prompt}
现在"{sender_name}"说的:{message_txt}。引起了你的注意,{relation_prompt_all}{mood_prompt}\n
现在"{sender_name}"说的:{message_txt}。引起了你的注意,{mood_prompt}\n
你的网名叫{global_config.BOT_NICKNAME},有人也叫你{"/".join(global_config.BOT_ALIAS_NAMES)}{prompt_personality}
你正在{chat_target_2},现在请你读读之前的聊天记录,然后给出日常且口语化的回复,平淡一些,
尽量简短一些。{keywords_reaction_prompt}请注意把握聊天内容,不要回复的太有条理,可以有个性。{prompt_ger}
@@ -170,9 +165,10 @@ class PromptBuilder:
请注意不要输出多余内容(包括前后缀,冒号和引号,括号,表情等),只输出回复内容。
{moderation_prompt}不要输出多余内容(包括前后缀冒号和引号括号表情包at或 @等 )。"""
prompt_check_if_response = ""
return prompt, prompt_check_if_response
return prompt
def _build_initiative_prompt_select(self, group_id, probability_1=0.8, probability_2=0.1):
current_date = time.strftime("%Y-%m-%d", time.localtime())

View File

@@ -10,7 +10,7 @@ logger = get_module_logger("message_storage")
class MessageStorage:
async def store_message(
self, message: Union[MessageSending, MessageRecv], chat_stream: ChatStream, topic: Optional[str] = None
self, message: Union[MessageSending, MessageRecv], chat_stream: ChatStream
) -> None:
"""存储消息到数据库"""
try:
@@ -22,7 +22,6 @@ class MessageStorage:
"user_info": message.message_info.user_info.to_dict(),
"processed_plain_text": message.processed_plain_text,
"detailed_plain_text": message.detailed_plain_text,
"topic": topic,
"memorized_times": message.memorized_times,
}
db.messages.insert_one(message_data)

View File

@@ -29,7 +29,7 @@ class EnvConfig:
if env_type == 'dev':
env_file = self.ROOT_DIR / '.env.dev'
elif env_type == 'prod':
env_file = self.ROOT_DIR / '.env.prod'
env_file = self.ROOT_DIR / '.env'
if env_file.exists():
load_dotenv(env_file, override=True)

View File

@@ -1203,8 +1203,8 @@ class Hippocampus:
activation_values[neighbor] = new_activation
visited_nodes.add(neighbor)
nodes_to_process.append((neighbor, new_activation, current_depth + 1))
logger.debug(
f"节点 '{neighbor}' 被激活,激活值: {new_activation:.2f} (通过 '{current_node}' 连接,强度: {strength}, 深度: {current_depth + 1})") # noqa: E501
# logger.debug(
# f"节点 '{neighbor}' 被激活,激活值: {new_activation:.2f} (通过 '{current_node}' 连接,强度: {strength}, 深度: {current_depth + 1})") # noqa: E501
# 更新激活映射
for node, activation_value in activation_values.items():
@@ -1260,27 +1260,20 @@ class HippocampusManager:
# 输出记忆系统参数信息
config = self._hippocampus.config
logger.success("--------------------------------")
logger.success("记忆系统参数配置:")
logger.success(f"记忆构建间隔: {global_config.build_memory_interval}")
logger.success(f"记忆遗忘间隔: {global_config.forget_memory_interval}")
logger.success(f"记忆遗忘比例: {global_config.memory_forget_percentage}")
logger.success(f"记忆压缩率: {config.memory_compress_rate}")
logger.success(f"记忆构建样本数: {config.build_memory_sample_num}")
logger.success(f"记忆构建样本长度: {config.build_memory_sample_length}")
logger.success(f"记忆遗忘时间: {config.memory_forget_time}小时")
logger.success(f"记忆构建分布: {config.memory_build_distribution}")
logger.success("--------------------------------")
# 输出记忆图统计信息
memory_graph = self._hippocampus.memory_graph.G
node_count = len(memory_graph.nodes())
edge_count = len(memory_graph.edges())
logger.success("--------------------------------")
logger.success("记忆图统计信息:")
logger.success(f"记忆节点数量: {node_count}")
logger.success(f"记忆连接数量: {edge_count}")
logger.success("--------------------------------")
logger.success(f'''--------------------------------
记忆系统参数配置:
构建间隔: {global_config.build_memory_interval}秒|样本数: {config.build_memory_sample_num},长度: {config.build_memory_sample_length}|压缩率: {config.memory_compress_rate}
记忆构建分布: {config.memory_build_distribution}
遗忘间隔: {global_config.forget_memory_interval}秒|遗忘比例: {global_config.memory_forget_percentage}|遗忘: {config.memory_forget_time}小时之后
记忆图统计信息: 节点数量: {node_count}, 连接数量: {edge_count}
--------------------------------''') #noqa: E501
return self._hippocampus

View File

@@ -164,7 +164,7 @@ class LLM_request:
# 常见Error Code Mapping
error_code_mapping = {
400: "参数不正确",
401: "API key 错误,认证失败,请检查/config/bot_config.toml和.env.prod中的配置是否正确哦~",
401: "API key 错误,认证失败,请检查/config/bot_config.toml和.env中的配置是否正确哦~",
402: "账号余额不足",
403: "需要实名,或余额不足",
404: "Not Found",

View File

@@ -10,7 +10,7 @@ import random
current_dir = Path(__file__).resolve().parent
project_root = current_dir.parent.parent.parent
env_path = project_root / ".env.prod"
env_path = project_root / ".env"
root_path = os.path.abspath(os.path.join(os.path.dirname(__file__), "../../.."))
sys.path.append(root_path)

View File

@@ -17,7 +17,7 @@ import matplotlib.font_manager as fm
current_dir = Path(__file__).resolve().parent
project_root = current_dir.parent.parent.parent
env_path = project_root / ".env.prod"
env_path = project_root / ".env"
root_path = os.path.abspath(os.path.join(os.path.dirname(__file__), "../../.."))
sys.path.append(root_path)

View File

@@ -9,7 +9,7 @@ from scipy import stats # 添加scipy导入用于t检验
current_dir = Path(__file__).resolve().parent
project_root = current_dir.parent.parent.parent
env_path = project_root / ".env.prod"
env_path = project_root / ".env"
root_path = os.path.abspath(os.path.join(os.path.dirname(__file__), "../../.."))
sys.path.append(root_path)

View File

@@ -20,7 +20,7 @@ import sys
"""
current_dir = Path(__file__).resolve().parent
project_root = current_dir.parent.parent.parent
env_path = project_root / ".env.prod"
env_path = project_root / ".env"
root_path = os.path.abspath(os.path.join(os.path.dirname(__file__), "../../.."))
sys.path.append(root_path)

View File

@@ -20,7 +20,7 @@ import sys
"""
current_dir = Path(__file__).resolve().parent
project_root = current_dir.parent.parent.parent
env_path = project_root / ".env.prod"
env_path = project_root / ".env"
root_path = os.path.abspath(os.path.join(os.path.dirname(__file__), "../../.."))
sys.path.append(root_path)

View File

@@ -7,7 +7,7 @@ from typing import List, Dict, Optional
current_dir = Path(__file__).resolve().parent
project_root = current_dir.parent.parent.parent
env_path = project_root / ".env.prod"
env_path = project_root / ".env"
root_path = os.path.abspath(os.path.join(os.path.dirname(__file__), "../../.."))
sys.path.append(root_path)

View File

@@ -84,7 +84,7 @@ class ScheduleGenerator:
self.print_schedule()
# 执行当前活动
# mind_thinking = subheartflow_manager.current_state.current_mind
# mind_thinking = heartflow.current_state.current_mind
await self.move_doing()

View File

@@ -5,15 +5,12 @@ from ..config.config import global_config
from .mode_classical import WillingManager as ClassicalWillingManager
from .mode_dynamic import WillingManager as DynamicWillingManager
from .mode_custom import WillingManager as CustomWillingManager
from src.common.logger import LogConfig
from src.common.logger import LogConfig, WILLING_STYLE_CONFIG
willing_config = LogConfig(
console_format=(
"<green>{time:YYYY-MM-DD HH:mm:ss}</green> | "
"<level>{level: <8}</level> | "
"<red>{extra[module]: <12}</red> | "
"<level>{message}</level>"
),
# 使用消息发送专用样式
console_format=WILLING_STYLE_CONFIG["console_format"],
file_format=WILLING_STYLE_CONFIG["file_format"],
)
logger = get_module_logger("willing", config=willing_config)

View File

@@ -16,7 +16,7 @@ sys.path.append(root_path)
from src.common.database import db # noqa E402
# 加载根目录下的env.edv文件
env_path = os.path.join(root_path, ".env.prod")
env_path = os.path.join(root_path, ".env")
if not os.path.exists(env_path):
raise FileNotFoundError(f"配置文件不存在: {env_path}")
load_dotenv(env_path)

View File

@@ -1,7 +1,8 @@
from .sub_heartflow import SubHeartflow
from .observation import ChattingObservation
from src.plugins.moods.moods import MoodManager
from src.plugins.models.utils_model import LLM_request
from src.plugins.config.config import global_config, BotConfig
from src.plugins.config.config import global_config
from src.plugins.schedule.schedule_generator import bot_schedule
import asyncio
from src.common.logger import get_module_logger, LogConfig, HEARTFLOW_STYLE_CONFIG # noqa: E402
@@ -107,15 +108,29 @@ class Heartflow:
return reponse
def create_subheartflow(self, observe_chat_id):
"""创建一个新的SubHeartflow实例"""
if observe_chat_id not in self._subheartflows:
subheartflow = SubHeartflow()
subheartflow.assign_observe(observe_chat_id)
def create_subheartflow(self, subheartflow_id):
"""
创建一个新的SubHeartflow实例
添加一个SubHeartflow实例到self._subheartflows字典中
并根据subheartflow_id为子心流创建一个观察对象
"""
if subheartflow_id not in self._subheartflows:
logger.debug(f"创建 subheartflow: {subheartflow_id}")
subheartflow = SubHeartflow(subheartflow_id)
#创建一个观察对象目前只可以用chat_id创建观察对象
logger.debug(f"创建 observation: {subheartflow_id}")
observation = ChattingObservation(subheartflow_id)
logger.debug(f"添加 observation ")
subheartflow.add_observation(observation)
logger.debug(f"添加 observation 成功")
# 创建异步任务
logger.debug(f"创建异步任务")
asyncio.create_task(subheartflow.subheartflow_start_working())
self._subheartflows[observe_chat_id] = subheartflow
return self._subheartflows[observe_chat_id]
logger.debug(f"创建异步任务 成功")
self._subheartflows[subheartflow_id] = subheartflow
logger.debug(f"添加 subheartflow 成功")
return self._subheartflows[subheartflow_id]
def get_subheartflow(self, observe_chat_id):
"""获取指定ID的SubHeartflow实例"""
@@ -123,4 +138,4 @@ class Heartflow:
# 创建一个全局的管理器实例
subheartflow_manager = Heartflow()
heartflow = Heartflow()

View File

@@ -0,0 +1,120 @@
#定义了来自外部世界的信息
#外部世界可以是某个聊天 不同平台的聊天 也可以是任意媒体
import asyncio
from datetime import datetime
from src.plugins.models.utils_model import LLM_request
from src.plugins.config.config import global_config
from src.common.database import db
# 所有观察的基类
class Observation:
def __init__(self,observe_type,observe_id):
self.observe_info = ""
self.observe_type = observe_type
self.observe_id = observe_id
self.last_observe_time = datetime.now().timestamp() # 初始化为当前时间
# 聊天观察
class ChattingObservation(Observation):
def __init__(self,chat_id):
super().__init__("chat",chat_id)
self.chat_id = chat_id
self.talking_message = []
self.talking_message_str = ""
self.observe_times = 0
self.summary_count = 0 # 30秒内的更新次数
self.max_update_in_30s = 2 #30秒内最多更新2次
self.last_summary_time = 0 #上次更新summary的时间
self.sub_observe = None
self.llm_summary = LLM_request(
model=global_config.llm_outer_world, temperature=0.7, max_tokens=300, request_type="outer_world")
# 进行一次观察 返回观察结果observe_info
async def observe(self):
# 查找新消息限制最多30条
new_messages = list(db.messages.find({
"chat_id": self.chat_id,
"time": {"$gt": self.last_observe_time}
}).sort("time", 1).limit(20)) # 按时间正序排列最多20条
if not new_messages:
return self.observe_info #没有新消息,返回上次观察结果
# 将新消息转换为字符串格式
new_messages_str = ""
for msg in new_messages:
if "sender_name" in msg and "content" in msg:
new_messages_str += f"{msg['sender_name']}: {msg['content']}\n"
# 将新消息添加到talking_message同时保持列表长度不超过20条
self.talking_message.extend(new_messages)
if len(self.talking_message) > 20:
self.talking_message = self.talking_message[-20:] # 只保留最新的20条
self.translate_message_list_to_str()
# 更新观察次数
self.observe_times += 1
self.last_observe_time = new_messages[-1]["time"]
# 检查是否需要更新summary
current_time = int(datetime.now().timestamp())
if current_time - self.last_summary_time >= 30: # 如果超过30秒重置计数
self.summary_count = 0
self.last_summary_time = current_time
if self.summary_count < self.max_update_in_30s: # 如果30秒内更新次数小于2次
await self.update_talking_summary(new_messages_str)
self.summary_count += 1
return self.observe_info
async def carefully_observe(self):
# 查找新消息限制最多40条
new_messages = list(db.messages.find({
"chat_id": self.chat_id,
"time": {"$gt": self.last_observe_time}
}).sort("time", 1).limit(30)) # 按时间正序排列最多30条
if not new_messages:
return self.observe_info #没有新消息,返回上次观察结果
# 将新消息转换为字符串格式
new_messages_str = ""
for msg in new_messages:
if "sender_name" in msg and "content" in msg:
new_messages_str += f"{msg['sender_name']}: {msg['content']}\n"
# 将新消息添加到talking_message同时保持列表长度不超过30条
self.talking_message.extend(new_messages)
if len(self.talking_message) > 30:
self.talking_message = self.talking_message[-30:] # 只保留最新的30条
self.translate_message_list_to_str()
# 更新观察次数
self.observe_times += 1
self.last_observe_time = new_messages[-1]["time"]
await self.update_talking_summary(new_messages_str)
return self.observe_info
async def update_talking_summary(self,new_messages_str):
#基于已经有的talking_summary和新的talking_message生成一个summary
# print(f"更新聊天总结:{self.talking_summary}")
prompt = ""
prompt = f"你正在参与一个qq群聊的讨论这个群之前在聊的内容是{self.observe_info}\n"
prompt += f"现在群里的群友们产生了新的讨论,有了新的发言,具体内容如下:{new_messages_str}\n"
prompt += '''以上是群里在进行的聊天,请你对这个聊天内容进行总结,总结内容要包含聊天的大致内容,
以及聊天中的一些重要信息,记得不要分点,不要太长,精简的概括成一段文本\n'''
prompt += "总结概括:"
self.observe_info, reasoning_content = await self.llm_summary.generate_response_async(prompt)
def translate_message_list_to_str(self):
self.talking_message_str = ""
for message in self.talking_message:
self.talking_message_str += message["detailed_plain_text"]

View File

@@ -1,144 +0,0 @@
#定义了来自外部世界的信息
import asyncio
from datetime import datetime
from src.plugins.models.utils_model import LLM_request
from src.plugins.config.config import global_config
from src.common.database import db
#存储一段聊天的大致内容
class Talking_info:
def __init__(self,chat_id):
self.chat_id = chat_id
self.talking_message = []
self.talking_message_str = ""
self.talking_summary = ""
self.last_observe_time = int(datetime.now().timestamp()) #初始化为当前时间
self.observe_times = 0
self.activate = 360
self.last_summary_time = int(datetime.now().timestamp()) # 上次更新summary的时间
self.summary_count = 0 # 30秒内的更新次数
self.max_update_in_30s = 2
self.oberve_interval = 3
self.llm_summary = LLM_request(
model=global_config.llm_outer_world, temperature=0.7, max_tokens=300, request_type="outer_world")
async def start_observe(self):
while True:
if self.activate <= 0:
print(f"聊天 {self.chat_id} 活跃度不足,进入休眠状态")
await self.waiting_for_activate()
print(f"聊天 {self.chat_id} 被重新激活")
await self.observe_world()
await asyncio.sleep(self.oberve_interval)
async def waiting_for_activate(self):
while True:
# 检查从上次观察时间之后的新消息数量
new_messages_count = db.messages.count_documents({
"chat_id": self.chat_id,
"time": {"$gt": self.last_observe_time}
})
if new_messages_count > 15:
self.activate = 360*(self.observe_times+1)
return
await asyncio.sleep(8) # 每10秒检查一次
async def observe_world(self):
# 查找新消息限制最多20条
new_messages = list(db.messages.find({
"chat_id": self.chat_id,
"time": {"$gt": self.last_observe_time}
}).sort("time", 1).limit(20)) # 按时间正序排列最多20条
if not new_messages:
self.activate += -1
return
# 将新消息添加到talking_message同时保持列表长度不超过20条
self.talking_message.extend(new_messages)
if len(self.talking_message) > 20:
self.talking_message = self.talking_message[-20:] # 只保留最新的20条
self.translate_message_list_to_str()
self.observe_times += 1
self.last_observe_time = new_messages[-1]["time"]
# 检查是否需要更新summary
current_time = int(datetime.now().timestamp())
if current_time - self.last_summary_time >= 30: # 如果超过30秒重置计数
self.summary_count = 0
self.last_summary_time = current_time
if self.summary_count < self.max_update_in_30s: # 如果30秒内更新次数小于2次
await self.update_talking_summary()
self.summary_count += 1
async def update_talking_summary(self):
#基于已经有的talking_summary和新的talking_message生成一个summary
# print(f"更新聊天总结:{self.talking_summary}")
prompt = ""
prompt = f"你正在参与一个qq群聊的讨论这个群之前在聊的内容是{self.talking_summary}\n"
prompt += f"现在群里的群友们产生了新的讨论,有了新的发言,具体内容如下:{self.talking_message_str}\n"
prompt += '''以上是群里在进行的聊天,请你对这个聊天内容进行总结,总结内容要包含聊天的大致内容,
以及聊天中的一些重要信息,记得不要分点,不要太长,精简的概括成一段文本\n'''
prompt += "总结概括:"
self.talking_summary, reasoning_content = await self.llm_summary.generate_response_async(prompt)
def translate_message_list_to_str(self):
self.talking_message_str = ""
for message in self.talking_message:
self.talking_message_str += message["detailed_plain_text"]
class SheduleInfo:
def __init__(self):
self.shedule_info = ""
class OuterWorld:
def __init__(self):
self.talking_info_list = [] #装的一堆talking_info
self.shedule_info = "无日程"
# self.interest_info = "麦麦你好"
self.outer_world_info = ""
self.start_time = int(datetime.now().timestamp())
self.llm_summary = LLM_request(
model=global_config.llm_outer_world, temperature=0.7, max_tokens=600, request_type="outer_world_info")
async def check_and_add_new_observe(self):
# 获取所有聊天流
all_streams = db.chat_streams.find({})
# 遍历所有聊天流
for data in all_streams:
stream_id = data.get("stream_id")
# 检查是否已存在该聊天流的观察对象
existing_info = next((info for info in self.talking_info_list if info.chat_id == stream_id), None)
# 如果不存在创建新的Talking_info对象并添加到列表中
if existing_info is None:
print(f"发现新的聊天流: {stream_id}")
new_talking_info = Talking_info(stream_id)
self.talking_info_list.append(new_talking_info)
# 启动新对象的观察任务
asyncio.create_task(new_talking_info.start_observe())
async def open_eyes(self):
while True:
print("检查新的聊天流")
await self.check_and_add_new_observe()
await asyncio.sleep(60)
def get_world_by_stream_id(self,stream_id):
for talking_info in self.talking_info_list:
if talking_info.chat_id == stream_id:
return talking_info
return None
outer_world = OuterWorld()
if __name__ == "__main__":
asyncio.run(outer_world.open_eyes())

View File

@@ -1,8 +1,8 @@
from .outer_world import outer_world
from .observation import Observation
import asyncio
from src.plugins.moods.moods import MoodManager
from src.plugins.models.utils_model import LLM_request
from src.plugins.config.config import global_config, BotConfig
from src.plugins.config.config import global_config
import re
import time
from src.plugins.schedule.schedule_generator import bot_schedule
@@ -30,18 +30,17 @@ class CuttentState:
class SubHeartflow:
def __init__(self):
def __init__(self,subheartflow_id):
self.subheartflow_id = subheartflow_id
self.current_mind = ""
self.past_mind = []
self.current_state : CuttentState = CuttentState()
self.llm_model = LLM_request(
model=global_config.llm_sub_heartflow, temperature=0.7, max_tokens=600, request_type="sub_heart_flow")
self.outer_world = None
self.main_heartflow_info = ""
self.observe_chat_id = None
self.last_reply_time = time.time()
if not self.current_mind:
@@ -50,10 +49,31 @@ class SubHeartflow:
self.personality_info = " ".join(global_config.PROMPT_PERSONALITY)
self.is_active = False
self.observations : list[Observation] = []
def assign_observe(self,stream_id):
self.outer_world = outer_world.get_world_by_stream_id(stream_id)
self.observe_chat_id = stream_id
def add_observation(self, observation: Observation):
"""添加一个新的observation对象到列表中如果已存在相同id的observation则不添加"""
# 查找是否存在相同id的observation
for existing_obs in self.observations:
if existing_obs.observe_id == observation.observe_id:
# 如果找到相同id的observation直接返回
return
# 如果没有找到相同id的observation则添加新的
self.observations.append(observation)
def remove_observation(self, observation: Observation):
"""从列表中移除一个observation对象"""
if observation in self.observations:
self.observations.remove(observation)
def get_all_observations(self) -> list[Observation]:
"""获取所有observation对象"""
return self.observations
def clear_observations(self):
"""清空所有observation对象"""
self.observations.clear()
async def subheartflow_start_working(self):
while True:
@@ -64,27 +84,34 @@ class SubHeartflow:
await asyncio.sleep(60) # 每30秒检查一次
else:
self.is_active = True
observation = self.observations[0]
observation.observe()
self.current_state.update_current_state_info()
await self.do_a_thinking()
await self.judge_willing()
await asyncio.sleep(60)
async def do_a_thinking(self):
self.current_state.update_current_state_info()
current_thinking_info = self.current_mind
mood_info = self.current_state.mood
message_stream_info = self.outer_world.talking_summary
print(f"message_stream_info{message_stream_info}")
observation = self.observations[0]
chat_observe_info = observation.observe_info
print(f"chat_observe_info{chat_observe_info}")
# 调取记忆
related_memory = await HippocampusManager.get_instance().get_memory_from_text(
text=message_stream_info,
text=chat_observe_info,
max_memory_num=2,
max_memory_length=2,
max_depth=3,
fast_retrieval=False
)
# print(f"相关记忆:{related_memory}")
if related_memory:
related_memory_info = ""
for memory in related_memory:
@@ -104,8 +131,7 @@ class SubHeartflow:
prompt += f"你想起来你之前见过的回忆:{related_memory_info}\n以上是你的回忆,不一定是目前聊天里的人说的,也不一定是现在发生的事情,请记住。\n"
prompt += f"刚刚你的想法是{current_thinking_info}\n"
prompt += "-----------------------------------\n"
if message_stream_info:
prompt += f"现在你正在上网和qq群里的网友们聊天群里正在聊的话题是{message_stream_info}\n"
prompt += f"现在你正在上网和qq群里的网友们聊天群里正在聊的话题是{chat_observe_info}\n"
prompt += f"你现在{mood_info}\n"
prompt += "现在你接下去继续思考,产生新的想法,不要分点输出,输出连贯的内心独白,不要太长,"
prompt += "但是记得结合上述的消息,要记得维持住你的人设,关注聊天和新内容,不要思考太多:"
@@ -119,12 +145,13 @@ class SubHeartflow:
async def do_after_reply(self,reply_content,chat_talking_prompt):
# print("麦麦脑袋转起来了")
self.current_state.update_current_state_info()
current_thinking_info = self.current_mind
mood_info = self.current_state.mood
# related_memory_info = 'memory'
message_stream_info = self.outer_world.talking_summary
observation = self.observations[0]
chat_observe_info = observation.observe_info
message_new_info = chat_talking_prompt
reply_info = reply_content
schedule_info = bot_schedule.get_current_num_task(num = 1,time_info = False)
@@ -133,8 +160,7 @@ class SubHeartflow:
prompt = ""
prompt += f"你刚刚在做的事情是:{schedule_info}\n"
prompt += f"{self.personality_info}\n"
prompt += f"现在你正在上网和qq群里的网友们聊天群里正在聊的话题是{message_stream_info}\n"
prompt += f"现在你正在上网和qq群里的网友们聊天群里正在聊的话题是{chat_observe_info}\n"
# if related_memory_info:
# prompt += f"你想起来{related_memory_info}。"
prompt += f"刚刚你的想法是{current_thinking_info}"
@@ -174,14 +200,8 @@ class SubHeartflow:
else:
self.current_state.willing = 0
logger.info(f"{self.observe_chat_id}麦麦的回复意愿:{self.current_state.willing}")
return self.current_state.willing
def build_outer_world_info(self):
outer_world_info = outer_world.outer_world_info
return outer_world_info
def update_current_mind(self,reponse):
self.past_mind.append(self.current_mind)
self.current_mind = reponse

View File

@@ -140,7 +140,7 @@ enable_friend_chat = false # 是否启用好友聊天
enable_think_flow = false # 是否启用思维流 注意可能会消耗大量token请谨慎开启
#思维流适合搭配低能耗普通模型使用例如qwen2.5 32b
#下面的模型若使用硅基流动则不需要更改使用ds官方则改成.env.prod自定义的宏,使用自定义模型则选择定位相似的模型自己填写
#下面的模型若使用硅基流动则不需要更改使用ds官方则改成.env自定义的宏使用自定义模型则选择定位相似的模型自己填写
#推理模型
[model.llm_reasoning] #回复模型1 主要回复模型

View File

@@ -118,12 +118,12 @@ else:
config_data = toml.load("config/bot_config.toml")
init_model_pricing()
if not os.path.exists(".env.prod"):
logger.error("环境配置文件 .env.prod 不存在,请检查配置文件路径")
raise FileNotFoundError("环境配置文件 .env.prod 不存在,请检查配置文件路径")
if not os.path.exists(".env"):
logger.error("环境配置文件 .env 不存在,请检查配置文件路径")
raise FileNotFoundError("环境配置文件 .env 不存在,请检查配置文件路径")
else:
# 载入env文件并解析
env_config_file = ".env.prod" # 配置文件路径
env_config_file = ".env" # 配置文件路径
env_config_data = parse_env_config(env_config_file)
# 增加最低支持版本
@@ -173,7 +173,7 @@ WEBUI_VERSION = version.parse("0.0.11")
# env环境配置文件保存函数
def save_to_env_file(env_variables, filename=".env.prod"):
def save_to_env_file(env_variables, filename=".env"):
"""
将修改后的变量保存到指定的.env文件中并在第一次保存前备份文件如果备份文件不存在
"""
@@ -196,7 +196,7 @@ def save_to_env_file(env_variables, filename=".env.prod"):
# 载入env文件并解析
env_config_file = ".env.prod" # 配置文件路径
env_config_file = ".env" # 配置文件路径
env_config_data = parse_env_config(env_config_file)
if "env_VOLCENGINE_BASE_URL" in env_config_data:
logger.info("VOLCENGINE_BASE_URL 已存在,使用默认值")
@@ -421,7 +421,7 @@ def save_trigger(
env_config_data[f"env_{t_api_provider}_KEY"] = t_api_key
save_to_env_file(env_config_data)
logger.success("配置已保存到 .env.prod 文件中")
logger.success("配置已保存到 .env 文件中")
return "配置已保存"

View File

@@ -556,7 +556,7 @@ def format_results(all_errors):
def main():
# 获取配置文件路径
config_path = Path("config/bot_config.toml")
env_path = Path(".env.prod")
env_path = Path(".env")
if not config_path.exists():
print(f"错误: 找不到配置文件 {config_path}")