Python Langchain RAG example code. Unsupported operand types for |: 'method' and 'operator.itemgetter'

1.4k views Asked by At

I am trying to implement the code for Python RAG with chat history from:

https://python.langchain.com/docs/expression_language/cookbook/retrieval#with-memory-and-returning-source-documents

However, I am hitting an error with this code:

# First we add a step to load memory
# This adds a "memory" key to the input object
loaded_memory = RunnablePassthrough.assign(
    chat_history=memory.load_memory_variables | itemgetter("history"),
)

I get the error:

chat_history=memory.load_memory_variables | itemgetter("history"),
                 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^~~~~~~~~~~~~~~~~~~~~~~
TypeError: unsupported operand type(s) for |: 'method' and 'operator.itemgetter'

I have tried to change the code to follow the syntax I have found online for itemgetter:

loaded_memory = RunnablePassthrough.assign(
    chat_history=itemgetter("history")(memory.load_memory_variables({}) ),
)

However I just get a TypeError with this:

TypeError: Expected a Runnable, callable or dict.Instead got an unsupported type: <class 'list'>

For completeness, here is a minimal, reproducible example, using the code from the Langchain docs:

from operator import itemgetter
from langchain.memory import ConversationBufferMemory
from langchain.schema.runnable import RunnablePassthrough

memory = ConversationBufferMemory(return_messages=True, output_key="answer", input_key="question")

loaded_memory = RunnablePassthrough.assign(
    chat_history=memory.load_memory_variables | itemgetter("history"),
)

Am I missing something obvious here?

1

There are 1 answers

0
abest On

it looks like the documentation for this issue has been updated. For any future users who run into the same problem, it is necessary to wrap the memory.load_memory_variables in a RunnableLambda as follows:

from langchain.schema.runnable import RunnableMap, RunnablePassthrough, RunnableLambda

loaded_memory = RunnablePassthrough.assign(
    chat_history=RunnableLambda(readonly_memory.load_memory_variables) | itemgetter("chat_history")
)

RunnableLambda converts a python callable into a Runnable. Once the memory function has been wrapped, the output can be piped to the function returned by itemgetter.