LanguageModel: measureContextUsage() method

Secure context: This feature is available only in secure contexts (HTTPS), in some or all supporting browsers.

The measureContextUsage() method of the LanguageModel interface estimates how many context window tokens the given input would consume without sending it to the model or modifying the session's state.

This allows you to check how much of the context window a given input requires before deciding whether to send it. The result can be compared against LanguageModel.contextWindow and LanguageModel.contextUsage to determine whether the input can fit into the context window limit.

This is particularly useful for long-context applications such as document summarization, where you may need to split or truncate content to stay within the context window limit.

Syntax

js
measureContextUsage(input)
measureContextUsage(input, options)

Parameters

input

The content to append to the context window. This is either:

options Optional

Options for measuring context usage. Properties include:

responseConstraint

An object following the structure defined by JSON Schema defining the precise format the model's output should be delivered in. When provided and omitResponseConstraintInput is false, any implementation-defined constraint-description message is included in the measurement.

omitResponseConstraintInput

A boolean; when true, the automatic constraint-description message is excluded from the measurement.

signal

An AbortSignal to cancel the operation.

Return value

A Promise that resolves with a Number representing the number of context window tokens the input would consume.

Exceptions

AbortError DOMException

Thrown if the operation was cancelled via the signal option.

NotAllowedError DOMException

Thrown if usage of the method is blocked by a language-model Permissions-Policy.

NotSupportedError DOMException

Thrown if:

SyntaxError DOMException

Thrown if:

TypeError

Thrown if:

Examples

undefined

Warning when the context is nearly full

The following example uses a function to verify that context is available before calling LanguageModel.prompt(). It first calculates the remaining context and passes that value to measureContextUsage(). If needed is less than or equal to remaining, it returns true and the session continues.

js
const promptText = "Let me ask you an interesting question...";
const session = await LanguageModel.create();

async function contextAvailable(promptText) {
  const remaining = session.contextWindow - session.contextUsage;
  const needed = await session.measureContextUsage(promptText);

  return needed <= remaining;
}

if (await contextAvailable(promptText)) {
  const response = await session.prompt(promptText);
  console.log(response);
} else {
  console.warn("Prompt skipped: Not enough context window remaining.");
}

Specifications

See also