generated from explainers-by-googlers/template
-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathindex.bs
1328 lines (849 loc) · 63.2 KB
/
index.bs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<pre class="metadata">
Title: Writing Assistance APIs
Shortname: writing-assistance
Level: None
Status: CG-DRAFT
Group: webml
Repository: webmachinelearning/writing-assistance-apis
URL: https://webmachinelearning.github.io/writing-assistance-apis
Editor: Domenic Denicola, Google https://www.google.com/, d@domenic.me, https://domenic.me/
Abstract: The summarizer, writer, and rewriter APIs provide high-level interfaces to call on a browser or operating system's built-in language model to help with writing tasks.
Markup Shorthands: markdown yes, css no
Complain About: accidental-2119 yes, missing-example-ids yes
Assume Explicit For: yes
Default Biblio Status: current
Boilerplate: omit conformance
Indent: 2
Die On: warning
</pre>
<pre class="link-defaults">
spec:infra; type:dfn; text:user agent
</pre>
<pre class="anchors">
urlPrefix: https://tc39.es/ecma402/; spec: ECMA-402
type: dfn
text: [[AvailableLocales]]; url: sec-internal-slots
text: Unicode canonicalized locale identifier; url: sec-language-tags
type: abstract-op
text: LookupMatchingLocaleByBestFit; url: sec-lookupmatchinglocalebybestfit
text: IsStructurallyValidLanguageTag; url: sec-isstructurallyvalidlanguagetag
text: CanonicalizeUnicodeLocaleId; url: sec-canonicalizeunicodelocaleid
</pre>
<style>
dl.props { display: grid; grid-template-columns: max-content auto; row-gap: 0.25em; column-gap: 1em; }
dl.props > dt { grid-column-start: 1; margin: 0; }
dl.props > dd { grid-column-start: 2; margin: 0; }
p + dl.props { margin-top: -0.5em; }
.enum-table tbody th { white-space: nowrap; }
</style>
<h2 id="intro">Introduction</h2>
For now, see the [explainer](https://github.com/webmachinelearning/writing-assistance-apis/blob/main/README.md).
<h2 id="shared-ai-api">Shared AI APIs and infrastructure</h2>
<xmp class="idl">
partial interface WindowOrWorkerGlobalScope {
[Replaceable, SecureContext] readonly attribute AI ai;
};
[Exposed=(Window,Worker), SecureContext]
interface AI {};
[Exposed=(Window,Worker), SecureContext]
interface AICreateMonitor : EventTarget {
attribute EventHandler ondownloadprogress;
};
[Exposed=(Window,Worker), SecureContext, Serializable]
interface TooManyTokensError : DOMException {
constructor(optional DOMString message = "", TooManyTokensErrorOptions options);
readonly attribute unsigned long long tokenCount;
readonly attribute unsigned long long tokensAvailable;
};
dictionary TooManyTokensErrorOptions {
required [EnforceRange] unsigned long long tokenCount;
required [EnforceRange] unsigned long long tokensAvailable;
};
callback AICreateMonitorCallback = undefined (AICreateMonitor monitor);
enum AICapabilityAvailability { "readily", "after-download", "no" };
</xmp>
<div algorithm>
The <dfn for="AICapabilityAvailability">minimum availability</dfn> given a [=list=] of {{AICapabilityAvailability}}-or-null values |availabilities| is:
1. If |availabilities| [=list/contains=] null, then return null.
1. If |availabilities| [=list/contains=] "{{AICapabilityAvailability/no}}", then return "{{AICapabilityAvailability/no}}".
1. If |availabilities| [=list/contains=] "{{AICapabilityAvailability/after-download}}", then return "{{AICapabilityAvailability/after-download}}".
1. Return "{{AICapabilityAvailability/readily}}".
</div>
<hr>
Each {{WindowOrWorkerGlobalScope}} has an <dfn for="WindowOrWorkerGlobalScope">AI namespace</dfn>, an {{AI}} object. Upon creation of the {{WindowOrWorkerGlobalScope}} object, its [=WindowOrWorkerGlobalScope/AI namespace=] must be set to a [=new=] {{AI}} object created in the {{WindowOrWorkerGlobalScope}} object's [=relevant realm=].
The <dfn attribute for="WindowOrWorkerGlobalScope">ai</dfn> getter steps are to return [=this=]'s [=WindowOrWorkerGlobalScope/AI namespace=].
<hr>
[=Tasks=] queued by this specification use the <dfn>AI task source</dfn>.
<hr>
The following are the [=event handlers=] (and their corresponding [=event handler event types=]) that must be supported, as [=event handler IDL attributes=], by all {{AICreateMonitor}} objects:
<table>
<thead>
<tr>
<th>[=Event handler=]
<th>[=Event handler event type=]
<tbody>
<tr>
<td><dfn attribute for="AICreateMonitor">ondownloadprogress</dfn>
<td><dfn event for="AICreateMonitor">downloadprogress</dfn>
</table>
<hr>
Every {{TooManyTokensError}} instance has a <dfn for="TooManyTokensError">token count</dfn> and a <dfn for="TooManyTokensError">tokens available</dfn>, both numbers.
<div algorithm>
The <dfn constructor for="TooManyTokensError" lt="TooManyTokensError(message, options)">new TooManyTokensError(|message|, |options|)</dfn> constructor steps are:
1. Set [=this=]'s [=DOMException/name=] to "`TooManyTokensError`".
1. Set [=this=]'s [=DOMException/message=] to |message|.
1. Set [=this=]'s [=TooManyTokensError/token count=] to |options|["{{TooManyTokensErrorOptions/tokenCount}}"].
1. Set [=this=]'s [=TooManyTokensError/tokens available=] to |options|["{{TooManyTokensErrorOptions/tokensAvailable}}"].
</div>
The <dfn attribute for="TooManyTokensError">tokenCount</dfn> getter steps are to return [=this=]'s [=TooManyTokensError/token count=].
The <dfn attribute for="TooManyTokensError">tokensAvailable</dfn> getter steps are to return [=this=]'s [=TooManyTokensError/tokens available=].
{{TooManyTokensError}} objects are [=serializable objects=].
<div algorithm="TooManyTokensError serialization steps">
Their [=serialization steps=], given |value| and |serialized|, are:
1. Run the {{DOMException}} [=serialization steps=] given |value| and |serialized|.
1. Set |serialized|.\[[TokensCount]] to |value|'s [=TooManyTokensError/token count=].
1. Set |serialized|.\[[TokensAvailable]] to |value|'s [=TooManyTokensError/tokens available=].
</div>
<div algorithm="TooManyTokensError deserialization steps">
Their [=deserialization steps=], given |serialized| and |value|, are:
1. Run the {{DOMException}} [=deserialization steps=] given |serialized| and |value|.
1. Set |value|'s [=TooManyTokensError/token count=] to |serialized|.\[[TokensCount]].
1. Set |value|'s [=TooManyTokensError/tokens available=] to |serialized|.\[[TokensAvailable]].
</div>
<h2 id="summarizer-api">The summarizer API</h2>
<xmp class="idl">
partial interface AI {
readonly attribute AISummarizerFactory summarizer;
};
[Exposed=(Window,Worker), SecureContext]
interface AISummarizerFactory {
Promise<AISummarizer> create(optional AISummarizerCreateOptions options = {});
Promise<AICapabilityAvailability> availability(optional AISummarizerCreateCoreOptions options = {});
};
[Exposed=(Window,Worker), SecureContext]
interface AISummarizer {
Promise<DOMString> summarize(
DOMString input,
optional AISummarizerSummarizeOptions options = {}
);
ReadableStream summarizeStreaming(
DOMString input,
optional AISummarizerSummarizeOptions options = {}
);
readonly attribute DOMString sharedContext;
readonly attribute AISummarizerType type;
readonly attribute AISummarizerFormat format;
readonly attribute AISummarizerLength length;
readonly attribute FrozenArray<DOMString>? expectedInputLanguages;
readonly attribute FrozenArray<DOMString>? expectedContextLanguages;
readonly attribute DOMString? outputLanguage;
Promise<unsigned long long> countTokens(
DOMString input,
optional AISummarizerSummarizeOptions options = {}
);
readonly attribute unsigned long long tokensAvailable;
undefined destroy();
};
dictionary AISummarizerCreateCoreOptions {
AISummarizerType type = "key-points";
AISummarizerFormat format = "markdown";
AISummarizerLength length = "short";
sequence<DOMString> expectedInputLanguages;
sequence<DOMString> expectedContextLanguages;
DOMString outputLanguage;
};
dictionary AISummarizerCreateOptions : AISummarizerCreateCoreOptions {
AbortSignal signal;
AICreateMonitorCallback monitor;
DOMString sharedContext;
};
dictionary AISummarizerSummarizeOptions {
AbortSignal signal;
DOMString context;
};
enum AISummarizerType { "tl;dr", "teaser", "key-points", "headline" };
enum AISummarizerFormat { "plain-text", "markdown" };
enum AISummarizerLength { "short", "medium", "long" };
</xmp>
Each {{AI}} has an <dfn for="AI">summarizer factory</dfn>, an {{AISummarizerFactory}} object. Upon creation of the {{AI}} object, its [=AI/summarizer factory=] must be set to a [=new=] {{AISummarizerFactory}} object created in the {{AI}} object's [=relevant realm=].
The <dfn attribute for="AI">summarizer</dfn> getter steps are to return [=this=]'s [=AI/summarizer factory=].
<h3 id="summarizer-creation">Creation</h3>
<div algorithm>
The <dfn method for="AISummarizerFactory">create(|options|)</dfn> method steps are:
1. If [=this=]'s [=relevant global object=] is a {{Window}} whose [=associated Document=] is not [=Document/fully active=], then return [=a promise rejected with=] an "{{InvalidStateError}}" {{DOMException}}.
1. If |options|["{{AISummarizerCreateOptions/signal}}"] [=map/exists=] and is [=AbortSignal/aborted=], then return [=a promise rejected with=] |options|["{{AISummarizerCreateOptions/signal}}"]'s [=AbortSignal/abort reason=].
1. [=Validate and canonicalize language tags=] given |options|. If this throws an exception |e|, catch it, and return [=a promise rejected with=] |e|.
<p class="note">This can mutate |options|.
1. Let |fireProgressEvent| be an algorithm taking two arguments that does nothing.
1. If |options|["{{AISummarizerCreateOptions/monitor}}"] [=map/exists=], then:
1. Let |monitor| be a [=new=] {{AICreateMonitor}} created in [=this=]'s [=relevant realm=].
1. [=Invoke=] |options|["{{AISummarizerCreateOptions/monitor}}"] with « |monitor| » and "`rethrow`".
If this throws an exception |e|, catch it, and return [=a promise rejected with=] |e|.
1. Set |fireProgressEvent| to an algorithm taking arguments |loaded| and |total|, which performs the following steps:
1. [=Assert=]: this algorithm is running [=in parallel=].
1. [=Queue a global task=] on the [=AI task source=] given [=this=]'s [=relevant global object=] to perform the following steps:
1. [=Fire an event=] named {{AICreateMonitor/downloadprogress}} at |monitor|, using {{ProgressEvent}}, with the {{ProgressEvent/loaded}} attribute initialized to |loaded|, the {{ProgressEvent/total}} attribute initialized to |total|, and the {{ProgressEvent/lengthComputable}} attribute initialized to true.
1. Let |abortedDuringDownload| be false.
<p class="note">This variable will be written to from the [=event loop=], but read from [=in parallel=].
1. If |options|["{{AISummarizerCreateOptions/signal}}"] [=map/exists=], then [=AbortSignal/add|add the following abort steps=] to |options|["{{AISummarizerCreateOptions/signal}}"]:
1. Set |abortedDuringDownload| to true.
1. Let |promise| be [=a new promise=] created in [=this=]'s [=relevant realm=].
1. [=In parallel=]:
1. Let |availability| be the result of [=computing summarizer options availability=] given |options|.
<p class="note">This can mutate |options|.
1. Switch on |availability|:
<dl class="switch">
: null
::
1. [=Reject=] |promise| with an "{{UnknownError}}" {{DOMException}}.
1. Abort these steps.
: "{{AICapabilityAvailability/no}}"
::
1. [=Reject=] |promise| with a "{{NotSupportedError}}" {{DOMException}}.
1. Abort these steps.
: "{{AICapabilityAvailability/readily}}"
::
1. If [=initializing the summarization model=] given |promise| and |options| returns false, then abort these steps.
1. Let |totalBytes| be the total size of the previously-downloaded summarization capabilities, in bytes.
1. [=Assert=]: |totalBytes| is greater than 0.
1. Perform |fireProgressEvent| given 0 and |totalBytes|.
1. Perform |fireProgressEvent| given |totalBytes| and |totalBytes|.
1. [=Finalize summarizer creation=] given |promise| and |options|.
: "{{AICapabilityAvailability/after-download}}"
::
1. Initiate the download process for everything the user agent needs to summarize text according to |options|.
1. Run the following steps, but [=abort when=] |abortedDuringDownload| becomes true:
1. Wait for the total number of bytes to be downloaded to become determined, and let that number be |totalBytes|.
1. Let |lastProgressTime| be the [=monotonic clock=]'s [=monotonic clock/unsafe current time=].
1. Perform |fireProgressEvent| given 0 and |totalBytes|.
1. While true:
1. If one or more bytes have been downloaded, then:
1. If the [=monotonic clock=]'s [=monotonic clock/unsafe current time=] minus |lastProgressTime| is greater than 50 ms, then:
1. Let |bytesSoFar| be the number of bytes downloaded so far.
1. [=Assert=]: |bytesSoFar| is greater than 0 and less than or equal to |totalBytes|.
1. Perform |fireProgressEvent| given |bytesSoFar| and |totalBytes|.
1. If |bytesSoFar| equals |totalBytes|, then [=iteration/break=].
1. Set |lastProgressTime| to the [=monotonic clock=]'s [=monotonic clock/unsafe current time=].
1. Otherwise, if downloading has failed and cannot continue, then:
1. [=Queue a global task=] on the [=AI task source=] given [=this=]'s [=relevant global object=] to [=reject=] |promise| with a "{{NetworkError}}" {{DOMException}}.
1. Abort these steps.
1. [=If aborted=], then:
1. [=Queue a global task=] on the [=AI task source=] given [=this=]'s [=relevant global object=] to perform the following steps:
1. [=Assert=]: |options|["{{AISummarizerCreateOptions/signal}}"]'s is [=AbortSignal/aborted=].
1. [=Reject=] |promise| with |options|["{{AISummarizerCreateOptions/signal}}"]'s [=AbortSignal/abort reason=].
1. Abort these steps.
1. If [=initializing the summarization model=] given |promise| and |options| returns false, then abort these steps.
1. [=Finalize summarizer creation=] given |promise| and |options|.
</dl>
1. Return |promise|.
</div>
<div algorithm>
To <dfn>initialize the summarization model</dfn>, given a {{Promise}} |promise| and an {{AISummarizerCreateOptions}} |options|:
1. [=Assert=]: these steps are running [=in parallel=].
1. Perform any necessary initialization operations for the AI model backing the [=user agent=]'s summarization capabilities.
This could include loading the model into memory, loading |options|["{{AISummarizerCreateOptions/sharedContext}}"] into the model's context window, or loading any fine-tunings necessary to support the other options expressed by |options|.
1. If initialization failed because the number of tokens needed to load |options| was too large for the implementation, then:
1. Let |tokenCount| be the result of [=counting the tokens=] necessary to encode |options|.
<p class="note" id="note-options-token-encoding">This could be the same value as given by [=counting the tokens=] in |options|["{{AISummarizerCreateOptions/sharedContext}}"], or it could be larger. For example, if other options are encoded using prompt engineering, then the prompt would be included when computing |tokenCount|.</p>
1. Let |tokensAvailable| be the maximum number of tokens that the user agent supports.
1. [=Assert=]: |tokensAvailable| is less than |tokenCount|. (That is how we reached this error branch.)
1. [=Queue a global task=] on the [=AI task source=] given |promise|'s [=relevant global object=] to [=reject=] |promise| with a {{TooManyTokensError}} whose [=TooManyTokensError/token count=] is |tokenCount| and [=TooManyTokensError/tokens available=] is |tokensAvailable|.
1. If initialization failed for any other reason, then:
1. [=Queue a global task=] on the [=AI task source=] given |promise|'s [=relevant global object=] to [=reject=] |promise| with an "{{OperationError}}" {{DOMException}}.
1. Return false.
1. Return true.
</div>
<div algorithm>
To <dfn>finalize summarizer creation</dfn>, given a {{Promise}} |promise| and an {{AISummarizerCreateOptions}} |options|:
1. [=Assert=]: these steps are running [=in parallel=].
1. [=Queue a global task=] on the [=AI task source=] given |promise|'s [=relevant global object=] to perform the following steps:
1. If |options|["{{AISummarizerCreateOptions/signal}}"] [=map/exists=] and is [=AbortSignal/aborted=], then:
1. [=Reject=] |promise| with |options|["{{AISummarizerCreateOptions/signal}}"]'s [=AbortSignal/abort reason=].
1. Abort these steps.
<p class="note">This check is necessary in case any code running on the [=agent/event loop=] caused the {{AbortSignal}} to become [=AbortSignal/aborted=] before this [=task=] ran.
1. Let |tokensAvailable| be the total number of tokens available to the user agent for future [=summarize|summarization=] operations.
<p class="note">This will generally vary for each {{AISummarizer}} instance, depending on how many tokens were taken up by encoding |options|. See <a href="#note-options-token-encoding">the earlier note</a> on this encoding.</p>
1. Let |summarizer| be a new {{AISummarizer}} object, created in |promise|'s [=relevant realm=], with
<dl class="props">
: [=AISummarizer/shared context=]
:: |options|["{{AISummarizerCreateOptions/sharedContext}}"] if it [=map/exists=]; otherwise null
: [=AISummarizer/summary type=]
:: |options|["{{AISummarizerCreateCoreOptions/type}}"]
: [=AISummarizer/summary format=]
:: |options|["{{AISummarizerCreateCoreOptions/format}}"]
: [=AISummarizer/summary length=]
:: |options|["{{AISummarizerCreateCoreOptions/length}}"]
: [=AISummarizer/tokens available=]
:: |tokensAvailable|
: [=AISummarizer/expected input languages=]
:: the result of [=creating a frozen array=] given |options|["{{AISummarizerCreateCoreOptions/expectedInputLanguages}}"] if it [=set/is empty|is not empty=]; otherwise null
: [=AISummarizer/expected context languages=]
:: the result of [=creating a frozen array=] given |options|["{{AISummarizerCreateCoreOptions/expectedContextLanguages}}"] if it [=set/is empty|is not empty=]; otherwise null
: [=AISummarizer/output language=]
:: |options|["{{AISummarizerCreateCoreOptions/outputLanguage}}"] if it [=map/exists=]; otherwise null
</dl>
1. If |options|["{{AISummarizerCreateOptions/signal}}"] [=map/exists=], then [=AbortSignal/add|add the following abort steps=] to |options|["{{AISummarizerCreateOptions/signal}}"]:
1. [=AISummarizer/Destroy=] |summarizer| with |options|["{{AISummarizerCreateOptions/signal}}"]'s [=AbortSignal/abort reason=].
1. [=Resolve=] |promise| with |summarizer|.
</div>
<div algorithm>
To <dfn>validate and canonicalize language tags</dfn> given an {{AISummarizerCreateCoreOptions}} |options|, perform the following steps. They mutate |options| in place to canonicalize and deduplicate language tags, and throw a {{TypeError}} if any are invalid.
1. Let |expectedInputLanguages| be an empty [=ordered set=].
1. If |options|["{{AISummarizerCreateCoreOptions/expectedInputLanguages}}"] [=map/exists=], then [=list/for each=] |languageTag| of |options|["{{AISummarizerCreateCoreOptions/expectedInputLanguages}}"]:
1. If [$IsStructurallyValidLanguageTag$](|languageTag|) is false, then throw a {{TypeError}}.
1. [=set/Append=] [$CanonicalizeUnicodeLocaleId$](|languageTag|) to |expectedInputLanguages|.
1. Set |options|["{{AISummarizerCreateCoreOptions/expectedInputLanguages}}"] to |expectedInputLanguages|.
1. Let |expectedContextLanguages| be an empty [=ordered set=].
1. If |options|["{{AISummarizerCreateCoreOptions/expectedContextLanguages}}"] [=map/exists=], then [=list/for each=] |languageTag| of |options|["{{AISummarizerCreateCoreOptions/expectedContextLanguages}}"]:
1. If [$IsStructurallyValidLanguageTag$](|languageTag|) is false, then throw a {{TypeError}}.
1. [=set/Append=] [$CanonicalizeUnicodeLocaleId$](|languageTag|) to |expectedContextLanguages|.
1. Set |options|["{{AISummarizerCreateCoreOptions/expectedContextLanguages}}"] to |expectedContextLanguages|.
1. If |options|["{{AISummarizerCreateCoreOptions/outputLanguage}}"] [=map/exists=], then:
1. If [$IsStructurallyValidLanguageTag$](|options|["{{AISummarizerCreateCoreOptions/outputLanguage}}"]) is false, then throw a {{TypeError}}.
1. Set |options|["{{AISummarizerCreateCoreOptions/outputLanguage}}"] to [$CanonicalizeUnicodeLocaleId$](|options|["{{AISummarizerCreateCoreOptions/outputLanguage}}"]).
</div>
<h3 id="summarizer-availability">Availability</h3>
<div algorithm>
The <dfn method for="AISummarizerFactory">availability(|options|)</dfn> method steps are:
1. If [=this=]'s [=relevant global object=] is a {{Window}} whose [=associated Document=] is not [=Document/fully active=], then return [=a promise rejected with=] an "{{InvalidStateError}}" {{DOMException}}.
1. [=Validate and canonicalize language tags=] given |options|.
1. Let |promise| be [=a new promise=] created in [=this=]'s [=relevant realm=].
1. [=In parallel=]:
1. Let |availability| be the result of [=computing summarizer options availability=] given |options|.
1. If |availability| is null, then [=reject=] |promise| with an "{{UnknownError}}" {{DOMException}}.
1. Otherwise, [=resolve=] |promise| with |availability|.
</div>
<div algorithm>
To <dfn>compute summarizer options availability</dfn> given an {{AISummarizerCreateCoreOptions}} |options|, perform the following steps. They return either an {{AICapabilityAvailability}} value or null, and they mutate |options| in place to update language tags to their best-fit matches.
1. [=Assert=]: this algorithm is running [=in parallel=].
1. Let |availability| be the [=summarizer non-language options availability=] given |options|["{{AISummarizerCreateCoreOptions/type}}"], |options|["{{AISummarizerCreateCoreOptions/format}}"], and |options|["{{AISummarizerCreateCoreOptions/length}}"].
1. If |availability| is null, then return null.
1. Let |languageAvailabilities| be the [=summarizer language availabilities=].
1. If |languageAvailabilities| is null, then return null.
1. [=set/For each=] |languageTag| of |options|["{{AISummarizerCreateCoreOptions/expectedInputLanguages}}"]:
1. Let |bestReadilyAvailableMatch| be [$LookupMatchingLocaleByBestFit$](|languageAvailabilities|'s [=language availabilities/readily available input languages=], |languageTag|).
1. If |bestReadilyAvailableMatch| is not undefined, then:
1. [=list/Replace=] |languageTag| with |bestReadilyAvailableMatch| in |options|["{{AISummarizerCreateCoreOptions/expectedInputLanguages}}"].
1. [=iteration/Continue=].
1. Let |bestAfterDownloadAvailableMatch| be [$LookupMatchingLocaleByBestFit$](|languageAvailabilities|'s [=language availabilities/after-download available input languages=], |languageTag|).
1. If |bestAfterDownloadAvailableMatch| is not undefined, then:
1. [=list/Replace=] |languageTag| with |bestAfterDownloadAvailableMatch| in |options|["{{AISummarizerCreateCoreOptions/expectedInputLanguages}}"].
1. Set |availability| to the [=AICapabilityAvailability/minimum availability=] given « |availability|, "{{AICapabilityAvailability/after-download}}" ».
1. Otherwise, return "{{AICapabilityAvailability/no}}".
1. [=set/For each=] |languageTag| of |options|["{{AISummarizerCreateCoreOptions/expectedContextLanguages}}"]:
1. Let |bestReadilyAvailableMatch| be [$LookupMatchingLocaleByBestFit$](|languageAvailabilities|'s [=language availabilities/readily available context languages=], |languageTag|).
1. If |bestReadilyAvailableMatch| is not undefined, then:
1. [=list/Replace=] |languageTag| with |bestReadilyAvailableMatch| in |options|["{{AISummarizerCreateCoreOptions/expectedContextLanguages}}"].
1. [=iteration/Continue=].
1. Let |bestAfterDownloadAvailableMatch| be [$LookupMatchingLocaleByBestFit$](|languageAvailabilities|'s [=language availabilities/after-download available context languages=], |languageTag|).
1. If |bestAfterDownloadAvailableMatch| is not undefined, then:
1. [=list/Replace=] |languageTag| with |bestAfterDownloadAvailableMatch| in |options|["{{AISummarizerCreateCoreOptions/expectedContextLanguages}}"].
1. Set |availability| to the [=AICapabilityAvailability/minimum availability=] given « |availability|, "{{AICapabilityAvailability/after-download}}" ».
1. Otherwise, return "{{AICapabilityAvailability/no}}".
1. If |options|["{{AISummarizerCreateCoreOptions/outputLanguage}}"] is present, then:
1. Let |bestReadilyAvailableMatch| be [$LookupMatchingLocaleByBestFit$](|languageAvailabilities|'s [=language availabilities/readily available output languages=], |options|["{{AISummarizerCreateCoreOptions/outputLanguage}}"]).
1. If |bestReadilyAvailableMatch| is not undefined, then:
1. Set |options|["{{AISummarizerCreateCoreOptions/outputLanguage}}"] to |bestReadilyAvailableMatch|.
1. Otherwise:
1. Let |bestAfterDownloadAvailableMatch| be [$LookupMatchingLocaleByBestFit$](|languageAvailabilities|'s [=language availabilities/after-download available output languages=], |options|["{{AISummarizerCreateCoreOptions/outputLanguage}}"]).
1. If |bestAfterDownloadAvailableMatch| is not undefined, then:
1. Set |options|["{{AISummarizerCreateCoreOptions/outputLanguage}}"] to |bestAfterDownloadAvailableMatch|.
1. Set |availability| to the [=AICapabilityAvailability/minimum availability=] given « |availability|, "{{AICapabilityAvailability/after-download}}" ».
1. Otherwise, return "{{AICapabilityAvailability/no}}".
1. [=Assert=]: |availability| is either "{{AICapabilityAvailability/readily}}" or "{{AICapabilityAvailability/after-download}}".
1. Return |availability|.
</div>
<div algorithm>
The <dfn>summarizer non-language options availability</dfn>, given a {{AISummarizerType}} |type|, {{AISummarizerFormat}} |format|, and an {{AISummarizerLength}} |length|, is given by the following steps. They return an {{AICapabilityAvailability}} value or null.
1. [=Assert=]: this algorithm is running [=in parallel=].
1. If there is some error attempting to determine whether the user agent supports summarizing text, which the user agent believes to be transient (such that re-querying the [=summarizer non-language options availability=] could stop producing such an error), then return null.
1. If the user agent supports summarizing text into the type of summary described by |type|, in the format described by |format|, and with the length guidance given by |length| without performing any downloading operations, then return "{{AICapabilityAvailability/readily}}".
1. If the user agent believes it can summarize text according to |type|, |format|, and |length|, but only after performing a download (e.g., of an AI model or fine-tuning), then return "{{AICapabilityAvailability/after-download}}".
1. Otherwise, return "{{AICapabilityAvailability/no}}".
</div>
A <dfn>language availabilities</dfn> is a [=struct=] with the following [=struct/items=]:
* <dfn for="language availabilities">readily available input languages</dfn>
* <dfn for="language availabilities">after-download available input languages</dfn>
* <dfn for="language availabilities">readily available context languages</dfn>
* <dfn for="language availabilities">after-download available context languages</dfn>
* <dfn for="language availabilities">readily available output languages</dfn>
* <dfn for="language availabilities">after-download available output languages</dfn>
All of these [=struct/items=] are [=sets=] of strings representing [=Unicode canonicalized locale identifiers=], initially empty. [[!ECMA-402]]
<div algorithm>
The <dfn>summarizer language availabilities</dfn> are given by the following steps. They return a [=language availabilities=] or null.
1. [=Assert=]: this algorithm is running [=in parallel=].
1. If there is some error attempting to determine whether the user agent supports summarizing text, which the user agent believes to be transient (such that re-querying the [=summarizer language availabilities=] could stop producing such an error), then return null.
1. Let |availabilities| be a [=language availabilities=].
1. [=Fill language availabilities=] given |availabilities|'s [=language availabilities/readily available input languages=], |availabilities|'s [=language availabilities/after-download available input languages=], and the purpose of summarizing text written in that language.
1. [=Fill language availabilities=] given |availabilities|'s [=language availabilities/readily available context languages=], |availabilities|'s [=language availabilities/after-download available context languages=], and the purpose of summarizing text using web-developer provided context information written in that language.
1. [=Fill language availabilities=] given |availabilities|'s [=language availabilities/readily available output languages=], |availabilities|'s [=language availabilities/after-download available output languages=], and the purpose of producing text summaries in that language.
1. Return |availabilities|.
</div>
<div algorithm>
To <dfn>fill language availabilities</dfn> given a [=set=] |readilyAvailableLanguages|, a [=set=] |afterDownloadAvailableLanguages|, and a description of the purpose for which we're checking language availability, perform the following steps:
1. [=list/For each=] human language |languageTag|, represented as a [=Unicode canonicalized locale identifier=], for which the user agent supports |purpose|, without performing any downloading operations:
1. [=set/Append=] |languageTag| to |readilyAvailableLanguages|.
1. [=list/For each=] human language |languageTag|, represented as a [=Unicode canonicalized locale identifier=], for which the user agent believes it can support |purpose|, but only after performing a download (e.g., of an AI model or fine-tuning):
1. [=Assert=]: |readilyAvailableLanguages| does not [=set/contain=] |languageTag|.
1. [=set/Append=] |languageTag| to |afterDownloadAvailableLanguages|.
1. If the [=set/union=] of |readilyAvailableLanguages| and |afterDownloadAvailableLanguages| does not meet the [=language tag set completeness rules=], then:
1. Let |missingLanguageTags| be the [=set=] of missing language tags necessary to meet the [=language tag set completeness rules=].
1. [=set/For each=] |languageTag| of |missingLanguageTags|:
1. <span id="readily-or-after-download-implementation-defined"></span> [=set/Append=] |languageTag| to either |readilyAvailableLanguages| or |afterDownloadAvailableLanguages|. Which of the two sets to append to is [=implementation-defined=], and should be guided by considerations similar to that of [$LookupMatchingLocaleByBestFit$] in terms of keeping "best fallback languages" together.
</div>
<div algorithm>
The <dfn>language tag set completeness rules</dfn> state that for every [=set/item=] |languageTag|, if |languageTag| has more than one subtag, then the set must also contain a less narrow language tag with the same language subtag and a strict subset of the same following subtags (i.e., omitting one or more).
<p class="note">This definition is intended to align with that of [=[[AvailableLocales]]=] in <cite>ECMAScript Internationalization API Specification</cite>. [[ECMA-402]]
<div class="example" id="example-subtags-intro">
This means that if an implementation supports summarization of "`de-DE`" input text, it will also count as supporting "`de`" input text.
The converse direction is supported not by the [=language tag set completeness rules=], but instead by the use of [$LookupMatchingLocaleByBestFit$], which ensures that if an implementation supports summarizing "`de`" input text, it also counts as supporting summarization of "`de-CH`", "`de-Latn-CH`", etc.
</div>
<div class="example" id="example-subtags-chinese">
A common setup seen in today's software is to support two types of written Chinese: "traditional Chinese" and "simplified Chinese". Let's suppose that the user agent supports summarizing text written in traditional Chinese readily, and simplified Chinese after a download.
One way this could be implemented would be for [=summarizer language availabilities=] to return that "`zh-Hant`" is in the [=language availabilities/readily available input languages=], and "`zh`" and "`zh-Hans`" are in the [=language availabilities/after-download available input languages=]. This return value conforms to the requirements of the [=language tag set completeness rules=], in ensuring that "`zh`" is present. Per <a class="allow-2119" href="#readily-or-after-download-implementation-defined">the "should"-level guidance</a>, the implementation has determined that "`zh`" belongs in the set of [=language availabilities/after-download available input languages=], with "`zh-Hans`", instead of in the set of [=language availabilities/readily available input languages=], with "`zh-Hant`".
Combined with the use of [$LookupMatchingLocaleByBestFit$], this means {{AISummarizerFactory/availability()}} will give the following answers:
<xmp class="language-js">
function inputLangAvailability(languageTag) {
return ai.summarizer.availability({
expectedInputLanguages: [languageTag]
});
}
inputLangAvailability("zh") === "after-download";
inputLangAvailability("zh-Hant") === "readily";
inputLangAvailability("zh-Hans") === "after-download";
inputLangAvailability("zh-TW") === "readily"; // zh-TW will best-fit to zh-Hant
inputLangAvailability("zh-HK") === "readily"; // zh-HK will best-fit to zh-Hant
inputLangAvailability("zh-CN") === "after-download"; // zh-CN will best-fit to zh-Hans
inputLangAvailability("zh-BR") === "after-download"; // zh-BR will best-fit to zh
inputLangAvailability("zh-Kana") === "after-download"; // zh-Kana will best-fit to zh
</xmp>
</div>
</div>
<h3 id="the-aisummarizer-class">The {{AISummarizer}} class</h3>
Every {{AISummarizer}} has a <dfn for="AISummarizer">shared context</dfn>, a [=string=]-or-null, set during creation.
Every {{AISummarizer}} has a <dfn for="AISummarizer">summary type</dfn>, an {{AISummarizerType}}, set during creation.
Every {{AISummarizer}} has a <dfn for="AISummarizer">summary format</dfn>, an {{AISummarizerFormat}}, set during creation.
Every {{AISummarizer}} has a <dfn for="AISummarizer">summary length</dfn>, an {{AISummarizerLength}}, set during creation.
Every {{AISummarizer}} has a <dfn for="AISummarizer">tokens available</dfn> number, set during creation.
Every {{AISummarizer}} has an <dfn for="AISummarizer">expected input languages</dfn>, a <code>{{FrozenArray}}<{{DOMString}}></code> or null, set during creation.
Every {{AISummarizer}} has an <dfn for="AISummarizer">expected context languages</dfn>, a <code>{{FrozenArray}}<{{DOMString}}></code> or null, set during creation.
Every {{AISummarizer}} has an <dfn for="AISummarizer">output language</dfn>, a [=string=] or null, set during creation.
Every {{AISummarizer}} has a <dfn for="AISummarizer">destruction reason</dfn>, a JavaScript value, initially undefined.
Every {{AISummarizer}} has a <dfn for="AISummarizer">destroyed</dfn> boolean, initially false.
<p class="note">This value is separate from the [=AISummarizer/destruction reason=] so that it can be read from [=in parallel=] during the summarization process.
<hr>
The <dfn attribute for="AISummarizer">sharedContext</dfn> getter steps are to return [=this=]'s [=AISummarizer/shared context=].
The <dfn attribute for="AISummarizer">type</dfn> getter steps are to return [=this=]'s [=AISummarizer/summary type=].
The <dfn attribute for="AISummarizer">format</dfn> getter steps are to return [=this=]'s [=AISummarizer/summary format=].
The <dfn attribute for="AISummarizer">length</dfn> getter steps are to return [=this=]'s [=AISummarizer/summary length=].
The <dfn attribute for="AISummarizer">tokensAvailable</dfn> getter steps are to return [=this=]'s [=AISummarizer/tokens available=].
The <dfn attribute for="AISummarizer">expectedInputLanguages</dfn> getter steps are to return [=this=]'s [=AISummarizer/expected input languages=].
The <dfn attribute for="AISummarizer">expectedContextLanguages</dfn> getter steps are to return [=this=]'s [=AISummarizer/expected context languages=].
The <dfn attribute for="AISummarizer">outputLanguage</dfn> getter steps are to return [=this=]'s [=AISummarizer/output language=].
<hr>
<div algorithm>
The <dfn method for="AISummarizer">summarize(|input|, |options|)</dfn> method steps are:
1. If [=this=]'s [=relevant global object=] is a {{Window}} whose [=associated Document=] is not [=Document/fully active=], then return [=a promise rejected with=] an "{{InvalidStateError}}" {{DOMException}}.
1. If |options|["{{AISummarizerSummarizeOptions/signal}}"] [=map/exists=] and is [=AbortSignal/aborted=], then return [=a promise rejected with=] |options|["{{AISummarizerSummarizeOptions/signal}}"]'s [=AbortSignal/abort reason=].
1. If [=this=]'s [=AISummarizer/destroyed=] is true, then return [=a promise rejected with=] [=this=]'s [=AISummarizer/destruction reason=].
1. Let |abortedDuringSummarization| be false.
<p class="note">This variable will be written to from the [=event loop=], but read from [=in parallel=].
1. If |options|["{{AISummarizerSummarizeOptions/signal}}"] [=map/exists=], then [=AbortSignal/add|add the following abort steps=] to |options|["{{AISummarizerSummarizeOptions/signal}}"]:
1. Set |abortedDuringSummarization| to true.
1. Let |promise| be [=a new promise=] created in [=this=]'s [=relevant realm=].
1. Let |context| be |options|["{{AISummarizerSummarizeOptions/context}}"] if it [=map/exists=]; otherwise null.
1. [=In parallel=]:
1. Let |summary| be the empty string.
1. Let |chunkProduced| be the following steps given a [=string=] |chunk|:
1. [=Queue a global task=] on the [=AI task source=] given [=this=]'s [=relevant global object=] to perform the following steps:
1. If |abortedDuringSummarization| is true, then:
1. [=Reject=] |promise| with |options|["{{AISummarizerSummarizeOptions/signal}}"]'s [=AbortSignal/abort reason=].
1. Abort these steps.
1. If [=this=]'s [=AISummarizer/destroyed=] is true, then:
1. [=Reject=] |promise| with [=this=]'s [=AISummarizer/destruction reason=].
1. Abort these steps.
1. Append |chunk| to |summary|.
1. Let |done| be the following steps:
1. [=Queue a global task=] on the [=AI task source=] given [=this=]'s [=relevant global object=] to perform the following steps:
1. If |abortedDuringSummarization| is true, then:
1. [=Reject=] |promise| with |options|["{{AISummarizerSummarizeOptions/signal}}"]'s [=AbortSignal/abort reason=].
1. Abort these steps.
1. If [=this=]'s [=AISummarizer/destroyed=] is true, then:
1. [=Reject=] |promise| with [=this=]'s [=AISummarizer/destruction reason=].
1. Abort these steps.
1. [=Resolve=] |promise| with |summary|.
1. Let |error| be the following steps given [=summarization error information=] |errorInfo|:
1. [=Queue a global task=] on the [=AI task source=] given [=this=]'s [=relevant global object=] to perform the following steps:
1. If |abortedDuringSummarization| is true, then:
1. [=Reject=] |promise| with |options|["{{AISummarizerSummarizeOptions/signal}}"]'s [=AbortSignal/abort reason=].
1. Abort these steps.
1. [=Reject=] |promise| with the result of [=converting error information into an exception object=] given [=this=] and |errorInfo|.
1. Let |stopProducing| be the following steps:
1. Return |abortedDuringSummarization|.
1. [=Summarize=] |input| given [=this=]'s [=AISummarizer/shared context=], |context|, [=this=]'s [=AISummarizer/summary type=], [=this=]'s [=AISummarizer/summary format=], [=this=]'s [=AISummarizer/summary length=], [=this=]'s [=AISummarizer/output language=], |chunkProduced|, |done|, |error|, and |stopProducing|.
1. Return |promise|.
</div>
<div algorithm>
The <dfn method for="AISummarizer">summarizeStreaming(|input|, |options|)</dfn> method steps are:
1. If [=this=]'s [=relevant global object=] is a {{Window}} whose [=associated Document=] is not [=Document/fully active=], then throw an "{{InvalidStateError}}" {{DOMException}}.
1. If |options|["{{AISummarizerSummarizeOptions/signal}}"] [=map/exists=] and is [=AbortSignal/aborted=], then throw |options|["{{AISummarizerSummarizeOptions/signal}}"]'s [=AbortSignal/abort reason=].
1. If [=this=]'s [=AISummarizer/destroyed=] is true, then throw [=this=]'s [=AISummarizer/destruction reason=].
1. Let |abortedDuringSummarization| be false.
<p class="note">This variable tracks web developer aborts via the |options|["{{AISummarizerSummarizeOptions/signal}}"] {{AbortSignal}}, which are surfaced as errors. It will be written to from the [=event loop=], but sometimes read from [=in parallel=].
1. If |options|["{{AISummarizerSummarizeOptions/signal}}"] [=map/exists=], then [=AbortSignal/add|add the following abort steps=] to |options|["{{AISummarizerSummarizeOptions/signal}}"]:
1. Set |abortedDuringSummarization| to true.
1. Let |stream| be a [=new=] {{ReadableStream}} created in [=this=]'s [=relevant realm=].
1. Let |canceledDuringSummarization| be false.
<p class="note">This variable tracks web developer [=ReadableStream/cancel|stream cancelations=] via {{ReadableStream/cancel()|stream.cancel()}}, which are not surfaced as errors. It will be written to from the [=event loop=], but sometimes read from [=in parallel=].
1. [=ReadableStream/Set up=] |stream| with <i>[=ReadableStream/set up/cancelAlgorithm=]</i> set to the following steps (ignoring the <var ignore>reason</var> argument):
1. Set |canceledDuringSummarization| to true.
1. Let |context| be |options|["{{AISummarizerSummarizeOptions/context}}"] if it [=map/exists=]; otherwise null.
1. [=In parallel=]:
1. Let |chunkProduced| be the following steps given a [=string=] |chunk|:
1. [=Queue a global task=] on the [=AI task source=] given [=this=]'s [=relevant global object=] to perform the following steps:
1. If |abortedDuringSummarization| is true, then:
1. [=ReadableStream/Error=] |stream| with |options|["{{AISummarizerSummarizeOptions/signal}}"]'s [=AbortSignal/abort reason=].
1. Abort these steps.
1. If [=this=]'s [=AISummarizer/destroyed=] is true, then:
1. [=ReadableStream/Error=] |stream| with [=this=]'s [=AISummarizer/destruction reason=].
1. Abort these steps.
1. [=ReadableStream/Enqueue=] |chunk| into |stream|.
1. Let |done| be the following steps:
1. [=Queue a global task=] on the [=AI task source=] given [=this=]'s [=relevant global object=] to perform the following steps:
1. If |abortedDuringSummarization| is true, then:
1. [=ReadableStream/Error=] |stream| with |options|["{{AISummarizerSummarizeOptions/signal}}"]'s [=AbortSignal/abort reason=].
1. Abort these steps.
1. If [=this=]'s [=AISummarizer/destroyed=] is true, then:
1. [=ReadableStream/Error=] |stream| with [=this=]'s [=AISummarizer/destruction reason=].
1. Abort these steps.
1. [=ReadableStream/Close=] |stream|.
1. Let |error| be the following steps given [=summarization error information=] |errorInfo|:
1. [=Queue a global task=] on the [=AI task source=] given [=this=]'s [=relevant global object=] to perform the following steps:
1. If |abortedDuringSummarization| is true, then:
1. [=ReadableStream/Error=] |stream| with |options|["{{AISummarizerSummarizeOptions/signal}}"]'s [=AbortSignal/abort reason=].
1. Abort these steps.
1. If [=this=]'s [=AISummarizer/destroyed=] is true, then:
1. [=ReadableStream/Error=] |stream| with [=this=]'s [=AISummarizer/destruction reason=].
1. Abort these steps.
1. [=ReadableStream/Error=] |stream| with the result of [=converting error information into an exception object=] given [=this=] and |errorInfo|.
1. Let |stopProducing| be the following steps:
1. If any of |abortedDuringSummarization|, |canceledDuringSummarization|, or [=this=]'s [=AISummarizer/destroyed=] are true, then return true.
1. Return false.
1. [=Summarize=] |input| given [=this=]'s [=AISummarizer/shared context=], |context|, [=this=]'s [=AISummarizer/summary type=], [=this=]'s [=AISummarizer/summary format=], [=this=]'s [=AISummarizer/summary length=], [=this=]'s [=AISummarizer/output language=], |chunkProduced|, |done|, |error|, and |stopProducing|.
1. Return |stream|.
</div>
<div algorithm>
The <dfn method for="AISummarizer">countTokens(|input|, |options|)</dfn> method steps are:
1. If [=this=]'s [=relevant global object=] is a {{Window}} whose [=associated Document=] is not [=Document/fully active=], then return [=a promise rejected with=] an "{{InvalidStateError}}" {{DOMException}}.
1. If |options|["{{AISummarizerSummarizeOptions/signal}}"] [=map/exists=] and is [=AbortSignal/aborted=], then return [=a promise rejected with=] |options|["{{AISummarizerSummarizeOptions/signal}}"]'s [=AbortSignal/abort reason=].
1. If [=this=]'s [=AISummarizer/destroyed=] is true, then return [=a promise rejected with=] [=this=]'s [=AISummarizer/destruction reason=].
1. Let |promise| be [=a new promise=] created in [=this=]'s [=relevant realm=].
1. Let |context| be |options|["{{AISummarizerSummarizeOptions/context}}"] if it [=map/exists=]; otherwise null.
1. [=In parallel=]:
1. Let |inputToModel| be the [=implementation-defined=] string that would be sent to the language model in order to [=summarize=] |input|, given [=this=]'s [=AISummarizer/shared context=], |context|, [=this=]'s [=AISummarizer/summary type=], [=this=]'s [=AISummarizer/summary format=], [=this=]'s [=AISummarizer/summary length=], and [=this=]'s [=AISummarizer/output language=].
<p class="note">See <a href="#note-input-to-model">this note</a> for more detail on what |inputToModel| might consist of.</p>
1. Let |tokenCount| be the result of [=counting the tokens=] given |inputToModel|.
1. [=Queue a global task=] on the [=AI task source=] given [=this=]'s [=relevant global object=] to perform the following steps:
1. If |options|["{{AISummarizerSummarizeOptions/signal}}"] [=map/exists=] and is [=AbortSignal/aborted=], then:
1. [=Reject=] |promise| with |options|["{{AISummarizerSummarizeOptions/signal}}"]'s [=AbortSignal/abort reason=].
1. Abort these steps.
1. If [=this=]'s [=AISummarizer/destroyed=] is true, then:
1. [=Reject=] |promise| with [=this=]'s [=AISummarizer/destruction reason=].
1. Abort these steps.
1. If |tokenCount| is null, then:
1. [=Reject=] |promise| with an "{{UnknownError}}" {{DOMException}}.
1. Abort these steps.
1. [=Resolve=] |promise| with |tokenCount|.
1. Return |promise|.
</div>
<div algorithm>
To <dfn>summarize</dfn> a string |input|, given a string-or-null |sharedContext|, a string-or-null |context|, an {{AISummarizerType}} |type|, an {{AISummarizerFormat}} |format|, an {{AISummarizerLength}} |length|, a [=string=]-or-null |outputLanguage|, an algorithm |chunkProduced| that takes a string and returns nothing, an algorithm |done| that takes no arguments and returns nothing, an algorithm |error| that takes [=summarization error information=] and returns nothing, and an algorithm |stopProducing| that takes no arguments and returns a boolean:
1. [=Assert=]: this algorithm is running [=in parallel=].
1. Let |inputToModel| be the [=implementation-defined=] string that would be sent to the language model in order to summarize according to <a href="#step-actual-summarization">the upcoming summarization step</a>.
<p class="note" id="note-input-to-model">This might be something similar to the concatenation of |input| and |context|, if all of the previous options were loaded into the model during initialization, and so the tokens used to express them are already accounted for via the {{AISummarizer/tokensAvailable}} property's current value. Or it might require more tokens, if the options are sent along with every summarization call, or if there is a per-summarization wrapper prompt of some sort.</p>
1. Let |tokenCount| be the result of [=counting the tokens=] given |inputToModel|.
1. If |tokenCount| is greater than the number of tokens the language model can accept, then:
1. Let |errorInfo| be a [=too many tokens error information=] with a [=too many tokens error information/token count=] of |tokenCount|.
1. Perform |error| given |errorInfo|.
1. Return.
1. <span id="step-actual-summarization"></span>In an [=implementation-defined=] manner, subject to the following guidelines, begin the processs of summarizing |input| into a string.
If they are non-null, |sharedContext| and |context| should be used to aid in the summarization by providing context on how the web developer wishes the input to be summarized.
The summarization should conform to the guidance given by |type|, |format|, and |length|, in the definitions of each of their enumeration values.
If |outputLanguage| is non-null, the summarization should be in that language. Otherwise, it should be in the language of |input| (which might not match that of |context| or |sharedContext|). If |input| contains multiple languages, or the language of |input| cannot be detected, then either the output language is [=implementation-defined=], or the implementation may treat this as an error, per the guidance in [[#summarizer-errors]].
1. While true:
1. Wait for the next chunk of summarization data to be produced, for the summarization process to finish, or for the result of calling |stopProducing| to become true.
1. If such a chunk is successfully produced:
1. Let it be represented as a [=string=] |chunk|.
1. Perform |chunkProduced| given |chunk|.
1. Otherwise, if the summarization process has finished:
1. Perform |done|.
1. [=iteration/Break=].
1. Otherwise, if |stopProducing| returns true, then [=iteration/break=].
<p class="note">The caller will handle signaling cancelation or aborting as necessary.
1. Otherwise, if an error occurred during summarization:
1. Let the error be represented as [=summarization error information=] |errorInfo| according to the guidance in [[#summarizer-errors]].
1. Perform |error| given |errorInfo|.
1. [=iteration/Break=].
</div>
<div algorithm>
To <dfn>count the tokens</dfn> in a string |inputToModel|: