Skip to content

Commit

Permalink
Update token-counting and context overflow API surface
Browse files Browse the repository at this point in the history
This is mostly to align with webmachinelearning/writing-assistance-apis#31:

* Use TooManyTokensError when appropriate, instead of a "QuotaExceededError" DOMException.
* Rename tokensLeft/tokensSoFar to tokensAvailable/tokenCount.
* Rename countPromptTokens() to countTokens().
* Remove maxTokens.
* Rename "contextoverflow" to "overflow", since the vocabulary "context" is not used elsewhere in the API and there's only one relevant type of overflow for the session.
  • Loading branch information
domenic committed Jan 23, 2025
1 parent 2dd11f5 commit ffd5aec
Showing 1 changed file with 23 additions and 33 deletions.
56 changes: 23 additions & 33 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,7 @@ console.log(await session.prompt("What is your favorite food?"));

The system prompt is special, in that the language model will not respond to it, and it will be preserved even if the context window otherwise overflows due to too many calls to `prompt()`.

If the system prompt is too large (see [below](#tokenization-context-window-length-limits-and-overflow)), then the promise will be rejected with a `"QuotaExceededError"` `DOMException`.
If the system prompt is too large, then the promise will be rejected with a `TooManyTokens` exception. See [below](#tokenization-context-window-length-limits-and-overflow) for more details on token counting and this new exception type.

### N-shot prompting

Expand Down Expand Up @@ -114,7 +114,7 @@ const result2 = await predictEmoji("This code is so good you should get promoted
Some details on error cases:

* Using both `systemPrompt` and a `{ role: "system" }` prompt in `initialPrompts`, or using multiple `{ role: "system" }` prompts, or placing the `{ role: "system" }` prompt anywhere besides at the 0th position in `initialPrompts`, will reject with a `TypeError`.
* If the combined token length of all the initial prompts (including the separate `systemPrompt`, if provided) is too large, then the promise will be rejected with a `"QuotaExceededError"` `DOMException`.
* If the combined token length of all the initial prompts (including the separate `systemPrompt`, if provided) is too large, then the promise will be rejected with a [`TooManyTokens` exception](#tokenization-context-window-length-limits-and-overflow).

### Customizing the role per prompt

Expand Down Expand Up @@ -295,31 +295,36 @@ Note that because sessions are stateful, and prompts can be queued, aborting a s
A given language model session will have a maximum number of tokens it can process. Developers can check their current usage and progress toward that limit by using the following properties on the session object:

```js
console.log(`${session.tokensSoFar}/${session.maxTokens} (${session.tokensLeft} left)`);
console.log(`${session.tokenCount} tokens used. ${session.tokensAvailable} tokens still left.`);
```

To know how many tokens a string will consume, without actually processing it, developers can use the `countPromptTokens()` method:
To know how many tokens a string will consume, without actually processing it, developers can use the `countTokens()` method:

```js
const numTokens = await session.countPromptTokens(promptString);
const numTokens = await session.countTokens(promptString);
```

Some notes on this API:

* We do not expose the actual tokenization to developers since that would make it too easy to depend on model-specific details.
* Implementations must include in their count any control tokens that will be necessary to process the prompt, e.g. ones indicating the start or end of the input.
* The counting process can be aborted by passing an `AbortSignal`, i.e. `session.countPromptTokens(promptString, { signal })`.
* The counting process can be aborted by passing an `AbortSignal`, i.e. `session.countTokens(promptString, { signal })`.

It's possible to send a prompt that causes the context window to overflow. That is, consider a case where `session.countPromptTokens(promptString) > session.tokensLeft` before calling `session.prompt(promptString)`, and then the web developer calls `session.prompt(promptString)` anyway. In such cases, the initial portions of the conversation with the language model will be removed, one prompt/response pair at a time, until enough tokens are available to process the new prompt. The exception is the [system prompt](#system-prompts), which is never removed. If it's not possible to remove enough tokens from the conversation history to process the new prompt, then the `prompt()` or `promptStreaming()` call will fail with an `"QuotaExceededError"` `DOMException` and nothing will be removed.
It's possible to send a prompt that causes the context window to overflow. That is, consider a case where `session.countTokens(promptString) > session.tokensAvailable` before calling `session.prompt(promptString)`, and then the web developer calls `session.prompt(promptString)` anyway. In such cases, the initial portions of the conversation with the language model will be removed, one prompt/response pair at a time, until enough tokens are available to process the new prompt. The exception is the [system prompt](#system-prompts), which is never removed.

Such overflows can be detected by listening for the `"contextoverflow"` event on the session:
Such overflows can be detected by listening for the `"overflow"` event on the session:

```js
session.addEventListener("contextoverflow", () => {
session.addEventListener("overflow", () => {
console.log("Context overflow!");
});
```

If it's not possible to remove enough tokens from the conversation history to process the new prompt, then the `prompt()` or `promptStreaming()` call will fail with a `TooManyTokens` exception and nothing will be removed. A `TooManyTokens` exception is a new type of exception, which subclasses `DOMException`, and adds the following additional properties:

* `tokenCount`: how many tokens the input consists of
* `tokensAvailable`: how many tokens were available (which will be less than `tokenCount`, and equal to the value of `session.tokensAvailable` at the time of the call)

### Multilingual content and expected languages

The default behavior for a language model session assumes that the input languages are unknown. In this case, implementations will use whatever "base" capabilities they have available for the language model, and might throw `"NotSupportedError"` `DOMException`s if they encounter languages they don't support.
Expand Down Expand Up @@ -398,33 +403,19 @@ It is also nicely future-extensible by adding more events and properties to the
Finally, note that there is a sort of precedent in the (never-shipped) [`FetchObserver` design](https://github.com/whatwg/fetch/issues/447#issuecomment-281731850).
</details>

### Too-large inputs

## Detailed design

### Full API surface in Web IDL

```webidl
// Shared self.ai APIs
// Shared self.ai APIs:
// See https://webmachinelearning.github.io/writing-assistance-apis/#shared-ai-api for most of them.
partial interface WindowOrWorkerGlobalScope {
[Replaceable, SecureContext] readonly attribute AI ai;
};
[Exposed=(Window,Worker), SecureContext]
interface AI {
partial interface AI {
readonly attribute AILanguageModelFactory languageModel;
};
[Exposed=(Window,Worker), SecureContext]
interface AICreateMonitor : EventTarget {
attribute EventHandler ondownloadprogress;
// Might get more stuff in the future, e.g. for
// https://github.com/webmachinelearning/prompt-api/issues/4
};
callback AICreateMonitorCallback = undefined (AICreateMonitor monitor);
enum AICapabilityAvailability { "readily", "after-download", "no" };
```

```webidl
Expand All @@ -442,16 +433,15 @@ interface AILanguageModel : EventTarget {
Promise<DOMString> prompt(AILanguageModelPromptInput input, optional AILanguageModelPromptOptions options = {});
ReadableStream promptStreaming(AILanguageModelPromptInput input, optional AILanguageModelPromptOptions options = {});
Promise<unsigned long long> countPromptTokens(AILanguageModelPromptInput input, optional AILanguageModelPromptOptions options = {});
readonly attribute unsigned long long maxTokens;
readonly attribute unsigned long long tokensSoFar;
readonly attribute unsigned long long tokensLeft;
Promise<unsigned long long> countTokens(AILanguageModelPromptInput input, optional AILanguageModelPromptOptions options = {});
readonly attribute unsigned long long tokensAvailable;
readonly attribute unsigned long long tokenCount;
readonly attribute unsigned long topK;
readonly attribute float temperature;
readonly attribute FrozenArray<DOMString>? expectedInputLanguages;
attribute EventHandler oncontextoverflow;
attribute EventHandler onoverflow;
Promise<AILanguageModel> clone(optional AILanguageModelCloneOptions options = {});
undefined destroy();
Expand Down

0 comments on commit ffd5aec

Please sign in to comment.