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

top_k must be positive

Error message

top_k must be positive

What it means

Error "top_k must be positive" thrown in rohitg00/ai-engineering-from-scratch.

Source

Thrown at certifications/claude/lessons/24-rag-retrieval-and-data-pipelines/code/main.py:119

        return math.log(1.0 + (total - containing + 0.5) / (containing + 0.5))

    def _score(self, query_terms: list[str], index: int, k1: float = 1.5, b: float = 0.75) -> float:
        frequencies = self.term_frequencies[index]
        length = self.lengths[index]
        normalization = 1.0 - b + b * (length / self.average_length) if self.average_length else 1.0
        score = 0.0
        for term in query_terms:
            frequency = frequencies.get(term, 0)
            if frequency == 0:
                continue
            numerator = frequency * (k1 + 1.0)
            denominator = frequency + k1 * normalization
            score += self._inverse_document_frequency(term) * numerator / denominator
        return score

    def search(self, query: str, top_k: int = 3) -> list[RetrievalHit]:
        if top_k <= 0:
            raise ValueError("top_k must be positive")
        query_terms = tokenize(query)
        if not query_terms:
            return []
        scored = []
        for index, chunk in enumerate(self.chunks):
            score = self._score(query_terms, index)
            if score > 0:
                scored.append((score, chunk))
        scored.sort(key=lambda item: (-item[0], item[1].chunk_id))
        return [
            RetrievalHit(
                chunk_id=chunk.chunk_id,
                document_id=chunk.document_id,
                text=chunk.text,
                updated_at=chunk.updated_at,
                score=round(score, 6),
            )
            for score, chunk in scored[:top_k]

View on GitHub (pinned to 39ea8a1c6d)

When it happens

Trigger: Thrown at certifications/claude/lessons/24-rag-retrieval-and-data-pipelines/code/main.py:119 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/f37384e931243863. Report an issue: GitHub.