# Token Counter & Text Stats API: Tokens, Language, Readability (`tudorlane/text-toolkit`) Actor

Count LLM tokens (exact OpenAI tiktoken, Claude/Gemini estimates), estimate cost, detect language, readability scores, words, sentences and reading time, and truncate text to a token budget.

- **URL**: https://apify.com/tudorlane/text-toolkit.md
- **Developed by:** [Tudor Lane](https://apify.com/tudorlane) (community)
- **Categories:** Developer tools
- **Security:** Limited permissions
- **Stats:** 2 total users, 1 monthly users, 100.0% runs succeeded, 0 bookmarks
- **User rating**: No ratings yet

## Pricing

$1.00 / 1,000 text analyses

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/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

## Token Counter & Text Stats API: Tokens, Language, Readability

**Use when:** an AI agent or pipeline needs to know, before calling a model, how many tokens a text is (exact for OpenAI, estimated for Claude and Gemini), whether it fits a token budget (and cut it to fit), roughly what it will cost, what language it is in, or how readable it is.

**Try this input**

```json
{"requests": [{"text": "The quick brown fox jumps over the lazy dog. Agents love cheap tools."}, {"text": "Le renard brun rapide saute par-dessus le chien paresseux."}, {"text": "Summarise this long support ticket before sending it to the model, please.", "max_tokens": 5, "truncate": true}]}
```

**Sample output** (real run, 30 Oct 2026, trimmed)

```json
{"words": 13, "sentences": 2, "language": "en", "tokens": {"o200k_base (GPT-4o/4.1/5)": 15, "cl100k_base (GPT-4/3.5)": 15, "claude_estimate": 16, "gemini_estimate": 17},
 "flesch_reading_ease": 96.1, "flesch_kincaid_grade": 1.5, "reading_time_seconds": 3.3, "est_input_cost_usd": {"gpt-4o": 0.000037, "gpt-4o-mini": 0.000002}, "error": null}
{"words": 10, "language": "fr", "tokens": {"o200k_base (GPT-4o/4.1/5)": 14, "cl100k_base (GPT-4/3.5)": 18, "claude_estimate": 20, "gemini_estimate": 14}, "reading_time_seconds": 2.5, "error": null}
{"words": 12, "language": "en", "tokens": {"o200k_base (GPT-4o/4.1/5)": 16}, "fits_max_tokens": false, "truncated_text": "Summarise this long", "error": null}
```

Each item needs `text`, with optional `max_tokens` (adds `fits_max_tokens`, checked against o200k_base) and `truncate: true` (adds `truncated_text`, cut to `max_tokens` o200k tokens). Every row also has `chars`, `chars_no_spaces`, `paragraphs`, `lines`, `language_candidates` (top 3 with probabilities) and `est_input_cost_usd` for gpt-4o, gpt-4o-mini, claude-sonnet (est.) and gemini-flash (est.). Up to 5000 items per run (text up to 2M characters each); no API key needed.

**Pricing:** pay per event, **$0.001 per text analysed**. Rows with errors (e.g. empty `text`) are not charged.

### Limits & failure modes

- Claude and Gemini token counts are estimates (cl100k × 1.1 and characters ÷ 4), not their official tokenizers.
- Cost estimates are input-only, use fixed list prices for a few models, and may be out of date.
- Readability scores (Flesch) are English only; other languages get reading time only.
- Language detection (langdetect, 55 languages) is unreliable on very short text.
- Sentence counting is punctuation-based, so lists and headings without full stops count as one sentence.
- Open-source libraries: tiktoken (MIT), langdetect (Apache 2.0).

Last tested: 30 Oct 2026.

### Use from AI agents (MCP)

- **Apify MCP server:** add `https://mcp.apify.com/?tools=tudorlane/text-toolkit` to Claude, Cursor, ChatGPT, VS Code or any MCP client.
- **REST:** `POST https://api.apify.com/v2/acts/tudorlane~text-toolkit/run-sync-get-dataset-items?token=YOUR_TOKEN` with the input JSON.

# Actor input Schema

## `requests` (type: `array`):

Each item: {"text": "...", "max_tokens": 8000, "truncate": true}. Max 5000. Errors are not charged.

## Actor input object example

```json
{
  "requests": [
    {
      "text": "The quick brown fox jumps over the lazy dog. Agents love cheap tools."
    },
    {
      "text": "Le renard brun rapide saute par-dessus le chien paresseux."
    }
  ]
}
```

# Actor output Schema

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

One item per request.

## `dataset` (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 = {
    "requests": [
        {
            "text": "The quick brown fox jumps over the lazy dog. Agents love cheap tools."
        },
        {
            "text": "Le renard brun rapide saute par-dessus le chien paresseux."
        }
    ]
};

// Run the Actor and wait for it to finish
const run = await client.actor("tudorlane/text-toolkit").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 = { "requests": [
        { "text": "The quick brown fox jumps over the lazy dog. Agents love cheap tools." },
        { "text": "Le renard brun rapide saute par-dessus le chien paresseux." },
    ] }

# Run the Actor and wait for it to finish
run = client.actor("tudorlane/text-toolkit").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 '{
  "requests": [
    {
      "text": "The quick brown fox jumps over the lazy dog. Agents love cheap tools."
    },
    {
      "text": "Le renard brun rapide saute par-dessus le chien paresseux."
    }
  ]
}' |
apify call tudorlane/text-toolkit --silent --output-dataset

```

## MCP server setup

```json
{
    "mcpServers": {
        "apify": {
            "type": "http",
            "url": "https://mcp.apify.com/?tools=fetch-actor-details,tudorlane/text-toolkit"
        }
    }
}
```

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/oB5rDBdrwoNHNHN4x/builds/QwRG3yfRjqQ6cPonO/openapi.json
