rohitg00/ai-engineering-from-scratch · error · ValueError

chunk_tokens must be > 0

Error message

chunk_tokens must be > 0

What it means

stream yields the simulated model response in chunks of chunk_tokens tokens; a non-positive chunk size cannot slice the text into pieces and would produce empty or infinite chunk loops, so it is rejected before streaming begins.

Solutions

  1. Pass a positive chunk size (default 4)
  2. Clamp user input: chunk_tokens = max(1, int(chunk_tokens))
  3. Validate streaming config parameters when initializing the client
Defensive patterns

Strategy: validation

When it happens

Trigger: Thrown at phases/19-capstone-projects/87-end-to-end-safety-gate/code/mock_llm_stream.py:62 when the library encounters an invalid state.

Common situations: See trigger scenarios.


AI-assisted analysis of rohitg00/ai-engineering-from-scratch@39ea8a1c6d (2026-08-26). Data as JSON: /api/errors/5bfad4d8c9714a96. Report an issue: GitHub.

Appendix: source

Thrown at phases/19-capstone-projects/87-end-to-end-safety-gate/code/mock_llm_stream.py:62

    r"\bbegin\s+your\s+answer\s+with\b",
    r"\bsure[, ]\s*here\s+is\b",
]


def _persona(prompt: str) -> str:
    low = prompt.lower()
    for pat in _REFUSE_PATTERNS:
        if re.search(pat, low):
            return "attacker-honest"
    for pat in _LAZY_PATTERNS:
        if re.search(pat, low):
            return "attacker-lazy"
    return "clean"


def stream(prompt: str, chunk_tokens: int = 4) -> Iterator[str]:
    if chunk_tokens <= 0:
        raise ValueError("chunk_tokens must be > 0")
    persona = _persona(prompt)
    if persona == "attacker-honest":
        text = REFUSAL
    elif persona == "attacker-lazy":
        text = HARMFUL_CONTINUATION
    else:
        text = BENIGN_REPLY
    tokens = text.split()
    for i in range(0, len(tokens), chunk_tokens):
        yield " ".join(tokens[i : i + chunk_tokens]) + " "


def persona_for(prompt: str) -> str:
    return _persona(prompt)

View on GitHub (pinned to 39ea8a1c6d)