@@ -148,3 +148,74 @@ export class GenerativeModel extends VertexAIModel {
148148 return countTokens ( this . _apiSettings , this . model , formattedParams ) ;
149149 }
150150}
151+
152+ interface ChatMethods {
153+ sendMessage (
154+ request : string | Array < string | Part >
155+ ) : Promise < GenerateContentResult > ;
156+ }
157+ class HybridChat implements ChatMethods {
158+ constructor (
159+ private remoteModel : GenerativeModel ,
160+ private localModel : LocalModel
161+ ) { }
162+ async sendMessage (
163+ request : string | Array < string | Part >
164+ ) : Promise < GenerateContentResult > {
165+ if ( await this . localModel . isSupported ( request ) ) {
166+ return this . localModel . generateContent ( request ) ;
167+ }
168+ return this . remoteModel . generateContent ( request ) ;
169+ }
170+ }
171+ interface GenModelMethods {
172+ generateContent (
173+ request : GenerateContentRequest | string | Array < string | Part >
174+ ) : Promise < GenerateContentResult > ;
175+ }
176+ /**
177+ * Normalizes Chrome API, if available, to Vertex API
178+ */
179+ export class LocalModel implements GenModelMethods {
180+ constructor ( private aiProvider ?: AI ) { }
181+ async generateContent (
182+ request : GenerateContentRequest | string | Array < string | Part >
183+ ) : Promise < GenerateContentResult > {
184+ const session = await this . session ( ) ;
185+ if ( typeof request !== 'string' ) {
186+ throw new Error ( 'unsupported request format' ) ;
187+ }
188+ const result = await session . prompt ( request ) ;
189+ return {
190+ response : {
191+ text : ( ) => result ,
192+ functionCalls : ( ) => undefined
193+ }
194+ } as GenerateContentResult ;
195+ }
196+ async isSupported (
197+ request : string | Array < string | Part > | GenerateContentRequest
198+ ) : Promise < boolean > {
199+ return typeof request === 'string' ;
200+ }
201+ private async session ( ) : Promise < AILanguageModel > {
202+ return this . aiProvider ! . languageModel . create ( ) ;
203+ }
204+ }
205+ export class HybridModel implements GenModelMethods {
206+ constructor (
207+ private remoteModel : GenerativeModel ,
208+ private localModel : LocalModel
209+ ) { }
210+ async generateContent (
211+ request : GenerateContentRequest | string | Array < string | Part >
212+ ) : Promise < GenerateContentResult > {
213+ if ( await this . localModel . isSupported ( request ) ) {
214+ return this . localModel . generateContent ( request ) ;
215+ }
216+ return this . remoteModel . generateContent ( request ) ;
217+ }
218+ startChat ( ) : HybridChat {
219+ return new HybridChat ( this . remoteModel , this . localModel ) ;
220+ }
221+ }
0 commit comments