chunking-strategies
БесплатноБез исполняемых скриптовНе проверенDocument chunking techniques for RAG. Fixed-size, recursive, semantic, token-based, document-aware, proposition, parent-child, sliding window, and Anthropic…
от claude-dev-suite★ 51 звезда на GitHubОб этом скилле
Chunking Strategies
Strategy Tradeoff Matrix
| Strategy | Preserves Semantics | Cost | Best For | Chunk Unit |
|---|---|---|---|---|
| Fixed-size | No | Free | Homogeneous prose | Chars |
| Recursive character | Partial | Free | General text | Chars with hierarchy |
| Token-based | No | Free | Exact token budgeting | Tokens |
| Document-aware (Markdown/HTML) | Yes | Free | Technical docs, wikis | Headers/sections |
| Code-aware | Yes | Free | Source code | Functions/classes |
| Semantic (embedding breakpoints) | Yes | $$ | Long narrative, research papers | Meaning shifts |
| Proposition-based | Yes | $$$ | High-precision Q&A, legal | Atomic facts |
| Parent-child | Yes | Free | Need small match + big context | Hierarchy |
| Sliding window | Partial | Free | Dialogues, timelines | Overlap + stride |
| Contextual retrieval (Anthropic) | Yes | $$ | Production RAG > 5k chunks | Chunk + LLM context |
Fixed-Size
def fixed_chunks(text: str, size: int = 800, overlap: int = 200) -> list[str]:
return [text[i:i + size] for i in range(0, len(text), size - overlap)]
Use only as a baseline. Breaks mid-sentence and mid-token.
Recursive Character (default for most projects)
from langchain_text_splitters import RecursiveCharacterTextSplitter
splitter = RecursiveCharacterTextSplitter(
chunk_size=800,
chunk_overlap=200,
separators=["\n\n", "\n", ". ", "? ", "! ", " ", ""],
length_function=len,
is_separator_regex=False,
)
chunks = splitter.split_documents(docs)
Tries separators in order so paragraph boundaries are preferred over arbitrary cuts.
Token-Based (exact LLM budgeting)
from langchain_text_splitters import TokenTextSplitter
splitter = TokenTextSplitter(
encoding_name="cl100k_base", # GPT-4, text-embedding-3
chunk_size=512,
chunk_overlap=64,
)
chunks = splitter.split_text(text)
For Claude, use anthropic.Anthropic().messages.count_tokens to measure; approximate ratio is ~3.5 chars per token for English.
Document-Aware: Markdown
from langchain_text_splitters import MarkdownHeaderTextSplitter, RecursiveCharacterTextSplitter
headers = [("#", "h1"), ("##", "h2"), ("###", "h3")]
md_splitter = MarkdownHeaderTextSplitter(headers_to_split_on=headers, strip_headers=False)
header_chunks = md_splitter.split_text(markdown_text)
# Secondary splitter for oversized sections
char_splitter = RecursiveCharacterTextSplitter(chunk_size=800, chunk_overlap=150)
chunks = char_splitter.split_documents(header_chunks) # metadata carries h1/h2/h3
Header metadata enables section-level filtering at query time.
Document-Aware: Code
from langchain_text_splitters import RecursiveCharacterTextSplitter, Language
py_splitter = RecursiveCharacterTextSplitter.from_language(
language=Language.PYTHON, chunk_size=1500, chunk_overlap=200
)
ts_splitter = RecursiveCharacterTextSplitter.from_language(
language=Language.TS, chunk_size=1500, chunk_overlap=200
)
Splits on class, def, function boundaries. Larger chunks because code lines are shorter than prose.
Semantic Chunking (embedding breakpoints)
Splits where adjacent sentences diverge in meaning. Expensive (embeds every sentence) but yields coherent chunks on long-form content.
from langchain_experimental.text_splitter import SemanticChunker
from langchain_openai import OpenAIEmbeddings
splitter = SemanticChunker(
OpenAIEmbeddings(model="text-embedding-3-small"),
breakpoint_threshold_type="percentile", # or "standard_deviation", "interquartile"
breakpoint_threshold_amount=95,
buffer_size=1,
)
chunks = splitter.create_documents([long_text])
Manual variant for fine control (break where cosine distance between adjacent sentence embeddings exceeds the 95th percentile):
import numpy as np
from sentence_transformers import SentenceTransformer
def semantic_chunks(text: str, pct: float = 95) -> list[str]:
sents = [s.strip() for s in text.split(". ") if s.strip()]
embs = SentenceTransformer("all-MiniLM-L6-v2").encode(sents)
sims = [np.dot(embs[i], embs[i+1]) / (np.linalg.norm(embs[i]) * np.linalg.norm(embs[i+1]))
for i in range(len(sents) - 1)]
dists = 1 - np.array(sims)
breaks = [i + 1 for i, d in enumerate(dists) if d > np.percentile(dists, pct)]
out, start = [], 0
for b in breaks + [len(sents)]:
out.append(". ".join(sents[start:b])); start = b
return out
Proposition-Based Chunking
Decompose text into atomic factual propositions using an LLM. Each proposition becomes one chunk.
from anthropic import Anthropic
import json
client = Anthropic()
PROMPT = """Decompose the passage into atomic propositions. Each proposition:
- Expresses exactly one fact
- Is self-contained (no pronouns without antecedents)
- Resolves coreferences inline
Return JSON array of strings. Passage:
{passage}"""
def propositionize(passage: str) -> list[str]:
Установить chunking-strategies в Claude Code и Claude Desktop
Зарегайся, чтобы установить скилл
Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.
- Открой команду установки в одну строку
- Сохраняй скиллы в синхронизируемую библиотеку
- Уведомления, когда скиллы обновляются
Разрешённые инструменты
Инструменты, которые скиллу разрешено вызывать.
ReadGrepGlobWriteEditFAQ
Что делает скилл chunking-strategies?
Document chunking techniques for RAG. Fixed-size, recursive, semantic, token-based, document-aware, proposition, parent-child, sliding window, and Anthropic contextual retrieval. Tradeoff tables, LangChain and LlamaIndex code. USE WHEN: user mentions "chunking", "text splitter", "split documents", "semantic chunking", "contextual retrieval", "parent-child chunks", "proposition chunking" DO NOT USE FOR: retrieval after chunking - use `advanced-retrieval`; query-side transforms - use `query-transformations`; overall design - use `rag-architecture`
Как установить скилл chunking-strategies?
Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.
Скилл chunking-strategies запускает скрипты?
Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.
Похожие скиллы
docx
Use this skill whenever the user wants to create, read, edit, or manipulate Word documents (.docx files) or Word templates (.dotx files). Triggers include…
от AnthropicUse this skill whenever the user wants to do anything with PDF files. This includes reading or extracting text/tables from PDFs, combining or merging multiple…
от Anthropicxlsx
Use this skill any time a spreadsheet file is the primary input or output. This means any task where the user wants to: open, read, edit, or fix an existing…
от Anthropicpptx
Use this skill any time a .pptx or .potx file is involved in any way — as input, output, or both. This includes: creating slide decks, pitch decks, or…
от Anthropic