Chat_engine

This module contains functionality related to the the chat_engine module for augmentation.components.chat_engines.langfuse.

Chat_engine

LangfuseChatEngine

Bases: 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.

Source code in src/augmentation/components/chat_engines/langfuse/chat_engine.py
 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)
        )

__init__(retriever, llm, memory, chainlit_tag_format, guardrails_engine, context_prompt=None, context_refine_prompt=None, condense_prompt=None, system_prompt=None, skip_condense=False, node_postprocessors=None, callback_manager=None, verbose=False)

Initialize LangfuseChatEngine with retriever, LLM, and optional parameters.

Parameters:
  • retriever (BaseRetriever) –

    Document retriever for RAG

  • llm (LLM) –

    Language model for response generation

  • memory (BaseMemory) –

    Memory buffer for chat history

  • chainlit_tag_format (str) –

    Format for Chainlit message ID in Langfuse

  • guardrails_engine (BaseGuardrailsEngine) –

    Guardrail engine for input/output validation

  • context_prompt (Optional[Union[str, PromptTemplate]], default: None ) –

    Prompt for context generation

  • context_refine_prompt (Optional[Union[str, PromptTemplate]], default: None ) –

    Prompt for refining context

  • condense_prompt (Optional[Union[str, PromptTemplate]], default: None ) –

    Prompt for condensing context

  • system_prompt (Optional[str], default: None ) –

    System prompt for LLM

  • input_guardrail_prompt_template

    Prompt template for input validation

  • output_guardrail_prompt_template

    Prompt template for output validation

  • skip_condense (bool, default: False ) –

    Flag to skip context condensing

  • node_postprocessors (Optional[List[BaseNodePostprocessor]], default: None ) –

    List of postprocessors for node processing

  • callback_manager (Optional[CallbackManager], default: None ) –

    Callback manager for tracing

  • verbose (bool, default: False ) –

    Flag for verbose output

Source code in src/augmentation/components/chat_engines/langfuse/chat_engine.py
 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
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

achat(message, chat_history=None, chainlit_message_id=None, source_process=SourceProcess.CHAT_COMPLETION) async

Asynchronously process a query using RAG pipeline with Langfuse tracing.

Parameters:
  • message (str) –

    Raw query string to process

  • chat_history (Optional[List[ChatMessage]], default: None ) –

    Optional chat history for context

  • chainlit_message_id (str, default: None ) –

    Optional ID for linking to Chainlit message in UI

  • source_process (SourceProcess, default: CHAT_COMPLETION ) –

    Context identifier indicating query's origin source

Returns:
  • AgentChatResponse( AgentChatResponse ) –

    Generated response from RAG pipeline with metadata

Source code in src/augmentation/components/chat_engines/langfuse/chat_engine.py
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
@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

astream_chat(message, chat_history=None, chainlit_message_id=None, source_process=SourceProcess.CHAT_COMPLETION) async

Asynchronously process a query using RAG pipeline with Langfuse tracing.

Parameters:
  • message (str) –

    Raw query string to process

  • chat_history (Optional[List[ChatMessage]], default: None ) –

    Optional chat history for context

  • chainlit_message_id (str, default: None ) –

    Optional ID for linking to Chainlit message in UI

  • source_process (SourceProcess, default: CHAT_COMPLETION ) –

    Context identifier indicating query's origin source

Returns:
  • AgentChatResponse( AgentChatResponse ) –

    Generated response from RAG pipeline with dummy streaming

Source code in src/augmentation/components/chat_engines/langfuse/chat_engine.py
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
@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

chat(message, chat_history=None, chainlit_message_id=None, source_process=SourceProcess.CHAT_COMPLETION)

Process a query using RAG pipeline with Langfuse tracing.

Parameters:
  • message (str) –

    Raw query string to process

  • chat_history (Optional[List[ChatMessage]], default: None ) –

    Optional chat history for context

  • chainlit_message_id (str, default: None ) –

    Optional ID for linking to Chainlit message in UI

  • source_process (SourceProcess, default: CHAT_COMPLETION ) –

    Context identifier indicating query's origin source

Returns:
  • AgentChatResponse( AgentChatResponse ) –

    Generated response from RAG pipeline with metadata

Source code in src/augmentation/components/chat_engines/langfuse/chat_engine.py
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
@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

get_current_langfuse_trace()

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( StatefulTraceClient ) –

    Active Langfuse trace or None if not found

Source code in src/augmentation/components/chat_engines/langfuse/chat_engine.py
306
307
308
309
310
311
312
313
314
315
316
317
318
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

set_session_id(session_id)

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.

Parameters:
  • session_id (str) –

    Unique identifier for current user session

Source code in src/augmentation/components/chat_engines/langfuse/chat_engine.py
320
321
322
323
324
325
326
327
328
329
330
331
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

stream_chat(message, chat_history=None, chainlit_message_id=None, source_process=SourceProcess.CHAT_COMPLETION)

Process a query using RAG pipeline with Langfuse tracing.

Parameters:
  • message (str) –

    Raw query string to process

  • chat_history (Optional[List[ChatMessage]], default: None ) –

    Optional chat history for context

  • chainlit_message_id (str, default: None ) –

    Optional ID for linking to Chainlit message in UI

  • source_process (SourceProcess, default: CHAT_COMPLETION ) –

    Context identifier indicating query's origin source

Returns:
  • AgentChatResponse( AgentChatResponse ) –

    Generated response from RAG pipeline with dummy streaming

Source code in src/augmentation/components/chat_engines/langfuse/chat_engine.py
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
@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

LangfuseChatEngineFactory

Bases: Factory

Factory for creating configured LangfuseChatEngine instances.

Constructs and connects components needed for the RAG pipeline.

Source code in src/augmentation/components/chat_engines/langfuse/chat_engine.py
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
class LangfuseChatEngineFactory(Factory):
    """Factory for creating configured LangfuseChatEngine instances.

    Constructs and connects components needed for the RAG pipeline.
    """

    _configuration_class: Type = AugmentationConfiguration

    @classmethod
    def _create_instance(
        cls, configuration: AugmentationConfiguration
    ) -> LangfuseChatEngine:
        """Create and configure a LangfuseChatEngine instance from configuration.

        Instantiates all RAG pipeline components based on configuration settings,
        connects them with a shared callback manager for tracing, and assembles
        them into a complete chat engine.

        Args:
            configuration: Complete augmentation configuration containing
                           settings for all components

        Returns:
            LangfuseChatEngine: Fully configured RAG chat engine with tracing
        """
        chat_engine_configuration = configuration.augmentation.chat_engine
        llm = LLMRegistry.get(chat_engine_configuration.llm.provider).create(
            chat_engine_configuration.llm
        )
        retriever = RetrieverRegistry.get(
            chat_engine_configuration.retriever.name
        ).create(configuration)
        postprocessors = [
            PostprocessorRegistry.get(postprocessor_configuration.name).create(
                postprocessor_configuration
            )
            for postprocessor_configuration in chat_engine_configuration.postprocessors
        ]
        langfuse_callback_manager = LlamaIndexCallbackManagerFactory.create(
            configuration.augmentation.langfuse
        )
        memory = ChatMemoryBuffer(
            chat_history=[], token_limit=llm.metadata.context_window - 256
        )
        (
            condense_prompt_template,
            context_prompt_template,
            context_refine_prompt_template,
            system_prompt_template,
        ) = cls._get_prompt_templates(configuration=configuration.augmentation)
        guardrails_configuration = (
            configuration.augmentation.chat_engine.guardrails
        )
        guardrails_engine = GuardrailsRegistry.get(
            guardrails_configuration.name
        ).create(configuration=configuration.augmentation)

        retriever.callback_manager = langfuse_callback_manager
        llm.callback_manager = langfuse_callback_manager
        for postprocessor in postprocessors:
            postprocessor.callback_manager = langfuse_callback_manager

        return LangfuseChatEngine(
            retriever=retriever,
            llm=llm,
            node_postprocessors=postprocessors,
            callback_manager=langfuse_callback_manager,
            memory=memory,
            context_prompt=context_prompt_template,
            system_prompt=system_prompt_template,
            context_refine_prompt=context_refine_prompt_template,
            condense_prompt=condense_prompt_template,
            chainlit_tag_format=configuration.augmentation.langfuse.chainlit_tag_format,
            guardrails_engine=guardrails_engine,
        )

    @staticmethod
    def _get_prompt_templates(
        configuration: _AugmentationConfiguration,
    ) -> tuple:
        """Retrieves the prompt template for the augmentation process.

        Args:
            configuration: Configuration object containing prompt templates settings.

        Returns:
            Tuple of prompt templates for condensing, context generation,
            context refinement, system prompts.
        """
        langfuse_prompt_service = LangfusePromptServiceFactory.create(
            configuration=configuration.langfuse
        )

        condense_prompt_template = langfuse_prompt_service.get_prompt_template(
            prompt_name=configuration.chat_engine.prompt_templates.condense_prompt_name
        )
        context_prompt_template = langfuse_prompt_service.get_prompt_template(
            prompt_name=configuration.chat_engine.prompt_templates.context_prompt_name
        )
        context_refine_prompt_template = langfuse_prompt_service.get_prompt_template(
            prompt_name=configuration.chat_engine.prompt_templates.context_refine_prompt_name
        )
        system_prompt_template = langfuse_prompt_service.get_prompt_template(
            prompt_name=configuration.chat_engine.prompt_templates.system_prompt_name
        )

        return (
            condense_prompt_template,
            context_prompt_template,
            context_refine_prompt_template,
            system_prompt_template,
        )

SourceProcess

Bases: Enum

Enumeration of possible chat processing sources.

Attributes:
  • CHAT_COMPLETION

    Query from interactive chat completion interface

  • DEPLOYMENT_EVALUATION

    Query from automated deployment testing and evaluation

Source code in src/augmentation/components/chat_engines/langfuse/chat_engine.py
37
38
39
40
41
42
43
44
45
46
class SourceProcess(Enum):
    """Enumeration of possible chat processing sources.

    Attributes:
        CHAT_COMPLETION: Query from interactive chat completion interface
        DEPLOYMENT_EVALUATION: Query from automated deployment testing and evaluation
    """

    CHAT_COMPLETION = 1
    DEPLOYMENT_EVALUATION = 2