@@ -157,7 +157,7 @@ describe('ChromeAdapter', () => {
157157 Promise . resolve ( {
158158 available : 'after-download'
159159 } ) ,
160- create : ( ) => { }
160+ create : ( ) => { }
161161 }
162162 } as AI ;
163163 const downloadPromise = new Promise < AILanguageModel > ( ( ) => {
@@ -182,7 +182,7 @@ describe('ChromeAdapter', () => {
182182 Promise . resolve ( {
183183 available : 'after-download'
184184 } ) ,
185- create : ( ) => { }
185+ create : ( ) => { }
186186 }
187187 } as AI ;
188188 let resolveDownload ;
@@ -298,4 +298,48 @@ describe('ChromeAdapter', () => {
298298 } ) ;
299299 } ) ;
300300 } ) ;
301+ describe ( 'countTokens' , ( ) => {
302+ it ( 'Extracts initial prompts and counts tokens' , async ( ) => {
303+ const aiProvider = {
304+ languageModel : {
305+ create : ( ) => Promise . resolve ( { } )
306+ }
307+ } as AI ;
308+ const expectedCount = 10 ;
309+ const countPromptTokensStub = stub ( ) . resolves ( expectedCount ) ;
310+ const factoryStub = stub ( aiProvider . languageModel , 'create' ) . resolves ( {
311+ countPromptTokens : countPromptTokensStub
312+ } as unknown as AILanguageModel ) ;
313+ const text = [ 'first' , 'second' , 'third' ] ;
314+ const onDeviceParams = {
315+ initialPrompts : [ { role : 'user' , content : text [ 0 ] } ]
316+ } as AILanguageModelCreateOptionsWithSystemPrompt ;
317+ const adapter = new ChromeAdapter (
318+ aiProvider ,
319+ 'prefer_on_device' ,
320+ onDeviceParams
321+ ) ;
322+ const response = await adapter . countTokens ( {
323+ contents : [
324+ { role : 'model' , parts : [ { text : text [ 1 ] } ] } ,
325+ { role : 'user' , parts : [ { text : text [ 2 ] } ] }
326+ ]
327+ } ) ;
328+ expect ( factoryStub ) . to . have . been . calledOnceWith ( {
329+ initialPrompts : [
330+ { role : 'user' , content : text [ 0 ] } ,
331+ // Asserts tail is passed as initial prompts, and
332+ // role is normalized from model to assistant.
333+ { role : 'assistant' , content : text [ 1 ] }
334+ ]
335+ } ) ;
336+ expect ( countPromptTokensStub ) . to . have . been . calledOnceWith ( {
337+ role : 'user' ,
338+ content : text [ 2 ]
339+ } ) ;
340+ expect ( await response . json ( ) ) . to . deep . equal ( {
341+ totalTokens : expectedCount
342+ } ) ;
343+ } ) ;
344+ } ) ;
301345} ) ;
0 commit comments