inspect_evals_utils.code¶
Helpers for extracting generated code and JSON from Markdown responses.
extract_code_blocks
¶
extract_code_blocks(
completion: str, language: str = "python"
) -> list[str]
Return the language-labelled code blocks, or else the unlabelled ones.
Blocks are in the order they appear. Unlabelled blocks are returned only when no block carries one of the language's labels. Labels are matched case-insensitively and both LF and CRLF line endings are accepted. Fences labelled for another language are not treated as unlabelled code, and empty blocks are skipped. A labelled fence that is never closed runs to the end of the text.
extract_code_block
¶
extract_code_block(
completion: str,
language: str = "python",
accept: Callable[[str], bool] | None = None,
) -> str | None
Return the first block from extract_code_blocks, or None if there is none.
Language-labelled blocks are preferred over unlabelled blocks even when an unlabelled block appears earlier in the response.
When accept is given, the first block it accepts is returned instead. If
it accepts none, the first block is returned as without it. Pass
defines(name) to take the block that implements the function the task
asks for, rather than a usage example or a draft that does not parse.
strip_json_fence
¶
strip_json_fence(text: str) -> str
Return the JSON inside one code fence wrapping the whole text, else the text unchanged.
The fence may be labelled json or unlabelled. Use it before parsing a
reply that should be bare JSON, such as one requested with a
response_schema: some providers accept the schema without enforcing it and
return the JSON in a fence. Text with prose around the fence, or more than
one fence, is returned unchanged, so it still fails validation.
defines
¶
defines(name: str) -> Callable[[str], bool]
Accept Python code that parses and defines name at the top level.