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 | class LangfuseChatEngine(CondensePlusContextChatEngine):
"""Custom chat engine implementing Retrieval-Augmented Generation (RAG).
Coordinates retrieval, post-processing, and response generation for RAG workflow.
Integrates with Langfuse for tracing and Chainlit for message tracking.
"""
chainlit_tag_format: str = Field(
description="Format of the tag used to retrieve the trace by chainlit message id in Langfuse."
)
input_guardrail_prompt_template: Optional[PromptTemplate] = Field(
description="Prompt template for validating user input compliance",
default=None,
)
output_guardrail_prompt_template: Optional[PromptTemplate] = Field(
description="Prompt template for validating response output compliance",
default=None,
)
def __init__(
self,
retriever: BaseRetriever,
llm: LLM,
memory: BaseMemory,
chainlit_tag_format: str,
guardrails_engine: BaseGuardrailsEngine,
context_prompt: Optional[Union[str, PromptTemplate]] = None,
context_refine_prompt: Optional[Union[str, PromptTemplate]] = None,
condense_prompt: Optional[Union[str, PromptTemplate]] = None,
system_prompt: Optional[str] = None,
skip_condense: bool = False,
node_postprocessors: Optional[List[BaseNodePostprocessor]] = None,
callback_manager: Optional[CallbackManager] = None,
verbose: bool = False,
):
"""
Initialize LangfuseChatEngine with retriever, LLM, and optional parameters.
Args:
retriever: Document retriever for RAG
llm: Language model for response generation
memory: Memory buffer for chat history
chainlit_tag_format: Format for Chainlit message ID in Langfuse
guardrails_engine: Guardrail engine for input/output validation
context_prompt: Prompt for context generation
context_refine_prompt: Prompt for refining context
condense_prompt: Prompt for condensing context
system_prompt: System prompt for LLM
input_guardrail_prompt_template: Prompt template for input validation
output_guardrail_prompt_template: Prompt template for output validation
skip_condense: Flag to skip context condensing
node_postprocessors: List of postprocessors for node processing
callback_manager: Callback manager for tracing
verbose: Flag for verbose output
"""
super().__init__(
retriever=retriever,
llm=llm,
memory=memory,
context_prompt=context_prompt,
context_refine_prompt=context_refine_prompt,
condense_prompt=condense_prompt,
system_prompt=system_prompt,
skip_condense=skip_condense,
node_postprocessors=node_postprocessors,
callback_manager=callback_manager,
verbose=verbose,
)
self.guardrails_engine = guardrails_engine
self.chainlit_tag_format = chainlit_tag_format
@trace_method("chat")
def chat(
self,
message: str,
chat_history: Optional[List[ChatMessage]] = None,
chainlit_message_id: str = None,
source_process: SourceProcess = SourceProcess.CHAT_COMPLETION,
) -> AgentChatResponse:
"""Process a query using RAG pipeline with Langfuse tracing.
Args:
message: Raw query string to process
chat_history: Optional chat history for context
chainlit_message_id: Optional ID for linking to Chainlit message in UI
source_process: Context identifier indicating query's origin source
Returns:
AgentChatResponse: Generated response from RAG pipeline with metadata
"""
self._set_chainlit_message_id(
message_id=chainlit_message_id, source_process=source_process
)
guarded_response = self.guardrails_engine.input_guard(
message=message, is_stream=False
)
if guarded_response:
self._save_chat_history(
input_message=message, output_message=guarded_response.response
)
return guarded_response
response = super().chat(message=message, chat_history=chat_history)
guarded_response = self.guardrails_engine.output_guard(
message=response.response, is_stream=False
)
if guarded_response:
self._save_chat_history(
input_message=message, output_message=guarded_response.response
)
return guarded_response
return response
@trace_method("chat")
async def achat(
self,
message: str,
chat_history: Optional[List[ChatMessage]] = None,
chainlit_message_id: str = None,
source_process: SourceProcess = SourceProcess.CHAT_COMPLETION,
) -> AgentChatResponse:
"""Asynchronously process a query using RAG pipeline with Langfuse tracing.
Args:
message: Raw query string to process
chat_history: Optional chat history for context
chainlit_message_id: Optional ID for linking to Chainlit message in UI
source_process: Context identifier indicating query's origin source
Returns:
AgentChatResponse: Generated response from RAG pipeline with metadata
"""
self._set_chainlit_message_id(
message_id=chainlit_message_id, source_process=source_process
)
guarded_response = self.guardrails_engine.input_guard(
message=message, is_stream=False
)
if guarded_response:
self._save_chat_history(
input_message=message, output_message=guarded_response.response
)
return guarded_response
response = await super().achat(
message=message, chat_history=chat_history
)
guarded_response = self.guardrails_engine.output_guard(
message=response.response, is_stream=False
)
if guarded_response:
self._save_chat_history(
input_message=message, output_message=guarded_response.response
)
return guarded_response
return response
@trace_method("chat")
def stream_chat(
self,
message: str,
chat_history: Optional[List[ChatMessage]] = None,
chainlit_message_id: str = None,
source_process: SourceProcess = SourceProcess.CHAT_COMPLETION,
) -> AgentChatResponse:
"""Process a query using RAG pipeline with Langfuse tracing.
Args:
message: Raw query string to process
chat_history: Optional chat history for context
chainlit_message_id: Optional ID for linking to Chainlit message in UI
source_process: Context identifier indicating query's origin source
Returns:
AgentChatResponse: Generated response from RAG pipeline with dummy streaming
"""
self._set_chainlit_message_id(
message_id=chainlit_message_id, source_process=source_process
)
guarded_response = self.guardrails_engine.input_guard(
message=message, is_stream=True
)
if guarded_response:
self._save_chat_history(
input_message=message, output_message=guarded_response.response
)
return guarded_response
response = super().chat(message=message, chat_history=chat_history)
guarded_response = self.guardrails_engine.output_guard(
message=response.response, is_stream=True
)
if guarded_response:
self._save_chat_history(
input_message=message, output_message=guarded_response.response
)
return guarded_response
response.is_dummy_stream = True
return response
@trace_method("chat")
async def astream_chat(
self,
message: str,
chat_history: Optional[List[ChatMessage]] = None,
chainlit_message_id: str = None,
source_process: SourceProcess = SourceProcess.CHAT_COMPLETION,
) -> AgentChatResponse:
"""Asynchronously process a query using RAG pipeline with Langfuse tracing.
Args:
message: Raw query string to process
chat_history: Optional chat history for context
chainlit_message_id: Optional ID for linking to Chainlit message in UI
source_process: Context identifier indicating query's origin source
Returns:
AgentChatResponse: Generated response from RAG pipeline with dummy streaming
"""
self._set_chainlit_message_id(
message_id=chainlit_message_id, source_process=source_process
)
guarded_response = self.guardrails_engine.input_guard(
message=message, is_stream=True
)
if guarded_response:
self._save_chat_history(
input_message=message, output_message=guarded_response.response
)
return guarded_response
response = await super().achat(
message=message, chat_history=chat_history
)
guarded_response = self.guardrails_engine.output_guard(
message=response.response, is_stream=True
)
if guarded_response:
self._save_chat_history(
input_message=message, output_message=guarded_response.response
)
return guarded_response
response.is_dummy_stream = True
return response
def get_current_langfuse_trace(self) -> StatefulTraceClient:
"""Retrieve current Langfuse trace from registered callback handler.
Searches through callback handlers to find active LlamaIndexCallbackHandler
and extract its associated Langfuse trace for monitoring or annotation.
Returns:
StatefulTraceClient: Active Langfuse trace or None if not found
"""
for handler in self.callback_manager.handlers:
if isinstance(handler, LlamaIndexCallbackHandler):
return handler.trace
return None
def set_session_id(self, session_id: str) -> None:
"""Set session ID for Langfuse tracing to group related queries.
Updates the session identifier in all registered Langfuse callback handlers
to enable session-level analytics and trace grouping.
Args:
session_id: Unique identifier for current user session
"""
for handler in self.callback_manager.handlers:
if isinstance(handler, LlamaIndexCallbackHandler):
handler.session_id = session_id
def _set_chainlit_message_id(
self, message_id: str, source_process: SourceProcess
) -> None:
"""Configure Chainlit message tracking in Langfuse trace.
Links the current Langfuse trace to a Chainlit message ID and tags
with the processing source context for traceability in the Langfuse UI.
Args:
message_id: Chainlit message identifier to reference
source_process: Source context enum categorizing the query origin
"""
for handler in self.callback_manager.handlers:
if isinstance(handler, LlamaIndexCallbackHandler):
handler.set_trace_params(
tags=[
self.chainlit_tag_format.format(message_id=message_id),
source_process.name.lower(),
]
)
def _save_chat_history(
self, input_message: str, output_message: str
) -> None:
"""Save chat history to memory buffer.
Args:
input_message: User input message
output_message: Generated response message
"""
self._memory.put(
ChatMessage(role=MessageRole.USER, content=input_message)
)
self._memory.put(
ChatMessage(role=MessageRole.ASSISTANT, content=output_message)
)
|