# Grounded Text & Entity Extractor (`solutionssmart/langextract-grounded-extractor`) Actor

Extract structured entities, clauses, and facts from text or web pages with exact character-offset citations. Fast LangExtract alternative with zero-LLM mode, Gemini/OpenAI support, hallucination filtering, and interactive HTML highlight reports.

- **URL**: https://apify.com/solutionssmart/langextract-grounded-extractor.md
- **Developed by:** [Solutions Smart](https://apify.com/solutionssmart) (community)
- **Features:** Limited permissions, Multi-tenant, Server interface
- **Stats:** 1 total users, 0 monthly users, 0.0% runs succeeded, 0 bookmarks
- **User rating**: No ratings yet

## Pricing

from $0.30 / 1,000 grounded extractions

This Actor is paid per event. You are not charged for the Apify platform usage, but only a fixed price for specific events.

Learn more: https://docs.apify.com/actors/store.md#pay-per-event

## What's an Apify Actor?

An Actor is a serverless cloud program that runs on the Apify platform. It has two run modes.
In Batch mode, an Actor accepts a well-defined JSON input, performs an action which can take anything from a few seconds to a few hours,
and optionally produces a well-defined JSON output, datasets with results, or files in key-value store.
In Standby mode, an Actor provides a web server which can be used as a website, API, or an MCP server.

Apify vocabulary and the platform model are defined once, in the agent quickstart at https://apify.com/agents.md.

## How to integrate an Actor?

If asked about integration, you help developers integrate Actors into their projects.
You adapt to their stack and deliver integrations that are safe, well-documented, and production-ready.

Do not guess an integration path. Every one of them is in the agent quickstart at https://apify.com/agents.md: the Apify MCP server, Agent Skills with the Apify CLI, the JavaScript and Python clients, the REST API, and the account-free path for an agent with no human to sign in. It also carries the rule on stating cost before the first paid run.

For examples already wired to this Actor's own input schema, see the [API](#api) section below.

Each client library has reference documentation the quickstart does not restate: [JavaScript/TypeScript](https://docs.apify.com/api/client/js/docs.md) (`npm install apify-client`) and [Python](https://docs.apify.com/api/client/python/docs.md) (`pip install apify-client`).

# README

## Grounded Text & Entity Extractor

Extract **structured entities, clauses, and key facts** from plain UTF-8 text and HTML web pages—with **exact character-position citations** (`startChar`, `endChar`) mapped back to the original source.

Built as a lightweight **LangExtract alternative** (`google/langextract`) with no headless browser or Python startup overhead, this Actor runs **with or without an LLM API key**, drops any extracted value not found verbatim in the source text, and generates an **interactive HTML highlight report** for visual review.

![Grounded Text & Entity Extractor Interactive HTML Highlight Report](https://api.apify.com/v2/key-value-stores/0YoV2Njb1iUwX8RPM/records/grounded-extractor-highlight-report.png)

***

### Why Use Grounded Text & Entity Extractor?

- **Lightweight, no browser or Python overhead:** Runs directly on plain UTF-8 text and fetched HTML pages without launching a headless browser or heavy Python runtime.
- **Zero-LLM mode or bring your own LLM:** Run immediately in **Zero-LLM (`rule_based`)** mode with built-in or custom regex rules, or connect **Google Gemini**, **OpenAI**, or any **OpenAI-compatible** endpoint for semantic few-shot entity extraction and NER.
- **Exact Unicode code-point offsets:** Every extracted item includes inclusive `startChar` and exclusive `endChar` positions counted in **Unicode code points (scalar values)**—not UTF-8 bytes and not UTF-16 code units. Accented characters (`ü`, `€`), CJK characters, and emojis (`🚀`) each count as **1** (matching Python `text[startChar:endChar]`; in JavaScript, use `[...text].slice(startChar, endChar).join("")` when text contains emojis).
- **Verbatim source verification:** Drops any value not found verbatim in the source text and saves dropped spans separately to `UNGROUNDED_EXTRACTIONS.json` for review. *(Note: verbatim filtering ensures every value actually exists in the source, but an LLM can still misclassify an existing span—such as tagging a date as an amount—so clear prompts and few-shot examples remain important.)*
- **Interactive HTML highlight report:** Open `OUTPUT_HIGHLIGHT.html` in **the run's Storage tab → Key-value store** to filter by entity class and click any highlighted span inside the original text.

***

### Use Cases

- **Contract Data Extraction & Legal Review:** Pull signatories, agreement IDs, effective dates, and monetary amounts with exact character offsets for audit trails.
- **Source Citations for RAG & AI Pipelines:** Attach verifiable `startChar`..`endChar` spans to extracted metadata so downstream apps can highlight exact supporting evidence.
- **Named Entity Recognition (NER) & Structured Data Extraction:** Extract custom entity schemas from articles, support tickets, or financial text using few-shot LLM prompting.
- **Web Page Entity Extraction:** Pass HTTP/HTTPS URLs directly—visible text is extracted from the HTML and grounded back to the cleaned page text.
- **Deterministic Compliance & QA:** Separate unverified AI guesses from verbatim source spans before loading records into your CRM or database.

***

### Supported Input Formats

- **Plain UTF-8 text:** Paste directly into `sourceText` (or pass `text` / `base64Text` via API). `base64Text` decodes **UTF-8 plain text only**—binary file formats such as **PDF or DOCX are not parsed directly** and should be converted to plain text first.
- **Web pages (HTTP/HTTPS URLs):** Add one or more URLs in `sourceUrls`. The Actor fetches each page over HTTP and extracts visible text from the HTML (stripping scripts, styles, and comments).

***

### Input

Configure the Actor using the form in the **Input** tab or pass JSON via the Apify API.

#### Main Options

- **Text to Extract From (`sourceText`) & Web Page URLs (`sourceUrls`)**: Paste plain UTF-8 text and/or add HTTP/HTTPS URLs. *(API callers can also pass a batch `sources` array with `id` plus `text`, `url`, or `base64Text`.)*
- **Extraction Mode / LLM Provider (`llmProvider`)**:
  - `rule_based` *(default)* — **Zero-LLM mode (no API key needed).** Built-in rules cover `person`, `agreement_id`, `date`, `amount`, `email`, and `url`. **Limitations:** built-in rules do not extract locations/cities (e.g., `München` in the sample below), and regex-based `person` matching can miss uncommon or non-standard name formats. Add `customRules` or switch to an LLM provider for broader NER.
  - `gemini` — Google Gemini models (e.g., `gemini-3.5-flash`).
  - `openai` — OpenAI models (e.g., `gpt-4o-mini`).
  - `openai_compatible` — Any OpenAI-compatible API endpoint via `apiBaseUrl`.
- **LLM API Key (`apiKey`)**: Secret input field—stored encrypted by Apify and never exposed in logs. Not required in `rule_based` mode.
- **Extraction Prompt (`promptDescription`) & Few-Shot Example (`exampleText`, `exampleExtractions`)**: Instructions and verbatim class-to-text pairs when using an LLM provider.
- **Custom Regex Rules (`customRules`, `rulesCaseInsensitive`)**: Optional entity-class and Unicode regex pattern pairs for `rule_based` mode.
- **Grounding & Output (`generateHtmlReport`, `filterUngrounded`, `requireExactMatch`, `caseInsensitiveFallback`)**: Control verbatim verification, exact vs. case-insensitive fallback matching, and `OUTPUT_HIGHLIGHT.html` generation.
- **Chunking & Performance (`maxCharBuffer`, `overlapChars`, `extractionPasses`, `maxConcurrency`)**: Tune long-text splitting, multi-pass recall, and worker concurrency.

#### Example Input: Zero-LLM Mode (No API Key Required)

```json
{
  "sourceText": "Dr. Clara Müller signed Service Agreement SA-2026-04 on 15 March 2026 in München for EUR 48,500.",
  "llmProvider": "rule_based",
  "generateHtmlReport": true
}
```

#### Example Input: AI Few-Shot Mode (Gemini / OpenAI)

```json
{
  "sourceText": "Dr. Clara Müller signed Service Agreement SA-2026-04 on 15 March 2026 in München for €48.500.",
  "promptDescription": "Extract person names, agreement IDs, dates, cities, and monetary amounts verbatim from the text.",
  "exampleText": "Max Weber executed Contract C-101 on 2 January 2025 in Berlin for €12.000.",
  "exampleExtractions": [
    { "key": "person", "value": "Max Weber" },
    { "key": "agreement_id", "value": "Contract C-101" },
    { "key": "date", "value": "2 January 2025" },
    { "key": "city", "value": "Berlin" },
    { "key": "amount", "value": "€12.000" }
  ],
  "llmProvider": "gemini",
  "modelId": "gemini-3.5-flash",
  "apiKey": "YOUR_API_KEY"
}
```

***

### Output

All verified extractions are saved to the run's **Dataset** (downloadable as JSON, CSV, Excel, XML, or HTML, or via the Apify API):

```json
[
  {
    "sourceId": "text-1",
    "sourceUrl": null,
    "chunkIndex": 0,
    "extractionClass": "person",
    "extractionText": "Dr. Clara Müller",
    "matchedSnippet": "Dr. Clara Müller",
    "attributes": { "source": "builtin_rule" },
    "charInterval": { "startChar": 0, "endChar": 16 },
    "groundingStatus": "exact",
    "extractionIndex": 0,
    "passNumber": 1
  },
  {
    "sourceId": "text-1",
    "sourceUrl": null,
    "chunkIndex": 0,
    "extractionClass": "amount",
    "extractionText": "EUR 48,500",
    "matchedSnippet": "EUR 48,500",
    "attributes": { "source": "builtin_rule" },
    "charInterval": { "startChar": 85, "endChar": 95 },
    "groundingStatus": "exact",
    "extractionIndex": 3,
    "passNumber": 1
  }
]
```

Additional artifacts saved in **the run's Storage tab → Key-value store**:

- **`OUTPUT_HIGHLIGHT.html`** — Self-contained interactive HTML report highlighting every grounded span inside the source text with an attribute inspector and class filters.
- **`UNGROUNDED_EXTRACTIONS.json`** — Created when `filterUngrounded` is enabled and any extracted spans could not be matched verbatim against the source text.

***

### Pricing

This Actor uses **Pay-Per-Event (PPE)** billing (platform usage costs are included) and respects your **max cost per run** setting, so runs stop cleanly before exceeding your budget.

| Event name | Trigger | Price (USD) |
| --- | --- | --- |
| `apify-actor-start` | Charged when the run starts, per GB of memory (minimum 1 GB) | `$0.00005` |
| `apify-default-dataset-item` | Charged per grounded extraction pushed to the Dataset | `$0.30 / 1,000` (`$0.0003` / item) |

**Example:** Extracting 1,000 grounded entities costs about **$0.30** *(tested on 1,000 entities in a single 1-second run at 256 MB memory, all exact matches)*.

- **Zero-LLM Mode (`rule_based`):** Only the Actor events above apply—no external AI API costs.
- **AI Mode (`gemini`, `openai`, `openai_compatible`):** Bring your own `apiKey` (stored encrypted) and pay your model provider directly with zero token markup.

***

### FAQ & Support

- **Do I need an LLM API key to try the Actor?**
  No. Leave `llmProvider` set to `rule_based` and click **Start** to run immediately on the prefilled sample text.
- **How are character offsets counted for emojis, accents, and CJK text?**
  `startChar` (inclusive) and `endChar` (exclusive) count **Unicode code points (scalar values)**. One emoji (`🚀`), umlaut (`ü`), or CJK character counts as `1`, matching Python string indexing. In JavaScript (UTF-16), slice with `[...text].slice(startChar, endChar).join("")`.
- **Does `base64Text` support PDF or DOCX files?**
  No—`base64Text` decodes UTF-8 plain text only. Extract text from PDF/DOCX files first before passing it in.
- **How does it handle repeated words or long texts?**
  Long inputs are split into overlapping chunks, and repeated terms are matched to the exact occurrence inside their originating chunk in reading order.
- **Questions or feature requests?**
  Open a ticket on the Actor's **Issues** tab in Apify Console and include a sample input or run ID.

# Actor input Schema

## `sourceText` (type: `string`):

Paste plain text or document content to extract structured entities from. You can also provide web page URLs below.

## `sourceUrls` (type: `array`):

Optional list of HTTP/HTTPS URLs to fetch and extract from. Clean text is automatically extracted from each page.

## `llmProvider` (type: `string`):

Use Zero-LLM mode with no API key required, or select an LLM provider for semantic few-shot extraction.

## `promptDescription` (type: `string`):

Instructions describing target entity classes, clauses, or facts to extract verbatim when using an LLM provider.

## `modelId` (type: `string`):

Model identifier for the chosen LLM provider (e.g. gemini-3.5-flash, gemini-2.5-flash, gpt-4o-mini).

## `apiKey` (type: `string`):

API key for Gemini, OpenAI, or OpenAI-compatible endpoints (not needed in Zero-LLM mode). Also supports GEMINI_API_KEY / OPENAI_API_KEY / LLM_API_KEY env vars.

## `apiBaseUrl` (type: `string`):

Required only when using an OpenAI-Compatible Endpoint (e.g. https://openrouter.ai/api/v1).

## `temperature` (type: `string`):

Sampling temperature (0.0 recommended for deterministic grounded extraction).

## `exampleText` (type: `string`):

Sample text used as a few-shot example for the LLM. Leave empty to skip few-shot examples.

## `exampleExtractions` (type: `array`):

Pairs of entity class and exact verbatim text that appears in Example Source Text.

## `customRules` (type: `array`):

Define custom entity classes and Unicode regex patterns for Zero-LLM mode.

## `rulesCaseInsensitive` (type: `boolean`):

When enabled, custom regex rules match regardless of letter casing.

## `generateHtmlReport` (type: `boolean`):

Writes a self-contained interactive HTML highlight report to OUTPUT_HIGHLIGHT.html in the default Key-Value Store.

## `filterUngrounded` (type: `boolean`):

Automatically filter out extractions that cannot be matched back to the source text (saved separately for review).

## `requireExactMatch` (type: `boolean`):

Only accept exact verbatim matches without whitespace or case-insensitive fallback.

## `caseInsensitiveFallback` (type: `boolean`):

Allow case-insensitive matching when an exact-case match is not found (ignored if Require Exact Character Match is enabled).

## `maxCharBuffer` (type: `integer`):

Maximum number of Unicode characters per chunk for long documents.

## `overlapChars` (type: `integer`):

Number of overlapping characters between consecutive chunks to avoid splitting entities at boundaries.

## `extractionPasses` (type: `integer`):

Number of extraction passes per chunk for higher recall on complex documents (1 to 5).

## `maxConcurrency` (type: `integer`):

Maximum number of concurrent chunk/source workers (automatically bounded by container memory).

## Actor input object example

```json
{
  "sourceText": "Dr. Clara Müller signed Service Agreement SA-2026-04 on 15 March 2026 in München for EUR 48,500.",
  "llmProvider": "rule_based",
  "promptDescription": "Extract person names, agreement identifiers, dates, locations, and monetary amounts using exact verbatim text from the document.",
  "modelId": "gemini-3.5-flash",
  "temperature": "0.0",
  "exampleText": "Max Weber executed Contract C-101 on 2 January 2025 in Berlin for USD 12,000.",
  "exampleExtractions": [
    {
      "key": "person",
      "value": "Max Weber"
    },
    {
      "key": "agreement_id",
      "value": "Contract C-101"
    },
    {
      "key": "date",
      "value": "2 January 2025"
    },
    {
      "key": "location",
      "value": "Berlin"
    },
    {
      "key": "amount",
      "value": "USD 12,000"
    }
  ],
  "rulesCaseInsensitive": false,
  "generateHtmlReport": true,
  "filterUngrounded": true,
  "requireExactMatch": false,
  "caseInsensitiveFallback": true,
  "maxCharBuffer": 4000,
  "overlapChars": 200,
  "extractionPasses": 1,
  "maxConcurrency": 4
}
```

# Actor output Schema

## `overview` (type: `string`):

All grounded extractions with exact Unicode character offsets (startChar, endChar), grounding status, and attributes.

## `highlightReport` (type: `string`):

Self-contained visual report highlighting every grounded span directly inside the original source text.

## `ungroundedAudit` (type: `string`):

Audit log of any unverified spans filtered out when filterUngrounded is enabled.

# API

You can run this Actor programmatically using our API. Below are code examples in JavaScript, Python, and CLI, as well as the OpenAPI specification and MCP server setup.

## JavaScript example

```javascript
import { ApifyClient } from 'apify-client';

// Initialize the ApifyClient with your Apify API token
// Replace the '<YOUR_API_TOKEN>' with your token
const client = new ApifyClient({
    token: '<YOUR_API_TOKEN>',
});

// Prepare Actor input
const input = {
    "sourceText": "Dr. Clara Müller signed Service Agreement SA-2026-04 on 15 March 2026 in München for EUR 48,500.",
    "promptDescription": "Extract person names, agreement identifiers, dates, locations, and monetary amounts using exact verbatim text from the document.",
    "exampleText": "Max Weber executed Contract C-101 on 2 January 2025 in Berlin for USD 12,000.",
    "exampleExtractions": [
        {
            "key": "person",
            "value": "Max Weber"
        },
        {
            "key": "agreement_id",
            "value": "Contract C-101"
        },
        {
            "key": "date",
            "value": "2 January 2025"
        },
        {
            "key": "location",
            "value": "Berlin"
        },
        {
            "key": "amount",
            "value": "USD 12,000"
        }
    ]
};

// Run the Actor and wait for it to finish
const run = await client.actor("solutionssmart/langextract-grounded-extractor").call(input);

// Fetch and print Actor results from the run's dataset (if any)
console.log('Results from dataset');
console.log(`💾 Check your data here: https://console.apify.com/storage/datasets/${run.defaultDatasetId}`);
const { items } = await client.dataset(run.defaultDatasetId).listItems();
items.forEach((item) => {
    console.dir(item);
});

// 📚 Want to learn more 📖? Go to → https://docs.apify.com/api/client/js/docs

```

## Python example

```python
from apify_client import ApifyClient

# Initialize the ApifyClient with your Apify API token
# Replace '<YOUR_API_TOKEN>' with your token.
client = ApifyClient("<YOUR_API_TOKEN>")

# Prepare the Actor input
run_input = {
    "sourceText": "Dr. Clara Müller signed Service Agreement SA-2026-04 on 15 March 2026 in München for EUR 48,500.",
    "promptDescription": "Extract person names, agreement identifiers, dates, locations, and monetary amounts using exact verbatim text from the document.",
    "exampleText": "Max Weber executed Contract C-101 on 2 January 2025 in Berlin for USD 12,000.",
    "exampleExtractions": [
        {
            "key": "person",
            "value": "Max Weber",
        },
        {
            "key": "agreement_id",
            "value": "Contract C-101",
        },
        {
            "key": "date",
            "value": "2 January 2025",
        },
        {
            "key": "location",
            "value": "Berlin",
        },
        {
            "key": "amount",
            "value": "USD 12,000",
        },
    ],
}

# Run the Actor and wait for it to finish
run = client.actor("solutionssmart/langextract-grounded-extractor").call(run_input=run_input)

# Fetch and print Actor results from the run's dataset (if there are any)
print(f"💾 Check your data here: https://console.apify.com/storage/datasets/{run.default_dataset_id}")
for item in client.dataset(run.default_dataset_id).iterate_items():
    print(item)

# 📚 Want to learn more 📖? Go to → https://docs.apify.com/api/client/python/docs/quick-start

```

## CLI example

```bash
echo '{
  "sourceText": "Dr. Clara Müller signed Service Agreement SA-2026-04 on 15 March 2026 in München for EUR 48,500.",
  "promptDescription": "Extract person names, agreement identifiers, dates, locations, and monetary amounts using exact verbatim text from the document.",
  "exampleText": "Max Weber executed Contract C-101 on 2 January 2025 in Berlin for USD 12,000.",
  "exampleExtractions": [
    {
      "key": "person",
      "value": "Max Weber"
    },
    {
      "key": "agreement_id",
      "value": "Contract C-101"
    },
    {
      "key": "date",
      "value": "2 January 2025"
    },
    {
      "key": "location",
      "value": "Berlin"
    },
    {
      "key": "amount",
      "value": "USD 12,000"
    }
  ]
}' |
apify call solutionssmart/langextract-grounded-extractor --silent --output-dataset

```

## MCP server setup

```json
{
    "mcpServers": {
        "apify": {
            "type": "http",
            "url": "https://mcp.apify.com/?tools=fetch-actor-details,solutionssmart/langextract-grounded-extractor"
        }
    }
}
```

The hosted server signs you in with OAuth on first connect, so no API token belongs in this config. Clients without OAuth support can send an `Authorization: Bearer <APIFY_API_TOKEN>` header instead, using a token from API & Integrations in Apify Console (https://console.apify.com/settings/integrations).

## OpenAPI specification

Download the OpenAPI definition: https://api.apify.com/v2/actors/b55ihjrkPB4ZcK43e/builds/hMKtIIxhfQRB72gp6/openapi.json
