文本chunk切分
更新时间:2026-05-18
文本 chunk 切分
简介
文本 chunk 切分算子,基于 llama-index SentenceSplitter 将长文本按语义边界切分为固定大小的文本块,适用于 RAG 检索增强生成的文档预处理场景。
功能描述
- 基于句子边界进行切分,保证语义完整性
- 支持 text、md(Markdown)、html 三种内容类型的预处理
- 可配置 chunk_size(目标块大小,token 数)和 chunk_overlap(块间重叠 token 数)
- 依赖 llama-index-core(
pip install llama-index-core)
算子参数
输入
| 输入 | 含义 |
|---|---|
| texts | 文本字符串数组 |
输出
| 输出 | 含义 |
|---|---|
| chunks | 切分后的文本块列表(list[string]),失败时返回空列表 |
参数
| 参数名称 | 类型 | 默认值 | 描述 |
|---|---|---|---|
| content_type | str | "text" | 输入内容类型:text(纯文本)、md(Markdown)、html(HTML) |
| chunk_size | int | 500 | 每个 chunk 的最大 token 数 |
| chunk_overlap | int | 50 | 相邻 chunk 之间的重叠 token 数,保证上下文连续性 |
调用示例
Plain Text
1from __future__ import annotations
2
3import os
4
5import daft
6from daft import col
7
8from daft.aihc.common.udf import aihc_udf
9from daft.aihc.functions.text.chunk_text_sentence_splitter import ChunkTextSentenceSplitter
10
11if __name__ == "__main__":
12 if os.getenv("DAFT_RUNNER", "native") == "ray":
13 import ray
14 ray.init(dashboard_host="0.0.0.0", ignore_reinit_error=True)
15 daft.set_runner_ray()
16 daft.set_execution_config(actor_udf_ready_timeout=6000, min_cpu_per_task=0)
17
18 samples = {
19 "text": [
20 "This is a long article. " * 100,
21 "# Title\n\nSection 1 content here.\n\n## Sub-section\n\nMore content." * 20,
22 ]
23 }
24 ds = daft.from_pydict(samples)
25 constructor_kwargs = {
26 "content_type": "text",
27 "chunk_size": 500,
28 "chunk_overlap": 50,
29 }
30 ds = ds.with_column(
31 "chunks",
32 aihc_udf(
33 ChunkTextSentenceSplitter,
34 construct_args=constructor_kwargs,
35 num_cpus=1,
36 concurrency=4,
37 batch_size=32,
38 )(col("text")),
39 )
40 ds.show()
评价此篇文章
