Spaces:
Sleeping
Sleeping
ingestor
Browse files- params.cfg +9 -2
- src/components/generator/generator_orchestrator.py +2 -4
- src/components/ingestor/ingestor.py +130 -0
- src/components/orchestration/nodes.py +64 -3
- src/components/orchestration/ui_adapters.py +29 -24
- src/components/orchestration/workflow.py +7 -5
- src/components/retriever/retriever_orchestrator.py +14 -7
- src/main.py +2 -6
params.cfg
CHANGED
|
@@ -1,5 +1,4 @@
|
|
| 1 |
[hf_endpoints]
|
| 2 |
-
# NOTE: The actual token should be set via the HF_TOKEN environment variable.
|
| 3 |
embedding_endpoint_url = https://f4veaarnbmqjhve9.eu-west-1.aws.endpoints.huggingface.cloud
|
| 4 |
reranker_endpoint_url = https://whikfgijnuog8fjv.eu-west-1.aws.endpoints.huggingface.cloud
|
| 5 |
|
|
@@ -8,7 +7,6 @@ reranker_endpoint_url = https://whikfgijnuog8fjv.eu-west-1.aws.endpoints.hugging
|
|
| 8 |
# for native just give url
|
| 9 |
mode = native
|
| 10 |
url = https://de438521-e2dd-43d9-b41b-b2e18299a2c0.europe-west3-0.gcp.cloud.qdrant.io:6333
|
| 11 |
-
# NOTE: The API key should be set via QDRANT_API_KEY environment variable.
|
| 12 |
port = 443
|
| 13 |
collection = allreports
|
| 14 |
|
|
@@ -25,3 +23,12 @@ INFERENCE_PROVIDER = novita
|
|
| 25 |
ORGANIZATION = GIZ
|
| 26 |
CONTEXT_META_FIELDS = filename,project_id,document_source
|
| 27 |
TITLE_META_FIELDS = filename,page
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
[hf_endpoints]
|
|
|
|
| 2 |
embedding_endpoint_url = https://f4veaarnbmqjhve9.eu-west-1.aws.endpoints.huggingface.cloud
|
| 3 |
reranker_endpoint_url = https://whikfgijnuog8fjv.eu-west-1.aws.endpoints.huggingface.cloud
|
| 4 |
|
|
|
|
| 7 |
# for native just give url
|
| 8 |
mode = native
|
| 9 |
url = https://de438521-e2dd-43d9-b41b-b2e18299a2c0.europe-west3-0.gcp.cloud.qdrant.io:6333
|
|
|
|
| 10 |
port = 443
|
| 11 |
collection = allreports
|
| 12 |
|
|
|
|
| 23 |
ORGANIZATION = GIZ
|
| 24 |
CONTEXT_META_FIELDS = filename,project_id,document_source
|
| 25 |
TITLE_META_FIELDS = filename,page
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
[ingestor]
|
| 29 |
+
# Size of each text chunk in characters
|
| 30 |
+
chunk_size = 700
|
| 31 |
+
# Overlap between consecutive chunks in characters
|
| 32 |
+
chunk_overlap = 50
|
| 33 |
+
# Text separators for splitting, comma-separated (order of preference)
|
| 34 |
+
separators = \n\n,\n,. ,! ,? , ,
|
src/components/generator/generator_orchestrator.py
CHANGED
|
@@ -205,7 +205,6 @@ class Generator:
|
|
| 205 |
error_msg = "Query cannot be empty"
|
| 206 |
return {"error": error_msg} if chatui_format else f"Error: {error_msg}"
|
| 207 |
logger.info(f"Generating answer for query: {query[:50]}")
|
| 208 |
-
logger.info(f"CHATUI format is {chatui_format}")
|
| 209 |
|
| 210 |
try:
|
| 211 |
# 1. Process Context
|
|
@@ -248,7 +247,6 @@ class Generator:
|
|
| 248 |
yield f"Error: {error_msg}"
|
| 249 |
return
|
| 250 |
logger.info(f"Generating streaming answer for query: {query[:50]}")
|
| 251 |
-
logger.info(f"CHATUI format is {chatui_format}")
|
| 252 |
if conversation_context:
|
| 253 |
logger.info(f"Using conversation context: {len(conversation_context)} chars")
|
| 254 |
|
|
@@ -278,10 +276,10 @@ class Generator:
|
|
| 278 |
if chatui_format and processed_results:
|
| 279 |
cited_numbers = parse_citations(cleaned_response)
|
| 280 |
cited_sources = extract_sources(processed_results, cited_numbers)
|
| 281 |
-
sources = create_sources_list(cited_sources,
|
| 282 |
title_metadata_fields=self.title_metadata_fields,
|
| 283 |
link_metadata_field=self.link_metadata_field)
|
| 284 |
-
|
| 285 |
yield {"event": "sources", "data": {"sources": sources}}
|
| 286 |
|
| 287 |
# Send END event for ChatUI format
|
|
|
|
| 205 |
error_msg = "Query cannot be empty"
|
| 206 |
return {"error": error_msg} if chatui_format else f"Error: {error_msg}"
|
| 207 |
logger.info(f"Generating answer for query: {query[:50]}")
|
|
|
|
| 208 |
|
| 209 |
try:
|
| 210 |
# 1. Process Context
|
|
|
|
| 247 |
yield f"Error: {error_msg}"
|
| 248 |
return
|
| 249 |
logger.info(f"Generating streaming answer for query: {query[:50]}")
|
|
|
|
| 250 |
if conversation_context:
|
| 251 |
logger.info(f"Using conversation context: {len(conversation_context)} chars")
|
| 252 |
|
|
|
|
| 276 |
if chatui_format and processed_results:
|
| 277 |
cited_numbers = parse_citations(cleaned_response)
|
| 278 |
cited_sources = extract_sources(processed_results, cited_numbers)
|
| 279 |
+
sources = create_sources_list(cited_sources,
|
| 280 |
title_metadata_fields=self.title_metadata_fields,
|
| 281 |
link_metadata_field=self.link_metadata_field)
|
| 282 |
+
logger.info(f"Sources received: {sources}")
|
| 283 |
yield {"event": "sources", "data": {"sources": sources}}
|
| 284 |
|
| 285 |
# Send END event for ChatUI format
|
src/components/ingestor/ingestor.py
ADDED
|
@@ -0,0 +1,130 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Document Ingestor Module
|
| 3 |
+
|
| 4 |
+
Processes PDF and DOCX files, extracting text and chunking for RAG pipelines.
|
| 5 |
+
Adapted from the original microservice architecture for integration into ChaBo.
|
| 6 |
+
"""
|
| 7 |
+
import os
|
| 8 |
+
import logging
|
| 9 |
+
import re
|
| 10 |
+
from io import BytesIO
|
| 11 |
+
from typing import Tuple, Dict, Any
|
| 12 |
+
|
| 13 |
+
import PyPDF2
|
| 14 |
+
from docx import Document as DocxDocument
|
| 15 |
+
from langchain_text_splitters import RecursiveCharacterTextSplitter
|
| 16 |
+
|
| 17 |
+
from components.utils import get_config_value, getconfig
|
| 18 |
+
|
| 19 |
+
logger = logging.getLogger(__name__)
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
def extract_text_from_pdf_bytes(file_content: bytes) -> Tuple[str, Dict[str, Any]]:
|
| 23 |
+
"""Extract text from PDF bytes (in memory)"""
|
| 24 |
+
try:
|
| 25 |
+
pdf_reader = PyPDF2.PdfReader(BytesIO(file_content))
|
| 26 |
+
text = ""
|
| 27 |
+
metadata = {"total_pages": len(pdf_reader.pages)}
|
| 28 |
+
|
| 29 |
+
for page_num, page in enumerate(pdf_reader.pages):
|
| 30 |
+
page_text = page.extract_text()
|
| 31 |
+
text += f"\n--- Page {page_num + 1} ---\n{page_text}"
|
| 32 |
+
|
| 33 |
+
return text, metadata
|
| 34 |
+
except Exception as e:
|
| 35 |
+
logger.error(f"PDF extraction error: {str(e)}")
|
| 36 |
+
raise Exception(f"Failed to extract text from PDF: {str(e)}")
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
def extract_text_from_docx_bytes(file_content: bytes) -> Tuple[str, Dict[str, Any]]:
|
| 40 |
+
"""Extract text from DOCX bytes (in memory)"""
|
| 41 |
+
try:
|
| 42 |
+
doc = DocxDocument(BytesIO(file_content))
|
| 43 |
+
text = ""
|
| 44 |
+
metadata = {"total_paragraphs": 0}
|
| 45 |
+
|
| 46 |
+
for paragraph in doc.paragraphs:
|
| 47 |
+
if paragraph.text.strip():
|
| 48 |
+
text += f"{paragraph.text}\n"
|
| 49 |
+
metadata["total_paragraphs"] += 1
|
| 50 |
+
|
| 51 |
+
return text, metadata
|
| 52 |
+
except Exception as e:
|
| 53 |
+
logger.error(f"DOCX extraction error: {str(e)}")
|
| 54 |
+
raise Exception(f"Failed to extract text from DOCX: {str(e)}")
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
def clean_and_chunk_text(text: str, config) -> str:
|
| 58 |
+
"""Clean text and split into chunks, returning formatted context"""
|
| 59 |
+
# Basic text cleaning
|
| 60 |
+
text = re.sub(r'\n+', '\n', text)
|
| 61 |
+
text = re.sub(r'\s+', ' ', text)
|
| 62 |
+
text = text.strip()
|
| 63 |
+
|
| 64 |
+
# Get chunking parameters from config
|
| 65 |
+
chunk_size = config.getint('ingestor', 'chunk_size', fallback=700)
|
| 66 |
+
chunk_overlap = config.getint('ingestor', 'chunk_overlap', fallback=50)
|
| 67 |
+
separators_str = config.get('ingestor', 'separators', fallback=r'\n\n,\n,. ,! ,? , ,')
|
| 68 |
+
separators = [s.strip() for s in separators_str.split(',')]
|
| 69 |
+
|
| 70 |
+
# Split text into chunks
|
| 71 |
+
text_splitter = RecursiveCharacterTextSplitter(
|
| 72 |
+
chunk_size=chunk_size,
|
| 73 |
+
chunk_overlap=chunk_overlap,
|
| 74 |
+
length_function=len,
|
| 75 |
+
separators=separators,
|
| 76 |
+
is_separator_regex=False
|
| 77 |
+
)
|
| 78 |
+
|
| 79 |
+
chunks = text_splitter.split_text(text)
|
| 80 |
+
|
| 81 |
+
# Create formatted context with chunk markers
|
| 82 |
+
context_parts = []
|
| 83 |
+
for i, chunk_text in enumerate(chunks):
|
| 84 |
+
context_parts.append(f"[Chunk {i+1}]: {chunk_text}")
|
| 85 |
+
|
| 86 |
+
return "\n\n".join(context_parts)
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
def process_document(file_content: bytes, filename: str) -> str:
|
| 90 |
+
"""
|
| 91 |
+
Main document processing function - processes file and returns chunked context.
|
| 92 |
+
|
| 93 |
+
Args:
|
| 94 |
+
file_content: Raw bytes of the uploaded file
|
| 95 |
+
filename: Name of the file (used to determine file type)
|
| 96 |
+
|
| 97 |
+
Returns:
|
| 98 |
+
Formatted chunked context string ready for RAG pipeline
|
| 99 |
+
|
| 100 |
+
Raises:
|
| 101 |
+
ValueError: If file type is unsupported
|
| 102 |
+
Exception: If processing fails
|
| 103 |
+
"""
|
| 104 |
+
try:
|
| 105 |
+
# Load config
|
| 106 |
+
config = getconfig("params.cfg")
|
| 107 |
+
|
| 108 |
+
# Extract text based on file type (in memory)
|
| 109 |
+
file_extension = os.path.splitext(filename)[1].lower()
|
| 110 |
+
|
| 111 |
+
if file_extension == '.pdf':
|
| 112 |
+
text, extraction_metadata = extract_text_from_pdf_bytes(file_content)
|
| 113 |
+
elif file_extension == '.docx':
|
| 114 |
+
text, extraction_metadata = extract_text_from_docx_bytes(file_content)
|
| 115 |
+
else:
|
| 116 |
+
raise ValueError(f"Unsupported file type: {file_extension}")
|
| 117 |
+
|
| 118 |
+
# Clean and chunk text
|
| 119 |
+
context = clean_and_chunk_text(text, config)
|
| 120 |
+
|
| 121 |
+
logger.info(
|
| 122 |
+
f"Successfully processed document {filename}: "
|
| 123 |
+
f"{len(text)} characters, {extraction_metadata}"
|
| 124 |
+
)
|
| 125 |
+
|
| 126 |
+
return context
|
| 127 |
+
|
| 128 |
+
except Exception as e:
|
| 129 |
+
logger.error(f"Document processing failed for {filename}: {str(e)}")
|
| 130 |
+
raise Exception(f"Processing failed: {str(e)}")
|
src/components/orchestration/nodes.py
CHANGED
|
@@ -2,14 +2,15 @@
|
|
| 2 |
LangGraph orchestration nodes for retrieval and generation
|
| 3 |
|
| 4 |
NEEDS TO BE UPDATED
|
| 5 |
-
"""
|
| 6 |
import logging
|
| 7 |
logger = logging.getLogger(__name__)
|
| 8 |
from datetime import datetime
|
| 9 |
import json
|
| 10 |
-
from typing import TYPE_CHECKING
|
| 11 |
from langchain_core.documents import Document
|
| 12 |
from .telemetry import extract_retriever_telemetry
|
|
|
|
| 13 |
|
| 14 |
# Assuming these Type definitions are available from state.py and retriever_orchestrator.py
|
| 15 |
if TYPE_CHECKING:
|
|
@@ -90,6 +91,16 @@ async def generate_node_streaming(state: "GraphState", generator: "Generator", *
|
|
| 90 |
query = state.get("query")
|
| 91 |
raw_docs = state.get("raw_documents", [])
|
| 92 |
metadata = state.get("metadata", {})
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 93 |
|
| 94 |
accumulated_text = ""
|
| 95 |
logger.info(f"Generation: {query[:50]}... ({len(raw_docs)} docs)")
|
|
@@ -118,7 +129,6 @@ async def generate_node_streaming(state: "GraphState", generator: "Generator", *
|
|
| 118 |
})
|
| 119 |
|
| 120 |
logger.info(f"Streaming complete in {duration:.2f}s. Length: {len(accumulated_text)}")
|
| 121 |
-
logger.debug(f"Final answer: {accumulated_text}")
|
| 122 |
|
| 123 |
except Exception as e:
|
| 124 |
duration = (datetime.now() - start_time).total_seconds()
|
|
@@ -131,6 +141,57 @@ async def generate_node_streaming(state: "GraphState", generator: "Generator", *
|
|
| 131 |
writer({"event": "error", "data": {"error": str(e)}})
|
| 132 |
|
| 133 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 134 |
|
| 135 |
# from .state import GraphState
|
| 136 |
|
|
|
|
| 2 |
LangGraph orchestration nodes for retrieval and generation
|
| 3 |
|
| 4 |
NEEDS TO BE UPDATED
|
| 5 |
+
"""
|
| 6 |
import logging
|
| 7 |
logger = logging.getLogger(__name__)
|
| 8 |
from datetime import datetime
|
| 9 |
import json
|
| 10 |
+
from typing import TYPE_CHECKING
|
| 11 |
from langchain_core.documents import Document
|
| 12 |
from .telemetry import extract_retriever_telemetry
|
| 13 |
+
from components.ingestor.ingestor_main import process_document
|
| 14 |
|
| 15 |
# Assuming these Type definitions are available from state.py and retriever_orchestrator.py
|
| 16 |
if TYPE_CHECKING:
|
|
|
|
| 91 |
query = state.get("query")
|
| 92 |
raw_docs = state.get("raw_documents", [])
|
| 93 |
metadata = state.get("metadata", {})
|
| 94 |
+
ingestor_context = state.get("ingestor_context")
|
| 95 |
+
|
| 96 |
+
# If we have ingestor_context, prepend it to raw_docs as a Document
|
| 97 |
+
if ingestor_context:
|
| 98 |
+
ingestor_doc = Document(
|
| 99 |
+
page_content=ingestor_context,
|
| 100 |
+
metadata={"source": "uploaded_file", "filename": state.get("filename", "unknown")}
|
| 101 |
+
)
|
| 102 |
+
raw_docs = [ingestor_doc] + raw_docs
|
| 103 |
+
logger.info(f"Including ingestor context ({len(ingestor_context)} chars) with retrieved docs")
|
| 104 |
|
| 105 |
accumulated_text = ""
|
| 106 |
logger.info(f"Generation: {query[:50]}... ({len(raw_docs)} docs)")
|
|
|
|
| 129 |
})
|
| 130 |
|
| 131 |
logger.info(f"Streaming complete in {duration:.2f}s. Length: {len(accumulated_text)}")
|
|
|
|
| 132 |
|
| 133 |
except Exception as e:
|
| 134 |
duration = (datetime.now() - start_time).total_seconds()
|
|
|
|
| 141 |
writer({"event": "error", "data": {"error": str(e)}})
|
| 142 |
|
| 143 |
|
| 144 |
+
async def ingest_node(state: 'GraphState') -> 'GraphState':
|
| 145 |
+
"""
|
| 146 |
+
Node to process uploaded documents (PDF, DOCX) and extract chunked context.
|
| 147 |
+
Only runs if file_content and filename are present in state.
|
| 148 |
+
"""
|
| 149 |
+
start_time = datetime.now()
|
| 150 |
+
|
| 151 |
+
file_content = state.get("file_content")
|
| 152 |
+
filename = state.get("filename")
|
| 153 |
+
metadata = state.get("metadata", {})
|
| 154 |
+
|
| 155 |
+
# Skip if no file uploaded
|
| 156 |
+
if not file_content or not filename:
|
| 157 |
+
logger.info("No file to ingest, skipping ingest_node")
|
| 158 |
+
return {}
|
| 159 |
+
|
| 160 |
+
logger.info(f"Ingesting document: {filename}")
|
| 161 |
+
|
| 162 |
+
try:
|
| 163 |
+
# Process document and get chunked context
|
| 164 |
+
ingestor_context = process_document(file_content, filename)
|
| 165 |
+
|
| 166 |
+
duration = (datetime.now() - start_time).total_seconds()
|
| 167 |
+
|
| 168 |
+
metadata.update({
|
| 169 |
+
"ingest_duration": duration,
|
| 170 |
+
"ingest_success": True,
|
| 171 |
+
"ingested_filename": filename,
|
| 172 |
+
"ingestor_context_length": len(ingestor_context)
|
| 173 |
+
})
|
| 174 |
+
|
| 175 |
+
logger.info(f"Document ingested successfully in {duration:.2f}s")
|
| 176 |
+
|
| 177 |
+
return {
|
| 178 |
+
"ingestor_context": ingestor_context,
|
| 179 |
+
"metadata": metadata
|
| 180 |
+
}
|
| 181 |
+
|
| 182 |
+
except Exception as e:
|
| 183 |
+
duration = (datetime.now() - start_time).total_seconds()
|
| 184 |
+
logger.error(f"Document ingestion failed: {str(e)}", exc_info=True)
|
| 185 |
+
|
| 186 |
+
metadata.update({
|
| 187 |
+
"ingest_duration": duration,
|
| 188 |
+
"ingest_success": False,
|
| 189 |
+
"ingest_error": str(e)
|
| 190 |
+
})
|
| 191 |
+
|
| 192 |
+
return {"ingestor_context": "", "metadata": metadata}
|
| 193 |
+
|
| 194 |
+
|
| 195 |
|
| 196 |
# from .state import GraphState
|
| 197 |
|
src/components/orchestration/ui_adapters.py
CHANGED
|
@@ -18,7 +18,9 @@ async def process_query_streaming(
|
|
| 18 |
sources_filter: str = "",
|
| 19 |
subtype_filter: str = "",
|
| 20 |
year_filter: str = "",
|
| 21 |
-
conversation_context: str = None
|
|
|
|
|
|
|
| 22 |
):
|
| 23 |
"""
|
| 24 |
Process a query through the LangGraph workflow with streaming.
|
|
@@ -46,6 +48,11 @@ async def process_query_streaming(
|
|
| 46 |
"metadata_filters": metadata_filters
|
| 47 |
}
|
| 48 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 49 |
try:
|
| 50 |
async for output in compiled_graph.astream(initial_state, stream_mode="custom"):
|
| 51 |
if output.get("event") == "data":
|
|
@@ -65,12 +72,7 @@ async def process_query_streaming(
|
|
| 65 |
|
| 66 |
async def chatui_adapter(data, compiled_graph, max_turns: int = 3, max_chars: int = 8000):
|
| 67 |
"""Text-only adapter for ChatUI with structured message support"""
|
| 68 |
-
logger.
|
| 69 |
-
logger.info("CHATUI_ADAPTER CALLED - Request reached adapter function")
|
| 70 |
-
logger.info(f"Data type: {type(data)}")
|
| 71 |
-
logger.info(f"Data repr: {repr(data)[:500]}")
|
| 72 |
-
logger.info(f"Data dict: {data.__dict__ if hasattr(data, '__dict__') else 'N/A'}")
|
| 73 |
-
logger.info("=" * 80)
|
| 74 |
|
| 75 |
try:
|
| 76 |
# Handle both dict and object access patterns
|
|
@@ -83,10 +85,6 @@ async def chatui_adapter(data, compiled_graph, max_turns: int = 3, max_chars: in
|
|
| 83 |
messages_value = getattr(data, 'messages', None)
|
| 84 |
preprompt_value = getattr(data, 'preprompt', None)
|
| 85 |
|
| 86 |
-
logger.info(f"Extracted - text: {text_value[:100] if text_value else 'None'}")
|
| 87 |
-
logger.info(f"Extracted - messages count: {len(messages_value) if messages_value else 0}")
|
| 88 |
-
logger.info(f"Extracted - preprompt: {preprompt_value[:100] if preprompt_value else 'None'}")
|
| 89 |
-
|
| 90 |
# Convert dict messages to objects if needed
|
| 91 |
messages = []
|
| 92 |
if messages_value:
|
|
@@ -99,19 +97,21 @@ async def chatui_adapter(data, compiled_graph, max_turns: int = 3, max_chars: in
|
|
| 99 |
else:
|
| 100 |
messages.append(msg)
|
| 101 |
|
| 102 |
-
logger.info(f"Context: {messages}")
|
| 103 |
# Extract latest user query
|
| 104 |
user_messages = [msg for msg in messages if msg.role == 'user']
|
| 105 |
query = user_messages[-1].content if user_messages else text_value
|
| 106 |
|
| 107 |
-
#
|
| 108 |
-
|
| 109 |
-
|
| 110 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 111 |
|
| 112 |
# Build conversation context for generation (last N turns)
|
| 113 |
conversation_context = build_conversation_context(messages, max_turns=max_turns, max_chars=max_chars)
|
| 114 |
-
logger.info(f"Context: {conversation_context}")
|
| 115 |
full_response = ""
|
| 116 |
sources_collected = None
|
| 117 |
|
|
@@ -173,8 +173,6 @@ async def chatui_file_adapter(data, compiled_graph, max_turns: int = 3, max_char
|
|
| 173 |
# Extract query - prefer structured messages
|
| 174 |
conversation_context = None
|
| 175 |
if messages_value and len(messages_value) > 0:
|
| 176 |
-
logger.info("Using structured messages")
|
| 177 |
-
|
| 178 |
# Convert dict messages to objects
|
| 179 |
messages = []
|
| 180 |
for msg in messages_value:
|
|
@@ -189,9 +187,14 @@ async def chatui_file_adapter(data, compiled_graph, max_turns: int = 3, max_char
|
|
| 189 |
user_messages = [msg for msg in messages if msg.role == 'user']
|
| 190 |
query = user_messages[-1].content if user_messages else text_value
|
| 191 |
|
| 192 |
-
|
| 193 |
-
|
| 194 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 195 |
|
| 196 |
conversation_context = build_conversation_context(messages, max_turns=max_turns, max_chars=max_chars)
|
| 197 |
else:
|
|
@@ -219,12 +222,14 @@ async def chatui_file_adapter(data, compiled_graph, max_turns: int = 3, max_char
|
|
| 219 |
async for result in process_query_streaming(
|
| 220 |
compiled_graph=compiled_graph,
|
| 221 |
query=query,
|
| 222 |
-
file_upload=None,
|
| 223 |
reports_filter="",
|
| 224 |
sources_filter="",
|
| 225 |
subtype_filter="",
|
| 226 |
year_filter="",
|
| 227 |
-
conversation_context=conversation_context
|
|
|
|
|
|
|
| 228 |
):
|
| 229 |
if isinstance(result, dict):
|
| 230 |
result_type = result.get("type", "data")
|
|
|
|
| 18 |
sources_filter: str = "",
|
| 19 |
subtype_filter: str = "",
|
| 20 |
year_filter: str = "",
|
| 21 |
+
conversation_context: str = None,
|
| 22 |
+
file_content: bytes = None,
|
| 23 |
+
filename: str = None
|
| 24 |
):
|
| 25 |
"""
|
| 26 |
Process a query through the LangGraph workflow with streaming.
|
|
|
|
| 48 |
"metadata_filters": metadata_filters
|
| 49 |
}
|
| 50 |
|
| 51 |
+
# Add file content if present
|
| 52 |
+
if file_content and filename:
|
| 53 |
+
initial_state["file_content"] = file_content
|
| 54 |
+
initial_state["filename"] = filename
|
| 55 |
+
|
| 56 |
try:
|
| 57 |
async for output in compiled_graph.astream(initial_state, stream_mode="custom"):
|
| 58 |
if output.get("event") == "data":
|
|
|
|
| 72 |
|
| 73 |
async def chatui_adapter(data, compiled_graph, max_turns: int = 3, max_chars: int = 8000):
|
| 74 |
"""Text-only adapter for ChatUI with structured message support"""
|
| 75 |
+
logger.debug(f"ChatUI adapter called with data type: {type(data)}")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 76 |
|
| 77 |
try:
|
| 78 |
# Handle both dict and object access patterns
|
|
|
|
| 85 |
messages_value = getattr(data, 'messages', None)
|
| 86 |
preprompt_value = getattr(data, 'preprompt', None)
|
| 87 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 88 |
# Convert dict messages to objects if needed
|
| 89 |
messages = []
|
| 90 |
if messages_value:
|
|
|
|
| 97 |
else:
|
| 98 |
messages.append(msg)
|
| 99 |
|
|
|
|
| 100 |
# Extract latest user query
|
| 101 |
user_messages = [msg for msg in messages if msg.role == 'user']
|
| 102 |
query = user_messages[-1].content if user_messages else text_value
|
| 103 |
|
| 104 |
+
# Conversation metadata (troubleshooting purposes)
|
| 105 |
+
msg_metadata = {
|
| 106 |
+
'total': len(messages),
|
| 107 |
+
'user': len(user_messages),
|
| 108 |
+
'assistant': len([m for m in messages if m.role == 'assistant']),
|
| 109 |
+
'msg_lengths': [len(m.content) for m in messages]
|
| 110 |
+
}
|
| 111 |
+
logger.info(f"Processing query: {query[:20]}... | Conversation: {msg_metadata}")
|
| 112 |
|
| 113 |
# Build conversation context for generation (last N turns)
|
| 114 |
conversation_context = build_conversation_context(messages, max_turns=max_turns, max_chars=max_chars)
|
|
|
|
| 115 |
full_response = ""
|
| 116 |
sources_collected = None
|
| 117 |
|
|
|
|
| 173 |
# Extract query - prefer structured messages
|
| 174 |
conversation_context = None
|
| 175 |
if messages_value and len(messages_value) > 0:
|
|
|
|
|
|
|
| 176 |
# Convert dict messages to objects
|
| 177 |
messages = []
|
| 178 |
for msg in messages_value:
|
|
|
|
| 187 |
user_messages = [msg for msg in messages if msg.role == 'user']
|
| 188 |
query = user_messages[-1].content if user_messages else text_value
|
| 189 |
|
| 190 |
+
# Conversation metadata (troubleshooting purposes)
|
| 191 |
+
msg_metadata = {
|
| 192 |
+
'total': len(messages),
|
| 193 |
+
'user': len(user_messages),
|
| 194 |
+
'assistant': len([m for m in messages if m.role == 'assistant']),
|
| 195 |
+
'msg_lengths': [len(m.content) for m in messages]
|
| 196 |
+
}
|
| 197 |
+
logger.info(f"Processing query with file: {query[:20]}... | Conversation: {msg_metadata}")
|
| 198 |
|
| 199 |
conversation_context = build_conversation_context(messages, max_turns=max_turns, max_chars=max_chars)
|
| 200 |
else:
|
|
|
|
| 222 |
async for result in process_query_streaming(
|
| 223 |
compiled_graph=compiled_graph,
|
| 224 |
query=query,
|
| 225 |
+
file_upload=None,
|
| 226 |
reports_filter="",
|
| 227 |
sources_filter="",
|
| 228 |
subtype_filter="",
|
| 229 |
year_filter="",
|
| 230 |
+
conversation_context=conversation_context,
|
| 231 |
+
file_content=file_content,
|
| 232 |
+
filename=filename
|
| 233 |
):
|
| 234 |
if isinstance(result, dict):
|
| 235 |
result_type = result.get("type", "data")
|
src/components/orchestration/workflow.py
CHANGED
|
@@ -6,7 +6,7 @@ from functools import partial
|
|
| 6 |
from langgraph.graph import StateGraph, START, END
|
| 7 |
|
| 8 |
from .state import GraphState
|
| 9 |
-
from .nodes import retrieve_node, generate_node_streaming
|
| 10 |
|
| 11 |
logger = logging.getLogger(__name__)
|
| 12 |
|
|
@@ -17,20 +17,22 @@ def build_workflow(retriever_instance, generator_instance):
|
|
| 17 |
"""
|
| 18 |
workflow = StateGraph(GraphState)
|
| 19 |
|
| 20 |
-
# Inject services into nodes
|
| 21 |
r_node = partial(retrieve_node, retriever=retriever_instance)
|
| 22 |
g_node = partial(generate_node_streaming, generator=generator_instance)
|
| 23 |
|
| 24 |
# Add nodes
|
|
|
|
| 25 |
workflow.add_node("retrieve", r_node)
|
| 26 |
workflow.add_node("generate", g_node)
|
| 27 |
|
| 28 |
-
# Define edges
|
| 29 |
-
workflow.add_edge(START, "
|
|
|
|
| 30 |
workflow.add_edge("retrieve", "generate")
|
| 31 |
workflow.add_edge("generate", END)
|
| 32 |
|
| 33 |
compiled_graph = workflow.compile()
|
| 34 |
|
| 35 |
-
logger.info("LangGraph workflow compiled successfully")
|
| 36 |
return compiled_graph
|
|
|
|
| 6 |
from langgraph.graph import StateGraph, START, END
|
| 7 |
|
| 8 |
from .state import GraphState
|
| 9 |
+
from .nodes import retrieve_node, generate_node_streaming, ingest_node
|
| 10 |
|
| 11 |
logger = logging.getLogger(__name__)
|
| 12 |
|
|
|
|
| 17 |
"""
|
| 18 |
workflow = StateGraph(GraphState)
|
| 19 |
|
| 20 |
+
# Inject services into nodes (ingest_node doesn't need dependency injection)
|
| 21 |
r_node = partial(retrieve_node, retriever=retriever_instance)
|
| 22 |
g_node = partial(generate_node_streaming, generator=generator_instance)
|
| 23 |
|
| 24 |
# Add nodes
|
| 25 |
+
workflow.add_node("ingest", ingest_node)
|
| 26 |
workflow.add_node("retrieve", r_node)
|
| 27 |
workflow.add_node("generate", g_node)
|
| 28 |
|
| 29 |
+
# Define edges: ingest -> retrieve -> generate
|
| 30 |
+
workflow.add_edge(START, "ingest")
|
| 31 |
+
workflow.add_edge("ingest", "retrieve")
|
| 32 |
workflow.add_edge("retrieve", "generate")
|
| 33 |
workflow.add_edge("generate", END)
|
| 34 |
|
| 35 |
compiled_graph = workflow.compile()
|
| 36 |
|
| 37 |
+
logger.info("LangGraph workflow compiled successfully with ingest node")
|
| 38 |
return compiled_graph
|
src/components/retriever/retriever_orchestrator.py
CHANGED
|
@@ -110,7 +110,7 @@ class ChaBoHFEndpointRetriever(BaseRetriever):
|
|
| 110 |
client = self._get_qdrant_client()
|
| 111 |
|
| 112 |
if self.qdrant_mode.lower() == 'native':
|
| 113 |
-
logger.
|
| 114 |
search_result = client.query_points(
|
| 115 |
collection_name=self.qdrant_collection,
|
| 116 |
query=query_vector,
|
|
@@ -131,7 +131,7 @@ class ChaBoHFEndpointRetriever(BaseRetriever):
|
|
| 131 |
} for hit in search_result.points]
|
| 132 |
|
| 133 |
elif self.qdrant_mode.lower() == 'gradio':
|
| 134 |
-
logger.
|
| 135 |
return client.predict(
|
| 136 |
query_vector_json=query_vector,
|
| 137 |
collection_name=self.qdrant_collection,
|
|
@@ -152,8 +152,8 @@ class ChaBoHFEndpointRetriever(BaseRetriever):
|
|
| 152 |
client = await self._aget_qdrant_client()
|
| 153 |
|
| 154 |
if self.qdrant_mode.lower() == 'native':
|
| 155 |
-
logger.
|
| 156 |
-
|
| 157 |
search_result = await client.query_points(
|
| 158 |
collection_name=self.qdrant_collection,
|
| 159 |
query=query_vector,
|
|
@@ -170,7 +170,7 @@ class ChaBoHFEndpointRetriever(BaseRetriever):
|
|
| 170 |
} for hit in search_result.points]
|
| 171 |
|
| 172 |
elif self.qdrant_mode.lower() == 'gradio':
|
| 173 |
-
logger.
|
| 174 |
loop = asyncio.get_running_loop()
|
| 175 |
|
| 176 |
# Use run_in_executor to make the synchronous .predict() awaitable
|
|
@@ -344,7 +344,12 @@ def create_retriever_from_config(config_file: str = "params.cfg"):
|
|
| 344 |
config = getconfig(config_file)
|
| 345 |
|
| 346 |
hf_token = os.getenv("HF_TOKEN")
|
|
|
|
|
|
|
|
|
|
| 347 |
qdrant_api_key = os.getenv("QDRANT_API_KEY")
|
|
|
|
|
|
|
| 348 |
|
| 349 |
config_map = {
|
| 350 |
"embedding_endpoint_url": ("hf_endpoints", "embedding_endpoint_url", "EMBEDDING_ENDPOINT_URL"),
|
|
@@ -361,17 +366,19 @@ def create_retriever_from_config(config_file: str = "params.cfg"):
|
|
| 361 |
|
| 362 |
retriever_config_kwargs = {
|
| 363 |
"hf_token": hf_token,
|
| 364 |
-
"qdrant_api_key": qdrant_api_key
|
| 365 |
}
|
| 366 |
|
| 367 |
for key, params in config_map.items():
|
|
|
|
| 368 |
section, option, env_var = params[:3]
|
| 369 |
fallback = params[3] if len(params) > 3 else None
|
| 370 |
value = get_config_value(config, section, option, env_var, fallback)
|
| 371 |
-
|
| 372 |
if key in ['initial_k', 'top_k', 'qdrant_port']:
|
| 373 |
value = int(value)
|
| 374 |
|
|
|
|
| 375 |
retriever_config_kwargs[key] = value
|
| 376 |
|
| 377 |
logger.info(f"Configuration loaded. Qdrant Mode: {retriever_config_kwargs['qdrant_mode']}")
|
|
|
|
| 110 |
client = self._get_qdrant_client()
|
| 111 |
|
| 112 |
if self.qdrant_mode.lower() == 'native':
|
| 113 |
+
logger.debug(f"Sync Native Qdrant search: collection={self.qdrant_collection}, k={self.initial_k}")
|
| 114 |
search_result = client.query_points(
|
| 115 |
collection_name=self.qdrant_collection,
|
| 116 |
query=query_vector,
|
|
|
|
| 131 |
} for hit in search_result.points]
|
| 132 |
|
| 133 |
elif self.qdrant_mode.lower() == 'gradio':
|
| 134 |
+
logger.debug(f"Sync Gradio Qdrant search: collection={self.qdrant_collection}, k={self.initial_k}")
|
| 135 |
return client.predict(
|
| 136 |
query_vector_json=query_vector,
|
| 137 |
collection_name=self.qdrant_collection,
|
|
|
|
| 152 |
client = await self._aget_qdrant_client()
|
| 153 |
|
| 154 |
if self.qdrant_mode.lower() == 'native':
|
| 155 |
+
logger.debug(f"Async Native Qdrant search: collection={self.qdrant_collection}, k={self.initial_k}")
|
| 156 |
+
|
| 157 |
search_result = await client.query_points(
|
| 158 |
collection_name=self.qdrant_collection,
|
| 159 |
query=query_vector,
|
|
|
|
| 170 |
} for hit in search_result.points]
|
| 171 |
|
| 172 |
elif self.qdrant_mode.lower() == 'gradio':
|
| 173 |
+
logger.debug(f"Async Gradio Qdrant search: collection={self.qdrant_collection}, k={self.initial_k}")
|
| 174 |
loop = asyncio.get_running_loop()
|
| 175 |
|
| 176 |
# Use run_in_executor to make the synchronous .predict() awaitable
|
|
|
|
| 344 |
config = getconfig(config_file)
|
| 345 |
|
| 346 |
hf_token = os.getenv("HF_TOKEN")
|
| 347 |
+
if not hf_token:
|
| 348 |
+
raise ValueError("HF_TOKEN environment variable is required but not set")
|
| 349 |
+
|
| 350 |
qdrant_api_key = os.getenv("QDRANT_API_KEY")
|
| 351 |
+
if not qdrant_api_key:
|
| 352 |
+
raise ValueError("QDRANT_API_KEY environment variable is required but not set")
|
| 353 |
|
| 354 |
config_map = {
|
| 355 |
"embedding_endpoint_url": ("hf_endpoints", "embedding_endpoint_url", "EMBEDDING_ENDPOINT_URL"),
|
|
|
|
| 366 |
|
| 367 |
retriever_config_kwargs = {
|
| 368 |
"hf_token": hf_token,
|
| 369 |
+
"qdrant_api_key": qdrant_api_key
|
| 370 |
}
|
| 371 |
|
| 372 |
for key, params in config_map.items():
|
| 373 |
+
|
| 374 |
section, option, env_var = params[:3]
|
| 375 |
fallback = params[3] if len(params) > 3 else None
|
| 376 |
value = get_config_value(config, section, option, env_var, fallback)
|
| 377 |
+
|
| 378 |
if key in ['initial_k', 'top_k', 'qdrant_port']:
|
| 379 |
value = int(value)
|
| 380 |
|
| 381 |
+
|
| 382 |
retriever_config_kwargs[key] = value
|
| 383 |
|
| 384 |
logger.info(f"Configuration loaded. Qdrant Mode: {retriever_config_kwargs['qdrant_mode']}")
|
src/main.py
CHANGED
|
@@ -84,12 +84,8 @@ add_routes(
|
|
| 84 |
enable_public_trace_link_endpoint=True,
|
| 85 |
)
|
| 86 |
|
| 87 |
-
|
| 88 |
-
logger.
|
| 89 |
-
logger.info("LangServe Routes Configured")
|
| 90 |
-
logger.info(f"ChatUIInput schema: {ChatUIInput.model_json_schema()}")
|
| 91 |
-
logger.info(f"ChatUIFileInput schema: {ChatUIFileInput.model_json_schema()}")
|
| 92 |
-
logger.info("=" * 80)
|
| 93 |
|
| 94 |
#----------------------------------------
|
| 95 |
|
|
|
|
| 84 |
enable_public_trace_link_endpoint=True,
|
| 85 |
)
|
| 86 |
|
| 87 |
+
logger.debug(f"ChatUIInput schema: {ChatUIInput.model_json_schema()}")
|
| 88 |
+
logger.debug(f"ChatUIFileInput schema: {ChatUIFileInput.model_json_schema()}")
|
|
|
|
|
|
|
|
|
|
|
|
|
| 89 |
|
| 90 |
#----------------------------------------
|
| 91 |
|