Muscle Memory 是一个为AI代理设计的行为缓存工具,核心思想是记录AI代理在解决任务时的工具调用模式(trajectory),在再次遇到相同任务时,直接重放这些已学习的轨迹,避免每次都调用大型语言模型(LLM),从而提高速度、降低成本并减少输出结果的变异性。如果遇到边缘情况,则会回退到原始的agent模式。Muscle Memory不是另一个agent框架,而是可以让你将现有的agent集成进去,重点在于缓存验证,通过定义Check来判断在什么情况下可以安全地重用缓存的工具调用序列。

Muscle Memory 的核心在于让大语言模型(LLMs)从重复性任务中解脱出来,提升任务处理速度,减少结果差异,降低token消耗——许多场景本可以通过脚本完成,无需依赖语言模型实时处理。

Muscle Memory 并非独立的智能体框架,而是可与现有智能体集成的插件,其运行流程如下:

1、环境识别:通过“检查”(Checks)机制判断当前环境是已知(缓存命中)还是未知(缓存未命中)。

2、任务执行

缓存命中时,直接调用已存储的行为轨迹完成任务。

缓存未命中时,将任务传递给智能体进行处理。

3、数据收集:记录新的工具调用事件,作为新的行为轨迹存入缓存。

Muscle Memory关键模块:缓存验证(Checks)

缓存验证能确保智能体安全复用工具的核心是缓存验证,需针对每个工具回答:“环境中哪些特征可用于判断执行该操作是否安全?”通过定义Checks实现这一逻辑,每个Check包含:

捕获(capture):从当前环境提取相关特征的回调函数。

比较(compare):判断当前环境与缓存环境是否匹配的回调函数(返回布尔值或相似度分数)。

Checks可作为预处理(调用工具前验证)或后处理(调用工具后验证)附加到工具上。以下是一个简单示例,通过时间戳验证“hello”工具的缓存有效性:

from dataclasses import dataclass
from muscle_mem import Check, Engine
import time

engine = Engine()

@dataclass
class T:
    name: str
    time: float

def capture(name: str) -> T:
    now = time.time()
    return T(name=name, time=now)

def compare(current: T, candidate: T) -> bool:
    diff = current.time - candidate.time
    return diff <= 1  # 缓存有效期为1秒

@engine.tool(pre_check=Check(capture, compare))
def hello(name: str):
    time.sleep(0.1)
    print(f"hello {name}")

def agent(name: str):
    for i in range(9):
        hello(name + " + " + str(i))

engine.set_agent(agent)

# 首次运行:缓存未命中
cache_hit = engine("erik")
assert not cache_hit

# 再次运行:缓存命中
cache_hit = engine("erik")
assert cache_hit

# 等待3秒后运行:缓存过期,未命中
time.sleep(3)
cache_hit = engine("erik")
assert not cache_hit

Muscle Memory 使用方式

安装

通过pip安装:

pip install muscle-mem

核心组件

1、引擎(Engine)

包裹智能体,作为任务执行的核心组件。

管理行为轨迹缓存,决定何时调用智能体。

from muscle_mem import Engine
engine = Engine()
engine.set_agent(your_agent)  # 绑定自定义智能体
engine("do some task")  # 调用任务,支持缓存机制

2、工具(Tool)

通过@engine.tool装饰器标记工具,记录调用参数。

@engine.tool()
def hello(name: str):
    print(f"hello {name}!")
hello("world")  # 调用会被记录到缓存