Text completion

Also known as: completion API

On this page 7

Text completion is the task in which a language model receives a piece of text, the prompt, and generates a continuation that is statistically likely to follow it, one token at a time. In the study of language models, it is the most basic interface to an autoregressive model: the model does not answer, obey or converse by design, it predicts what comes next.

The term also names a style of programming interface, often called a completion API, that accepts a single string and returns the generated text. It predates the message-based chat interfaces that now dominate, and it remains the native way to use base models, to run few-shot prompts and to fill in code.

How text completion produces a continuation

Text completion works by repeated next-token prediction. The prompt is split into tokens by the model’s tokenizer, the network scores every candidate and turns those scores into next-token probabilities, a sampler picks a single candidate, and the pick is fed back as fresh input before another step runs.

The loop stops when one of three conditions is met: the model emits an end-of-sequence token, the output reaches the max tokens limit, or the generated text matches a stop sequence supplied by the caller. Because each step depends on every previous token, the whole prompt plus the generated text must fit inside the context window.

The following table lists the stages of a single completion request and what each one controls.

StageWhat happensMain controls
TokenizationPrompt text becomes token IDsTokenizer vocabulary
Forward passModel computes logits for the next tokenModel weights, context length
SamplingOne token is chosen from the distributionTemperature, top-p, top-k
AppendingChosen token joins the input sequenceNone, automatic
StoppingGeneration ends on a defined conditionMax tokens, stop sequences
DetokenizationToken IDs become readable textTokenizer decoding rules
Stages of a text completion request

Parameters that shape a completion

Completion behavior is governed mainly by decoding parameters, which change how tokens are selected without changing the model itself. Most completion APIs expose a similar set, although names and default values differ between providers and open-source inference servers.

ParameterTypical rangeEffect on output
Temperature0 to 2Higher values flatten the distribution and add variety
Top-p0.1 to 1.0Restricts sampling to the smallest set reaching the given probability mass
Top-k1 to several hundredRestricts sampling to the k most likely tokens
Max tokens1 to model limitCaps the length of the generated text
Stop sequencesOne or a few stringsEnds output when a delimiter appears
Frequency penaltyAbout -2 to 2Discourages tokens that already appeared often
Logprobs0 to about 20Returns probabilities of chosen and alternative tokens
Common completion parameters and their effects

A temperature of zero approximates greedy decoding and gives nearly deterministic output, which suits extraction and classification. Values between 0.7 and 1.0 are common for open-ended writing. Strict determinism is not guaranteed even at zero, because floating-point nondeterminism and batching on shared hardware can change near-tied choices.

Text completion compared with chat interfaces

The essential difference between text completion and chat is how the input is structured. A completion request is one free-form string, while a chat request is a list of messages with roles such as system, user and assistant, which the server converts into a single string through a chat template before running the same next-token loop.

AspectText completionChat interface
Input formatOne raw stringList of role-tagged messages
Typical modelBase or instruction-tuned modelInstruction-tuned chat model
Prompt controlFull control of every tokenTemplate inserted by the server
Best usesFew-shot patterns, code infill, scoringDialogue, assistants, tool use
Main riskModel continues in unintended directionsLess control over formatting tokens
Completion and chat interfaces side by side

Several major providers have deprecated or frozen their legacy completion endpoints in favor of chat-style APIs, while open-weight inference servers usually still offer both. In practice, chat is a thin layer on top of completion, so knowledge of raw completion helps when debugging templates, special tokens and unexpected formatting.

Prompt design for raw completion

Prompting for raw completion means drafting the opening of a document so that the wanted answer is its most plausible next part. A base model does not follow instructions reliably, so a request such as “Summarize this article” may be continued with more questions instead of a summary.

Effective patterns exploit in-context learning and the structure of familiar documents:

  • Few-shot formatting: show several input and output pairs, then leave the last output empty.
  • Document framing: begin a FAQ, a report or a code file so that the answer is the expected next part.
  • Explicit delimiters: end each example with a marker and pass the same marker as a stop sequence.
  • Prefilling: start the answer yourself, for example with an opening brace, to lock the output format.

These techniques also explain fill-in-the-middle completion in code assistants. The editor sends the code before and after the cursor, arranged with special tokens, and the model completes the gap, which is still text completion with a rearranged context.

Limitations and common mistakes

Text completion inherits every weakness of the underlying model and adds a few of its own, because nothing in the interface constrains the output beyond the parameters. Recurring completion faults, their origins and remedies appear in the next table.

SymptomLikely causeFix
Output never stopsNo stop sequence or end tokenAdd delimiters and a max tokens cap
Repetitive loopsLow temperature with greedy decodingRaise temperature or add a repetition penalty
Answer ignores the taskBase model treats instructions as textUse few-shot examples or an instruction-tuned model
Truncated answerMax tokens set too lowRaise the limit within the context window
Confident false factsHallucination from parametric knowledgeSupply source text in the prompt and verify
Typical completion problems and remedies

A frequent misconception is that a completion reflects what the model believes. It reflects only which continuation is probable given the prompt and decoding settings, so the same model can produce contradictory completions from slightly different prompts. Outputs therefore need validation whenever accuracy matters.

Stripped to the essentials

Text completion is like the autocomplete on a phone keyboard, made far more powerful. You type the start of something. The model guesses the most likely next word piece. Then it guesses the next one, and the next.

The model does not truly understand a request. It only continues the text it sees. So the way you start the text decides what you get back. A well-chosen beginning, a few good examples and a clear stopping point produce the most reliable results.

Where it is applied

A data team at a regional insurer needs to pull claim categories from 40,000 short adjuster notes. Instead of a chat assistant, an engineer uses the raw completion endpoint of an open-weight base model running on an internal server. The prompt contains eight labeled examples, each written as “Note:”, the note text, “Category:” and a label, followed by a newline marker.

Every request ends with a new note and the word “Category:”, uses a temperature of 0, a max tokens value of 5 and the newline as a stop sequence. The model returns only a short label, which a script checks against the list of twelve allowed categories. About 3 percent of outputs fall outside the list and go to a human reviewer.

The result is a classification pipeline that processes the whole backlog overnight at low and predictable cost, with an output format that never drifts, because the completion setup leaves the model no room to add explanations.