Smart Systems for Home

Plain how-to guides for smart home, security and home Wi-Fi

AI Agent That Learns from Failed Fixes

· 6 min read · Home Tech

In this article
  1. What You'll Need
  2. Step-by-Step
  3. Common Mistakes
  4. Tips
  5. Troubleshooting
  6. Frequently Asked Questions

This guide walks you through building an AI agent that improves by analyzing its own failed repair attempts. Instead of repeating the same mistake, the agent logs what went wrong, extracts a lesson, and applies that lesson to future fixes. You'll end up with a self-improving loop that reduces repeated errors over time.

What You'll Need

  • Python 3.9+ installed on your machine
  • Basic familiarity with Python and command-line usage
  • An LLM API key (e.g., OpenAI, Anthropic, or a local model via Ollama)
  • A code editor (VS Code, PyCharm, or even a simple text editor)
  • Git (optional but recommended for version control)

Step-by-Step

  1. Define the agent's task scope. Decide what kind of fixes the agent will handle. For example, it could fix Python syntax errors, resolve configuration issues, or debug API integration problems. Keep the scope narrow to start—this makes the learning loop manageable.
  2. Set up the project structure. Create a folder with subdirectories: agent/ for the main logic, logs/ for failure records, memory/ for learned lessons, and tests/ for verifying fixes. This separation keeps the system organized.
  3. Implement the core fix loop. Write a function that takes a problem description and an initial attempt. The agent calls an LLM to generate a fix, applies it, and runs a validation test. If the test passes, the loop ends. If it fails, the agent records the failure and moves to the next iteration.
  4. Create a failure log schema. For each failed attempt, store: the problem ID, the attempted fix, the error message, the timestamp, and the context (like code snippet or config). Use JSON or SQLite for easy retrieval.
  5. Build the lesson extraction step. After a failure, prompt the LLM to analyze the error and suggest a general rule. For example: "When you see a KeyError in a dict, always check if the key exists before accessing it." Store these rules in a memory/lessons.json file.
  6. Inject lessons into future prompts. Before generating a new fix, retrieve relevant lessons from memory. You can use simple keyword matching or embeddings to find similar past failures. Include these lessons in the system prompt so the LLM avoids repeating the same mistake.
  7. Add a confidence scoring system. Track how often a lesson leads to a successful fix. If a lesson is applied and the fix succeeds, increase its score; if it fails, decrease it. Only include lessons with a score above a threshold in the prompt, so low-quality lessons are filtered out.
  8. Implement a retry limit. Set a maximum number of attempts per problem (e.g., 5). If the agent still hasn't fixed it, log the entire history and move on. This prevents infinite loops and wasted API calls.
  9. Write a validation harness. For each problem, have a clear pass/fail test. This could be running a unit test, checking for expected output, or verifying a config file parses. Without a reliable test, the agent can't know if a fix worked.
  10. Test with a small dataset. Collect 10-20 real problems with known fixes. Run the agent on them and observe how often it succeeds on the first try versus after learning. Iterate on the lesson extraction and injection until you see improvement.
  11. Add a feedback loop for human review. When the agent fails all attempts, allow a human to provide the correct fix. Store that as a high-confidence lesson, so the agent learns from human expertise as well.

Common Mistakes

  • Storing too many lessons. If you keep every failure as a lesson, the prompt becomes cluttered and the agent may get confused. Filter by relevance and confidence.
  • Ignoring the error message. The error message is the most valuable signal. Make sure it's included in the failure log and the lesson extraction prompt.
  • Not testing the fix properly. A fix that looks correct but doesn't pass validation is still a failure. Always run the test before declaring success.
  • Overfitting to old problems. If the agent only learns from a narrow set of past failures, it may not generalize. Include a variety of problems in your training set.
  • Forgetting to clean up. When you apply a fix, make sure to revert any temporary changes if validation fails. Otherwise, the environment may be left in a broken state.

Tips

  • Start with a simple domain. For example, fixing JSON formatting errors is easier than debugging complex concurrency issues.
  • Use embeddings for lesson retrieval. Instead of keyword matching, embed the error message and find similar past failures using cosine similarity. This often finds more relevant lessons.
  • Keep lessons concise. A lesson should be a single sentence, not a paragraph. This makes it easier to include in prompts and reduces token usage.
  • Log everything. Even successful fixes should be logged, because they can serve as positive examples. But only failures are used for learning.
  • Set a budget. LLM API costs can add up. Set a maximum number of attempts per problem and a daily limit on total calls.

Troubleshooting

  • The agent keeps repeating the same mistake. Check if the lesson extraction is working. Print the lessons that are injected into the prompt. If none are injected, your retrieval may be too strict or the lessons are not being stored correctly.
  • The agent never succeeds, even after learning. The problem might be too hard for the LLM, or your validation test is too strict. Try a simpler problem set, or relax the test criteria temporarily.
  • API errors or rate limits. Implement retry with exponential backoff. Also, consider using a local model (like Ollama) to avoid rate limits during development.
  • The memory file grows too large. Implement a pruning mechanism: remove lessons that haven't been used in a while or have a very low confidence score.
  • The agent takes too long per attempt. Set a timeout for each LLM call. If it times out, treat it as a failure and log it.

Frequently Asked Questions

Do I need a powerful GPU to run this?

No. You can use a cloud LLM API, which only requires an internet connection. If you want to run locally, a modest CPU can handle small models, but it will be slower.

Can I use this for non-coding fixes?

Yes, the same pattern works for any task where you have a clear pass/fail test, such as fixing configuration files, troubleshooting network issues, or even answering questions with known answers.

How many failures does the agent need to learn effectively?

It depends on the complexity. For simple tasks, 10-20 failures may be enough to see improvement. For complex tasks, you might need hundreds. The key is to have a diverse set of failures.

Will the agent ever become perfect?

No, but it will get better. The goal is to reduce repeated mistakes, not to eliminate all errors. You'll still need human oversight for novel problems.

How do I prevent the agent from learning incorrect lessons?

Use the confidence scoring system. Only include lessons that have been validated by successful fixes. Also, have a human review the lessons periodically.

Can I integrate this with my existing CI/CD pipeline?

Yes, you can call the agent as a step in your pipeline. When a build fails, the agent attempts a fix, and if it succeeds, it commits the change. This is a powerful way to automate routine fixes.