...{"), t.rfind("}")
    if a != -1 and b != -1 and b > a:
        t = t[a:b + 1]
    return t.strip()


def extract_allowed_codes(codebook_text: str) -> set[str]:
    # capture all code tokens like LSM_..., THM_..., HIM_..., NAB_...
    return set(re.findall(r"\b(?:LSM|THM|HIM|NAB)_[A-Z0-9]+(?:_[A-Z0-9]+)*\b", codebook_text))


def ollama_chat(model: str, prompt: str, timeout: int, num_ctx: int, num_pr...