语义分块是一种通过分析文本片段之间的语义相似性来将文档分割成更小块的方法,它使用嵌入(embeddings)来实现。该方法利用 chonkie 库,根据可配置的相似度阈值,识别语义含义发生显著变化时的自然断点。与固定长度分块相比,它能更好地保留上下文和意义,通过确保语义相关的内​​容保留在同一块中,并在有意义的主题过渡处进行分割。

from agno.agent import Agent
from agno.document.chunking.semantic import SemanticChunking
from agno.knowledge.pdf_url import PDFUrlKnowledgeBase
from agno.vectordb.pgvector import PgVector

db_url = "postgresql+psycopg://ai:ai@localhost:5532/ai"

knowledge_base = PDFUrlKnowledgeBase(
    urls=["https://agno-public.s3.amazonaws.com/recipes/ThaiRecipes.pdf"],
    vector_db=PgVector(table_name="recipes_semantic_chunking", db_url=db_url),
    chunking_strategy=SemanticChunking(),
)
knowledge_base.load(recreate=False)  # Comment out after first run

agent = Agent(
    knowledge_base=knowledge_base,
    search_knowledge=True,
)

agent.print_response("How to make Thai curry?", markdown=True)

语义分块参数

参数类型默认值描述
embedderEmbedderOpenAIEmbedder用于语义分块的 embedder。
chunk_sizeint5000每个块的最大大小。
similarity_thresholdfloat0.5用于确定块边界的相似度阈值。