# tiktoken

> Count, tokenize, truncate and chunk text using exact OpenAI BPE token counts

This page includes setup, release pins, credentials, hosting and verification evidence. [JSON alternative](https://query.farm/products/orchard/api/v1/connectors/tiktoken.json) contains the same setup facts for structured readers; choose one format.

## Runtime and release

Use DuckDB or Haybarn **2.0.1** with **VGI protocol 3.4**.
Catalog alias: `tiktoken`. Release: [v0.5.0](https://github.com/Query-farm/vgi-tiktoken/releases/tag/v0.5.0). Metadata generated: 2026-12-01T18:22:16+00:00.

## Choose where it runs

- On your machine: use an installation method below. No Query Farm account is required for local execution.
- Self-host: follow [the connector deployment instructions](https://github.com/Query-farm/vgi-tiktoken) and [connection guide](https://query.farm/vgi/connect-to-a-worker/). Use your real endpoint and its authentication settings.
- Query Farm hosted: [create a deployment](https://auth.queryfarm.cloud/console/new?worker=tiktoken). Hosting has a $10 monthly minimum per organization; usage and license fees may apply. Copy the deployment-specific ATTACH from the console.

## Service credentials and prerequisites

No service credentials are declared by this connector. Individual datasets, input files or deployments may have their own prerequisites.

Secret parameter required flags describe the upstream declaration; they do not override the service-level mode above. Keep secrets in environment variables or the deployment secret store. SQL values in angle brackets are placeholders, not automatic environment lookups. Native DuckDB and Haybarn 2.0.1 do not provide a SQL getenv() function, even when worker-supplied snippets mention it. Read environment variables in your application and pass credential values through client parameter bindings (for example, Python con.execute("CREATE SECRET stripe (TYPE stripe, api_key ?)", [os.environ["STRIPE_API_KEY"]]) after attaching the connector. Omit unused optional parameters and keep real values out of saved SQL and logs.

## Install the extension

In stock DuckDB:

```sql
SET allow_extension_repositories = 'allowed';

CREATE EXTENSION REPOSITORY IF NOT EXISTS query_farm
    WITH PREFIX 'https://duckdb-extensions.query.farm';

INSTALL vgi FROM query_farm;
LOAD vgi FROM query_farm;
```

In Haybarn:

```sql
INSTALL vgi FROM community;
LOAD vgi;
```

## Attach the connector

The local recipes below pin the catalog release for repeatability. A public demo endpoint follows its deployed release.

### From GitHub

Attach the release directly

Uses the verified release each time you attach the connector.

```sql
ATTACH 'tiktoken' AS tiktoken (
  TYPE vgi,
  LOCATION 'github-auto://Query-farm/vgi-tiktoken@v0.5.0'
);
```

### Docker

Attach the signed image

Needs Docker, Podman or another OCI runtime. The extension runs the container and talks to it over stdio.

```sql
ATTACH 'tiktoken' AS tiktoken (
  TYPE vgi,
  LOCATION 'oci://ghcr.io/query-farm/vgi-tiktoken:0.5.0'
);
```

## See what you can query

Service credentials required for this example: not declared by this example; check the connector requirements above.

```sql
SELECT c.chunk_no, c.chunk, tiktoken.main.count_tokens(c.chunk) AS tokens FROM unnest(tiktoken.main.chunk_by_tokens('Retrieval augmented generation splits long documents into token-bounded chunks, embeds each chunk, and retrieves the most relevant ones at query time.', 8)) WITH ORDINALITY AS c(chunk, chunk_no) ORDER BY c.chunk_no;
```

- [tiktoken.main.count_tokens — scalar_function](https://query.farm/products/orchard/connectors/tiktoken/objects/scalar_function.bWFpbg.Y291bnRfdG9rZW5z.md): exact declaration for this example.
- [tiktoken.main.chunk_by_tokens — scalar_function](https://query.farm/products/orchard/connectors/tiktoken/objects/scalar_function.bWFpbg.Y2h1bmtfYnlfdG9rZW5z.md): exact declaration for this example.

Execution evidence: **captured_result**.

```json
{
  "status": "captured_result",
  "capturedAt": "2026-12-01T06:21:29+00:00",
  "engineVersion": "2.0.1",
  "protocolVersion": "3.4.0",
  "releaseTag": "v0.5.0",
  "sample": {
    "columns": [
      "chunk_no",
      "chunk",
      "tokens"
    ],
    "types": [
      "BIGINT",
      "VARCHAR",
      "INTEGER"
    ],
    "rows": [
      [
        1,
        "Retrieval augmented generation splits long documents",
        8
      ],
      [
        2,
        " into token-bounded chunks, embeds",
        8
      ],
      [
        3,
        " each chunk, and retrieves the most relevant",
        8
      ],
      [
        4,
        " ones at query time.",
        5
      ]
    ],
    "more": false
  }
}
```

## Connector reference

### tiktoken — Count LLM Tokens & Chunk Text in SQL

![OpenAI logo](https://upload.wikimedia.org/wikipedia/commons/thumb/a/a0/OpenAI_wordmark_2017.svg/330px-OpenAI_wordmark_2017.svg.png)

**Count LLM tokens, tokenize text, and split documents into token-bounded chunks directly in DuckDB SQL** — exact OpenAI-compatible BPE token counting and token-aware text chunking for prompt budgeting, API cost estimation, and retrieval-augmented generation (RAG), with no Python and no network calls.

This extension is for anyone who needs to know exactly how many tokens a piece of text will consume before sending it to a large language model. Instead of approximating with character or word counts, `tiktoken` computes the *real* token count using the same byte-pair-encoding (BPE) vocabularies that OpenAI's GPT models use. That makes it ideal for staying within context-window limits, estimating the cost of an API call, deduplicating or filtering rows by token length, and preparing large corpora for embedding pipelines — all from ordinary SQL over your existing tables.

Under the hood the worker wraps the Rust crate [`tiktoken-rs`](https://github.com/zurawiki/tiktoken-rs) ([docs](https://docs.rs/tiktoken-rs)), a fast, pure-Rust port of OpenAI's [`tiktoken`](https://github.com/openai/tiktoken) tokenizer. The BPE encodings are **bundled into the binary** and built lazily on first use, so token counting works fully offline with no model download. The supported encodings cover every modern OpenAI model family: `cl100k_base` (GPT-4 / GPT-3.5), `o200k_base` (GPT-4o), `p50k_base`, `r50k_base`, and `o200k_harmony`. Results are exact and deterministic, so the same text always yields the same count and the same token-id sequence.

The worker exposes a small, composable set of scalar SQL functions in the `tiktoken.main` schema, covering the everyday token-oriented tasks: getting an exact token count for a string, returning the raw BPE token ids as an `INTEGER[]`, mapping a model name (e.g. `'gpt-4o'`) to its encoding name, clipping text to a fixed token budget, and splitting text into token-bounded, optionally overlapping windows that make ideal RAG chunks before embedding. Each text function offers a default-encoding form (`cl100k_base`) and a model-aware form that accepts a model or encoding name; unknown model names return `NULL`, and `NULL` input flows through to `NULL`. Built and maintained by [Query.Farm](https://query.farm).

## Find the exact SQL object

[Browse 5 object declarations](https://query.farm/products/orchard/api/v1/connectors/tiktoken/objects.json) or [search within this connector](https://query.farm/products/orchard/api/v1/search.json?kind=object&connector=tiktoken&q=tiktoken).

Follow one format of each needed object for complete argument types, defaults, named flags, return columns and examples. Existing links above can replace another search. For questions about hosting, credentials or supported operations, stop once the documentation answers the question; SQL and unrelated object lookups are unnecessary.

## Verification and interpretation

- Missing, null, or undeclared metadata means unknown; do not invent defaults, credential scope, platform support or endpoint URLs.
- Search is keyword retrieval, not proof of a capability. Read the exact object declaration before generating SQL.
- A table and a table function can have the same name. Preserve parentheses and use the matching overload and schema.
- Service credentials, external data availability and deployment authentication are separate requirements.
- Catalog verification records the harvest environment. It is not proof that every query or current live API call succeeds. Only an example with captured_result has a saved result for that exact SQL.

```json
{
  "generatedAt": "2026-12-01T18:22:16+00:00",
  "repository": "https://github.com/Query-farm/vgi-tiktoken",
  "harvest": {
    "status": "ok",
    "method": "github-auto",
    "error": null,
    "vgi_version": "9773130dde"
  },
  "catalogVerification": {
    "verified": true,
    "status": "passed",
    "total": 8,
    "passed": 8,
    "failed": 0,
    "needs_credentials": 0,
    "location": "github-auto://Query-farm/vgi-tiktoken@v0.5.0",
    "transport": "github-auto",
    "environment": {
      "vgi_extension_version": "9773130dde",
      "haybarn_version": "2.0.1rc3",
      "engine_version": "v2.0.1",
      "python": "3.12.4",
      "platform": "darwin_arm64",
      "protocol_version": "3.4.0"
    },
    "checked_at": "2026-12-01T06:19:57+00:00"
  },
  "interpretation": "Catalog verification records the harvest environment. It is not proof that every query or current live API call succeeds. Only an example with captured_result has a saved result for that exact SQL."
}
```
