Run a self-refinement loop with a stopping rule

Why it matters Refine loops in agents and reasoning pipelines need a budget, a quality bar and a plateau check, or they burn tokens and can degrade answers.

Self-refinement asks a model to critique and rewrite its own answer repeatedly. Without a stopping rule it wastes calls or makes the answer worse.

Write refine_loop(initial, refine_fn, score_fn, threshold, max_iters, min_gain). Start with draft = initial, s = score_fn(draft), history = [s]. Repeat at most max_iters times: if s >= threshold, stop. Otherwise new = refine_fn(draft), ns = score_fn(new), append ns to history; if ns - s < min_gain, stop after this step; else continue from new. Track the best draft seen (highest score, the earliest one on ties). Return (best_draft, best_score, history).

Signaturedef refine_loop(initial, refine_fn, score_fn, threshold, max_iters, min_gain)

Example

initial "a", refine_fn appends "+", score_fn = len, threshold 3, max_iters 5, min_gain 0.5 gives ("a++", 3, [1, 2, 3]).

Understand the idea

A self-refine loop is an editor reading their own draft: write, critique, rewrite, repeat. Without rules it can go on forever, and rewrites can get worse, so you need to know when to stop and which version to keep.

Example: scores by version are v0 0.4, v1 0.7, v2 0.8, v3 0.6. Threshold 0.95, min_gain 0.01. v0 to v1 gains 0.3, keep going. v1 to v2 gains 0.1, keep going. v2 to v3 drops by 0.2, below min_gain, so stop. The best draft is v2 at 0.8, not the last one.

Rule: stop when score >= threshold, when new_score - old_score < min_gain, or when the iteration budget runs out; always return the highest-scoring draft seen.

The Self-Refine paper showed that feedback-and-rewrite loops can improve outputs, and agent frameworks use the same pattern with a verifier or a test suite as score_fn.

solution.pyPython idle
Ctrl/Cmd + Enter runs sample tests

Run checks the first 2 tests. Submit checks the hidden tests with Pro.

  • Sample 1: examplerefine_loop('a', lambda d: d + '+', len, 3, 5, 0.5)
  • Sample 2: gets worserefine_loop('v0', step, SCORES.get, 0.95, 5, 0.01)