better:更好的心流结构,使用了观察取代外部世界
This commit is contained in:
101
README.md
101
README.md
@@ -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) - 项目结构和核心功能实现细节
|
||||
|
||||
## 🎯 功能介绍
|
||||
|
||||
|
||||
20
bot.py
20
bot.py
@@ -45,25 +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.prod文件是否存在
|
||||
if not os.path.exists(".env.prod"):
|
||||
logger.error("检测到.env.prod文件不存在")
|
||||
shutil.copy("template/template.env", "./.env.prod")
|
||||
logger.info("已从template/template.env复制创建.env.prod,请修改配置后重新启动")
|
||||
# 检测.env文件是否存在
|
||||
if not os.path.exists(".env"):
|
||||
logger.error("检测到.env文件不存在")
|
||||
shutil.copy("template/template.env", "./.env")
|
||||
logger.info("已从template/template.env复制创建.env,请修改配置后重新启动")
|
||||
|
||||
|
||||
def load_env():
|
||||
# 直接加载生产环境变量配置
|
||||
if os.path.exists(".env.prod"):
|
||||
load_dotenv(".env.prod", override=True)
|
||||
if os.path.exists(".env"):
|
||||
load_dotenv(".env", override=True)
|
||||
logger.success("成功加载环境变量配置")
|
||||
else:
|
||||
logger.error("未找到.env.prod文件,请确保文件存在")
|
||||
raise FileNotFoundError("未找到.env.prod文件,请确保文件存在")
|
||||
logger.error("未找到.env文件,请确保文件存在")
|
||||
raise FileNotFoundError("未找到.env文件,请确保文件存在")
|
||||
|
||||
|
||||
def scan_provider(env_config: dict):
|
||||
|
||||
@@ -114,7 +114,7 @@ AI总结
|
||||
- 优化脚本逻辑
|
||||
- 修复虚拟环境选项闪退和conda激活问题
|
||||
- 修复环境检测菜单闪退问题
|
||||
- 修复.env.prod文件复制路径错误
|
||||
- 修复.env文件复制路径错误
|
||||
|
||||
#### 日志系统改进
|
||||
- 新增GUI日志查看器
|
||||
|
||||
@@ -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:
|
||||
|
||||
@@ -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容器:
|
||||
|
||||
|
||||
@@ -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网站调用了一个并不存在的模型**
|
||||
>
|
||||
|
||||
@@ -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. **主要模型功能**:
|
||||
|
||||
@@ -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配置
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -111,7 +111,7 @@ nb run
|
||||
# 或
|
||||
python3 bot.py
|
||||
```
|
||||
之后你就可以找到`.env.prod`和`bot_config.toml`这两个文件了
|
||||
之后你就可以找到`.env`和`bot_config.toml`这两个文件了
|
||||
关于文件内容的配置请参考:
|
||||
- [🎀 新手配置指南](./installation_cute.md) - 通俗易懂的配置教程,适合初次使用的猫娘
|
||||
- [⚙️ 标准配置指南](./installation_standard.md) - 简明专业的配置说明,适合有经验的用户
|
||||
|
||||
@@ -82,7 +82,7 @@ nb run
|
||||
python3 bot.py
|
||||
```
|
||||
|
||||
之后你就可以找到`.env.prod`和`bot_config.toml`这两个文件了
|
||||
之后你就可以找到`.env`和`bot_config.toml`这两个文件了
|
||||
|
||||
关于文件内容的配置请参考:
|
||||
- [🎀 新手配置指南](./installation_cute.md) - 通俗易懂的配置教程,适合初次使用的猫娘
|
||||
|
||||
@@ -87,7 +87,7 @@ pip install -r requirements.txt
|
||||
|
||||
### 5️⃣ **配置文件设置,让麦麦Bot正常工作**
|
||||
|
||||
- 修改环境配置文件:`.env.prod`
|
||||
- 修改环境配置文件:`.env`
|
||||
- 修改机器人配置文件:`bot_config.toml`
|
||||
|
||||
### 6️⃣ **启动麦麦机器人**
|
||||
|
||||
@@ -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`
|
||||

|
||||

|
||||
|
||||
把 `bot_config.toml` 和 `.env.prod` 放入之前创建的 `MaiMBot`文件夹
|
||||
把 `bot_config.toml` 和 `.env` 放入之前创建的 `MaiMBot`文件夹
|
||||
|
||||
#### 如何下载?
|
||||
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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("未找到环境配置文件")
|
||||
|
||||
30
src/main.py
30
src/main.py
@@ -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
|
||||
@@ -73,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(
|
||||
@@ -89,14 +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_end_time = time.time()
|
||||
logger.success(f"初始化完成,用时{init_end_time - init_start_time}秒")
|
||||
init_time = int(1000*(time.time()- init_start_time))
|
||||
logger.success(f"初始化完成,神经元放电{init_time}次")
|
||||
except Exception as e:
|
||||
logger.error(f"启动大脑和外部世界失败: {e}")
|
||||
raise
|
||||
@@ -107,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(),
|
||||
@@ -132,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:
|
||||
|
||||
@@ -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的子心流
|
||||
|
||||
@@ -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,7 +56,7 @@ class ChatBot:
|
||||
5. 更新关系
|
||||
6. 更新情绪
|
||||
"""
|
||||
|
||||
|
||||
message = MessageRecv(message_data)
|
||||
groupinfo = message.message_info.group_info
|
||||
userinfo = message.message_info.user_info
|
||||
@@ -74,18 +72,8 @@ class ChatBot:
|
||||
)
|
||||
message.update_chat_stream(chat)
|
||||
|
||||
# 创建 心流 观察
|
||||
|
||||
await outer_world.check_and_add_new_observe()
|
||||
subheartflow_manager.create_subheartflow(chat.stream_id)
|
||||
|
||||
timer1 = time.time()
|
||||
await relationship_manager.update_relationship(
|
||||
chat_stream=chat,
|
||||
)
|
||||
await relationship_manager.update_relationship_value(chat_stream=chat, relationship_value=0)
|
||||
timer2 = time.time()
|
||||
logger.info(f"1关系更新时间: {timer2 - timer1}秒")
|
||||
# 创建 心流与chat的观察
|
||||
heartflow.create_subheartflow(chat.stream_id)
|
||||
|
||||
timer1 = time.time()
|
||||
await message.process()
|
||||
@@ -99,10 +87,9 @@ class ChatBot:
|
||||
):
|
||||
return
|
||||
|
||||
current_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(messageinfo.time))
|
||||
|
||||
# 根据话题计算激活度
|
||||
await self.storage.store_message(message, chat)
|
||||
|
||||
|
||||
timer1 = time.time()
|
||||
interested_rate = 0
|
||||
@@ -117,8 +104,8 @@ class ChatBot:
|
||||
|
||||
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
|
||||
print(f"4旧回复意愿:{current_willing_old},新回复意愿:{current_willing_new}")
|
||||
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:
|
||||
current_willing = willing_manager.get_willing(chat_stream=chat)
|
||||
@@ -147,7 +134,8 @@ class ChatBot:
|
||||
else:
|
||||
mes_name = '私聊'
|
||||
|
||||
# print(f"mes_name: {mes_name}")
|
||||
#打印收到的信息的信息
|
||||
current_time = time.strftime("%H:%M:%S", time.localtime(messageinfo.time))
|
||||
logger.info(
|
||||
f"[{current_time}][{mes_name}]"
|
||||
f"{chat.user_info.user_nickname}:"
|
||||
@@ -225,7 +213,7 @@ class ChatBot:
|
||||
|
||||
return response_set, thinking_id
|
||||
|
||||
async def _update_using_response(self, message, chat, response_set):
|
||||
async def _update_using_response(self, message, response_set):
|
||||
# 更新心流状态
|
||||
stream_id = message.chat_stream.stream_id
|
||||
chat_talking_prompt = ""
|
||||
@@ -234,10 +222,10 @@ class ChatBot:
|
||||
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_set, chat_talking_prompt)
|
||||
if heartflow.get_subheartflow(stream_id):
|
||||
await heartflow.get_subheartflow(stream_id).do_after_reply(response_set, chat_talking_prompt)
|
||||
else:
|
||||
await subheartflow_manager.create_subheartflow(stream_id).do_after_reply(response_set, chat_talking_prompt)
|
||||
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):
|
||||
|
||||
@@ -97,9 +97,7 @@ class ResponseGenerator:
|
||||
logger.info(f"构建prompt时间: {timer2 - timer1}秒")
|
||||
|
||||
try:
|
||||
print(111111111111111111111111111111111111111111111111111111111)
|
||||
content, reasoning_content, self.current_model_name = await model.generate_response(prompt)
|
||||
print(222222222222222222222222222222222222222222222222222222222)
|
||||
except Exception:
|
||||
logger.exception("生成回复时出错")
|
||||
return None
|
||||
|
||||
@@ -12,7 +12,7 @@ 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")
|
||||
|
||||
@@ -34,12 +34,11 @@ class PromptBuilder:
|
||||
# )
|
||||
|
||||
# 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 = ""
|
||||
current_mind_info = heartflow.get_subheartflow(stream_id).current_mind
|
||||
|
||||
|
||||
# relation_prompt = ""
|
||||
# for person in who_chat_in_group:
|
||||
# relation_prompt += relationship_manager.build_relationship_info(person)
|
||||
|
||||
@@ -74,23 +73,22 @@ class PromptBuilder:
|
||||
chat_talking_prompt = chat_talking_prompt
|
||||
# print(f"\033[1;34m[调试]\033[0m 已从数据库获取群 {group_id} 的消息记录:{chat_talking_prompt}")
|
||||
|
||||
logger.info(f"聊天上下文prompt: {chat_talking_prompt}")
|
||||
|
||||
# 使用新的记忆获取方法
|
||||
memory_prompt = ""
|
||||
start_time = time.time()
|
||||
|
||||
# 调用 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=2, fast_retrieval=True
|
||||
# )
|
||||
# memory_str = ""
|
||||
# for _topic, memories in relevant_memories:
|
||||
# memory_str += f"{memories}\n"
|
||||
#调用 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=2, fast_retrieval=False
|
||||
)
|
||||
memory_str = ""
|
||||
for _topic, memories in relevant_memories:
|
||||
memory_str += f"{memories}\n"
|
||||
|
||||
# if relevant_memories:
|
||||
# # 格式化记忆内容
|
||||
# memory_prompt = f"你回忆起:\n{memory_str}\n"
|
||||
if relevant_memories:
|
||||
# 格式化记忆内容
|
||||
memory_prompt = f"你回忆起:\n{memory_str}\n"
|
||||
|
||||
end_time = time.time()
|
||||
logger.info(f"回忆耗时: {(end_time - start_time):.3f}秒")
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -1266,13 +1266,13 @@ class HippocampusManager:
|
||||
node_count = len(memory_graph.nodes())
|
||||
edge_count = len(memory_graph.edges())
|
||||
|
||||
logger.success("--------------------------------")
|
||||
logger.success("记忆系统参数配置:")
|
||||
logger.success(f"构建间隔: {global_config.build_memory_interval}秒|样本数: {config.build_memory_sample_num},长度: {config.build_memory_sample_length}|压缩率: {config.memory_compress_rate}") # noqa: E501
|
||||
logger.success(f"记忆构建分布: {config.memory_build_distribution}")
|
||||
logger.success(f"遗忘间隔: {global_config.forget_memory_interval}秒|遗忘比例: {global_config.memory_forget_percentage}|遗忘: {config.memory_forget_time}小时之后") # noqa: E501
|
||||
logger.success(f"记忆图统计信息: 节点数量: {node_count}, 连接数量: {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
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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()
|
||||
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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()
|
||||
|
||||
120
src/think_flow_demo/observation.py
Normal file
120
src/think_flow_demo/observation.py
Normal 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"]
|
||||
@@ -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())
|
||||
@@ -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
|
||||
|
||||
@@ -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 主要回复模型
|
||||
|
||||
14
webui.py
14
webui.py
@@ -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 "配置已保存"
|
||||
|
||||
|
||||
|
||||
@@ -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}")
|
||||
|
||||
Reference in New Issue
Block a user