How to fix LangChain deprecated import langchain.document_loaders
langchain.document_loaders is deprecated and removed in recent LangChain versions. Replace it with langchain_community.document_loaders to fix import errors and maintain compatibility with LangChain v0.2+.code_error from langchain.document_loaders import XYZ to from langchain_community.document_loaders import XYZ.Why this happens
LangChain reorganized its package structure in v0.2+, moving many document loader classes out of the core langchain package into the separate langchain_community namespace. This change removes the old import path langchain.document_loaders, causing ModuleNotFoundError or ImportError when using the deprecated import.
Example of broken code:
from langchain.document_loaders import TextLoader
loader = TextLoader("example.txt")This triggers errors like:
ModuleNotFoundError: No module named 'langchain.document_loaders'from langchain.document_loaders import TextLoader
loader = TextLoader("example.txt") ModuleNotFoundError: No module named 'langchain.document_loaders'
The fix
Update your imports to use the new langchain_community.document_loaders package. This reflects the current LangChain v0.2+ structure and resolves import errors.
Corrected code example:
from langchain_community.document_loaders import TextLoader
loader = TextLoader("example.txt")
print(f"Loaded document from example.txt") Loaded document from example.txt
Preventing it in production
To avoid breaking changes from LangChain updates, pin your langchain and langchain_community versions in requirements.txt or pipfile. Use semantic versioning constraints to prevent automatic upgrades that remove deprecated imports.
Additionally, implement automated tests that verify imports and basic functionality after dependency upgrades. This ensures you catch breaking changes early.
Consider using retry logic or fallback error handling around your AI calls to handle unexpected runtime errors gracefully.
Key Takeaways
- Always import document loaders from
langchain_community.document_loadersin LangChain v0.2+. - Pin LangChain and langchain_community versions to avoid unexpected breaking changes.
- Test imports and basic functionality after dependency upgrades to catch errors early.