---
catalog_id: "R-110"
kind: "repo"
domain: "agent"
domain_label: "Agent 编排 / Agent Systems"
date: "2026-11-28"
title: "google/langextract"
verdict: "按句分块配动态规划偏移对齐，让长文本结构抽取句句可溯源"
summary: "Apache-2.0 开源的 Python 结构化信息抽取库，通过句子边界分块、多轮顺序召回、单调发生动态规划（DP）+ LCS 密度的精确字符偏移源文本对齐、Provider 原生 Schema 约束与插件化模型路由，将非结构化长文本映射为可溯源的 AnnotatedDocument 与交互式高亮 HTML。"
summary_en: "Python extraction library pairing sentence chunking, multi-pass recall, and DP+LCS char-offset grounding with schema-constrained routing."
canonical_url: "https://oumuatown.com/repos/google__langextract/"
markdown_url: "https://oumuatown.com/repos/google__langextract.md"
og_image_zh: "https://oumuatown.com/og/zh/R-110.png"
og_image_en: "https://oumuatown.com/og/en/R-110.png"
cite_count: 69
repo: "google/langextract"
github_url: "https://github.com/google/langextract"
commit: "9ed9613"
tags:
  - "structured-extraction"
  - "source-grounding"
  - "chunking"
  - "schema-constraints"
  - "provider-abstraction"
  - "html-visualization"
github_repos:
  - "https://github.com/google/langextract/tree/9ed9613"
---

# R-110 · google/langextract

> **结论 / Verdict**: 按句分块配动态规划偏移对齐，让长文本结构抽取句句可溯源
> **EN Summary**: Python extraction library pairing sentence chunking, multi-pass recall, and DP+LCS char-offset grounding with schema-constrained routing.

## Provenance & Evidence

- Primary Repository: https://github.com/google/langextract (@9ed9613)
- Verified Source Citations (#Lxx): 69
- Web Reader: https://oumuatown.com/repos/google__langextract/

# google/langextract

> 仓库地址：https://github.com/google/langextract · 审计版本：`google/langextract@9ed9613` · 审计日期：2026-11-28
> 来源文章：[20 个 Google Agent 开源仓库分层图谱](../articles/2026-11-28-0xmovez-20-google-agent-repos.md)

## 定位与解决的真问题

- **核心定位与目标用户**：面向需要从医疗病历、法务文书、文学长篇或业务文档中抽取结构化实体的 Python 开发者与 Agent 工具链；在源文引用中归入“Grounded 外部工具层”，同时仓库内置 `skills/langextract-usage/SKILL.md` 供编码 Agent 按需加载。
- **相比常规做法解决的关键痛点**：
  1. **提取结果缺乏可验证的源文本坐标**：常规 LLM JSON 抽取常出现轻微改写、幻觉或漏掉位置信息；LangExtract 在解析 LLM 输出后强制执行词元/字符级对齐（`WordAligner`），为每条 `Extraction` 绑定精确 `CharInterval(start_pos, end_pos)` 与 `AlignmentStatus`（`langextract/core/data.py#L43-L119`、`langextract/resolver.py#L828-L1112`）。
  2. **长文档与多实体召回衰减**：通过基于正则/Unicode 句子边界的自适应分块（`ChunkIterator`）、跨块前文共指窗口（`context_window_chars`）以及“首轮优先合并”的多轮顺序抽取（`extraction_passes > 1`），兼顾长文吞吐与跨句指代/低频实体召回（`langextract/chunking.py#L343-L506`、`langextract/annotation.py#L46-L116`, `#L459-L542`）。
  3. **多模型结构化输出能力参差**：将“提示词生成与容错解析（`FormatHandler`）”与“各厂商受限解码 Schema（`GeminiSchema` / `OpenAISchema` / `FormatModeSchema`）”解耦，统一支持从 `examples` 自动推导约束或由调用方传入显式 `output_schema`（`langextract/core/output_schema.py#L50-L322`、`langextract/factory.py#L256-L346`）。

## 技术栈与核心目录结构

- **语言 / 运行时 / 关键依赖**：Python `>=3.10`（版本 `1.7.2`，Apache-2.0 协议），核心依赖 `google-genai>=1.39.0`、`google-cloud-storage>=2.14.0`（Vertex Batch 缓存）、`pydantic>=1.8.0`、`PyYAML>=6.0`、`regex>=2023.0.0`、`pandas>=1.3.0`、`requests>=2.25.0`、`tqdm>=4.64.0`，可选 `openai>=1.50.0`（`pyproject.toml#L20-L60`）。内部通过 `import-linter` 强制单向分层约束：`core` 禁止导入 `providers` 与高层编排模块，`providers` 禁止导入 `inference`（`pyproject.toml#L137-L162`）。
- **关键目录树与职责划分**（`google/langextract@9ed9613`）：
  - `langextract/extraction.py`：主入口 `extract`，串联 URL 下载（默认关闭）、Few-shot 预检、模型构建、格式解析与 `Annotator` 调度。
  - `langextract/annotation.py`：`Annotator` 流式单轮/多轮（`extraction_passes`）批处理引擎与重叠区间合并。
  - `langextract/chunking.py` & `langextract/core/tokenizer.py`：`RegexTokenizer` / `UnicodeTokenizer` 分词、句界探测与 `ChunkIterator` / `TextChunk` 分块器。
  - `langextract/resolver.py`：`Resolver` 解析与 `WordAligner` 源文本对齐引擎（单调发生 DP 精确对齐 + LCS 密闭度模糊对齐）。
  - `langextract/prompting.py` & `langextract/prompt_validation.py`：`QAPromptGenerator`、`ContextAwarePromptBuilder` 与 Few-shot 示例预对齐自检。
  - `langextract/core/`：`BaseLanguageModel`、`FormatHandler`、`output_schema`、`BaseSchema`/`FormatModeSchema`、`data` 核心数据模型。
  - `langextract/providers/` & `langextract/factory.py` & `langextract/plugins.py`：正则路由注册表（`router.py`）、`entry_points` 第三方插件发现，以及 `gemini` / `gemini_batch` / `openai` / `openai_batch` / `ollama` 驱动与对应 `schemas/`。
  - `langextract/visualization.py` & `langextract/io.py`：交互式 HTML 染色/动画导出（含 Jupyter & GIF 优化模式）与 JSONL/CSV 读写。
  - `skills/langextract-usage/`：面向编码 Agent 的 `SKILL.md` 与参数参考手册。

## 核心实现源码级剖析（附文件路径与行号）

1. **端到端结构化抽取管线与安全边界**（`langextract/extraction.py#L45-L462`、`langextract/annotation.py#L209-L458`）：
   - `extract` 先校验 `examples` 与 `output_schema` 至少存在其一，并拒绝 `output_schema` 与 `fence_output=True` 的冲突组合（`extraction.py#L213-L226`）。
   - 若 `prompt_validation_level` 不为 `OFF`（默认 `WARNING`），调用 `validate_prompt_alignment` 预先将用户编写的 few-shot `examples` 反向对齐到各自的 `ex.text` 上，提前拦截拼写改写或无法溯源的坏示例（`extraction.py#L228-L245`、`prompt_validation.py#L130-L269`）。
   - `fetch_urls` 默认 `False`；文档注释明确警示开启时直接走无净化 `requests.get`，存在 SSRF 风险，仅限可信 URL 与沙箱环境使用（`extraction.py#L188-L192`, `#L264-L269`）。
   - 实例化模型与 `FormatHandler`、`Resolver` 后，交由 `Annotator.annotate_documents`。单轮模式 `_annotate_documents_single_pass` 采用惰性流式消费：通过 `_capture_docs` → `_document_chunk_iterator` → `make_batches_of_textchunk` 按 `batch_length` 切批，批内调用 `model.infer`（过滤掉对齐专用 `ALIGNMENT_PARAM_KEYS` 避免透传给 Ollama 等外部接口），解析对齐后一旦切换至下一篇文档立即 `_emit_docs_iter(keep_last_doc=True)` 释放内存（`annotation.py#L310-L457`）。

2. **Unicode 感知分词、句界分块与多轮召回**（`langextract/core/tokenizer.py#L180-L647`、`langextract/chunking.py#L282-L506`、`langextract/annotation.py#L46-L116`, `#L459-L542`）：
   - 提供两套分词器：`RegexTokenizer`（英文默认快路径，`tokenizer.py#L180-L227`）与 `UnicodeTokenizer`（基于 `regex` 的 `\X` 字素簇迭代，刻意**不做 NFC 归一化**以保证字符偏移与原字符串 1:1 对齐，并强制对 CJK/泰语等无空格文字逐字切分，`tokenizer.py#L321-L442`）。
   - `find_sentence_range` 以句末标点（含 `。！？` 与 `\u0964`）及“换行后接非小写字符”切句，同时跳过 `Mr.`/`Dr.` 等 `_KNOWN_ABBREVIATIONS` 并吞并尾部闭合引号括号（`tokenizer.py#L510-L647`）。
   - `ChunkIterator` 按 `max_char_buffer`（默认 `1000`）贪心合并完整句子；若单句超长则优先在 `first_token_after_newline` 换行处折断，若单个 Token 本身超长则独立成块（`chunking.py#L441-L506`）。
   - 跨块共指与多轮召回：`ContextAwarePromptBuilder` 按 `document_id` 隔离记录上一块尾部 `context_window_chars` 字符并拼接 `[Previous text]: ...` 前缀（`prompting.py#L179-L276`）；当 `extraction_passes > 1` 时，`_annotate_documents_sequential_passes` 会全量重跑 `N` 轮并由 `_merge_non_overlapping_extractions` 按“字符区间交叉即丢弃后者（first-pass wins）”策略合并结果（`annotation.py#L46-L116`, `#L459-L542`）。

3. **精确字符偏移源文本定位与对齐算法**（`langextract/resolver.py#L296-L1443`）：
   - **解析阶段**：`Resolver.resolve` 委托 `FormatHandler.parse_output` 提取内容。当 `use_fences=True` 时通过 `_FENCE_RE` 抽取代码块；若解析失败且非 `strict` 模式，会自动剥离推理模型（如 DeepSeek-R1/QwQ）输出的 `<think>...</think>` 标签后重试，并兼容裸顶层列表 `[...]` 与 `{"extractions": [...]}` 两种包络（`core/format_handler.py#L46`, `#L169-L352`）。`extract_ordered_extractions` 过滤空值/不可见 `Cc`/`Cf` 控制字符，并支持按 `_index` 后缀重排或按出现顺序输出（`resolver.py#L93-L105`, `#L467-L575`）。
   - **三段式对齐阶段**（`WordAligner.align_extractions`，`resolver.py#L828-L1112`）：
     1. **精确对齐（默认 `"dp"`）**：`_apply_monotonic_exact_matches` → `_select_monotonic_matches` 使用基于二分查找维护的 Pareto 最优前沿（`_FrontierEntry(end, weight)`）执行**单调发生动态规划**：在保持模型输出顺序与不重叠的前提下最大化匹配 Token 总数，平局优先最早结束位置，使重复提及的同名实体依次落到后继真实出现位置上（`resolver.py#L1152-L1282`）；也可切回 `"difflib"` 旧贪心策略。
     2. **部分精确匹配（`MATCH_LESSER`）**：对 DP 未命中的剩余抽取，走 `difflib.SequenceMatcher`（`autojunk=False`，以 `\u241F` 分隔符拼接全部抽取一次比对）匹配子块，若 `accept_match_lesser=True` 则标为 `MATCH_LESSER`（`resolver.py#L933-L1059`）。
     3. **模糊对齐（默认 `"lcs"`）**：对仍未对齐项执行 `_lcs_fuzzy_align_extraction`。先用 `_normalize_token` 做轻量复数词干归一化（`len > 3` 去尾 `s`），再运行 $O(n \cdot m^2)$ 滚动行 LCS DP `_best_lcs_spans` 为每个匹配数 `k` 找最紧凑源跨度，并按降序检验双门禁 `_accept_lcs_match`：覆盖率 `matches >= ceil(m * 0.75)` 且密度 `matches / span_len >= 1/3`，防止匹配 Token 稀疏分散在整段噪声文本中（`resolver.py#L756-L826`, `#L1315-L1443`）。最终将 Token 区间与块的 `(token_offset, char_offset)` 相加，写回原文精确 `CharInterval`。

4. **Few-shot 模板与显式/推导式 Schema 约束**（`langextract/prompting.py#L39-L139`、`langextract/core/output_schema.py#L50-L322`、`langextract/providers/schemas/gemini.py#L34-L204`、`openai.py#L158-L329`）：
   - `QAPromptGenerator` 将 `PromptTemplateStructured(description, examples)` 渲染为 `description + additional_context + Examples (Q:/A:) + Q: <chunk> + A:` 文本流（`prompting.py#L85-L138`）。
   - 若调用方未传 `output_schema` 且 `use_schema_constraints=True`，`factory._create_model_with_schema` 会调用目标 Provider 的 `get_schema_class.from_examples(examples)` 动态推导结构约束：`GeminiSchema` 生成 `response_schema`（OpenAPI 风格）并强制 `response_mime_type='application/json'`（`schemas/gemini.py#L63-L193`）；`OpenAISchema` 则构造 `strict: True` 的 `anyOf` 联合体，用 `anyOf: [..., {"type": "null"}]` 包裹属性对象以兼顾 OpenAI 严格模式的全字段 `required` 要求与可选属性语义（`schemas/openai.py#L42-L290`）。
   - 若传入显式 `output_schema`（可由 `lx.schema.extractions_schema` / `extraction_item_schema` 构造），`validate_output_schema` 强制校验顶层 `extractions` 数组包络且禁用 `extraction_class`/`extraction_text`/`attributes` 等保留键，Gemini 将其透传给原生 JSON Schema 字段 `response_json_schema`（`core/output_schema.py#L108-L322`、`schemas/gemini.py#L69-L75`, `#L195-L204`）。

5. **交互式 HTML 可视化与 XSS 防护**（`langextract/visualization.py#L183-L646`）：
   - `visualize` 过滤出带有效 `CharInterval` 的抽取并按分类分配 10 色循环调色板；`_build_highlighted_text` 为起止边界生成 `SpanPoint` 并按 `(position, END先于START, 闭合短跨度先关/开启长跨度先开)` 排序，确保嵌套或重合跨度生成合法嵌套的 `<span class="lx-highlight">` 标签（`visualization.py#L239-L315`）。
   - 嵌入内联 `<script>` 的 JSON 数据通过 `_to_script_safe_json` 将 `<`、`>`、`&` 转义为 `\u003c`、`\u003e`、`\u0026` 防止 `</script>` 闭合注入，纯文本片段均经过 `html.escape`（`visualization.py#L405-L431`）。生成包含 Play/Pause/Prev/Next 与进度滑块的自包含交互页面，默认开启 `gif_optimized=True` 放大字号与高亮边框。

6. **模型 Provider 抽象、延迟路由与并发/Batch 执行**（`langextract/core/base_model.py#L32-L231`、`langextract/factory.py#L58-L346`、`langextract/providers/router.py#L86-L247`、`langextract/plugins.py#L62-L210`、`langextract/providers/gemini.py#L397-L639`）：
   - **延迟注册与插件发现**：`providers/builtin_registry.py` 通过 `register_lazy` 仅存正则与 `"module:Class"` 字符串，直到 `factory._resolve_provider_class` 命中 `model_id` 正则（如 `^gemini`、`^gpt-[456]`、`^o[1-9]`、`^(gemma|llama|qwen...)`）才按需导入 SDK，并同步扫描 `langextract.providers` entry points 加载社区第三方 Provider（`plugins.py#L75-L91`、`router.py#L86-L169`）。
   - **并发与重试**：`GeminiLanguageModel` 与 `OpenAILanguageModel` 均使用 `ThreadPoolExecutor(max_workers=...)` 并行推理 `batch_prompts`；Gemini 内置 `_RETRYABLE_API_CODES`（408/429/5xx）指数退避抖动重试并显式禁止与 SDK 自带 `http_options.retry_options` 叠加（`gemini.py#L51`, `#L338-L342`, `#L433-L482`, `#L604-L634`），同时支持在达到 `batch.threshold`（默认 50）时自动切换至 GCS/Files API 驱动的 `gemini_batch.infer_batch`（`gemini.py#L539-L592`、`gemini_batch.py#L113-L151`）。`OllamaLanguageModel` 通过 `FormatModeSchema` 支持本地 JSON/YAML 推理，并对 `gpt-oss` 系列的 Harmony 格式冲突单独走窄化系统指令分支（`ollama.py#L110-L127`, `#L171-L178`）。

## 亮点设计 vs 局限/坑点

- **值得借鉴的设计**：
  - **单调发生 DP + 带密度门禁的 LCS 模糊对齐**：既解决了“同一词在文中多次出现时如何按序归位”的经典对齐歧义，又用 `density >= 1/3` 堵住了传统 LCS 把跨页零散词拼成超长高亮框的缺陷。
  - **Prompt 示例预对齐自检（`prompt_validation.py`）**：在花钱调模型之前先用同一套 `WordAligner` 校验 few-shot 示例，把“示例本身不可溯源”这一最隐蔽的调优故障前置暴露。
  - **推理模型 `<think>` 容错与依赖层隔离**：`FormatHandler` 自动剥离 `<think>` 块，且通过 `import-linter` 守护 `core` 与 `providers` 解耦，第三方 Provider 无需修改核心库即可通过 `entry_points` + `BaseSchema` 接入。
- **局限、隐含假设与潜在坑点**：
  - **它不是 MCP Server**：与文章中同层的 `chrome-devtools-mcp` / `mcp-toolbox` 不同，`langextract` 是纯 Python 库（`lx.extract`），仅附带 `skills/langextract-usage/SKILL.md` 供 Agent 编写 Python 调用代码，无法直接作为 MCP 工具挂给无代码执行环境的客户端。
  - **分词器与语言/模型预设偏置**：默认 `tokenizer` 为英文向 `RegexTokenizer`，中文/日文/泰文长文档若未显式传入 `UnicodeTokenizer`，无空格长句会降低句界切分与对齐粒度；默认 `model_id="gemini-3.5-flash"`，使用其他前缀或自建 OpenAI 兼容网关时必须显式提供 `ModelConfig(model_id=..., provider=...)`（`skills/langextract-usage/SKILL.md#L33-L35`）。
  - **多轮与长文成本及 `fetch_urls` 安全**：`extraction_passes > 1` 会按倍数全量重算 Token；`fetch_urls=True` 未做内网/回环地址拦截（依赖调用方自行沙箱隔离）。

## 可复用的模块或设计模式

- **如何迁移到未来项目**：
  1. **引用溯源与 Grounding 引擎（`resolver.py` + `core/tokenizer.py`）**：任何做文档问答高亮、合同条款定位或代码片段溯源的系统，均可直接复用其“不归一化字素簇保留偏移 + 单调 DP 精确匹配 + 密度受限 LCS 模糊匹配”组合。
  2. **嵌套 Span HTML 渲染器（`visualization.py#L239-L315`, `#L421-L431`）**：`SpanPoint` 边界排序与 `_to_script_safe_json` 可直接迁移到需要前端展示重叠实体高亮的任何标注审校工具。
  3. **多厂商受限结构化输出适配模式**：借鉴 `BaseSchema.from_examples` 与 `OpenAISchema` 的 `anyOf + null` 严格模式转换，解决不同模型 API 对 `required` / `additionalProperties` / `nullable` 语义差异的兼容问题。
- **关联 Pattern**：（由 `synthesizer` 补全）

## Cross-Referenced Specimens

- [A-020 · 用 5 层 20 个 Google 系 Agent 开源仓库武装 Gemini 4 Neon `/swarm`——从裸跑编排到技能、运行时与工具栈（先装 3 个而非 20 个）](https://oumuatown.com/articles/2026-11-28-0xmovez-20-google-agent-repos.md) — 二十款谷歌 Agent 仓实测：先装三件套与五处源码勘误
- [P-023 · Google 5 层 Agent 工程栈、协议互操作与运行时选型模式（Google 5-Layer Agent Stack, Protocols & Runtimes）](https://oumuatown.com/patterns/google-agent-stack-protocols-and-runtimes.md) — 五层谷歌 Agent 栈选型矩阵与全栈源码避坑清单
