Howwise RSS
AI & Automation6 min read

LangChain create_retrieval_chain Import Error: Fix in 1.x

Short answer

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.

Key takeaways
  • 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.

  1. Install it in the same environment that runs your app: pip install -U langchain-classic
  2. Replace from langchain.chains import create_retrieval_chain with from langchain_classic.chains import create_retrieval_chain.
  3. Replace from langchain.chains.combine_documents import create_stuff_documents_chain with from langchain_classic.chains.combine_documents import create_stuff_documents_chain.
  4. Do the same for RetrievalQA, ConversationalRetrievalChain and create_history_aware_retriever, all importable from langchain_classic.chains.
  5. 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_chain
Tip: langchain-classic is a bridge, not the long-term home for new code. It keeps old apps working, but new features land in the agent and LCEL APIs.

Which 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 locationPackage to install
langchain.chains.RetrievalQAlangchain_classic.chains.RetrievalQAlangchain-classic
langchain.chains.create_retrieval_chain (langchain.chains.retrieval)langchain_classic.chains.create_retrieval_chainlangchain-classic
langchain.chains.combine_documents.create_stuff_documents_chainlangchain_classic.chains.combine_documents.create_stuff_documents_chainlangchain-classic
langchain.chains.create_history_aware_retrieverlangchain_classic.chains.create_history_aware_retrieverlangchain-classic
langchain.prompts.ChatPromptTemplatelangchain_core.prompts.ChatPromptTemplatelangchain-core
langchain.schema.Documentlangchain_core.documents.Documentlangchain-core
langchain.text_splitter.RecursiveCharacterTextSplitterlangchain_text_splitters.RecursiveCharacterTextSplitterlangchain-text-splitters
langchain.vectorstores.Chromalangchain_chroma.Chromalangchain-chroma
langchain.embeddings.OpenAIEmbeddingslangchain_openai.OpenAIEmbeddingslangchain-openai
langchain.chat_models.ChatOpenAIlangchain_openai.ChatOpenAIlangchain-openai
Other community vector stores and loaderslangchain_community.vectorstores / document_loaders, or a partner packagelangchain-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.

SymptomLikely causeFix
No module named langchain_classic after installingpip installed into a different environment than the one runningUse python -m pip install, and in notebooks run %pip install langchain-classic, then restart the kernel
cannot import name from langchain_corelangchain-core is older than what langchain-classic or langchain requirespip install -U langchain langchain-core langchain-classic langchain-openai together
langchain.__file__ points to your project folderA local file or folder named langchain.py shadows the packageRename it and delete its __pycache__ directory
Install fails with a Python requirement errorLangChain 1.x needs Python 3.10 or newerUpgrade the interpreter or recreate the venv
Works in terminal, fails in Jupyter or VS CodeNotebook kernel uses another interpreterSelect 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__)"
Warning: Do not mix 0.3 partner packages with 1.x core. Old pins such as langchain-core==0.3.* in requirements.txt will make pip resolve to an older langchain or fail. Remove stale pins before upgrading.

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.

AspectRetrievalQAcreate_retrieval_chainLCEL pipeline
Input{'query': ...}{'input': ...}A plain string
Answerresult['result']result['answer']The returned string
Sourcessource_documents (needs return_source_documents=True)context (always included)Only if you add them with RunnableParallel
Prompt variablescontext, questioncontext, inputWhatever you define
StatusLegacy, in langchain_classicLegacy, in langchain_classicCore, 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"]])
Warning: A prompt without {context} runs without any error but never shows the retrieved documents to the model, so answers look fluent yet ungrounded. Always confirm {context} is in the prompt and check result['context'] when answers seem generic.

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, answer
Tip: Simple pipeline: retriever | format_docs | prompt | llm | StrOutputParser() returns just the answer string. Use the RunnableParallel version when you need citations.

When 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.

Related topics:langchainragpythonlangchain-classicretrievalqa