diff --git a/files/en-us/web/api/createmonitor/downloadprogress_event/index.md b/files/en-us/web/api/createmonitor/downloadprogress_event/index.md new file mode 100644 index 000000000000000..558b4fb3f7df7b2 --- /dev/null +++ b/files/en-us/web/api/createmonitor/downloadprogress_event/index.md @@ -0,0 +1,46 @@ +--- +title: "CreateMonitor: downloadprogress event" +short-title: downloadprogress +slug: Web/API/CreateMonitor/downloadprogress_event +page-type: web-api-event +status: + - experimental +browser-compat: api.CreateMonitor.downloadprogress_event +--- + +{{APIRef("Summarizer API")}}{{SeeCompatTable}} + +The **`downloadprogress`** event of the {{domxref("CreateMonitor")}} interface is fired when progress is made on the AI model download. + +## Syntax + +Use the event name in methods like {{domxref("EventTarget.addEventListener", "addEventListener()")}}, or set an event handler property. + +```js +addEventListener("downloadprogress", (event) => {}); + +ondownloadprogress = (event) => {}; +``` + +## Event type + +A {{domxref("ProgressEvent")}}. Inherits from {{domxref("Event")}}. + +{{InheritanceDiagram("ProgressEvent")}} + +## Examples + +See the main {{domxref("CreateMonitor")}} page for an example. + +## Specifications + +{{Specifications}} + +## Browser compatibility + +{{Compat}} + +## See also + +- [Using the Summarizer API](/en-US/docs/Web/API/Summarizer_API/Using) +- [Web AI demos](https://chrome.dev/web-ai-demos/) on chrome.dev. diff --git a/files/en-us/web/api/createmonitor/index.md b/files/en-us/web/api/createmonitor/index.md new file mode 100644 index 000000000000000..bb02f6927846279 --- /dev/null +++ b/files/en-us/web/api/createmonitor/index.md @@ -0,0 +1,60 @@ +--- +title: CreateMonitor +slug: Web/API/CreateMonitor +page-type: web-api-interface +status: + - experimental +browser-compat: api.CreateMonitor +--- + +{{APIRef("Summarizer API")}}{{SeeCompatTable}} + +The **`CreateMonitor`** interface provides information on the progress of an AI model download or some fine-tuning data for the model. + +It can be used via: + +- {{domxref("Summarizer.create_static", "Summarizer.create()")}} +- {{domxref("LanguageDetector.create_static", "LanguageDetector.create()")}} +- {{domxref("Translator.create_static", "Translator.create()")}} + +{{InheritanceDiagram}} + +## Events + +_Inherits events from its parent, {{DOMxRef("EventTarget")}}._ + +- {{domxref("CreateMonitor/downloadprogress_event", "downloadprogress")}} {{Experimental_Inline}} + - : Fired when progress is made on the AI model download. + +## Examples + +### Basic `CreateMonitor` usage + +A `CreateMonitor` instance is used via the `monitor` property of an AI API's `create()` method ({{domxref("Summarizer.create_static", "Summarizer.create()")}} is shown below). The `monitor` property takes a callback function as a value, the argument of which is the `CreateMonitor` instance. You can then monitor download progress via the instance's {{domxref("CreateMonitor/downloadprogress_event", "downloadprogress")}} event. + +```js +const summarizer = await Summarizer.create({ + sharedContext: + "A general summary to help a user decide if the text is worth reading", + monitor: (monitor) => { + monitor.addEventListener("downloadprogress", (e) => { + console.log(`download progress: ${e.loaded}/${e.total}`); + }); + }, +}); + +const summary = await summarizer.summarize(myText); +``` + +## Specifications + +{{Specifications}} + +## Browser compatibility + +{{Compat}} + +## See also + +- [Using the Summarizer API](/en-US/docs/Web/API/Summarizer_API/Using) +- [Web AI demos](https://chrome.dev/web-ai-demos/) on chrome.dev. diff --git a/files/en-us/web/api/summarizer/availability_static/index.md b/files/en-us/web/api/summarizer/availability_static/index.md new file mode 100644 index 000000000000000..1369323147608cb --- /dev/null +++ b/files/en-us/web/api/summarizer/availability_static/index.md @@ -0,0 +1,118 @@ +--- +title: "Summarizer: availability() static method" +short-title: availability() +slug: Web/API/Summarizer/availability_static +page-type: web-api-static-method +browser-compat: api.Summarizer.availability_static +--- + +{{APIRef("Summarizer API")}}{{securecontext_header}} + +The **`availability()`** static method of the {{domxref("Summarizer")}} interface returns an enumerated value that indicates whether the browser AI model supports (or will support) a given `Summarizer` configuration. + +## Syntax + +```js-nolint +Summarizer.availability() +Summarizer.availability(options) +``` + +### Parameters + +- `options` {{optional_inline}} + + - : An options object specifying a possible configuration for a `Summarizer`. Possible values include: + + - `expectedInputLanguages` + - : An array of strings equal to [BCP 47 language tags](https://en.wikipedia.org/wiki/IETF_language_tag#List_of_common_primary_language_subtags) (as specified in [RFC 5646](https://datatracker.ietf.org/doc/html/rfc5646)) specifying the expected languages of the input text. Defaults to `["en"]`. + - `expectedContextLanguages` + - : An array of strings equal to BCP 47 language tags specifying the expected languages of any provided context strings (either the [`sharedContext`](#sharedContext) passed to the `Summarizer`, or a `context` specified during a {{domxref("Summarizer.summarize", "summarize()")}} or {{domxref("Summarizer.summarizeStreaming", "summarizeStreaming()")}} call). Defaults to `["en"]`. + - `format` + - : An enumerated value specifying the text {{domxref("Summarizer.format", "format")}} you want summaries returned in. Defaults to `markdown`. + - `length` + - : An enumerated value specifying the relative {{domxref("Summarizer.length", "length")}} for the generated summaries. Defaults to `short`. + - `outputLanguage` + - : A string equal to a BCP 47 language tag specifying the expected language of summaries generated by the `Summarizer`. Defaults to `en`. + - `type` + - : An enumerated value specifying the {{domxref("Summarizer.type", "type")}} of summary you want this `Summarizer` to generate. Defaults to `key-points`. + +### Return value + +A {{jsxref("Promise")}} that fulfills with an enumerated value indicating whether support is available (or will be available) for a given `Summarizer` configuration, or `null` if support could not be determined. + +Possible values include: + +- `available` + - : The browser supports the given configuration and can be used immediately. +- `downloadable` + - : The browser supports the given configuration, but it first needs to download an AI model, or some fine-tuning data for the model. +- `downloading` + - : The browser supports the given configuration, but it needs to finish an ongoing download before it can proceed. +- `unavailable` + - : The browser does not support the given configuration. + +### Exceptions + +- `NotAllowedError` {{domxref("DOMException")}} + - : Thrown if usage of the Summarizer API is blocked by a {{httpheader('Permissions-Policy/summarizer','summarizer')}} {{httpheader("Permissions-Policy")}}. +- `NotSupportedError` {{domxref("DOMException")}} + - : Thrown if the provided `context` is not in language the `Summarizer` supports. +- `UnknownError` {{domxref("DOMException")}} + - : Thrown if the `measureInputUsage()` call failed for any other reason, or a reason the user agent did not wish to disclose. + +## Examples + +### Basic `availability()` usage + +```js +const options = { + sharedContext: "This is a scientific article", + type: "key-points", + format: "markdown", + length: "medium", +}; + +const availability = await Summarizer.availability(options); +let summarizer; +if (availability === "unavailable") { + // The Summarizer API isn't usable + return; +} else if (availability === "available") { + // The Summarizer API can be used immediately + summarizer = await Summarizer.create(options); +} else { + // The Summarizer API can be used after the model is downloaded + summarizer = await Summarizer.create(options); + summarizer.addEventListener("downloadprogress", (e) => { + console.log(`Downloaded ${e.loaded * 100}%`); + }); +} +``` + +### Detecting language support + +```js +async function langSupport(lang) { + const availability = await Summarizer.availability({ + expectedInputLanguages: [lang], + }); + return availability; +} + +langSupport("en-US"); +langSupport("fr"); +langSupport("zh-CN"); +``` + +## Specifications + +{{Specifications}} + +## Browser compatibility + +{{Compat}} + +## See also + +- [Using the Summarizer API](/en-US/docs/Web/API/Summarizer_API/Using) +- [Web AI demos](https://chrome.dev/web-ai-demos/) on chrome.dev diff --git a/files/en-us/web/api/summarizer/create_static/index.md b/files/en-us/web/api/summarizer/create_static/index.md new file mode 100644 index 000000000000000..e5050485b94f1c0 --- /dev/null +++ b/files/en-us/web/api/summarizer/create_static/index.md @@ -0,0 +1,88 @@ +--- +title: "Summarizer: create() static method" +short-title: create() +slug: Web/API/Summarizer/create_static +page-type: web-api-static-method +browser-compat: api.Summarizer.create_static +--- + +{{APIRef("Summarizer API")}}{{securecontext_header}} + +The **`create()`** static method of the {{domxref("Summarizer")}} interface creates a new `Summarizer` instance from which to generate summaries. + +> [!NOTE] +> The `create()` method requires [transient activation](/en-US/docs/Glossary/Transient_activation), that is, it must be invoked in response to a user action such as a mouse click or button press. + +## Syntax + +```js-nolint +Summarizer.create() +Summarizer.create(options) +``` + +### Parameters + +- `options` {{optional_inline}} + + - : An object specifying configuration options for the `Summarizer`. Possible values include: + + - `expectedInputLanguages` + - : An array of strings specifying the expected languages of the input text, which should be valid [BCP 47 language tags](https://en.wikipedia.org/wiki/IETF_language_tag#List_of_common_primary_language_subtags) (as specified in [RFC 5646](https://datatracker.ietf.org/doc/html/rfc5646)). Defaults to `["en"]`. + - `expectedContextLanguages` + - : An array of strings specifying the expected languages of any provided context strings (either the [`sharedContext`](#sharedContext) passed to the `Summarizer`, or a `context` specified during a {{domxref("Summarizer.summarize", "summarize()")}} or {{domxref("Summarizer.summarizeStreaming", "summarizeStreaming()")}} call), which should be valid BCP 47 language tags. Defaults to `["en"]`. + - `format` + - : An enumerated value specifying the text {{domxref("Summarizer.format", "format")}} you want summaries returned in. Defaults to `markdown`. + - `length` + - : An enumerated value specifying the relative {{domxref("Summarizer.length", "length")}} for the generated summaries. Defaults to `short`. + - `monitor` + - : A callback function with a {{domxref("CreateMonitor")}} argument that enables monitoring download progress of the AI model. + - `outputLanguage` + - : A string specifying the expected language of summaries generated by the `Summarizer`, which should be a valid BCP 47 language tag. Defaults to `en`. + - `sharedContext` + - : A {{domxref("Summarizer.sharedContext", "sharedContext")}} string describing the context the pieces of text to summarize are being used in, which helps the `Summarizer` generate more suitable summaries. + - `signal` + - : An {{domxref("AbortSignal")}} object instance, which allows the `create()` operation to be aborted via the associated {{domxref("AbortController")}}. + - `type` + - : An enumerated value specifying the {{domxref("Summarizer.type", "type")}} of summary you want this `Summarizer` to generate. Defaults to `key-points`. + +### Return value + +A {{jsxref("Promise")}} that fulfills with a `Summarizer` object instance. + +### Exceptions + +- `NotAllowedError` {{domxref("DOMException")}} + - : Thrown if usage of the Summarizer API is blocked by a {{httpheader('Permissions-Policy/summarizer','summarizer')}} {{httpheader("Permissions-Policy")}}. +- `NotSupportedError` {{domxref("DOMException")}} + - : Thrown if any of the language tags specified in `expectedContextLanguages`, `expectedInputLanguages`, or `outputLanguage` are invalid, or not supported. +- `OperationError` {{domxref("DOMException")}} + - : General-purpose exception thrown if `Summarizer` creation failed for any other reason. + +## Examples + +### Basic `Summarizer` creation + +```js +const summarizer = await Summarizer.create({ + sharedContext: + "A general summary to help a user decide if the text is worth reading", + type: "tl;dr", + length: "short", + format: "markdown", + expectedInputLanguages: ["en-US"], + outputLanguage: "en-US", +}); +``` + +## Specifications + +{{Specifications}} + +## Browser compatibility + +{{Compat}} + +## See also + +- [Using the Summarizer API](/en-US/docs/Web/API/Summarizer_API/Using) +- [Web AI demos](https://chrome.dev/web-ai-demos/) on chrome.dev diff --git a/files/en-us/web/api/summarizer/destroy/index.md b/files/en-us/web/api/summarizer/destroy/index.md new file mode 100644 index 000000000000000..6a2e9618f9002f0 --- /dev/null +++ b/files/en-us/web/api/summarizer/destroy/index.md @@ -0,0 +1,57 @@ +--- +title: "Summarizer: destroy() method" +short-title: destroy() +slug: Web/API/Summarizer/destroy +page-type: web-api-instance-method +status: + - experimental +browser-compat: api.Summarizer.destroy +--- + +{{APIRef("Summarizer API")}}{{SeeCompatTable}} + +The **`destroy()`** method of the {{domxref("Summarizer")}} interface destroys the `Summarizer` instance it is called on. It makes sense to destroy `Summarizer` objects if they are no longer going to be used, as they tie up significant resources in their handling. + +## Syntax + +```js-nolint +destroy() +``` + +### Parameters + +None. + +### Return value + +None ({{jsxref("undefined")}}). + +## Examples + +### Basic `destroy()` usage + +```js +const summarizer = await Summarizer.create({ + sharedContext: + "A general summary to help a user decide if the text is worth reading", + type: "tl;dr", + length: "short", +}); + +// ... + +summarizer.destroy(); +``` + +## Specifications + +{{Specifications}} + +## Browser compatibility + +{{Compat}} + +## See also + +- [Using the Summarizer API](/en-US/docs/Web/API/Summarizer_API/Using) +- [Web AI demos](https://chrome.dev/web-ai-demos/) on chrome.dev diff --git a/files/en-us/web/api/summarizer/expectedcontextlanguages/index.md b/files/en-us/web/api/summarizer/expectedcontextlanguages/index.md new file mode 100644 index 000000000000000..f06dcf6747a0b35 --- /dev/null +++ b/files/en-us/web/api/summarizer/expectedcontextlanguages/index.md @@ -0,0 +1,44 @@ +--- +title: "Summarizer: expectedContextLanguages property" +short-title: expectedContextLanguages +slug: Web/API/Summarizer/expectedContextLanguages +page-type: web-api-instance-property +status: + - experimental +browser-compat: api.Summarizer.expectedContextLanguages +--- + +{{APIRef("Summarizer API")}}{{SeeCompatTable}} + +The **`expectedContextLanguages`** read-only property of the {{domxref("Summarizer")}} interface returns the languages the context strings should be written in. + +## Value + +An array of strings specifying the expected languages of any provided context strings (either the {{domxref("Summarizer.sharedContext")}}, or a `context` specified during a {{domxref("Summarizer.summarize", "summarize()")}} or {{domxref("Summarizer.summarizeStreaming", "summarizeStreaming()")}} call). + +The strings should be valid [BCP 47 language tags](https://en.wikipedia.org/wiki/IETF_language_tag#List_of_common_primary_language_subtags) (as specified in [RFC 5646](https://datatracker.ietf.org/doc/html/rfc5646)). + +## Examples + +```js +const summarizer = await Summarizer.create({ + expectedContextLanguages: ["en-US", "fr"], + // ... +}); + +// Logs "en-US" +console.log(summarizer.expectedContextLanguages[0]); +``` + +## Specifications + +{{Specifications}} + +## Browser compatibility + +{{Compat}} + +## See also + +- [Using the Summarizer API](/en-US/docs/Web/API/Summarizer_API/Using) +- [Web AI demos](https://chrome.dev/web-ai-demos/) on chrome.dev diff --git a/files/en-us/web/api/summarizer/expectedinputlanguages/index.md b/files/en-us/web/api/summarizer/expectedinputlanguages/index.md new file mode 100644 index 000000000000000..c5e323ad050ecb4 --- /dev/null +++ b/files/en-us/web/api/summarizer/expectedinputlanguages/index.md @@ -0,0 +1,44 @@ +--- +title: "Summarizer: expectedInputLanguages property" +short-title: expectedInputLanguages +slug: Web/API/Summarizer/expectedInputLanguages +page-type: web-api-instance-property +status: + - experimental +browser-compat: api.Summarizer.expectedInputLanguages +--- + +{{APIRef("Summarizer API")}}{{SeeCompatTable}} + +The **`expectedInputLanguages`** read-only property of the {{domxref("Summarizer")}} interface returns the languages the `Summarizer` should support. + +## Value + +An array of strings specifying the languages the `Summarizer` should support. + +The strings should be valid [BCP 47 language tags](https://en.wikipedia.org/wiki/IETF_language_tag#List_of_common_primary_language_subtags) (as specified in [RFC 5646](https://datatracker.ietf.org/doc/html/rfc5646)). + +## Examples + +```js +const summarizer = await Summarizer.create({ + expectedInputLanguages: ["en-US", "fr"], + // ... +}); + +// Logs "en-US" +console.log(summarizer.expectedInputLanguages[0]); +``` + +## Specifications + +{{Specifications}} + +## Browser compatibility + +{{Compat}} + +## See also + +- [Using the Summarizer API](/en-US/docs/Web/API/Summarizer_API/Using) +- [Web AI demos](https://chrome.dev/web-ai-demos/) on chrome.dev diff --git a/files/en-us/web/api/summarizer/format/index.md b/files/en-us/web/api/summarizer/format/index.md new file mode 100644 index 000000000000000..d3ea78836538957 --- /dev/null +++ b/files/en-us/web/api/summarizer/format/index.md @@ -0,0 +1,47 @@ +--- +title: "Summarizer: format property" +short-title: format +slug: Web/API/Summarizer/format +page-type: web-api-instance-property +status: + - experimental +browser-compat: api.Summarizer.format +--- + +{{APIRef("Summarizer API")}}{{SeeCompatTable}} + +The **`format`** read-only property of the {{domxref("Summarizer")}} interface returns the text format summaries will be returned in. + +## Value + +An enumerated value specifying the format of returned summaries. Possible values are: + +- `markdown` + - : Summaries contain no formatting. +- `plain-text` + - : Summaries contain markdown formatting (conforming to the [CommonMark](https://spec.commonmark.org/) spec). + +## Examples + +```js +const summarizer = await Summarizer.create({ + format: "plain-text", + // ... +}); + +// Logs "plain-text" +console.log(summarizer.format); +``` + +## Specifications + +{{Specifications}} + +## Browser compatibility + +{{Compat}} + +## See also + +- [Using the Summarizer API](/en-US/docs/Web/API/Summarizer_API/Using) +- [Web AI demos](https://chrome.dev/web-ai-demos/) on chrome.dev diff --git a/files/en-us/web/api/summarizer/index.md b/files/en-us/web/api/summarizer/index.md new file mode 100644 index 000000000000000..29af5c781d40b52 --- /dev/null +++ b/files/en-us/web/api/summarizer/index.md @@ -0,0 +1,103 @@ +--- +title: Summarizer +slug: Web/API/Summarizer +page-type: web-api-interface +status: + - experimental +browser-compat: api.Summarizer +--- + +{{APIRef("Summarizer API")}}{{SeeCompatTable}} + +The **`Summarizer`** interface of the {{domxref("Summarizer API", "Summarizer API", "", "nocode")}} contains all the functionality for this API, including checking AI model availability, creating a new `Summarizer` instance, using it to generate a new summary, and more. + +{{InheritanceDiagram}} + +## Instance properties + +- {{domxref("Summarizer.expectedContextLanguages", "expectedContextLanguages")}} {{ReadOnlyInline}} {{Experimental_Inline}} + - : The languages the context strings should be written in. +- {{domxref("Summarizer.expectedInputLanguages", "expectedInputLanguages")}} {{ReadOnlyInline}} {{Experimental_Inline}} + - : The languages the `Summarizer` should support. +- {{domxref("Summarizer.format", "format")}} {{ReadOnlyInline}} {{Experimental_Inline}} + - : The text format summaries will be returned in. +- {{domxref("Summarizer.inputQuota", "inputQuota")}} {{ReadOnlyInline}} {{Experimental_Inline}} + - : The input quota available to the browser for generating summaries. +- {{domxref("Summarizer.length", "length")}} {{ReadOnlyInline}} {{Experimental_Inline}} + - : The relative length of the generated summaries. +- {{domxref("Summarizer.outputLanguage", "outputLanguage")}} {{ReadOnlyInline}} {{Experimental_Inline}} + - : The language the summary should be generated in. +- {{domxref("Summarizer.sharedContext", "sharedContext")}} {{ReadOnlyInline}} {{Experimental_Inline}} + - : A text string describing the context the pieces of text to summarize are being used in, which helps the `Summarizer` generate more suitable summaries. +- {{domxref("Summarizer.type", "type")}} {{ReadOnlyInline}} {{Experimental_Inline}} + - : The type of summary that will generated by the `Summarizer`. + +## Static methods + +- {{domxref("Summarizer.availability_static", "availability()")}} {{Experimental_Inline}} + - : Returns an enumerated value that indicates whether the browser AI model supports a given `Summarizer` configuration. +- {{domxref("Summarizer.create_static", "create()")}} {{Experimental_Inline}} + - : Creates a new `Summarizer` instance from which to generate summaries. + +## Instance methods + +- {{domxref("Summarizer.destroy", "destroy()")}} {{Experimental_Inline}} + - : Destroys the `Summarizer` instance it is called on. +- {{domxref("Summarizer.measureInputUsage", "measureInputUsage()")}} {{Experimental_Inline}} + - : Reports how much input quota would be used by a summarize operation for a given text input. +- {{domxref("Summarizer.summarize", "summarize()")}} {{Experimental_Inline}} + - : Generates a new summary string. +- {{domxref("Summarizer.summarizeStreaming", "summarizeStreaming()")}} {{Experimental_Inline}} + - : Generates a new summary as a {{domxref("ReadableStream")}}. + +## Examples + +See [Using the Summarizer API](/en-US/docs/Web/API/Summarizer_API/Using) for a complete example. + +### Creating a `Summarizer` instance + +```js +const summarizer = await Summarizer.create({ + sharedContext: + "A general summary to help a user decide if the text is worth reading", + type: "tl;dr", + length: "short", + format: "markdown", + expectedInputLanguages: ["en-US"], + outputLanguage: "en-US", +}); +``` + +### Generating a summary + +```js +const summary = await summarizer.summarize(myTextString); +console.log(summary); +``` + +### Generating a summary stream + +```js +const stream = summarizer.summarizeStreaming(myTextString); +let summary = ""; + +for await (const chunk of stream) { + summary += chunk; +} + +console.log("Stream complete"); +summaryOutput.textContent = summary; +``` + +## Specifications + +{{Specifications}} + +## Browser compatibility + +{{Compat}} + +## See also + +- [Using the Summarizer API](/en-US/docs/Web/API/Summarizer_API/Using) +- [Web AI demos](https://chrome.dev/web-ai-demos/) on chrome.dev diff --git a/files/en-us/web/api/summarizer/inputquota/index.md b/files/en-us/web/api/summarizer/inputquota/index.md new file mode 100644 index 000000000000000..dde2b3d19302edd --- /dev/null +++ b/files/en-us/web/api/summarizer/inputquota/index.md @@ -0,0 +1,58 @@ +--- +title: "Summarizer: inputQuota property" +short-title: inputQuota +slug: Web/API/Summarizer/inputQuota +page-type: web-api-instance-property +status: + - experimental +browser-compat: api.Summarizer.inputQuota +--- + +{{APIRef("Summarizer API")}}{{SeeCompatTable}} + +The **`inputQuota`** read-only property of the {{domxref("Summarizer")}} interface returns the input quota available to the browser for generating summaries. + +## Value + +A number specifying the available input quota. This number is implementation-dependent. For example, it might be {{jsxref("infinity")}} if there are no limits beyond the user's memory and the maximum length of JavaScript strings, or it might be a number of tokens in the case of AI models that use a token/credits scheme. + +## Examples + +### Checking if you have sufficient quota + +In the below snippet, we create a new `Summarizer` instance using {{domxref("Summarizer.create_static", "create()")}}, then return the total input quota via `inputQuota` and the input quota usage for a summarizing a particular text string via {{domxref("Summarizer.measureInputUsage", "measureInputUsage()")}}. + +We then test to see if the individual input usage for that string is great than the total available quota. If so, we throw an appropriate error; it not, we commence summarizing the string using {{domxref("Summarizer.summarize", "summarize()")}}. + +```js +const summarizer = await Summarizer.create({ + sharedContext: + "A general summary to help a user decide if the text is worth reading", + type: "tl;dr", + length: "short", +}); + +const totalInputQuota = summarizer.inputQuota; +const inputUsage = await summarizer.measureInputUsage(myTextString); + +if (inputUsage > totalInputQuota) { + throw new Error("Boo, insufficient quota to generate a summary."); +} else { + console.log("Yay, quota available to generate a summary."); + const summary = await summarizer.summarize(myTextString); + // ... +} +``` + +## Specifications + +{{Specifications}} + +## Browser compatibility + +{{Compat}} + +## See also + +- [Using the Summarizer API](/en-US/docs/Web/API/Summarizer_API/Using) +- [Web AI demos](https://chrome.dev/web-ai-demos/) on chrome.dev diff --git a/files/en-us/web/api/summarizer/length/index.md b/files/en-us/web/api/summarizer/length/index.md new file mode 100644 index 000000000000000..f90f48c902f6bcf --- /dev/null +++ b/files/en-us/web/api/summarizer/length/index.md @@ -0,0 +1,60 @@ +--- +title: "Summarizer: length property" +short-title: length +slug: Web/API/Summarizer/length +page-type: web-api-instance-property +status: + - experimental +browser-compat: api.Summarizer.length +--- + +{{APIRef("Summarizer API")}}{{SeeCompatTable}} + +The **`length`** read-only property of the {{domxref("Summarizer")}} interface returns the relative length of the generated summaries. + +## Value + +An enumerated value specifying the relative length of the generated summaries, the exact nature of which depends on the `Summarizer` {{domxref("Summarizer.type", "type")}} value. + +Possible values are: + +- `short` + - : A "short" summary + - For `type` `tl;dr` and `teaser`, the summary should fit into one sentence. + - For `type` `key-points`, the summary should be no more than three bullet points. + - For `type` `headline`, the summary should be no more than 12 words. +- `medium` + - : A "medium" summary + - For `type` `tl;dr` and `teaser`, the summary should fit into one short paragraph. + - For `type` `key-points`, the summary should be no more than five bullet points. + - For `type` `headline`, the summary should be no more than 17 words. +- `long` + - : A "long" summary + - For `type` `tl;dr` and `teaser`, the summary should fit into one paragraph. + - For `type` `key-points`, the summary should be no more than seven bullet points. + - For `type` `headline`, the summary should be no more than 22 words. + +## Examples + +```js +const summarizer = await Summarizer.create({ + length: "medium", + // ... +}); + +// Logs "medium" +console.log(summarizer.length); +``` + +## Specifications + +{{Specifications}} + +## Browser compatibility + +{{Compat}} + +## See also + +- [Using the Summarizer API](/en-US/docs/Web/API/Summarizer_API/Using) +- [Web AI demos](https://chrome.dev/web-ai-demos/) on chrome.dev. diff --git a/files/en-us/web/api/summarizer/measureinputusage/index.md b/files/en-us/web/api/summarizer/measureinputusage/index.md new file mode 100644 index 000000000000000..dc83aabe2dc235c --- /dev/null +++ b/files/en-us/web/api/summarizer/measureinputusage/index.md @@ -0,0 +1,87 @@ +--- +title: "Summarizer: measureInputUsage() method" +short-title: measureInputUsage() +slug: Web/API/Summarizer/measureInputUsage +page-type: web-api-instance-method +status: + - experimental +browser-compat: api.Summarizer.measureInputUsage +--- + +{{APIRef("Summarizer API")}}{{SeeCompatTable}} + +The **`measureInputUsage()`** method of the {{domxref("Summarizer")}} interface reports how much {{domxref("Summarizer.inputQuota", "inputQuota")}} would be used by a summarize operation for a given text input. + +## Syntax + +```js-nolint +measureInputUsage(input) +measureInputUsage(input, options) +``` + +### Parameters + +- `input` + - : A string representing the input text you want an input usage measurement for. +- `options` {{optional_inline}} + - : An object specifying configuration options for the `measureInputUsage()` operation. Possible values include: + - `context` + - : A string describing the context the input text would be used in, to help generate a more suitable summary. + - `signal` + - : An {{domxref("AbortSignal")}} object instance, which allows the `measureInputUsage()` operation to be aborted via the associated {{domxref("AbortController")}}. + +### Return value + +A {{jsxref("Promise")}} that fulfills with a number specifying the {{domxref("Summarizer.inputQuota", "inputQuota")}} usage of the given input text. + +### Exceptions + +- `NotAllowedError` {{domxref("DOMException")}} + - : Thrown if usage of the Summarizer API is blocked by a {{httpheader('Permissions-Policy/summarizer','summarizer')}} {{httpheader("Permissions-Policy")}}. +- `NotReadableError` {{domxref("DOMException")}} + - : Thrown if the output summary was filtered by the user agent, for example because it was detected to be harmful, inaccurate, or nonsensical. +- `NotSupportedError` {{domxref("DOMException")}} + - : Thrown if the provided `context` is not in language the `Summarizer` supports. +- `UnknownError` {{domxref("DOMException")}} + - : Thrown if the `measureInputUsage()` call failed for any other reason, or a reason the user agent did not wish to disclose. + +## Examples + +### Checking if you have sufficient quota + +In the below snippet, we create a new `Summarizer` instance using {{domxref("Summarizer.create_static", "create()")}}, then return the total input quota via {{domxref("Summarizer.inputQuota", "inputQuota")}} and the input quota usage for a summarizing a particular text string via `measureInputUsage()`. + +We then test to see if the individual input usage for that string is great than the total available quota. If so, we throw an appropriate error; it not, we commence summarizing the string using {{domxref("Summarizer.summarize", "summarize()")}}. + +```js +const summarizer = await Summarizer.create({ + sharedContext: + "A general summary to help a user decide if the text is worth reading", + type: "tl;dr", + length: "short", +}); + +const totalInputQuota = summarizer.inputQuota; +const inputUsage = await summarizer.measureInputUsage(myTextString); + +if (inputUsage > totalInputQuota) { + throw new Error("Boo, insufficient quota to generate a summary."); +} else { + console.log("Yay, quota available to generate a summary."); + const summary = await summarizer.summarize(myTextString); + // ... +} +``` + +## Specifications + +{{Specifications}} + +## Browser compatibility + +{{Compat}} + +## See also + +- [Using the Summarizer API](/en-US/docs/Web/API/Summarizer_API/Using) +- [Web AI demos](https://chrome.dev/web-ai-demos/) on chrome.dev diff --git a/files/en-us/web/api/summarizer/outputlanguage/index.md b/files/en-us/web/api/summarizer/outputlanguage/index.md new file mode 100644 index 000000000000000..66cdb4dc0eb757c --- /dev/null +++ b/files/en-us/web/api/summarizer/outputlanguage/index.md @@ -0,0 +1,44 @@ +--- +title: "Summarizer: outputLanguage property" +short-title: outputLanguage +slug: Web/API/Summarizer/outputLanguage +page-type: web-api-instance-property +status: + - experimental +browser-compat: api.Summarizer.outputLanguage +--- + +{{APIRef("Summarizer API")}}{{SeeCompatTable}} + +The **`outputLanguage`** read-only property of the {{domxref("Summarizer")}} interface returns the language the summary should be generated in. + +## Value + +A string specifying the language the summary should be generated in. + +The string should be a valid [BCP 47 language tag](https://en.wikipedia.org/wiki/IETF_language_tag#List_of_common_primary_language_subtags) (as specified in [RFC 5646](https://datatracker.ietf.org/doc/html/rfc5646)). + +## Examples + +```js +const summarizer = await Summarizer.create({ + outputLanguage: "en-US", + // ... +}); + +// Logs "en-US" +console.log(summarizer.outputLanguage); +``` + +## Specifications + +{{Specifications}} + +## Browser compatibility + +{{Compat}} + +## See also + +- [Using the Summarizer API](/en-US/docs/Web/API/Summarizer_API/Using) +- [Web AI demos](https://chrome.dev/web-ai-demos/) on chrome.dev diff --git a/files/en-us/web/api/summarizer/sharedcontext/index.md b/files/en-us/web/api/summarizer/sharedcontext/index.md new file mode 100644 index 000000000000000..911f92ce1b5bc60 --- /dev/null +++ b/files/en-us/web/api/summarizer/sharedcontext/index.md @@ -0,0 +1,43 @@ +--- +title: "Summarizer: sharedContext property" +short-title: sharedContext +slug: Web/API/Summarizer/sharedContext +page-type: web-api-instance-property +status: + - experimental +browser-compat: api.Summarizer.sharedContext +--- + +{{APIRef("Summarizer API")}}{{SeeCompatTable}} + +The **`sharedContext`** read-only property of the {{domxref("Summarizer")}} interface returns a string describing the context the pieces of text to summarize are being used in. This helps the `Summarizer` to generate more suitable summaries. + +## Value + +A string. + +## Examples + +```js +const summarizer = await Summarizer.create({ + sharedContext: + "A general summary to help a user decide if the text is worth reading", + // ... +}); + +// Logs "A general summary to help a user ..." +console.log(summarizer.sharedContext); +``` + +## Specifications + +{{Specifications}} + +## Browser compatibility + +{{Compat}} + +## See also + +- [Using the Summarizer API](/en-US/docs/Web/API/Summarizer_API/Using) +- [Web AI demos](https://chrome.dev/web-ai-demos/) on chrome.dev diff --git a/files/en-us/web/api/summarizer/summarize/index.md b/files/en-us/web/api/summarizer/summarize/index.md new file mode 100644 index 000000000000000..18f0aec9422b2f9 --- /dev/null +++ b/files/en-us/web/api/summarizer/summarize/index.md @@ -0,0 +1,79 @@ +--- +title: "Summarizer: summarize() method" +short-title: summarize() +slug: Web/API/Summarizer/summarize +page-type: web-api-instance-method +status: + - experimental +browser-compat: api.Summarizer.summarize +--- + +{{APIRef("Summarizer API")}}{{SeeCompatTable}} + +The **`summarize()`** method of the {{domxref("Summarizer")}} interface generates a new summary string. + +## Syntax + +```js-nolint +summarize(input) +summarize(input, options) +``` + +### Parameters + +- `input` + - : A string representing the text to be summarized. +- `options` {{optional_inline}} + - : An object specifying configuration options for the `summarize()` operation. Possible values include: + - `context` + - : A string describing the context the input text is being used in, which helps the `Summarizer` generate a more suitable summary. + - `signal` + - : An {{domxref("AbortSignal")}} object instance, which allows the `summarize()` operation to be aborted via the associated {{domxref("AbortController")}}. + +### Return value + +A {{jsxref("Promise")}} that fulfills with a string containing the generated summary. + +### Exceptions + +- `InvalidStateError` {{domxref("DOMException")}} + - : Thrown if the current {{domxref("Document")}} is not active. +- `NotAllowedError` {{domxref("DOMException")}} + - : Thrown if usage of the Summarizer API is blocked by a {{httpheader('Permissions-Policy/summarizer','summarizer')}} {{httpheader("Permissions-Policy")}}. +- `NotReadableError` {{domxref("DOMException")}} + - : Thrown if the output summary was filtered by the user agent, for example because it was detected to be harmful, inaccurate, or nonsensical. +- `NotSupportedError` {{domxref("DOMException")}} + - : Thrown if the provided `context` is not in language the `Summarizer` supports. +- `QuotaExceededError` {{domxref("DOMException")}} + - : Thrown if the summarize operation exceeds the available {{domxref("Summarize.inputQuota", "inputQuota")}}. +- `UnknownError` {{domxref("DOMException")}} + - : Thrown if the `summarize()` call failed for any other reason, or a reason the user agent did not wish to disclose. + +## Examples + +### Basic `summarize()` usage + +```js +const summarizer = await Summarizer.create({ + sharedContext: + "A general summary to help a user decide if the text is worth reading", + type: "tl;dr", + length: "short", +}); + +const summary = await summarizer.summarize(myTextString); +console.log(summary); +``` + +## Specifications + +{{Specifications}} + +## Browser compatibility + +{{Compat}} + +## See also + +- [Using the Summarizer API](/en-US/docs/Web/API/Summarizer_API/Using) +- [Web AI demos](https://chrome.dev/web-ai-demos/) on chrome.dev diff --git a/files/en-us/web/api/summarizer/summarizestreaming/index.md b/files/en-us/web/api/summarizer/summarizestreaming/index.md new file mode 100644 index 000000000000000..ac06979a07772be --- /dev/null +++ b/files/en-us/web/api/summarizer/summarizestreaming/index.md @@ -0,0 +1,86 @@ +--- +title: "Summarizer: summarizeStreaming() method" +short-title: summarizeStreaming() +slug: Web/API/Summarizer/summarizeStreaming +page-type: web-api-instance-method +status: + - experimental +browser-compat: api.Summarizer.summarizeStreaming +--- + +{{APIRef("Summarizer API")}}{{SeeCompatTable}} + +The **`summarizeStreaming()`** method of the {{domxref("Summarizer")}} interface generates a new summary as a {{domxref("ReadableStream")}}. + +## Syntax + +```js-nolint +summarizeStreaming(input) +summarizeStreaming(input, options) +``` + +### Parameters + +- `input` + - : A string representing the text to be summarized. +- `options` {{optional_inline}} + - : An object specifying configuration options for the `summarizeStreaming()` operation. Possible values include: + - `context` + - : A string describing the context the input text is being used in, which helps the `Summarizer` generate a more suitable summary. + - `signal` + - : An {{domxref("AbortSignal")}} object instance, which allows the `summarizeStreaming()` operation to be aborted via the associated {{domxref("AbortController")}}. + +### Return value + +A {{domxref("ReadableStream")}} containing the generated summary. + +### Exceptions + +- `InvalidStateError` {{domxref("DOMException")}} + - : Thrown if the current {{domxref("Document")}} is not active. +- `NotAllowedError` {{domxref("DOMException")}} + - : Thrown if usage of the Summarizer API is blocked by a {{httpheader('Permissions-Policy/summarizer','summarizer')}} {{httpheader("Permissions-Policy")}}. +- `NotReadableError` {{domxref("DOMException")}} + - : Thrown if the output summary was filtered by the user agent, for example because it was detected to be harmful, inaccurate, or nonsensical. +- `NotSupportedError` {{domxref("DOMException")}} + - : Thrown if the provided `context` is not in language the `Summarizer` supports. +- `QuotaExceededError` {{domxref("DOMException")}} + - : Thrown if the summarize operation exceeds the available {{domxref("Summarize.inputQuota", "inputQuota")}}. +- `UnknownError` {{domxref("DOMException")}} + - : Thrown if the `summarizeStreaming()` call failed for any other reason, or a reason the user agent did not wish to disclose. + +## Examples + +### Basic `summarizeStreaming()` usage + +```js +const summarizer = await Summarizer.create({ + sharedContext: + "A general summary to help a user decide if the text is worth reading", + type: "tl;dr", + length: "short", +}); + +const stream = summarizer.summarizeStreaming(myTextString); +let summary = ""; + +for await (const chunk of stream) { + summary += chunk; +} + +console.log("Stream complete"); +summaryOutput.textContent = summary; +``` + +## Specifications + +{{Specifications}} + +## Browser compatibility + +{{Compat}} + +## See also + +- [Using the Summarizer API](/en-US/docs/Web/API/Summarizer_API/Using) +- [Web AI demos](https://chrome.dev/web-ai-demos/) on chrome.dev diff --git a/files/en-us/web/api/summarizer/type/index.md b/files/en-us/web/api/summarizer/type/index.md new file mode 100644 index 000000000000000..d2de723b985918c --- /dev/null +++ b/files/en-us/web/api/summarizer/type/index.md @@ -0,0 +1,51 @@ +--- +title: "Summarizer: type property" +short-title: type +slug: Web/API/Summarizer/type +page-type: web-api-instance-property +status: + - experimental +browser-compat: api.Summarizer.type +--- + +{{APIRef("Summarizer API")}}{{SeeCompatTable}} + +The **`type`** read-only property of the {{domxref("Summarizer")}} interface returns the type of summary that will generated by the `Summarizer`. + +## Value + +An enumerated value specifying the form the summary will be generated in; possible values are: + +- `headline` + - : A single sentence article headline, capturing the main point of the input text. +- `key-points` + - : A bulleted list specifying the most important points presented in the input text. +- `teaser` + - : A "teaser" paragraph summarizing the most interesting or intriguing points of the input text, designed to draw the reader in to read more. +- `tl;dr` + - : A short, concise overview, designed as a summary for a busy reader. + +## Examples + +```js +const summarizer = await Summarizer.create({ + type: "tl;dr", + // ... +}); + +// Logs "tl;dr" +console.log(summarizer.type); +``` + +## Specifications + +{{Specifications}} + +## Browser compatibility + +{{Compat}} + +## See also + +- [Using the Summarizer API](/en-US/docs/Web/API/Summarizer_API/Using) +- [Web AI demos](https://chrome.dev/web-ai-demos/) on chrome.dev diff --git a/files/en-us/web/api/summarizer_api/index.md b/files/en-us/web/api/summarizer_api/index.md new file mode 100644 index 000000000000000..46a33e7747051aa --- /dev/null +++ b/files/en-us/web/api/summarizer_api/index.md @@ -0,0 +1,67 @@ +--- +title: Summarizer API +slug: Web/API/Summarizer_API +page-type: web-api-overview +status: + - experimental +browser-compat: api.Summarizer +spec-urls: https://webmachinelearning.github.io/writing-assistance-apis/#summarizer-api +--- + +{{SeeCompatTable}}{{DefaultAPISidebar("Summarizer API")}} + +The **Summarizer API** summarizes a given body of text via a browser's internal AI model. + +## Concepts and usage + +Writing a summary of a larger body of text is a common writing task, and one that AI is well-suited to. Typical use cases include: + +- Providing a summary of a full article so the reader can judge whether to read the whole thing. +- Summarizing a meeting transcript so those joining the meeting late can get up to speed with what they've missed. +- Summarizing a set of product reviews to quickly communicate overall sentiment. + +The Summarizer API provides an asynchronous ({{jsxref("Promise")}}-based) mechanism for a website to feed a body of text into the browser's own internal AI model and request that it returns a summary of the text based on specified options. + +This is done using the functionality made available by the {{domxref("Summarizer")}} interface, in a two-step process: + +1. Create a `Summarizer` object instance using the {{domxref("Summarizer.create_static", "Summarizer.create()")}} static method, specifying options for what kind of summary you want written. Options include length, type (for example, "tl;dr" or key points), format (plain text or markdown), and input and output languages. + > [!NOTE] + > If you want to check whether the browser AI model is able to support your preferences, you can do so with the {{domxref("Summarizer.availability_static", "Summarizer.availability()")}} static method. +2. Run the {{domxref("Summarizer.summarize()")}} instance method to request the summary. + +After a `Summarizer` instance has been created, you can remove it again using the {{domxref("Summarizer.destroy()")}} instance method. You can also cancel a pending `create()` or `summarize()` operation using an {{domxref("AbortController")}}. + +See [Using the Summarizer API](/en-US/docs/Web/API/Summarizer_API/Using) for a walkthrough of how the API works. + +## Interfaces + +- {{domxref("Summarizer")}} {{Experimental_Inline}} + - : Contains all the functionality for the Summarizer API, including checking AI model availability, creating a new `Summarizer` instance, using it to generate a new summary, and more. + +## HTTP headers + +- {{httpheader("Permissions-Policy")}}; the {{httpheader('Permissions-Policy/summarizer','summarizer')}} directive + - : Controls access to the Summarizer API. Where a policy specifically disallows the use of the Summarizer API, any attempts to call the API's methods will fail with a `NotAllowedError` {{domxref("DOMException")}}. + +## Security considerations + +The specification requires that a user has recently interacted with the page when creating `Summarizer` objects ([transient user activation](/en-US/docs/Web/Security/User_activation) is required). + +In addition, the specification controls access to the API via {{httpheader('Permissions-Policy/summarizer','summarizer')}} {{httpheader("Permissions-Policy")}} directives. + +## Examples + +For a full example, see [Using the Summarizer API](/en-US/docs/Web/API/Summarizer_API/Using). + +## Specifications + +{{Specifications}} + +## Browser compatibility + +{{Compat}} + +## See also + +- [Summarize with built-in AI](https://developer.chrome.com/docs/ai/summarizer-api) on developer.chrome.com (2025) +- [Web AI demos](https://chrome.dev/web-ai-demos/) on chrome.dev diff --git a/files/en-us/web/api/summarizer_api/using/index.md b/files/en-us/web/api/summarizer_api/using/index.md new file mode 100644 index 000000000000000..818dbd604e82cce --- /dev/null +++ b/files/en-us/web/api/summarizer_api/using/index.md @@ -0,0 +1,338 @@ +--- +title: Using the Summarizer API +slug: Web/API/Summarizer_API/Using +page-type: guide +--- + +{{DefaultAPISidebar("Summarizer API")}} + +The [Summarizer API](/en-US/docs/Web/API/Summarizer_API) provides an asynchronous ({{jsxref("Promise")}}-based) mechanism for a website to feed a body of text into the browser's own internal AI model and request that it returns a summary of the text based on specified options. This article explains how to use the fundamentals of the Summarizer API. + +## Creating a summarizer + +All of the Summarizer API's functionality is accessed through a single interface — {{domxref("Summarizer")}}. + +The first step in getting the browser AI model to output a summary is to create a `Summarizer` object instance. This is done using the {{domxref("Summarizer.create_static", "Summarizer.create()")}} static method, which takes an options object as an argument specifying options for what kind of summary you want written: + +```js +const summarizer = await Summarizer.create({ + sharedContext: + "A general summary to help a user decide if the text is worth reading", + type: "tl;dr", + length: "short", + format: "markdown", + expectedInputLanguages: ["en-US"], + outputLanguage: "en-US", +}); +``` + +The {{domxref("Summarizer.sharedContext", "sharedContext")}} option provides a string that helps the AI model write a more suitable summary for the context the text is being used in, while the {{domxref("Summarizer.type", "type")}} specifies what kind of summary you want to provide, like key bullet points or a "tl;dr" summary. + +We also specify the desired {{domxref("Summarizer.length", "length")}}, output {{domxref("Summarizer.format", "format")}}, {{domxref("Summarizer.expectedInputLanguages", "expectedInputLanguages")}}, and desired {{domxref("Summarizer.outputLanguage", "outputLanguage")}}. If the input and output languages are not specified, the language of the input text is auto-detected, and the output language will match the input language. + +If the browser's AI model does not support the specified input or output languages, an error is thrown. + +> [!NOTE] +> See the {{domxref("Summarizer.create_static", "create()")}} reference page for the full list of available options. + +## Checking configuration support + +Before creating a `Summarizer`, you can check whether your desired configuration is supported by the current browser using the {{domxref("Summarizer.availability_static", "Summarizer.availability()")}} static method. For example: + +```js +const availability = await Summarizer.availability({ + type: "tl;dr", + length: "short", + format: "markdown", + expectedInputLanguages: ["en-US"], + outputLanguage: "en-US", +}); +``` + +This method returns an enumerated value indicating whether support is, or will be available for the specified set of options: + +- `downloadable` means that the browser supports the requested options, but it first needs to download an AI model, or some fine-tuning data for the model. +- `downloading` means that the browser supports the requested options, but needs to finish an ongoing download before it can proceed. +- `available` means that the browser supports the given configuration without requiring any new downloads. +- `unavailable` means that the browser does not support the given configuration. + +If a download is required, it will be started automatically by the browser once a `Summarizer` instance is created using the `create()` method. You can track download progress automatically using a [monitor](#monitoring_download_progress). + +## Generating a summary + +When you've determined that your desired configuration works and you've created a `Summarizer` instance, you can use it to generate a summary by calling the {{domxref("Summarizer.summarize()")}} instance method on it, passing it the text to summarize as an argument. + +```js +const summary = await summarizer.summarize(myTextString); +console.log(summary); +``` + +It also optionally accepts an options object as a second argument that can accept a `context` string specific to this summary, and an abort {{domxref("AbortSignal", "signal")}} allowing the summary request to be aborted (see next section). + +There is a streaming version of the `summarize()` method available — {{domxref("Summarizer.summarizeStreaming()")}} — that allows you to return the summary as a {{domxref("ReadableStream")}}: + +```js +const stream = summarizer.summarizeStreaming(myTextString); +let summary = ""; + +for await (const chunk of stream) { + summary += chunk; +} + +console.log("Stream complete"); +summaryOutput.textContent = summary; +``` + +After a `Summarizer` instance has been created, you can remove it again using the {{domxref("Summarizer.destroy()")}} instance method. It makes sense to destroy `Summarizer` objects if they are no longer going to be used, as they tie up significant resources in their handling. + +## Cancelling summarize operations + +You can cancel a pending `create()`, `summarize()`, or `summarizeStreaming()` operation using an {{domxref("AbortController")}}: + +```js +const controller = new AbortController(); +const summary = await summarizer.summarize(myTextString, { + signal: controller.signal, +}); + +// ... + +controller.abort(); +``` + +## Monitoring download progress + +If the AI model for a particular summarizer is downloading (`availability()` returns `downloadable` and `downloading`), it is helpful to provide the user with feedback to tell them how long they need to wait before the operation completes. + +The `Summarizer.create()` method can accept a `monitor` property, the value of which is a callback function that takes a {{domxref("CreateMonitor")}} instance as an argument. `CreateMonitor` has a {{domxref("CreateMonitor/downloadprogress_event", "downloadprogress")}} event available, which fires when progress is made on downloading the AI model. +You can use this event to expose loading progress data: + +```js +const summarizer = await Summarizer.create({ + sharedContext: + "A general summary to help a user decide if the text is worth reading", + type: "tl;dr", + length: "short", + monitor: (monitor) => { + monitor.addEventListener("downloadprogress", (e) => { + console.log(`Downloaded ${Math.floor(e.loaded * 100)}%`); + }); + }, +}); +``` + +## Usage quotas + +Some implementations have an input quota that governs how many operations a website can request in a given period. The total quota can be accessed via the {{domxref("Summarizer.inputQuota")}} property, while the quota usage for a particular summary operation can be returned using the {{domxref("Summarizer.measureInputUsage()")}} method: + +For example, in the below snippet, we create a new `Summarizer` instance using {{domxref("Summarizer.create_static", "create()")}}, then return the total input quota via `inputQuota` and the input quota usage for a summarizing a particular text string via `measureInputUsage()`. + +We then test to see if the individual input usage for that string is great than the total available quota. If so, we throw an appropriate error; it not, we commence summarizing the string using {{domxref("Summarizer.summarize", "summarize()")}}. + +```js +const summarizer = await Summarizer.create({ + sharedContext: + "A general summary to help a user decide if the text is worth reading", + type: "tl;dr", + length: "short", +}); + +const totalInputQuota = summarizer.inputQuota; +const inputUsage = await summarizer.measureInputUsage(myTextString); + +if (inputUsage > totalInputQuota) { + throw new Error("Boo, insufficient quota to generate a summary."); +} else { + console.log("Yay, quota available to generate a summary."); + const summary = await summarizer.summarize(myTextString); + // ... +} +``` + +If you try to run a summarize operation that exceeds the available quota, a `QuotaExceededError` {{domxref("DOMException")}} will be thrown. + +## Complete example + +Let's look at a complete example that demonstrates the Summarizer API in action. + +### HTML + +In our markup, we first define an input {{htmlelement("form")}} that allows the user to set the text to summarize, and configuration options. This includes a {{htmlelement("textarea")}} for entering the text to be summarized, an {{htmlelement("output")}} element to display the character count of the text set by the user, and two {{htmlelement("select")}} elements for choosing a summarizer {{domxref("Summarizer.type", "type")}} and {{domxref("Summarizer.length", "length")}}. + +```html live-sample___summarizer-example +

Input

+ +
+
+ + + Input character count: +
+
+ + +
+
+ + +
+ +
+``` + +The second half of our markup includes a {{htmlelement("p")}} element to display the generated summary, and a second {{htmlelement("output")}} element to display the summary character count. + +```html live-sample___summarizer-example +

Summary output

+ +

+Output summary character count: 0 +``` + +```css hidden live-sample___summarizer-example +* { + box-sizing: border-box; +} + +html { + font-family: Arial, Helvetica, sans-serif; +} + +body { + max-width: 600px; + margin: 0 auto; +} + +form div { + display: flex; + flex-direction: column; + gap: 10px; + margin-bottom: 20px; +} + +select, +textarea, +.summary-output { + padding: 5px; +} + +.summary-output { + min-height: 150px; + border: 1px solid black; + width: 100%; + display: block; +} + +.error { + color: red; +} +``` + +Note that we won't show the CSS for this example, as none of it is relevant to understanding the Summarizer API. + +### JavaScript + +In our script, we start off by grabbing references to the `
`, `