Implementation:AI4Finance Foundation FinGPT Raptor RAG
| Knowledge Sources | |
|---|---|
| Domains | RAG, NLP, Financial_Report_Analysis |
| Last Updated | 2026-10-18 00:00 GMT |
Overview
Concrete tool for recursive abstractive processing and tree-organized retrieval (RAPTOR) of financial report documents provided by the FinGPT FinGPT_FinancialReportAnalysis subproject.
Description
The Raptor class implements the RAPTOR clustering-and-summarization pipeline. It chunks a long financial report, embeds the chunks, clusters them with a Gaussian Mixture Model over UMAP-reduced embeddings, summarizes each cluster with an LLM, and then recurses on the summaries to build a multi-level tree of abstractions. The result is a flat list of original chunks plus hierarchical summaries that can be indexed for retrieval-augmented generation.
Usage
Import this class when you need to build a hierarchical summary tree from a long financial document (e.g., 10-K filings, earnings transcripts) for use in a RAG retrieval index. Requires a LangChain chat model and an embedding model with an `embed_documents` method.
Code Reference
Source Location
- Repository: AI4Finance_Foundation_FinGPT
- File: fingpt/FinGPT_FinancialReportAnalysis/utils/rag.py
- Lines: 1-412
Signature
class Raptor:
def __init__(self, model, embed):
"""
Args:
model: A LangChain chat model (invokable via LCEL chain).
embed: An embedding object exposing embed_documents(list[str]) -> list[vector].
"""
def global_cluster_embeddings(self, embeddings: np.ndarray, dim: int,
n_neighbors: Optional[int] = None,
metric: str = "cosine") -> np.ndarray: ...
def local_cluster_embeddings(self, embeddings: np.ndarray, dim: int,
num_neighbors: int = 10,
metric: str = "cosine") -> np.ndarray: ...
def get_optimal_clusters(self, embeddings: np.ndarray,
max_clusters: int = 50,
random_state: int = 224) -> int: ...
def GMM_cluster(self, embeddings: np.ndarray, threshold: float,
random_state: int = 0): ...
def perform_clustering(self, embeddings: np.ndarray, dim: int,
threshold: float) -> List[np.ndarray]: ...
def embed(self, texts) -> np.ndarray: ...
def embed_cluster_texts(self, texts) -> pd.DataFrame: ...
def fmt_txt(self, df: pd.DataFrame) -> str: ...
def embed_cluster_summarize_texts(self, texts: List[str], level: int
) -> Tuple[pd.DataFrame, pd.DataFrame]: ...
def recursive_embed_cluster_summarize(self, texts: List[str], level: int = 1,
n_levels: int = 3
) -> Dict[int, Tuple[pd.DataFrame, pd.DataFrame]]: ...
def text_spliter(self, text, chunk_size_tok=2000, level=1, n_levels=3) -> List[str]: ...
Import
from fingpt.FinGPT_FinancialReportAnalysis.utils.rag import Raptor
I/O Contract
Inputs
| Name | Type | Required | Description |
|---|---|---|---|
| model | LangChain ChatModel | Yes | LLM used to summarize each cluster of chunks |
| embed | Embedding object | Yes | Object exposing `embed_documents(list[str])` for vectorization |
| text | str | Yes (text_spliter) | Raw financial report text to process |
| chunk_size_tok | int | No | Chunk size in tokens (default 2000) |
| n_levels | int | No | Maximum recursion depth for the summary tree (default 3) |
Outputs
| Name | Type | Description |
|---|---|---|
| text_spliter returns | List[str] | Original chunks plus hierarchical summaries, ready for retrieval indexing |
| recursive_embed_cluster_summarize returns | Dict[int, Tuple[DataFrame, DataFrame]] | Per-level cluster and summary DataFrames |
Usage Examples
Build a RAPTOR Tree from a 10-K Filing
from langchain_openai import ChatOpenAI, OpenAIEmbeddings
from fingpt.FinGPT_FinancialReportAnalysis.utils.rag import Raptor
# 1. Configure the LLM and embedding model
llm = ChatOpenAI(model="gpt-4o", temperature=0)
embeddings = OpenAIEmbeddings(model="text-embedding-3-small")
# 2. Instantiate the Raptor pipeline
raptor = Raptor(model=llm, embed=embeddings)
# 3. Load a long financial report
with open("AAPL_10K_2024.txt", "r") as f:
report_text = f.read()
# 4. Build the hierarchical summary tree
retrieval_texts = raptor.text_spliter(
report_text, chunk_size_tok=2000, n_levels=3
)
# 5. Index the resulting texts for RAG retrieval
print(f"Indexed {len(retrieval_texts)} chunks + summaries")