> ## Documentation Index
> Fetch the complete documentation index at: https://praison.ai/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# Hierarchical Summaries

> Multi-level summaries for efficient navigation of large knowledge bases

```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
from praisonaiagents import Agent

agent = Agent(name="summariser", instructions="Create hierarchical summaries of long documents.")
agent.start("Summarise this 50-page report into a 3-level hierarchy.")
```

Hierarchical summaries build file → folder → project abstractions so agents route queries efficiently across large knowledge bases.

The user asks a broad or specific question; routing picks the right summary level.

```mermaid theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
graph LR
    subgraph "Hierarchical Summaries"
        F[📄 Files] --> FS[📁 Folder summaries]
        FS --> PS[🏗️ Project summary]
        Q[❓ Query] --> R{Route level}
        R -->|specific| F
        R -->|folder| FS
        R -->|broad| PS
    end

    classDef input fill:#6366F1,stroke:#7C90A0,color:#fff
    classDef process fill:#189AB4,stroke:#7C90A0,color:#fff
    classDef decision fill:#F59E0B,stroke:#7C90A0,color:#fff
    classDef result fill:#10B981,stroke:#7C90A0,color:#fff

    class F,FS,PS process
    class Q input
    class R decision

```

## How It Works

```mermaid theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
sequenceDiagram
    participant User
    participant Agent
    participant Feature as Hierarchical Summaries

    User->>Agent: Request
    Agent->>Feature: Process request
    Feature-->>Agent: Result    Agent-->>User: Response
```

## Quick Start

**1. Build a three-level hierarchy**

```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
from praisonaiagents.rag import HierarchicalSummarizer

summarizer = HierarchicalSummarizer(max_levels=3)

files = ["./docs/api.md", "./docs/auth.md", "./docs/config.md"]
summarizer.build_hierarchy(files, base_path="./docs")

answer = summarizer.query("How do I authenticate?")
print(answer)
```

**2. Persist and reload**

```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
summarizer.save("./summaries/hierarchy.json")
summarizer.load("./summaries/hierarchy.json")
```

***

## Overview

The HierarchicalSummarizer provides:

* **Multi-level summaries** at file, folder, and project levels
* **Query routing** to appropriate summary levels
* **Incremental updates** when files change
* **Persistent storage** of summary hierarchies

## Building Hierarchies

### From Directory

```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
import os
from praisonaiagents.rag import HierarchicalSummarizer

summarizer = HierarchicalSummarizer(max_levels=3)

files = []
for root, _, filenames in os.walk("./docs"):
    for f in filenames:
        if f.endswith(('.md', '.txt', '.py')):
            files.append(os.path.join(root, f))

result = summarizer.build_hierarchy(files, base_path="./docs")

print(f"Files processed: {len(files)}")
print(f"Summary nodes: {len(result.nodes)}")
```

### Summary Levels

| Level | Scope | Description |
| - | - | - |
| 1 | File | Summary of individual file content |
| 2 | Folder | Summary of all files in a folder |
| 3 | Project | Summary of entire project/corpus |

```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
summarizer = HierarchicalSummarizer(
    max_levels=3,
    file_summary_tokens=500,
    folder_summary_tokens=1000,
    project_summary_tokens=2000,
)
```

## Query Routing

### Automatic Routing

```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
answer = summarizer.query("What parameters does the auth function accept?")
answer = summarizer.query("What authentication methods are available?")
answer = summarizer.query("What is this project about?")
```

### Manual Level Selection

```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
answer = summarizer.query("Overview of the project", level="project")
answer = summarizer.query("What's in the API folder?", level="folder", path="api/")
```

## Persistence

```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
summarizer.save("./summaries/hierarchy.json")
summarizer.load("./summaries/hierarchy.json")

summarizer.update_file("./docs/new_file.md")
summarizer.rebuild_folder("./docs/api/")
```

### Durable persistence

The hierarchy JSON written by `build_hierarchy()` is saved atomically as of PR [#6111](https://github.com/MervinPraison/PraisonAI/pull/6111).

A crash, OOM kill, or non-serialisable value during the save cannot truncate the previous hierarchy file — the last-known-good hierarchy survives, and the failure is logged at `WARNING` level (`Failed to save hierarchy ...`).

> [!NOTE]
>
> Before #6111, a failed write could leave a partial or empty hierarchy file with no log entry, so the next load had no routing data and no explanation.

## CLI Usage

```bash theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
praisonai knowledge summarize ./docs
praisonai knowledge summarize ./docs --levels 2 --output ./summaries
praisonai knowledge summarize ./docs -i "*.md,*.txt" -e "test_*" --verbose
```

## Integration with Agents

```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
from praisonaiagents import Agent

agent = Agent(
    name="HierarchicalAgent",
    instructions="Answer questions using the knowledge base.",
    knowledge={
        "sources": ["./docs"],
        "retrieval_k": 5,
    },
)

response = agent.start("What is this project about?")
response = agent.start("What are the auth function parameters?")
```

## Best Practices

> [accordion] Use three levels for most projects
>
> File, folder, and project summaries balance routing precision with build cost for typical documentation corpora.

> [accordion] Set token limits per level
>
> Keep file summaries shorter than folder summaries, and folder summaries shorter than the project root — avoids bloated parent nodes.

> [accordion] Persist hierarchies to disk
>
> Save to JSON after the initial build so startup skips re-summarising unchanged files.

> [accordion] Rebuild incrementally on change
>
> Call `update_file()` or `rebuild_folder()` instead of rebuilding the entire tree when only part of the corpus changes.

***

## Related

> [card] [Knowledge](https://praison.ai/docs/features/knowledge.md)
>
> Knowledge sources and retrieval

> [card] [Smart Retrieval](https://praison.ai/docs/features/smart-retrieval.md)
>
> Query routing and relevance strategies

> [card] [Context Compression](https://praison.ai/docs/features/context-compression.md)
>
> Compress long contexts before LLM calls

> [card] [RAG Overview](https://praison.ai/docs/features/rag.md)
>
> Retrieval-augmented generation patterns


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.