Skip to content

Condense plus context

CondensePlusContextChatEngine #

Bases: BaseChatEngine

对话内容压缩和上下文聊天引擎。

首先将对话内容和最新用户消息压缩为一个独立的问题, 然后从检索器中构建独立问题的上下文, 然后将上下文与提示和用户消息一起传递给LLM以生成响应。

Source code in llama_index/core/chat_engine/condense_plus_context.py
 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
class CondensePlusContextChatEngine(BaseChatEngine):
    """对话内容压缩和上下文聊天引擎。

首先将对话内容和最新用户消息压缩为一个独立的问题,
然后从检索器中构建独立问题的上下文,
然后将上下文与提示和用户消息一起传递给LLM以生成响应。"""

    def __init__(
        self,
        retriever: BaseRetriever,
        llm: LLM,
        memory: BaseMemory,
        context_prompt: Optional[str] = None,
        condense_prompt: Optional[str] = None,
        system_prompt: Optional[str] = None,
        skip_condense: bool = False,
        node_postprocessors: Optional[List[BaseNodePostprocessor]] = None,
        callback_manager: Optional[CallbackManager] = None,
        verbose: bool = False,
    ):
        self._retriever = retriever
        self._llm = llm
        self._memory = memory
        self._context_prompt_template = (
            context_prompt or DEFAULT_CONTEXT_PROMPT_TEMPLATE
        )
        condense_prompt_str = condense_prompt or DEFAULT_CONDENSE_PROMPT_TEMPLATE
        self._condense_prompt_template = PromptTemplate(condense_prompt_str)
        self._system_prompt = system_prompt
        self._skip_condense = skip_condense
        self._node_postprocessors = node_postprocessors or []
        self.callback_manager = callback_manager or CallbackManager([])
        for node_postprocessor in self._node_postprocessors:
            node_postprocessor.callback_manager = self.callback_manager

        self._token_counter = TokenCounter()
        self._verbose = verbose

    @classmethod
    def from_defaults(
        cls,
        retriever: BaseRetriever,
        llm: Optional[LLM] = None,
        service_context: Optional[ServiceContext] = None,
        chat_history: Optional[List[ChatMessage]] = None,
        memory: Optional[BaseMemory] = None,
        system_prompt: Optional[str] = None,
        context_prompt: Optional[str] = None,
        condense_prompt: Optional[str] = None,
        skip_condense: bool = False,
        node_postprocessors: Optional[List[BaseNodePostprocessor]] = None,
        verbose: bool = False,
        **kwargs: Any,
    ) -> "CondensePlusContextChatEngine":
        """使用默认参数初始化一个CondensePlusContextChatEngine。"""
        llm = llm or llm_from_settings_or_context(Settings, service_context)

        chat_history = chat_history or []
        memory = memory or ChatMemoryBuffer.from_defaults(
            chat_history=chat_history, token_limit=llm.metadata.context_window - 256
        )

        return cls(
            retriever=retriever,
            llm=llm,
            memory=memory,
            context_prompt=context_prompt,
            condense_prompt=condense_prompt,
            skip_condense=skip_condense,
            callback_manager=callback_manager_from_settings_or_context(
                Settings, service_context
            ),
            node_postprocessors=node_postprocessors,
            system_prompt=system_prompt,
            verbose=verbose,
        )

    def _condense_question(
        self, chat_history: List[ChatMessage], latest_message: str
    ) -> str:
        """将对话历史和最新用户消息压缩为一个独立的问题。"""
        if self._skip_condense or len(chat_history) == 0:
            return latest_message

        chat_history_str = messages_to_history_str(chat_history)
        logger.debug(chat_history_str)

        return self._llm.predict(
            self._condense_prompt_template,
            question=latest_message,
            chat_history=chat_history_str,
        )

    async def _acondense_question(
        self, chat_history: List[ChatMessage], latest_message: str
    ) -> str:
        """将对话历史和最新用户消息压缩为一个独立的问题。"""
        if self._skip_condense or len(chat_history) == 0:
            return latest_message

        chat_history_str = messages_to_history_str(chat_history)
        logger.debug(chat_history_str)

        return await self._llm.apredict(
            self._condense_prompt_template,
            question=latest_message,
            chat_history=chat_history_str,
        )

    def _retrieve_context(self, message: str) -> Tuple[str, List[NodeWithScore]]:
        """为从检索器中获取的消息构建上下文。"""
        nodes = self._retriever.retrieve(message)
        for postprocessor in self._node_postprocessors:
            nodes = postprocessor.postprocess_nodes(
                nodes, query_bundle=QueryBundle(message)
            )

        context_str = "\n\n".join(
            [n.node.get_content(metadata_mode=MetadataMode.LLM).strip() for n in nodes]
        )
        return context_str, nodes

    async def _aretrieve_context(self, message: str) -> Tuple[str, List[NodeWithScore]]:
        """为从检索器中获取的消息构建上下文。"""
        nodes = await self._retriever.aretrieve(message)
        for postprocessor in self._node_postprocessors:
            nodes = postprocessor.postprocess_nodes(
                nodes, query_bundle=QueryBundle(message)
            )

        context_str = "\n\n".join(
            [n.node.get_content(metadata_mode=MetadataMode.LLM).strip() for n in nodes]
        )
        return context_str, nodes

    def _run_c3(
        self, message: str, chat_history: Optional[List[ChatMessage]] = None
    ) -> Tuple[List[ChatMessage], ToolOutput, List[NodeWithScore]]:
        if chat_history is not None:
            self._memory.set(chat_history)

        chat_history = self._memory.get(input=message)

        # Condense conversation history and latest message to a standalone question
        condensed_question = self._condense_question(chat_history, message)  # type: ignore
        logger.info(f"Condensed question: {condensed_question}")
        if self._verbose:
            print(f"Condensed question: {condensed_question}")

        # Build context for the standalone question from a retriever
        context_str, context_nodes = self._retrieve_context(condensed_question)
        context_source = ToolOutput(
            tool_name="retriever",
            content=context_str,
            raw_input={"message": condensed_question},
            raw_output=context_str,
        )
        logger.debug(f"Context: {context_str}")
        if self._verbose:
            print(f"Context: {context_str}")

        system_message_content = self._context_prompt_template.format(
            context_str=context_str
        )
        if self._system_prompt:
            system_message_content = self._system_prompt + "\n" + system_message_content

        system_message = ChatMessage(
            content=system_message_content, role=self._llm.metadata.system_role
        )

        initial_token_count = self._token_counter.estimate_tokens_in_messages(
            [system_message]
        )

        self._memory.put(ChatMessage(content=message, role=MessageRole.USER))
        chat_messages = [
            system_message,
            *self._memory.get(initial_token_count=initial_token_count),
        ]
        return chat_messages, context_source, context_nodes

    async def _arun_c3(
        self, message: str, chat_history: Optional[List[ChatMessage]] = None
    ) -> Tuple[List[ChatMessage], ToolOutput, List[NodeWithScore]]:
        if chat_history is not None:
            self._memory.set(chat_history)

        chat_history = self._memory.get(input=message)

        # Condense conversation history and latest message to a standalone question
        condensed_question = await self._acondense_question(chat_history, message)  # type: ignore
        logger.info(f"Condensed question: {condensed_question}")
        if self._verbose:
            print(f"Condensed question: {condensed_question}")

        # Build context for the standalone question from a retriever
        context_str, context_nodes = await self._aretrieve_context(condensed_question)
        context_source = ToolOutput(
            tool_name="retriever",
            content=context_str,
            raw_input={"message": condensed_question},
            raw_output=context_str,
        )
        logger.debug(f"Context: {context_str}")
        if self._verbose:
            print(f"Context: {context_str}")

        system_message_content = self._context_prompt_template.format(
            context_str=context_str
        )
        if self._system_prompt:
            system_message_content = self._system_prompt + "\n" + system_message_content

        system_message = ChatMessage(
            content=system_message_content, role=self._llm.metadata.system_role
        )

        initial_token_count = self._token_counter.estimate_tokens_in_messages(
            [system_message]
        )

        self._memory.put(ChatMessage(content=message, role=MessageRole.USER))
        chat_messages = [
            system_message,
            *self._memory.get(initial_token_count=initial_token_count),
        ]

        return chat_messages, context_source, context_nodes

    @trace_method("chat")
    def chat(
        self, message: str, chat_history: Optional[List[ChatMessage]] = None
    ) -> AgentChatResponse:
        chat_messages, context_source, context_nodes = self._run_c3(
            message, chat_history
        )

        # pass the context, system prompt and user message as chat to LLM to generate a response
        chat_response = self._llm.chat(chat_messages)
        assistant_message = chat_response.message
        self._memory.put(assistant_message)

        return AgentChatResponse(
            response=str(assistant_message.content),
            sources=[context_source],
            source_nodes=context_nodes,
        )

    @trace_method("chat")
    def stream_chat(
        self, message: str, chat_history: Optional[List[ChatMessage]] = None
    ) -> StreamingAgentChatResponse:
        chat_messages, context_source, context_nodes = self._run_c3(
            message, chat_history
        )

        # pass the context, system prompt and user message as chat to LLM to generate a response
        chat_response = StreamingAgentChatResponse(
            chat_stream=self._llm.stream_chat(chat_messages),
            sources=[context_source],
            source_nodes=context_nodes,
        )
        thread = Thread(
            target=chat_response.write_response_to_history, args=(self._memory,)
        )
        thread.start()

        return chat_response

    @trace_method("chat")
    async def achat(
        self, message: str, chat_history: Optional[List[ChatMessage]] = None
    ) -> AgentChatResponse:
        chat_messages, context_source, context_nodes = await self._arun_c3(
            message, chat_history
        )

        # pass the context, system prompt and user message as chat to LLM to generate a response
        chat_response = await self._llm.achat(chat_messages)
        assistant_message = chat_response.message
        self._memory.put(assistant_message)

        return AgentChatResponse(
            response=str(assistant_message.content),
            sources=[context_source],
            source_nodes=context_nodes,
        )

    @trace_method("chat")
    async def astream_chat(
        self, message: str, chat_history: Optional[List[ChatMessage]] = None
    ) -> StreamingAgentChatResponse:
        chat_messages, context_source, context_nodes = await self._arun_c3(
            message, chat_history
        )

        # pass the context, system prompt and user message as chat to LLM to generate a response
        chat_response = StreamingAgentChatResponse(
            achat_stream=await self._llm.astream_chat(chat_messages),
            sources=[context_source],
            source_nodes=context_nodes,
        )
        asyncio.create_task(chat_response.awrite_response_to_history(self._memory))
        return chat_response

    def reset(self) -> None:
        # Clear chat history
        self._memory.reset()

    @property
    def chat_history(self) -> List[ChatMessage]:
        """获取聊天记录。"""
        return self._memory.get_all()

chat_history property #

chat_history: List[ChatMessage]

获取聊天记录。

from_defaults classmethod #

from_defaults(
    retriever: BaseRetriever,
    llm: Optional[LLM] = None,
    service_context: Optional[ServiceContext] = None,
    chat_history: Optional[List[ChatMessage]] = None,
    memory: Optional[BaseMemory] = None,
    system_prompt: Optional[str] = None,
    context_prompt: Optional[str] = None,
    condense_prompt: Optional[str] = None,
    skip_condense: bool = False,
    node_postprocessors: Optional[
        List[BaseNodePostprocessor]
    ] = None,
    verbose: bool = False,
    **kwargs: Any
) -> CondensePlusContextChatEngine

使用默认参数初始化一个CondensePlusContextChatEngine。

Source code in llama_index/core/chat_engine/condense_plus_context.py
 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
@classmethod
def from_defaults(
    cls,
    retriever: BaseRetriever,
    llm: Optional[LLM] = None,
    service_context: Optional[ServiceContext] = None,
    chat_history: Optional[List[ChatMessage]] = None,
    memory: Optional[BaseMemory] = None,
    system_prompt: Optional[str] = None,
    context_prompt: Optional[str] = None,
    condense_prompt: Optional[str] = None,
    skip_condense: bool = False,
    node_postprocessors: Optional[List[BaseNodePostprocessor]] = None,
    verbose: bool = False,
    **kwargs: Any,
) -> "CondensePlusContextChatEngine":
    """使用默认参数初始化一个CondensePlusContextChatEngine。"""
    llm = llm or llm_from_settings_or_context(Settings, service_context)

    chat_history = chat_history or []
    memory = memory or ChatMemoryBuffer.from_defaults(
        chat_history=chat_history, token_limit=llm.metadata.context_window - 256
    )

    return cls(
        retriever=retriever,
        llm=llm,
        memory=memory,
        context_prompt=context_prompt,
        condense_prompt=condense_prompt,
        skip_condense=skip_condense,
        callback_manager=callback_manager_from_settings_or_context(
            Settings, service_context
        ),
        node_postprocessors=node_postprocessors,
        system_prompt=system_prompt,
        verbose=verbose,
    )