Verify code against real source
CompletionExercise: Grounding code excerpts via whole-identifier membership
In the LlamaIndex + Qdrant project, emitted code snippets are verified against the real source code to catch hallucinated APIs. The key insight: substring checks (e.g., "index" in source_text) are too permissive because they match parts of longer real identifiers (index_documents). Instead, the check must use whole-token membership: collect all identifiers from the code block (using regex), then compute what fraction belong to the set of identifiers appearing in the real source.
Your task: implement the function verify_code_excerpt(source_text: str, code_markdown: str) -> list[str] that:
- Extracts exactly one fenced code block from
code_markdown(if not exactly one, return a violation). - Extracts all identifiers (tokens matching
[A-Za-z_][A-Za-z0-9_]{2,}, case-sensitive) from that block, excluding a set of stopwords. - Computes the set of source identifiers: all identifiers appearing in
source_text. - Calculates the ratio of grounded identifiers (those found in the source set) to total identifiers.
- If ratio < 0.667, adds a violation with details about unknown identifiers.
Also, in a comment at the end of the function, explain why a substring check (ident in source_text) would incorrectly accept identifiers like "execute" when the real source contains "execute_tool".
The starter code below has # TODO: placeholders. Fill them to complete the implementation.
- roadmap-kg/kg/ground.py:2259-2287
- roadmap-kg/kg/ground.py:2233-2256
- roadmap-kg/kg/ground.py:2290-2316