当前位置: 首页 > news >正文

MetaGPT源码 (Memory 类)

目录

    • MetaGPT源码:Memory 类
    • 例子

MetaGPT源码:Memory 类

这段代码定义了一个名为 Memory 的类,用于存储和管理消息(Message)对象。Memory 提供了多种操作消息的功能,包括添加单条或批量消息、按角色或内容筛选消息、删除最新消息、清空存储、按触发动作获取消息等。消息存储在 storage 列表中,同时使用 index 字典对消息的触发动作(cause_by)进行索引,以支持快速检索。通过这些方法,Memory 类能够高效地管理消息流,实现对消息的组织、查询和更新,适用于需要处理复杂消息交互的场景。

from collections import defaultdict
from typing import DefaultDict, Iterable, Setfrom pydantic import BaseModel, Field, SerializeAsAnyfrom metagpt.const import IGNORED_MESSAGE_ID
from metagpt.schema import Message
from metagpt.utils.common import any_to_str, any_to_str_setclass Memory(BaseModel):"""The most basic memory: super-memory"""storage: list[SerializeAsAny[Message]] = []index: DefaultDict[str, list[SerializeAsAny[Message]]] = Field(default_factory=lambda: defaultdict(list))ignore_id: bool = Falsedef add(self, message: Message):"""Add a new message to storage, while updating the index"""if self.ignore_id:message.id = IGNORED_MESSAGE_IDif message in self.storage:returnself.storage.append(message)if message.cause_by:self.index[message.cause_by].append(message)def add_batch(self, messages: Iterable[Message]):for message in messages:self.add(message)def get_by_role(self, role: str) -> list[Message]:"""Return all messages of a specified role"""return [message for message in self.storage if message.role == role]def get_by_content(self, content: str) -> list[Message]:"""Return all messages containing a specified content"""return [message for message in self.storage if content in message.content]def delete_newest(self) -> "Message":"""delete the newest message from the storage"""if len(self.storage) > 0:newest_msg = self.storage.pop()if newest_msg.cause_by and newest_msg in self.index[newest_msg.cause_by]:self.index[newest_msg.cause_by].remove(newest_msg)else:newest_msg = Nonereturn newest_msgdef delete(self, message: Message):"""Delete the specified message from storage, while updating the index"""if self.ignore_id:message.id = IGNORED_MESSAGE_IDself.storage.remove(message)if message.cause_by and message in self.index[message.cause_by]:self.index[message.cause_by].remove(message)def clear(self):"""Clear storage and index"""self.storage = []self.index = defaultdict(list)def count(self) -> int:"""Return the number of messages in storage"""return len(self.storage)def try_remember(self, keyword: str) -> list[Message]:"""Try to recall all messages containing a specified keyword"""return [message for message in self.storage if keyword in message.content]def get(self, k=0) -> list[Message]:"""Return the most recent k memories, return all when k=0"""return self.storage[-k:]def find_news(self, observed: list[Message], k=0) -> list[Message]:"""find news (previously unseen messages) from the most recent k memories, from all memories when k=0"""already_observed = self.get(k)news: list[Message] = []for i in observed:if i in already_observed:continuenews.append(i)return newsdef get_by_action(self, action) -> list[Message]:"""Return all messages triggered by a specified Action"""index = any_to_str(action)return self.index[index]def get_by_actions(self, actions: Set) -> list[Message]:"""Return all messages triggered by specified Actions"""rsp = []indices = any_to_str_set(actions)for action in indices:if action not in self.index:continuersp += self.index[action]return rsp

2024-12-11 22:38:16.092 | INFO | metagpt.const:get_metagpt_package_root:21 - Package root set to d:\llm\metagpt

例子

以下是一些例子,帮助你理解 Memory 类及其方法的使用:

  1. 创建 Memory 对象并添加消息
from metagpt.schema import Message# 创建 Memory 实例
memory = Memory()# 创建一个 Message 实例
message1 = Message(role="user", content="Hello!", cause_by=None, id="1")
message2 = Message(role="assistant", content="Hi there!", cause_by="1", id="2")# 添加消息
memory.add(message1)
memory.add(message2)print("Storage:", memory.storage)

Storage: [user: Hello!, assistant: Hi there!]

  1. 批量添加消息
messages = [Message(role="user", content="How are you?", cause_by=None, id="3"),Message(role="assistant", content="I'm fine, thank you!", cause_by="3", id="4"),
]memory.add_batch(messages)print("Storage after batch add:", memory.storage)

Storage after batch add: [user: Hello!, assistant: Hi there!, user: How are you?, assistant: I'm fine, thank you!]

  1. 按角色获取消息
user_messages = memory.get_by_role("user")
print("Messages from user:", user_messages)

Messages from user: [user: Hello!, user: How are you?]

  1. 按内容查找消息
matching_messages = memory.get_by_content("fine")
print("Messages containing 'fine':", matching_messages)

Messages containing 'fine': [assistant: I'm fine, thank you!]

  1. 删除最新消息
newest_message = memory.delete_newest()
print("Deleted newest message:", newest_message)
print("Storage after deletion:", memory.storage)

Deleted newest message: assistant: I'm fine, thank you!
Storage after deletion: [user: Hello!, assistant: Hi there!, user: How are you?]

  1. 清空存储
memory.clear()
print("Storage after clear:", memory.storage)

Storage after clear: []

  1. 按触发动作查找消息
# 添加一些消息
memory.add(Message(role="assistant", content="Task completed!", cause_by="action_1", id="5"))
memory.add(Message(role="assistant", content="Another task completed!", cause_by="action_2", id="6"))# 根据动作获取消息
action_messages = memory.get_by_action("action_1")
print("Messages triggered by 'action_1':", action_messages)

Messages triggered by 'action_1': [assistant: Task completed!]

如果有任何问题,欢迎在评论区提问。

相关文章:

MetaGPT源码 (Memory 类)

目录 MetaGPT源码:Memory 类例子 MetaGPT源码:Memory 类 这段代码定义了一个名为 Memory 的类,用于存储和管理消息(Message)对象。Memory 提供了多种操作消息的功能,包括添加单条或批量消息、按角色或内容筛选消息、删除最新消息…...

数据结构与算法复习AVL树插入过程

环境 $ cat /proc/version Linux version 6.8.0-45-generic (builddlcy02-amd64-115) (x86_64-linux-gnu-gcc-13 (Ubuntu 13.2.0-23ubuntu4) 13.2.0, GNU ld (GNU Binutils for Ubuntu) 2.42) #45-Ubuntu SMP PREEMPT_DYNAMIC Fri Aug 30 12:02:04 UTC 2024 #include <std…...

小迪笔记第 五十天 文件包含漏洞 远程包含 本地包含 ctf练习题实战

前言 文件包含漏洞 原理就是包含的文件如果可控就会造成这个漏洞 php文件包含的特征 &#xff1a; PHP&#xff1a;include、require、include_once、require_once等 一共是分为了2 种 一个就是 远程文件包含 这个的前提是php开启了 远程文件上传这个选项 原理应用就是…...

单片机:实现点阵汉字平滑滚动显示(附带源码)

单片机实现点阵汉字平滑滚动显示 点阵显示技术是嵌入式系统中的常见显示技术之一&#xff0c;广泛应用于LED矩阵显示屏、广告牌、电子时钟等设备。在本项目中&#xff0c;我们将实现一个基于单片机的点阵汉字平滑滚动显示系统&#xff0c;使用LED点阵显示屏来实现动态滚动的汉…...

C# 实现 10 位纯数字随机数

本文将介绍如何用 C# 实现一个生成 10 位纯数字随机数的功能。以下是完整的代码示例&#xff1a; using System; using System.Collections.Generic; using System.Linq; using System.Text;namespace RandomTset {class Program{// 使用GUID作为种子来创建随机数生成器static…...

分布式全文检索引擎ElasticSearch-基本概念介绍

一、索引类型 索引&#xff0c;可以理解是我们的目录&#xff0c;看一本书的时候&#xff0c;可以根据目录准确快速定位到某一页&#xff0c;那么索引就可以帮我们快速定位到某条数据在庞大的数据表的哪一个位置。 我们常见的索引包括正排索引和倒排索引 1、正排索引 正排索…...

电子应用设计方案-49:智能拖把系统方案设计

智能拖把系统方案设计 一、引言 随着人们生活水平的提高和对清洁效率的追求&#xff0c;智能拖把作为一种创新的清洁工具应运而生。本方案旨在设计一款功能强大、操作便捷、清洁效果出色的智能拖把系统。 二、系统概述 1. 系统目标 - 实现自动清洁地面&#xff0c;减轻用户劳…...

汽车免拆诊断案例 | 2014款保时捷卡宴车发动机偶尔无法起动

故障现象 一辆2014款保时捷卡宴车&#xff0c;搭载3.0T 发动机&#xff0c;累计行驶里程约为18万km。车主反映&#xff0c;发动机偶尔无法起动。 故障诊断 接车后试车&#xff0c;发动机起动及运转均正常。用故障检测仪检测&#xff0c;发动机控制单元&#xff08;DME&#x…...

电脑怎么设置通电自动开机(工控机)

操作系统&#xff1a;win10 第一步&#xff0c;电脑开机时按del键进入bios页面。 第二步&#xff0c;选择advanced下的IT8712 Super IO Configuration 第三步&#xff0c;找到Auto Power On&#xff0c;将其从Power off设置为Power On 第四步&#xff0c;F10保存&#xff0c;大…...

MaxKB进阶:豆包大模型驱动的智能日报小助手

MaxKB进阶&#xff1a;豆包大模型驱动的智能日报小助手 说明&#xff1a; 在本教程中&#xff0c;我们通过“智能日报小助手”的应用场景&#xff0c;全面解析MaxKB的进阶功能&#xff1a;从如何接入公共大模型&#xff08;以豆包为例&#xff09;&#xff0c;到函数功能的灵活…...

Python爬虫之使用xpath进行HTML Document文档的解析

响应有两种&#xff1a;JSON数据和HTML页面&#xff0c;对于后者就需要进行解析HTML Documen得到我们需要的信息。 ① xpath使用 可以提前安装xpath插件&#xff0c;也可以自己从HTML源码解析。 &#xff08;1&#xff09;打开chrome浏览器 &#xff08;2&#xff09;点击右…...

调度系统:使用 Airflow 对 Couchbase 执行 SQL 调度时的潜在问题

使用 Airflow 对 Couchbase 执行 SQL 调度时&#xff0c;通常情况下不会直接遇到与 Couchbase 分布式特性相关的异常&#xff0c;但在某些特定情境下&#xff0c;可能会出现一些与分布式环境、调度和数据一致性相关的潜在问题。以下是一些可能会遇到的问题和建议的解决方案&…...

【数据结构——查找】二分查找(头歌实践教学平台习题)【合集】

目录&#x1f60b; 任务描述 相关知识 测试说明 我的通关代码: 测试结果&#xff1a; 任务描述 本关任务&#xff1a;实现二分查找的算法。 相关知识 为了完成本关任务&#xff0c;你需要掌握&#xff1a;1.根据键盘输入的一组有序数据建立顺序表&#xff0c;2.顺序表的输…...

简单网页制作提升用户体验和客户转化

在当今竞争激烈的市场中&#xff0c;用户体验和客户转化率往往是决定企业成败的关键。简单而高效的网页制作&#xff0c;正是提升用户体验和客户转化的重要手段之一。 首先&#xff0c;简洁的网页设计能够有效减轻用户的认知负担。当用户打开一个层次分明、界面整洁的网站时&am…...

数据类型(使用与定义)

基本数据类型是CPU可以直接进行运算的类型&#xff0c;在算法直接被使用&#xff0c;主要包括&#xff1a; 整数类型&#xff1a;byte、short、int、long。 浮点数类型&#xff1a;float、double,用于表示小数。 字符类型&#xff1a;char&#xff0c;用于表示各种语言的字母…...

VMware:CentOS 7.* 连不上网络

1、修改网络适配 2、修改网卡配置参数 cd /etc/sysconfig/network-scripts/ vi ifcfg-e33# 修改 ONBOOTyes 3、重启网卡 service network restart 直接虚拟机中【ping 宿主机】&#xff0c;能PING通说明centOS和宿主机网络通了&#xff0c;只要宿主机有网&#xff0c;则 Ce…...

日志分析详解

文章目录 日志分析的概述日志分析的作用主要收集工具集中式日志系统主要特点采集日志分类ELK概述ELK收集日志的两种形式 搭建ELK平台安装部署docker添加镜像加速器安装部署Elasticsearch安装ElasticSearch-head&#xff08;可选&#xff09;运行容器页面无数据问题测试 安装Kib…...

【JavaWeb后端学习笔记】Maven项目管理

Maven 1、分模块设计2、Maven继承2.1 继承关系2.2 版本锁定 3、Maven聚合4、聚合与继承的关系 1、分模块设计 如果一个项目中含有大量的功能模块。可以考虑将这些功能分模块设计&#xff0c;逐一进行开发。例如将公共类可以定义在一个项目中&#xff0c;将通用工具类也放在一个…...

Docker--Docker Container(容器) 之 操作实例

容器的基本操作 容器的操作步骤其实很简单&#xff0c;根据拉取的镜像&#xff0c;进行启动&#xff0c;后可以查看容器&#xff0c;不用时停止容器&#xff0c;删除容器。 下面简单演示操作步骤 1.创建并运行容器 例如&#xff0c;创建一个名为"my-nginx"的交互…...

Android前端签到web迁移到rust的axum的过程-签到的重构

本次变更了以下内容: 为了使用之前ip2sta的ip到端点名的python,dic变量,将其存入redis hashset.使用地址/api/ip2dic 手动执行之.并且定义在/station/init,这个每天初始化redis的路径下.在rust axum的route中定义/sta/ip2dic,用来得到redis字典的内容,包含值和键.在前端的人名…...

Vue记事本应用实现教程

文章目录 1. 项目介绍2. 开发环境准备3. 设计应用界面4. 创建Vue实例和数据模型5. 实现记事本功能5.1 添加新记事项5.2 删除记事项5.3 清空所有记事 6. 添加样式7. 功能扩展&#xff1a;显示创建时间8. 功能扩展&#xff1a;记事项搜索9. 完整代码10. Vue知识点解析10.1 数据绑…...

Debian系统简介

目录 Debian系统介绍 Debian版本介绍 Debian软件源介绍 软件包管理工具dpkg dpkg核心指令详解 安装软件包 卸载软件包 查询软件包状态 验证软件包完整性 手动处理依赖关系 dpkg vs apt Debian系统介绍 Debian 和 Ubuntu 都是基于 Debian内核 的 Linux 发行版&#xff…...

在 Nginx Stream 层“改写”MQTT ngx_stream_mqtt_filter_module

1、为什么要修改 CONNECT 报文&#xff1f; 多租户隔离&#xff1a;自动为接入设备追加租户前缀&#xff0c;后端按 ClientID 拆分队列。零代码鉴权&#xff1a;将入站用户名替换为 OAuth Access-Token&#xff0c;后端 Broker 统一校验。灰度发布&#xff1a;根据 IP/地理位写…...

TRS收益互换:跨境资本流动的金融创新工具与系统化解决方案

一、TRS收益互换的本质与业务逻辑 &#xff08;一&#xff09;概念解析 TRS&#xff08;Total Return Swap&#xff09;收益互换是一种金融衍生工具&#xff0c;指交易双方约定在未来一定期限内&#xff0c;基于特定资产或指数的表现进行现金流交换的协议。其核心特征包括&am…...

【AI学习】三、AI算法中的向量

在人工智能&#xff08;AI&#xff09;算法中&#xff0c;向量&#xff08;Vector&#xff09;是一种将现实世界中的数据&#xff08;如图像、文本、音频等&#xff09;转化为计算机可处理的数值型特征表示的工具。它是连接人类认知&#xff08;如语义、视觉特征&#xff09;与…...

Pinocchio 库详解及其在足式机器人上的应用

Pinocchio 库详解及其在足式机器人上的应用 Pinocchio (Pinocchio is not only a nose) 是一个开源的 C 库&#xff0c;专门用于快速计算机器人模型的正向运动学、逆向运动学、雅可比矩阵、动力学和动力学导数。它主要关注效率和准确性&#xff0c;并提供了一个通用的框架&…...

scikit-learn机器学习

# 同时添加如下代码, 这样每次环境(kernel)启动的时候只要运行下方代码即可: # Also add the following code, # so that every time the environment (kernel) starts, # just run the following code: import sys sys.path.append(/home/aistudio/external-libraries)机…...

LangFlow技术架构分析

&#x1f527; LangFlow 的可视化技术栈 前端节点编辑器 底层框架&#xff1a;基于 &#xff08;一个现代化的 React 节点绘图库&#xff09; 功能&#xff1a; 拖拽式构建 LangGraph 状态机 实时连线定义节点依赖关系 可视化调试循环和分支逻辑 与 LangGraph 的深…...

在golang中如何将已安装的依赖降级处理,比如:将 go-ansible/v2@v2.2.0 更换为 go-ansible/@v1.1.7

在 Go 项目中降级 go-ansible 从 v2.2.0 到 v1.1.7 具体步骤&#xff1a; 第一步&#xff1a; 修改 go.mod 文件 // 原 v2 版本声明 require github.com/apenella/go-ansible/v2 v2.2.0 替换为&#xff1a; // 改为 v…...

Qt的学习(二)

1. 创建Hello Word 两种方式&#xff0c;实现helloworld&#xff1a; 1.通过图形化的方式&#xff0c;在界面上创建出一个控件&#xff0c;显示helloworld 2.通过纯代码的方式&#xff0c;通过编写代码&#xff0c;在界面上创建控件&#xff0c; 显示hello world&#xff1b; …...