导入URL文档
(self, url: str, workflow_id: str | None = None)
| 267 | return document.id |
| 268 | |
| 269 | async def ingest_url(self, url: str, workflow_id: str | None = None) -> str: |
| 270 | """导入URL文档""" |
| 271 | logger.info(f"Ingesting URL: {url}") |
| 272 | |
| 273 | # 加载文档内容 |
| 274 | content = await self._load_document_from_url(url) |
| 275 | if not content: |
| 276 | raise ValueError(f"Failed to load document from URL: {url}") |
| 277 | |
| 278 | # 生成文档ID |
| 279 | doc_id = hashlib.md5(f"url:{url}:{workflow_id}".encode()).hexdigest() |
| 280 | content_hash = await self._generate_document_hash(content) |
| 281 | |
| 282 | # 检查文档是否已存在 |
| 283 | existing_doc = await self.repository.find_document_by_id(doc_id) |
| 284 | if existing_doc: |
| 285 | existing_hash = ( |
| 286 | existing_doc.metadata.get("content_hash") if existing_doc.metadata else None |
| 287 | ) |
| 288 | if existing_hash == content_hash: |
| 289 | logger.info(f"URL {url} already exists and unchanged") |
| 290 | return doc_id |
| 291 | |
| 292 | # 创建文档实体 |
| 293 | document = Document.create( |
| 294 | title=url, |
| 295 | content=content, |
| 296 | source=DocumentSource.URL, |
| 297 | workflow_id=workflow_id, |
| 298 | metadata={ |
| 299 | "content_hash": content_hash, |
| 300 | "ingestion_time": datetime.now().isoformat(), |
| 301 | }, |
| 302 | ) |
| 303 | |
| 304 | # 切分文档、生成嵌入并保存 |
| 305 | chunks = await self._chunk_document(content) |
| 306 | embeddings = await self._generate_embeddings(chunks) |
| 307 | |
| 308 | await self.repository.save_document(document) |
| 309 | await self.repository.delete_chunks_by_document_id(document.id) |
| 310 | |
| 311 | for i, (chunk_text, embedding) in enumerate(zip(chunks, embeddings, strict=False)): |
| 312 | chunk = DocumentChunk.create( |
| 313 | document_id=document.id, |
| 314 | content=chunk_text, |
| 315 | embedding=embedding, |
| 316 | chunk_index=i, |
| 317 | metadata={ |
| 318 | "token_count": self._count_tokens(chunk_text), |
| 319 | }, |
| 320 | ) |
| 321 | await self.repository.save_document_chunk(chunk) |
| 322 | |
| 323 | document.mark_processed() |
| 324 | await self.repository.update_document(document) |
| 325 | |
| 326 | logger.info(f"Successfully ingested URL {url} with {len(chunks)} chunks") |
no test coverage detected