Skip to main content
skill CX Codex

chunking-strategy — Claude Code skill: what it does, how to install

Configures document chunking workflows and overlap for RAG pipelines and vector search. It validates semantic coherence and tunes retrieval precision.

Install into Claude Code · Skills CLI (Vercel) All methods and platforms ↓
npx skills add giuseppe-trisciuoglio/developer-kit --skill chunking-strategy -a claude-code
Open on GitHub

What chunking-strategy does

The skill organizes document splitting into five tiers, moving from fixed-size chunks to semantic boundary detection. Simple texts start around 512 tokens with 10–20% overlap. Factoid queries run better at 256 tokens. Analytical tasks require up to 1024 tokens. For Python code, Markdown, and tables, structure-aware splitting preserves logical units like functions or classes using AST parsing.

The workflow enforces automated checks against retrieval metrics. If retrieval precision drops below 0.7, chunk size is reduced by 25%. If recall falls below 0.6, overlap increases by 10%. Running semantic coherence checks relies on sentence-transformers and models like all-MiniLM-L6-v2. Semantic splits introduce heavy computational overhead. That extra load increases latency during batch processing.

What it helps with

  • configure token chunk sizes and overlap ratios for vector databases
  • split Python code along function and class boundaries via AST
  • evaluate retrieval precision and recall metrics after splitting
  • set up semantic boundary detection based on cosine similarity thresholds

Example prompts for the agent

  • Recommend a chunking strategy for technical Markdown docs and Python files
  • Check semantic coherence for my chunks using sentence-transformers
  • How should I adjust chunk overlap if my RAG recall is below 0.6?

How to install chunking-strategy

1Skills CLI (Vercel)

npx skills add giuseppe-trisciuoglio/developer-kit --skill chunking-strategy -a claude-code

2Manually: put the files in place

~/.claude/skills/chunking-strategy/SKILL.md

Copy the whole skill folder; for one project use .claude/skills/chunking-strategy/

Step by step, with commands for each platform: How to install skills in Claude Code: five ways

Questions about chunking-strategy

How do I install chunking-strategy in Claude Code?

Run npx skills add giuseppe-trisciuoglio/developer-kit --skill chunking-strategy -a claude-code. The skill file is placed in ~/.claude/skills/chunking-strategy/SKILL.md.

What does chunking-strategy do?

It provides chunk size guidelines from 256 to 1024 tokens, overlap rules, and five splitting levels for RAG systems. It also includes validation scripts for precision, recall, and semantic cohesion.

What dependencies are required for semantic validation?

Semantic coherence testing requires the sentence-transformers Python package. Distribution metrics rely on numpy, while Python code parsing uses the standard ast module.

Source text

SKILL.md · MIT
---
name: chunking-strategy
description: Provides chunking strategies for RAG systems. Generates chunk size recommendations (256-1024 tokens), overlap percentages (10-20%), and semantic boundary detection methods. Validates semantic coherence and evaluates retrieval precision/recall metrics. Use when building retrieval-augmented generation systems, vector databases, or processing large documents.
allowed-tools: Read, Write, Bash
---

# Chunking Strategy for RAG Systems

## Overview

Provides chunking strategies for RAG systems, vector databases, and document processing. Recommends chunk sizes, overlap percentages, and boundary detection methods; validates semantic coherence; evaluates retrieval metrics.

## When to Use

Use when building or optimizing RAG systems, vector search pipelines, document chunking workflows, or performance-tuning existing systems with poor retrieval quality.

## Instructions

### Choose Chunking Strategy

Select based on document type and use case:

1. **Fixed-Size Chunking** (Level 1)
   - Use for simple documents without clear structure
   - Start with 512 tokens and 10-20% overlap
   - Adjust: 256 for factoid queries, 1024 for analytical

2. **Recursive Character Chunking** (Level 2)
   - Use for documents with structural boundaries
   - Hierarchical separators: paragraphs → sentences → words
   - Customize for document types (HTML, Markdown, JSON)

3. **Structure-Aware Chunking** (Level 3)
   - Use for structured content (Markdown, code, tables, PDFs)
   - Preserve semantic units: functions, sections, table blocks
   - Validate structure preservation post-split

4. **Semantic Chunking** (Level 4)
   - Use for complex documents with thematic shifts
   - Embedding-based boundary detection with 0.8 similarity threshold
   - Buffer size: 3-5 sentences

5. **Advanced Methods** (Level 5)
   - Late Chunking for long-context models
   - Contextual Retrieval for high-precision requirements
   - Monitor computational cost vs. retrieval gain

Reference: [references/strategies.md](references/strategies.md).

### Implement Chunking Pipeline

1. **Pre-process documents**
   - Analyze structure, content types, information density
   - Identify multi-modal content (tables, images, code)

2. **Select parameters**
   - Chunk size: embedding model context window / 4
   - Overlap: 10-20% for most cases
   - Strategy-specific settings

3. **Process and validate**
   - Apply chunking strategy
   - Validate coherence: run `evaluate_chunks.py --coherence` (see below)
   - Test with representative documents

4. **Evaluate and iterate**
   - Measure precision and recall
   - If precision < 0.7: reduce chunk_size by 25% and re-evaluate
   - If recall < 0.6: increase overlap by 10% and re-evaluate
   - Monitor latency and memory usage

Reference: [references/implementation.md](references/implementation.md).

### Validate Chunk Quality

Run validation commands to assess chunk quality:

```bash
# Check semantic coherence (requires sentence-transformers)
python -c "
from sentence_transformers import SentenceTransformer
model = SentenceTransformer('all-MiniLM-L6-v2')
chunks = [...]  # your chunks
embeddings = model.encode(chunks)
similarity = (embeddings @ embeddings.T).mean()
print(f'Cohesion: {similarity:.3f}')  # target: 0.3-0.7
"

# Measure retrieval precision
python -c "
relevant = sum(1 for c in retrieved if c in relevant_chunks)
precision = relevant / len(retrieved)
print(f'Precision: {precision:.2f}')  # target: >= 0.7
"

# Check chunk size distribution
python -c "
import numpy as np
sizes = [len(c.split()) for c in chunks]
print(f'Mean: {np.mean(sizes):.0f}, Std: {np.std(sizes):.0f}')
print(f'Min: {min(sizes)}, Max: {max(sizes)}')
"
```

Reference: [references/evaluation.md](references/evaluation.md).

## Examples

### Fixed-Size Chunking

```python
from langchain.text_splitter import RecursiveCharacterTextSplitter

splitter = RecursiveCharacterTextSplitter(
    chunk_size=256,
    chunk_overlap=25,
    length_function=len
)
chunks = splitter.split_documents(documents)
```

### Structure-Aware Code Chunking

```python
import ast

def chunk_python_code(code):
    tree = ast.parse(code)
    chunks = []
    for node in ast.walk(tree):
        if isinstance(node, (ast.FunctionDef, ast.ClassDef)):
            chunks.append(ast.get_source_segment(code, node))
    return chunks
```

### Semantic Chunking

```python
def semantic_chunk(text, similarity_threshold=0.8):
    sentences = split_into_sentences(text)
    embeddings = generate_embeddings(sentences)
    chunks, current = [], [sentences[0]]
    for i in range(1, len(sentences)):
        sim = cosine_similarity(embeddings[i-1], embeddings[i])
        if sim < similarity_threshold:
            chunks.append(" ".join(current))
            current = [sentences[i]]
        else:
            current.append(sentences[i])
    chunks.append(" ".join(current))
    return chunks
```

## Best Practices

### Core Principles
- Balance context preservation with retrieval precision
- Maintain semantic coherence within chunks
- Optimize for embedding model context window constraints

### Implementation
- Start with fixed-size (512 tokens, 15% overlap)
- Iterate based on document characteristics
- Test with domain-specific documents before deployment

### Pitfalls to Avoid
- Over-chunking: context-poor small chunks
- Under-chunking: missing information in oversized chunks
- Ignoring semantic boundaries and document structure
- One-size-fits-all for diverse content types

## Constraints and Warnings

### Resource Considerations
- Semantic methods require significant compute resources
- Late chunking needs long-context embedding models
- Complex strategies increase processing latency
- Monitor memory for large document batches

### Quality Requirements
- Validate semantic coherence post-processing
- Test with representative documents before deployment
- Ensure chunks maintain standalone meaning
- Implement error handling for malformed content

## References

- [strategies.md](references/strategies.md) - Detailed strategies
- [implementation.md](references/implementation.md) - Implementation guidelines
- [evaluation.md](references/evaluation.md) - Performance metrics
- [tools.md](references/tools.md) - Libraries and frameworks
- [research.md](references/research.md) - Research papers
- [advanced-strategies.md](references/advanced-strategies.md) - 11 advanced methods
- [semantic-methods.md](references/semantic-methods.md) - Semantic approaches
- [visualization-tools.md](references/visualization-tools.md) - Visualization tools

© giuseppe-trisciuoglio · MIT · giuseppe-trisciuoglio/developer-kit

Similar skills

Everything for AI and ML →

From the same set93

nestjs-best-practices A skill that hands your agent a rulebook for NestJS: module boundaries, provider scopes, exception filters, DTO validation and Drizzle ORM. CX Codex +1 3,800installs spring-boot-cache Configures caching in Spring Boot services using Caffeine, Redis, or Ehcache providers. Helps set up TTL policies, apply cache annotations, and trace cache misses. CX Codex +1 3,800installs zod-validation-utilities Guides Zod v4 validation for TypeScript APIs, forms, and configuration. Use it when external input needs parsing, coercion, and clear validation errors. CX Codex +1 3,800installs spring-boot-event-driven-patterns A Spring Boot 3.x skill for domain events, @TransactionalEventListener, Kafka messaging and the transactional outbox pattern. Useful when sync calls between services need to become events. CX Codex +1 3,800installs aws-sdk-java-v2-rds Guides AI agents in managing Amazon RDS databases via the AWS SDK for Java 2.x. Useful for provisioning instances, snapshots, and parameter groups. CX Codex +1 3,700installs aws-sdk-java-v2-kms This skill provides AWS KMS patterns for AWS SDK for Java 2.x, covering keys, encryption, data keys, signatures, and Spring Boot integration. CX Codex +1 3,700installs aws-sdk-java-v2-secrets-manager A skill for pulling AWS Secrets Manager values into Java services: retrieval, caching, rotation-aware access and Spring Boot wiring. CX Codex +1 3,700installs aws-sdk-java-v2-messaging Code patterns for AWS SQS and SNS using AWS SDK for Java 2.x. Helps configure clients, handle FIFO queues, set up DLQ, and integrate messaging into Spring Boot. CX Codex +1 3,700installs

Project sponsors

Companies that keep this analytics open
Gold sponsor

Impressions, clicks and code copies — open statistics. We keep the numbers public for the same reason NeBlask itself is public. Become a sponsor