libre-webui 0.45.0 → 0.45.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/backend/dist/routes/work.js +1 -1
- package/backend/dist/routes/work.js.map +1 -1
- package/backend/dist/services/ollamaService.d.ts.map +1 -1
- package/backend/dist/services/ollamaService.js +2 -1
- package/backend/dist/services/ollamaService.js.map +1 -1
- package/backend/dist/services/pluginService.d.ts.map +1 -1
- package/backend/dist/services/pluginService.js +24 -10
- package/backend/dist/services/pluginService.js.map +1 -1
- package/backend/dist/services/workModelProviderService.d.ts.map +1 -1
- package/backend/dist/services/workModelProviderService.js +13 -131
- package/backend/dist/services/workModelProviderService.js.map +1 -1
- package/backend/dist/types/index.d.ts +3 -3
- package/backend/dist/types/index.d.ts.map +1 -1
- package/backend/dist/utils/decisionProtocol.d.ts.map +1 -1
- package/backend/dist/utils/decisionProtocol.js +3 -1
- package/backend/dist/utils/decisionProtocol.js.map +1 -1
- package/backend/dist/utils/geminiProtocol.d.ts +103 -0
- package/backend/dist/utils/geminiProtocol.d.ts.map +1 -0
- package/backend/dist/utils/geminiProtocol.js +582 -0
- package/backend/dist/utils/geminiProtocol.js.map +1 -0
- package/backend/dist/utils/openAIResponsesAdapter.d.ts +1 -1
- package/backend/dist/utils/openAIResponsesAdapter.d.ts.map +1 -1
- package/backend/dist/utils/pluginChatAdapter.d.ts +13 -11
- package/backend/dist/utils/pluginChatAdapter.d.ts.map +1 -1
- package/backend/dist/utils/pluginChatAdapter.js +60 -125
- package/backend/dist/utils/pluginChatAdapter.js.map +1 -1
- package/backend/dist/utils/pluginDefinitionTrust.js +1 -1
- package/backend/dist/utils/pluginValidation.d.ts.map +1 -1
- package/backend/dist/utils/pluginValidation.js +7 -0
- package/backend/dist/utils/pluginValidation.js.map +1 -1
- package/backend/dist/utils/thinkingOptions.d.ts +12 -1
- package/backend/dist/utils/thinkingOptions.d.ts.map +1 -1
- package/backend/dist/utils/thinkingOptions.js +10 -1
- package/backend/dist/utils/thinkingOptions.js.map +1 -1
- package/backend/package.json +1 -1
- package/frontend/dist/artifact-runtime/.build-fingerprint +1 -1
- package/frontend/dist/assets/index-Bi4dLGow.js +32 -0
- package/frontend/dist/index.html +20 -20
- package/frontend/dist/js/{ArtifactContainer-DCCcjK16.js → ArtifactContainer-CFVJv-mM.js} +1 -1
- package/frontend/dist/js/{ArtifactDemoPage-C-1acgxJ.js → ArtifactDemoPage-DH0FzsNI.js} +1 -1
- package/frontend/dist/js/{ArtifactSandboxFrame-BXWNhmtI.js → ArtifactSandboxFrame-WnLSNpGj.js} +1 -1
- package/frontend/dist/js/{ArtifactSlideOutPanel-CvfdP_o2.js → ArtifactSlideOutPanel-ASrltUrj.js} +1 -1
- package/frontend/dist/js/{AutomationModal-D7qiRMhj.js → AutomationModal-CyKk0tlC.js} +1 -1
- package/frontend/dist/js/{AutomationsPage-v98Ucl9p.js → AutomationsPage-DyWCHZB4.js} +1 -1
- package/frontend/dist/js/{AvatarUpload-W41SCHKE.js → AvatarUpload-CndjrKep.js} +1 -1
- package/frontend/dist/js/{CalendarPage-DkAa61Pa.js → CalendarPage-CoUeeBLZ.js} +1 -1
- package/frontend/dist/js/{ChannelsPage-0Vnfpgdr.js → ChannelsPage-BTtm0zgq.js} +1 -1
- package/frontend/dist/js/{ChatPage-iyMY-uoE.js → ChatPage-CNVzf1Nh.js} +2 -2
- package/frontend/dist/js/{ConnectModels-CpWO6ALS.js → ConnectModels-BNmJfvfw.js} +1 -1
- package/frontend/dist/js/{EvaluationsPage-C7WHA1MJ.js → EvaluationsPage-Duxm4ft2.js} +1 -1
- package/frontend/dist/js/{FirstTimeSetup-B8wcelBc.js → FirstTimeSetup-BZ4pQGa_.js} +1 -1
- package/frontend/dist/js/{GalleryPage-u7dYKl3q.js → GalleryPage-BD_mUDta.js} +1 -1
- package/frontend/dist/js/{HomePage-Cjlt3b9n.js → HomePage-CllRyMmx.js} +1 -1
- package/frontend/dist/js/{LanguageSwitcher-gbTZY15P.js → LanguageSwitcher-D4QF6lpW.js} +1 -1
- package/frontend/dist/js/{ModelManagerModals-12hL-b-U.js → ModelManagerModals-BjLwU-MI.js} +1 -1
- package/frontend/dist/js/{NotesPage-BQWBA5li.js → NotesPage-DFL_4FyE.js} +1 -1
- package/frontend/dist/js/{PasswordStrengthMeter-DdqX0FXA.js → PasswordStrengthMeter-Cvrt6Q9S.js} +1 -1
- package/frontend/dist/js/{PersonasPage-B8mFdWcX.js → PersonasPage-C0FD_dR6.js} +1 -1
- package/frontend/dist/js/{PluginUsagePage-Uz6aHPIp.js → PluginUsagePage-D5cfifCU.js} +1 -1
- package/frontend/dist/js/{RichMessageContent-DwMoWuR_.js → RichMessageContent-BQtj6ZIo.js} +1 -1
- package/frontend/dist/js/{RichMessageContent-CVk-fp0N.js → RichMessageContent-BTq5fi2Q.js} +1 -1
- package/frontend/dist/js/SettingsModal-D4K6DG99.js +19 -0
- package/frontend/dist/js/{ShareDialog-NwirTDLR.js → ShareDialog-JrPQi4_S.js} +1 -1
- package/frontend/dist/js/{StrandsPage-ddHNdb6J.js → StrandsPage-CG4rywyz.js} +1 -1
- package/frontend/dist/js/{SystemPage-C_1exwI7.js → SystemPage-DSHe65ZO.js} +1 -1
- package/frontend/dist/js/{UserManagementPanel-hg7ztEtL.js → UserManagementPanel-B5p2mcC9.js} +1 -1
- package/frontend/dist/js/{WhatsNewModal-yYk7N4KY.js → WhatsNewModal-CeHAg8Uz.js} +1 -1
- package/frontend/dist/js/{WorkPage-i7yYRAuj.js → WorkPage-Cq_VMf9T.js} +1 -1
- package/frontend/dist/js/api-1Ym789zb.js +1 -0
- package/frontend/dist/js/{api-Dasm8tVY.js → api-R43sAAC-.js} +1 -1
- package/frontend/dist/js/{appNavigation-DqP7fTWU.js → appNavigation-C59KQTgx.js} +1 -1
- package/frontend/dist/js/{appStore-DCIUnT8X.js → appStore-DDxf13l_.js} +2 -2
- package/frontend/dist/js/appVersion-6CB3OX6W.js +1 -0
- package/frontend/dist/js/ar-Cq-76la4.js +2 -0
- package/frontend/dist/js/authStore-KZxTYkaU.js +1 -0
- package/frontend/dist/js/{authStore-ac5-hjOH.js → authStore-RsBcSMMM.js} +3 -3
- package/frontend/dist/js/bn-sjvarZOb.js +2 -0
- package/frontend/dist/js/chatStore-D-0TPlCx.js +3 -0
- package/frontend/dist/js/{client-DxPoTB_C.js → client-b-EoJr_G.js} +2 -2
- package/frontend/dist/js/{config-CQJEcQtz.js → config-cjZnwBYY.js} +1 -1
- package/frontend/dist/js/cs-HDycqDhD.js +2 -0
- package/frontend/dist/js/da-BVFJgeVO.js +2 -0
- package/frontend/dist/js/de-BvHBSBK4.js +2 -0
- package/frontend/dist/js/decisionsApi-6OUw07DU.js +1 -0
- package/frontend/dist/js/{decisionsApi-BWB64EGn.js → decisionsApi-CCPE-Qru.js} +1 -1
- package/frontend/dist/js/es-DbVEuhTV.js +2 -0
- package/frontend/dist/js/{evaluationsApi-CBqKkjmI.js → evaluationsApi-Due3Xmlx.js} +1 -1
- package/frontend/dist/js/fr-B1KGm4dd.js +2 -0
- package/frontend/dist/js/hi-DxJ8DThp.js +2 -0
- package/frontend/dist/js/id-BeHcweMq.js +2 -0
- package/frontend/dist/js/is-g5BLxkpl.js +2 -0
- package/frontend/dist/js/it-Dc4XkI8W.js +2 -0
- package/frontend/dist/js/ja-CDtOkRnL.js +2 -0
- package/frontend/dist/js/ko-BBKgPWyC.js +2 -0
- package/frontend/dist/js/{messageCodeStyles-BugWE4s5.js → messageCodeStyles-DQBFoYPS.js} +1 -1
- package/frontend/dist/js/modelPresentation-ChKS6M4O.js +1 -0
- package/frontend/dist/js/ms-rIHXR3GT.js +2 -0
- package/frontend/dist/js/nl-CoQBZ4yX.js +2 -0
- package/frontend/dist/js/pl-DEEj4YnX.js +2 -0
- package/frontend/dist/js/pt-CRlblKN3.js +2 -0
- package/frontend/dist/js/ru-CWyM0zYW.js +2 -0
- package/frontend/dist/js/{strandsApi-Ck7FrcHH.js → strandsApi-dlXURr1J.js} +1 -1
- package/frontend/dist/js/sv-BZb9WtOT.js +2 -0
- package/frontend/dist/js/{teamEventStream-O3qGbUZz.js → teamEventStream-LCbFl9c-.js} +1 -1
- package/frontend/dist/js/th-CyVttEeX.js +2 -0
- package/frontend/dist/js/tr-8W-DKlX6.js +2 -0
- package/frontend/dist/js/{ui-DxaHE9GD.js → ui-CtgjJ55f.js} +2 -2
- package/frontend/dist/js/{ui-vendor-DsURZnZt.js → ui-vendor-CjZizWzb.js} +1 -1
- package/frontend/dist/js/uk-CCS3WiT5.js +2 -0
- package/frontend/dist/js/{useChat-1HyAPpCk.js → useChat-DJk_sA_g.js} +1 -1
- package/frontend/dist/js/useDictation-C5NoYnvs.js +1 -0
- package/frontend/dist/js/vi-9LSI-JjZ.js +2 -0
- package/frontend/dist/js/workApi-CEjmKHnw.js +1 -0
- package/frontend/dist/js/{workApi-BNGRSv7q.js → workApi-DoqjHVys.js} +1 -1
- package/frontend/dist/js/zh-B8TvwSpQ.js +2 -0
- package/package.json +3 -3
- package/plugins/gemini.json +6 -1
- package/frontend/dist/assets/index-C2A5Ko4-.js +0 -59
- package/frontend/dist/js/SettingsModal-CfjxNSmJ.js +0 -19
- package/frontend/dist/js/api-BU13N8gU.js +0 -1
- package/frontend/dist/js/appVersion-PJGaVilS.js +0 -1
- package/frontend/dist/js/ar-CsCftCVF.js +0 -2
- package/frontend/dist/js/authStore-Bp17zKvS.js +0 -1
- package/frontend/dist/js/bn-CvxUTZ9a.js +0 -2
- package/frontend/dist/js/chatStore-GhucyjJu.js +0 -3
- package/frontend/dist/js/cs-BovmMwcD.js +0 -2
- package/frontend/dist/js/da-Dof1gmsv.js +0 -2
- package/frontend/dist/js/de-CF9CXojW.js +0 -2
- package/frontend/dist/js/decisionsApi-CoJtg4PZ.js +0 -1
- package/frontend/dist/js/es-BXCt50HZ.js +0 -2
- package/frontend/dist/js/fr-B5QcCDIw.js +0 -2
- package/frontend/dist/js/hi-BXYwSyKl.js +0 -2
- package/frontend/dist/js/id-BV3mY5L7.js +0 -2
- package/frontend/dist/js/is-BDK4LrQC.js +0 -2
- package/frontend/dist/js/it-DAeWl1Fm.js +0 -2
- package/frontend/dist/js/ja-DIJV01rA.js +0 -2
- package/frontend/dist/js/ko-Btr9-64X.js +0 -2
- package/frontend/dist/js/ms-DgVmv5zF.js +0 -2
- package/frontend/dist/js/nl-Dz5HpdLi.js +0 -2
- package/frontend/dist/js/pl-CIATY2b0.js +0 -2
- package/frontend/dist/js/pt-lrDXX76Y.js +0 -2
- package/frontend/dist/js/ru-_zovUYcg.js +0 -2
- package/frontend/dist/js/sv-TkRDWCb8.js +0 -2
- package/frontend/dist/js/th-CQyavDiP.js +0 -2
- package/frontend/dist/js/thinking-DwlkTfPX.js +0 -1
- package/frontend/dist/js/tr-CBcFl4_Z.js +0 -2
- package/frontend/dist/js/uk-BNn1cUt8.js +0 -2
- package/frontend/dist/js/useDictation-B3vNgs5D.js +0 -1
- package/frontend/dist/js/vi-Be8GO7e_.js +0 -2
- package/frontend/dist/js/workApi-C5jw1ra6.js +0 -1
- package/frontend/dist/js/zh-9CUKyYw5.js +0 -2
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The Gemini API's own wire format (`generateContent` and
|
|
3
|
+
* `streamGenerateContent`), shared by Chat and Work so the two cannot drift.
|
|
4
|
+
*
|
|
5
|
+
* Gemini differs from the OpenAI shape in every place that matters: the
|
|
6
|
+
* conversation is `contents` with `user` and `model` roles, the system prompt
|
|
7
|
+
* is a separate `systemInstruction`, tools are `functionDeclarations`, a tool
|
|
8
|
+
* result is a `functionResponse` part, and a stream is a sequence of whole
|
|
9
|
+
* `GenerateContentResponse` objects rather than deltas.
|
|
10
|
+
*/
|
|
11
|
+
import type { ChatMessage, PluginResponse, ProviderToolSpec } from '../types/index.js';
|
|
12
|
+
import type { PluginStreamChunk } from './pluginStreamAdapter.js';
|
|
13
|
+
/**
|
|
14
|
+
* Where a reply's thought signatures are kept. Signatures are tied to the
|
|
15
|
+
* model that produced them, so the model travels with them and a different
|
|
16
|
+
* model never receives another one's.
|
|
17
|
+
*/
|
|
18
|
+
export declare const GEMINI_THOUGHT_SIGNATURES_METADATA_KEY = "geminiThoughtSignatures";
|
|
19
|
+
export interface GeminiThoughtSignatures {
|
|
20
|
+
model: string;
|
|
21
|
+
/** The signature on the reply's text, if the model attached one there. */
|
|
22
|
+
text?: string;
|
|
23
|
+
/** Signatures on function calls, keyed by call id. */
|
|
24
|
+
calls?: Record<string, string>;
|
|
25
|
+
}
|
|
26
|
+
/** The synchronous output ceiling of every current Gemini text model. */
|
|
27
|
+
export declare const GEMINI_MAX_OUTPUT_TOKENS = 65536;
|
|
28
|
+
type JsonObject = Record<string, unknown>;
|
|
29
|
+
/** `gemini-3.8-flash` is generation 3.8; aliases have no generation. */
|
|
30
|
+
export declare function geminiModelGeneration(model: string): number | undefined;
|
|
31
|
+
/**
|
|
32
|
+
* Gemini 3 and later take a named `thinkingLevel`; Google's reference says
|
|
33
|
+
* sending one to an earlier model is an error, and its migration guides
|
|
34
|
+
* replace `thinkingBudget` with the level from Gemini 3.8 Flash on. The
|
|
35
|
+
* `-latest` aliases point at Gemini 3 models.
|
|
36
|
+
*/
|
|
37
|
+
export declare function geminiUsesThinkingLevels(model: string): boolean;
|
|
38
|
+
/**
|
|
39
|
+
* Temperature and top-p are deprecated, and silently ignored on Gemini 3.6
|
|
40
|
+
* Flash and newer models, so they are not sent there.
|
|
41
|
+
*/
|
|
42
|
+
export declare function geminiIgnoresSampling(model: string): boolean;
|
|
43
|
+
/**
|
|
44
|
+
* The thinking part of a generation config. Gemini counts thinking against
|
|
45
|
+
* `maxOutputTokens`, so a budget is fitted beside the answer; a level has no
|
|
46
|
+
* size, so the ceiling is whatever was asked for, or the model's own when
|
|
47
|
+
* nothing was. Nothing is sent for an unset preference.
|
|
48
|
+
*/
|
|
49
|
+
export declare function resolveGeminiThinking(model: string, think: unknown, requestedMaxTokens: number | undefined): {
|
|
50
|
+
maxOutputTokens?: number;
|
|
51
|
+
thinkingConfig?: JsonObject;
|
|
52
|
+
};
|
|
53
|
+
/** Sampling fields for a generation config, left out where Gemini ignores them. */
|
|
54
|
+
export declare function geminiSamplingConfig(model: string, params: {
|
|
55
|
+
temperature?: number;
|
|
56
|
+
topP?: number;
|
|
57
|
+
}): JsonObject;
|
|
58
|
+
/** The signatures a stored reply carries, if the same model produced them. */
|
|
59
|
+
export declare function readGeminiThoughtSignatures(providerMetadata: Record<string, unknown> | undefined, model: string): GeminiThoughtSignatures | undefined;
|
|
60
|
+
/**
|
|
61
|
+
* A chat history as Gemini contents. System messages become the system
|
|
62
|
+
* instruction; images travel as inline data beside the text they came with;
|
|
63
|
+
* an in-turn tool round becomes `functionCall` parts answered by
|
|
64
|
+
* `functionResponse` parts. Thought signatures go back on the parts they came
|
|
65
|
+
* from, and only to the model that issued them.
|
|
66
|
+
*/
|
|
67
|
+
export declare function toGeminiContents(messages: readonly ChatMessage[], model: string): {
|
|
68
|
+
systemInstruction?: {
|
|
69
|
+
parts: Array<{
|
|
70
|
+
text: string;
|
|
71
|
+
}>;
|
|
72
|
+
};
|
|
73
|
+
contents: Array<{
|
|
74
|
+
role: 'user' | 'model';
|
|
75
|
+
parts: JsonObject[];
|
|
76
|
+
}>;
|
|
77
|
+
};
|
|
78
|
+
export declare function toGeminiTools(tools: readonly ProviderToolSpec[] | undefined): JsonObject[] | undefined;
|
|
79
|
+
/**
|
|
80
|
+
* One page of `models.list` as listing entries in the shape model discovery
|
|
81
|
+
* reads: the id without its `models/` prefix, the input limit as the context
|
|
82
|
+
* window, and the listing's own `thinking` flag as reasoning support. Only the
|
|
83
|
+
* text chat models that answer generateContent are kept.
|
|
84
|
+
*/
|
|
85
|
+
export declare function readGeminiModelListing(models: readonly unknown[]): JsonObject[];
|
|
86
|
+
/**
|
|
87
|
+
* Every page of `models.list`. Google returns at most 1,000 models a page and
|
|
88
|
+
* omits `nextPageToken` on the last one; the page count is bounded so a
|
|
89
|
+
* misbehaving server cannot keep discovery going.
|
|
90
|
+
*/
|
|
91
|
+
export declare function listGeminiModels(modelsEndpoint: string, fetchPage: (url: string) => Promise<unknown>, maxPages?: number): Promise<JsonObject[]>;
|
|
92
|
+
/** `:generateContent` becomes the server-sent-events stream of the same call. */
|
|
93
|
+
export declare function geminiStreamingEndpoint(endpoint: string): string;
|
|
94
|
+
/**
|
|
95
|
+
* A `streamGenerateContent?alt=sse` response as stream chunks. A server that
|
|
96
|
+
* answers with plain JSON instead (a whole response, or the JSON array the
|
|
97
|
+
* stream returns without `alt=sse`) is read the same way.
|
|
98
|
+
*/
|
|
99
|
+
export declare function streamGeminiResponse(response: Response, model: string): AsyncGenerator<PluginStreamChunk, void, unknown>;
|
|
100
|
+
/** A whole `generateContent` response in the OpenAI-shaped plugin response. */
|
|
101
|
+
export declare function convertGeminiResponse(geminiResponse: Record<string, unknown>, model: string): PluginResponse;
|
|
102
|
+
export {};
|
|
103
|
+
//# sourceMappingURL=geminiProtocol.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"geminiProtocol.d.ts","sourceRoot":"","sources":["../../src/utils/geminiProtocol.ts"],"names":[],"mappings":"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"}
|
|
@@ -0,0 +1,582 @@
|
|
|
1
|
+
/*
|
|
2
|
+
* Libre WebUI
|
|
3
|
+
* Copyright (C) 2025 Kroonen AI, Inc.
|
|
4
|
+
*
|
|
5
|
+
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
6
|
+
* you may not use this file except in compliance with the License.
|
|
7
|
+
* You may obtain a copy of the License at:
|
|
8
|
+
*
|
|
9
|
+
* http://www.apache.org/licenses/LICENSE-2.0
|
|
10
|
+
*
|
|
11
|
+
* Unless required by applicable law or agreed to in writing, software
|
|
12
|
+
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
13
|
+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
14
|
+
* See the License for the specific language governing permissions and
|
|
15
|
+
* limitations under the License.
|
|
16
|
+
*/
|
|
17
|
+
import { fitThinkingBudget, normalizeThinkingPreference, thinkingBudgetTokens, } from './thinkingOptions.js';
|
|
18
|
+
/**
|
|
19
|
+
* Where a reply's thought signatures are kept. Signatures are tied to the
|
|
20
|
+
* model that produced them, so the model travels with them and a different
|
|
21
|
+
* model never receives another one's.
|
|
22
|
+
*/
|
|
23
|
+
export const GEMINI_THOUGHT_SIGNATURES_METADATA_KEY = 'geminiThoughtSignatures';
|
|
24
|
+
/**
|
|
25
|
+
* Ids the stream assigns to function calls that arrived without one. Gemini
|
|
26
|
+
* never issued them, so they are not sent back on the wire.
|
|
27
|
+
*/
|
|
28
|
+
const LOCAL_CALL_ID_PREFIX = 'gemini-call-';
|
|
29
|
+
/** The synchronous output ceiling of every current Gemini text model. */
|
|
30
|
+
export const GEMINI_MAX_OUTPUT_TOKENS = 65536;
|
|
31
|
+
/**
|
|
32
|
+
* Models whose lowest thinking level is `minimal` ("near-off"), per Google's
|
|
33
|
+
* thinking guide. Thinking cannot be switched off on Gemini 3 and later, so
|
|
34
|
+
* this is what **Off** becomes where it exists. Gemini 3.8 Flash and the
|
|
35
|
+
* Gemini 4 models reject `minimal`.
|
|
36
|
+
*/
|
|
37
|
+
const GEMINI_MINIMAL_THINKING_MODELS = new Set([
|
|
38
|
+
'gemini-3-flash-preview',
|
|
39
|
+
'gemini-3.1-flash-lite',
|
|
40
|
+
'gemini-3.5-flash-lite',
|
|
41
|
+
'gemini-3.6-flash',
|
|
42
|
+
]);
|
|
43
|
+
/**
|
|
44
|
+
* Models that take the `xhigh` level above high. Google's thinking guide lists
|
|
45
|
+
* it for Gemini 4 Hydrogen only; elsewhere extra high asks for `high`.
|
|
46
|
+
*/
|
|
47
|
+
const GEMINI_XHIGH_THINKING_MODELS = new Set(['gemini-4-hydrogen']);
|
|
48
|
+
/**
|
|
49
|
+
* Gemini 2.5 Flash and Flash-Lite cap a thinking budget at 24,576 tokens
|
|
50
|
+
* (Pro at 32,768), so the budget for extra high stays inside every 2.5 model.
|
|
51
|
+
*/
|
|
52
|
+
const GEMINI_MAX_THINKING_BUDGET = 24576;
|
|
53
|
+
function asObject(value) {
|
|
54
|
+
return value && typeof value === 'object' && !Array.isArray(value)
|
|
55
|
+
? value
|
|
56
|
+
: undefined;
|
|
57
|
+
}
|
|
58
|
+
/** `gemini-3.8-flash` is generation 3.8; aliases have no generation. */
|
|
59
|
+
export function geminiModelGeneration(model) {
|
|
60
|
+
const match = /(?:^|\/)gemini-(\d+(?:\.\d+)?)/.exec(model.toLowerCase());
|
|
61
|
+
return match ? Number(match[1]) : undefined;
|
|
62
|
+
}
|
|
63
|
+
/**
|
|
64
|
+
* Gemini 3 and later take a named `thinkingLevel`; Google's reference says
|
|
65
|
+
* sending one to an earlier model is an error, and its migration guides
|
|
66
|
+
* replace `thinkingBudget` with the level from Gemini 3.8 Flash on. The
|
|
67
|
+
* `-latest` aliases point at Gemini 3 models.
|
|
68
|
+
*/
|
|
69
|
+
export function geminiUsesThinkingLevels(model) {
|
|
70
|
+
const generation = geminiModelGeneration(model);
|
|
71
|
+
if (generation !== undefined)
|
|
72
|
+
return generation >= 3;
|
|
73
|
+
return /(?:^|\/)gemini-(?:flash|flash-lite|pro)-latest$/.test(model.toLowerCase());
|
|
74
|
+
}
|
|
75
|
+
/**
|
|
76
|
+
* Temperature and top-p are deprecated, and silently ignored on Gemini 3.6
|
|
77
|
+
* Flash and newer models, so they are not sent there.
|
|
78
|
+
*/
|
|
79
|
+
export function geminiIgnoresSampling(model) {
|
|
80
|
+
const generation = geminiModelGeneration(model);
|
|
81
|
+
return generation !== undefined && generation >= 3.6;
|
|
82
|
+
}
|
|
83
|
+
function capOutputTokens(tokens) {
|
|
84
|
+
return Math.min(tokens, GEMINI_MAX_OUTPUT_TOKENS);
|
|
85
|
+
}
|
|
86
|
+
/**
|
|
87
|
+
* The thinking part of a generation config. Gemini counts thinking against
|
|
88
|
+
* `maxOutputTokens`, so a budget is fitted beside the answer; a level has no
|
|
89
|
+
* size, so the ceiling is whatever was asked for, or the model's own when
|
|
90
|
+
* nothing was. Nothing is sent for an unset preference.
|
|
91
|
+
*/
|
|
92
|
+
export function resolveGeminiThinking(model, think, requestedMaxTokens) {
|
|
93
|
+
const preference = normalizeThinkingPreference(think);
|
|
94
|
+
const requested = requestedMaxTokens === undefined
|
|
95
|
+
? {}
|
|
96
|
+
: { maxOutputTokens: capOutputTokens(requestedMaxTokens) };
|
|
97
|
+
if (geminiUsesThinkingLevels(model)) {
|
|
98
|
+
if (preference === undefined)
|
|
99
|
+
return requested;
|
|
100
|
+
if (preference === false) {
|
|
101
|
+
return GEMINI_MINIMAL_THINKING_MODELS.has(model)
|
|
102
|
+
? { ...requested, thinkingConfig: { thinkingLevel: 'MINIMAL' } }
|
|
103
|
+
: requested;
|
|
104
|
+
}
|
|
105
|
+
const level = preference === 'xhigh' && !GEMINI_XHIGH_THINKING_MODELS.has(model)
|
|
106
|
+
? 'high'
|
|
107
|
+
: preference;
|
|
108
|
+
return {
|
|
109
|
+
...requested,
|
|
110
|
+
thinkingConfig: {
|
|
111
|
+
...(level === true ? {} : { thinkingLevel: level.toUpperCase() }),
|
|
112
|
+
// Without this the user pays for thinking and sees none.
|
|
113
|
+
includeThoughts: true,
|
|
114
|
+
},
|
|
115
|
+
};
|
|
116
|
+
}
|
|
117
|
+
// Gemini 2.5 takes a token budget. Only an enabled setting is sent: a zero
|
|
118
|
+
// budget is rejected by the models that always reason, so switching
|
|
119
|
+
// thinking off is left to the model.
|
|
120
|
+
const levelBudget = thinkingBudgetTokens(think);
|
|
121
|
+
if (levelBudget === undefined)
|
|
122
|
+
return requested;
|
|
123
|
+
const fitted = fitThinkingBudget(requestedMaxTokens, Math.min(levelBudget, GEMINI_MAX_THINKING_BUDGET));
|
|
124
|
+
return {
|
|
125
|
+
maxOutputTokens: capOutputTokens(fitted.maxTokens),
|
|
126
|
+
thinkingConfig: {
|
|
127
|
+
thinkingBudget: fitted.budgetTokens,
|
|
128
|
+
includeThoughts: true,
|
|
129
|
+
},
|
|
130
|
+
};
|
|
131
|
+
}
|
|
132
|
+
/** Sampling fields for a generation config, left out where Gemini ignores them. */
|
|
133
|
+
export function geminiSamplingConfig(model, params) {
|
|
134
|
+
if (geminiIgnoresSampling(model))
|
|
135
|
+
return {};
|
|
136
|
+
return {
|
|
137
|
+
...(params.temperature !== undefined
|
|
138
|
+
? { temperature: params.temperature }
|
|
139
|
+
: {}),
|
|
140
|
+
...(params.topP !== undefined ? { topP: params.topP } : {}),
|
|
141
|
+
};
|
|
142
|
+
}
|
|
143
|
+
/** The signatures a stored reply carries, if the same model produced them. */
|
|
144
|
+
export function readGeminiThoughtSignatures(providerMetadata, model) {
|
|
145
|
+
const stored = asObject(providerMetadata?.[GEMINI_THOUGHT_SIGNATURES_METADATA_KEY]);
|
|
146
|
+
if (!stored || stored.model !== model)
|
|
147
|
+
return undefined;
|
|
148
|
+
const calls = asObject(stored.calls);
|
|
149
|
+
return {
|
|
150
|
+
model,
|
|
151
|
+
...(typeof stored.text === 'string' ? { text: stored.text } : {}),
|
|
152
|
+
...(calls
|
|
153
|
+
? {
|
|
154
|
+
calls: Object.fromEntries(Object.entries(calls).filter((entry) => typeof entry[1] === 'string')),
|
|
155
|
+
}
|
|
156
|
+
: {}),
|
|
157
|
+
};
|
|
158
|
+
}
|
|
159
|
+
function splitImage(image) {
|
|
160
|
+
const match = /^data:([^;]+);base64,(.+)$/.exec(image);
|
|
161
|
+
return match
|
|
162
|
+
? { mimeType: match[1], data: match[2] }
|
|
163
|
+
: { mimeType: 'image/jpeg', data: image };
|
|
164
|
+
}
|
|
165
|
+
function parseArguments(value) {
|
|
166
|
+
try {
|
|
167
|
+
return asObject(JSON.parse(value)) ?? {};
|
|
168
|
+
}
|
|
169
|
+
catch {
|
|
170
|
+
return {};
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
/**
|
|
174
|
+
* A chat history as Gemini contents. System messages become the system
|
|
175
|
+
* instruction; images travel as inline data beside the text they came with;
|
|
176
|
+
* an in-turn tool round becomes `functionCall` parts answered by
|
|
177
|
+
* `functionResponse` parts. Thought signatures go back on the parts they came
|
|
178
|
+
* from, and only to the model that issued them.
|
|
179
|
+
*/
|
|
180
|
+
export function toGeminiContents(messages, model) {
|
|
181
|
+
const system = messages
|
|
182
|
+
.filter(message => message.role === 'system' && message.content)
|
|
183
|
+
.map(message => message.content)
|
|
184
|
+
.join('\n');
|
|
185
|
+
const contents = [];
|
|
186
|
+
const callNames = new Map();
|
|
187
|
+
const append = (role, parts) => {
|
|
188
|
+
if (parts.length === 0)
|
|
189
|
+
return;
|
|
190
|
+
const previous = contents[contents.length - 1];
|
|
191
|
+
if (previous?.role === role)
|
|
192
|
+
previous.parts.push(...parts);
|
|
193
|
+
else
|
|
194
|
+
contents.push({ role, parts });
|
|
195
|
+
};
|
|
196
|
+
for (const message of messages) {
|
|
197
|
+
if (message.role === 'system')
|
|
198
|
+
continue;
|
|
199
|
+
if (message.role === 'assistant') {
|
|
200
|
+
const signatures = readGeminiThoughtSignatures(message.providerMetadata, model);
|
|
201
|
+
const parts = [];
|
|
202
|
+
if (message.content) {
|
|
203
|
+
parts.push({
|
|
204
|
+
text: message.content,
|
|
205
|
+
...(signatures?.text ? { thoughtSignature: signatures.text } : {}),
|
|
206
|
+
});
|
|
207
|
+
}
|
|
208
|
+
for (const call of message.tool_calls ?? []) {
|
|
209
|
+
callNames.set(call.id, call.function.name);
|
|
210
|
+
const signature = signatures?.calls?.[call.id];
|
|
211
|
+
parts.push({
|
|
212
|
+
functionCall: {
|
|
213
|
+
...(call.id.startsWith(LOCAL_CALL_ID_PREFIX)
|
|
214
|
+
? {}
|
|
215
|
+
: { id: call.id }),
|
|
216
|
+
name: call.function.name,
|
|
217
|
+
args: parseArguments(call.function.arguments),
|
|
218
|
+
},
|
|
219
|
+
...(signature ? { thoughtSignature: signature } : {}),
|
|
220
|
+
});
|
|
221
|
+
}
|
|
222
|
+
append('model', parts);
|
|
223
|
+
continue;
|
|
224
|
+
}
|
|
225
|
+
if (message.role === 'tool') {
|
|
226
|
+
const id = message.tool_call_id ?? '';
|
|
227
|
+
append('user', [
|
|
228
|
+
{
|
|
229
|
+
functionResponse: {
|
|
230
|
+
...(id && !id.startsWith(LOCAL_CALL_ID_PREFIX) ? { id } : {}),
|
|
231
|
+
name: callNames.get(id) ?? 'tool',
|
|
232
|
+
response: { result: message.content },
|
|
233
|
+
},
|
|
234
|
+
},
|
|
235
|
+
]);
|
|
236
|
+
continue;
|
|
237
|
+
}
|
|
238
|
+
const parts = (message.images ?? []).map(image => ({
|
|
239
|
+
inlineData: splitImage(image),
|
|
240
|
+
}));
|
|
241
|
+
if (message.content)
|
|
242
|
+
parts.push({ text: message.content });
|
|
243
|
+
append('user', parts);
|
|
244
|
+
}
|
|
245
|
+
return {
|
|
246
|
+
...(system ? { systemInstruction: { parts: [{ text: system }] } } : {}),
|
|
247
|
+
contents,
|
|
248
|
+
};
|
|
249
|
+
}
|
|
250
|
+
export function toGeminiTools(tools) {
|
|
251
|
+
if (!tools || tools.length === 0)
|
|
252
|
+
return undefined;
|
|
253
|
+
return [
|
|
254
|
+
{
|
|
255
|
+
functionDeclarations: tools.map(tool => ({
|
|
256
|
+
name: tool.name,
|
|
257
|
+
...(tool.description ? { description: tool.description } : {}),
|
|
258
|
+
parameters: tool.parameters ?? { type: 'object', properties: {} },
|
|
259
|
+
})),
|
|
260
|
+
},
|
|
261
|
+
];
|
|
262
|
+
}
|
|
263
|
+
/**
|
|
264
|
+
* Model families the Gemini API serves through generateContent that are not
|
|
265
|
+
* text chat: speech, images, video, music, embeddings, live audio, and agents.
|
|
266
|
+
* Gemma is left out too: the Gemini API serves it without system
|
|
267
|
+
* instructions, which every chat here can carry.
|
|
268
|
+
*/
|
|
269
|
+
const GEMINI_NON_CHAT_MODEL = /(?:^|-)(?:tts|image|imagen|veo|lyria|embedding|aqa|live|audio|native-audio|computer-use|robotics|nano-banana|omni|decision|deep-research|antigravity|learnlm)(?:-|$)|^gemma-/;
|
|
270
|
+
/**
|
|
271
|
+
* One page of `models.list` as listing entries in the shape model discovery
|
|
272
|
+
* reads: the id without its `models/` prefix, the input limit as the context
|
|
273
|
+
* window, and the listing's own `thinking` flag as reasoning support. Only the
|
|
274
|
+
* text chat models that answer generateContent are kept.
|
|
275
|
+
*/
|
|
276
|
+
export function readGeminiModelListing(models) {
|
|
277
|
+
const entries = [];
|
|
278
|
+
const seen = new Set();
|
|
279
|
+
for (const value of models) {
|
|
280
|
+
const model = asObject(value);
|
|
281
|
+
if (!model || typeof model.name !== 'string')
|
|
282
|
+
continue;
|
|
283
|
+
const id = model.name.replace(/^models\//, '');
|
|
284
|
+
const methods = Array.isArray(model.supportedGenerationMethods)
|
|
285
|
+
? model.supportedGenerationMethods
|
|
286
|
+
: Array.isArray(model.supportedActions)
|
|
287
|
+
? model.supportedActions
|
|
288
|
+
: [];
|
|
289
|
+
if (!id ||
|
|
290
|
+
seen.has(id) ||
|
|
291
|
+
!methods.includes('generateContent') ||
|
|
292
|
+
GEMINI_NON_CHAT_MODEL.test(id.toLowerCase())) {
|
|
293
|
+
continue;
|
|
294
|
+
}
|
|
295
|
+
seen.add(id);
|
|
296
|
+
entries.push({
|
|
297
|
+
id,
|
|
298
|
+
...(typeof model.inputTokenLimit === 'number'
|
|
299
|
+
? { context_length: model.inputTokenLimit }
|
|
300
|
+
: {}),
|
|
301
|
+
// An array that names reasoning is how discovery records a listing's
|
|
302
|
+
// own answer, so a model Google says cannot think is not offered it.
|
|
303
|
+
...(typeof model.thinking === 'boolean'
|
|
304
|
+
? { supported_parameters: model.thinking ? ['reasoning'] : [] }
|
|
305
|
+
: {}),
|
|
306
|
+
});
|
|
307
|
+
}
|
|
308
|
+
return entries;
|
|
309
|
+
}
|
|
310
|
+
/**
|
|
311
|
+
* Every page of `models.list`. Google returns at most 1,000 models a page and
|
|
312
|
+
* omits `nextPageToken` on the last one; the page count is bounded so a
|
|
313
|
+
* misbehaving server cannot keep discovery going.
|
|
314
|
+
*/
|
|
315
|
+
export async function listGeminiModels(modelsEndpoint, fetchPage, maxPages = 10) {
|
|
316
|
+
const entries = [];
|
|
317
|
+
let pageToken;
|
|
318
|
+
for (let page = 0; page < maxPages; page++) {
|
|
319
|
+
const url = new URL(modelsEndpoint);
|
|
320
|
+
url.searchParams.set('pageSize', '1000');
|
|
321
|
+
if (pageToken)
|
|
322
|
+
url.searchParams.set('pageToken', pageToken);
|
|
323
|
+
const body = asObject(await fetchPage(url.toString()));
|
|
324
|
+
entries.push(...readGeminiModelListing(Array.isArray(body?.models) ? body.models : []));
|
|
325
|
+
pageToken =
|
|
326
|
+
typeof body?.nextPageToken === 'string' && body.nextPageToken
|
|
327
|
+
? body.nextPageToken
|
|
328
|
+
: undefined;
|
|
329
|
+
if (!pageToken)
|
|
330
|
+
break;
|
|
331
|
+
}
|
|
332
|
+
const seen = new Set();
|
|
333
|
+
return entries
|
|
334
|
+
.filter(entry => !seen.has(String(entry.id)) && seen.add(String(entry.id)))
|
|
335
|
+
.sort((left, right) => String(left.id).localeCompare(String(right.id)));
|
|
336
|
+
}
|
|
337
|
+
/** `:generateContent` becomes the server-sent-events stream of the same call. */
|
|
338
|
+
export function geminiStreamingEndpoint(endpoint) {
|
|
339
|
+
const url = new URL(endpoint);
|
|
340
|
+
url.pathname = url.pathname.replace(/:generateContent$/, ':streamGenerateContent');
|
|
341
|
+
url.searchParams.set('alt', 'sse');
|
|
342
|
+
return url.toString();
|
|
343
|
+
}
|
|
344
|
+
const FINISH_REASONS = {
|
|
345
|
+
STOP: 'stop',
|
|
346
|
+
MAX_TOKENS: 'length',
|
|
347
|
+
SAFETY: 'content_filter',
|
|
348
|
+
RECITATION: 'content_filter',
|
|
349
|
+
BLOCKLIST: 'content_filter',
|
|
350
|
+
PROHIBITED_CONTENT: 'content_filter',
|
|
351
|
+
SPII: 'content_filter',
|
|
352
|
+
IMAGE_SAFETY: 'content_filter',
|
|
353
|
+
};
|
|
354
|
+
function finishReason(value) {
|
|
355
|
+
if (typeof value !== 'string' || value === 'FINISH_REASON_UNSPECIFIED') {
|
|
356
|
+
return undefined;
|
|
357
|
+
}
|
|
358
|
+
return FINISH_REASONS[value] ?? value.toLowerCase();
|
|
359
|
+
}
|
|
360
|
+
function usageFrom(value) {
|
|
361
|
+
const usage = asObject(value);
|
|
362
|
+
if (!usage)
|
|
363
|
+
return undefined;
|
|
364
|
+
const count = (key) => typeof usage[key] === 'number' ? usage[key] : undefined;
|
|
365
|
+
const promptTokens = count('promptTokenCount');
|
|
366
|
+
const candidates = count('candidatesTokenCount');
|
|
367
|
+
const thoughts = count('thoughtsTokenCount');
|
|
368
|
+
// Thinking is billed as output but reported apart from the answer.
|
|
369
|
+
const completionTokens = candidates === undefined && thoughts === undefined
|
|
370
|
+
? undefined
|
|
371
|
+
: (candidates ?? 0) + (thoughts ?? 0);
|
|
372
|
+
const totalTokens = count('totalTokenCount') ??
|
|
373
|
+
(promptTokens !== undefined || completionTokens !== undefined
|
|
374
|
+
? (promptTokens ?? 0) + (completionTokens ?? 0)
|
|
375
|
+
: undefined);
|
|
376
|
+
if (promptTokens === undefined &&
|
|
377
|
+
completionTokens === undefined &&
|
|
378
|
+
totalTokens === undefined) {
|
|
379
|
+
return undefined;
|
|
380
|
+
}
|
|
381
|
+
return { promptTokens, completionTokens, totalTokens };
|
|
382
|
+
}
|
|
383
|
+
function providerError(payload) {
|
|
384
|
+
const error = asObject(payload.error);
|
|
385
|
+
if (typeof error?.message === 'string')
|
|
386
|
+
return error.message.slice(0, 500);
|
|
387
|
+
const blocked = asObject(payload.promptFeedback)?.blockReason;
|
|
388
|
+
if (typeof blocked === 'string' &&
|
|
389
|
+
!(Array.isArray(payload.candidates) && payload.candidates.length > 0)) {
|
|
390
|
+
return `Gemini blocked the prompt (${blocked})`;
|
|
391
|
+
}
|
|
392
|
+
return undefined;
|
|
393
|
+
}
|
|
394
|
+
/**
|
|
395
|
+
* Reads one `GenerateContentResponse`, whole or streamed, into stream chunks
|
|
396
|
+
* and collects the signatures it carries.
|
|
397
|
+
*/
|
|
398
|
+
class GeminiResponseReader {
|
|
399
|
+
constructor(model) {
|
|
400
|
+
this.callIndex = 0;
|
|
401
|
+
this.signatures = { model };
|
|
402
|
+
}
|
|
403
|
+
*read(payload) {
|
|
404
|
+
const error = providerError(payload);
|
|
405
|
+
if (error)
|
|
406
|
+
throw new Error(`Plugin API error: ${error}`);
|
|
407
|
+
const candidates = Array.isArray(payload.candidates)
|
|
408
|
+
? payload.candidates
|
|
409
|
+
: [];
|
|
410
|
+
const candidate = asObject(candidates[0]);
|
|
411
|
+
const parts = asObject(candidate?.content)?.parts;
|
|
412
|
+
for (const rawPart of Array.isArray(parts) ? parts : []) {
|
|
413
|
+
const part = asObject(rawPart);
|
|
414
|
+
if (!part)
|
|
415
|
+
continue;
|
|
416
|
+
const signature = typeof part.thoughtSignature === 'string'
|
|
417
|
+
? part.thoughtSignature
|
|
418
|
+
: undefined;
|
|
419
|
+
const call = asObject(part.functionCall);
|
|
420
|
+
if (call && typeof call.name === 'string') {
|
|
421
|
+
const id = typeof call.id === 'string' && call.id
|
|
422
|
+
? call.id
|
|
423
|
+
: `${LOCAL_CALL_ID_PREFIX}${this.callIndex++}`;
|
|
424
|
+
if (signature) {
|
|
425
|
+
this.signatures.calls = { ...this.signatures.calls, [id]: signature };
|
|
426
|
+
}
|
|
427
|
+
yield {
|
|
428
|
+
type: 'tool_call',
|
|
429
|
+
toolCall: {
|
|
430
|
+
id,
|
|
431
|
+
name: call.name,
|
|
432
|
+
arguments: JSON.stringify(asObject(call.args) ?? {}),
|
|
433
|
+
...(signature
|
|
434
|
+
? { providerMetadata: { geminiThoughtSignature: signature } }
|
|
435
|
+
: {}),
|
|
436
|
+
},
|
|
437
|
+
};
|
|
438
|
+
continue;
|
|
439
|
+
}
|
|
440
|
+
if (signature)
|
|
441
|
+
this.signatures.text = signature;
|
|
442
|
+
if (typeof part.text === 'string' && part.text) {
|
|
443
|
+
yield part.thought === true
|
|
444
|
+
? { type: 'reasoning', content: part.text }
|
|
445
|
+
: { type: 'content', content: part.text };
|
|
446
|
+
}
|
|
447
|
+
}
|
|
448
|
+
const reason = finishReason(candidate?.finishReason);
|
|
449
|
+
if (reason)
|
|
450
|
+
this.doneReason = reason;
|
|
451
|
+
const usage = usageFrom(payload.usageMetadata);
|
|
452
|
+
if (usage)
|
|
453
|
+
yield { type: 'usage', usage };
|
|
454
|
+
}
|
|
455
|
+
providerMetadata() {
|
|
456
|
+
return this.signatures.text || this.signatures.calls
|
|
457
|
+
? { [GEMINI_THOUGHT_SIGNATURES_METADATA_KEY]: { ...this.signatures } }
|
|
458
|
+
: undefined;
|
|
459
|
+
}
|
|
460
|
+
done() {
|
|
461
|
+
const providerMetadata = this.providerMetadata();
|
|
462
|
+
return {
|
|
463
|
+
type: 'done',
|
|
464
|
+
...(this.doneReason ? { doneReason: this.doneReason } : {}),
|
|
465
|
+
...(providerMetadata ? { providerMetadata } : {}),
|
|
466
|
+
};
|
|
467
|
+
}
|
|
468
|
+
}
|
|
469
|
+
/**
|
|
470
|
+
* A `streamGenerateContent?alt=sse` response as stream chunks. A server that
|
|
471
|
+
* answers with plain JSON instead (a whole response, or the JSON array the
|
|
472
|
+
* stream returns without `alt=sse`) is read the same way.
|
|
473
|
+
*/
|
|
474
|
+
export async function* streamGeminiResponse(response, model) {
|
|
475
|
+
if (!response.ok) {
|
|
476
|
+
const errorText = await response.text();
|
|
477
|
+
throw new Error(`Plugin API error: ${response.status} - ${errorText.slice(0, 200)}`);
|
|
478
|
+
}
|
|
479
|
+
const reader = new GeminiResponseReader(model);
|
|
480
|
+
const contentType = response.headers.get('content-type') || '';
|
|
481
|
+
if (!contentType.includes('text/event-stream')) {
|
|
482
|
+
const parsed = (await response.json());
|
|
483
|
+
for (const payload of Array.isArray(parsed) ? parsed : [parsed]) {
|
|
484
|
+
const record = asObject(payload);
|
|
485
|
+
if (record)
|
|
486
|
+
yield* reader.read(record);
|
|
487
|
+
}
|
|
488
|
+
yield reader.done();
|
|
489
|
+
return;
|
|
490
|
+
}
|
|
491
|
+
if (!response.body) {
|
|
492
|
+
throw new Error('No response body for streaming');
|
|
493
|
+
}
|
|
494
|
+
const body = response.body.getReader();
|
|
495
|
+
const decoder = new TextDecoder();
|
|
496
|
+
let buffer = '';
|
|
497
|
+
try {
|
|
498
|
+
while (true) {
|
|
499
|
+
const { done, value } = await body.read();
|
|
500
|
+
if (done)
|
|
501
|
+
break;
|
|
502
|
+
buffer += decoder.decode(value, { stream: true });
|
|
503
|
+
const lines = buffer.split('\n');
|
|
504
|
+
buffer = lines.pop() || '';
|
|
505
|
+
for (const line of lines) {
|
|
506
|
+
const trimmed = line.trim();
|
|
507
|
+
if (!trimmed.startsWith('data:'))
|
|
508
|
+
continue;
|
|
509
|
+
let payload;
|
|
510
|
+
try {
|
|
511
|
+
payload = asObject(JSON.parse(trimmed.slice(5).trim()));
|
|
512
|
+
}
|
|
513
|
+
catch {
|
|
514
|
+
// A malformed event does not end the stream.
|
|
515
|
+
continue;
|
|
516
|
+
}
|
|
517
|
+
if (payload)
|
|
518
|
+
yield* reader.read(payload);
|
|
519
|
+
}
|
|
520
|
+
}
|
|
521
|
+
yield reader.done();
|
|
522
|
+
}
|
|
523
|
+
finally {
|
|
524
|
+
await body.cancel().catch(() => undefined);
|
|
525
|
+
body.releaseLock();
|
|
526
|
+
}
|
|
527
|
+
}
|
|
528
|
+
/** A whole `generateContent` response in the OpenAI-shaped plugin response. */
|
|
529
|
+
export function convertGeminiResponse(geminiResponse, model) {
|
|
530
|
+
const reader = new GeminiResponseReader(model);
|
|
531
|
+
let content = '';
|
|
532
|
+
let reasoning = '';
|
|
533
|
+
let usage;
|
|
534
|
+
const toolCalls = [];
|
|
535
|
+
for (const chunk of reader.read(geminiResponse)) {
|
|
536
|
+
if (chunk.type === 'content')
|
|
537
|
+
content += chunk.content;
|
|
538
|
+
else if (chunk.type === 'reasoning')
|
|
539
|
+
reasoning += chunk.content;
|
|
540
|
+
else if (chunk.type === 'tool_call') {
|
|
541
|
+
toolCalls.push({
|
|
542
|
+
id: chunk.toolCall.id,
|
|
543
|
+
type: 'function',
|
|
544
|
+
function: {
|
|
545
|
+
name: chunk.toolCall.name,
|
|
546
|
+
arguments: chunk.toolCall.arguments,
|
|
547
|
+
},
|
|
548
|
+
});
|
|
549
|
+
}
|
|
550
|
+
else if (chunk.type === 'usage' && chunk.usage) {
|
|
551
|
+
const prompt = chunk.usage.promptTokens ?? 0;
|
|
552
|
+
const completion = chunk.usage.completionTokens ?? 0;
|
|
553
|
+
usage = {
|
|
554
|
+
prompt_tokens: prompt,
|
|
555
|
+
completion_tokens: completion,
|
|
556
|
+
total_tokens: chunk.usage.totalTokens ?? prompt + completion,
|
|
557
|
+
};
|
|
558
|
+
}
|
|
559
|
+
}
|
|
560
|
+
const providerMetadata = reader.providerMetadata();
|
|
561
|
+
return {
|
|
562
|
+
id: `chatcmpl-${Date.now()}`,
|
|
563
|
+
object: 'chat.completion',
|
|
564
|
+
created: Math.floor(Date.now() / 1000),
|
|
565
|
+
model,
|
|
566
|
+
...(providerMetadata ? { providerMetadata } : {}),
|
|
567
|
+
choices: [
|
|
568
|
+
{
|
|
569
|
+
index: 0,
|
|
570
|
+
message: {
|
|
571
|
+
role: 'assistant',
|
|
572
|
+
content,
|
|
573
|
+
...(reasoning ? { reasoning_content: reasoning } : {}),
|
|
574
|
+
...(toolCalls.length > 0 ? { tool_calls: toolCalls } : {}),
|
|
575
|
+
},
|
|
576
|
+
finish_reason: reader.doneReason ?? 'stop',
|
|
577
|
+
},
|
|
578
|
+
],
|
|
579
|
+
usage,
|
|
580
|
+
};
|
|
581
|
+
}
|
|
582
|
+
//# sourceMappingURL=geminiProtocol.js.map
|