一键导入
langchain-text-splitters
Guide to using text splitter integrations in LangChain including recursive, character, and semantic splitters
用 Codex 或 Claude 帮你安装 复制这段 Prompt,粘贴到 Codex、Claude 或其他助手里,让它检查 Skill 页面并帮你完成安装。
菜单
Guide to using text splitter integrations in LangChain including recursive, character, and semantic splitters
用 Codex 或 Claude 帮你安装 复制这段 Prompt,粘贴到 Codex、Claude 或其他助手里,让它检查 Skill 页面并帮你完成安装。
基于 SOC 职业分类
Using the Deep Agents CLI - terminal interface, persistent memory with AGENTS.md, project conventions, skills directories, and CLI commands.
Understanding Deep Agents framework - what they are, how to create them with createDeepAgent, and the agent harness architecture with built-in middleware for planning, filesystems, and subagents.
Creating and using custom skills with progressive disclosure, SKILL.md format, and the Agent Skills protocol in Deep Agents.
Using the Deep Agents CLI - terminal interface, persistent memory with AGENTS.md, project conventions, skills directories, and CLI commands.
Using FilesystemMiddleware with virtual filesystems, backends (State, Store, Filesystem, Composite), and context management for Deep Agents.
Using FilesystemMiddleware with virtual filesystems, backends (State, Store, Filesystem, Composite), and context management for Deep Agents.
| name | langchain-text-splitters |
| description | Guide to using text splitter integrations in LangChain including recursive, character, and semantic splitters |
| language | js |
Text splitters divide large documents into smaller chunks that fit within model context windows and enable effective retrieval. Proper chunking is critical for RAG system performance - chunks must be small enough for retrieval but large enough to preserve context.
| Splitter | Best For | Package | Key Features |
|---|---|---|---|
| RecursiveCharacterTextSplitter | General purpose | @langchain/textsplitters | Hierarchical splitting, preserves structure |
| CharacterTextSplitter | Simple splitting | @langchain/textsplitters | Split by single separator |
| TokenTextSplitter | Token-aware splitting | @langchain/textsplitters | Counts actual tokens, not characters |
| MarkdownTextSplitter | Markdown documents | @langchain/textsplitters | Preserves markdown structure |
| RecursiveJsonSplitter | JSON data | @langchain/textsplitters | Splits JSON while preserving structure |
Choose RecursiveCharacterTextSplitter if:
Choose TokenTextSplitter if:
Choose MarkdownTextSplitter if:
import { RecursiveCharacterTextSplitter } from "@langchain/textsplitters";
// Basic usage
const splitter = new RecursiveCharacterTextSplitter({
chunkSize: 1000, // Target chunk size in characters
chunkOverlap: 200, // Overlap between chunks
});
const text = "Long document text here...";
const chunks = await splitter.splitText(text);
console.log(`Created ${chunks.length} chunks`);
chunks.forEach((chunk, i) => {
console.log(`Chunk ${i + 1}: ${chunk.length} characters`);
});
// Split documents (preserves metadata)
import { Document } from "@langchain/core/documents";
const docs = [
new Document({
pageContent: "Long text...",
metadata: { source: "doc1.pdf", page: 1 }
})
];
const splitDocs = await splitter.splitDocuments(docs);
// Metadata is preserved and enriched with loc.lines
// Tries to split on these separators in order:
// 1. "\n\n" (double newline - paragraphs)
// 2. "\n" (single newline)
// 3. " " (space)
// 4. "" (character-by-character if needed)
const splitter = new RecursiveCharacterTextSplitter({
chunkSize: 1000,
chunkOverlap: 200,
separators: ["\n\n", "\n", " ", ""], // Default, can customize
});
// This preserves natural text structure better than simple splitting
import { CharacterTextSplitter } from "@langchain/textsplitters";
// Split by single separator
const splitter = new CharacterTextSplitter({
separator: "\n\n", // Split on double newlines
chunkSize: 1000,
chunkOverlap: 200,
});
const chunks = await splitter.splitText(text);
import { TokenTextSplitter } from "@langchain/textsplitters";
// Split based on actual token count
const splitter = new TokenTextSplitter({
chunkSize: 512, // Number of tokens, not characters
chunkOverlap: 50,
encodingName: "cl100k_base", // OpenAI's encoding
});
const chunks = await splitter.splitText(text);
// Good for precise model context window management
// 1 token ≈ 4 characters for English text, but varies
import { RecursiveCharacterTextSplitter } from "@langchain/textsplitters";
// Split markdown while preserving structure
const splitter = RecursiveCharacterTextSplitter.fromLanguage("markdown", {
chunkSize: 1000,
chunkOverlap: 200,
});
const markdown = `
# Header 1
Some content under header 1.
## Header 2
Content under header 2.
`;
const chunks = await splitter.splitText(markdown);
// Tries to keep headers with their content
import { RecursiveCharacterTextSplitter } from "@langchain/textsplitters";
import { PDFLoader } from "@langchain/community/document_loaders/fs/pdf";
// Load PDF
const loader = new PDFLoader("large-document.pdf");
const docs = await loader.load();
// Split into manageable chunks
const splitter = new RecursiveCharacterTextSplitter({
chunkSize: 1000,
chunkOverlap: 200,
});
const splitDocs = await splitter.splitDocuments(docs);
console.log(`${docs.length} pages split into ${splitDocs.length} chunks`);
// Each chunk preserves source metadata
splitDocs.forEach(chunk => {
console.log(chunk.metadata); // Includes original page number
});
import { RecursiveCharacterTextSplitter } from "@langchain/textsplitters";
// Split code while preserving structure
const jsSplitter = RecursiveCharacterTextSplitter.fromLanguage("js", {
chunkSize: 500,
chunkOverlap: 50,
});
const pythonSplitter = RecursiveCharacterTextSplitter.fromLanguage("python", {
chunkSize: 500,
chunkOverlap: 50,
});
// Uses language-specific separators (functions, classes, etc.)
import { RecursiveCharacterTextSplitter } from "@langchain/textsplitters";
// Custom splitting logic
const splitter = new RecursiveCharacterTextSplitter({
chunkSize: 1000,
chunkOverlap: 100,
separators: [
"\n\n\n", // Triple newline (section breaks)
"\n\n", // Double newline (paragraphs)
"\n", // Single newline
". ", // Sentences
" ", // Words
"", // Characters
],
});
import { RecursiveCharacterTextSplitter } from "@langchain/textsplitters";
import { MemoryVectorStore } from "langchain/vectorstores/memory";
import { OpenAIEmbeddings } from "@langchain/openai";
import { CheerioWebBaseLoader } from "@langchain/community/document_loaders/web/cheerio";
// Complete RAG pipeline
const loader = new CheerioWebBaseLoader("https://docs.example.com");
const docs = await loader.load();
const splitter = new RecursiveCharacterTextSplitter({
chunkSize: 1000,
chunkOverlap: 200,
});
const splitDocs = await splitter.splitDocuments(docs);
const vectorStore = await MemoryVectorStore.fromDocuments(
splitDocs,
new OpenAIEmbeddings()
);
// Now ready for semantic search
const results = await vectorStore.similaritySearch("query", 4);
✅ Split text intelligently
✅ Handle various formats
✅ Optimize for use case
✅ Integrate with pipelines
❌ Guarantee semantic boundaries
❌ Perfectly estimate tokens
❌ Split without losing some context
// ❌ Character count != token count
const splitter = new RecursiveCharacterTextSplitter({
chunkSize: 4000, // Characters
});
// GPT-3.5 has 4096 token limit, this may exceed it!
// ✅ Use TokenTextSplitter for precise token counts
import { TokenTextSplitter } from "@langchain/textsplitters";
const splitter = new TokenTextSplitter({
chunkSize: 4000, // Actual tokens
encodingName: "cl100k_base",
});
Fix: Use TokenTextSplitter when token precision matters.
// ❌ Chunks too small
const splitter = new RecursiveCharacterTextSplitter({
chunkSize: 100, // Very small
chunkOverlap: 0, // No overlap
});
// Chunks lack sufficient context for good retrieval
// ✅ Reasonable chunk size with overlap
const splitter = new RecursiveCharacterTextSplitter({
chunkSize: 1000, // Good size
chunkOverlap: 200, // 20% overlap
});
Fix: Use 500-2000 characters with 10-20% overlap for most cases.
// ❌ No overlap
const splitter = new RecursiveCharacterTextSplitter({
chunkSize: 1000,
chunkOverlap: 0, // Information at boundaries may be lost
});
// ✅ Use overlap to preserve context
const splitter = new RecursiveCharacterTextSplitter({
chunkSize: 1000,
chunkOverlap: 200, // 20% overlap is good default
});
Fix: Always use overlap (typically 10-20% of chunk size).
// ❌ Using splitText loses metadata
const chunks = await splitter.splitText(documentText);
// No metadata!
// ✅ Use splitDocuments to preserve metadata
const docs = [new Document({
pageContent: documentText,
metadata: { source: "file.pdf" }
})];
const chunks = await splitter.splitDocuments(docs);
// Metadata preserved!
Fix: Use splitDocuments() instead of splitText() to keep metadata.
npm install @langchain/textsplitters