LangChain create_retrieval_chain Import Error: Fix in 1.x
The langchain create_retrieval_chain import error happens because LangChain 1.0 moved legacy chains to the langchain-classic package. Run pip install langchain-classic and import from langchain_classic.chains, or migrate to an LCEL pipeline.
- LangChain 1.0 removed RetrievalQA, create_retrieval_chain, create_stuff_documents_chain and create_history_aware_retriever from langchain; they now live in langchain-classic.
- The one-minute fix is pip install langchain-classic and changing the import prefix from langchain.chains to langchain_classic.chains.
- create_retrieval_chain takes {'input': ...} and returns input, context and answer, whereas RetrievalQA used query, source_documents and result.
- For new code, an LCEL pipeline (retriever | format_docs | prompt | llm | StrOutputParser) or create_agent with a retriever tool avoids legacy chains entirely.
- Check pip show langchain langchain-core langchain-classic inside the exact interpreter or notebook kernel that raises the error.
Why does create_retrieval_chain fail to import in LangChain 1.x?
LangChain 1.0 (October 2025) cut the main langchain package down to a small surface built around agents (create_agent), models, tools and messages. The older chain classes were not deleted. They were moved into a separate package called langchain-classic, so that existing applications could keep running while new code moved to agents and LCEL.
Tutorials written for 0.2 and 0.3 use from langchain.chains import create_retrieval_chain and from langchain.chains.combine_documents import create_stuff_documents_chain. In 1.x those modules no longer exist, so Python raises ModuleNotFoundError (no module named langchain.chains.retrieval) or ImportError (cannot import name).
The same move affected RetrievalQA, ConversationalRetrievalChain, create_history_aware_retriever, LLMChain and most other classes in langchain.chains. If one of them fails, the cause is the same, and so is the fix.
How do I fix the import error in under a minute?
Install the compatibility package and change the import prefix. Nothing else in your chain code needs to change.
- Install it in the same environment that runs your app: pip install -U langchain-classic
- Replace from langchain.chains import create_retrieval_chain with from langchain_classic.chains import create_retrieval_chain.
- Replace from langchain.chains.combine_documents import create_stuff_documents_chain with from langchain_classic.chains.combine_documents import create_stuff_documents_chain.
- Do the same for RetrievalQA, ConversationalRetrievalChain and create_history_aware_retriever, all importable from langchain_classic.chains.
- Restart the process or notebook kernel so the new package is picked up.
# before (0.2 / 0.3)
from langchain.chains import create_retrieval_chain
from langchain.chains.combine_documents import create_stuff_documents_chain
# after (1.x)
from langchain_classic.chains import create_retrieval_chain
from langchain_classic.chains.combine_documents import create_stuff_documents_chainWhich old imports moved, and where do they live now?
Besides chains, several other import paths from older tutorials break for related reasons: integrations were split into partner packages years ago and the old re-exports are gone. Use this table when you migrate a whole file.
| Old import (0.2/0.3) | 1.x location | Package to install |
|---|---|---|
| langchain.chains.RetrievalQA | langchain_classic.chains.RetrievalQA | langchain-classic |
| langchain.chains.create_retrieval_chain (langchain.chains.retrieval) | langchain_classic.chains.create_retrieval_chain | langchain-classic |
| langchain.chains.combine_documents.create_stuff_documents_chain | langchain_classic.chains.combine_documents.create_stuff_documents_chain | langchain-classic |
| langchain.chains.create_history_aware_retriever | langchain_classic.chains.create_history_aware_retriever | langchain-classic |
| langchain.prompts.ChatPromptTemplate | langchain_core.prompts.ChatPromptTemplate | langchain-core |
| langchain.schema.Document | langchain_core.documents.Document | langchain-core |
| langchain.text_splitter.RecursiveCharacterTextSplitter | langchain_text_splitters.RecursiveCharacterTextSplitter | langchain-text-splitters |
| langchain.vectorstores.Chroma | langchain_chroma.Chroma | langchain-chroma |
| langchain.embeddings.OpenAIEmbeddings | langchain_openai.OpenAIEmbeddings | langchain-openai |
| langchain.chat_models.ChatOpenAI | langchain_openai.ChatOpenAI | langchain-openai |
| Other community vector stores and loaders | langchain_community.vectorstores / document_loaders, or a partner package | langchain-community |
Why does the error persist after installing langchain-classic?
Most remaining failures are environment problems, not code problems. Start by checking what the failing interpreter actually sees, then match your symptom in the table below.
| Symptom | Likely cause | Fix |
|---|---|---|
| No module named langchain_classic after installing | pip installed into a different environment than the one running | Use python -m pip install, and in notebooks run %pip install langchain-classic, then restart the kernel |
| cannot import name from langchain_core | langchain-core is older than what langchain-classic or langchain requires | pip install -U langchain langchain-core langchain-classic langchain-openai together |
| langchain.__file__ points to your project folder | A local file or folder named langchain.py shadows the package | Rename it and delete its __pycache__ directory |
| Install fails with a Python requirement error | LangChain 1.x needs Python 3.10 or newer | Upgrade the interpreter or recreate the venv |
| Works in terminal, fails in Jupyter or VS Code | Notebook kernel uses another interpreter | Select the venv's kernel and restart it |
python -m pip show langchain langchain-core langchain-classic
python -c "import sys; print(sys.executable, sys.version)"
python -c "import langchain, sys; print(langchain.__file__)"What does a working create_retrieval_chain example look like, and how does it differ from RetrievalQA?
The chain needs three parts: a retriever (not a vector store), a prompt containing both {context} and {input}, and a stuff documents chain that fills {context} with the retrieved documents. Omitting {context} does not raise an error: the retrieved documents are silently ignored and the model answers without them. A prompt that uses a different name such as {question} raises a missing-variable error.
Moving from RetrievalQA changes the invocation shape and output keys, so any code that reads the result needs updating. Sources are always returned now, so return_source_documents is no longer needed.
| Aspect | RetrievalQA | create_retrieval_chain | LCEL pipeline |
|---|---|---|---|
| Input | {'query': ...} | {'input': ...} | A plain string |
| Answer | result['result'] | result['answer'] | The returned string |
| Sources | source_documents (needs return_source_documents=True) | context (always included) | Only if you add them with RunnableParallel |
| Prompt variables | context, question | context, input | Whatever you define |
| Status | Legacy, in langchain_classic | Legacy, in langchain_classic | Core, recommended |
from langchain_classic.chains import create_retrieval_chain
from langchain_classic.chains.combine_documents import create_stuff_documents_chain
from langchain_core.prompts import ChatPromptTemplate
from langchain_openai import ChatOpenAI, OpenAIEmbeddings
from langchain_chroma import Chroma
vectorstore = Chroma(collection_name="docs", embedding_function=OpenAIEmbeddings(),
persist_directory="./chroma")
retriever = vectorstore.as_retriever(search_kwargs={"k": 4}) # retriever, not vectorstore
prompt = ChatPromptTemplate.from_messages([
("system", "Answer only from the context. If unsure, say you don't know.\n\n{context}"),
("human", "{input}"),
])
llm = ChatOpenAI(model="gpt-4o-mini", temperature=0)
qa_chain = create_stuff_documents_chain(llm, prompt)
rag_chain = create_retrieval_chain(retriever, qa_chain)
result = rag_chain.invoke({"input": "What is the refund policy?"})
print(result["answer"])
print([d.metadata for d in result["context"]])How do I do RAG in 1.x without legacy chains?
The recommended chain-free approach is an LCEL pipeline. It is a few lines, fully visible, and supports streaming and async.
RunnablePassthrough forwards the question, and RunnableParallel keeps the retrieved documents so you can return sources next to the answer.
from langchain_core.runnables import RunnablePassthrough, RunnableParallel
from langchain_core.output_parsers import StrOutputParser
from langchain_core.prompts import ChatPromptTemplate
def format_docs(docs):
return "\n\n".join(d.page_content for d in docs)
prompt = ChatPromptTemplate.from_template(
"Answer from the context only.\n\n{context}\n\nQuestion: {question}")
answer_chain = prompt | llm | StrOutputParser()
rag = (
RunnableParallel(context=retriever, question=RunnablePassthrough())
.assign(answer=lambda x: answer_chain.invoke(
{"context": format_docs(x["context"]), "question": x["question"]}))
)
out = rag.invoke("What is the refund policy?")
# out keys: context (list of Documents), question, answerWhen should I use an agent instead, and how do I keep chat history?
Choose by who decides when to retrieve. A fixed pipeline always retrieves once, which is cheap, predictable and fast. An agent with a retriever tool lets the model skip retrieval, rephrase queries or search several times, at the cost of extra model calls and less predictable behavior.
A two-step chain suits FAQ and document lookup. Agentic RAG suits questions needing multiple searches or a mix of tools. For complex branching, a LangGraph graph gives explicit control.
For history, the legacy route is create_history_aware_retriever from langchain_classic.chains. It rewrites a follow-up such as "and for EU orders?" into a standalone query using a prompt with a MessagesPlaceholder named chat_history, and you include chat_history in the invoke input.
The current route is the agent checkpointer shown below: the thread_id keeps the conversation, and the model rewrites queries itself when it calls the tool. For LCEL pipelines, wrap the runnable in RunnableWithMessageHistory. In production, replace InMemorySaver with a persistent checkpointer.
from langchain.agents import create_agent
from langchain.tools import tool
from langgraph.checkpoint.memory import InMemorySaver
@tool
def search_docs(query: str) -> str:
"""Search the knowledge base for passages relevant to the query."""
docs = retriever.invoke(query)
return "\n\n".join(d.page_content for d in docs)
agent = create_agent(
model="openai:gpt-4o-mini",
tools=[search_docs],
system_prompt="Use search_docs before answering factual questions.",
checkpointer=InMemorySaver(),
)
cfg = {"configurable": {"thread_id": "user-1"}}
res = agent.invoke({"messages": [{"role": "user", "content": "What is the refund policy?"}]}, cfg)
print(res["messages"][-1].content) Common questions
Is RetrievalQA deprecated, and what replaces it?
RetrievalQA is legacy and now lives in langchain_classic.chains. The direct replacement is create_retrieval_chain with create_stuff_documents_chain, and the preferred long-term replacement is an LCEL pipeline or create_agent with a retriever tool.
Do I still need create_stuff_documents_chain in LangChain 1.x?
Only if you use create_retrieval_chain. It is available from langchain_classic.chains.combine_documents. In an LCEL pipeline you replace it with a small format_docs function that joins page_content, which gives you more control.
Can I use langchain-classic together with langchain 1.x?
Yes, they are designed to be installed side by side. Keep langchain, langchain-core and langchain-classic on current compatible versions, and upgrade them together to avoid cannot import name errors.
Why do I get a missing variable error for context or input?
The stuff documents chain injects the retrieved documents into {context}, and create_retrieval_chain passes your question as {input}. A prompt that uses a different name such as {question} raises a missing-variable error, so rename it to {input} or switch to the LCEL form where you choose the names. A prompt that omits {context} raises no error at all but silently ignores the retrieved documents, so verify the placeholder is present.
Should I pin langchain below 1.0 instead of migrating?
Pinning with pip install "langchain<1" "langchain-core<1" keeps the old imports working, but you must also pin partner packages such as langchain-openai and langchain-chroma to 0.3-compatible versions. The 0.3 line gets no new features, so treat it as a short stabilization window and prefer langchain-classic as the lower-risk step.