skip to Main Content

I have a mongoDB that stores user chat history using their session ID.

I need to pass this history to ConversationRetrievalChain, using the ConversationBufferMemory.

How can I transform/ insert the history into a new ConversationBufferMemory?

2

Answers


  1. What you can do is to

    1. Create MessagesPlaceholder in PromptTemplate
    prompt = ChatPromptTemplate.from_messages(
        [
            ("system", "You are a helpful chatbot"),
            MessagesPlaceholder(variable_name="history"),
            ("human", "{input}"),
        ]
    )
    
    1. Generate a memory. In your case, you can extract the memory from your MongoDB
    chain = (
        RunnablePassthrough.assign(
            history=RunnableLambda(memory.load_memory_variables) | itemgetter("history")
        )
        | prompt
        | model
    )
    
    inputs = {"input": "hi im bob"}
    response = chain.invoke(inputs)
    print(response)
    
    1. Save the output context into memory
    memory.save_context(inputs, {"output": response.content})
    print(memory.load_memory_variables({})
    
    inputs = {"input": "whats my name"}
    response = chain.invoke(inputs)
    print(response)
    

    The reference doc > https://python.langchain.com/docs/expression_language/cookbook/memory

    Login or Signup to reply.
  2. I am experiencing the same issue. Although I successfully retrieve the chat history from MongoDB for the specific session ID, it is not being utilized in the chain.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search