导入单个文件
(self, file_path: str, workflow_id: str | None = None)
| 193 | return embeddings |
| 194 | |
| 195 | async def ingest_file(self, file_path: str, workflow_id: str | None = None) -> str: |
| 196 | """导入单个文件""" |
| 197 | logger.info(f"Ingesting file: {file_path}") |
| 198 | |
| 199 | # 加载文档内容 |
| 200 | content = await self._load_document_from_file(file_path) |
| 201 | if not content: |
| 202 | raise ValueError(f"Failed to load document: {file_path}") |
| 203 | |
| 204 | # 生成文档ID和哈希 |
| 205 | doc_id = hashlib.md5(f"{file_path}:{workflow_id}".encode()).hexdigest() |
| 206 | content_hash = await self._generate_document_hash(content) |
| 207 | |
| 208 | # 检查文档是否已存在 |
| 209 | existing_doc = await self.repository.find_document_by_id(doc_id) |
| 210 | if existing_doc: |
| 211 | # 检查内容是否有变化 |
| 212 | existing_hash = ( |
| 213 | existing_doc.metadata.get("content_hash") if existing_doc.metadata else None |
| 214 | ) |
| 215 | if existing_hash == content_hash: |
| 216 | logger.info(f"Document {file_path} already exists and unchanged") |
| 217 | return doc_id |
| 218 | |
| 219 | # 创建文档实体 |
| 220 | document = Document.create( |
| 221 | title=Path(file_path).name, |
| 222 | content=content, |
| 223 | source=DocumentSource.FILESYSTEM, |
| 224 | file_path=file_path, |
| 225 | workflow_id=workflow_id, |
| 226 | metadata={ |
| 227 | "content_hash": content_hash, |
| 228 | "file_size": os.path.getsize(file_path), |
| 229 | "ingestion_time": datetime.now().isoformat(), |
| 230 | }, |
| 231 | ) |
| 232 | |
| 233 | # 切分文档 |
| 234 | chunks = await self._chunk_document(content) |
| 235 | if not chunks: |
| 236 | raise ValueError(f"Failed to chunk document: {file_path}") |
| 237 | |
| 238 | # 生成嵌入 |
| 239 | embeddings = await self._generate_embeddings(chunks) |
| 240 | if len(embeddings) != len(chunks): |
| 241 | raise ValueError(f"Embedding count mismatch: {len(embeddings)} != {len(chunks)}") |
| 242 | |
| 243 | # 保存文档和分块 |
| 244 | await self.repository.save_document(document) |
| 245 | |
| 246 | # 删除旧的分块(如果存在) |
| 247 | await self.repository.delete_chunks_by_document_id(document.id) |
| 248 | |
| 249 | # 保存新的分块 |
| 250 | for i, (chunk_text, embedding) in enumerate(zip(chunks, embeddings, strict=False)): |
| 251 | chunk = DocumentChunk.create( |
| 252 | document_id=document.id, |
no test coverage detected