liveBook · Manning

Token

As explained in Build AI-Enhanced Web Apps

A token is a discrete unit of text, such as a word, subword, or character, processed by a language model.

A token is a unit produced when text is tokenized for an LLM. Tokenization turns input into tokens and numerical IDs; the model processes numbers and translates its output back into human-readable form. Because services may bill for input and generated tokens, token counts matter for cost management. section 5.1.1

Figure 5.2 The end-to-end process of how human input is transformed, processed by an LLM and converted back into human-readable output

Trace how human input is tokenized, processed by an LLM, and converted into readable output. section 5.1.1

Listing 5.1 Function that counts prompt tokens
import { encoding_for_model } from '@dqbd/tiktoken';    #1

function countTokens(text, model = "gpt-3.5-turbo") {
  const enc = encoding_for_model(model);
  const tokens = enc.encode(text);    #2
  enc.free();
  return tokens.length;
}
const prompt =
  "Translate the following English text to French: 'Hello, how are you?'";
const systemMessage 
  "You are a helpful assistant that translates English to French.";

const promptTokens = countTokens(prompt);    #3
const systemTokens = countTokens(systemMessage);    #4
const totalTokens = promptTokens + systemTokens;

console.log(`Prompt tokens: ${promptTokens}`);
console.log(`System message tokens: ${systemTokens}`);
console.log(`Total tokens: ${totalTokens}`);

See a JavaScript function that counts tokens in a prompt and system message using @dqbd/tiktoken. section 5.1.1

How Build AI-Enhanced Web Apps covers it

How deep it goes
Defines tokenization as splitting text into tokens and numerical IDs, then situates those IDs in model processing and output conversion.
Examples
Counts tokens in a translation prompt and system message with JavaScript and @dqbd/tiktoken.
What you can do after
Apply token counting with @dqbd/tiktoken to estimate prompt and system-message totals.
How it connects
Connects tokens with prompts, tokenization, token IDs, language models, and usage billing.

Also explained in

Compare how 31 books explain token →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Build AI-Enhanced Web Apps. The section links point to the parts of the book it draws on.