tiktoken
Count, tokenize, truncate and chunk text using exact OpenAI BPE token counts
- Connector software
- Free and open source
- Service credentials
- Not needed
- Query Farm hosting
- Available Β· $10/month organization minimum
Use with an agent
Install the Orchard skill in your project to help your agent find connectors, configure them, and verify SQL results.
npx skills add Query-farm/vgi-skills --skill orchard
Copy this request into your coding agent to get started.
Use https://query.farm/products/orchard/connectors/tiktoken/index.md to help me query tiktoken with DuckDB or Haybarn 2.0.1 and VGI protocol 3.4. Ask only for missing details about the result I need or whether I want local execution, self-hosting or Query Farm hosting. Check the connector's actual hosting availability, credentials and input requirements. Read one format of each needed reference and the exact object declarations before writing SQL. Use a released connector, and distinguish a saved example result from anything you actually execute. If you cannot run the query, tell me what remains to verify.
See what you can query
Example output Β· captured
- Connector release
- v0.5.0
- Engine
- 2.0.1
- VGI protocol
- 3.4.0
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;
| chunk_no | chunk | tokens |
|---|---|---|
| 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 |
Quick start
Choose where to run tiktoken, then follow the steps below.
The connector runs alongside DuckDB or Haybarn. No Query Farm account is needed.
1. Install the vgi extension
Run this in your SQL client. On DuckDB, keep FROM query_farm on LOAD in later sessions.
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;
INSTALL vgi FROM community;
LOAD vgi;
2. Attach the connector
Attach the release directly
Downloads the latest release for your platform and caches it locally.
ATTACH 'tiktoken' AS tiktoken (
TYPE vgi,
LOCATION 'github-auto://Query-farm/vgi-tiktoken'
);
Attach the signed image
Needs Docker, Podman or another OCI runtime. The extension runs the container and talks to it over stdio.
ATTACH 'tiktoken' AS tiktoken (
TYPE vgi,
LOCATION 'oci://ghcr.io/query-farm/vgi-tiktoken:0.5.0'
);
3. Run a query
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;
Run the connector on a server you manage. You operate the service and choose who can connect.
1. Deploy the connector on your server
Follow the connectorβs deployment instructions. Use its supported HTTP transport, or launch it remotely over SSH. The connection guide explains both options.
2. Install the vgi extension
Run this in your SQL client. On DuckDB, keep FROM query_farm on LOAD in later sessions.
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;
INSTALL vgi FROM community;
LOAD vgi;
3. Attach the connector
For an HTTP deployment, replace the example URL with your endpoint. Add the authentication options your deployment requires. For SSH, use the SSH connection instructions.
ATTACH 'tiktoken' AS tiktoken
(TYPE vgi, LOCATION 'https://your-connector.example.com');
4. Run a query
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;
Query Farm operates tiktoken for your team. Hosting has a $10 monthly minimum per organization; usage counts toward it. From $2.97 per instance-month ($10 monthly minimum).
1. Create your hosted connector
Open the console, choose your organization and deployment size, and add any service credentials there.
2. Install the vgi extension
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;
INSTALL vgi FROM community;
LOAD vgi;
3. Attach your deployment
Copy the ATTACH statement from your deployment in the console and run it in DuckDB or Haybarn. Use tiktoken as the catalog alias for the query below.
4. Run a query
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;
Technical details
- Verified connector release
- v0.5.0
- Engine
- 2.0.1
- VGI protocol
- 3.4.0
- Verified on
- December 1, 2026
Pin a version for production
When running the connector yourself, keep a specific release until youβre ready to upgrade. Replace the ATTACH statement above with this one and follow the same extension and credential setup.
Attach the release directly
Uses the verified release each time you attach the connector.
ATTACH 'tiktoken' AS tiktoken (
TYPE vgi,
LOCATION 'github-auto://Query-farm/[email protected]'
);
Attach the signed image
Needs Docker, Podman or another OCI runtime. The extension runs the container and talks to it over stdio.
ATTACH 'tiktoken' AS tiktoken (
TYPE vgi,
LOCATION 'oci://ghcr.io/query-farm/vgi-tiktoken:0.5.0'
);
Overview
Exact LLM token counting and token-aware text chunking, powered by tiktoken-rs.
![]()
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 (docs), a fast, pure-Rust port of OpenAI's 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.
Catalog
Everything tiktoken exposes once attached β read straight from the worker's
released build.
main 5 functions
LLM token counting and token-aware text chunking functions.
Schema examples (9)
Count the GPT-4/3.5 (cl100k_base) tokens in a sentence.
SELECT tiktoken.main.count_tokens('The quick brown fox jumps over the lazy dog.');
Count tokens with a specific model's encoding (gpt-4o uses o200k_base).
SELECT tiktoken.main.count_tokens('Summarize this prompt.', 'gpt-4o');
Get the raw BPE token ids of a string under the default encoding.
SELECT tiktoken.main.tokenize('tiktoken is great!');
Look up which tiktoken encoding a model uses.
SELECT tiktoken.main.encoding_for_model('gpt-4o');
5 more examples
Clip text to its first 5 cl100k_base tokens, decoded back to a string.
SELECT tiktoken.main.truncate_to_tokens('The quick brown fox jumps over the lazy dog.', 5);
Split a document into non-overlapping 8-token chunks for embedding.
SELECT tiktoken.main.chunk_by_tokens('A long document to split before embedding.', 8);
Split a document into 8-token chunks (cl100k_base), number them in order with WITH ORDINALITY, and count the tokens in each chunk to confirm it fits the budget (4 chunks of 8, 8, 8 and 5 tokens).
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;
| chunk_no | chunk | tokens |
|---|---|---|
| 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 |
Compare what one multilingual sentence costs under three models, showing each model's encoding: gpt-4o (o200k_base) needs 20 tokens versus 24 for gpt-4 (cl100k_base) and 30 for text-davinci-003 (p50k_base).
SELECT m.model, tiktoken.main.encoding_for_model(m.model) AS encoding,
tiktoken.main.count_tokens('Tokenizers differ: GPT-4o packs multilingual text such as γγγ«γ‘γ―δΈη into fewer tokens.', m.model) AS tokens
FROM (VALUES ('gpt-4o'), ('gpt-4'), ('text-davinci-003')) AS m(model)
ORDER BY tokens, m.model;
Fit a table of prompts to a 10-token budget: report each prompt's original token count, the clipped text, and its token count after truncation (the 3-token prompt passes through unchanged; the 20-token one is cut to 10).
SELECT p.id, tiktoken.main.count_tokens(p.prompt) AS original_tokens,
tiktoken.main.truncate_to_tokens(p.prompt, 10) AS clipped,
tiktoken.main.count_tokens(tiktoken.main.truncate_to_tokens(p.prompt, 10)) AS clipped_tokens
FROM (VALUES (1, 'Short question?'), (2, 'Please summarize the following quarterly report in three bullet points, focusing on revenue growth, margins and guidance.')) AS p(id, prompt)
ORDER BY p.id;
chunk_by_tokens (text VARCHAR, max_tokens INTEGER, overlap INTEGER) +1 overload
Split text into chunks of at most max_tokens tokens (cl100k_base), with no overlap, as VARCHAR[]. Each chunk decodes to valid text. NULL -> NULL
chunk_by_tokens(text VARCHAR, max_tokens INTEGER) β VARCHAR[]chunk_by_tokens(text VARCHAR, max_tokens INTEGER, overlap INTEGER) β VARCHAR[]
Split a document into non-overlapping windows of at most 256 tokens (cl100k_base) for embedding.
SELECT tiktoken.main.chunk_by_tokens('A long document to split before embedding.', 256);
Split a document into 256-token windows that share 32 overlapping tokens, preserving context across chunks for RAG.
SELECT tiktoken.main.chunk_by_tokens('A long RAG document to split into overlapping windows.', 256, 32);
Split a document into 8-token chunks (cl100k_base), number them in order with WITH ORDINALITY, and count the tokens in each chunk to confirm it fits the budget (4 chunks of 8, 8, 8 and 5 tokens).
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;
| chunk_no | chunk | tokens |
|---|---|---|
| 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 |
7 more examples
SELECT tiktoken.main.count_tokens('The quick brown fox jumps over the lazy dog.') AS n;
SELECT tiktoken.main.count_tokens('Summarize this prompt.', 'gpt-4o') AS n;
SELECT tiktoken.main.tokenize('tiktoken is great!') AS ids;
SELECT tiktoken.main.encoding_for_model('gpt-4o') AS encoding;
SELECT tiktoken.main.truncate_to_tokens('The quick brown fox jumps over the lazy dog.', 5) AS clipped;
SELECT tiktoken.main.chunk_by_tokens('A long document to split before embedding for retrieval augmented generation.', 8) AS chunks;
SELECT tiktoken.main.chunk_by_tokens('A long document to split into overlapping windows for retrieval.', 8, 2) AS chunks;
count_tokens (text VARCHAR, model VARCHAR) +1 overload
Count LLM tokens in text under the default encoding (cl100k_base, the GPT-4/3.5 tokenizer). Empty text -> 0
count_tokens(text VARCHAR) β INTEGERcount_tokens(text VARCHAR, model VARCHAR) β INTEGER
Count the GPT-4/3.5 (cl100k_base) tokens in a sentence.
SELECT tiktoken.main.count_tokens('The quick brown fox jumps over the lazy dog.');
Count tokens with the encoding for a specific model (gpt-4o uses o200k_base) to budget a context window.
SELECT tiktoken.main.count_tokens('Summarize this prompt for GPT-4o.', 'gpt-4o');
Compare what one multilingual sentence costs under three models, showing each model's encoding: gpt-4o (o200k_base) needs 20 tokens versus 24 for gpt-4 (cl100k_base) and 30 for text-davinci-003 (p50k_base).
SELECT m.model, tiktoken.main.encoding_for_model(m.model) AS encoding,
tiktoken.main.count_tokens('Tokenizers differ: GPT-4o packs multilingual text such as γγγ«γ‘γ―δΈη into fewer tokens.', m.model) AS tokens
FROM (VALUES ('gpt-4o'), ('gpt-4'), ('text-davinci-003')) AS m(model)
ORDER BY tokens, m.model;
encoding_for_model (model VARCHAR)
Map an LLM model name to its tiktoken encoding name (e.g. 'gpt-4o' -> 'o200k_base'); NULL if the model is unknown
Look up the tiktoken encoding a model uses (gpt-4o -> 'o200k_base').
SELECT tiktoken.main.encoding_for_model('gpt-4o');
tokenize (text VARCHAR, model VARCHAR) +1 overload
Tokenize text to BPE token ids under the default encoding (cl100k_base) as INTEGER[]. Empty -> []; NULL -> NULL
tokenize(text VARCHAR) β INTEGER[]tokenize(text VARCHAR, model VARCHAR) β INTEGER[]
Get the cl100k_base BPE token ids for a string as an INTEGER[].
SELECT tiktoken.main.tokenize('tiktoken is great!');
Tokenize text using a specific model's encoding (gpt-4o uses o200k_base).
SELECT tiktoken.main.tokenize('hello world', 'gpt-4o');
truncate_to_tokens (text VARCHAR, n INTEGER, model VARCHAR) +1 overload
Keep the first n tokens of text (default cl100k_base) and decode them back to VARCHAR. n <= 0 -> ''
truncate_to_tokens(text VARCHAR, n INTEGER) β VARCHARtruncate_to_tokens(text VARCHAR, n INTEGER, model VARCHAR) β VARCHAR
Keep only the first 5 cl100k_base tokens of the text, decoded back to a string.
SELECT tiktoken.main.truncate_to_tokens('The quick brown fox jumps over the lazy dog.', 5);
Truncate text to a token budget using a specific model's encoding (gpt-4o uses o200k_base).
SELECT tiktoken.main.truncate_to_tokens('The quick brown fox jumps over the lazy dog.', 5, 'gpt-4o');
Fit a table of prompts to a 10-token budget: report each prompt's original token count, the clipped text, and its token count after truncation (the 3-token prompt passes through unchanged; the 20-token one is cut to 10).
SELECT p.id, tiktoken.main.count_tokens(p.prompt) AS original_tokens,
tiktoken.main.truncate_to_tokens(p.prompt, 10) AS clipped,
tiktoken.main.count_tokens(tiktoken.main.truncate_to_tokens(p.prompt, 10)) AS clipped_tokens
FROM (VALUES (1, 'Short question?'), (2, 'Please summarize the following quarterly report in three bullet points, focusing on revenue growth, margins and guidance.')) AS p(id, prompt)
ORDER BY p.id;
Try these queries
Count the GPT-4/3.5 (cl100k_base) tokens in a sentence.
SELECT tiktoken.main.count_tokens('The quick brown fox jumps over the lazy dog.');
Uses count_tokens
Count tokens with a specific model's encoding (gpt-4o uses o200k_base).
SELECT tiktoken.main.count_tokens('Summarize this prompt.', 'gpt-4o');
Uses count_tokens
Get the raw BPE token ids of a string under the default encoding.
SELECT tiktoken.main.tokenize('tiktoken is great!');
Uses tokenize
Look up which tiktoken encoding a model uses.
SELECT tiktoken.main.encoding_for_model('gpt-4o');
Uses encoding_for_model
Clip text to its first 5 cl100k_base tokens, decoded back to a string.
SELECT tiktoken.main.truncate_to_tokens('The quick brown fox jumps over the lazy dog.', 5);
Uses truncate_to_tokens
Split a document into non-overlapping 8-token chunks for embedding.
SELECT tiktoken.main.chunk_by_tokens('A long document to split before embedding.', 8);
Uses chunk_by_tokens
14 more examples in the Catalog, each listed under the table or function it uses.
tiktoken is an independent open-source connector from Query.Farm. It is not affiliated with, endorsed by or sponsored by the services, projects or organisations it works with. Product names, logos and trademarks belong to their respective owners.
Related workers
LLM
AI & language
Call LLMs from SQL β Anthropic, OpenAI, OpenRouter or local Ollama β plus local embeddings
Embed
AI & language
Turn text into embedding vectors on your own machine and rank it by cosine similarity for semantic search and RAG
Rerank
AI & language
Score and reorder retrieved passages against a query with local cross-encoder models, for sharper RAG results