|
15 | 15 | * limitations under the License.
|
16 | 16 | */
|
17 | 17 |
|
18 |
| -import { GenerateContentRequest, InferenceMode } from '../types'; |
19 | 18 | import {
|
| 19 | + Content, |
| 20 | + GenerateContentRequest, |
| 21 | + InferenceMode, |
| 22 | + Part, |
| 23 | + Role, |
| 24 | + TextPart |
| 25 | +} from '../types'; |
| 26 | +import { |
| 27 | + Availability, |
20 | 28 | LanguageModel,
|
21 |
| - LanguageModelCreateOptions |
| 29 | + LanguageModelCreateOptions, |
| 30 | + LanguageModelMessageRole, |
| 31 | + LanguageModelMessageShorthand |
22 | 32 | } from '../types/language-model';
|
| 33 | +import { isChrome } from '@firebase/util'; |
23 | 34 |
|
24 | 35 | /**
|
25 | 36 | * Defines an inference "backend" that uses Chrome's on-device model,
|
26 | 37 | * and encapsulates logic for detecting when on-device is possible.
|
27 | 38 | */
|
28 | 39 | export class ChromeAdapter {
|
| 40 | + downloadPromise: Promise<LanguageModel> | undefined; |
| 41 | + oldSession: LanguageModel | undefined; |
29 | 42 | constructor(
|
30 | 43 | private languageModelProvider?: LanguageModel,
|
31 | 44 | private mode?: InferenceMode,
|
32 | 45 | private onDeviceParams?: LanguageModelCreateOptions
|
33 | 46 | ) {}
|
34 |
| - // eslint-disable-next-line @typescript-eslint/no-unused-vars |
| 47 | + /** |
| 48 | + * Convenience method to check if a given request can be made on-device. |
| 49 | + * Encapsulates a few concerns: 1) the mode, 2) API existence, 3) prompt formatting, and |
| 50 | + * 4) model availability, including triggering download if necessary. |
| 51 | + * Pros: caller needn't be concerned with details of on-device availability. Cons: this method |
| 52 | + * spans a few concerns and splits request validation from usage. If instance variables weren't |
| 53 | + * already part of the API, we could consider a better separation of concerns. |
| 54 | + */ |
35 | 55 | async isAvailable(request: GenerateContentRequest): Promise<boolean> {
|
36 |
| - return false; |
| 56 | + // Returns false if we should only use in-cloud inference. |
| 57 | + if (this.mode === 'only_in_cloud') { |
| 58 | + return false; |
| 59 | + } |
| 60 | + // Returns false because only Chrome's experimental Prompt API is supported. |
| 61 | + if (!isChrome()) { |
| 62 | + return false; |
| 63 | + } |
| 64 | + // Returns false if the on-device inference API is undefined.; |
| 65 | + if (!this.languageModelProvider) { |
| 66 | + return false; |
| 67 | + } |
| 68 | + // Returns false if the request can't be run on-device. |
| 69 | + if (!ChromeAdapter._isOnDeviceRequest(request)) { |
| 70 | + return false; |
| 71 | + } |
| 72 | + const availability = await this.languageModelProvider.availability(); |
| 73 | + switch (availability) { |
| 74 | + case Availability.available: |
| 75 | + // Returns true only if a model is immediately available. |
| 76 | + return true; |
| 77 | + case Availability.downloadable: |
| 78 | + // Triggers async download if model is downloadable. |
| 79 | + this.download(); |
| 80 | + default: |
| 81 | + return false; |
| 82 | + } |
37 | 83 | }
|
38 | 84 | async generateContentOnDevice(
|
39 |
| - // eslint-disable-next-line @typescript-eslint/no-unused-vars |
40 | 85 | request: GenerateContentRequest
|
41 | 86 | ): Promise<Response> {
|
| 87 | + const initialPrompts = ChromeAdapter.toInitialPrompts(request.contents); |
| 88 | + // Assumes validation asserted there is at least one initial prompt. |
| 89 | + const prompt = initialPrompts.pop()!; |
| 90 | + const systemPrompt = ChromeAdapter.toSystemPrompt( |
| 91 | + request.systemInstruction |
| 92 | + ); |
| 93 | + const session = await this.session({ |
| 94 | + initialPrompts, |
| 95 | + systemPrompt |
| 96 | + }); |
| 97 | + const text = await session.prompt(prompt.content); |
42 | 98 | return {
|
43 | 99 | json: () =>
|
44 | 100 | Promise.resolve({
|
45 | 101 | candidates: [
|
46 | 102 | {
|
47 | 103 | content: {
|
48 |
| - parts: [{ text: '' }] |
| 104 | + parts: [{ text }] |
49 | 105 | }
|
50 | 106 | }
|
51 | 107 | ]
|
52 | 108 | })
|
53 | 109 | } as Response;
|
54 | 110 | }
|
| 111 | + // Visible for testing |
| 112 | + static _isOnDeviceRequest(request: GenerateContentRequest): boolean { |
| 113 | + if (request.systemInstruction) { |
| 114 | + const systemContent = request.systemInstruction as Content; |
| 115 | + // Returns false if the role can't be represented on-device. |
| 116 | + if (systemContent.role && systemContent.role === 'function') { |
| 117 | + return false; |
| 118 | + } |
| 119 | + |
| 120 | + // Returns false if the system prompt is multi-part. |
| 121 | + if (systemContent.parts && systemContent.parts.length > 1) { |
| 122 | + return false; |
| 123 | + } |
| 124 | + |
| 125 | + // Returns false if the system prompt isn't text. |
| 126 | + const systemText = request.systemInstruction as TextPart; |
| 127 | + if (!systemText.text) { |
| 128 | + return false; |
| 129 | + } |
| 130 | + } |
| 131 | + |
| 132 | + // Returns false if the prompt is empty. |
| 133 | + if (request.contents.length === 0) { |
| 134 | + return false; |
| 135 | + } |
| 136 | + |
| 137 | + // Applies the same checks as above, but for each content item. |
| 138 | + for (const content of request.contents) { |
| 139 | + if (content.role === 'function') { |
| 140 | + return false; |
| 141 | + } |
| 142 | + |
| 143 | + if (content.parts.length > 1) { |
| 144 | + return false; |
| 145 | + } |
| 146 | + |
| 147 | + if (!content.parts[0].text) { |
| 148 | + return false; |
| 149 | + } |
| 150 | + } |
| 151 | + |
| 152 | + return true; |
| 153 | + } |
| 154 | + private download(): void { |
| 155 | + if (this.downloadPromise) { |
| 156 | + return; |
| 157 | + } |
| 158 | + this.downloadPromise = this.languageModelProvider |
| 159 | + ?.create(this.onDeviceParams) |
| 160 | + .then((model: LanguageModel) => { |
| 161 | + delete this.downloadPromise; |
| 162 | + return model; |
| 163 | + }); |
| 164 | + return; |
| 165 | + } |
| 166 | + private static toSystemPrompt( |
| 167 | + prompt: string | Content | Part | undefined |
| 168 | + ): string | undefined { |
| 169 | + if (!prompt) { |
| 170 | + return undefined; |
| 171 | + } |
| 172 | + |
| 173 | + if (typeof prompt === 'string') { |
| 174 | + return prompt; |
| 175 | + } |
| 176 | + |
| 177 | + const systemContent = prompt as Content; |
| 178 | + if ( |
| 179 | + systemContent.parts && |
| 180 | + systemContent.parts[0] && |
| 181 | + systemContent.parts[0].text |
| 182 | + ) { |
| 183 | + return systemContent.parts[0].text; |
| 184 | + } |
| 185 | + |
| 186 | + const systemPart = prompt as Part; |
| 187 | + if (systemPart.text) { |
| 188 | + return systemPart.text; |
| 189 | + } |
| 190 | + |
| 191 | + return undefined; |
| 192 | + } |
| 193 | + private static toOnDeviceRole(role: Role): LanguageModelMessageRole { |
| 194 | + return role === 'model' ? 'assistant' : 'user'; |
| 195 | + } |
| 196 | + private static toInitialPrompts( |
| 197 | + contents: Content[] |
| 198 | + ): LanguageModelMessageShorthand[] { |
| 199 | + return contents.map(c => ({ |
| 200 | + role: ChromeAdapter.toOnDeviceRole(c.role), |
| 201 | + // Assumes contents have been verified to contain only a single TextPart. |
| 202 | + content: c.parts[0].text! |
| 203 | + })); |
| 204 | + } |
| 205 | + private async session( |
| 206 | + opts: LanguageModelCreateOptions |
| 207 | + ): Promise<LanguageModel> { |
| 208 | + const newSession = await this.languageModelProvider!.create(opts); |
| 209 | + if (this.oldSession) { |
| 210 | + this.oldSession.destroy(); |
| 211 | + } |
| 212 | + // Holds session reference, so model isn't unloaded from memory. |
| 213 | + this.oldSession = newSession; |
| 214 | + return newSession; |
| 215 | + } |
55 | 216 | }
|
0 commit comments