Most samples of using LangChain's Expression Language (LCEL) look like this:
chain = setup_and_retrieval | prompt | model | output_parser
How can I access the source_documents
in a RAG application when using this expression language?
Most samples of using LangChain's Expression Language (LCEL) look like this:
chain = setup_and_retrieval | prompt | model | output_parser
How can I access the source_documents
in a RAG application when using this expression language?
Copyright © 2021 Jogjafile Inc.
This works well for me:
It's called like this:
The way that helped me understand how to do it was this:
question
andchat_history
).RunnablePassthrough.assign
, you can ADD stuff to that dictionary and then pass that on to the next step.RunnablePassthrough.assign
always RETURNS a dictionary.This is what happens in my code example:
RunnablePassthrough.assign
to add a newsource_documents
key to the dictionary. Its value is the result of calling thecondense_question
function (defined elsewhere) that builds and returns a condenser chain. Its condensed result is passed into our retriever (also defined elsewhere).RunnablePassthrough.assign
to add a newcontext
key to the dictionary. Its value is the result of calling aformat_docs
method (defined elsewhere) that combines the source_documents into a single context string.RunnablePassthrough.assign
to add a newprompt
key to the dictionary. Its value is the result of callingqa_prompt
, which is defined asqa_prompt = ChatPromptTemplate.from_messages(...)
.RunnablePassthrough.assign
one more time to add a newresponse
key to the dictionary. Its value is the result of actually calling the llm with the messages from our prompt.response
key contains the LLM's response as anAIMessage
, and thesource_documents
key contains the source documents.I'm sure this can be done in a more concise way, but this worked for me and I can understand it :)