FencedCodeExtractor

Helpers & Utilities · AiDotNet.Evolution.Programs

Extracts fenced code blocks from a model response and picks the best full rewrite.

For Beginners

Chat models normally return code wrapped in triple backticks. This class pulls the code back out. It copes with the awkward cases: a model that shows a short example before the real answer, a model that forgot the language name, and a model that nested one code block inside another. It also tells you how it found the code, so you can retry when the model clearly ignored the requested format.

How It Works

The reference OpenEvolve implementation builds a regular expression by concatenating the language name into <language>\n(.*?), then falls back to (.*?) and finally to the whole response. Three consequences follow: the first fence always wins even when it is a short illustrative snippet, a nested fence terminates its parent early, and a caller cannot tell a labelled extraction from a raw-prose fallback. This scanner walks the response line by line with CommonMark fence rules — an opening run of three or more backticks or tildes is closed only by a run of at least the same length of the same character — so nested fences survive, and it selects the longest block on the strongest available rung rather than the first block on any rung.

Selection order is: a fence whose label resolves to the requested language, then an unlabelled fence, then any other labelled fence, then the raw response. Within a rung the longest block wins and ties go to the earliest, so the choice is reproducible. Content keeps its leading indentation, which matters for Python, and only leading and trailing blank lines are removed.

Methods

Method Summary
FencedCodeExtractionResult Extract(string response, ProgramLanguage language, bool allowRawFallback) Extracts the best full rewrite from a model response.
IReadOnlyList<FencedCodeBlock> ExtractBlocks(string response) Returns every fenced block in a response without selecting one.