-
Notifications
You must be signed in to change notification settings - Fork 2.4k
Add RALPH-loop recipes to Copilot SDK cookbook #696
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
aaronpowell
merged 13 commits into
github:main
from
tonybaloney:cookbook/ralph-loop-recipe
Feb 11, 2026
+1,405
−2
Merged
Changes from 1 commit
Commits
Show all changes
13 commits
Select commit
Hold shift + click to select a range
d8fc473
Add RALPH-loop recipe to Copilot SDK cookbook
tonybaloney 7e39d55
Apply suggestions from code review
tonybaloney bb9f63a
Update README to remove RALPH-loop reference
tonybaloney ab82acc
Address review feedback: fix event handler leak, error handling, mode…
tonybaloney 952372c
Rewrite Ralph loop recipes: split into simple vs ideal versions
tonybaloney 92df16d
Remove git commands from Ralph loop recipes
tonybaloney 1074e34
Add SDK features to all Ralph loop recipes
tonybaloney 0e61670
Remove package-lock.json from tracking
tonybaloney 3eb7efc
Use gpt-5.1-codex-mini as default model in Ralph loop recipes
tonybaloney 3b4d601
Remove package-lock.json from tracking
tonybaloney 84486c2
Apply suggestions from code review
tonybaloney ff69b80
renaming
tonybaloney 717c012
PR feedback
tonybaloney File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Some comments aren't visible on the classic Files Changed page.
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,238 @@ | ||
| # RALPH-loop: Iterative Self-Referential AI Loops | ||
|
|
||
| Implement self-referential feedback loops where an AI agent iteratively improves work by reading its own previous output. | ||
|
|
||
| > **Runnable example:** [recipe/ralph-loop.cs](recipe/ralph-loop.cs) | ||
| > | ||
| > ```bash | ||
| > cd dotnet/recipe | ||
| > dotnet run ralph-loop.cs | ||
tonybaloney marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| > ``` | ||
|
|
||
| ## What is RALPH-loop? | ||
|
|
||
| RALPH-loop is a development methodology for iterative AI-powered task completion. Named after the Ralph Wiggum technique, it embodies the philosophy of persistent iteration: | ||
|
|
||
| - **One prompt, multiple iterations**: The same prompt is processed repeatedly | ||
| - **Self-referential feedback**: The AI reads its own previous work (file changes, git history) | ||
| - **Completion detection**: Loop exits when a completion promise is detected in output | ||
| - **Safety limits**: Always include a maximum iteration count to prevent infinite loops | ||
|
|
||
| ## Example Scenario | ||
|
|
||
| You need to iteratively improve code until all tests pass. Instead of asking Claude to "write perfect code," you use RALPH-loop to: | ||
|
|
||
| 1. Send the initial prompt with clear success criteria | ||
| 2. Claude writes code and tests | ||
| 3. Claude runs tests and sees failures | ||
| 4. Loop automatically re-sends the prompt | ||
| 5. Claude reads test output and previous code, fixes issues | ||
| 6. Repeat until all tests pass and completion promise is output | ||
|
|
||
| ## Basic Implementation | ||
|
|
||
| ```csharp | ||
| using GitHub.Copilot.SDK; | ||
|
|
||
| public class RalphLoop | ||
| { | ||
| private readonly CopilotClient _client; | ||
| private int _iteration = 0; | ||
| private readonly int _maxIterations; | ||
| private readonly string _completionPromise; | ||
| private string? _lastResponse; | ||
|
|
||
| public RalphLoop(int maxIterations = 10, string completionPromise = "COMPLETE") | ||
| { | ||
| _client = new CopilotClient(); | ||
| _maxIterations = maxIterations; | ||
| _completionPromise = completionPromise; | ||
| } | ||
|
|
||
| public async Task<string> RunAsync(string prompt) | ||
| { | ||
| await _client.StartAsync(); | ||
| var session = await _client.CreateSessionAsync(new SessionConfig { Model = "gpt-5" }); | ||
|
|
||
tonybaloney marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| try | ||
| { | ||
| while (_iteration < _maxIterations) | ||
| { | ||
| _iteration++; | ||
| Console.WriteLine($"\n--- Iteration {_iteration} ---"); | ||
|
|
||
| var done = new TaskCompletionSource<string>(); | ||
| session.On(evt => | ||
| { | ||
| if (evt is AssistantMessageEvent msg) | ||
| { | ||
| _lastResponse = msg.Data.Content; | ||
| done.SetResult(msg.Data.Content); | ||
| } | ||
| }); | ||
|
|
||
| // Send prompt (on first iteration) or continuation | ||
| var messagePrompt = _iteration == 1 | ||
| ? prompt | ||
| : $"{prompt}\n\nPrevious attempt:\n{_lastResponse}\n\nContinue iterating..."; | ||
|
|
||
| await session.SendAsync(new MessageOptions { Prompt = messagePrompt }); | ||
| var response = await done.Task; | ||
|
|
||
| // Check for completion promise | ||
| if (response.Contains(_completionPromise)) | ||
| { | ||
| Console.WriteLine($"✓ Completion promise detected: {_completionPromise}"); | ||
| return response; | ||
| } | ||
|
|
||
| Console.WriteLine($"Iteration {_iteration} complete. Continuing..."); | ||
| } | ||
|
|
||
| throw new InvalidOperationException( | ||
| $"Max iterations ({_maxIterations}) reached without completion promise"); | ||
| } | ||
| finally | ||
| { | ||
| await session.DisposeAsync(); | ||
| await _client.StopAsync(); | ||
| } | ||
| } | ||
| } | ||
|
|
||
| // Usage | ||
| var loop = new RalphLoop(maxIterations: 5, completionPromise: "DONE"); | ||
tonybaloney marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| var result = await loop.RunAsync("Your task here"); | ||
| Console.WriteLine(result); | ||
| ``` | ||
|
|
||
| ## With File Persistence | ||
|
|
||
| For tasks involving code generation, persist state to files so the AI can see changes: | ||
|
|
||
| ```csharp | ||
| public class PersistentRalphLoop | ||
| { | ||
| private readonly string _workDir; | ||
| private readonly CopilotClient _client; | ||
| private int _iteration = 0; | ||
|
|
||
| public PersistentRalphLoop(string workDir, int maxIterations = 10) | ||
| { | ||
| _workDir = workDir; | ||
| Directory.CreateDirectory(_workDir); | ||
| _client = new CopilotClient(); | ||
| } | ||
|
|
||
| public async Task<string> RunAsync(string prompt) | ||
| { | ||
| await _client.StartAsync(); | ||
| var session = await _client.CreateSessionAsync(new SessionConfig { Model = "gpt-5" }); | ||
|
|
||
| try | ||
| { | ||
| // Store initial prompt | ||
| var promptFile = Path.Combine(_workDir, "prompt.md"); | ||
| await File.WriteAllTextAsync(promptFile, prompt); | ||
|
|
||
| while (_iteration < 10) | ||
| { | ||
| _iteration++; | ||
tonybaloney marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| Console.WriteLine($"\n--- Iteration {_iteration} ---"); | ||
|
|
||
| // Build context including previous work | ||
| var contextBuilder = new StringBuilder(prompt); | ||
| var previousOutput = Path.Combine(_workDir, $"output-{_iteration - 1}.txt"); | ||
| if (File.Exists(previousOutput)) | ||
| { | ||
| contextBuilder.AppendLine($"\nPrevious iteration output:\n{await File.ReadAllTextAsync(previousOutput)}"); | ||
| } | ||
|
|
||
| var done = new TaskCompletionSource<string>(); | ||
| string response = ""; | ||
| session.On(evt => | ||
| { | ||
| if (evt is AssistantMessageEvent msg) | ||
| { | ||
| response = msg.Data.Content; | ||
| done.SetResult(msg.Data.Content); | ||
tonybaloney marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| } | ||
| }); | ||
|
|
||
| await session.SendAsync(new MessageOptions { Prompt = contextBuilder.ToString() }); | ||
| await done.Task; | ||
|
|
||
| // Persist output | ||
| await File.WriteAllTextAsync( | ||
| Path.Combine(_workDir, $"output-{_iteration}.txt"), | ||
| response); | ||
|
|
||
| if (response.Contains("COMPLETE")) | ||
| { | ||
| return response; | ||
| } | ||
| } | ||
|
|
||
| throw new InvalidOperationException("Max iterations reached"); | ||
| } | ||
| finally | ||
| { | ||
| await session.DisposeAsync(); | ||
| await _client.StopAsync(); | ||
| } | ||
| } | ||
| } | ||
| ``` | ||
|
|
||
| ## Best Practices | ||
|
|
||
| 1. **Write clear completion criteria**: Include exactly what "done" looks like | ||
| 2. **Use output markers**: Include `<promise>COMPLETE</promise>` or similar in completion condition | ||
| 3. **Always set max iterations**: Prevents infinite loops on impossible tasks | ||
| 4. **Persist state**: Save files so AI can see what changed between iterations | ||
| 5. **Include context**: Feed previous iteration output back as context | ||
| 6. **Monitor progress**: Log each iteration to track what's happening | ||
|
|
||
| ## Example: Iterative Code Generation | ||
|
|
||
| ```csharp | ||
| var prompt = @"Write a function that: | ||
| 1. Parses CSV data | ||
| 2. Validates required fields | ||
| 3. Returns parsed records or error | ||
| 4. Has unit tests | ||
| 5. Output <promise>COMPLETE</promise> when done"; | ||
|
|
||
| var loop = new RalphLoop(maxIterations: 10, completionPromise: "COMPLETE"); | ||
| var result = await loop.RunAsync(prompt); | ||
| ``` | ||
|
|
||
| ## Handling Failures | ||
|
|
||
| ```csharp | ||
| try | ||
| { | ||
| var result = await loop.RunAsync(prompt); | ||
| Console.WriteLine("Task completed successfully!"); | ||
| } | ||
| catch (InvalidOperationException ex) when (ex.Message.Contains("Max iterations")) | ||
| { | ||
| Console.WriteLine("Task did not complete within iteration limit."); | ||
| Console.WriteLine($"Last response: {loop.LastResponse}"); | ||
| // Document what was attempted and suggest alternatives | ||
| } | ||
| ``` | ||
|
|
||
| ## When to Use RALPH-loop | ||
|
|
||
| **Good for:** | ||
| - Code generation with automatic verification (tests, linters) | ||
| - Tasks with clear success criteria | ||
| - Iterative refinement where each attempt learns from previous failures | ||
| - Unattended long-running improvements | ||
|
|
||
| **Not good for:** | ||
| - Tasks requiring human judgment or design input | ||
| - One-shot operations | ||
| - Tasks with vague success criteria | ||
| - Real-time interactive debugging | ||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.