MCPcopy Create free account
hub / github.com/DSGWJQ/Feagent / _chunk_document

Method _chunk_document

scripts/ingest_docs.py:149–183  ·  view source on GitHub ↗

将文档切分为多个块

(self, content: str)

Source from the content-addressed store, hash-verified

147 return None
148
149 async def _chunk_document(self, content: str) -> list[str]:
150 """将文档切分为多个块"""
151 # 使用token数量来更精确地切分
152 chunks = []
153 current_chunk = ""
154 current_tokens = 0
155
156 lines = content.split("\n")
157 for line in lines:
158 line_tokens = self._count_tokens(line)
159
160 # 如果当前块为空,直接添加
161 if not current_chunk:
162 current_chunk = line
163 current_tokens = line_tokens
164 # 如果添加后不超过限制,添加到当前块
165 elif current_tokens + line_tokens + 1 <= self.chunk_size:
166 current_chunk += "\n" + line
167 current_tokens += line_tokens + 1
168 # 否则保存当前块并开始新块
169 else:
170 chunks.append(current_chunk.strip())
171 current_chunk = line
172 current_tokens = line_tokens
173
174 # 添加最后一个块
175 if current_chunk.strip():
176 chunks.append(current_chunk.strip())
177
178 # 使用langchain的切分器作为后备
179 if not chunks:
180 chunks = self.text_splitter.split_text(content)
181
182 logger.info(f"Split document into {len(chunks)} chunks")
183 return chunks
184
185 async def _generate_embeddings(self, chunks: list[str]) -> list[list[float]]:
186 """生成文本块的向量嵌入"""

Callers 2

ingest_fileMethod · 0.95
ingest_urlMethod · 0.95

Calls 4

_count_tokensMethod · 0.95
split_textMethod · 0.80
appendMethod · 0.45
infoMethod · 0.45

Tested by

no test coverage detected