Skip to content

AI Code Explainer — Python source

Paste any code snippet and get a plain-language explanation from an LLM — beginner, developer, or expert depth — with your own free Groq key, straight from your browser.

This is the Python implementation — the same logic the interactive tool runs, in a shareable, citable form.

"""code-explainer — language guessing, depth-graded prompts, reply cleanup.

Language: Python 3 (standard library only).
CosmoDev polyglot showcase port of the `code-explainer` tool, ported from
src/lib/code-explainer.ts (the canonical TypeScript implementation).

Why this file exists: the whole explainer pipeline is three pure functions —
guess the language, build a depth-graded chat prompt, strip code fences from
the reply — so each runtime ships the identical pipeline with no provider
dependency. Python's ``re`` speaks the TS regex dialect (with ``re.ASCII``
matching JavaScript's ASCII-only ``\\w`` / ``\\b``), so the rules port verbatim.

display source — part of CosmoDev's polyglot tool pages.
"""

from __future__ import annotations

import re

#: Depth knob for the prompt: how much explanation contract the model gets.
LEVELS = ("beginner", "developer", "expert")

#: Guess the language from (and prompt with) at most this many chars.
MAX_CODE_CHARS = 12000

#: Per-level explanation contract, verbatim from the TS lib.
LEVEL_CONTRACT: dict[str, str] = {
    "beginner": (
        "Explain for a smart newcomer: no unexplained jargon, short sentences, "
        "one everyday analogy if it helps. Say what it does first, then how, "
        "step by step."
    ),
    "developer": (
        "Explain for a working developer: concise and practical. Lead with what "
        "it does, then the flow, the patterns used, and the pitfalls an editor "
        "should catch."
    ),
    "expert": (
        "Explain for an expert: dense and precise. Cover invariants, complexity, "
        "edge cases, and anything subtle an experienced reviewer would flag."
    ),
}

# Cheap keyword heuristics — enough to name the language in the prompt so the
# model starts right; never a language detector. First match wins, so order
# matters: go before rust before python before the web trio.
_RULES: list[tuple[str, re.Pattern[str]]] = [
    ("go", re.compile(r"\bpackage\s+\w+|\bfunc\s+\w+|:=", re.ASCII)),
    ("rust", re.compile(r"\bfn\s+\w+|\blet\s+mut\b|\bimpl\b", re.ASCII)),
    (
        "python",
        re.compile(r"\bdef\s+\w+\s*\(|\bprint\s*\(|\bimport\s+\w+\s*$", re.ASCII | re.MULTILINE),
    ),
    ("sql", re.compile(r"\bSELECT\b.+\bFROM\b", re.ASCII | re.IGNORECASE)),
    (
        "typescript",
        re.compile(
            r"\binterface\s+\w+\s*\{|\btype\s+\w+\s*=|:\s*(string|number|boolean)\b", re.ASCII
        ),
    ),
    ("javascript", re.compile(r"\bconst\s+\w+\s*=|=>|console\.log", re.ASCII)),
    ("css", re.compile(r"[.#]?[\w-]+\s*\{[^}]*:[^}]*;", re.ASCII)),
    ("html", re.compile(r"</?[a-z][\w-]*(\s+[\w-]+=\"[^\"]*\")*\s*/?>", re.ASCII | re.IGNORECASE)),
]


def guess_language(code: str) -> str:
    """Guess the language of a code sample.

    Falls back to ``"text"`` when no rule matches, so the prompt can tell the
    model to reason about the paste as pseudocode instead of pretending to
    know better.
    """
    for lang, pattern in _RULES:
        if pattern.search(code):
            return lang
    return "text"


def build_prompt_messages(code: str, *, level: str) -> list[dict[str, str]]:
    """Build the [system, user] chat messages for the provider layer.

    The code is truncated BEFORE guessing: the heuristics only need a sample,
    and running them over a 30k-char paste is pure waste.
    """
    truncated = len(code) > MAX_CODE_CHARS
    body = f"{code[:MAX_CODE_CHARS]}\n… (code truncated)" if truncated else code
    lang = guess_language(body)
    uncertainty = (
        " (no clear language — say so and reason about it as pseudocode)"
        if lang == "text"
        else ""
    )
    system = (
        f"You explain code. {LEVEL_CONTRACT[level]} The code appears to be "
        f"{lang}{uncertainty}. Use short paragraphs or bullets; markdown is fine."
    )
    return [
        {"role": "system", "content": system},
        {"role": "user", "content": body},
    ]


def parse_explanation(text: str) -> str | None:
    """Clean the model's reply into displayable explanation text.

    Strips markdown code fences, then trims. Returns ``None`` only when
    nothing survives cleaning — there is no strict format contract beyond
    "non-empty".
    """
    cleaned = re.sub(r"```[a-z]*\n?", "", text).strip()
    return cleaned or None

Also available in 13 other languages

Every CosmoDev tool ships its pure logic in TypeScript (web) and Go (CLI), with authored implementations in a dozen-plus languages — the same contract, ported. Compare all languages side by side →