how to add chat memory in a a custom chat engine? #14945
-
This my custom chat engine that wraps a query pipeline:
this is my query pipeline:
how to add memory in this code? |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
To add chat memory functionality to your custom chat engine, you can use the
Here's the updated code: from llama_index.legacy.chat_engine.types import (
AgentChatResponse,
BaseChatEngine,
StreamingAgentChatResponse,
ChatMessage,
)
from typing import AsyncGenerator, Generator, List, Optional, Union
from llama_index.core.memory import BaseMemory, ChatMemoryBuffer
from llama_index.core.storage.chat_store import SimpleChatStore
class CustomChatEngine(BaseChatEngine):
def __init__(self, query_pipeline, memory: BaseMemory, *args, **kwargs):
super().__init__(*args, **kwargs)
self.query_pipeline = query_pipeline
self._memory = memory
def chat(self, message):
try:
# Retrieve chat history
chat_history = self._memory.get()
# Add the new message to the chat history
chat_history.append(ChatMessage(role="user", content=message))
# Process the message with the query pipeline
response = self.query_pipeline.run(query=message)
# Add the response to the chat history
chat_history.append(ChatMessage(role="assistant", content=response))
# Update the memory with the new chat history
self._memory.chat_store.set_messages(self._memory.chat_store_key, chat_history)
print(response)
return response
except Exception as e:
return "An error occurred while processing your query: {}".format(e)
def reset(self) -> None:
# Reset conversation state if applicable
self._memory.chat_store.set_messages(self._memory.chat_store_key, [])
async def achat(
self, message: str, chat_history: Optional[List[ChatMessage]] = None
):
chat_response = await self.query_pipeline.arun(query=message)
return chat_response
# Initialize the query pipeline
vn_component = create_vn_component()
response_component = create_response_component()
qp = QP(
modules={
"input": InputComponent(),
"vn_component": vn_component,
"response_component": response_component,
},
verbose=True,
)
qp.add_link("input", "vn_component", dest_key="input_str")
qp.add_link("vn_component", "response_component", dest_key="response")
# Initialize the chat memory buffer
chat_store = SimpleChatStore()
memory = ChatMemoryBuffer.from_defaults(
token_limit=3000,
chat_store=chat_store,
chat_store_key="user1",
)
# Create the custom chat engine with memory
chat_engine = CustomChatEngine(qp, memory)
print("chat_engine", chat_engine) In this updated code:
This will enable your custom chat engine to maintain a memory of the conversation history. |
Beta Was this translation helpful? Give feedback.
To add chat memory functionality to the
achat
method, you can follow a similar approach as with thechat
method. Here's how you can modify theachat
method to include chat memory:Here's the updated code: