-
Notifications
You must be signed in to change notification settings - Fork 144
Expand file tree
/
Copy pathadapter.py
More file actions
1685 lines (1440 loc) · 66.4 KB
/
adapter.py
File metadata and controls
1685 lines (1440 loc) · 66.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# SPDX-FileCopyrightText: Copyright (c) 2025-2026, NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""
Foundational RAG adapter for NVIDIA RAG Blueprint endpoints.
Provides retrieval and ingestion adapters for the hosted RAG Blueprint service.
Requires a deployed RAG Blueprint: https://github.com/NVIDIA-AI-Blueprints/rag
Prerequisites:
Deploy the NVIDIA RAG Blueprint first:
https://github.com/NVIDIA-AI-Blueprints/rag/blob/main/docs/deploy-docker-self-hosted.md
Configuration:
rag_url: Base URL of the RAG server
- ingestor-server: port 8082 (e.g., "http://ingestor-server:8082/v1")
- rag-server: port 8081 (e.g., "http://rag-server:8081/v1")
api_key: Optional API key for authentication
timeout: Request timeout in seconds (default: 300)
API Reference (ingestor-server :8082):
- POST /documents - Upload documents (async, returns task_id)
- GET /documents - List documents in a collection
- DELETE /documents - Delete documents by name
- GET /status - Get ingestion task status
- GET /collections - List all collections
- POST /collection - Create a new collection
- DELETE /collections - Delete collections
- GET /health - Health check
API Reference (rag-server :8081):
- POST /search - Search/retrieve chunks from collections
- GET /health - Health check
Repository: https://github.com/NVIDIA-AI-Blueprints/rag
"""
import asyncio
import json
import logging
import os
import re
import threading
import uuid
from datetime import datetime
from functools import partial
from pathlib import Path
from typing import Any
import requests
import urllib3
from requests.adapters import HTTPAdapter
from urllib3.util.retry import Retry
from aiq_agent.knowledge.base import BaseIngestor
from aiq_agent.knowledge.base import BaseRetriever
from aiq_agent.knowledge.base import TTLCleanupMixin
from aiq_agent.knowledge.factory import register_ingestor
from aiq_agent.knowledge.factory import register_retriever
from aiq_agent.knowledge.schema import Chunk
from aiq_agent.knowledge.schema import CollectionInfo
from aiq_agent.knowledge.schema import ContentType
from aiq_agent.knowledge.schema import FileInfo
from aiq_agent.knowledge.schema import FileProgress
from aiq_agent.knowledge.schema import FileStatus
from aiq_agent.knowledge.schema import IngestionJobStatus
from aiq_agent.knowledge.schema import JobState
from aiq_agent.knowledge.schema import RetrievalResult
# Suppress InsecureRequestWarning when verify_ssl=False
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
logger = logging.getLogger(__name__)
# Default configuration
# Note: NVIDIA RAG Blueprint has two servers:
# - Ingestion Server (port 8082): documents, collections, status
# - Query Server (port 8081): generate, search, retrieval
# @environment_variable RAG_SERVER_URL
# @category Knowledge Layer
# @type str
# @default http://localhost:8081/v1
# @required false
# Base URL for the Foundational RAG query server.
DEFAULT_RAG_URL = os.environ.get("RAG_SERVER_URL", "http://localhost:8081/v1")
# @environment_variable RAG_INGEST_URL
# @category Knowledge Layer
# @type str
# @default http://localhost:8082/v1
# @required false
# Base URL for the Foundational RAG ingestion server.
DEFAULT_INGEST_URL = os.environ.get("RAG_INGEST_URL", "http://localhost:8082/v1")
DEFAULT_TIMEOUT = 300
# Retrieval settings for reranking
VDB_TOP_K_MULTIPLIER = 10
MAX_VDB_TOP_K = 100
# Collection TTL settings (configurable via environment)
COLLECTION_TTL_HOURS = float(os.environ.get("AIQ_COLLECTION_TTL_HOURS", "24"))
TTL_CLEANUP_INTERVAL_SECONDS = int(os.environ.get("AIQ_TTL_CLEANUP_INTERVAL_SECONDS", "3600"))
# Completed jobs are retained for this long so list_files can include failed
# files, then pruned to avoid unbounded memory growth.
JOB_RETENTION_SECONDS = 3600 # 1 hour
# Client-side summary settings (runs parallel to FRAG ingestion)
SUMMARY_MAX_CHARS = 4000
SUMMARY_MAX_PAGES = 2
SUMMARIZABLE_EXTENSIONS = {".pdf", ".docx", ".pptx", ".txt", ".md"}
def _create_session(timeout: int = DEFAULT_TIMEOUT, verify_ssl: bool = True) -> requests.Session:
"""Create a requests session with retry logic.
Args:
timeout: Request timeout in seconds.
verify_ssl: Whether to verify SSL certificates. Set False for self-signed certs.
"""
session = requests.Session()
# Disable SSL verification if requested (for self-signed certificates)
session.verify = verify_ssl
# Configure retry strategy for resilience
retries = Retry(
total=3,
backoff_factor=0.5,
status_forcelist=[500, 502, 503, 504],
allowed_methods=["HEAD", "GET", "POST", "PUT", "DELETE", "PATCH"],
)
adapter = HTTPAdapter(max_retries=retries)
session.mount("http://", adapter)
session.mount("https://", adapter)
return session
def _extract_text(file_path: str, max_chars: int = SUMMARY_MAX_CHARS) -> str | None:
"""
Extract text from a file for summary generation.
Supports PDF, DOCX, PPTX, TXT, and Markdown files.
Args:
file_path: Path to the file.
max_chars: Maximum characters to return.
Returns:
Extracted text or None if extraction fails or format is unsupported.
"""
suffix = Path(file_path).suffix.lower()
try:
if suffix == ".pdf":
try:
import pypdf
except ImportError:
logger.debug("pypdf not installed, skipping PDF text extraction")
return None
with open(file_path, "rb") as f:
reader = pypdf.PdfReader(f)
text = ""
for page in reader.pages[:SUMMARY_MAX_PAGES]:
text += (page.extract_text() or "") + "\n"
if len(text) > max_chars:
break
return text[:max_chars].strip() or None
elif suffix == ".docx":
try:
import docx2txt
except ImportError:
logger.debug("docx2txt not installed, skipping DOCX text extraction")
return None
text = docx2txt.process(file_path) or ""
return text[:max_chars].strip() or None
elif suffix == ".pptx":
try:
from pptx import Presentation
except ImportError:
logger.debug("python-pptx not installed, skipping PPTX text extraction")
return None
prs = Presentation(file_path)
text = ""
for slide in prs.slides:
for shape in slide.shapes:
if shape.has_text_frame:
text += shape.text_frame.text + "\n"
if len(text) > max_chars:
break
if len(text) > max_chars:
break
return text[:max_chars].strip() or None
elif suffix in (".txt", ".md"):
with open(file_path, encoding="utf-8", errors="replace") as f:
text = f.read(max_chars)
return text.strip() or None
except Exception as e:
logger.debug("Text extraction failed for %s: %s", file_path, e)
return None
def _generate_file_summary(file_path: str, llm=None) -> str | None:
"""
Generate one-sentence summary from a local file.
Runs client-side in parallel with FRAG upload. Supports PDF, DOCX,
PPTX, TXT, and Markdown files.
Args:
file_path: Path to the file to summarize.
llm: LangChain LLM object. Required - no default fallback.
Returns:
One-sentence summary or None if unsupported format, no LLM, or generation fails.
"""
if llm is None:
return None
if Path(file_path).suffix.lower() not in SUMMARIZABLE_EXTENSIONS:
return None
text = _extract_text(file_path)
if not text:
return None
prompt = f"Summarize in ONE sentence:\n\n{text}"
try:
response = llm.invoke(prompt)
content = response.content if hasattr(response, "content") else str(response)
return content.strip()
except Exception as e:
logger.warning("Summary generation via LLM failed: %s", e)
return None
@register_retriever("foundational_rag")
class FoundationalRagRetriever(BaseRetriever):
"""
Retriever adapter that calls hosted NVIDIA RAG Blueprint endpoints.
This retriever makes HTTP calls to the RAG server's /search endpoint
and converts responses to the universal Chunk schema.
Requires a deployed RAG Blueprint server. See:
https://github.com/NVIDIA-AI-Blueprints/rag/blob/main/docs/deploy-docker-self-hosted.md
"""
def __init__(self, config: dict[str, Any] | None = None):
"""
Initialize the RAG server retriever.
Args:
config: Configuration dictionary with:
- rag_url: Base URL of the RAG Query server (port 8081)
- api_key: Optional API key for authentication
- timeout: Request timeout in seconds
- verify_ssl: Whether to verify SSL certificates (default: True)
"""
super().__init__(config)
self.rag_url = self.config.get("rag_url", DEFAULT_RAG_URL).rstrip("/")
# @environment_variable RAG_API_KEY
# @category API Keys
# @type str
# @required false
# Optional API key for authenticating with the Foundational RAG backend.
self.api_key = self.config.get("api_key", os.environ.get("RAG_API_KEY"))
self.timeout = self.config.get("timeout", DEFAULT_TIMEOUT)
self.verify_ssl = self.config.get("verify_ssl", True)
self.session = _create_session(self.timeout, self.verify_ssl)
logger.info(
f"FoundationalRagRetriever initialized with Query URL: {self.rag_url}, verify_ssl={self.verify_ssl}"
)
@property
def backend_name(self) -> str:
return "foundational_rag"
def _get_headers(self) -> dict[str, str]:
"""Get request headers including optional auth."""
headers = {
"Content-Type": "application/json",
"Accept": "application/json",
}
if self.api_key:
headers["Authorization"] = f"Bearer {self.api_key}"
return headers
async def retrieve(
self,
query: str,
collection_name: str,
top_k: int = 10,
filters: dict[str, Any] | None = None,
) -> RetrievalResult:
"""
Retrieve documents from the RAG server using POST /search.
The RAG Blueprint search API returns document chunks ranked by relevance.
Uses reranking for better results.
Args:
query: Search query string.
collection_name: Target collection name.
top_k: Maximum number of results (maps to reranker_top_k).
filters: Optional metadata filters (maps to filter_expr).
Returns:
RetrievalResult with normalized Chunk objects.
"""
try:
endpoint = f"{self.rag_url}/search"
# Build payload per RAG Blueprint /search API spec
payload = {
"query": query,
"collection_names": [collection_name], # API expects array
"reranker_top_k": top_k, # Final number of results after reranking
"vdb_top_k": min(top_k * VDB_TOP_K_MULTIPLIER, MAX_VDB_TOP_K),
"enable_reranker": True, # Enable reranking for better results
}
# Add filter expression if provided
if filters:
if isinstance(filters, str):
payload["filter_expr"] = filters
elif "filter_expr" in filters:
payload["filter_expr"] = filters["filter_expr"]
else:
# Try to build filter expression from dict
# e.g., {"category": "AI"} -> "category == 'AI'"
filter_parts = []
for k, v in filters.items():
if isinstance(v, str):
filter_parts.append(f'{k} == "{v}"')
else:
filter_parts.append(f"{k} == {v}")
if filter_parts:
payload["filter_expr"] = " and ".join(filter_parts)
logger.debug(f"Search request to {endpoint}: {payload}")
# Run blocking HTTP call in thread pool to avoid blocking the event loop
loop = asyncio.get_event_loop()
response = await loop.run_in_executor(
None,
partial(
self.session.post,
endpoint,
json=payload,
headers=self._get_headers(),
timeout=self.timeout,
),
)
response.raise_for_status()
data = response.json()
if data is None:
data = {}
logger.debug(f"Search response: total_results={data.get('total_results', 0)}")
# Convert RAG server response to universal schema
chunks = self._parse_search_response(data, query)
return RetrievalResult(
chunks=chunks,
total_tokens=sum(len(c.content.split()) for c in chunks),
query=query,
backend=self.backend_name,
success=True,
)
except requests.exceptions.ConnectionError as e:
logger.error(f"Cannot connect to RAG server at {self.rag_url}: {e}")
return RetrievalResult(
chunks=[],
total_tokens=0,
query=query,
backend=self.backend_name,
success=False,
error_message=f"Cannot connect to RAG server: {str(e)[:100]}",
)
except requests.exceptions.Timeout as e:
logger.error(f"RAG server request timed out: {e}")
return RetrievalResult(
chunks=[],
total_tokens=0,
query=query,
backend=self.backend_name,
success=False,
error_message=f"Request timed out after {self.timeout}s",
)
except requests.exceptions.HTTPError as e:
logger.error(f"RAG server returned error: {e}")
return RetrievalResult(
chunks=[],
total_tokens=0,
query=query,
backend=self.backend_name,
success=False,
error_message=f"Server error: {str(e)[:100]}",
)
except requests.exceptions.RequestException as e:
logger.error(f"RAG server retrieval failed: {e}")
return RetrievalResult(
chunks=[],
total_tokens=0,
query=query,
backend=self.backend_name,
success=False,
error_message=f"Request failed: {str(e)[:100]}",
)
def _parse_search_response(self, data: dict[str, Any] | None, query: str) -> list[Chunk]:
"""
Parse RAG server /search response into Chunk objects.
Response format:
{
"total_results": 3,
"results": [
{
"chunk_id": "...",
"document_id": "...",
"document_name": "...",
"document_type": "text",
"content": "...",
"page_number": 15,
"collection_name": "...",
"score": 0.89,
"metadata": {...}
}
]
}
"""
chunks = []
if data is None:
data = {}
results = data.get("results", [])
for i, result in enumerate(results):
chunk = self._normalize_search_result(result, idx=i)
if chunk:
chunks.append(chunk)
return chunks
def _normalize_search_result(self, result: dict[str, Any], idx: int = 0) -> Chunk | None:
"""
Convert a single RAG server search result to universal Chunk format.
Args:
result: A SourceResult from the /search response.
idx: Index for fallback chunk ID.
Returns:
Normalized Chunk object.
"""
if not isinstance(result, dict):
return None
# Extract fields from the SourceResult schema (use "or {}" so null values become dict)
document_name_raw = result.get("document_name", "unknown")
document_type = result.get("document_type", "text").lower()
content = result.get("content", "")
score = result.get("score", 0.0)
collection_name = result.get("collection_name", "")
metadata = result.get("metadata") or {}
content_metadata = metadata.get("content_metadata") or {}
# Strip temp file prefix (tmp + 8 random chars + _) for display; keep raw for delete ops
display_name = re.sub(r"^tmp.{8}_", "", document_name_raw)
# Extract page_number from multiple locations (FRAG puts it in metadata)
page_number = result.get("page_number") or metadata.get("page_number") or content_metadata.get("page_number")
if page_number in (-1, 0, None):
page_number = None
# Generate chunk_id for citation tracking
doc_base = Path(display_name).stem if display_name != "unknown" else "doc"
if page_number:
chunk_id = result.get("chunk_id") or f"{doc_base}_p{page_number}_{idx}"
else:
chunk_id = result.get("chunk_id") or f"{doc_base}_{idx}"
# Determine content type from document_type
if document_type == "image" or "image" in document_type:
content_type = ContentType.IMAGE
elif document_type == "table" or "table" in document_type:
content_type = ContentType.TABLE
elif document_type == "chart" or "chart" in document_type:
content_type = ContentType.CHART
else:
content_type = ContentType.TEXT
# Build display citation
if page_number and page_number > 0:
display_citation = f"[{display_name}, p.{page_number}]"
else:
display_citation = f"[{display_name}]"
document_id = result.get("document_id") or document_name_raw
return Chunk(
chunk_id=chunk_id,
content=content if content else "",
score=float(score),
file_name=display_name,
page_number=page_number,
display_citation=display_citation,
content_type=content_type,
metadata={
"document_id": document_id,
"document_name_raw": document_name_raw,
"collection_name": collection_name,
"page_count": (content_metadata.get("hierarchy") or {}).get("page_count"),
"language": (content_metadata.get("text_metadata") or {}).get("language"),
"source_metadata": metadata,
},
)
def normalize(self, raw_result: Any, idx: int = 0) -> Chunk | None:
"""
Convert RAG server document to universal Chunk format.
Args:
raw_result: Raw document from RAG server response.
idx: Index for generating chunk ID.
Returns:
Normalized Chunk object.
"""
if isinstance(raw_result, dict):
return self._normalize_search_result(raw_result, idx)
if isinstance(raw_result, str):
return Chunk(
chunk_id=f"rag_{idx}",
content=raw_result,
score=1.0,
file_name="unknown",
display_citation="[RAG Result]",
content_type=ContentType.TEXT,
)
return None
async def health_check(self) -> bool:
"""Check if the RAG server is healthy."""
try:
loop = asyncio.get_running_loop()
response = await loop.run_in_executor(
None,
lambda: self.session.get(
f"{self.rag_url}/health",
headers=self._get_headers(),
timeout=10,
),
)
return response.status_code == 200
except Exception as e:
logger.warning(f"RAG server health check failed: {e}")
return False
@register_ingestor("foundational_rag")
class FoundationalRagIngestor(TTLCleanupMixin, BaseIngestor):
"""
Ingestor adapter that calls hosted NVIDIA RAG Blueprint endpoints.
This ingestor makes HTTP calls to the RAG server's document management
and collection management endpoints, enabling remote ingestion and
file management.
API Endpoints Used:
- POST /documents: Upload files for ingestion
- GET /documents: List files in a collection
- DELETE /documents: Delete files
- GET /status: Check ingestion task status
- GET /collections: List collections
- POST /collection: Create collection
- DELETE /collections: Delete collections
"""
def __init__(self, config: dict[str, Any] | None = None):
"""
Initialize the RAG server ingestor.
Args:
config: Configuration dictionary with:
- rag_url: Base URL of the RAG Query server (port 8081) - for backwards compat
- ingest_url: Base URL of the RAG Ingestion server (port 8082)
- api_key: Optional API key for authentication
- timeout: Request timeout in seconds
- chunk_size: Default chunk size for ingestion
- chunk_overlap: Default chunk overlap
"""
super().__init__(config)
# Support both rag_url (legacy) and ingest_url (explicit)
# If only rag_url is provided, try to derive ingest_url by changing port
rag_url = self.config.get("rag_url", DEFAULT_RAG_URL).rstrip("/")
ingest_url = self.config.get("ingest_url", DEFAULT_INGEST_URL).rstrip("/")
# If ingest_url not explicitly set but rag_url points to 8081, auto-switch to 8082
if "ingest_url" not in self.config and ":8081" in rag_url:
ingest_url = rag_url.replace(":8081", ":8082")
elif "ingest_url" not in self.config and ":8082" in rag_url:
# User provided 8082 directly as rag_url, use it for ingestion
ingest_url = rag_url
self.rag_url = ingest_url # Ingestor uses ingestion server
self.api_key = self.config.get("api_key", os.environ.get("RAG_API_KEY"))
self.timeout = self.config.get("timeout", DEFAULT_TIMEOUT)
self.chunk_size = self.config.get("chunk_size", 512)
self.chunk_overlap = self.config.get("chunk_overlap", 150)
self.generate_summary = self.config.get("generate_summary", False)
self.summary_llm = self.config.get("summary_llm") # Resolved LangChain LLM (or None)
self.verify_ssl = self.config.get("verify_ssl", True)
self.session = _create_session(self.timeout, self.verify_ssl)
# Local job tracking (for jobs submitted through this adapter)
self._jobs: dict[str, IngestionJobStatus] = {}
self._lock = threading.RLock()
# Start background TTL cleanup task
self._start_ttl_cleanup_task(COLLECTION_TTL_HOURS, TTL_CLEANUP_INTERVAL_SECONDS)
llm_info = "configured" if self.summary_llm else "not configured"
logger.info(
"FoundationalRagIngestor initialized: url=%s, generate_summary=%s, summary_llm=%s, verify_ssl=%s",
self.rag_url,
self.generate_summary,
llm_info,
self.verify_ssl,
)
@property
def backend_name(self) -> str:
return "foundational_rag"
def _prune_completed_jobs(self) -> None:
"""Remove completed/failed jobs older than JOB_RETENTION_SECONDS."""
now = datetime.now()
with self._lock:
stale = [
jid
for jid, job in self._jobs.items()
if job.completed_at is not None and (now - job.completed_at).total_seconds() > JOB_RETENTION_SECONDS
]
for jid in stale:
del self._jobs[jid]
if stale:
logger.debug("Pruned %d completed job(s) from tracking", len(stale))
def _get_headers(self, content_type: str | None = None) -> dict[str, str]:
"""Get request headers including optional auth."""
headers = {"Accept": "application/json"}
if content_type:
headers["Content-Type"] = content_type
if self.api_key:
headers["Authorization"] = f"Bearer {self.api_key}"
return headers
# =========================================================================
# Job Submission & Status (Required by BaseIngestor)
# =========================================================================
def submit_job(
self,
file_paths: list[str],
collection_name: str,
config: dict[str, Any] | None = None,
) -> str:
"""
Submit files for ingestion via the RAG server.
This uploads all files and returns a tracking job ID.
The RAG server handles ingestion asynchronously.
Args:
file_paths: List of local file paths to ingest.
collection_name: Target collection name.
config: Optional ingestion configuration (supports original_filenames).
Returns:
Job ID for status tracking.
"""
job_id = str(uuid.uuid4())
now = datetime.now()
config = config or {}
# Original filenames for temp file uploads (avoids tmp prefix)
original_filenames = config.get("original_filenames", [])
# Create initial job status using original filenames when available
file_details = []
for i, fp in enumerate(file_paths):
file_name = original_filenames[i] if i < len(original_filenames) else Path(fp).name
file_details.append(
FileProgress(
file_id=file_name,
file_name=file_name,
status=FileStatus.UPLOADING,
)
)
job_status = IngestionJobStatus(
job_id=job_id,
status=JobState.PENDING,
submitted_at=now,
total_files=len(file_paths),
processed_files=0,
file_details=file_details,
collection_name=collection_name,
backend=self.backend_name,
metadata={"rag_url": self.rag_url},
)
with self._lock:
self._jobs[job_id] = job_status
# Upload files in background
thread = threading.Thread(
target=self._upload_files_async,
args=(job_id, file_paths, collection_name, config),
daemon=True,
)
thread.start()
return job_id
def _upload_files_async(
self,
job_id: str,
file_paths: list[str],
collection_name: str,
config: dict[str, Any] | None = None,
):
"""Background thread to upload files to RAG server."""
from concurrent.futures import ThreadPoolExecutor
with self._lock:
job = self._jobs.get(job_id)
if not job:
return
job.status = JobState.PROCESSING
job.started_at = datetime.now()
config = config or {}
# Original filenames for temp file uploads
original_filenames = config.get("original_filenames", [])
task_ids = []
# Track summary futures for parallel generation
summary_futures: dict[int, tuple[str, Any]] = {} # index -> (file_name, future)
executor = None
if self.generate_summary:
executor = ThreadPoolExecutor(max_workers=min(len(file_paths), 4))
# Pre-loop: update statuses and kick off summary generation
file_handles = []
files_payload = []
for i, file_path in enumerate(file_paths):
file_name = original_filenames[i] if i < len(original_filenames) else Path(file_path).name
file_path_obj = Path(file_path)
job.file_details[i].status = FileStatus.INGESTING
# Start client-side summary generation in parallel (if enabled)
if self.generate_summary and file_path_obj.suffix.lower() in SUMMARIZABLE_EXTENSIONS:
logger.info("Starting client-side summary generation")
future = executor.submit(_generate_file_summary, file_path, self.summary_llm)
summary_futures[i] = (file_name, future)
# Open file handle for batch upload
try:
fh = open(file_path, "rb")
file_handles.append(fh)
files_payload.append(("documents", (file_name, fh, "application/octet-stream")))
except Exception as e:
logger.error(f"Failed to open file {file_path}: {e}")
for fh in file_handles:
fh.close()
raise
# Single batch upload - all files in one POST request
# This matches the RAG UI behavior and prevents concurrent ingestion deadlocks
try:
data_payload = {
"collection_name": collection_name,
"blocking": False,
"split_options": {
"chunk_size": config.get("chunk_size", self.chunk_size),
"chunk_overlap": config.get("chunk_overlap", self.chunk_overlap),
},
"custom_metadata": [],
"generate_summary": False, # Server-side summary disabled, using client-side
}
response = self.session.post(
f"{self.rag_url}/documents",
files=files_payload,
data={"data": json.dumps(data_payload)},
headers=self._get_headers(),
timeout=self.timeout,
)
response.raise_for_status()
result = response.json()
# Track the single task ID from the batch upload
task_id = result.get("task_id", "")
if task_id:
task_ids.append(task_id)
# Map single task_id to all file indices
job.metadata["task_to_file"] = {task_id: list(range(len(file_paths)))}
logger.info(f"Uploaded {len(file_paths)} file(s) to RAG server in batch, task_id: {task_id}")
except Exception as e:
logger.error(f"Batch upload failed: {e}")
for i in range(len(file_paths)):
job.file_details[i].status = FileStatus.FAILED
job.file_details[i].error_message = str(e)
job.processed_files = len(file_paths)
finally:
for fh in file_handles:
fh.close()
# Collect summaries from parallel generation and register them
if summary_futures:
from aiq_agent.knowledge import register_summary
for idx, (file_name, future) in summary_futures.items():
try:
summary = future.result(timeout=30)
if summary:
register_summary(collection_name, file_name, summary)
logger.info(f" Summary generated ({len(summary)} chars)")
except Exception as e:
logger.debug(f"Summary generation failed for {file_name}: {e}")
# Clean up executor
if executor:
executor.shutdown(wait=False)
# Store task IDs for status polling
job.metadata["task_ids"] = task_ids
# Check if all uploads failed immediately
failed_count = sum(1 for fd in job.file_details if fd.status == FileStatus.FAILED)
if failed_count == job.total_files:
job.status = JobState.FAILED
job.error_message = "File upload failed"
job.completed_at = datetime.now()
# Otherwise keep as PROCESSING - get_job_status will poll FRAG and update
def get_job_status(self, job_id: str) -> IngestionJobStatus:
"""
Get the status of an ingestion job.
This checks local job tracking and optionally polls the
RAG server for task status updates.
Args:
job_id: Job ID from submit_job.
Returns:
Current job status.
"""
self._prune_completed_jobs()
with self._lock:
job = self._jobs.get(job_id)
if not job:
# Return a failed status for unknown jobs
return IngestionJobStatus(
job_id=job_id,
status=JobState.FAILED,
submitted_at=datetime.now(),
collection_name="unknown",
backend=self.backend_name,
error_message=f"Job {job_id} not found",
)
# If job is still processing, check RAG server task status
if job.status == JobState.PROCESSING:
task_ids = job.metadata.get("task_ids", [])
task_to_file = job.metadata.get("task_to_file", {})
for task_id in task_ids:
# Get file indices for this task (list for batch, int for legacy single-file)
file_idx_raw = task_to_file.get(task_id)
if isinstance(file_idx_raw, list):
file_indices = file_idx_raw
elif file_idx_raw is not None:
file_indices = [file_idx_raw]
else:
file_indices = []
try:
response = self.session.get(
f"{self.rag_url}/status",
params={"task_id": task_id},
headers=self._get_headers("application/json"),
timeout=30,
)
if response.status_code == 200:
status_data = response.json()
state = status_data.get("state", "").lower()
logger.debug(f"FRAG task {task_id[:8]} state={state}")
if state in ("success", "completed", "finished"):
result = status_data.get("result", {})
failed_docs = result.get("failed_documents", [])
failed_names: dict[str, str] = {}
for fdoc in failed_docs:
fname = fdoc.get("document_name", "")
ferr = fdoc.get("error_message", "Ingestion failed")
if fname:
failed_names[fname] = ferr
if failed_names:
logger.warning(
f"FRAG task {task_id[:8]} completed with "
f"{len(failed_names)} failed file(s): {list(failed_names.keys())}"
)
if file_indices:
for idx in file_indices:
if (
idx < len(job.file_details)
and job.file_details[idx].status == FileStatus.INGESTING
):
fd = job.file_details[idx]
# Check if this file appears in failed_documents
matched_error = next(
(err for fname, err in failed_names.items() if fname == fd.file_name),
None,
)
if matched_error:
fd.status = FileStatus.FAILED
fd.error_message = matched_error
else:
fd.status = FileStatus.SUCCESS
succeeded = sum(
1
for i in file_indices
if i < len(job.file_details) and job.file_details[i].status == FileStatus.SUCCESS
)
failed = sum(
1
for i in file_indices
if i < len(job.file_details) and job.file_details[i].status == FileStatus.FAILED
)
logger.debug(f"Batch ingestion done: {succeeded} succeeded, {failed} failed")
else:
# Fallback: match by document name
docs = result.get("documents", [])
for doc in docs:
doc_name = doc.get("document_name", "")
for fd in job.file_details:
if doc_name == fd.file_name and fd.status == FileStatus.INGESTING:
fd.status = FileStatus.SUCCESS
logger.debug("File ingestion succeeded")
for fname, ferr in failed_names.items():
for fd in job.file_details:
if fname == fd.file_name and fd.status == FileStatus.INGESTING:
fd.status = FileStatus.FAILED
fd.error_message = ferr
logger.warning(f"File ingestion failed: {ferr}")
elif state == "failed":
result = status_data.get("result", {})
# Try multiple fields for error message
# FRAG puts detailed errors in result.message