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 | 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."
)
def __init__(
self,
retriever: BaseRetriever,
llm: LLM,
memory: BaseMemory,
chainlit_tag_format: str,
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
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
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.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
)
return super().chat(message=message, chat_history=chat_history)
@trace_method("chat")
def achat(
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
)
return super().achat(message=message, chat_history=chat_history)
@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,
) -> StreamingAgentChatResponse:
"""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:
StreamingAgentChatResponse: Generated response from RAG pipeline with metadata
"""
self._set_chainlit_message_id(
message_id=chainlit_message_id, source_process=source_process
)
return super().stream_chat(message=message, chat_history=chat_history)
@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,
) -> StreamingAgentChatResponse:
"""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:
StreamingAgentChatResponse: Generated response from RAG pipeline with metadata
"""
self._set_chainlit_message_id(
message_id=chainlit_message_id, source_process=source_process
)
return await super().astream_chat(
message=message, chat_history=chat_history
)
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(),
]
)
|