为什么你的AI Agent总是隔天就忘?——从Prompt到Loop Engineering的跃迁

你是否遇到过:精心调教了一下午的Agent,第二天打开发现它完全不记得昨天说过的话?别急着怪模型——问题不在模型,在你的架构。

  1. 前提条件

在开始之前,确保你具备以下环境: Python ≥ 3.10

pip install openai(本文使用 openai≥1.0.0)

OpenAI API Key:[1]https://platform.openai.com/api-keys[2]

操作系统:macOS / Linux / Windows WSL 均可

本文的终极目标:你复制代码就能跑,跑完就能看到 Loop Agent 的效果。

  1. 痛点:你的Agent为什么隔天就忘?

凌晨两点,你终于把那个多步骤工作流调通了。Agent 按照你精心设计的 Prompt,一步步完成了数据抓取、清洗、分析、出图。你心满意足地关了电脑。 第二天早上,你满怀期待地打开对话——Agent 一脸茫然地看着你,仿佛昨晚的一切从未发生过。 你检查日志。没有报错。没有异常。Agent 重新生成了所有内容,只是——它「忘」了昨天在哪里停下的。 这不是段子。这是每个深度使用 Agent 的开发者都经历过的噩梦。问题的根源不是什么「模型不够聪明」,而是一个更根本的事实:你写的 Agent 从来就不是被设计成活过一夜的。

  1. 四阶段演化:Prompt → Context → Harness → Loop

要理解这个问题,让我们用一个简单的演化框架来看这条路:

阶段你在做的事致命缺陷
Prompt Engineering把任务描述、示例、格式写进 Prompt,期望一次性搞定任何意外输入都能让输出崩溃
Context Engineering把历史对话、中间结果塞进上下文窗口Token 成本线性增长,最终被窗口上限撑死
Harness Engineering引入工具调用、结构化输出、错误捕获框架搭好了,但 Agent 还是「一次性」的
Loop Engineering构建闭环系统:状态 + 记忆 + 反馈 + 重试 + 持久化真正的工程化,Agent 开始「活」下去

Loop Engineering 不是对 Prompt Engineering 的否定,而是对它的超越。Prompt 仍然重要——但它只是发动机,你不能把发动机当车开。

  1. 最小可运行 Loop Agent(完整50行代码)

下面是完整的、可复制粘贴、可直接运行的 Loop Agent。你可以先跑起来,再逐行理解。

import json, os, time
from pathlib import Path
from datetime import datetime
from openai import OpenAI

client = OpenAI()  # 自动读取环境变量 OPENAI_API_KEY

STATE_FILE = Path("./agent_state.json")
MEMORY_FILE = Path("./agent_memory.json")
MAX_RETRIES = 3


defload_memory() -> dict:
    if MEMORY_FILE.exists():
        return json.loads(MEMORY_FILE.read_text())
    return {"facts": {}, "errors": []}


defsave_memory(mem: dict):
    MEMORY_FILE.write_text(json.dumps(mem, indent=2, ensure_ascii=False))


defload_state() -> dict:
    if STATE_FILE.exists():
        return json.loads(STATE_FILE.read_text())
    return {"state": "idle", "step": 0}


defsave_state(state: str, step: int):
    STATE_FILE.write_text(json.dumps({
        "state": state, "step": step,
        "updated_at": datetime.now().isoformat()
    }, indent=2, ensure_ascii=False))


defexecute(task: str, memory: dict, error_ctx: str = "") -> str:
    system = f"你是任务执行Agent。已知事实:{json.dumps(memory.get('facts', {}), ensure_ascii=False)}"
    if error_ctx:
        system += f"\n上次错误:{error_ctx}\n请修正。"
    resp = client.chat.completions.create(
        model="gpt-4o-mini",
        messages=[{"role": "system", "content": system},
                  {"role": "user", "content": task}]
    )
    return resp.choices[0].message.content


defcheck(output: str, keywords: list[str]) -> tuple[bool, str]:
    missing = [kw for kw in keywords if kw notin output]
    if missing:
        returnFalse, f"缺失:{missing}"
    iflen(output) < 20:
        returnFalse, "输出过短"
    returnTrue, ""


defrun(task: str, keywords: list[str]):
    memory = load_memory()
    save_state("running", 0)

    for i inrange(1, MAX_RETRIES + 1):
        error = memory["errors"][-1]["reason"] if memory["errors"] else""
        output = execute(task, memory, error)
        ok, reason = check(output, keywords)

        if ok:
            save_state("done", i)
            memory["facts"][task[:30]] = output[:100]
            save_memory(memory)
            returnf"✅ 第{i}次成功:\n{output}"
        else:
            save_state("retrying", i)
            memory["errors"].append(
                {"task": task, "reason": reason, "attempt": i}
            )
            save_memory(memory)
            print(f" 第{i}次未通过:{reason}")
            time.sleep(1)

    save_state("failed", MAX_RETRIES)
    returnf"❌ {MAX_RETRIES}次重试均失败"


if __name__ == "__main__":
    result = run(
        task="列出3个Python Web框架及其特点",
        keywords=["Flask", "Django", "FastAPI"]
    )
    print(result)

以上代码,复制到一个新文件

loop_agent.py

即可运行。

  1. 验证方法

打开终端,按以下步骤验证:

# 1. 安装依赖
pip install openai

# 2. 设置 API Key
export OPENAI_API_KEY="sk-your-actual-key-here"

# 3. 第一次运行
python loop_agent.py

预期输出:

✅ 第1次成功:
目前主流的 3 个 Python Web 框架及其特点如下:

1. **Flask**:轻量级微框架,灵活自由,适合中小型项目和 API 开发...
2. **Django**:全栈框架,"电池已满",内置 ORM、Admin、认证...
3. **FastAPI**:现代异步框架,自动生成 OpenAPI 文档,高性能...

接下来验证持久化——关闭终端,重新打开,再执行:

# 4. 查看状态文件
cat agent_state.json

预期输出:

{
  "state": "done",
  "step": 1,
  "updated_at": "2026-07-01T12:00:00.000000"
}
# 5. 查看记忆文件
cat agent_memory.json

预期输出:

{
  "facts": {
    "列出3个Python Web框架及其特点": "目前主流的 3 个 Python Web 框架及其特点如下:\n\n1. **Flask**:轻量级微框架..."
  },
  "errors": []
}
# 6. 再次运行——Agent 自动加载记忆
python loop_agent.py

Agent 会读取

agent_memory.json

中的

facts

,将其作为已知事实传递给执行器。这就是「隔天不忘」的机制。

  1. 六大组件在代码中的对应关系

原文章提到的六大组件,全部落在这 50 行代码中:

组件代码位置说明
Memory Store/ (第14-20行)用 持久化记忆
State Machine/ (第23-31行)用 持久化状态
Executor(第34-46行)调用 OpenAI API 执行任务
Checker(第49-55行)验证输出是否包含指定关键词
Task Scheduler(第58-72行)重试循环 + 状态流转
Guardrails(第10行)最大重试次数限制
  1. 常见错误及解决

错误 1:

ModuleNotFoundError: No module named 'openai'
pip install openai

如果已经安装但版本不对,升级到最新:

pip install --upgrade openai

错误 2:

openai.AuthenticationError: Error code: 401

你没有设置 API Key,或者 Key 无效。

export OPENAI_API_KEY="sk-your-actual-key"

也可以在代码中直接传入:

client = OpenAI(api_key="sk-your-actual-key")

错误 3:Agent 输出内容但不包含 Flask/Django/FastAPI 这是正常现象! LLM 有时候不会完全按要求输出。这正是 Loop Agent 的价值所在—— Checker 会检测到输出缺失关键词,拒绝通过,Agent 自动重试。你会看到终端打印:

 第1次未通过:缺失:['Flask', 'Django', 'FastAPI']
 第2次未通过:缺失:['Django']
✅ 第3次成功:
...

如果 3 次全部失败,终端的最后一行会是:

❌ 3次重试均失败

此时检查

agent_memory.json

errors

数组记录了每一次失败的原因,便于调试。 错误 4:API 调用超时或限流 默认使用

gpt-4o-mini

,成本极低(约 $0.00015/次)。如果遇到限流,可以: 增大

time.sleep(1)

中的等待时间

检查 OpenAI Dashboard 的使用额度

  1. 下一步:从 50 行出发

现在你手上有一个完整可运行的 Loop Agent。它用了最朴素的方式(JSON 文件)实现持久化,但这正是你能亲手触碰每个组件的地方。 按你的需求扩展: 换 ChromaDB 替代 JSON 文件做向量记忆存储

接 Celery 做真正的异步任务队列

接飞书/钉钉 Webhook 做任务完成通知

加结构化日志 + Trace ID 做可观测性

Loop Engineering 不是一个可以一键安装的包,它是一种架构思维的转变。从这 50 行开始,你已经站在了第 4 阶段的门槛上。 下一篇预告:你的 Agent 到底需要多少记忆?——Memory Store 实战选型指南 欢迎在评论区留言分享你的 Agent 失忆故事,或提交你的 loop_agent.py 运行截图。 关于作者:魏无记,AI 和数智化实践者。专注 Agent 工程化与 Loop Engineering 研究以及数智化转型。公众号持续更新 Agent 工程化实战系列和数智化转型相关知识实践——每篇都是保姆级教程照做就行。 引用链接 [1]undefined: https://platform.openai.com/api-keys [2]https://platform.openai.com/api-keys

posted @ 2026-08-05 11:41  魏无记  阅读(1)  评论(0)    收藏  举报