Skip to content

Commit 9211561

Browse files
committed
Add too many tokens errors and token-counting APIs
Closes #5.
1 parent 6b66dfd commit 9211561

File tree

2 files changed

+290
-24
lines changed

2 files changed

+290
-24
lines changed

README.md

+67
Original file line numberDiff line numberDiff line change
@@ -175,6 +175,73 @@ console.log(summary); // will be in Chinese
175175

176176
If the `outputLanguage` is not supplied, the default behavior is to produce the output in "the same language as the input". For the multilingual input case, what this means is left implementation-defined for now, and implementations should err on the side of rejecting with a `"NotSupportedError"` `DOMException`. For this reason, it's strongly recommended that developers supply `outputLanguage`.
177177

178+
### Too-large inputs
179+
180+
It's possible that the inputs given for summarizing and rewriting might be too large for the underlying machine learning model to handle. The same can even be the case for strings that are usually smaller, such as the writing task for the writer API, or the context given to all APIs.
181+
182+
Whenever any API call fails due to too-large input, it is rejected with a `TooManyTokensError`. This is a new type of exception, which subclasses `DOMException`, and has the following additional properties:
183+
184+
* `tokenCount`: how many tokens the input consists of
185+
* `tokensAvailable`: how many tokens were available (which will be less than `tokenCount`)
186+
187+
("[Tokens](https://arxiv.org/abs/2404.08335)" are the way that current language models process their input, and the exact mapping of strings to tokens is implementation-defined. However, we believe this API is relatively future-proof, since even if the technology moves away from current tokenization strategies, at the limit we can reinterpret tokens to mean code units, i.e., normal JavaScript string length.)
188+
189+
This allows detecting failures due to overlarge inputs and giving clear feedback to the user, with code such as the following:
190+
191+
```js
192+
const summarizer = await ai.summarizer.create();
193+
194+
try {
195+
console.log(await summarizer.summarize(potentiallyLargeInput));
196+
} catch (e) {
197+
if (e.name === "TooManyTokensError") {
198+
console.error(`Input too large! You tried to summarize ${e.tokenCount} tokens, but only ${e.tokensAvailable} were available.`);
199+
200+
// Or maybe:
201+
console.error(`Input too large! It's ${e.tokenCount / e.tokensAvailable}x as large as the maximum possible input size.`);
202+
}
203+
}
204+
```
205+
206+
Note that all of the following methods can reject (or error the relevant stream) with this exception:
207+
208+
* `ai.summarizer.create()`, if `sharedContext` is too large;
209+
210+
* `ai.summarizer.summarize()`/`summarizeStreaming()`, if the combination of the creation-time `sharedContext`, the current method call's `input` argument, and the current method call's `context` is too large;
211+
212+
* Similarly for writer creation / writing, and rewriter creation / rewriting.
213+
214+
In some cases, instead of providing errors after the fact, the developer needs to be able to communicate to the user how close they are to the limit. For this, they can use the `tokensAvailable` property and `countTokens()` methods on the summarizer/writer/rewriter objects:
215+
216+
```js
217+
const rewriter = await ai.rewriter.create();
218+
meterEl.max = rewriter.tokensAvailable;
219+
220+
textbox.addEventListener("input", () => {
221+
meterEl.value = await rewriter.countTokens(textbox.value);
222+
submitButton.disabled = meterEl.value > meterEl.max;
223+
});
224+
225+
submitButton.addEventListener("click", () => {
226+
console.log(rewriter.rewrite(textbox.value));
227+
});
228+
```
229+
230+
Developers need to be cautious not to over-use this API, however, as it requires a round-trip to the language model. That is, the following code is bad, as it performs two round trips with the same input:
231+
232+
```js
233+
// DO NOT DO THIS
234+
235+
const tokenCount = await rewriter.countTokens(input);
236+
if (tokenCount < rewriter.tokensAvailable) {
237+
console.log(await rewriter.rewrite(input));
238+
} else {
239+
console.error(`Input too large!`);
240+
}
241+
```
242+
243+
If you're planning to call `rewrite()` anyway, then using a pattern like the one that opened this section, which catches `TooManyTokensError`s, is more efficient than using `countTokens()` plus a conditional call to `rewrite()`.
244+
178245
### Testing available options before creation
179246

180247
All APIs are customizable during their `create()` calls, with various options. In addition to the language options above, the others are given in more detail in [the spec](https://webmachinelearning.github.io/writing-assistance-apis/).

0 commit comments

Comments
 (0)