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.
measureContextUsage(input)
measureContextUsage(input, options)inputThe content to append to the context window. This is either:
roleA string indicating the point of view the message is phrased from. Must be one of:
systemA system-level instruction that guides the model's overall behavior. This must be the first instruction passed to the model.
userA message from the user, which the API should respond to.
assistantAn input that provides context for the AI assistant, such as its persona or the format of its responses. Such messages mainly serve to provide context/history, and further shape how the model responds.
contentA string representing a textual prompt, or an array of objects. Each object includes the following properties:
typeAn enumerated value representing the type of content. This can be one of:
audioAudio content.
imageImage content.
textTextual content.
tool-callA tool invocation issued by the model.
tool-responseThe result of a tool invocation.
valueThe content of the message. If the type is text, this is always a string. If the type is audio or image, the value can be one of several different object types; see What data types are accepted?.
prefix OptionalA boolean, defaulting to false. When true, the message is treated as a prefix for the model's next generated response rather than a complete turn.
options OptionalOptions for measuring context usage. Properties include:
responseConstraintAn 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.
omitResponseConstraintInputA boolean; when true, the automatic constraint-description message is excluded from the measurement.
signalAn AbortSignal to cancel the operation.
A Promise that resolves with a Number representing the number of context window tokens the input would consume.
AbortError DOMExceptionThrown if the operation was cancelled via the signal option.
NotAllowedError DOMExceptionThrown if usage of the method is blocked by a language-model Permissions-Policy.
NotSupportedError DOMExceptionThrown if:
role is assistant and its type is anything other than text.type is text and its value is not a string.type is image or audio but the type was not listed in expectedInputs, or the value is not an accepted data type.SyntaxError DOMExceptionThrown if:
prefix property is set to true and:role is not assistant.TypeErrorThrown if:
omitResponseConstraintInput is true but responseConstraint is not provided.role is system but it was not the first message passed to the context.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.
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.");
}