Spaces:
Running
on
CPU Upgrade
Running
on
CPU Upgrade
File size: 18,741 Bytes
ecc8726 1900b1d ecc8726 d13d866 ea45e0c 99fffc4 d13d866 1900b1d d13d866 ecc8726 de25c1c 019f514 4ef25e0 f5bde8f 019f514 5e79e19 1900b1d 019f514 de25c1c ecc8726 f5bde8f ecc8726 f9cf2d2 5e79e19 99fffc4 aa7f532 de25c1c 5e79e19 de25c1c ecc8726 de25c1c 5e79e19 ecc8726 f5bde8f ecc8726 32ef85f f5bde8f ecc8726 d13d866 ecc8726 f5bde8f ecc8726 f5bde8f ecc8726 99fffc4 ecc8726 f5bde8f ecc8726 f5bde8f f9cf2d2 5e79e19 f9cf2d2 5e79e19 ecc8726 f9cf2d2 ecc8726 f9cf2d2 ecc8726 f5bde8f ecc8726 1900b1d ecc8726 1900b1d ecc8726 1900b1d ecc8726 1900b1d ecc8726 ea45e0c f5bde8f ea45e0c f5bde8f ea45e0c f5bde8f 8a344c6 f5bde8f ea45e0c 8a344c6 ea45e0c f5bde8f 8a344c6 ea45e0c 8a344c6 ea45e0c 8a344c6 ea45e0c 8a344c6 ea45e0c 8a344c6 f5bde8f 8a344c6 f5bde8f 8a344c6 ea45e0c f5bde8f ea45e0c f5bde8f ea45e0c 201e72b 4f39e33 f5bde8f 4f39e33 f5bde8f ea45e0c f5bde8f ea45e0c f5bde8f ea45e0c f5bde8f ea45e0c f5bde8f ea45e0c f5bde8f ea45e0c de25c1c 99fffc4 de25c1c ea45e0c f5bde8f ea45e0c f5bde8f f47ba34 f5bde8f ea45e0c f47ba34 ea45e0c 201e72b ea45e0c f5bde8f ea45e0c f47ba34 ea45e0c f5bde8f ea45e0c f47ba34 ea45e0c f47ba34 ea45e0c f47ba34 ea45e0c f5bde8f de25c1c ea45e0c de25c1c ea45e0c de25c1c ea45e0c de25c1c ea45e0c de25c1c f47ba34 de25c1c f47ba34 de25c1c f47ba34 de25c1c ea45e0c de25c1c ea45e0c de25c1c ea45e0c 99fffc4 |
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 |
import tempfile
import os
from models import GraphState
from datetime import datetime
from gradio_client import Client, file
import logging
import dotenv
import httpx
import json
from typing import Generator, Optional
from utils import detect_file_type, convert_context_to_list, merge_state, getconfig
from retriever_adapter import RetrieverAdapter
dotenv.load_dotenv()
logger = logging.getLogger(__name__)
# Load config
config = getconfig("params.cfg")
RETRIEVER = config.get("retriever", "RETRIEVER")
GENERATOR = config.get("generator", "GENERATOR")
INGESTOR = config.get("ingestor", "INGESTOR")
MAX_CONTEXT_CHARS = int(config.get("general", "MAX_CONTEXT_CHARS"))
# Check if direct output mode is enabled
DIRECT_OUTPUT_ENABLED = config.getboolean("file_processing", "DIRECT_OUTPUT", fallback=False)
retriever_adapter = RetrieverAdapter("params.cfg")
#----------------------------------------
# LANGGRAPH NODE FUNCTIONS
#----------------------------------------
def detect_file_type_node(state: GraphState) -> GraphState:
"""Detect file type and determine workflow"""
file_type = "unknown"
workflow_type = "standard"
if state.get("file_content") and state.get("filename"):
file_type = detect_file_type(state["filename"], state["file_content"])
# Check if direct output mode is enabled
if DIRECT_OUTPUT_ENABLED:
logger.info(f"Direct output mode enabled - file will show ingestor results directly")
workflow_type = "direct_output"
else:
# Direct output disabled - use standard workflow
logger.info(f"Direct output mode disabled - using standard RAG pipeline")
workflow_type = "standard"
metadata = state.get("metadata", {})
metadata.update({
"file_type": file_type,
"workflow_type": workflow_type,
"direct_output_enabled": DIRECT_OUTPUT_ENABLED
})
return {
"file_type": file_type,
"workflow_type": workflow_type,
"metadata": metadata
}
def ingest_node(state: GraphState) -> GraphState:
"""Process file through appropriate ingestor based on file type"""
start_time = datetime.now()
if not state.get("file_content") or not state.get("filename"):
logger.info("No file provided, skipping ingestion")
return {"ingestor_context": "", "metadata": state.get("metadata", {})}
file_type = state.get("file_type", "unknown")
logger.info(f"Ingesting {file_type} file: {state['filename']}")
try:
ingestor_url = INGESTOR
logger.info(f"Using ingestor: {ingestor_url}")
client = Client(ingestor_url, hf_token=os.getenv("HF_TOKEN"))
# Create temporary file for upload
with tempfile.NamedTemporaryFile(delete=False, suffix=os.path.splitext(state["filename"])[1]) as tmp_file:
tmp_file.write(state["file_content"])
tmp_file_path = tmp_file.name
try:
ingestor_context = client.predict(file(tmp_file_path), api_name="/ingest")
logger.info(f"Ingest result length: {len(ingestor_context) if ingestor_context else 0}")
if isinstance(ingestor_context, str) and ingestor_context.startswith("Error:"):
raise Exception(ingestor_context)
finally:
os.unlink(tmp_file_path)
duration = (datetime.now() - start_time).total_seconds()
metadata = state.get("metadata", {})
metadata.update({
"ingestion_duration": duration,
"ingestor_context_length": len(ingestor_context) if ingestor_context else 0,
"ingestion_success": True,
"ingestor_used": ingestor_url
})
return {"ingestor_context": ingestor_context, "metadata": metadata}
except Exception as e:
duration = (datetime.now() - start_time).total_seconds()
logger.error(f"Ingestion failed: {str(e)}")
metadata = state.get("metadata", {})
metadata.update({
"ingestion_duration": duration,
"ingestion_success": False,
"ingestion_error": str(e)
})
return {"ingestor_context": "", "metadata": metadata}
def direct_output_node(state: GraphState) -> GraphState:
"""
For files when direct output mode is enabled, return ingestor results directly.
"""
file_type = state.get('file_type', 'unknown')
logger.info(f"Direct output mode - returning ingestor results for {file_type} file")
ingestor_context = state.get("ingestor_context", "")
result = ingestor_context if ingestor_context else "No results from file processing."
metadata = state.get("metadata", {})
metadata.update({
"processing_type": "direct_output",
"result_length": len(result)
})
return {"result": result, "metadata": metadata}
def retrieve_node(state: GraphState) -> GraphState:
"""Retrieve relevant context using adapter"""
start_time = datetime.now()
logger.info(f"Retrieval: {state['query'][:50]}...")
try:
# Get filters from state (provided by ChatUI or LLM agent)
filters = state.get("metadata_filters")
context = retriever_adapter.retrieve(
query=state["query"],
filters=filters,
hf_token=os.getenv("HF_TOKEN")
)
duration = (datetime.now() - start_time).total_seconds()
metadata = state.get("metadata", {})
metadata.update({
"retrieval_duration": duration,
"context_length": len(context) if context else 0,
"retrieval_success": True,
"filters_applied": filters,
"retriever_config": retriever_adapter.get_metadata()
})
return {"context": context, "metadata": metadata}
except Exception as e:
duration = (datetime.now() - start_time).total_seconds()
logger.error(f"Retrieval failed: {str(e)}")
metadata = state.get("metadata", {})
metadata.update({
"retrieval_duration": duration,
"retrieval_success": False,
"retrieval_error": str(e)
})
return {"context": "", "metadata": metadata}
async def generate_node_streaming(state: GraphState) -> Generator[GraphState, None, None]:
"""Streaming generation using generator's FastAPI endpoint"""
start_time = datetime.now()
logger.info(f"Generation (streaming): {state['query'][:50]}...")
try:
# Combine contexts
retrieved_context = state.get("context", "")
ingestor_context = state.get("ingestor_context", "")
logger.info(f"Context lengths - Ingestor: {len(ingestor_context)}, Retrieved: {len(retrieved_context)}")
# Build context list with truncation
context_list = []
total_context_chars = 0
if ingestor_context:
truncated_ingestor = (
ingestor_context[:MAX_CONTEXT_CHARS] + "...\n[Content truncated due to length]"
if len(ingestor_context) > MAX_CONTEXT_CHARS
else ingestor_context
)
context_list.append({
"answer": truncated_ingestor,
"answer_metadata": {
"filename": state.get("filename", "Uploaded Document"),
"page": "Unknown",
"year": "Unknown",
"source": "Ingestor"
}
})
total_context_chars += len(truncated_ingestor)
if retrieved_context and total_context_chars < MAX_CONTEXT_CHARS:
retrieved_list = convert_context_to_list(retrieved_context)
remaining_chars = MAX_CONTEXT_CHARS - total_context_chars
for item in retrieved_list:
item_text = item.get("answer", "")
if len(item_text) <= remaining_chars:
context_list.append(item)
remaining_chars -= len(item_text)
else:
if remaining_chars > 100:
item["answer"] = item_text[:remaining_chars-50] + "...\n[Content truncated]"
context_list.append(item)
break
final_context_size = sum(len(item.get("answer", "")) for item in context_list)
logger.info(f"Final context size: {final_context_size} characters (limit: {MAX_CONTEXT_CHARS})")
payload = {"query": state["query"], "context": context_list}
# Normalize generator URL
generator_url = GENERATOR
# Stream from generator with authentication
headers = {
"Content-Type": "application/json",
"Authorization": f"Bearer {os.getenv('HF_TOKEN')}"
}
async with httpx.AsyncClient(timeout=300.0, verify=False) as client:
async with client.stream(
"POST",
f"{generator_url}/generate/stream",
json=payload,
headers=headers
) as response:
if response.status_code != 200:
raise Exception(f"Generator returned status {response.status_code}")
current_text = ""
sources = None
event_type = None
async for line in response.aiter_lines():
if not line.strip():
continue
if line.startswith("event: "):
event_type = line[7:].strip()
continue
elif line.startswith("data: "):
data_content = line[6:].strip()
if event_type == "data":
try:
chunk = json.loads(data_content)
if isinstance(chunk, str):
current_text += chunk
except json.JSONDecodeError:
current_text += data_content
chunk = data_content
metadata = state.get("metadata", {})
metadata.update({
"generation_duration": (datetime.now() - start_time).total_seconds(),
"result_length": len(current_text),
"generation_success": True,
"streaming": True,
"context_chars_used": final_context_size
})
yield {"result": chunk, "metadata": metadata}
elif event_type == "sources":
try:
sources_data = json.loads(data_content)
sources = sources_data.get("sources", [])
metadata = state.get("metadata", {})
metadata.update({
"sources_received": True,
"sources_count": len(sources)
})
yield {"sources": sources, "metadata": metadata}
except json.JSONDecodeError:
logger.warning(f"Failed to parse sources: {data_content}")
elif event_type == "end":
logger.info("Generator stream ended")
break
elif event_type == "error":
try:
error_data = json.loads(data_content)
raise Exception(error_data.get("error", "Unknown error"))
except json.JSONDecodeError:
raise Exception(data_content)
except Exception as e:
duration = (datetime.now() - start_time).total_seconds()
logger.error(f"Streaming generation failed: {str(e)}")
metadata = state.get("metadata", {})
metadata.update({
"generation_duration": duration,
"generation_success": False,
"generation_error": str(e),
"streaming": True
})
yield {"result": f"Error: {str(e)}", "metadata": metadata}
def route_workflow(state: GraphState) -> str:
"""
Conditional routing based on workflow type after ingestion.
Returns 'direct_output' when DIRECT_OUTPUT=True, 'standard' otherwise.
"""
workflow_type = state.get("workflow_type", "standard")
logger.info(f"Routing to: {workflow_type}")
return workflow_type
#----------------------------------------
# UNIFIED STREAMING PROCESSOR
#----------------------------------------
async def process_query_streaming(
query: str,
file_upload=None,
file_content: Optional[bytes] = None,
filename: Optional[str] = None,
reports_filter: str = "",
sources_filter: str = "",
subtype_filter: str = "",
year_filter: str = "",
output_format: str = "structured",
conversation_context: Optional[str] = None # NEW: conversation context
):
"""
Unified streaming function with conversation context support.
Args:
query: Latest user query
conversation_context: Optional conversation history for generation context
... (other args remain the same)
"""
# Handle file_upload if provided
if file_upload is not None:
try:
with open(file_upload.name, 'rb') as f:
file_content = f.read()
filename = os.path.basename(file_upload.name)
logger.info(f"File uploaded: {filename}, size: {len(file_content)} bytes")
except Exception as e:
logger.error(f"Error reading uploaded file: {str(e)}")
if output_format == "structured":
yield {"type": "error", "content": f"Error reading file: {str(e)}"}
else:
yield f"Error reading file: {str(e)}"
return
start_time = datetime.now()
session_id = f"stream_{start_time.strftime('%Y%m%d_%H%M%S')}"
# Log retrieval strategy
logger.info(f"Retrieval query: {query[:100]}...")
if conversation_context:
logger.info(f"Generation will use conversation context ({len(conversation_context)} chars)")
try:
# Build initial state
initial_state = {
"query": query, # Use ONLY latest query for retrieval
"context": "",
"ingestor_context": "",
"result": "",
"sources": [],
"reports_filter": reports_filter or "",
"sources_filter": sources_filter or "",
"subtype_filter": subtype_filter or "",
"year_filter": year_filter or "",
"file_content": file_content,
"filename": filename,
"file_type": "unknown",
"workflow_type": "standard",
"conversation_context": conversation_context, # Store for generation
"metadata": {
"session_id": session_id,
"start_time": start_time.isoformat(),
"has_file_attachment": file_content is not None,
"has_conversation_context": conversation_context is not None
}
}
# Execute workflow nodes
if file_content and filename:
state = merge_state(initial_state, detect_file_type_node(initial_state))
state = merge_state(state, ingest_node(state))
workflow_type = route_workflow(state)
if workflow_type == "direct_output":
final_state = direct_output_node(state)
if output_format == "structured":
yield {"type": "data", "content": final_state["result"]}
yield {"type": "end", "content": ""}
else:
yield final_state["result"]
return
else:
# Retrieve using ONLY the latest query
state = merge_state(state, retrieve_node(state))
else:
# No file: retrieve using latest query only
state = merge_state(initial_state, retrieve_node(initial_state))
# Generate response with streaming
# The generator can optionally use conversation_context for better responses
sources_collected = None
accumulated_response = "" if output_format == "gradio" else None
async for partial_state in generate_node_streaming(state):
if "result" in partial_state:
if output_format == "structured":
yield {"type": "data", "content": partial_state["result"]}
else:
accumulated_response += partial_state["result"]
yield accumulated_response
if "sources" in partial_state:
sources_collected = partial_state["sources"]
# Format and yield sources
if sources_collected:
if output_format == "structured":
yield {"type": "sources", "content": sources_collected}
else:
sources_text = "\n\n**Sources:**\n"
for i, source in enumerate(sources_collected, 1):
if isinstance(source, dict):
title = source.get('title', 'Unknown')
link = source.get('link', '#')
sources_text += f"{i}. [{title}]({link})\n"
else:
sources_text += f"{i}. {source}\n"
accumulated_response += sources_text
yield accumulated_response
if output_format == "structured":
yield {"type": "end", "content": ""}
except Exception as e:
logger.error(f"Streaming pipeline failed: {str(e)}")
if output_format == "structured":
yield {"type": "error", "content": f"Error: {str(e)}"}
else:
yield f"Error: {str(e)}" |