Principle:Langchain ai Langchain Public API Surface
Overview
A pattern for defining a clean, explicit public API in a Python package through __init__.py exports, the __all__ list, and version metadata.
Description
The Public API Surface principle governs how LangChain partner packages expose their functionality to users. A well-defined public API makes it clear what is supported, what is internal, and what version of the package is installed.
Key elements:
__init__.pyas the entry point: The top-level__init__.pyof the package is the sole place where public classes and functions are imported and re-exported. Users should be able to import everything they need from the package root (e.g.,from langchain_deepseek import ChatDeepSeek).__all__list: Explicitly enumerates every public symbol. This controls whatfrom package import *exposes and serves as documentation of the supported API. Only classes, functions, and constants that are part of the stable interface should appear here.__version__from metadata: The package version is read dynamically fromimportlib.metadatarather than hardcoded. This ensures the version always matches what was installed by pip/uv. APackageNotFoundErrorfallback handles the case where the package is used in an editable install without metadata.- Namespace hygiene: After use, the
metadatamodule is deleted (del metadata) to avoid polluting the package namespace.
Why this matters:
- Stable imports: Users have a single, documented import path for each symbol.
- Discoverability:
dir(package)andhelp(package)show only public symbols. - Backward compatibility: Changes to internal modules do not break user code as long as
__init__.pyre-exports are maintained.
Usage
Apply this principle when:
- Creating the
__init__.pyfor a new LangChain integration package. - Adding new public classes or functions to an existing package.
- Reviewing whether internal implementation details are accidentally exposed.
Theoretical Basis
The pattern follows Python's explicit-is-better-than-implicit philosophy. By declaring __all__, the package author makes a contract with users about what is public and supported.
"""LangChain <Provider> integration."""
from importlib import metadata
from langchain_<name>.chat_models import Chat<Provider>
try:
__version__ = metadata.version(__package__)
except metadata.PackageNotFoundError:
__version__ = ""
del metadata
__all__ = [
"Chat<Provider>",
"__version__",
]