stayingaheadwithtech

self_correct.py

Oct 29th, 2026 (edited)
123
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 3.08 KB | None | 0 0
  1. import os
  2. import subprocess
  3. import sys
  4. import tempfile
  5. from pathlib import Path
  6. from openai import OpenAI
  7.  
  8. client = OpenAI()
  9. MODEL = os.getenv("OPENAI_MODEL", "gpt-4.1-mini")
  10. MAX_ATTEMPTS = 3
  11.  
  12. TASK = """
  13. Write a Python function unique_items(items).
  14. Remove duplicates while preserving original order.
  15. Return only Python code. No markdown.
  16. """
  17.  
  18. TESTS = """
  19. def check(name, actual, expected):
  20.    assert actual == expected, (
  21.        f"{name}: expected {expected!r}, got {actual!r}"
  22.    )
  23.  
  24. check("order", unique_items([3, 1, 3, 2, 1]), [3, 1, 2])
  25. check("empty", unique_items([]), [])
  26. check("duplicates", unique_items([5, 5, 5]), [5])
  27. check("strings", unique_items(["b", "a", "b"]), ["b", "a"])
  28. check("unique", unique_items([1, 2, 3]), [1, 2, 3])
  29. """
  30.  
  31. def generate(prompt):
  32.     response = client.responses.create(
  33.         model=MODEL,
  34.         input=prompt,
  35.     )
  36.     code = response.output_text.strip()
  37.  
  38.     if code.startswith("```"):
  39.         code = "\n".join(code.splitlines()[1:-1])
  40.  
  41.     return code.strip()
  42.  
  43.  
  44. def validate(code):
  45.     with tempfile.TemporaryDirectory() as folder:
  46.         path = Path(folder) / "solution.py"
  47.         path.write_text(code + "\n\n" + TESTS)
  48.  
  49.         try:
  50.             result = subprocess.run(
  51.                 [sys.executable, "-I", str(path)],
  52.                 capture_output=True,
  53.                 text=True,
  54.                 timeout=5,
  55.             )
  56.             feedback = result.stderr or result.stdout
  57.             return result.returncode == 0, feedback
  58.  
  59.         except subprocess.TimeoutExpired:
  60.             return False, "Execution timed out"
  61.  
  62.  
  63. def self_correct(task):
  64.     prompt = task
  65.  
  66.     print("=" * 52)
  67.     print("           SELF-CORRECTING AI")
  68.     print("=" * 52)
  69.     print(f"Model: {MODEL}")
  70.     print("Task: Remove duplicates while preserving order")
  71.     print(f"Maximum attempts: {MAX_ATTEMPTS}")
  72.  
  73.     for attempt in range(1, MAX_ATTEMPTS + 1):
  74.         print(f"\n[ATTEMPT {attempt}/{MAX_ATTEMPTS}]")
  75.         print("[AI] Generating Python code...")
  76.  
  77.         code = generate(prompt)
  78.  
  79.         print("\n[GENERATED CODE]")
  80.         print(code)
  81.  
  82.         print("\n[TEST] Running 5 test cases...")
  83.         passed, feedback = validate(code)
  84.  
  85.         if passed:
  86.             print("[PASS] All 5 tests passed!")
  87.             print("\n[SUCCESS] Validated solution returned.")
  88.             return code
  89.  
  90.         print("[FAIL] Validation failed.")
  91.         print(feedback[-1200:].strip())
  92.  
  93.         if attempt < MAX_ATTEMPTS:
  94.             print("\n[REPAIR] Sending test failure to model...")
  95.  
  96.             prompt = f"""
  97. Original task:
  98. {task}
  99.  
  100. Your previous implementation:
  101. {code}
  102.  
  103. Actual test failure:
  104. {feedback[-3000:]}
  105.  
  106. Fix the implementation based on the error.
  107. Preserve all original requirements.
  108. Return only executable Python code.
  109. """
  110.  
  111.     raise RuntimeError(
  112.         f"Failed to produce a passing solution "
  113.         f"after {MAX_ATTEMPTS} attempts."
  114.     )
  115.  
  116.  
  117. if __name__ == "__main__":
  118.     try:
  119.         self_correct(TASK)
  120.     except Exception as error:
  121.         print(f"\n[ERROR] {error}")
  122.         sys.exit(1)
  123.  
Advertisement
Add Comment
Please, Sign In to add comment