Kokil Thapa - Professional Web Developer in Nepal
Freelancer Web Developer in Nepal with 15+ Years of Experience

Kokil Thapa is an experienced full-stack web developer focused on building fast, secure, and scalable web applications. He helps businesses and individuals create SEO-friendly, user-focused digital platforms designed for long-term growth.

Tokens, Embeddings, and Context Windows Explained

By Kokil Thapa | Last reviewed: September 2026

Tokens, embeddings, and context windows explained in plain engineering terms: three ideas that decide whether your AI integration works, how much it costs, and how far it scales. You send text to an API. The provider turns it into tokens, runs it through a model, and sometimes stores embeddings for search. Every bill, timeout, and truncated reply traces back to those mechanics. If you build chat, RAG, or document workflows on Laravel or WordPress, you need this model in your head before you write the first controller.

What are tokens in large language models?

Tokens are the atomic units a language model actually processes. You type English, Nepali, or JSON. The tokenizer splits that string into integer IDs. The model never sees your raw characters during inference—it sees those IDs and their position numbers.

That gap causes most production surprises. A prompt that looks short in your editor can exceed the context window. A log line with base64 can explode in token count. Billing is per token, not per word.

How tokenization works in practice

Modern APIs use subword tokenizers—often byte-pair encoding (BPE) or similar schemes. Common English words may map to one token. Rare words, typos, and non-Latin scripts split into smaller pieces. Nepali Devanagari text typically uses more tokens per visible character than English prose.

On a legal-tech portal I built, a bilingual FAQ page cost nearly double the English-only estimate. The Nepali paragraphs tokenized aggressively. Always measure; never guess from word count.

From User Text to Model InputRaw Textprompt + docsTokenizerBPE / SentencePieceToken IDs[1284, 392, …]LLMtransformerRough Token Rules (English)• 1 token ≈ 4 characters• 100 tokens ≈ 75 words• Code and JSON cost more• Unicode splits often• Billing = input + output• Count before you ship
Tokens, embeddings, and context windows explained: how raw text becomes integer token IDs before the model runs.

Rules of thumb for token counting

Use these estimates only for back-of-envelope planning. Confirm with the provider’s tokenizer before you commit to architecture.

  • English prose: about 1 token per 0.75 words, or roughly 4 characters.
  • Source code and JSON: often 1.2–2× the token count of equivalent prose.
  • Devanagari and mixed scripts: plan for higher token-per-character ratios.
  • Output tokens are billed separately from input tokens on most APIs.

The OpenAI tokenizer playground and equivalent tools from other vendors let you paste real prompts and see exact counts. That step belongs in every AI rate limits and cost optimization review.

curl https://api.openai.com/v1/chat/completions \
  -H "Authorization: Bearer $OPENAI_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "gpt-4o",
    "messages": [{"role": "user", "content": "Summarise this contract clause."}],
    "max_tokens": 500
  }'

/* Response usage block — log this on every call */
{
  "usage": {
    "prompt_tokens": 842,
    "completion_tokens": 187,
    "total_tokens": 1029
  }
}

In Laravel, persist prompt_tokens and completion_tokens per request. Aggregate by user, feature, and day. Without that telemetry, you cannot explain a Rs 15,000 (~USD 112) monthly API bill to a client.

How do embeddings work in AI applications?

Embeddings are fixed-length vectors—lists of floating-point numbers—that represent the semantic meaning of text, images, or other inputs. Similar meanings produce vectors that sit close together in high-dimensional space. Dissimilar meanings sit farther apart.

That geometry powers semantic search, recommendation, clustering, and deduplication. You do not send embeddings to a chat model for reasoning. You store them in a vector database and retrieve relevant chunks before you call the chat model.

From text chunk to searchable vector

A typical RAG pipeline on a production Laravel app looks like this:

  1. Split documents into chunks—often 300–800 tokens with overlap.
  2. Call an embedding model API for each chunk.
  3. Store vectors plus metadata in PostgreSQL with pgvector, Redis, or a dedicated engine.
  4. On user query, embed the question and run nearest-neighbour search.
  5. Inject top-k chunks into the chat prompt as context.

I have shipped this pattern on client portals where users search uploaded PDFs. The embedding step is cheap and cacheable. The chat step is expensive and must stay small. See our guide on how to build an embeddings pipeline for ingestion details.

Embedding Ingest and RetrievalDocumentsPDF, HTMLChunker512 tokensEmbed API1536 dimsVector DBpgvectorQuery PathUser question → embed → cosine similarity → top 5 chunksChat LLM + Retrieved Contextanswer grounded in your data
How embeddings enable semantic search: chunk, vectorize, store, then retrieve similar content at query time.

Choosing embedding dimensions and models

Embedding models differ by vector size, language support, and cost. A 1536-dimension model from a major provider is a safe default for English-heavy apps in 2026. Smaller models trade accuracy for speed on edge deployments.

Google’s embedding documentation and OpenAI’s embeddings guide both stress one point: use the same model for ingestion and query. Mixing models breaks similarity math.

/* Laravel job — embed one chunk */
$response = Http::withToken(config('services.openai.key'))
    ->post('https://api.openai.com/v1/embeddings', [
        'model' => 'text-embedding-3-small',
        'input' => $chunkText,
    ]);

$vector = $response->json('data.0.embedding');

DB::table('document_chunks')->insert([
    'document_id' => $documentId,
    'content'     => $chunkText,
    'embedding'   => json_encode($vector),
    'token_count' => $tokenCount,
]);

For Nepali content, validate retrieval quality with real queries—not English-only benchmarks. A Nepali word counter helps estimate chunk sizes before tokenization, but only the API tokenizer gives you billable numbers.

What is a context window and why does it matter?

The context window is the maximum number of tokens a model can accept in a single request. That total includes your system prompt, conversation history, retrieved documents, tool results, and the space reserved for the model’s reply.

Exceed the limit and the API returns an error—or silently truncates input if your client library does not validate first. Both outcomes hurt production apps.

What fills the context window

Think of the window as a fixed bucket. Every byte of prompt competes for the same space.

  • System instructions: persona, rules, output format—often 200–800 tokens.
  • Few-shot examples: powerful but expensive; each example consumes budget.
  • RAG chunks: five chunks at 400 tokens each can eat 2,000 tokens before the user speaks.
  • Chat history: grows linearly with every turn unless you prune it.
  • Tool JSON: function definitions and API responses add up fast.
  • Completion reserve: max_tokens must fit inside the remaining space.

Models advertised with 128K or 200K context windows still charge per token. A larger window removes truncation pain; it does not remove cost. Read our companion piece on long-context LLM strategies and limits for when big windows help versus hurt.

Context Window Token Budget128,000 token window (example model)System600RAG chunks4,000Chat history12,000Tools2,400Output2,000When the bucket overflows→ API 400 error→ Or silent head truncation→ Fix: summarize history→ Fix: reduce k in RAG
Context window limits: every prompt section competes for the same fixed token budget including reserved output space.

Context window sizes in 2026

Vendor limits change quarterly. Treat published maximums as ceilings, not targets. Latency and cost scale with input length even when the call succeeds.

ConceptWhat it measuresTypical range (2026 APIs)Primary cost driver
TokenSubword text unit~4 chars or ~0.75 English wordsInput + output per call
EmbeddingSemantic vector256–3072 dimensionsOne-time ingest; cheap re-query
Context windowMax tokens per request8K–200K+ depending on modelLong prompts increase $ and latency

Anthropic’s model documentation describes context as shared between input and output. OpenAI’s API reference documents the same constraint under max_tokens and model-specific limits. Always read the vendor page for the model string you pass in production.

How do tokens, embeddings, and context windows work together in production?

Tokens, embeddings, and context windows are not three separate features you pick among. They stack. Embeddings shrink what must live inside the context window. Tokens determine whether what remains still fits. The context window caps the entire operation.

On a production Laravel application, I treat this as a pipeline budget problem—not a prompt-writing exercise.

A production budgeting workflow

  1. Measure baseline: tokenize your system prompt and tool schemas once at deploy time.
  2. Cap RAG: retrieve by similarity, then re-rank and trim to a token ceiling—often 2,000–6,000 tokens.
  3. Summarize history: after N turns, compress older messages into a rolling summary stored in Redis.
  4. Reserve output: set max_tokens explicitly; never assume unlimited completion space.
  5. Log usage: store token counts per feature flag and customer tier.
  6. Cache embeddings: hash chunk content; skip re-embedding unchanged documents.
/* Guard before calling the chat API */
$budget = 128_000;
$reservedForOutput = 2_000;
$fixedOverhead = $systemTokens + $toolSchemaTokens;

$availableForContext = $budget - $reservedForOutput - $fixedOverhead;
$selectedChunks = $retriever
    ->search($query, limit: 20)
    ->fitWithinTokens($availableForContext * 0.6);

if ($historyTokens + $selectedChunks->tokenSum() > $availableForContext) {
    $history = $summarizer->compress($history);
}

This mirrors patterns from AI-powered search for Laravel products and standard API development practice: validate inputs server-side, never trust client-side length checks alone.

Context Overflow Decision TreePrompt too large?Trim RAG chunksLower top-kre-rank tighterSummarize historyrolling memoryStill over limit?Switch model or split task
Production response when tokens exceed the context window: trim retrieval, compress history, then escalate model or task split.

Common mistakes I see on client projects

Dumping whole PDFs into the prompt. A 40-page contract can exceed 30,000 tokens. Embed and retrieve instead. On document-heavy legal workflows—similar to portals like Mijar Law Associates—RAG is mandatory, not optional.

Ignoring output tokens. A 128K window with 127K input leaves almost no room for the answer. Always subtract max_tokens from your budget math.

Re-embedding on every deploy. Embeddings are deterministic for unchanged text. Version your embedding model in the database schema and migrate deliberately.

Word-count pricing estimates. Stakeholders multiply words by a dollar rate. Developers pay per token. Bridge that gap with logged usage dashboards early.

How do you choose the right approach for your application?

Not every feature needs embeddings. Not every chat needs a 128K window. Match the machinery to the job.

Decision guide by use case

Use caseTokens focusEmbeddings?Context strategy
Short FAQ botLow; static promptOptional8K window sufficient
Document Q&AHigh; chunk sizingRequiredRAG + strict token cap
Multi-turn support chatMedium; history growthHelpful for KB searchSummarize after 6–10 turns
Code assistantVery high; syntax splitsFor repo searchLarge window or file scoping
Batch summarisationInput-heavyUsually noMap-reduce across chunks

For enterprise application development, define token budgets in the requirements doc the same way you define SLA response times. For content-heavy sites, pair AI features with technical SEO so generated pages still ship with canonical URLs and crawlable structure.

Validate JSON payloads with a JSON formatter during integration testing. Tool-call schemas that balloon silently are a frequent source of context overflow.

Security and compliance notes

Tokens can carry secrets if users paste API keys or PAN numbers into chat boxes. Log token counts, not raw prompts, in production unless you have a data-retention policy and client consent.

Embeddings are not encryption. A vector can leak semantic information about source documents. Treat the vector store with the same access controls as the original files.

External references worth bookmarking: OpenAI’s tokenizer tool, OpenAI embeddings documentation, and Anthropic’s context window guide.

Key Takeaways

  • Tokens are billable subword units—count them with the vendor tokenizer before you design prompts or SLAs.
  • Embeddings power semantic search; store them once, query cheaply, and never mix embedding model versions.
  • The context window is a hard shared budget for input and output—RAG and summarization exist to stay inside it.
  • Log prompt_tokens and completion_tokens per request so costs map to features and customers.
  • Trim retrieval results and compress chat history before you pay for a larger model tier.
  • Match architecture to use case: FAQ bots stay simple; document portals need embeddings plus strict token caps.

People Also Ask

How many tokens is 1,000 words?

For English prose, expect roughly 1,300–1,400 tokens per 1,000 words. Code, tables, and Nepali Unicode text run higher. Paste the actual text into a tokenizer tool rather than using word-count divided by 0.75 in production billing models.

What is the difference between tokens and embeddings?

Tokens are discrete input symbols the language model reads during generation. Embeddings are continuous numeric vectors that represent meaning for similarity search. You convert text to tokens for chat completions; you convert text to embeddings for retrieval and clustering.

What happens when you exceed the context window?

Most APIs return a 400-class error with a message about maximum context length. Some client libraries truncate from the start or end without a loud failure. Always validate total tokens server-side before sending the request.

Do embeddings count toward the context window?

No. Embeddings are produced by a separate model call and stored offline. Only the text chunks you inject into the chat prompt after retrieval consume context window tokens.

Ship AI features with your eyes open

Tokens, embeddings, and context windows explained is the foundation for every sane LLM integration in 2026. Measure tokens, embed documents instead of stuffing prompts, and treat the context window as a budget—not a challenge to fill. That discipline keeps latency predictable and bills explainable to clients in Kathmandu or abroad.

If you want help wiring RAG, usage logging, or guardrails into a Laravel or WordPress platform, see our AI integration and automation service or browse the portfolio for shipped examples. When you are ready to scope a feature with real token math, contact us with a sample prompt and document set—we will tell you what fits before you commit.

Frequently Asked Questions

Tokens are the atomic units a language model actually processes. When you send English, Nepali, or JSON to an API, a tokenizer splits the string into integer IDs. The model never sees raw characters during inference—it sees those IDs plus position numbers. That gap between what looks short in your editor and what the API bills causes most production surprises. Billing is per token, not per word, so token count is the number you must measure before designing prompts, SLAs, or client cost estimates.

For English prose, expect roughly 1,300–1,400 tokens per 1,000 words. Code, tables, and Nepali Unicode text run higher—always paste real text into a vendor tokenizer instead of dividing word count by 0.75.

Modern APIs use subword tokenizers, often byte-pair encoding or similar schemes. Common English words may map to one token. Rare words, typos, and non-Latin scripts split into smaller pieces. Devanagari Nepali text typically uses more tokens per visible character than English prose. Source code and JSON often run 1.2–2× the token count of equivalent prose. Rules of thumb help for planning, but the OpenAI tokenizer playground and equivalent vendor tools give exact billable counts—use those before committing to architecture.

Tokens are discrete input symbols the language model reads during generation. Embeddings are continuous numeric vectors that represent meaning for similarity search. You convert text to tokens for chat completions; you convert text to embeddings for retrieval and clustering.

Embeddings are fixed-length vectors—lists of floating-point numbers—that represent the semantic meaning of text, images, or other inputs. Similar meanings produce vectors that sit close together in high-dimensional space; dissimilar meanings sit farther apart. That geometry powers semantic search, recommendation, clustering, and deduplication. You do not send embeddings to a chat model for reasoning. You store them in a vector database and retrieve relevant chunks before calling the chat model. The embedding step is cheap and cacheable; the chat step is expensive and must stay small.

The context window is the maximum number of tokens a model can accept in a single request. That total includes your system prompt, conversation history, retrieved documents, tool results, and the space reserved for the model's reply. Think of it as a fixed bucket where every byte of prompt competes for the same space. Models advertised with 128K or 200K context windows still charge per token—a larger window removes truncation pain but does not remove cost. Latency also scales with input length even when the call succeeds.

No. Embeddings are produced by a separate model call and stored offline in a vector database. Only the text chunks you inject into the chat prompt after retrieval consume context window tokens.

Most APIs return a 400-class error with a message about maximum context length. Some client libraries truncate from the start or end without a loud failure—both outcomes hurt production apps. Always validate total tokens server-side before sending the request, never relying on client-side length checks alone. When you are near the limit, trim retrieval results, compress chat history, or split the task across multiple calls rather than assuming the model will silently cope.

Input tokens and output tokens are billed separately on most APIs. A prompt that looks modest in your editor can exceed budget if it contains base64, JSON, or multilingual text. Without telemetry, you cannot explain a monthly API bill to a client—I have seen unexplained bills around Rs 15,000 (~USD 112) when usage was not logged. In Laravel, persist prompt_tokens and completion_tokens per request and aggregate by user, feature, and day. Log the usage block from every API response and map costs to features and customer tiers early.

They stack rather than compete. Embeddings shrink what must live inside the context window by letting you retrieve only relevant chunks instead of stuffing whole documents into the prompt. Tokens determine whether what remains still fits. The context window caps the entire operation. On a production Laravel application, treat this as a pipeline budget problem: measure baseline system and tool schema tokens at deploy time, cap RAG retrieval to a token ceiling, summarize chat history after several turns, reserve max_tokens explicitly, log usage per feature, and cache embeddings for unchanged documents.

Split documents into chunks of roughly 300–800 tokens with overlap before calling an embedding model API for each chunk. Store vectors plus metadata in PostgreSQL with pgvector, Redis, or a dedicated vector engine. On user query, embed the question, run nearest-neighbour search, and inject the top-k chunks into the chat prompt as context. After similarity search, re-rank and trim results to fit your token ceiling—often 2,000–6,000 tokens for retrieved context. Use the same embedding model for ingestion and query; mixing models breaks similarity math.

Subword tokenizers split non-Latin scripts into smaller pieces than common English words, so Nepali Devanagari text typically uses more tokens per visible character than English prose. On a legal-tech portal I built, a bilingual FAQ page cost nearly double the English-only estimate because Nepali paragraphs tokenized aggressively. Mixed-script content and Unicode-heavy text follow the same pattern. Always measure with the provider's tokenizer rather than guessing from word count or character count, especially when quoting API costs to Nepali clients.

Dumping whole PDFs into the prompt—a 40-page contract can exceed 30,000 tokens; embed and retrieve instead. Ignoring output tokens when a 128K window with 127K input leaves almost no room for the answer. Re-embedding unchanged documents on every deploy when embeddings are deterministic for the same text. Using word-count pricing estimates with stakeholders while developers pay per token. Tool-call JSON schemas that balloon silently are another frequent source of context overflow—validate payloads during integration testing.

Log the usage block from every chat completion response, including prompt_tokens, completion_tokens, and total_tokens. Persist those values per request in your database and aggregate by user, feature, and day. Set max_tokens explicitly on each API call and never assume unlimited completion space. Measure your system prompt and tool schemas once at deploy time so you know fixed overhead before RAG and history consume the rest. Build a dashboard early so costs map to features and customer tiers instead of arriving as a surprise monthly bill.

Embeddings are not encryption—a vector can leak semantic information about source documents, so treat the vector store with the same access controls as the original files. Tokens can carry secrets if users paste API keys or PAN numbers into chat boxes, so log token counts in production rather than raw prompts unless you have a data-retention policy and client consent. For document-heavy legal workflows, RAG with strict access controls is mandatory, not optional, because both the source files and their vector representations need protection.

Share this article

0 Comments

Leave a comment

Your email is not published. Comments appear once they have been read. Sign in to have your details filled in.

Quick Contact Options
Choose how you want to connect me: