Self-Improving Memory for AI Agents: Turning Failures into Reusable Experience

    Self-improving memory (SIM) is an engineering pattern that lets an AI agent analyze its failures, store conclusions in an external memory store, and retrieve those lessons for similar future tasks. This article explains how SIM differs from RAG, proposes a JSON experience schema, discusses retrieval and injection limits, and covers cross-model reuse, a runnable code skeleton, pre-launch checks, and risks such as memory contamination.

    1. The Bottom Line

    SIM is an engineering pattern, not a new model capability. After an agent fails, the model analyzes the cause, and the conclusion is stored in an external memory store. The next time a similar task appears, the system retrieves those experiences and places them in the prompt. The model parameters do not change; what changes is the context the model receives each time. Understanding this point is necessary to judge the effect boundaries and risks of SIM.

    2. SIM vs. RAG

    Retrieval-augmented generation (RAG) gives external documents to the model for reference, and the knowledge source is usually human-curated material. SIM’s knowledge source is the agent’s own run results, including failed task descriptions, execution traces, and error logs. Both require retrieval and injection, but SIM adds a “reflection” step that turns raw logs into reusable experience.

    Therefore, the effectiveness of SIM depends on the reflection step. If the model misjudges the cause of an error, the wrong experience will be stored and will continue to affect later tasks. This is the root of the “memory contamination” problem, which is discussed in detail later.

    3. Data Format for an Experience

    It is recommended to constrain experiences to a fixed JSON structure for validation and retrieval. A usable template is shown below:

    1. {
    2. "experience": "When handling dates, specify the time zone explicitly; otherwise, cross-region services may show time offsets.",
    3. "applicable_scenario": "Code tasks involving date parsing or cross-time-zone calls",
    4. "trigger_keywords": ["datetime", "timezone"],
    5. "confidence": 0.8,
    6. "source_task_id": "task-20261124-017",
    7. "created_at": "2026-11-24T13:46:19+00:00",
    8. "last_used_at": null
    9. }

    Field constraints:

    • experience must be no more than 200 characters and must contain only one verifiable conclusion, not a process description.
    • confidence is a value between 0 and 1. Experiences below the threshold enter a manual review queue and do not participate directly in retrieval.
    • Before writing, remove secrets, tokens, phone numbers, and other sensitive information from logs.

    Failure example: if the model only outputs “the code has a problem and needs modification,” the content has no actionable information and should be discarded directly.

    4. Retrieval and Injection Strategy

    More experience is not always better. Injecting too much content can fill the context and may lead the model astray with irrelevant experience. In practice, the following approaches can be used:

    1. Retrieve the top 3 results and keep only experiences whose relevance exceeds a threshold.
    2. Keep the total amount of injected experience to around 1000 tokens.
    3. When two experiences have opposite conclusions, keep the newer one with higher confidence, and record the conflict for manual review.
    4. Downweight experiences that have not been retrieved for a long time. For example, halve the weight after 90 days without use. Archive experiences when the weight falls below a configured value.

    5. Cross-Model Reuse: What Works and What Does Not

    Experiences are stored as natural language or JSON and do not include model weights, activations, or system prompts. Therefore, the same experience library can be read by different models, provided that the models can understand the injected text. When switching models, teams do not need to accumulate experience from scratch.

    However, this does not mean the experiences will take effect automatically. Different models understand the same prompt to different degrees, and some models may ignore injected content. After switching models, use a fixed set of test tasks to compare first-attempt success rates and confirm that the experience is actually helpful.

    6. Code Example

    The following code is a complete skeleton that can run locally. The LLM call is represented by a function passed in as a parameter; replace it with your own model interface when using it. Retrieval uses keyword matching; in production, replace it with a vector database.

    1. import json
    2. import re
    3. import subprocess
    4. import tempfile
    5. from dataclasses import dataclass, field
    6. from typing import Callable, List, Optional
    7. CONFIDENCE_THRESHOLD = 0.7
    8. TOP_K = 3
    9. @dataclass
    10. class Experience:
    11. experience: str
    12. applicable_scenario: str
    13. trigger_keywords: List[str] = field(default_factory=list)
    14. confidence: float = 0.0
    15. def redact(text: str) -> str:
    16. # Example rules: redact suspected keys and 11-digit phone numbers.
    17. # Add actual rules according to company security requirements.
    18. text = re.sub(r"sk-[A-Za-z0-9]+", "[REDACTED]", text)
    19. return re.sub(r"\d{11}", "[REDACTED]", text)
    20. class SelfImprovementMemory:
    21. def __init__(self, llm: Callable[[str], str]):
    22. self.llm = llm
    23. self.store: List[Experience] = [] # Replace with a vector database in production.
    24. self.review_queue: List[Experience] = [] # Experiences awaiting manual review.
    25. def reflect(self, task_desc: str, error_log: str) -> Optional[Experience]:
    26. prompt = (
    27. f"Task description: {task_desc}\nError log: {redact(error_log)}\n"
    28. "Analyze the root cause and output exactly one experience item as JSON: "
    29. '{"experience": "...", "applicable_scenario": "...", '
    30. '"trigger_keywords": [], "confidence": 0.0}'
    31. )
    32. try:
    33. data = json.loads(self.llm(prompt))
    34. exp = Experience(
    35. experience=str(data["experience"]).strip(),
    36. applicable_scenario=str(data["applicable_scenario"]),
    37. trigger_keywords=[str(k) for k in data.get("trigger_keywords", [])],
    38. confidence=float(data.get("confidence", 0.0)),
    39. )
    40. except (json.JSONDecodeError, KeyError, TypeError, ValueError):
    41. return None # Invalid format; discard directly.
    42. if not exp.experience:
    43. return None
    44. if exp.confidence >= CONFIDENCE_THRESHOLD:
    45. self.store.append(exp)
    46. else:
    47. self.review_queue.append(exp)
    48. return exp
    49. def retrieve(self, task: str) -> List[Experience]:
    50. task_lower = task.lower()
    51. scored = []
    52. for exp in self.store:
    53. hits = sum(1 for kw in exp.trigger_keywords if kw.lower() in task_lower)
    54. if hits:
    55. scored.append((hits, exp))
    56. scored.sort(key=lambda item: item[0], reverse=True)
    57. return [exp for _, exp in scored[:TOP_K]]
    58. def run_in_sandbox(code: str, timeout: int = 10) -> None:
    59. # For demonstration only. subprocess is not a secure sandbox.
    60. # Run model-generated code in a container or isolated environment.
    61. with tempfile.NamedTemporaryFile("w", suffix=".py", delete=False, encoding="utf-8") as f:
    62. f.write(code)
    63. path = f.name
    64. result = subprocess.run(["python", path], capture_output=True, text=True, timeout=timeout)
    65. if result.returncode != 0:
    66. raise RuntimeError(result.stderr.strip() or "Unknown error")
    67. def execute_task(task: str, memory: SelfImprovementMemory, llm: Callable[[str], str]) -> None:
    68. past = memory.retrieve(task)
    69. hints = "\n".join(f"- {exp.experience}" for exp in past) or "None"
    70. code = llm(f"Historical experience:\n{hints}\nCurrent task: {task}\nOutput Python code only.")
    71. try:
    72. run_in_sandbox(code)
    73. except Exception as e:
    74. memory.reflect(task, str(e))

    7. Pre-Launch Checklist

    • Sample-review every newly stored experience and record the human pass rate.
    • Use a fixed set of test tasks and compare first-attempt success rate, error recurrence rate, and retrieval accuracy after every change.
    • Keep version history for the experience library. If an experience is found to be wrong, roll back to a previous version.
    • Configure access permissions for logs and the experience library according to the principle of least privilege, so unrelated services cannot read them.
    • Run the sandbox in a container or on an isolated host, with network access and filesystem scope restricted.

    8. Risks and Boundaries

    Memory contamination is the issue that requires the most attention. Once an incorrect experience generated by a hallucinating model is stored, it will continue to affect later tasks. Confidence thresholds, manual review, and periodic decay are the main controls, but none of them can completely eliminate the risk.

    The memory library will also keep growing. Experiences that are not used for a long time need to be downweighted or archived. Outdated technical details, such as deprecated APIs, should be cleaned up as soon as possible.

    SIM cannot replace testing and code review. It reduces the number of times an agent repeats the same type of error; it does not guarantee that the result of a new task will be correct.

    9. Conclusion

    The value of SIM lies in turning an agent’s failure records into retrievable experience. In implementation, the experience format, admission review, and injection strategy usually have a greater impact on results than the model itself. It is advisable to first run a complete closed loop on a small set of tasks, use test data to determine whether the experience is useful, and then decide whether to expand its use.