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.

21
Documented modules
1,321
Python files
28
Sub-directories
Python 3
Language

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

DecisionChoice MadeAlternativesWhy This Approach
Composition primitiveClass inheritance (Chain, BaseTool)LCEL-only; functional pipesBackwards-compat with 2022 user code; LCEL is wrapped, not replaced
Validation frameworkPydantic v1 BaseModeldataclasses; attrs; Pydantic v2v1 was the version when adoption began; migration to v2 would break thousands of subclasses
Sync vs asyncBoth, with async as opt-in overrideAsync-onlyMany integrations were sync-only in 2022; forcing async would block adoption
Provider integrationsOptional imports per fileRequired dependency list100+ providers × heavy SDKs; users install only what they need
ObservabilityCallback observer pattern, fan-out per eventOpenTelemetry only; loggingStreaming requires per-token callbacks; tracing builds a tree of run_ids
MemoryBaseMemory plugged into ChainExternal middlewareMemory needs access to inputs & outputs the chain processes; built-in is simpler
Document modelSingle Document(page_content, metadata) shapePer-source classesLoaders, splitters, embedders, vectorstores all need the same input
Tool schemaPydantic args_schema or function signature inspectionJSON Schema stringsType-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

foundations

schema, _api, adapters, load, utils, graphs, chat_loaders

  • 90 files
  • 7 sub-directories

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 pairMechanismTightnessWhy
chains ↔ promptsChain holds a BasePromptTemplateTightTemplates are core abstractions; nearly every chain has one
agents ↔ toolsAgentExecutor.tools: list[BaseTool]Tight at the type level, loose at the runtime: tools are interchangeable behind BaseTool
agents ↔ output_parsersPluggable per agent flavourLooseStrategy pattern; each parser implements AgentOutputParser
chains ↔ memorychain.memory attributeLooseOptional; Chain works without memory
retrievers ↔ vectorstoresStrategy holds a BaseRetriever, often VectorStoreRetrieverLooseRetriever can wrap any retriever, not just vectorstore-backed
Everything ↔ callbacksBaseModel.callbacks field, manager passed throughLooseOptional; defaults work with no callbacks
Everything ↔ langchain_coreImports of Runnable/BaseMessage/DocumentTightCore is the contract surface
langchain_classic.{llms,chat_models,…} ↔ langchain_community__getattr__ trampolineLoose at import time, tight at runtimeLazy resolution
chains/graph_qa ↔ graphs/Direct importsTightGraph-specific
evaluation/criteria ↔ chains/LLMChain for the judgeTightThe judge is itself an LLMChain

Architectural philosophy

  1. Composition over configuration. Chains compose; agents compose with tools; retrievers wrap retrievers. Configuration flags are reserved for orthogonal concerns (verbose, callbacks, max_iterations).
  2. 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.
  3. 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.
  4. 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.
  5. Backward compatibility is a feature. Re-export shims (schema/, prompts/, tools/), lazy trampolines (llms/, chat_models/), @deprecated decorators, and side-by-side legacy + factory APIs (AgentType enum + create_*_agent factories; Chain subclassing + create_*_chain LCEL factories) all reflect a project that values stability for users on old code paths.
  6. 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 legacy Chain and Agent classes remain for compat but new code is encouraged toward LCEL.

Shared state inventory

System evolution

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:

  1. High-level orchestration primitives — Chain, AgentExecutor, MultiQueryRetriever, ParentDocumentRetriever, conversational memory.
  2. Compatibility shims — re-exports of types that used to live in langchain.* so legacy code keeps importing.
  3. Lazy integration trampolines — __getattr__ hooks that forward langchain_classic.llms.OpenAI to langchain_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

ModuleRoleDoc styleWhy this style
chainsComposition primitive (the original LangChain idea)L1 + 5 deep-dive focus pagesHeavily structured, multi-pattern (LCEL bridge, retrieval, router, summarize)
agentsTool-using LLM loopL1 + 5 deep-dive focus pagesAlgorithmic (act-observe loop), multiple agent flavours
toolsBaseTool + 60+ integrationsL1 flatIntegrations are roll-ups; one BaseTool algorithm
retrieversStrategies that wrap vectorstoresL1 + focus pages on MultiQuery / ParentDocument / Ensemble / Self-QueryEach retriever is its own algorithm
memoryConversation stateL1 + focus pages on Summary / KG / Token-BufferEach is a distinct compaction algorithm
vectorstoresRe-export shim around community vectorstoresL1 flatAlmost no logic owned here
document_loadersRe-export shim, 166 file/web/cloud loadersL1 flatPure delegation
document_transformersSplitters + redundancy filtersL1Small, but text_splitter.py is a real algorithm
llms / chat_models / embeddingsLazy trampolinesL1 flat eachProvider-agnostic façades
output_parsersParse → structured valueL1 (focus on retry, fix, pydantic)Self-contained
promptsRe-export of langchain_core.promptsL1 flatPure shim
callbacksObserver pattern, manager fan-outL1 flatOne mechanism, many subscribers
evaluationScoring + criteria + comparisonL1 (focus on criteria CoT)10 sub-dirs, each a metric family
smithLangSmith runnerL1Bridge to external service
utilitiesAPI wrappers (search, sql, requests)L1 flatEach is small
runnablesOpenAI Assistants + utilityL1 flatTiny
indexesRecord manager + index() algorithmL1 (focus on record manager hash)One non-trivial algorithm
storageKV abstractionsL1 flatSmall
docstoreIn-memory doc lookupL1 flatTiny legacy module
graphsGraph DB query wrappersL1 flatOne thin pattern
chat_loadersChat history → BaseMessageL1 flatEach loader is small
loadSerialization (Serializable)L1 flatOne pattern
_apiDeprecation machineryL1 flatCross-cutting infrastructure
adapters / schema / utils / runnablesMisc shimsCombined into "Foundations" L1Tiny 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

  1. Template Method — Chain._call / _acall and BaseRetriever._get_relevant_documents define the skeleton; subclasses override one method. Lets the base class own logging/callback orchestration.
  2. Observer (callbacks) — CallbackManager fans on_*_start/end/error to N handlers. Decouples instrumentation from logic.
  3. Strategy — agent output parsers (ReAct, JSON, OpenAI tools, XML) are interchangeable strategies behind AgentOutputParser. Same for memory (Buffer, Summary, KG, TokenBuffer).
  4. Composite (LCEL) — Runnables compose with |; the new world. langchain_classic uses LCEL internally for create_retrieval_chain, create_history_aware_retriever.
  5. Lazy trampoline — module-level __getattr__ looks up integration classes from langchain_community on first access, emitting a deprecation warning. See llms/__init__.py, chat_models/__init__.py, tools/__init__.py.
  6. Decorator (deprecation) — @deprecated from _api.deprecation wraps classes/functions with a runtime warning. Centralised migration path.
  7. Adapter — runnables/openai_functions.py, adapters/openai.py translate provider-specific shapes to LangChain abstractions.
  8. Iterator (agent loop) — AgentExecutorIterator exposes per-step yields so a UI can stream reasoning steps.

Domain terminology (cross-module glossary)

TermMeaning
RunnableCore abstraction with .invoke / .ainvoke / .batch / .stream. Replaces Chain.
ChainPre-Runnable composition primitive; subclass Chain, override _call.
AgentReturns either an AgentAction (call this tool) or AgentFinish (we're done).
AgentExecutorThe loop that runs agents until AgentFinish or limits reached.
ToolA callable with a Pydantic input schema, name, description; BaseTool ABC.
ToolkitA collection of related Tools (e.g., SQLDatabaseToolkit).
RetrieverRunnable[str, list[Document]], abstracts vectorstore + strategy.
VectorStoreEmbedding-indexed document storage with similarity_search.
Document{page_content, metadata} pair.
MemoryRead/write buffer for conversation context (load_memory_variables, save_context).
CallbackHook invoked at lifecycle events (on_llm_start, on_chain_end, …).
CallbackManagerFan-out object that wraps a list of handlers.
Prompt templateA string with {placeholders}, optionally with partials and example selectors.
OutputParserRunnable[str, T] that turns LLM text into structured output.
SerializableMixin that records __module__ / __class_name__ so a Chain can be JSON-dumped.
LCEL"LangChain Expression Language" — the `R1 \R2 \R3` composition style.
Record managerindexes/-owned table that tracks doc hashes & timestamps for incremental upsert.
MMRMaximum Marginal Relevance — diversity-aware re-ranking used in vectorstores/retrievers.
RRFReciprocal Rank Fusion — combines rankings in EnsembleRetriever.
TrajectoryThe list of (action, observation) tuples produced by an agent run.
Intermediate stepsSynonym for trajectory; appears in AgentExecutor outputs.
ScratchpadThe agent's running notebook — the textual rendering of intermediate steps fed back into the next prompt.
AgentAction / AgentFinishOutput union returned by BaseSingleActionAgent.plan().
AgentTypeLegacy enum (ZERO_SHOT_REACT_DESCRIPTION, OPENAI_FUNCTIONS, …).
Deprecation warningSurfaced by @deprecated and _warn_on_import; suppressed in interactive envs.

Per-module headline metrics

ModuleFilesKey public symbolsSub-modules
chains140Chain, LLMChain, SequentialChain, RouterChain, RetrievalQA, ConversationalRetrievalChain, MapReduceDocumentsChain, StuffDocumentsChain28
agents146AgentExecutor, BaseSingleActionAgent, Tool, initialize_agent, create_react_agent, create_openai_tools_agent, create_structured_chat_agent17
tools186BaseTool, Tool, StructuredTool, tool (decorator), render_text_description, convert_to_openai_function64
retrievers78MultiQueryRetriever, ParentDocumentRetriever, EnsembleRetriever, ContextualCompressionRetriever, SelfQueryRetriever, TimeWeightedVectorStoreRetriever2
vectorstores75VectorStore, VectorStoreRetriever (re-exports)2
document_loaders166BaseLoader (re-export), 160+ integrations2
document_transformers11EmbeddingsRedundantFilter, LongContextReorder, BeautifulSoupTransformer1
llms83Trampolines for OpenAI, Anthropic, HuggingFace, …1
chat_models35Trampolines0
embeddings51Trampolines + CacheBackedEmbeddings0
memory39ConversationBufferMemory, ConversationSummaryMemory, ConversationKGMemory, EntityMemory, VectorStoreRetrieverMemory, ConversationTokenBufferMemory1
callbacks45CallbackManager, BaseCallbackHandler, StdOutCallbackHandler, StreamingStdOutCallbackHandler, FileCallbackHandler, LangChainTracer2
prompts12Re-exports PromptTemplate, ChatPromptTemplate, FewShotPromptTemplate, MessagesPlaceholder1
output_parsers23RetryOutputParser, OutputFixingParser, PydanticOutputParser, StructuredOutputParser, RegexParser, EnumOutputParser0
evaluation32load_evaluator, LabeledCriteriaEvalChain, QAEvalChain, EmbeddingDistanceEvalChain, StringDistanceEvalChain, TrajectoryEvalChain10
smith7run_on_dataset, arun_on_dataset1
utilities58SerpAPIWrapper, GoogleSearchAPIWrapper, WikipediaAPIWrapper, SQLDatabase, RequestsWrapper, PythonREPL0
docstore6InMemoryDocstore, Wikipedia0
storage8LocalFileStore, InMemoryByteStore, EncoderBackedStore, create_lc_store0
indexes9index(), aindex(), SQLRecordManager1
graphs13Neo4jGraph, NetworkxEntityGraph, KuzuGraph, NebulaGraph0
chat_loaders10BaseChatLoader, merge_chat_runs, map_ai_messages0
schema43Re-exports langchain_core.runnables, messages, outputs, agent, documents2
_api5@deprecated, surface_langchain_deprecation_warnings0
load4Serializable, dumps, loads0
adapters2openai.py — message/tool-call shape adapter0
runnables3OpenAIAssistantRunnable, create_openai_fn_runnable0
utils15get_from_dict_or_env, mock_now, interactive_env, aiter, formatting0

Top-level single-file modules

  • cache.py — BaseCache interfaces (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-exports langchain_text_splitters (RecursiveCharacterTextSplitter, …).
  • sql_database.py — re-export of langchain_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 helpers

Directory 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/