> ## Documentation Index
> Fetch the complete documentation index at: https://www.yuan111.asia/doc/llms.txt
> Use this file to discover all available pages before exploring further.

# 13 · langchain_core 全地图：那个"地基包"里到底有什么

# 13 · langchain\_core 全地图：那个"地基包"里到底有什么

> **本片目标**：把 langchain\_core 的 36 个模块全部过一遍——哪些你已天天用、哪些以后用得上、哪些是历史包袱要避开。学完你能看着任何 `from langchain_core.xxx import yyy` 说出它属于哪一族、干嘛的。
> **新增规定性：—**（本片不新增概念，是对前 12 篇用过的模块做全景收束——规定性展开链条的一次"中场盘点"）
> **数据字典**：36 个模块 + 5 大家族 + 每个模块的核心类清单（实测）。
> **进程线程模型**：无网络、无并发——纯代码阅读 + 一次 `dir()` 检查。
> **网络模型**：0 网络请求。

***

## 1. 上集回顾

第 12 篇我们钻进了 `langchain_core.runnables.config` 的源码，看到了 `ContextThreadPoolExecutor`、`run_in_executor`。你意识到：**你一直在用 langchain\_core，但只用了它的冰山一角。**

回头看看前 12 篇，你其实已经用过这些模块：

| 模块                | 你用过的类                                                    | 在哪篇         |
| ----------------- | -------------------------------------------------------- | ----------- |
| `messages`        | AIMessage / HumanMessage / SystemMessage                 | 02、04、05、06 |
| `prompts`         | ChatPromptTemplate / MessagesPlaceholder                 | 03          |
| `language_models` | BaseChatModel（ChatAnthropic 的爹）                          | 01          |
| `output_parsers`  | StrOutputParser                                          | 04          |
| `embeddings`      | Embeddings（HuggingFaceEmbeddings 的接口）                    | 08          |
| `documents`       | Document                                                 | 07          |
| `retrievers`      | BaseRetriever                                            | 08、09       |
| `vectorstores`    | VectorStore / VectorStoreRetriever / InMemoryVectorStore | 08          |
| `runnables`       | Runnable / RunnablePassthrough / RunnableParallel        | 04、09       |

**9 个模块，11 篇。** 但 langchain\_core 有 **36 个模块**。剩下 27 个是什么？哪些值得学？哪些是坑？

***

## 2. 数据字典：36 个模块全清单（实测，langchain\_core 1.5.1）

```python theme={null}
import langchain_core
print(langchain_core.__version__)   # 1.5.1
```

**实测模块列表（2026-08，本机）**：

```
langchain_core/ 共 36 个模块：
  _api  _import_utils  _security      ← 内部模块（下划线开头，别动）
  agents  caches  callbacks
  chat_history  chat_loaders  chat_sessions
  cross_encoders  document_loaders  documents
  embeddings  env  example_selectors
  exceptions  globals  indexing
  language_models  load  messages
  output_parsers  outputs  prompt_values
  prompts  rate_limiters  retrievers
  runnables  stores  structured_query
  sys_info  tools  tracers  utils
  vectorstores  version
```

### 2.1 五大家族分类

| 家族                    | 模块                                                                                                                                                                           | 干什么的             |
| --------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------- |
| **① 消息与提示**（对话的"信"）   | `messages`、`prompts`、`prompt_values`                                                                                                                                         | 怎么表达"说给模型的话"     |
| **② 模型与解析**（对话的"脑子"）  | `language_models`、`output_parsers`、`embeddings`                                                                                                                              | 怎么调模型、怎么解析输出     |
| **③ 数据与检索**（对话的"资料"）  | `documents`、`document_loaders`、`retrievers`、`vectorstores`、`cross_encoders`                                                                                                  | 怎么准备和召回知识        |
| **④ 组合与编排**（对话的"流水线"） | `runnables`、`outputs`、`load`、`tools`、`agents`                                                                                                                                | 怎么把零件串成链         |
| **⑤ 基础设施**（对话的"后勤"）   | `callbacks`、`tracers`、`utils`、`chat_history`、`stores`、`caches`、`example_selectors`、`indexing`、`rate_limiters`、`chat_loaders`、`chat_sessions`、`structured_query`、`exceptions` | 追踪、存储、限速、报错等支撑能力 |

***

## 3. 数据字典：⭐ 必须掌握（你已经在用的 9 个模块）

### 3.1 `messages`（56 个导出）——消息对象全集

| 类/函数                                           | 作用                     | 你见过的位置   |
| ---------------------------------------------- | ---------------------- | -------- |
| `BaseMessage`                                  | 所有消息的爹（6 字段）           | 02 篇     |
| `HumanMessage` / `SystemMessage` / `AIMessage` | 三种基本消息                 | 02 篇     |
| `AIMessageChunk`                               | 流式碎片                   | 04 篇     |
| `ToolMessage`                                  | 工具返回结果（本系列没用，agent 才用） | —        |
| `ToolCall`                                     | 工具调用结构（name/args/id）   | 02 篇     |
| `trim_messages`                                | 裁剪消息（长对话用）             | 06 篇边界提过 |
| `AnyMessage`                                   | 类型别名（消息列表的类型注解）        | —        |

### 3.2 `prompts`（21 个导出）——模板

`ChatPromptTemplate` / `MessagesPlaceholder` / `PromptTemplate`——03 篇全用过。

### 3.3 `language_models`（19 个导出）——模型的"爹"

| 类                   | 作用                                                                        |
| ------------------- | ------------------------------------------------------------------------- |
| `BaseChatModel`     | **所有 Chat 模型的爹**：invoke/stream/bind\_tools/with\_structured\_output 都定义在这 |
| `BaseLLM`           | 旧式文本模型（0.x 遗留，一般不用）                                                       |
| `FakeListChatModel` | **假模型**！测试时模拟模型回复，不真调 API                                                 |

### 3.4 `output_parsers`（17 个导出）——输出处理

`StrOutputParser`（04 篇）、`BaseOutputParser`（接口）、`PydanticOutputParser`（05 篇的底层）。

### 3.5 `embeddings`（3 个导出）——向量接口

`Embeddings`（08 篇）：`embed_query` / `embed_documents` / 异步版。

### 3.6 `documents`（3 个导出）——知识盒子

`Document`（07 篇）、`BaseDocumentTransformer`（切分器接口的爹）、`BaseDocumentCompressor`（压缩器接口的爹）。

### 3.7 `retrievers`（24 个导出）——检索器

`BaseRetriever`（08 篇）：`invoke(query) -> list[Document]`。

### 3.8 `vectorstores`（4 个导出）——向量库接口

`VectorStore`（08 篇：add\_texts/similarity\_search/as\_retriever）、`VectorStoreRetriever`、**`InMemoryVectorStore`（内存版向量库，测试神器——不用装 Chroma）**。

### 3.9 `runnables`（29 个导出）——组合协议（规定性 9 的核心）

| 类                            | 作用                                                          |
| ---------------------------- | ----------------------------------------------------------- |
| `Runnable`                   | 所有可执行单元的接口（invoke/batch/stream/\|）                          |
| `RunnablePassthrough`        | 透传（09 篇）                                                    |
| `RunnableLambda`             | 把普通函数变成 Runnable                                            |
| `RunnableParallel`           | 并行分支（09 篇的 `{...}` 语法糖）                                     |
| `RunnableSequence`           | 顺序链（`a \| b` 的产物）                                           |
| `RunnableWithMessageHistory` | **⚠️ 已废弃**（1.3.3 标记 deprecated，2.0 移除）——06 篇我们不用它，教了更稳的手动方案 |

***

## 4. 数据字典：✅ 了解即可（进阶/生产才用）

### 4.1 `callbacks`（34 个导出）——生命周期监听

`BaseCallbackHandler`：监听 `on_llm_start` / `on_llm_end` / `on_tool_start`……**做生产应用想看"每次调用多少 token、耗时多久"就写它的子类。LangSmith 追踪的底层就是它。**

### 4.2 `chat_history`（13 个导出）——记忆存储抽象

`BaseChatMessageHistory` / `InMemoryChatMessageHistory`——**06 篇的"正规军"**。接口统一，生产换 Redis 实现即可。

### 4.3 `stores`（19 个导出）——通用 KV 存储

`BaseStore` / `InMemoryStore`：比 chat\_history 更底层，存任意键值数据、跨会话共享。

### 4.4 `load`（6 个导出）——序列化

`dumps` / `loads`：把 prompt/消息存成 JSON，下次加载。生产配置管理用。

### 4.5 `indexing`（8 个导出）——增量索引

`index()` / `RecordManager`：**生产文档更新时才需要**——只处理新文档，不用每次全量重建（13 篇的 indexer 是简化版）。

### 4.6 `rate_limiters`（7 个导出）——限速

`InMemoryRateLimiter` / `BaseRateLimiter`：批量调用防 429（11 篇讲过 API 限流）。

### 4.7 `example_selectors`（5 个导出）——few-shot 选例

`SemanticSimilarityExampleSelector`：给模型例子（few-shot）时自动挑最相关的。

### 4.8 `cross_encoders`（3 个导出）——重排序接口

`BaseCrossEncoder`：**10 篇重排的接口抽象**（我们直接用的 sentence-transformers）。

### 4.9 `outputs`（7 个导出）——内部结构

`LLMResult` / `ChatResult`：`generate()` 批量接口和回调里的原始结构。**`invoke()` 直接给 AIMessage，日常碰不到。**

### 4.10 其他（知道存在即可）

`document_loaders`（文档加载接口）、`structured_query`（结构化查询翻译）、`caches`（缓存）、`chat_loaders`/`chat_sessions`（聊天记录导入）、`tracers`（追踪）、`utils`（工具函数）、`exceptions`（下一节）、`env`/`globals`/`version`/`sys_info`/`_api`/`_security`/`_import_utils`（内部基础设施）。

***

## 5. 数据字典：⚠️ 避坑（这些是"坑"不是"知识"）

### 5.1 `agents` 模块（14 个导出）——历史包袱

里面有 `AgentAction` / `AgentStep` / `AgentFinish`——**这是 LangChain 0.x 时代 AgentExecutor 的数据结构**。看到旧教程里的 `AgentExecutor`/`AgentAction` 就知道是历史遗留。本系列不用 agent（你要求的），直接避开。

### 5.2 根本没有 `structured_output` 模块！

```python theme={null}
from langchain_core.structured_output import ...   # ← ImportError！
```

**结构化输出不是独立模块**，是 `BaseChatModel.with_structured_output()` 方法 + `output_parsers` 里的 Pydantic 系列实现的（05 篇）。

### 5.3 `exceptions`（8 个导出）——报错认类型

`LangChainException`（所有异常的爹）、`OutputParserException`（解析失败）。**catch `LangChainException` 不会漏。**

***

## 6. 关键方法（本片主角：怎么"看"这个包）

```python theme={null}
import langchain_core, pkgutil
# 列所有模块
[p.name for p in pkgutil.iter_modules(langchain_core.__path__)]
# 看某个模块的公开导出
import langchain_core.messages as m
[n for n in dir(m) if not n.startswith('_')]
# 看类从哪来
ChatAnthropic.__mro__   # 继承链 → BaseChatModel
```

***

## 7. 进程线程模型

```
本片 0 并发、0 网络、0 阻塞：
  import + dir() + 读源码 —— 纯 CPU 毫秒级
```

唯一的"耗时"是理解本身。

***

## 8. 网络模型

**0 网络请求。** 本片是纯代码考古——翻 `site-packages/langchain_core/` 目录和 `dir()` 输出。这正是 langchain\_core 的定位：**它是协议层，不发请求；发请求的是集成包（langchain-anthropic 等）。**

***

## 9. 验证：跑起来

配套代码 `code/13_core_map.py`：

1. 打印 langchain\_core 版本和全部模块；
2. 验证"没有 structured\_output 模块"（ImportError 演示）；
3. 验证 `ChatAnthropic` 是 `BaseChatModel` 的子类（你天天用的东西的"族谱"）；
4. 打印 `RunnableWithMessageHistory` 的废弃警告。

```powershell theme={null}
cd enterprise-rag-course\code
python 13_core_map.py
```

**预期输出（节选，实测）**：

```
===== ① 模块清单 =====
langchain_core 1.5.1 共 36 个模块:
  agents  caches  callbacks  chat_history  ...  vectorstores  version

===== ② 结构化输出模块不存在 =====
ImportError: No module named 'langchain_core.structured_output'
→ 结构化输出在 BaseChatModel.with_structured_output() 里

===== ③ ChatAnthropic 的族谱 =====
ChatAnthropic 是 BaseChatModel 的子类: True
```

***

## 10. 边界

* **模块数量会随版本变**——1.5.1 是 36 个，升级可能增减。以 `dir()` 实测为准，别背死。
* **下划线开头的模块（\_api/\_security 等）是内部的**——别 import，别学，API 随时变。
* **`agents` 模块 ≠ 本系列说的"不用 agent"**——那是旧 AgentExecutor 的历史数据结构，和 create\_agent（LangGraph）无关。两者都不是我们要用的。
* **`RunnableWithMessageHistory` 已废弃**——网上旧教程大量用它，看到就换手动方案（06 篇）。

***

## 推荐资料（延伸阅读）

* [langchain-core API 参考（全目录）](https://reference.langchain.com/python/langchain-core/) —— 36 个模块的完整类清单
* [LangChain 官方文档 · 总览](https://docs.langchain.com/oss/python/langchain/overview) —— 包结构官方说明

***

## 11. 未完待续

地基盘点完了。你知道了 36 个模块里哪些是你的日常工具（9 个）、哪些是进阶武器（callbacks/indexing/rate\_limiters）、哪些是坑（agents/废弃 API）。

但地基再清楚，**机器人还没法被外部调用**。100 个用户怎么同时用你的 RAG？——这就是第 14 篇：FastAPI 服务化。

→ [14 · FastAPI 服务化](/doc/doc/enterprise-rag-course/14-FastAPI服务化)
