Document Chunking
Group paragraphs into chunks and split oversized paragraphs at sentence boundaries.
DocumentChunking packs double-newline-separated paragraphs toward chunk_size. It splits an oversized paragraph at sentence boundaries.
Create a Python file
from agno.agent import Agent
from agno.knowledge.chunking.document import DocumentChunking
from agno.knowledge.knowledge import Knowledge
from agno.knowledge.reader.pdf_reader import PDFReader
from agno.vectordb.pgvector import PgVector
db_url = "postgresql+psycopg://ai:ai@localhost:5532/ai"
knowledge = Knowledge(
vector_db=PgVector(table_name="recipes_document_chunking", db_url=db_url),
)
knowledge.insert(
url="https://agno-public.s3.amazonaws.com/recipes/ThaiRecipes.pdf",
reader=PDFReader(
name="Document Chunking Reader",
split_on_pages=False,
chunking_strategy=DocumentChunking(),
),
)
agent = Agent(
knowledge=knowledge,
search_knowledge=True,
)
agent.print_response("How do I make Thai curry?", markdown=True)Set up your virtual environment
uv venv --python 3.12
source .venv/bin/activateInstall dependencies
uv pip install -U agno sqlalchemy psycopg pgvector pypdf openaiExport your OpenAI API key
Set OpenAI Key
Set your OPENAI_API_KEY as an environment variable. You can get one from OpenAI.
export OPENAI_API_KEY=sk-***Run PgVector
docker run -d \
-e POSTGRES_DB=ai \
-e POSTGRES_USER=ai \
-e POSTGRES_PASSWORD=ai \
-e PGDATA=/var/lib/postgresql \
-v pgvolume:/var/lib/postgresql \
-p 5532:5432 \
--name pgvector \
agnohq/pgvector:18Run the script
python document_chunking.pyThe example sets split_on_pages=False so PDFReader combines the pages before applying DocumentChunking. Keep the default value of True to chunk each page independently.
Chunk Size
chunk_size is a target rather than a strict ceiling. Paragraph separators, a sentence longer than the target, and overlap can produce a longer chunk. Overlap is prepended without an added separator.
Document Chunking Params
| Parameter | Type | Default | Description |
|---|---|---|---|
chunk_size | int | 5000 | Approximate character target. Long atomic content and overlap can make final chunks larger. |
overlap | int | 0 | The number of characters to overlap between chunks. |