Plumb an explicit resource-lifecycle contract through `BaseChatModel`, `RunnableWithFallbacks`, and the two largest partner integrations. Adds an opt-in `FallbackLatch` so `with_fallbacks(...)` can short-circuit the primary after a failure. Motivation: provider SDKs (`anthropic`, `openai`) back their clients with httpx connection pools that the SDKs only release best-effort from `__del__` — `asyncio.get_running_loop().create_task(self.aclose())` with a bare `except Exception: pass`. Long-lived workers that construct chat models per request (multi-tenant LangGraph deployments, agents-as-services) silently accumulate pools and leak memory + file descriptors. The fix today requires reaching into private attributes (`_async_client`, `root_async_client`, ...) on each provider. This PR makes teardown a first-class part of the chat-model API. ## langchain-core - `BaseChatModel.close()` / `aclose()` — default no-ops that subclasses override. `aclose()` dispatches to `close()` so async teardown works for sync-only subclasses. Adds `__enter__`/`__exit__`/`__aenter__`/ `__aexit__` so models can be used as context managers. - `RunnableWithFallbacks.close()` / `aclose()` — walks `runnable` and `fallbacks`, calling each one's lifecycle method. Per-runnable failures are suppressed so one bad close doesn't prevent the others from running. - `FallbackLatch` + `with_fallbacks(..., latch=...)` — opt-in circuit-breaker: once the primary raises a handled exception, latch trips and subsequent calls (on this wrapper, or any wrapper sharing the same latch instance) skip the primary. Useful when a primary failure is unlikely to recover within the wrapper's lifetime — wrong API key, sustained outage — so the default `try-primary-on-every-call` doesn't waste a round-trip on every retry. `latch.reset()` re-enables the primary. The latch propagates through `__getattr__` rebinds (e.g. `wrapper.bind_tools([...])`) so tool-bound and bare wrappers share one circuit. - Default-latch behaviour is unchanged: passing no `latch` retains the existing "retry primary on every call" semantics. ## langchain-anthropic - `ChatAnthropic.close()` / `aclose()` — closes `_client` (sync) and `_async_client` (async). Both are `cached_property` slots; guarded via `__dict__` so we don't materialize an uninstantiated cached client just to immediately close it. Idempotent. ## langchain-openai - `BaseChatOpenAI.close()` / `aclose()` — closes `root_client` and `root_async_client`, then clears the corresponding `client` / `async_client` attributes so the model can't be used after teardown. Idempotent. Tolerates the API-key-missing case where one client is `None`. Note: `BaseChatOpenAI`'s eager construction of both sync + async clients in its `model_validator` (even for async-only use) is a related inefficiency but not addressed here — it's a fixed per-instance cost rather than the per-request leak that `aclose()` solves. ## Tests - 7 new latch + propagation tests in `test_fallbacks.py` - 4 new lifecycle tests in `test_base.py` for `BaseChatModel` - 5 new tests in `test_chat_models.py` for `ChatAnthropic` - 5 new tests in `test_base.py` for `BaseChatOpenAI` Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
The agent engineering platform.
LangChain is a framework for building agents and LLM-powered applications. It helps you chain together interoperable components and third-party integrations to simplify AI application development — all while future-proofing decisions as the underlying technology evolves.
Tip
Just getting started? Check out Deep Agents — a higher-level package built on LangChain for agents that have built-in capabilites for common usage patterns such as planning, subagents, file system usage, and more.
Quickstart
pip install langchain
# or
uv add langchain
from langchain.chat_models import init_chat_model
model = init_chat_model("openai:gpt-5.4")
result = model.invoke("Hello, world!")
If you're looking for more advanced customization or agent orchestration, check out LangGraph, our framework for building controllable agent workflows.
For an equivalent JS/TS library, check out LangChain.js.
Tip
For developing, debugging, and deploying AI agents and LLM applications, see LangSmith.
LangChain ecosystem
While the LangChain framework can be used standalone, it also integrates seamlessly with any LangChain product, giving developers a full suite of tools when building LLM applications.
- Deep Agents — Build agents that can plan, use subagents, and leverage file systems for complex tasks
- LangGraph — Build agents that can reliably handle complex tasks with our low-level agent orchestration framework
- Integrations — Chat & embedding models, tools & toolkits, and more
- LangSmith — Agent evals, observability, and debugging for LLM apps
- LangSmith Deployment — Deploy and scale agents with a purpose-built platform for long-running, stateful workflows
Why use LangChain?
LangChain helps developers build applications powered by LLMs through a standard interface for models, embeddings, vector stores, and more.
- Real-time data augmentation — Easily connect LLMs to diverse data sources and external/internal systems, drawing from LangChain's vast library of integrations with model providers, tools, vector stores, retrievers, and more
- Model interoperability — Swap models in and out as your engineering team experiments to find the best choice for your application's needs. As the industry frontier evolves, adapt quickly — LangChain's abstractions keep you moving without losing momentum
- Rapid prototyping — Quickly build and iterate on LLM applications with LangChain's modular, component-based architecture. Test different approaches and workflows without rebuilding from scratch, accelerating your development cycle
- Production-ready features — Deploy reliable applications with built-in support for monitoring, evaluation, and debugging through integrations like LangSmith. Scale with confidence using battle-tested patterns and best practices
- Vibrant community and ecosystem — Leverage a rich ecosystem of integrations, templates, and community-contributed components. Benefit from continuous improvements and stay up-to-date with the latest AI developments through an active open-source community
- Flexible abstraction layers — Work at the level of abstraction that suits your needs — from high-level chains for quick starts to low-level components for fine-grained control. LangChain grows with your application's complexity
Documentation
- docs.langchain.com – Comprehensive documentation, including conceptual overviews and guides
- reference.langchain.com/python – API reference docs for LangChain packages
- Chat LangChain – Chat with the LangChain documentation and get answers to your questions
Discussions: Visit the LangChain Forum to connect with the community and share all of your technical questions, ideas, and feedback.
Additional resources
- Contributing Guide – Learn how to contribute to LangChain projects and find good first issues.
- Code of Conduct – Our community guidelines and standards for participation.
- LangChain Academy – Comprehensive, free courses on LangChain libraries and products, made by the LangChain team.