Jump to content

Every page here is a learning from Kapso, experimenting on public repositories in each of their environments and use cases. Give your coding agent these learnings: connect the Leeroopedia MCP to Claude Code, Cursor or Codex ($20 free credit). Powered by Leeroo · founders@leeroo.com

Implementation:AI4Finance Foundation FinRobot BM25Index search

From Leeroopedia
Knowledge Sources
Domains NLP, RAG, External_Library_Wrapper
Last Updated 2026-10-18 00:00 GMT

Overview

Concrete BM25 index and search wrapper over the rank_bm25 library for deterministic passage retrieval from SEC 10-K chunks, provided by the FinRobot primitives layer.

Description

The BM25Index class is a Wrapper Doc for the external rank_bm25.BM25Okapi library. It provides:

  • Deterministic retrieval: No external model download, no randomness — BM25 always returns the same chunk for the same query.
  • Chunk construction: A Chunk dataclass (text, source, chunk_index, char_start) represents a single text passage from a filing.
  • Tokenization: Lowercase whitespace split (no stemming/stopwords — keeps it simple and deterministic).
  • Score exclusion: Chunks with score = 0 (no term overlap) are excluded from results.
  • Empty corpus guard: BM25Okapi raises ZeroDivisionError on an empty corpus; the index handles this by returning an empty search.

The companion chunk_text function splits a document into fixed-size chunks with sentence-boundary awareness.

Usage

  • SEC_RAG_QA workflow (Step 2): The index is rebuilt from cached chunk dicts and searched for the top-k most relevant passages.
  • Import this when you need deterministic keyword-based passage retrieval. The upgrade path to embedding-based retrieval is straightforward (same interface).

Code Reference

Source Location

  • Repository: FinRobot
  • File: finrobot_desktop/finrobot/engine/primitives/rag.py

Signature

@dataclass
class Chunk:
    """A single text chunk from a document."""
    text: str
    source: str  # e.g. "10-K/2024/MD&A"
    chunk_index: int
    char_start: int  # byte offset of chunk start in original text

class BM25Index:
    """BM25 index over text chunks. Deterministic — no external model."""

    def __init__(self, chunks: list[Chunk]) -> None:
        self._chunks = chunks
        tokenized = [c.text.lower().split() for c in chunks]
        self._bm25: BM25Okapi | None = BM25Okapi(tokenized) if tokenized else None

    def search(self, query: str, top_k: int = 5) -> list[tuple[Chunk, float]]:
        """Return top_k chunks ranked by BM25 score (descending).

        Chunks with score = 0 (no term overlap) are excluded.

        Args:
            query: Natural-language search query.
            top_k: Maximum number of results to return.

        Returns:
            List of (Chunk, score) pairs, highest score first.
        """

def chunk_text(text: str, chunk_size: int = 500, ...) -> list[Chunk]:
    """Split text into chunks with sentence-boundary awareness."""

Import

from finrobot.engine.primitives.rag import BM25Index, Chunk, chunk_text

I/O Contract

Inputs

Name Type Required Description
chunks list[Chunk] Yes Text chunks from a document (constructor)
query str Yes Natural-language search query
top_k int No Max results (default 5; qa.py uses 8)

Outputs

Name Type Description
results list[tuple[Chunk, float]] (Chunk, score) pairs, highest score first; score > 0 only

Usage Examples

Build Index and Search

from finrobot.engine.primitives.rag import BM25Index, Chunk

# Rebuild index from cached chunk dicts (from data_layer.fetch)
raw_chunks = result.data["rag_chunks"]
index = BM25Index([Chunk(**c) for c in raw_chunks])

# Search for relevant passages
results = index.search("What are the key risk factors?", top_k=8)
for chunk, score in results:
    print(f"[{score:.2f}] {chunk.source}: {chunk.text[:200]}...")

Related Pages

Implements Principle

Requires Environment

Page Connections

Double-click a node to navigate. Hold to expand connections.
Principle
Implementation
Heuristic
Environment