What Is LangExtract? When It Fits a Structured-Extraction Pipeline

LangExtract is Google's free, Apache 2.0 library for grounded LLM extraction. When it fits a pipeline, where it breaks, and the alternatives to weigh.

What Is LangExtract? When It Fits a Structured-Extraction Pipeline
Written by TechnoLynx Published on 24 Aug 2026

LangExtract is Google’s open-source Python library for turning unstructured text into structured information with a large language model (LLM). It follows your own instructions and a few worked examples. Every extracted entity is mapped back to its exact character offsets in the source text. So LangExtract is a schema-and-grounding harness around a model call, not a general “point it at documents, get fields” answer. It fits when the source is free-form prose with unpredictable phrasing, the documents are long, and a reviewer has to see where each field came from. When the source is semi-structured and stable, a parser, a rule-based matcher or a fine-tuned token classifier is usually cheaper and easier to audit.

What Is LangExtract, and When Does It Fit a Structured-Extraction Pipeline?

The library itself is free to use. LangExtract was released by Google on 30 July 2025 under the Apache 2.0 licence, which makes it free for commercial and research use, and PyPI lists v1.2.0 as of March 2026. The real cost is the model behind it: Google’s own long-document example warns that it will incur API costs.

The limits belong in the fit decision from the start. LangExtract is not an officially supported Google product, has no vendor SLA, has no OCR, classification or workflow layer, and offers weaker deterministic guarantees than fine-tuned or rule-based systems. Its extraction quality depends on how clear the instructions are and how good the examples are. None of that rules it out. It does mean the team that adopts LangExtract owns its behaviour in production, including version pinning and regression testing when the library or the model changes.

LangExtract earns its per-token cost when three things are true together: the phrasing in the source varies too much for rules to cover, the schema is still changing (so labelling data for a trained model would be premature), and someone downstream has to verify fields against the original text. Clinical notes are the case Google gives. The ideas behind the library were first applied to medical extraction, where it can pick out medications, dosages and their attributes and map the relationships between them.

What Does LangExtract Actually Do That a Plain LLM Prompt with a JSON Schema Does Not?

LangExtract adds provenance and long-document handling on top of structured output. A bare prompt asking for JSON does not even guarantee the shape: OpenAI’s documentation says JSON mode guarantees only valid JSON, not a match to any particular schema, and recommends validation and retries where schema-enforcing Structured Outputs is not available. Native structured outputs close that gap. OpenAI’s Structured Outputs keeps responses to the supplied JSON Schema, and Gemini can be configured the same way for type-safe extraction.

LangExtract defines the output through its own data representation plus few-shot examples and uses Controlled Generation in supported models such as Gemini to keep outputs consistently structured. It then attaches each entity to its character span in the source. It also splits long input into delimiter-aware chunks, runs them in parallel and merges the results across passes. Google pitches it as working across domains from a few well-chosen examples, without fine-tuning a model.

So compare LangExtract with a schema-enforced call to the same model, not with “an LLM”. The question is whether span grounding and the chunk-and-merge loop are worth a library dependency, or whether you would rather write those two pieces yourself around a structured-output call.

How Does Source Grounding Work, and Why Do Traceable Spans Matter for Extraction Review?

Source grounding in LangExtract means each extracted entity carries the exact character offsets where it appears in the input. Google’s tooling uses those offsets to highlight every extraction in the original text so it can be checked. Results are saved as JSONL, one self-contained JSON object per line, and can be reloaded later for analysis.

Spans matter because they change what review costs. With a span, a reviewer confirms a field by looking at the highlighted sentence. Without one, they have to re-read the document to find out whether the value is there at all. Spans also turn an unverifiable class of error into a checkable one. A value whose span does not contain it, or that has no span, can be flagged automatically before a human sees it.

One feature works against this. LangExtract can supplement extractions with the model’s world knowledge, and Google separates explicit information (taken from the text) from inferred information (taken from the model). Google says the accuracy of inferred values depends heavily on the chosen model and the precision of the examples. In a pipeline where fields feed decisions, we would keep inferred values in a separate field and never mix them with grounded ones. An inferred value has no passage to check it against, so it cannot be reviewed the way a grounded one can.

Which Models Can LangExtract Run with Besides Gemini?

LangExtract ships three built-in providers. Gemini works through the Gemini API or Vertex AI. OpenAI works through the OpenAI API or OpenAI-compatible endpoints. Local open-source models run through an Ollama server, which needs no authentication. Gemini and Ollama are core providers with their dependencies included. The OpenAI provider’s code ships with the package, but you install its SDK with pip install langextract[openai]. Any other backend comes in as a separately installed external plugin, which LangExtract discovers through Python entry points. The project recommends plugins for adding providers. For Azure OpenAI, we would try an OpenAI-compatible endpoint or a plugin. Check whichever you choose against your deployment before you rely on it.

Choosing a backend is partly a data-handling decision. Running through a local Ollama server keeps extraction local, which can settle the question for clinical or legal text before quality comes into it.

How Does LangExtract Handle Long Documents, and What Breaks as Length and Schema Complexity Grow?

LangExtract handles long documents by not giving the model the whole document at once. It splits text into chunks that respect delimiters such as paragraph breaks. It processes the chunks in parallel and aggregates and deduplicates the results. Three parameters control this:

  • max_char_buffer sets the context size of each chunk.
  • max_workers sets how many chunks run concurrently, with up to 20 workers reported.
  • extraction_passes runs the full extraction several times with identical prompts and examples. Overlapping entities are merged on a “first pass wins” basis, and unique entities from later passes are added.

Google’s reasoning for chunking is that recall can drop in multi-fact retrieval across million-token contexts, even for models that do well on benchmarks. Smaller, focused contexts avoid that degradation. A separate study of LLM extraction measures the same weakness. A study of LLM information extraction describes the “lost in the middle” effect, where attention favours the beginning and end of a long context. On documents that nearly filled gpt-4-1106-preview’s 128,000-token input window, extraction from middle sections was measurably more redundant. The same study notes that the output limit is typically much stricter than the input limit: that model allowed 4,095 output tokens, so a dense enough text simply runs out of room for more entities.

Extra passes help only up to a point. In that study, repeated extraction improved completeness, but from the third iteration most quality scores worsened or stagnated. The authors saw growing bias and a rising risk of hallucination, and used three iterations as their working setting for documents of roughly 12,000 characters. They also say the right number depends heavily on the text and the schema. For that reason we would treat extraction_passes as something to tune against a labelled sample, not as a dial to turn up for safety. Each pass reprocesses the full text. Google’s own demo runs about 44,000 tokens and suggests a Tier 2 Gemini quota for large-scale use.

Schema complexity has a separate ceiling, set by the model provider. Gemini’s structured output mode supports only a subset of JSON Schema, and OpenAI returns an error if strict mode is called with an unsupported schema. Our view is that a sprawling schema should be split into several focused extraction tasks well before it reaches those limits. Every extra type and nested attribute competes for the same examples and output budget.

PDFs and Scans Need Parsing Before LangExtract Sees Them

LangExtract works on clean text. In a PDF pipeline, a parser such as Docling handles layout recovery and format conversion, and LangExtract then extracts entities from the resulting text. The two are complementary, not competing. Scanned pages and complex layouts may need OCR and reading-order recovery first, because PDFs and images carry no semantic markup describing their structure. That upstream stage is its own engineering problem, covered in our piece on document intelligence for regulated teams.

When a Parser, Regex or Fine-Tuned Token Classifier Beats an LLM Extractor

A deterministic parser or regex is the better choice when the target has a clear pattern or a roughly finite set of values. spaCy’s documentation gives country names, IP addresses and URLs as cases that rules handle well. spaCy’s PhraseMatcher finds exact instances from an existing terminology list. Its token-level Matcher can express patterns over lemmas, part-of-speech tags and fuzzy spellings. Rules also give stronger deterministic guarantees than LangExtract.

A fine-tuned token classifier is the better choice when the schema has settled and you can label data. Token classification assigns a label to each token, and named entity recognition (NER) is its most common form. The evidence here cuts against treating a large model as the safe default. Across nine datasets and four extraction tasks, a 2023 study found that advanced LLMs consistently performed worse, with higher latency and cost, than fine-tuned small models under most settings. The GLiNER authors (2023) report that a 50-million-parameter encoder NER model outperformed ChatGPT on zero-shot entity recognition, and that it handles arbitrary entity types by matching them against text spans instead of generating tokens. A 2024 review of LLM data extraction in materials science adds that BERT-class encoder models need less data and compute when general capabilities are not required, though they should still be fine-tuned for the task.

LLMs keep two roles in this picture. The same 2023 study reports promising preliminary improvements, a 2.4% average F1 gain, from LLMs reranking the hard cases a small model flags. The review’s decision tree starts with a general-purpose model on zero- or few-shot prompts and moves to fine-tuning only if results fall short and labelled data exists. spaCy makes a similar point from the other side: rules are often the practical start of a project and can help bootstrap a trained model. For the wider selection between rule-based, statistical and neural methods, see our practitioner’s guide to natural language processing algorithms.

LangExtract Alternatives for LLM-Based Structured Extraction

The tools below are all named options, and none wins outright. The right one depends on whether you need span provenance, guaranteed shape, local models or no LLM at all.

Tool Approach Fits when
LangExtract Few-shot schema with Controlled Generation, character-offset grounding, chunking and passes Long free text where reviewers must trace each field to its source
Instructor (MIT licence) Pydantic-based validation, automatic retries and streaming across 15+ providers Fast, schema-first extraction without extra agent machinery
Outlines Enforces structure during generation: JSON schemas, regex, grammars, fixed choices; runs across OpenAI, Ollama, vLLM and more Local or self-hosted models where output must match a format exactly
OpenAI Structured Outputs Responses keep to the supplied JSON Schema; unsupported schemas error in strict mode Short inputs on OpenAI models where shape matters more than provenance
Gemini structured output JSON Schema subset, Pydantic or Zod definitions in the SDKs The same need on Gemini, with no library layer
LangStruct DSPy prompt optimisers, Pydantic types, character-level mapping to source text You want prompts tuned automatically from examples and feedback
GLiNER Compact bidirectional encoder for any entity type, parallel span extraction Entity extraction at volume without LLM inference cost
spaCy Matcher / PhraseMatcher Token and phrase rules, deterministic Clear patterns or a fixed vocabulary

The 2024 materials-science review lists Outlines, Instructor and OpenAI’s structured outputs among the libraries that support constrained decoding, which restricts sampling to allowed tokens. That family solves output shape. LangExtract and LangStruct also address where the value came from.

How Do I Measure Whether a LangExtract-Based Pipeline Is Good Enough?

Measure a LangExtract pipeline per field, against a labelled sample from your own corpus, on three numbers: field-level precision and recall, the share of extracted values with a span that actually contains them, and token spend per thousand pages. A demo run on public text says nothing about your documents. The 2024 review calls evaluation essential to optimising any extraction pipeline.

Sample size is where we would push back on a single number. No single figure holds in general. What sets it is the rarest field that matters, because the sample needs enough occurrences of that field for its recall to mean anything. So we would size the sample by field frequency, not by document count, and add a few deliberately long documents to expose middle-of-context losses. One technique produces known ground truth without manual labelling. The extraction-quality study’s MINEA score scatters known synthetic “needles” through a document (10 to 30% of the enriched text) and measures how many are recovered. Because you know exactly what should come out, the score is objective.

Hold the setup fixed while you measure. The review says a temperature of 0 is typically best for structured extraction because it leads to deterministic outputs. Model choice matters a lot: the same study measured gpt-4-turbo nearly 15% ahead of gpt-3.5-turbo and gpt-4o a further 12% ahead. Changing the backend means re-running the evaluation, not assuming the numbers carry over.

A Pre-Commitment Checklist for a Production LangExtract Pipeline

Run these checks before LangExtract becomes a dependency:

  1. Text quality upstream. Is the input clean text, with PDF parsing, OCR and reading order handled by a separate stage?
  2. Deterministic coverage. How much of the corpus could rules or a parser handle, and could only the residual free text go to the LLM?
  3. Labelled sample. Do you have field-level ground truth, sized by your rarest important field, including long documents?
  4. Grounding policy. Are inferred values allowed, and if so, are they stored apart from grounded spans and excluded from automatic acceptance?
  5. Chunking and passes. Have max_char_buffer and extraction_passes been tuned against the sample, with the point of diminishing returns recorded?
  6. Schema limits. Does the schema stay inside the chosen provider’s supported JSON Schema subset, or should it be split into focused tasks?
  7. Backend and data handling. Is the model cloud-hosted or local through Ollama, and does that match where the documents are allowed to go?
  8. Cost per document. Is token spend per thousand pages measured at production volume and quota, not estimated from a demo?
  9. Ownership. Is the library version pinned, with a regression run on the labelled sample before any library or model upgrade?

Where extraction feeds retrieval, review queues or downstream models, TechnoLynx’s Generative & Agentic AI R&D work covers that territory.

The Design That Usually Beats Picking One Tool

On a mixed corpus, the choice is often not LangExtract or a parser but which documents go where. Rules or a trained classifier take the stable, high-volume subset. LangExtract takes the free-form residue where phrasing is unpredictable and spans are needed for review. That keeps inference cost in proportion to the hard subset instead of the whole pipeline. The 2023 filter-then-rerank result points the same way: small models screen everything, and the LLM is spent on the samples they find hard. What you still have to settle is where your corpus actually splits. Only your labelled sample can tell you that, so build it before you choose the library.