Repository navigation
Expand file tree
/
Copy pathllm_orchestration_service.py
More file actions
3067 lines (2678 loc) · 129 KB
/
Copy pathllm_orchestration_service.py
File metadata and controls
3067 lines (2678 loc) · 129 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
"""LLM Orchestration Service - Business logic for LLM orchestration."""
from typing import Optional, List, Dict, Union, Any, AsyncIterator, TYPE_CHECKING
import os
import time
import asyncio
import threading
from src.loki_logger import LokiLogger
from langfuse import Langfuse, observe
import dspy
from datetime import datetime
import json as json_module
from llm_orchestrator_config.llm_manager import LLMManager
from models.request_models import (
OrchestrationRequest,
OrchestrationResponse,
ConversationItem,
PromptRefinerOutput,
ContextGenerationRequest,
TestOrchestrationResponse,
ChunkInfo,
DocumentReference,
)
from prompt_refine_manager.prompt_refiner import PromptRefinerAgent
from src.response_generator.response_generate import ResponseGeneratorAgent
from src.response_generator.response_generate import stream_response_native
from src.llm_orchestrator_config.llm_ochestrator_constants import (
OUT_OF_SCOPE_MESSAGES,
TECHNICAL_ISSUE_MESSAGE,
TECHNICAL_ISSUE_MESSAGES,
INPUT_GUARDRAIL_VIOLATION_MESSAGE,
INPUT_GUARDRAIL_VIOLATION_MESSAGES,
OUTPUT_GUARDRAIL_VIOLATION_MESSAGE,
OUTPUT_GUARDRAIL_VIOLATION_MESSAGES,
QUERY_VALIDATION_FAILED_MESSAGES,
get_localized_message,
GUARDRAILS_BLOCKED_PHRASES,
TEST_DEPLOYMENT_ENVIRONMENT,
STREAM_TOKEN_LIMIT_MESSAGE,
PRODUCTION_DEPLOYMENT_ENVIRONMENT,
RUUTER_PROMPT_CONFIG_ENDPOINT,
PROMPT_CONFIG_CACHE_TTL,
)
from src.llm_orchestrator_config.stream_config import StreamConfig
from src.vector_indexer.constants import ResponseGenerationConstants
from src.utils.error_utils import generate_error_id, log_error_with_context
from src.utils.stream_manager import stream_manager, StreamContext
from src.utils.cost_utils import (
calculate_total_costs,
get_lm_usage_since,
get_lm_usage_since_split,
)
if TYPE_CHECKING:
from src.llm_orchestrator_config.embedding_manager import EmbeddingManager
from src.llm_orchestrator_config.context_manager import (
ContextGenerationManager,
)
from src.llm_orchestrator_config.config.loader import ConfigurationLoader
from src.utils.time_tracker import log_step_timings
from src.utils.budget_tracker import get_budget_tracker
from src.utils.production_store import get_production_store
from src.utils.language_detector import detect_language, get_language_name
from src.utils.prompt_config_loader import PromptConfigurationLoader
from src.utils.query_validator import validate_query_basic
from src.utils.sse_utils import extract_content_from_sse
from src.utils.conversation_history_store import should_save_history, save_history_round
from src.utils.conversation_history_helpers import get_conversation_history
from src.guardrails import NeMoRailsAdapter, GuardrailCheckResult
from src.contextual_retrieval import ContextualRetriever
from src.contextual_retrieval.bm25_search import SmartBM25Search
from src.llm_orchestrator_config.exceptions import (
ContextualRetrieverInitializationError,
ContextualRetrievalFailureError,
)
from src.llm_orchestrator_config.feature_flags import FeatureFlags
from src.tool_classifier import ToolClassifier, WorkflowType
from src.tool_classifier.constants import SERVICE_STEP_PREFIXES
from src.tool_classifier.workflows.service_workflow import ServiceWorkflowExecutor
# Initialize Loki logger for orchestration service
logger = LokiLogger(service_name="llm-orchestration-service")
REFERENCES_SECTION_HEADER = "\n\n**References:**\n"
# Set of content strings that must NOT be persisted in conversation history.
# Covers all multilingual error / OOS / guardrail-violation messages so that
# failed or blocked exchanges are never written to Redis.
_HISTORY_EXCLUDED_MESSAGES: frozenset[str] = frozenset(
{
*OUT_OF_SCOPE_MESSAGES.values(),
*TECHNICAL_ISSUE_MESSAGES.values(),
*INPUT_GUARDRAIL_VIOLATION_MESSAGES.values(),
*OUTPUT_GUARDRAIL_VIOLATION_MESSAGES.values(),
*QUERY_VALIDATION_FAILED_MESSAGES.values(),
STREAM_TOKEN_LIMIT_MESSAGE,
}
)
class LangfuseConfig:
"""Configuration for Langfuse integration."""
def __init__(self) -> None:
self.langfuse_client: Optional[Langfuse] = None
self._initialize_langfuse()
def _initialize_langfuse(self) -> None:
"""Initialize Langfuse client with Vault secrets."""
try:
from llm_orchestrator_config.vault.vault_client import get_vault_client
vault = get_vault_client()
if vault.is_vault_available():
langfuse_secrets = vault.get_secret("langfuse/config")
if langfuse_secrets:
self.langfuse_client = Langfuse(
public_key=langfuse_secrets.get("public_key"),
secret_key=langfuse_secrets.get("secret_key"),
host=langfuse_secrets.get("host", "http://langfuse-web:3000"),
)
logger.info("Langfuse client initialized successfully")
else:
logger.warning("Langfuse secrets not found in Vault")
else:
logger.warning("Vault not available, Langfuse tracing disabled")
except Exception as e:
logger.warning(f"Failed to initialize Langfuse: {e}")
class LLMOrchestrationService:
"""
Service class for handling LLM orchestration with integrated guardrails.
Features:
- Input guardrails before prompt refinement
- Output guardrails after response generation
- Comprehensive cost tracking for all components
"""
def __init__(self) -> None:
"""Initialize the orchestration service."""
self.langfuse_config = LangfuseConfig()
# Initialize prompt configuration loader
self.prompt_config_loader = PromptConfigurationLoader(
ruuter_endpoint=RUUTER_PROMPT_CONFIG_ENDPOINT,
cache_ttl_seconds=PROMPT_CONFIG_CACHE_TTL,
max_retries=3,
timeout_seconds=10,
)
try:
custom_instructions = self.prompt_config_loader.get_custom_instructions()
if custom_instructions:
logger.info(
f"Custom prompt configuration loaded at startup "
f"({len(custom_instructions)} chars)"
)
else:
logger.info("ℹNo custom prompt configuration found - using defaults")
except Exception as e:
logger.warning(
f"Failed to load custom prompts at startup: {e}. "
f"Service will continue with default behavior."
)
# Initialize tool classifier (lazy initialization - will be created when first needed)
# This allows components to be initialized per-request with proper context
self.tool_classifier = None
# Redis-backed session store for API Tool Calling agentic loop.
# Set to None here; the FastAPI lifespan injects the live store after
# Redis initialises (app.state.orchestration_service.session_store = ...).
# Workflow executors access it via self.orchestration_service.session_store.
self.session_store: Any = None
# Redis-backed conversation history store.
# Set to None here; the FastAPI lifespan injects the live store after
# Redis initialises (app.state.orchestration_service.conversation_history_store = ...).
self.conversation_history_store: Any = None
# Shared BM25 search index pre-warmed at startup.
# Populated by _prewarm_shared_bm25() which is called from the FastAPI
# lifespan so it runs inside the async event loop. Until then it is None
# and each ContextualRetriever will build the index on first query (graceful
# degradation path).
self.shared_bm25_search: Optional[SmartBM25Search] = None
self._retriever_cache: Dict[tuple, ContextualRetriever] = {}
self._component_cache_lock = threading.Lock()
# Initialize shared guardrails adapters at startup (production and testing)
self.shared_guardrails_adapters = (
self._initialize_shared_guardrails_at_startup()
)
# Log feature flag configuration
FeatureFlags.log_configuration()
def _initialize_shared_guardrails_at_startup(self) -> Dict[str, NeMoRailsAdapter]:
"""
Initialize shared guardrails adapters at startup for production and testing environments.
Returns:
Dictionary mapping environment names to NeMoRailsAdapter instances.
Empty dict on failure (graceful degradation).
"""
adapters: Dict[str, NeMoRailsAdapter] = {}
# Initialize adapters for commonly-used environments
environments_to_initialize = ["production", "testing"]
logger.info(" Initializing shared guardrails at startup...")
total_start_time = time.time()
for env in environments_to_initialize:
try:
logger.info(f" Initializing guardrails for environment: {env}")
start_time = time.time()
# Initialize with specific environment and no connection (shared config)
guardrails_adapter = self._initialize_guardrails(
environment=env,
connection_id=None, # Shared configuration, not user-specific
)
# Eagerly trigger the full internal initialization (NeMo config
# loading, LLMRails creation, embedding model download) so that
# the first user query is not penalised by the cold-start cost.
# Without this, _ensure_initialized() runs lazily on the first
guardrails_adapter._ensure_initialized()
elapsed_time = time.time() - start_time
adapters[env] = guardrails_adapter
logger.info(
f" Guardrails for '{env}' fully initialized in {elapsed_time:.3f}s "
f"(NeMo Rails + embedding model loaded)"
)
except Exception as e:
logger.error(f" Failed to initialize guardrails for '{env}': {e}")
logger.warning(
f" Service will fall back to per-request initialization for '{env}' environment"
)
# Continue with other environments - partial success is acceptable
continue
total_elapsed = time.time() - total_start_time
if adapters:
logger.info(
f" Shared guardrails initialized for {len(adapters)} environment(s) "
f"in {total_elapsed:.3f}s total"
)
else:
logger.error(
" Failed to initialize any shared guardrails - "
"service will use per-request initialization (slower)"
)
return adapters
async def _prewarm_shared_bm25(self) -> None:
"""
Pre-warm the shared BM25 index at application startup.
Must be called from an async context (e.g. FastAPI lifespan) so that
asyncio is available for the HTTP calls to Qdrant. Absorbs the
cold-start latency (fetching all chunks + building BM25Okapi corpus)
at deploy time so that the first real user query is not penalised.
On any failure the method logs a warning and leaves
self.shared_bm25_search as None — the ContextualRetriever will then
fall back to building the index on the first query (graceful degradation).
"""
qdrant_url = os.getenv("QDRANT_URL", "http://qdrant:6333")
logger.info("Pre-warming shared BM25 index at startup...")
prewarm_start = time.time()
try:
bm25 = SmartBM25Search(qdrant_url=qdrant_url)
success = await bm25.initialize_index()
if success:
self.shared_bm25_search = bm25
elapsed = time.time() - prewarm_start
logger.info(
f"Shared BM25 index pre-warmed in {elapsed:.2f}s "
f"({len(bm25.chunk_mapping)} chunks indexed)"
)
else:
logger.warning(
"BM25 pre-warming produced an empty index - "
"index will be built on first query instead"
)
except Exception as e:
logger.warning(
f"BM25 pre-warming failed: {e} - "
f"index will be built on first query (graceful degradation)"
)
async def aclose(self) -> None:
"""Release all long-lived async resources held by the service.
Must be awaited during application shutdown (FastAPI lifespan teardown)
to avoid connection leaks from the ToolClassifier's httpx client.
"""
if self.tool_classifier is not None:
await self.tool_classifier.aclose()
logger.debug("LLMOrchestrationService async resources closed")
def _get_service_workflow_executor(self) -> ServiceWorkflowExecutor:
"""Return the ServiceWorkflowExecutor, reusing the ToolClassifier instance
when available, or creating a lightweight standalone executor otherwise.
Direct MCQ steps do not invoke any LLM, so llm_manager=None is safe.
orchestration_service=self is needed for format_sse() in the streaming path.
"""
if self.tool_classifier is not None:
return self.tool_classifier.service_workflow
return ServiceWorkflowExecutor(
llm_manager=None,
orchestration_service=self,
)
@observe(name="orchestration_request", as_type="agent")
async def process_orchestration_request(
self, request: OrchestrationRequest
) -> Union[OrchestrationResponse, TestOrchestrationResponse]:
"""
Process an orchestration request with guardrails and return response.
Pipeline:
1. Input Guardrails Check
2. Prompt Refinement (if input allowed)
3. Chunk Retrieval
4. Response Generation
5. Output Guardrails Check
6. Cost Logging
Args:
request: The orchestration request containing user message and context
Returns:
OrchestrationResponse: Response with LLM output and status flags
Raises:
Exception: For any processing errors
"""
costs_metric: Dict[str, Dict[str, Any]] = {}
time_metric: Dict[str, float] = {}
try:
logger.info(
f"Processing orchestration request for chatId: {request.chatId}, "
f"authorId: {request.authorId}, environment: {request.environment}"
)
# STEP 0: Detect language from user message (with timing)
start_time = time.time()
detected_language = detect_language(request.message)
language_name = get_language_name(detected_language)
time_metric["language_detection"] = time.time() - start_time
logger.info(
f"[{request.chatId}] Detected language: {language_name} ({detected_language})"
)
# Store detected language in request for use throughout pipeline
# Using setattr for type safety - adds dynamic attribute to Pydantic model instance
setattr(request, "_detected_language", detected_language) # noqa: B010
# STEP 0.1: Multi-step service prefix check (bypass NLU pipeline)
if request.message.startswith(SERVICE_STEP_PREFIXES):
logger.info(
f"[{request.chatId}] #service prefix detected - direct step execution"
)
executor = self._get_service_workflow_executor()
direct_response = await executor.execute_direct_step(
request=request,
time_metric=time_metric,
)
if direct_response is not None:
log_step_timings(time_metric, request.chatId)
return direct_response
# Parse failed — fall through to normal pipeline
logger.warning(
f"[{request.chatId}] Direct step failed, falling through to normal pipeline"
)
# STEP 0.5: Basic Query Validation (before expensive component initialization)
start_time = time.time()
validation_result = validate_query_basic(request.message)
time_metric["query_validation"] = time.time() - start_time
if not validation_result.is_valid:
logger.info(
f"[{request.chatId}] Query validation failed: {validation_result.rejection_reason}"
)
# Get localized message
validation_msg = get_localized_message(
QUERY_VALIDATION_FAILED_MESSAGES, detected_language
)
# Return appropriate response type without initializing components
if request.environment == TEST_DEPLOYMENT_ENVIRONMENT:
return TestOrchestrationResponse(
llmServiceActive=True,
questionOutOfLLMScope=False,
inputGuardFailed=False,
content=validation_msg,
chunks=None,
)
else:
return OrchestrationResponse(
chatId=request.chatId,
llmServiceActive=True,
questionOutOfLLMScope=False,
inputGuardFailed=False,
content=validation_msg,
)
# Initialize all service components (only for valid queries, with timing)
start_time = time.time()
components = self._initialize_service_components(request)
time_metric["initialization"] = time.time() - start_time
if components["guardrails_adapter"]:
start_time = time.time()
input_blocked_response = await self.handle_input_guardrails(
components["guardrails_adapter"], request, costs_metric
)
time_metric["input_guardrails_check"] = time.time() - start_time
if input_blocked_response:
logger.warning(
f"[{request.chatId}] Input blocked before classifier - "
f"saved expensive service discovery"
)
log_step_timings(time_metric, request.chatId)
return input_blocked_response
else:
logger.info(
f"[{request.chatId}] Guardrails not available - "
f"proceeding without input validation"
)
# TOOL CLASSIFIER INTEGRATION
# Route through tool classifier if enabled, otherwise use existing RAG pipeline
if FeatureFlags.TOOL_CLASSIFIER_ENABLED:
try:
logger.info(
f"[{request.chatId}] Tool classifier enabled - routing query"
)
# Initialize tool classifier if not already done
if self.tool_classifier is None:
self.tool_classifier = ToolClassifier(
llm_manager=components["llm_manager"],
orchestration_service=self,
)
logger.info("Tool classifier initialized")
# Classify query to determine workflow (with timing)
start_time = time.time()
classification = await self.tool_classifier.classify(
query=request.message,
language=detected_language,
request=request,
)
time_metric["classifier.classify"] = time.time() - start_time
logger.info(
f"[{request.chatId}] Classification: {classification.workflow.value} "
f"(confidence: {classification.confidence:.2f})"
)
# Route to appropriate workflow (with timing)
start_time = time.time()
response = await self.tool_classifier.route_to_workflow(
classification=classification,
request=request,
is_streaming=False,
time_metric=time_metric,
)
time_metric["classifier.route"] = time.time() - start_time
except Exception as classifier_error:
logger.error(
f"[{request.chatId}] Tool classifier error: {classifier_error}",
exc_info=True,
)
if FeatureFlags.FALLBACK_TO_RAG_ON_ERROR:
logger.info(
f"[{request.chatId}] Falling back to RAG pipeline due to classifier error"
)
# Execute existing RAG pipeline as fallback
response = await self._execute_orchestration_pipeline(
request, components, costs_metric, time_metric
)
else:
raise
else:
# Tool classifier disabled - use existing RAG pipeline
logger.debug(
f"[{request.chatId}] Tool classifier disabled - using RAG pipeline"
)
response = await self._execute_orchestration_pipeline(
request, components, costs_metric, time_metric
)
# Log final costs and return response
self.log_costs(costs_metric)
log_step_timings(time_metric, request.chatId)
# Update budget for the LLM connection
self._update_connection_budget(
request.connection_id, costs_metric, request.environment
)
if self.langfuse_config.langfuse_client:
langfuse = self.langfuse_config.langfuse_client
total_costs = calculate_total_costs(costs_metric)
langfuse.update_current_generation(
metadata={
"total_calls": total_costs.get("total_calls", 0),
"cost_breakdown": costs_metric,
"chat_id": request.chatId,
"author_id": request.authorId,
"environment": request.environment,
},
)
langfuse.flush()
# Persist successful exchange to conversation history (non-streaming)
if should_save_history(
self.conversation_history_store, response, _HISTORY_EXCLUDED_MESSAGES
):
await save_history_round(
self.conversation_history_store,
request.chatId,
request.message,
response.content,
)
return response
except Exception as e:
error_id = generate_error_id()
log_error_with_context(
logger, error_id, "orchestration_request", request.chatId, e
)
if self.langfuse_config.langfuse_client:
langfuse = self.langfuse_config.langfuse_client
langfuse.update_current_generation(
metadata={
"error_id": error_id,
"error_type": type(e).__name__,
"response_type": "technical_issue",
}
)
langfuse.flush()
self.log_costs(costs_metric)
log_step_timings(time_metric, request.chatId)
# Update budget even on error
self._update_connection_budget(
request.connection_id, costs_metric, request.environment
)
return self._create_error_response(request)
async def stream_orchestration_response(
self, request: OrchestrationRequest
) -> AsyncIterator[str]:
"""
Stream orchestration response with validation-first guardrails.
Pipeline:
1. Input Guardrails Check (blocking)
2. Prompt Refinement (blocking)
3. Chunk Retrieval (blocking)
4. Out-of-scope Check (blocking, quick)
5. Stream through NeMo Guardrails (validation-first)
Args:
request: The orchestration request containing user message and context
Yields:
SSE-formatted strings: "data: {json}\\n\\n"
SSE Message Format:
{
"chatId": "...",
"payload": {"content": "..."},
"timestamp": "...",
"sentTo": []
}
Content Types:
- Regular token: "Python", " is", " awesome"
- Stream complete: "END"
- Input blocked: INPUT_GUARDRAIL_VIOLATION_MESSAGE
- Out of scope: OUT_OF_SCOPE_MESSAGE
- Guardrail failed: OUTPUT_GUARDRAIL_VIOLATION_MESSAGE
- Technical error: TECHNICAL_ISSUE_MESSAGE
"""
# Track costs after streaming completes
costs_metric: Dict[str, Dict[str, Any]] = {}
time_metric: Dict[str, float] = {}
# Capture DSPy history baseline before any LLM calls.
# Used at the end of the request to compute the total cost delta,
_lm = dspy.settings.lm
initial_history_length = (
len(_lm.history) if _lm and hasattr(_lm, "history") else 0
)
# STEP 0: Detect language from user message (with timing)
start_time = time.time()
detected_language = detect_language(request.message)
language_name = get_language_name(detected_language)
time_metric["language_detection"] = time.time() - start_time
logger.info(
f"[{request.chatId}] Streaming request - Detected language: {language_name} ({detected_language})"
)
# Store detected language in request for use throughout pipeline
# Using setattr for type safety - adds dynamic attribute to Pydantic model instance
setattr(request, "_detected_language", detected_language) # noqa: B010
# STEP 0.1: Multi-step service prefix check (bypass NLU pipeline)
if request.message.startswith(SERVICE_STEP_PREFIXES):
logger.info(
f"[{request.chatId}] #service prefix detected - direct step stream"
)
executor = self._get_service_workflow_executor()
step_stream = await executor.execute_direct_step_streaming(
request=request,
time_metric=time_metric,
)
if step_stream is not None:
async for chunk in step_stream:
yield chunk
log_step_timings(time_metric, request.chatId)
return
# Parse failed — fall through to normal pipeline
logger.warning(
f"[{request.chatId}] Direct step stream failed, falling through to normal pipeline"
)
# Step 0.5: Basic Query Validation (before guardrails, with timing)
start_time = time.time()
validation_result = validate_query_basic(request.message)
time_metric["query_validation"] = time.time() - start_time
if not validation_result.is_valid:
logger.info(
f"[{request.chatId}] Streaming - Query validation failed: {validation_result.rejection_reason}"
)
# Get localized message
validation_msg = get_localized_message(
QUERY_VALIDATION_FAILED_MESSAGES, detected_language
)
# Yield SSE format error + END marker
yield self.format_sse(request.chatId, validation_msg)
yield self.format_sse(request.chatId, "END")
return # Stop processing
# Use StreamManager for centralized tracking and guaranteed cleanup
async with stream_manager.managed_stream(
chat_id=request.chatId, author_id=request.authorId
) as stream_ctx:
try:
logger.info(
f"[{request.chatId}] [{stream_ctx.stream_id}] Starting streaming orchestration "
f"(environment: {request.environment})"
)
# Initialize all service components (with timing)
start_time = time.time()
components = self._initialize_service_components(request)
time_metric["initialization"] = time.time() - start_time
# This implements fail-fast principle - block malicious/policy-violating inputs
# before expensive operations (service discovery, LLM calls, streaming setup)
logger.info(
f"[{request.chatId}] [{stream_ctx.stream_id}] Checking input guardrails (before classifier)"
)
if components["guardrails_adapter"]:
start_time = time.time()
input_check_result = await self._check_input_guardrails_async(
guardrails_adapter=components["guardrails_adapter"],
user_message=request.message,
costs_metric=costs_metric,
)
time_metric["input_guardrails_check"] = time.time() - start_time
if not input_check_result.allowed:
logger.warning(
f"[{request.chatId}] [{stream_ctx.stream_id}] Input blocked before classifier - "
f"saved expensive service discovery. Reason: {input_check_result.reason}"
)
yield self.format_sse(
request.chatId, INPUT_GUARDRAIL_VIOLATION_MESSAGE
)
yield self.format_sse(request.chatId, "END")
self.log_costs(costs_metric)
# Log timings before returning (for visibility)
log_step_timings(time_metric, request.chatId)
stream_ctx.mark_completed()
return
else:
logger.info(
f"[{request.chatId}] [{stream_ctx.stream_id}] Guardrails not available - "
f"proceeding without input validation"
)
logger.info(
f"[{request.chatId}] [{stream_ctx.stream_id}] Input guardrails passed"
)
# TOOL CLASSIFIER INTEGRATION (STREAMING)
# Route through tool classifier if enabled, otherwise use existing RAG pipeline
if FeatureFlags.TOOL_CLASSIFIER_ENABLED:
try:
logger.info(
f"[{request.chatId}] [{stream_ctx.stream_id}] Tool classifier enabled - routing query (streaming)"
)
# Initialize tool classifier if not already done
if self.tool_classifier is None:
self.tool_classifier = ToolClassifier(
llm_manager=components["llm_manager"],
orchestration_service=self,
)
logger.info(
f"[{request.chatId}] [{stream_ctx.stream_id}] Tool classifier initialized"
)
# Classify query to determine workflow
start_time = time.time()
classification = await self.tool_classifier.classify(
query=request.message,
language=detected_language,
request=request,
)
time_metric["classifier.classify"] = time.time() - start_time
logger.info(
f"[{request.chatId}] [{stream_ctx.stream_id}] Classification: {classification.workflow.value} "
f"(confidence: {classification.confidence:.2f})"
)
# Route to appropriate workflow (streaming)
# route_to_workflow returns AsyncIterator[str] when is_streaming=True
# Inject costs_metric and pre-initialized components into the
# classification context so downstream workflows can reuse them
# without re-initializing (saves ~1.5s on fallback paths).
classification.metadata["costs_metric"] = costs_metric
classification.metadata["components"] = components
start_time = time.time()
stream_result = await self.tool_classifier.route_to_workflow(
classification=classification,
request=request,
is_streaming=True,
time_metric=time_metric,
)
time_metric["classifier.route"] = time.time() - start_time
# Accumulate content for history only on non-RAG workflows;
# RAG routes through _stream_rag_pipeline which has its own hook.
_save_classifier_history = (
self.conversation_history_store is not None
and classification.workflow != WorkflowType.RAG
)
_classifier_accumulated: list[str] = []
# Tracks whether an excluded marker (OOS / guardrail violation /
# error) was observed at any point during the stream. When True
# the entire accumulated buffer is discarded so no partial content
# from before the blocked marker is ever written to Redis.
_history_blocked = False
async for sse_chunk in stream_result:
yield sse_chunk
if _save_classifier_history and not _history_blocked:
extracted = extract_content_from_sse(sse_chunk)
if extracted is not None and extracted != "END":
if extracted in _HISTORY_EXCLUDED_MESSAGES:
# Excluded marker observed — discard any partial
# content accumulated before this point and stop
# accumulating for the rest of the stream.
_classifier_accumulated.clear()
_history_blocked = True
else:
_classifier_accumulated.append(extracted)
# Successfully completed streaming through classifier
logger.info(
f"[{request.chatId}] [{stream_ctx.stream_id}] Tool classifier streaming completed"
)
# Persist conversation history (classifier streaming, non-RAG workflows)
if (
_save_classifier_history
and not _history_blocked
and _classifier_accumulated
):
await save_history_round(
self.conversation_history_store,
request.chatId,
request.message,
"".join(_classifier_accumulated),
)
# Log costs and timings
self.log_costs(costs_metric)
log_step_timings(time_metric, request.chatId)
# Budget update: use full DSPy history delta
_total_usage = get_lm_usage_since(initial_history_length)
self._update_connection_budget(
request.connection_id,
{"streaming_total": _total_usage},
request.environment,
)
stream_ctx.mark_completed()
return # Exit after successful classifier routing
except Exception as classifier_error:
logger.error(
f"[{request.chatId}] [{stream_ctx.stream_id}] Tool classifier error: {classifier_error}",
exc_info=True,
)
if not FeatureFlags.FALLBACK_TO_RAG_ON_ERROR:
# Don't fallback - raise error
raise
# Fallback to RAG pipeline below
logger.info(
f"[{request.chatId}] [{stream_ctx.stream_id}] Falling back to RAG streaming due to classifier error"
)
# Continue to existing RAG streaming pipeline below
else:
logger.debug(
f"[{request.chatId}] [{stream_ctx.stream_id}] Tool classifier disabled - using RAG streaming"
)
# Execute core RAG streaming pipeline
# NOTE: This only executes if tool classifier is disabled or fallback occurred
async for sse_chunk in self._stream_rag_pipeline(
request=request,
components=components,
stream_ctx=stream_ctx,
costs_metric=costs_metric,
time_metric=time_metric,
):
yield sse_chunk
# Pipeline completed successfully.
# Budget update: use full DSPy history delta (covers guardrails,
# refiner, and streaming generation across this request).
_total_usage = get_lm_usage_since(initial_history_length)
self._update_connection_budget(
request.connection_id,
{"streaming_total": _total_usage},
request.environment,
)
return
except Exception as e:
error_id = generate_error_id()
stream_ctx.mark_error(error_id)
log_error_with_context(
logger, error_id, "streaming_orchestration", request.chatId, e
)
yield self.format_sse(request.chatId, TECHNICAL_ISSUE_MESSAGE)
yield self.format_sse(request.chatId, "END")
self.log_costs(costs_metric)
log_step_timings(time_metric, request.chatId)
# Budget update on outer exception using full DSPy history delta.
_total_usage = get_lm_usage_since(initial_history_length)
self._update_connection_budget(
request.connection_id,
{"streaming_total": _total_usage},
request.environment,
)
if self.langfuse_config.langfuse_client:
langfuse = self.langfuse_config.langfuse_client
langfuse.update_current_generation(
metadata={
"error_id": error_id,
"error_type": type(e).__name__,
"streaming": True,
"streaming_failed": True,
"stream_id": stream_ctx.stream_id,
}
)
langfuse.flush()
async def _stream_rag_pipeline(
self,
request: OrchestrationRequest,
components: Dict[str, Any],
stream_ctx: StreamContext,
costs_metric: Dict[str, Dict[str, Any]],
time_metric: Dict[str, float],
) -> AsyncIterator[str]:
"""
Core RAG streaming pipeline without classifier routing.
This method contains the RAG pipeline logic that can be called directly
by workflows to avoid infinite recursion when the tool classifier is enabled.
Pipeline Steps:
1. Refine user prompt (blocking)
2. Retrieve context chunks (blocking)
3. Out-of-scope check (blocking)
4. Stream through NeMo Guardrails (validation-first)
Args:
request: Orchestration request
components: Initialized service components (LLM, retriever, generator, guardrails)
stream_ctx: Stream context for tracking
costs_metric: Dictionary to accumulate costs
time_metric: Dictionary to accumulate timings
Yields:
SSE-formatted strings
"""
streaming_start_time = datetime.now()
detected_language = getattr(request, "_detected_language", "en")
# STEP 1: REFINE USER PROMPT (blocking)
logger.info(
f"[{request.chatId}] [{stream_ctx.stream_id}] RAG Pipeline Step 1: Refining user prompt"
)
start_time = time.time()
conversation_history, conversation_summary = await get_conversation_history(
chat_id=request.chatId,
store=self.conversation_history_store,
fallback=request.conversationHistory,
)
refined_output, refiner_usage = self._refine_user_prompt(
llm_manager=components["llm_manager"],
original_message=request.message,
conversation_history=conversation_history,
conversation_summary=conversation_summary,
)
time_metric["prompt_refiner"] = time.time() - start_time
costs_metric["prompt_refiner"] = refiner_usage
logger.info(
f"[{request.chatId}] [{stream_ctx.stream_id}] Prompt refinement complete"
)
# STEP 2: RETRIEVE CONTEXT CHUNKS (blocking)
logger.info(
f"[{request.chatId}] [{stream_ctx.stream_id}] RAG Pipeline Step 2: Retrieving context chunks"
)
try:
start_time = time.time()
relevant_chunks = await self._safe_retrieve_contextual_chunks(
components["contextual_retriever"], refined_output, request
)
time_metric["contextual_retrieval"] = time.time() - start_time
except (
ContextualRetrieverInitializationError,
ContextualRetrievalFailureError,
) as e:
logger.warning(
f"[{request.chatId}] [{stream_ctx.stream_id}] Contextual retrieval failed: {str(e)}"
)
logger.info(
f"[{request.chatId}] [{stream_ctx.stream_id}] Returning out-of-scope due to retrieval failure"
)
localized_msg = get_localized_message(
OUT_OF_SCOPE_MESSAGES, detected_language
)
yield self.format_sse(request.chatId, localized_msg)
yield self.format_sse(request.chatId, "END")
self.log_costs(costs_metric)
log_step_timings(time_metric, request.chatId)
stream_ctx.mark_completed()
return
if len(relevant_chunks) == 0:
logger.info(
f"[{request.chatId}] [{stream_ctx.stream_id}] No relevant chunks - out of scope"
)
localized_msg = get_localized_message(
OUT_OF_SCOPE_MESSAGES, detected_language