langchain_classic — Internal Wiki
The legacy LangChain composition library — chains, agents, retrievers, tools, memory.
This wiki documents langchain_classic/: the 1,321-file module that powers pre-LCEL LangChain code. It is the bridge between the modern langchain_core Runnable protocol and the 2022–2023 Chain/AgentExecutor idioms that production users still rely on.
CompositionPydantic v1Pre-LCEL legacyProduction-critical
Project Philosophy
When LangChain split into langchain_core + integrations + classic, the design problem was how to keep four years of public API intact while migrating to LCEL. The answer was langchain_classic/: a library that re-implements (or thinly wraps) the historical surface — Chain, AgentExecutor, BaseLLM, BaseRetriever, BaseMemory, BaseTool — while internally bridging to the new Runnable protocol where possible. Every module here exists for one of three reasons: (1) a public class hierarchy users still subclass; (2) a factory function that builds an LCEL chain with the same shape as the legacy class; or (3) glue (callbacks, output parsers) where the legacy and modern stacks share infrastructure.
The unifying design choice across the codebase is Pydantic v1 BaseModel as the universal extension point. Every Chain, Tool, Retriever, Memory, and LLM is a BaseModel subclass. This gives free input validation, JSON serialisation, schema-driven UIs, and a discoverable __init__ contract — at the cost of locking the project to Pydantic v1 long after the ecosystem moved to v2.
Project-level Design Decisions
| Decision | Choice Made | Alternatives | Why This Approach |
|---|---|---|---|
| Composition primitive | Class inheritance (Chain, BaseTool) | LCEL-only; functional pipes | Backwards-compat with 2022 user code; LCEL is wrapped, not replaced |
| Validation framework | Pydantic v1 BaseModel | dataclasses; attrs; Pydantic v2 | v1 was the version when adoption began; migration to v2 would break thousands of subclasses |
| Sync vs async | Both, with async as opt-in override | Async-only | Many integrations were sync-only in 2022; forcing async would block adoption |
| Provider integrations | Optional imports per file | Required dependency list | 100+ providers × heavy SDKs; users install only what they need |
| Observability | Callback observer pattern, fan-out per event | OpenTelemetry only; logging | Streaming requires per-token callbacks; tracing builds a tree of run_ids |
| Memory | BaseMemory plugged into Chain | External middleware | Memory needs access to inputs & outputs the chain processes; built-in is simpler |
| Document model | Single Document(page_content, metadata) shape | Per-source classes | Loaders, splitters, embedders, vectorstores all need the same input |
| Tool schema | Pydantic args_schema or function signature inspection | JSON Schema strings | Type-safe; auto-generated OpenAI tool descriptors |
System Architecture
flowchart TD
subgraph Orch["Orchestration"]
CH["chains/"]
AG["agents/"]
RN["runnables/"]
end
subgraph MIO["Models I/O"]
LL["llms/"]
CM["chat_models/"]
EM["embeddings/"]
PR["prompts/"]
OP["output_parsers/"]
end
subgraph RD["Retrieval & Data"]
RE["retrievers/"]
VS["vectorstores/"]
DL["document_loaders/"]
DT["document_transformers/"]
IX["indexes/"]
end
subgraph ST["State & Tools"]
TO["tools/"]
ME["memory/"]
SG["storage/"]
end
subgraph CC["Cross-cutting"]
CB["callbacks/"]
EV["evaluation/"]
UT["utilities/"]
end
subgraph FN["Foundations (langchain_core)"]
SC["schema/"]
AD["adapters/"]
end
CH -->|"composes"| MIO
AG -->|"calls"| TO
AG -->|"streams"| CB
CH -->|"emits"| CB
RE --> VS
RE --> EM
DL --> DT
DT --> VS
IX --> VS
ME --> SG
TO --> UT
Orch --> FN
MIO --> FN
RD --> FN
Modules
Orchestration
chains
Pre-LCEL composition primitive — Chain class + 28 chain families
- 140 files
- 28 sub-directories
agents
ReAct/MRKL agents, AgentExecutor, plan-and-execute
- 146 files
- 17 sub-directories
runnables
LangChain-classic surface adapters over langchain_core Runnables
- 8 files
- 0 sub-directories
Models I/O
llms
Legacy completion-style LLM wrappers (text-in, text-out)
- 83 files
- 0 sub-directories
chat_models
Message-based chat model wrappers (BaseMessage in/out)
- 35 files
- 0 sub-directories
embeddings
Vector embedding adapters for retrieval & semantic search
- 51 files
- 0 sub-directories
prompts
PromptTemplate, ChatPromptTemplate, FewShot, example selectors
- 12 files
- 0 sub-directories
output_parsers
Structured output extraction from LLM strings
- 23 files
- 0 sub-directories
models_io (legacy alias)
Re-export façade for prompts/llms/chat_models/parsers
- 0 files
- 0 sub-directories
Retrieval & Data
retrievers
MultiQuery, ContextualCompression, ParentDocument, EnsembleRetriever
- 78 files
- 2 sub-directories
vectorstores
Pinecone, FAISS, Chroma, Weaviate, ... uniform interface
- 75 files
- 0 sub-directories
document_loaders
PDF, web, S3, Notion, ... unified Document model
- 166 files
- 0 sub-directories
document_transformers
Splitters, doc compressors, EmbeddingsRedundantFilter
- 11 files
- 0 sub-directories
indexes
Source-controlled vector store sync (delete, update, upsert)
- 9 files
- 0 sub-directories
State & Tools
tools
BaseTool + 64 first-party tool integrations
- 186 files
- 64 sub-directories
memory
Conversation history strategies (Buffer, Window, Summary, KG, Vector)
- 39 files
- 0 sub-directories
storage (+ docstore)
Key-value byte stores: in-memory, file, Redis, encoder layers
- 14 files
- 0 sub-directories
Cross-cutting
callbacks
Observer pattern for tracing, logging, streaming, metrics
- 45 files
- 0 sub-directories
evaluation
QA correctness, criteria, embedding distance, agent trajectory eval
- 32 files
- 10 sub-directories
smith
LangSmith dataset evaluation runner (legacy)
- 7 files
- 0 sub-directories
utilities
Wrappers for SerpAPI, SQL, Wikipedia, BashProcess, etc.
- 58 files
- 0 sub-directories
Foundations
Cross-module Synthesis
End-to-end flows
Flow 1 — Conversational RAG with citations
User asks a question in a chat UI. The system retrieves relevant docs, answers with the LLM, and stores the turn for follow-up questions.
User input
│
▼
chat history (memory.ChatMessageHistory)
│
├──► history-aware rephrase (chains.history_aware_retriever)
│ └── prompt | LLM | StrOutputParser ──► standalone question
│
▼
retriever (retrievers.MultiQueryRetriever wrapping vectorstores.Chroma)
│ └── LLM expands to N variants
│ └── each variant → similarity_search → fuse via dedupe
▼
docs (list[Document])
│
▼
contextual compression (retrievers.ContextualCompressionRetriever)
│ └── EmbeddingsFilter → LLMChainExtractor
▼
answer chain (chains.create_stuff_documents_chain)
│ └── prompt-with-{context} | LLM | StrOutputParser
▼
answer + cited docs
│
├──► memory.save_context({"input": q}, {"output": a}) → updates ChatMessageHistory
│
▼
response to user
Touched modules. memory/, chains/, retrievers/, vectorstores/, document_compressors/ (under retrievers/), output_parsers/, callbacks/ (instrumenting every step).
Total LLM calls. Typically 3 — rephrase, multi-query expand, answer. Plus optional compression LLM call.
Key insight. This entire flow is now expressible in LCEL: history_aware | retriever | compress | stuff. The classic Chain-class equivalents still exist for legacy code.
Flow 2 — Tool-calling agent answering "what's the weather in Paris and convert to F?"
input → AgentExecutor.invoke({"input": q})
│
▼ (loop iteration 1)
prompt = ChatPromptTemplate(system, MessagesPlaceholder("history"),
HumanMessage(q),
MessagesPlaceholder("agent_scratchpad"))
│
▼
prompt | llm.bind_tools(tools) | OpenAIToolsAgentOutputParser
│ └── llm returns tool_calls=[get_weather(city="Paris")]
▼
AgentAction("get_weather", {"city": "Paris"}, log=…)
│
▼
AgentExecutor calls tools["get_weather"].arun({"city":"Paris"})
│ └── utilities.GoogleSearchAPIWrapper or open-meteo HTTP
▼
observation = "21 °C, partly cloudy"
intermediate_steps.append((action, observation))
│
▼ (loop iteration 2)
same prompt with new scratchpad
│
▼
LLM returns tool_calls=[convert_temperature(value=21, from="C", to="F")]
│
▼ … observation = "69.8 °F"
│
▼ (loop iteration 3)
LLM returns AgentFinish(return_values={"output": "Paris is 21 °C / 69.8 °F"})
│
▼
AgentExecutor returns {"input": …, "output": …, "intermediate_steps": [...]}
Touched modules. agents/, tools/, chat_models/, prompts/ (MessagesPlaceholder), output_parsers/, callbacks/.
Key insight. All loop control lives in AgentExecutor. The agent itself is a stateless Runnable; the executor passes intermediate_steps back in on each iteration.
Flow 3 — Indexing a documentation site
loader = WebBaseLoader([...]) # document_loaders
docs = loader.lazy_load()
splits = RecursiveCharacterTextSplitter(...).split_documents(docs) # text_splitter
embedder = CacheBackedEmbeddings.from_bytes_store(
OpenAIEmbeddings(), LocalFileStore("./cache"), namespace="docs"
) # embeddings + storage
vs = Chroma(embedding_function=embedder, persist_directory="./db") # vectorstores
record_manager = SQLRecordManager("docs", db_url="sqlite:///rm.db")
record_manager.create_schema() # indexes
result = index(
splits, record_manager, vs, cleanup="incremental", source_id_key="source"
) # indexes
# {"num_added": 142, "num_updated": 7, "num_deleted": 3, "num_skipped": 1820}
Touched modules. document_loaders, text_splitter, embeddings, storage, vectorstores, indexes.
Key insight. The record_manager + index() pair is what makes this idempotent. Without it, every run would re-embed every document.
Flow 4 — Evaluating an agent on a dataset
run_on_dataset(
dataset_name="my-dataset",
llm_or_chain_factory=lambda: AgentExecutor(...),
evaluation=RunEvalConfig(evaluators=[
RunEvalConfig.LabeledCriteria("correctness"),
RunEvalConfig.AgentTrajectory(),
]),
)
│
▼
LangSmith pulls dataset rows → for each, factory() builds a fresh chain
│ └── this isolation prevents memory leaks across rows
▼
chain.invoke(row.input) under tracing
│
▼
LangChainTracer (callbacks) streams runs to LangSmith
│
▼
For each evaluator: load_evaluator(...) → evaluate_strings/evaluate_run
│ └── criteria evaluator: LLM judge with CoT
│ └── trajectory evaluator: rates tool-use correctness
▼
Feedback rows stored against the run
Coupling analysis
| Coupling pair | Mechanism | Tightness | Why |
|---|---|---|---|
chains ↔ prompts | Chain holds a BasePromptTemplate | Tight | Templates are core abstractions; nearly every chain has one |
agents ↔ tools | AgentExecutor.tools: list[BaseTool] | Tight at the type level, loose at the runtime: tools are interchangeable behind BaseTool | |
agents ↔ output_parsers | Pluggable per agent flavour | Loose | Strategy pattern; each parser implements AgentOutputParser |
chains ↔ memory | chain.memory attribute | Loose | Optional; Chain works without memory |
retrievers ↔ vectorstores | Strategy holds a BaseRetriever, often VectorStoreRetriever | Loose | Retriever can wrap any retriever, not just vectorstore-backed |
Everything ↔ callbacks | BaseModel.callbacks field, manager passed through | Loose | Optional; defaults work with no callbacks |
Everything ↔ langchain_core | Imports of Runnable/BaseMessage/Document | Tight | Core is the contract surface |
langchain_classic.{llms,chat_models,…} ↔ langchain_community | __getattr__ trampoline | Loose at import time, tight at runtime | Lazy resolution |
chains/graph_qa ↔ graphs/ | Direct imports | Tight | Graph-specific |
evaluation/criteria ↔ chains/ | LLMChain for the judge | Tight | The judge is itself an LLMChain |
Architectural philosophy
- Composition over configuration. Chains compose; agents compose with tools; retrievers wrap retrievers. Configuration flags are reserved for orthogonal concerns (verbose, callbacks, max_iterations).
- Pluggable strategies behind small ABCs.
BaseTool,BaseRetriever,BaseMemory,BaseOutputParser,AgentOutputParser,BaseDocumentCompressor,BaseChatMessageHistory,ByteStore,RecordManager,Embeddings,BaseLLM,BaseChatModel. Every notable axis of variation is an ABC. - Evidence: Pydantic-typed I/O. Dict-based I/O at the chain boundary lets callers introspect; Pydantic models inside ABCs catch wiring mistakes at construction time.
- Callbacks everywhere. No code is unobservable. Even tools have callbacks. This is a deliberate observability tax — you pay a tiny per-call overhead and get streaming + tracing + cost accounting for free.
- Backward compatibility is a feature. Re-export shims (
schema/,prompts/,tools/), lazy trampolines (llms/,chat_models/),@deprecateddecorators, and side-by-side legacy + factory APIs (AgentTypeenum +create_*_agentfactories;Chainsubclassing +create_*_chainLCEL factories) all reflect a project that values stability for users on old code paths. - LCEL is the future, classic is the museum. Many newer constructors (
create_retrieval_chain,create_history_aware_retriever,create_stuff_documents_chain,create_*_agent) return Runnables. The legacyChainandAgentclasses remain for compat but new code is encouraged toward LCEL.
Shared state inventory
- **Process-globals (
globals.py):**verbose,debug,llm_cache. Set once at boot; consulted by every chain/agent. The convenience comes at the cost of test isolation — tests must reset. - Inheritable callbacks:
RunnableConfig.callbackspropagate through child runs, forming the run tree LangSmith renders. - Memory: Owned by the chain; not shared between chains unless explicitly passed.
- Vectorstores / record managers: External, shared across processes; the indexing API treats them as ground truth.
System evolution
- Layer 1 — Core (Aug 2022):
Chain,LLM,PromptTemplate. Single repo. Everything in one place. - Layer 2 — Agents (Oct 2022): ZERO_SHOT_REACT_DESCRIPTION agent +
Tool. The act-observe loop is invented. - Layer 3 — Retrievers (early 2023): Vectorstore explosion +
BaseRetrieverABC. RAG becomes a first-class pattern. - Layer 4 — Memory (mid 2023):
BaseMemoryaccumulates flavours: Buffer → Window → Summary → KG → VectorStore. - Layer 5 — LCEL (late 2023):
RunnableABC,|composition, streaming as a first-class concern. ManyChains become wrappers over LCEL. - Layer 6 — Package split (early 2024): Core / community / classic / provider packages.
langchain_classicbecomes the home of pre-LCEL code + classic-only constructors. - Layer 7 — Modern factory APIs (2024–):
create_*_agent,create_*_chain,init_chat_model,RunnableWithMessageHistory. The legacy classes persist; new code is steered to factories.
The "core" — most stable, most depended on — is langchain_core (not in this repo). Inside langchain_classic, the most stable layer is chains/base.py, agents/agent.py, BaseMemory, BaseRetriever. The most evolutionary churn is at the surface (factory functions, agent flavours).
Connection diagram
flowchart LR
subgraph Core["langchain_core (external)"]
R[Runnable]
BM[BaseMessage]
BT[BaseTool]
BRet[BaseRetriever]
BLLM[BaseLanguageModel]
PT[BasePromptTemplate]
DOC[Document]
end
subgraph Orch[Orchestration]
CH[chains/]
AG[agents/]
RUN[runnables/]
end
subgraph IO[Models I/O]
LL[llms/, chat_models/]
EMB[embeddings/]
OP[output_parsers/]
PR[prompts/]
CB[callbacks/]
end
subgraph Retrieve[Retrieval & Storage]
RT[retrievers/]
VS[vectorstores/]
DL[document_loaders/]
DT[document_transformers/]
DS[docstore/]
ST[storage/]
IDX[indexes/]
end
subgraph Tools[Tools & I/O]
TL[tools/]
UT[utilities/]
CL[chat_loaders/]
GR[graphs/]
end
subgraph State[State]
MM[memory/]
end
subgraph EvalSubgraph[Evaluation]
EV[evaluation/]
SM[smith/]
end
R --> Orch
R --> IO
R --> Retrieve
R --> Tools
BM --> IO
BT --> AG
BRet --> RT
BLLM --> LL
PT --> PR
DOC --> Retrieve
CH -.uses.-> PR
CH -.uses.-> LL
CH -.uses.-> OP
CH -.uses.-> MM
CH -.uses.-> RT
AG -.uses.-> TL
AG -.uses.-> CH
AG -.uses.-> OP
AG -.uses.-> CB
RT -.uses.-> VS
RT -.uses.-> EMB
RT -.uses.-> DT
IDX -.uses.-> VS
IDX -.uses.-> ST
DL -.feeds.-> DT
DT -.feeds.-> VS
TL -.uses.-> UT
TL -.uses.-> GR
EV -.uses.-> CH
SM -.uses.-> EV
CB -.observes.-> Orch
CB -.observes.-> IO
CB -.observes.-> Tools
CB -.observes.-> Retrieve
Phase 1A — Broad Survey
Show Phase 1A research artifact (depth detection, classification, terminology)
Source path: /mnt/disk1/zy/LLM/agent/langchain/libs/langchain/langchain_classic Source SHA: 1519ed5afb Generated: 2026-05-06 Language: Python (1,321 source files)
---
What this package is
langchain_classic is the legacy, batteries-included surface of LangChain. After the 0.1 → 0.2/0.3 refactor split LangChain into langchain_core (abstractions: Runnable, BaseMessage, tools, prompts), langchain_community (3rd-party integrations), and provider-specific packages (langchain_openai, langchain_anthropic, …), langchain_classic was preserved as the home of:
- High-level orchestration primitives —
Chain,AgentExecutor,MultiQueryRetriever,ParentDocumentRetriever, conversational memory. - Compatibility shims — re-exports of types that used to live in
langchain.*so legacy code keeps importing. - Lazy integration trampolines —
__getattr__hooks that forwardlangchain_classic.llms.OpenAItolangchain_community.llms.OpenAI, with deprecation warnings.
It is the surface code — the parts intentionally kept stable so user code from 2023 still runs in 2026.
Depth detection
langchain_classic/ ← 28 functional sub-modules, 1321 .py files
├── chains/ (28 sub-dirs, 140 files) ← L1+L2 candidate
├── agents/ (17 sub-dirs, 146 files) ← L1+L2 candidate
├── tools/ (64 sub-dirs, 186 files) ← L1, sub-dirs are integrations
├── document_loaders/ (2 sub-dirs, 166 files) ← L1 flat (mostly re-exports)
├── llms/ (1 sub-dir, 83 files)
├── retrievers/ (2 sub-dirs, 78 files)
├── vectorstores/ (2 sub-dirs, 75 files)
├── utilities/ (0 sub-dirs, 58 files)
├── embeddings/ (0 sub-dirs, 51 files)
├── callbacks/ (2 sub-dirs, 45 files)
├── memory/ (1 sub-dir, 39 files)
├── chat_models/ (0 sub-dirs, 35 files)
├── evaluation/ (10 sub-dirs, 32 files)
├── output_parsers/ (0 sub-dirs, 23 files)
├── utils/ (0 sub-dirs, 15 files)
├── graphs/ (0 sub-dirs, 13 files)
├── prompts/ (1 sub-dir, 12 files)
├── document_transformers/ (1 sub-dir, 11 files)
├── chat_loaders/ (0 sub-dirs, 10 files)
├── indexes/ (1 sub-dir, 9 files)
├── storage/ (0 sub-dirs, 8 files)
├── smith/ (1 sub-dir, 7 files)
├── docstore/ (0 sub-dirs, 6 files)
├── _api/ (0 sub-dirs, 5 files)
├── load/ (0 sub-dirs, 4 files)
├── runnables/ (0 sub-dirs, 3 files)
├── adapters/ (0 sub-dirs, 2 files)
└── (single-file modules) cache.py · globals.py · hub.py · sql_database.py ·
requests.py · python.py · serpapi.py · text_splitter.py
· base_language.py · base_memory.py · model_laboratory.py
Decision: 3-level wiki (L0 hub + L1 module overviews). L2 deep-dives are produced selectively for the most algorithmically interesting modules: chains, agents, retrievers, memory. The remaining modules are documented as L1-flat pages (single comprehensive page each), since their sub-dirs are either single-file integrations (tools/gmail/, tools/jira/) or single-purpose helpers.
Module classification table
| Module | Role | Doc style | Why this style |
|---|---|---|---|
chains | Composition primitive (the original LangChain idea) | L1 + 5 deep-dive focus pages | Heavily structured, multi-pattern (LCEL bridge, retrieval, router, summarize) |
agents | Tool-using LLM loop | L1 + 5 deep-dive focus pages | Algorithmic (act-observe loop), multiple agent flavours |
tools | BaseTool + 60+ integrations | L1 flat | Integrations are roll-ups; one BaseTool algorithm |
retrievers | Strategies that wrap vectorstores | L1 + focus pages on MultiQuery / ParentDocument / Ensemble / Self-Query | Each retriever is its own algorithm |
memory | Conversation state | L1 + focus pages on Summary / KG / Token-Buffer | Each is a distinct compaction algorithm |
vectorstores | Re-export shim around community vectorstores | L1 flat | Almost no logic owned here |
document_loaders | Re-export shim, 166 file/web/cloud loaders | L1 flat | Pure delegation |
document_transformers | Splitters + redundancy filters | L1 | Small, but text_splitter.py is a real algorithm |
llms / chat_models / embeddings | Lazy trampolines | L1 flat each | Provider-agnostic façades |
output_parsers | Parse → structured value | L1 (focus on retry, fix, pydantic) | Self-contained |
prompts | Re-export of langchain_core.prompts | L1 flat | Pure shim |
callbacks | Observer pattern, manager fan-out | L1 flat | One mechanism, many subscribers |
evaluation | Scoring + criteria + comparison | L1 (focus on criteria CoT) | 10 sub-dirs, each a metric family |
smith | LangSmith runner | L1 | Bridge to external service |
utilities | API wrappers (search, sql, requests) | L1 flat | Each is small |
runnables | OpenAI Assistants + utility | L1 flat | Tiny |
indexes | Record manager + index() algorithm | L1 (focus on record manager hash) | One non-trivial algorithm |
storage | KV abstractions | L1 flat | Small |
docstore | In-memory doc lookup | L1 flat | Tiny legacy module |
graphs | Graph DB query wrappers | L1 flat | One thin pattern |
chat_loaders | Chat history → BaseMessage | L1 flat | Each loader is small |
load | Serialization (Serializable) | L1 flat | One pattern |
_api | Deprecation machinery | L1 flat | Cross-cutting infrastructure |
adapters / schema / utils / runnables | Misc shims | Combined into "Foundations" L1 | Tiny each |
Cross-module dependency map (high-level)
langchain_core
(Runnable, BaseMessage, BaseTool, BaseRetriever,
BasePromptTemplate, Document, BaseLanguageModel)
▲ ▲ ▲ ▲
│ │ │ │
┌──────────────────────────┘ │ │ └────────────┐
│ ┌───────────┘ │ │
│ │ │ │
chains/ ◄─── prompts/ ◄── llms/, chat_models/ tools/ ◄── output_parsers/
▲ ▲ embeddings/ ▲
│ │ callbacks/ │
│ └──────────────────┐ │
│ │ │
agents/ ─────────────────► memory/ ◄── retrievers/ ◄── vectorstores/
│ ▲
└─► utilities/ ─────► tools/integrations/ │
document_loaders/ ──► document_transformers/
│
▼
indexes/, storage/
evaluation/ ─────► chains/ + criteria
smith/ ─────► evaluation/ + LangSmith API
graphs/ ─────► graph DB drivers (neo4j, networkx, kuzu)
load/ ◄── used by every Serializable subclass
_api/ ◄── used by every deprecated symbol
Architectural patterns observed across the codebase
- Template Method —
Chain._call/_acallandBaseRetriever._get_relevant_documentsdefine the skeleton; subclasses override one method. Lets the base class own logging/callback orchestration. - Observer (callbacks) —
CallbackManagerfanson_*_start/end/errorto N handlers. Decouples instrumentation from logic. - Strategy — agent output parsers (ReAct, JSON, OpenAI tools, XML) are interchangeable strategies behind
AgentOutputParser. Same for memory (Buffer, Summary, KG, TokenBuffer). - Composite (LCEL) — Runnables compose with
|; the new world.langchain_classicuses LCEL internally forcreate_retrieval_chain,create_history_aware_retriever. - Lazy trampoline — module-level
__getattr__looks up integration classes fromlangchain_communityon first access, emitting a deprecation warning. Seellms/__init__.py,chat_models/__init__.py,tools/__init__.py. - Decorator (deprecation) —
@deprecatedfrom_api.deprecationwraps classes/functions with a runtime warning. Centralised migration path. - Adapter —
runnables/openai_functions.py,adapters/openai.pytranslate provider-specific shapes to LangChain abstractions. - Iterator (agent loop) —
AgentExecutorIteratorexposes per-step yields so a UI can stream reasoning steps.
Domain terminology (cross-module glossary)
| Term | Meaning | ||
|---|---|---|---|
| Runnable | Core abstraction with .invoke / .ainvoke / .batch / .stream. Replaces Chain. | ||
| Chain | Pre-Runnable composition primitive; subclass Chain, override _call. | ||
| Agent | Returns either an AgentAction (call this tool) or AgentFinish (we're done). | ||
| AgentExecutor | The loop that runs agents until AgentFinish or limits reached. | ||
| Tool | A callable with a Pydantic input schema, name, description; BaseTool ABC. | ||
| Toolkit | A collection of related Tools (e.g., SQLDatabaseToolkit). | ||
| Retriever | Runnable[str, list[Document]], abstracts vectorstore + strategy. | ||
| VectorStore | Embedding-indexed document storage with similarity_search. | ||
| Document | {page_content, metadata} pair. | ||
| Memory | Read/write buffer for conversation context (load_memory_variables, save_context). | ||
| Callback | Hook invoked at lifecycle events (on_llm_start, on_chain_end, …). | ||
| CallbackManager | Fan-out object that wraps a list of handlers. | ||
| Prompt template | A string with {placeholders}, optionally with partials and example selectors. | ||
| OutputParser | Runnable[str, T] that turns LLM text into structured output. | ||
| Serializable | Mixin that records __module__ / __class_name__ so a Chain can be JSON-dumped. | ||
| LCEL | "LangChain Expression Language" — the `R1 \ | R2 \ | R3` composition style. |
| Record manager | indexes/-owned table that tracks doc hashes & timestamps for incremental upsert. | ||
| MMR | Maximum Marginal Relevance — diversity-aware re-ranking used in vectorstores/retrievers. | ||
| RRF | Reciprocal Rank Fusion — combines rankings in EnsembleRetriever. | ||
| Trajectory | The list of (action, observation) tuples produced by an agent run. | ||
| Intermediate steps | Synonym for trajectory; appears in AgentExecutor outputs. | ||
| Scratchpad | The agent's running notebook — the textual rendering of intermediate steps fed back into the next prompt. | ||
| AgentAction / AgentFinish | Output union returned by BaseSingleActionAgent.plan(). | ||
| AgentType | Legacy enum (ZERO_SHOT_REACT_DESCRIPTION, OPENAI_FUNCTIONS, …). | ||
| Deprecation warning | Surfaced by @deprecated and _warn_on_import; suppressed in interactive envs. |
Per-module headline metrics
| Module | Files | Key public symbols | Sub-modules |
|---|---|---|---|
| chains | 140 | Chain, LLMChain, SequentialChain, RouterChain, RetrievalQA, ConversationalRetrievalChain, MapReduceDocumentsChain, StuffDocumentsChain | 28 |
| agents | 146 | AgentExecutor, BaseSingleActionAgent, Tool, initialize_agent, create_react_agent, create_openai_tools_agent, create_structured_chat_agent | 17 |
| tools | 186 | BaseTool, Tool, StructuredTool, tool (decorator), render_text_description, convert_to_openai_function | 64 |
| retrievers | 78 | MultiQueryRetriever, ParentDocumentRetriever, EnsembleRetriever, ContextualCompressionRetriever, SelfQueryRetriever, TimeWeightedVectorStoreRetriever | 2 |
| vectorstores | 75 | VectorStore, VectorStoreRetriever (re-exports) | 2 |
| document_loaders | 166 | BaseLoader (re-export), 160+ integrations | 2 |
| document_transformers | 11 | EmbeddingsRedundantFilter, LongContextReorder, BeautifulSoupTransformer | 1 |
| llms | 83 | Trampolines for OpenAI, Anthropic, HuggingFace, … | 1 |
| chat_models | 35 | Trampolines | 0 |
| embeddings | 51 | Trampolines + CacheBackedEmbeddings | 0 |
| memory | 39 | ConversationBufferMemory, ConversationSummaryMemory, ConversationKGMemory, EntityMemory, VectorStoreRetrieverMemory, ConversationTokenBufferMemory | 1 |
| callbacks | 45 | CallbackManager, BaseCallbackHandler, StdOutCallbackHandler, StreamingStdOutCallbackHandler, FileCallbackHandler, LangChainTracer | 2 |
| prompts | 12 | Re-exports PromptTemplate, ChatPromptTemplate, FewShotPromptTemplate, MessagesPlaceholder | 1 |
| output_parsers | 23 | RetryOutputParser, OutputFixingParser, PydanticOutputParser, StructuredOutputParser, RegexParser, EnumOutputParser | 0 |
| evaluation | 32 | load_evaluator, LabeledCriteriaEvalChain, QAEvalChain, EmbeddingDistanceEvalChain, StringDistanceEvalChain, TrajectoryEvalChain | 10 |
| smith | 7 | run_on_dataset, arun_on_dataset | 1 |
| utilities | 58 | SerpAPIWrapper, GoogleSearchAPIWrapper, WikipediaAPIWrapper, SQLDatabase, RequestsWrapper, PythonREPL | 0 |
| docstore | 6 | InMemoryDocstore, Wikipedia | 0 |
| storage | 8 | LocalFileStore, InMemoryByteStore, EncoderBackedStore, create_lc_store | 0 |
| indexes | 9 | index(), aindex(), SQLRecordManager | 1 |
| graphs | 13 | Neo4jGraph, NetworkxEntityGraph, KuzuGraph, NebulaGraph | 0 |
| chat_loaders | 10 | BaseChatLoader, merge_chat_runs, map_ai_messages | 0 |
| schema | 43 | Re-exports langchain_core.runnables, messages, outputs, agent, documents | 2 |
| _api | 5 | @deprecated, surface_langchain_deprecation_warnings | 0 |
| load | 4 | Serializable, dumps, loads | 0 |
| adapters | 2 | openai.py — message/tool-call shape adapter | 0 |
| runnables | 3 | OpenAIAssistantRunnable, create_openai_fn_runnable | 0 |
| utils | 15 | get_from_dict_or_env, mock_now, interactive_env, aiter, formatting | 0 |
Top-level single-file modules
cache.py—BaseCacheinterfaces (re-export),InMemoryCache, SQLite cache.globals.py—get_verbose / set_verbose,get_debug / set_debug,get_llm_cache / set_llm_cache. Process-global toggles.hub.py—pull(repo_id)/push(repo_id, object)against the LangChain Hub.model_laboratory.py— runs the same prompt across multiple models for side-by-side comparison.text_splitter.py— re-exportslangchain_text_splitters(RecursiveCharacterTextSplitter, …).sql_database.py— re-export oflangchain_community.utilities.SQLDatabase.requests.py/python.py/serpapi.py— single-class re-exports.formatting.py— string templating helper used by prompts.base_language.py/base_memory.py— re-exports of core abstractions.env.py— environment lookup helpers.example_generator.py/input.py— small helpers for prompt examples.
Source tree (top-level)
langchain_classic/
├── _api/ ← deprecation infrastructure
├── adapters/ ← provider adapters (currently openai.py)
├── agents/ ← Agent loop, AgentExecutor, agent flavours
├── cache.py ← LLM response cache
├── callbacks/ ← Observer pattern fan-out
├── chains/ ← Chain abstraction + 28 chain families
├── chat_loaders/ ← chat history → BaseMessage
├── chat_models/ ← lazy trampolines to community
├── docstore/ ← legacy in-memory document store
├── document_loaders/ ← 160+ file/web/cloud loaders
├── document_transformers/ ← splitters & filters
├── embeddings/ ← lazy trampolines + CacheBackedEmbeddings
├── env.py
├── evaluation/ ← QA, criteria, distance, comparison evals
├── example_generator.py
├── formatting.py
├── globals.py ← process-wide toggles
├── graphs/ ← graph DB query wrappers
├── hub.py ← LangChain Hub pull/push
├── indexes/ ← record manager + index() upsert algorithm
├── input.py
├── llms/ ← lazy trampolines to community
├── load/ ← Serializable mixin
├── memory/ ← conversation state strategies
├── model_laboratory.py
├── output_parsers/ ← retry, fix, pydantic, structured parsers
├── prompts/ ← re-exports of langchain_core.prompts
├── python.py
├── requests.py
├── retrievers/ ← MultiQuery, ParentDoc, Ensemble, SelfQuery
├── runnables/ ← OpenAIAssistantRunnable + helpers
├── schema/ ← legacy type re-exports
├── serpapi.py
├── smith/ ← LangSmith runner
├── sql_database.py
├── storage/ ← KV abstractions
├── text_splitter.py
├── tools/ ← BaseTool + 60+ integration sub-dirs
├── utilities/ ← API wrappers
└── utils/ ← misc helpersDirectory Map
Top-level source tree
/
├── __init__.py
├── _api/
├── adapters/
├── agents/
├── base_language.py
├── base_memory.py
├── cache.py
├── callbacks/
├── chains/
├── chat_loaders/
├── chat_models/
├── docstore/
├── document_loaders/
├── document_transformers/
├── embeddings/
├── env.py
├── evaluation/
├── example_generator.py
├── formatting.py
├── globals.py
├── graphs/
├── hub.py
├── indexes/
├── input.py
├── llms/
├── load/
├── memory/
├── model_laboratory.py
├── output_parsers/
├── prompts/
├── py.typed
├── python.py
├── requests.py
├── retrievers/
├── runnables/
├── schema/
├── serpapi.py
├── smith/
├── sql_database.py
├── storage/
├── text_splitter.py
├── tools/
├── utilities/
├── utils/
└── vectorstores/