# AI Context Distiller: Cut Tokens from HTML, JSON & Logs (`geeky_goth_gamer/ai-context-distiller`) Actor

Prune HTML, JSON, logs or prose and return query-focused, token-budgeted text for AI agents, with a safe telegraphic compression mode that never drops negations, numbers or code. Standby HTTP for sub-second warm calls. $0.0025 per payload or $0.005 per URL.

- **URL**: https://apify.com/geeky_goth_gamer/ai-context-distiller.md
- **Developed by:** [Chris Day](https://apify.com/geeky_goth_gamer) (community)
- **Categories:** AI, Developer tools, Automation
- **Features:** Limited permissions, Single-tenant, Server interface
- **Stats:** 1 total users, 0 monthly users, 0.0% runs succeeded, 0 bookmarks
- **User rating**: No ratings yet

## Pricing

from $2.50 / 1,000 distill payloads

This Actor is paid per event and usage. You are charged both the fixed price for specific events and for Apify platform usage.

Learn more: https://docs.apify.com/actors/running/actors-in-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

## AI Context Distiller for AI Agents

Send this Actor a **web URL**, **raw HTML**, a **JSON API payload**, **server logs**, or long **prose / Markdown / CSV**. It prunes boilerplate, ranks the remainder against an optional question, and returns compact text that fits a **token budget** — plus a section **outline** so the agent can pull only the slices it still needs.

It does **not** call a language model. Distillation is deterministic (HTML cleanup, JSON pruning, log collapsing, BM25 ranking, and an optional safe telegraphic compression mode). Token counts use OpenAI `tiktoken` `cl100k_base`.

### When an AI agent should use this

Use `geeky_goth_gamer/ai-context-distiller` when:

- A web page, API response, log dump or document is too large to paste into the model, and you want a much smaller, query-focused extract.
- You want to cut LLM input tokens before the model sees the payload (the call is priced so typical token savings exceed the fee).
- You need a warm, low-latency endpoint (`POST /distill`, `POST /slice`, `GET /health`) in Apify Standby / Server mode, with an outline you can slice on follow-up calls.

Don't use it for:

- Fetching a citation-checked evidence pack (use a dedicated evidence-pack Actor).
- Rendering JavaScript-only pages to a screenshot or PDF.
- Tasks that need a language model to paraphrase or summarise — this tool only prunes, ranks and optionally compresses; it does not rewrite facts.

**Example input:**

```json
{
  "url": "https://example.com/",
  "query": "What is this domain used for?",
  "maxTokens": 800,
  "compression": "light"
}
```

**Output:** One dataset item (or a JSON HTTP body in Standby mode): `distilledText`, `outline` (section ids, headings, token counts), `originalTokens`, `distilledTokens`, `tokensSaved`, `reductionPct`, `tokenizer`, `guardsPreserved`, and optional `distilledJson`.

**Cost:** $0.0025 per inline payload (`text` / `html` / `json` / logs) or $0.005 per URL fetch + distill. Failed fetches and invalid input are not billed. Apify also charges the standard $0.00005 Actor-start fee on ordinary runs.

**Call it from an agent:**

- Apify MCP server: add `https://mcp.apify.com/?tools=geeky_goth_gamer/ai-context-distiller` to your MCP client; the tool is `geeky_goth_gamer--ai-context-distiller`. Or use `call-actor` with `"actor": "geeky_goth_gamer/ai-context-distiller"`.
- Standby HTTP (once the Server interface is enabled): `POST https://geeky-goth-gamer--ai-context-distiller.apify.actor/distill` with `Authorization: Bearer YOUR_TOKEN` and the input JSON. Follow up with `POST /slice` and `{ "cacheId": "...", "sectionIds": ["s2", "s5"] }` while the process is warm. `GET /health` is a liveness check.
- Python: `ApifyClient(token).actor("geeky_goth_gamer/ai-context-distiller").call(run_input=...)`, then read `client.dataset(run["defaultDatasetId"]).list_items().items`.
- HTTP run: `POST https://api.apify.com/v2/acts/geeky_goth_gamer~ai-context-distiller/run-sync-get-dataset-items?token=YOUR_TOKEN` with the input JSON as the body.

### Why this exists

Language-model calls are billed by tokens. Agents routinely paste whole pages, bloated JSON and repetitive logs into the context window, paying for scripts, navigation, null fields and repeated lines. This Actor is meant to sit **in front of the model**: one cheap tool call returns the high-signal remainder, a token-saving report, and an index of sections the agent can retrieve later.

A second, optional **telegraphic** mode drops predictable English filler (articles, copulas, verbose transitions) so the receiving model reconstructs the grammar by prediction. It keeps real English words — it does not invent a shorthand language — and it will not drop or alter negations, logical qualifiers, numbers, dates, URLs, emails, identifiers, headings, quotations, Markdown tables or code.

### Input

Pass **exactly one** of `url`, `text`, `html` or `json`.

| Field | Default | Notes |
|---|---|---|
| `url` | (optional) | One public `http(s)` page. Private, loopback and metadata addresses are rejected. |
| `text` / `html` / `json` | (optional) | Inline payload, max 2,000,000 characters. `json` may be an object or a JSON string. |
| `contentType` | `auto` | `html`, `json`, `logs`, `markdown`, `csv`, `text`, or `auto`. |
| `query` | (empty) | Rank sections against this question. Phrases in `"double quotes"` get a bonus. |
| `focusTerms` | (empty) | Extra terms to boost. |
| `maxTokens` | 4000 | Cap on `distilledText` in `cl100k_base` tokens. `0` means no cap. |
| `keepFields` | (empty) | JSON dot-paths to keep, e.g. `items.*.price`. |
| `sectionIds` | (empty) | Return only these outline ids (`s1`, `s2`, …). |
| `compression` | `none` | `none`, `light`, or `telegraphic`. |
| `includeOutline` | true | Section ids, headings and token counts. |
| `maxFileSizeMb` | 5 | URL download cap. Oversize fetches are not billed. |
| `timeoutSeconds` | 30 | URL timeout. |

### Output

One dataset item (same shape as the Standby JSON body):

- `distilledText`: the pruned, optionally ranked and compressed text
- `distilledJson`: the pruned JSON object, when the source is JSON and was not sliced or compressed into prose
- `outline[]`: `id`, `heading`, `tokenCount`, `score`
- `originalTokens`, `distilledTokens`, `tokensSaved`, `reductionPct`
- `tokenizer`: `tiktoken:cl100k_base`
- `guardsPreserved`: `{ ok, checked, missing, categories }` — whether protected facts in the selected text survived compression
- `cacheId`: present in Standby mode so `/slice` can pull sections without resending the payload (the cache lives only while that process is warm)
- `billed`, `eventCharged` (`distill-payload` or `distill-url`)

### Standby / Server mode

When the Actor is started through Apify's server interface (`APIFY_META_ORIGIN=STANDBY`), it listens on `ACTOR_WEB_SERVER_PORT` and handles:

- `GET /health` — liveness
- `POST /distill` — same input as a normal run, JSON response
- `POST /slice` — `{ "cacheId": "...", "sectionIds": ["s2"] }` or the content again plus `sectionIds`
- Any request carrying the `x-apify-container-server-readiness-probe` header is answered immediately with HTTP 200 and body `ok`, including probes to `/`

Standard input-interface runs (Console, `call-actor`, run-sync) still work: one input, one dataset item, then the run exits.

### Pricing

| Event | Price | When it is charged |
|---|---|---|
| `distill-payload` (primary) | **US$0.0025** | One successful inline distill (`text`, `html`, `json` or logs). Also charged for a successful `/slice`. |
| `distill-url` | **US$0.005** | One successful URL fetch + distill. |
| `apify-actor-start` | US$0.00005 (Apify default) | Once when a standard run starts. Covers the first 5 seconds of compute. |

Failed fetches, rejected URLs and invalid input are free. Your maximum cost per run is respected: if it is below the event price, nothing is processed.

A typical page is tens of thousands of tokens; dropping even a few thousand `cl100k_base` input tokens usually saves more than US$0.001–0.002 at current model prices.

### Safety

URL fetches are SSRF-safe: only `http`/`https` on standard ports, every redirect hop is re-validated, and private, loopback, link-local, CGNAT and cloud-metadata addresses are blocked. Downloads are size- and time-capped. The helper connects to already-checked IPs, IPv4 first (Apify containers often have no IPv6 route).

### Limitations

- JavaScript-rendered pages will have little or no text; render them first if you need the visible DOM.
- Telegraphic mode is for model input, not for publishing. It is tested to preserve protected facts, but you should still keep `guardsPreserved.ok` in your loop.
- Standby `cacheId` values are per-process and disappear when the run idles out. Resubmit the payload (or store the outline yourself) if the cache is gone.

# Actor input Schema

## `url` (type: `string`):

Optional. One public http(s) page to fetch and distill. Do not also pass text, html or json. Only standard web ports (80, 443, 8080, 8443) are allowed. Private, loopback and metadata addresses are rejected.

## `text` (type: `string`):

Optional. Raw prose, Markdown, CSV or log text to distill (max 2,000,000 characters). Pass this instead of url, html or json. contentType can force the format; otherwise it is auto-detected.

## `html` (type: `string`):

Optional. Raw HTML to prune into compact Markdown (scripts, nav, footers, cookie banners and hidden nodes are stripped). Pass this instead of url, text or json.

## `json` (type: `object`):

Optional. An API payload to prune (null/empty fields dropped, repeated objects collapsed to a Markdown table, optional keepFields). Pass this instead of url, text or html. A JSON string is also accepted by the HTTP API.

## `contentType` (type: `string`):

How to parse the source. "auto" (default) sniffs HTML, JSON, CSV, logs or prose. Set this when auto-detection would be wrong.

## `query` (type: `string`):

Optional. Rank sections by lexical relevance to this question (BM25 plus exact phrase, number and entity boosts). Phrases in "double quotes" get an exact-match bonus. Combined with maxTokens to keep only the highest-signal slices.

## `focusTerms` (type: `array`):

Optional. Extra terms or entities that should be boosted when ranking sections (max 50).

## `maxTokens` (type: `integer`):

Maximum cl100k_base tokens in distilledText. Highest-scoring sections are kept until this budget is filled. 0 means no cap (return everything after pruning and compression). Default 4000.

## `keepFields` (type: `array`):

Optional. Dot-paths to extract from a JSON payload, e.g. \["items.*.name", "items.*.price", "meta.requestId"]. Use \* for every array (or object) item. Other fields are dropped.

## `sectionIds` (type: `array`):

Optional. After a first call (which returns an outline of section ids, headings and token counts), pass sectionIds to pull only those sections. In Standby mode you can send cacheId plus sectionIds to POST /slice without resending the payload.

## `compression` (type: `string`):

"none" (default) keeps the pruned text as-is. "light" drops verbose filler phrases and hedges. "telegraphic" also drops predictable articles and copulas so a language model can fill the grammar. Never drops or alters negations, logical qualifiers, numbers, dates, URLs, emails, identifiers, headings, quotes, tables or code.

## `includeOutline` (type: `boolean`):

When on (default), the result includes an outline of section ids, headings and token counts so an agent can inspect the index first and request only the sections it needs.

## `maxFileSizeMb` (type: `integer`):

Larger URL responses are rejected and the call is not billed.

## `timeoutSeconds` (type: `integer`):

Download time limit when url is set.

## Actor input object example

```json
{
  "url": "https://example.com/",
  "contentType": "auto",
  "maxTokens": 4000,
  "compression": "none",
  "includeOutline": true,
  "maxFileSizeMb": 5,
  "timeoutSeconds": 30
}
```

# Actor output Schema

## `results` (type: `string`):

No description

# 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 = {
    "url": "https://example.com/"
};

// Run the Actor and wait for it to finish
const run = await client.actor("geeky_goth_gamer/ai-context-distiller").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 = { "url": "https://example.com/" }

# Run the Actor and wait for it to finish
run = client.actor("geeky_goth_gamer/ai-context-distiller").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 '{
  "url": "https://example.com/"
}' |
apify call geeky_goth_gamer/ai-context-distiller --silent --output-dataset

```

## MCP server setup

```json
{
    "mcpServers": {
        "apify": {
            "type": "http",
            "url": "https://mcp.apify.com/?tools=fetch-actor-details,geeky_goth_gamer/ai-context-distiller"
        }
    }
}
```

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/OPCZzpE37BTeiQRsK/builds/6TpVhlES5qzwf7tl1/openapi.json
