@demicodes/provider-google 0.8.0
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/LICENSE +201 -0
- package/README.md +17 -0
- package/dist/index.d.mts +57 -0
- package/dist/index.mjs +497 -0
- package/package.json +38 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for reasonable and customary use in describing the
|
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
+
or other liability obligations and/or rights consistent with this
|
|
169
|
+
License. However, in accepting such obligations, You may act only
|
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or additional liability.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
|
177
|
+
|
|
178
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
179
|
+
|
|
180
|
+
To apply the Apache License to your work, attach the following
|
|
181
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
182
|
+
replaced with your own identifying information. (Don't include
|
|
183
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
184
|
+
comment syntax for the file format. We also recommend that a
|
|
185
|
+
file or class name and description of purpose be included on the
|
|
186
|
+
same "printed page" as the copyright notice for easier
|
|
187
|
+
identification within third-party archives.
|
|
188
|
+
|
|
189
|
+
Copyright [yyyy] [name of copyright owner]
|
|
190
|
+
|
|
191
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
192
|
+
you may not use this file except in compliance with the License.
|
|
193
|
+
You may obtain a copy of the License at
|
|
194
|
+
|
|
195
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
196
|
+
|
|
197
|
+
Unless required by applicable law or agreed to in writing, software
|
|
198
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
199
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
200
|
+
See the License for the specific language governing permissions and
|
|
201
|
+
limitations under the License.
|
package/README.md
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
# @demicodes/provider-google
|
|
2
|
+
|
|
3
|
+
A Demi provider for the Google Gemini API (`generateContent`). Exposes
|
|
4
|
+
`createGoogleProvider()`.
|
|
5
|
+
|
|
6
|
+
```ts
|
|
7
|
+
import { createGoogleProvider } from '@demicodes/provider-google'
|
|
8
|
+
```
|
|
9
|
+
|
|
10
|
+
Reads `GOOGLE_API_KEY` / `GOOGLE_BASE_URL` by default (`envPrefix` changes the
|
|
11
|
+
pair). Unlike the OpenAI-compatible route, this talks the native API, so video
|
|
12
|
+
is a real inline part — the model reads the frames *and* the audio track — and
|
|
13
|
+
thought summaries, thought signatures and thinking token counts all arrive as
|
|
14
|
+
first-class fields instead of tags glued into the answer text.
|
|
15
|
+
|
|
16
|
+
Implements the [`@demicodes/provider`](../provider/README.md) contract. Part of
|
|
17
|
+
[Demi](../../README.md). Apache-2.0.
|
package/dist/index.d.mts
ADDED
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
import { Provider, ProviderModel, ProviderModelList } from "@demicodes/provider";
|
|
2
|
+
//#region src/models.d.ts
|
|
3
|
+
interface GoogleModelOptions {
|
|
4
|
+
id: string;
|
|
5
|
+
displayName?: string;
|
|
6
|
+
description?: string;
|
|
7
|
+
contextWindow: number;
|
|
8
|
+
outputLimit?: number | null;
|
|
9
|
+
supportsTools?: boolean | null;
|
|
10
|
+
supportsAttachments?: boolean | null;
|
|
11
|
+
/** Gemini takes video natively (inline `inlineData` parts), audio track included. */
|
|
12
|
+
supportsVideo?: boolean | null;
|
|
13
|
+
supportsReasoning?: boolean | null;
|
|
14
|
+
supportedThinkingEfforts?: string[] | null;
|
|
15
|
+
defaultThinkingEffort?: string | null;
|
|
16
|
+
canDisableThinking?: boolean | null;
|
|
17
|
+
serviceTiers?: ProviderModel['serviceTiers'];
|
|
18
|
+
defaultServiceTierId?: string | null;
|
|
19
|
+
}
|
|
20
|
+
declare function googleDefaultModels(providerId?: string): ProviderModelList;
|
|
21
|
+
//#endregion
|
|
22
|
+
//#region src/provider.d.ts
|
|
23
|
+
type GoogleSecretResolver = () => string | Promise<string> | null | undefined;
|
|
24
|
+
type GoogleHeadersResolver = () => Record<string, string> | Promise<Record<string, string>>;
|
|
25
|
+
type GoogleFetch = (input: string | URL | Request, init?: RequestInit) => Promise<Response>;
|
|
26
|
+
interface GoogleRequestOptions {
|
|
27
|
+
/** Overrides the derived maxOutputTokens (default: the model's outputLimit, else 32000). */
|
|
28
|
+
maxOutputTokens?: number;
|
|
29
|
+
/**
|
|
30
|
+
* Thinking budget used when an effort config is mapped onto Gemini's
|
|
31
|
+
* `thinkingBudget` knob. Merged over the built-in ladder
|
|
32
|
+
* (low 4k / medium 16k / high 32k / xhigh 64k / max 96k).
|
|
33
|
+
*/
|
|
34
|
+
effortBudgetTokens?: Record<string, number>;
|
|
35
|
+
/**
|
|
36
|
+
* Ask the API to stream thought summaries. On by default: without it the model
|
|
37
|
+
* still thinks (and still bills `thoughtsTokenCount`) but the product has
|
|
38
|
+
* nothing to show for the pause.
|
|
39
|
+
*/
|
|
40
|
+
includeThoughts?: boolean;
|
|
41
|
+
extraBody?: Record<string, unknown>;
|
|
42
|
+
}
|
|
43
|
+
interface GoogleProviderOptions {
|
|
44
|
+
id?: string;
|
|
45
|
+
displayName?: string;
|
|
46
|
+
envPrefix?: string;
|
|
47
|
+
baseUrl?: string;
|
|
48
|
+
apiKey?: GoogleSecretResolver;
|
|
49
|
+
headers?: GoogleHeadersResolver;
|
|
50
|
+
models?: GoogleModelOptions[];
|
|
51
|
+
defaultModelId?: string;
|
|
52
|
+
request?: GoogleRequestOptions;
|
|
53
|
+
fetch?: GoogleFetch;
|
|
54
|
+
}
|
|
55
|
+
declare function createGoogleProvider(options?: GoogleProviderOptions): Provider;
|
|
56
|
+
//#endregion
|
|
57
|
+
export { type GoogleHeadersResolver, type GoogleModelOptions, type GoogleProviderOptions, type GoogleRequestOptions, type GoogleSecretResolver, createGoogleProvider, googleDefaultModels };
|
package/dist/index.mjs
ADDED
|
@@ -0,0 +1,497 @@
|
|
|
1
|
+
import { Buffer } from "node:buffer";
|
|
2
|
+
import process from "node:process";
|
|
3
|
+
import { isAbortError, isRecord, normalizeBaseUrl, numberOrZero, parseJsonObject, stringOrNull } from "@demicodes/utils";
|
|
4
|
+
import { zeroUsage } from "@demicodes/core";
|
|
5
|
+
import { authStatusFromKey, defineProvider, httpRequestFailedEvent, normalizeErrorCode, providerErrorFromUnknown, withProviderId } from "@demicodes/provider";
|
|
6
|
+
//#region src/models.ts
|
|
7
|
+
const SOURCE_FETCHED_AT = "1970-01-01T00:00:00.000Z";
|
|
8
|
+
const EFFORTS = [
|
|
9
|
+
"low",
|
|
10
|
+
"medium",
|
|
11
|
+
"high",
|
|
12
|
+
"xhigh",
|
|
13
|
+
"max"
|
|
14
|
+
];
|
|
15
|
+
function googleDefaultModels(providerId = "google") {
|
|
16
|
+
return modelListFromGoogleModels([
|
|
17
|
+
{
|
|
18
|
+
id: "gemini-3.6-flash",
|
|
19
|
+
displayName: "Gemini 3.6 Flash",
|
|
20
|
+
contextWindow: 1048576,
|
|
21
|
+
outputLimit: 65536,
|
|
22
|
+
supportsTools: true,
|
|
23
|
+
supportsAttachments: true,
|
|
24
|
+
supportsVideo: true,
|
|
25
|
+
supportsReasoning: true,
|
|
26
|
+
supportedThinkingEfforts: EFFORTS,
|
|
27
|
+
defaultThinkingEffort: "medium"
|
|
28
|
+
},
|
|
29
|
+
{
|
|
30
|
+
id: "gemini-3.5-flash",
|
|
31
|
+
displayName: "Gemini 3.5 Flash",
|
|
32
|
+
contextWindow: 1048576,
|
|
33
|
+
outputLimit: 65536,
|
|
34
|
+
supportsTools: true,
|
|
35
|
+
supportsAttachments: true,
|
|
36
|
+
supportsVideo: true,
|
|
37
|
+
supportsReasoning: true,
|
|
38
|
+
supportedThinkingEfforts: EFFORTS,
|
|
39
|
+
defaultThinkingEffort: "medium"
|
|
40
|
+
},
|
|
41
|
+
{
|
|
42
|
+
id: "gemini-3.1-pro-preview",
|
|
43
|
+
displayName: "Gemini 3.1 Pro Preview",
|
|
44
|
+
contextWindow: 1048576,
|
|
45
|
+
outputLimit: 65536,
|
|
46
|
+
supportsTools: true,
|
|
47
|
+
supportsAttachments: true,
|
|
48
|
+
supportsVideo: true,
|
|
49
|
+
supportsReasoning: true,
|
|
50
|
+
supportedThinkingEfforts: EFFORTS,
|
|
51
|
+
defaultThinkingEffort: "medium"
|
|
52
|
+
},
|
|
53
|
+
{
|
|
54
|
+
id: "gemini-2.5-flash",
|
|
55
|
+
displayName: "Gemini 2.5 Flash",
|
|
56
|
+
contextWindow: 1048576,
|
|
57
|
+
outputLimit: 65536,
|
|
58
|
+
supportsTools: true,
|
|
59
|
+
supportsAttachments: true,
|
|
60
|
+
supportsVideo: true,
|
|
61
|
+
supportsReasoning: true,
|
|
62
|
+
supportedThinkingEfforts: EFFORTS,
|
|
63
|
+
defaultThinkingEffort: "medium"
|
|
64
|
+
}
|
|
65
|
+
], {
|
|
66
|
+
providerId,
|
|
67
|
+
defaultModelId: "gemini-3.6-flash",
|
|
68
|
+
sourceFetchedAt: SOURCE_FETCHED_AT
|
|
69
|
+
});
|
|
70
|
+
}
|
|
71
|
+
function modelListFromGoogleModels(models, options) {
|
|
72
|
+
const sourceFetchedAt = options.sourceFetchedAt ?? (/* @__PURE__ */ new Date()).toISOString();
|
|
73
|
+
const stale = options.stale === true;
|
|
74
|
+
const mapped = models.map((model) => ({
|
|
75
|
+
providerId: options.providerId,
|
|
76
|
+
id: model.id,
|
|
77
|
+
displayName: model.displayName ?? model.id,
|
|
78
|
+
description: model.description,
|
|
79
|
+
contextWindow: positiveInteger(model.contextWindow, `models[${model.id}].contextWindow`),
|
|
80
|
+
outputLimit: model.outputLimit ?? null,
|
|
81
|
+
supportsTools: model.supportsTools ?? null,
|
|
82
|
+
supportsAttachments: model.supportsAttachments ?? null,
|
|
83
|
+
supportsVideo: model.supportsVideo ?? null,
|
|
84
|
+
supportsReasoning: model.supportsReasoning ?? null,
|
|
85
|
+
supportedThinkingEfforts: model.supportedThinkingEfforts ? [...model.supportedThinkingEfforts] : null,
|
|
86
|
+
defaultThinkingEffort: model.defaultThinkingEffort ?? null,
|
|
87
|
+
canDisableThinking: model.canDisableThinking ?? null,
|
|
88
|
+
serviceTiers: model.serviceTiers ? model.serviceTiers.map((tier) => ({ ...tier })) : model.serviceTiers,
|
|
89
|
+
defaultServiceTierId: model.defaultServiceTierId ?? null,
|
|
90
|
+
sourceFetchedAt,
|
|
91
|
+
stale
|
|
92
|
+
}));
|
|
93
|
+
return {
|
|
94
|
+
providerId: options.providerId,
|
|
95
|
+
models: mapped,
|
|
96
|
+
defaultModelId: options.defaultModelId && mapped.some((model) => model.id === options.defaultModelId) ? options.defaultModelId : mapped[0]?.id ?? null,
|
|
97
|
+
warnings: [],
|
|
98
|
+
sourceFetchedAt,
|
|
99
|
+
stale
|
|
100
|
+
};
|
|
101
|
+
}
|
|
102
|
+
function positiveInteger(value, field) {
|
|
103
|
+
if (!Number.isInteger(value) || value <= 0) throw new Error(`${field} must be a positive integer`);
|
|
104
|
+
return value;
|
|
105
|
+
}
|
|
106
|
+
//#endregion
|
|
107
|
+
//#region src/provider.ts
|
|
108
|
+
const DEFAULT_GOOGLE_BASE_URL = "https://generativelanguage.googleapis.com/v1beta";
|
|
109
|
+
const DEFAULT_MAX_OUTPUT_TOKENS = 32e3;
|
|
110
|
+
const DEFAULT_EFFORT_BUDGET_TOKENS = {
|
|
111
|
+
low: 4096,
|
|
112
|
+
medium: 16384,
|
|
113
|
+
high: 32768,
|
|
114
|
+
xhigh: 65536,
|
|
115
|
+
max: 98304
|
|
116
|
+
};
|
|
117
|
+
var GoogleProvider = class {
|
|
118
|
+
options;
|
|
119
|
+
constructor(options) {
|
|
120
|
+
this.options = options;
|
|
121
|
+
}
|
|
122
|
+
async *run(request) {
|
|
123
|
+
if (request.cancel.aborted) {
|
|
124
|
+
yield { type: "abort" };
|
|
125
|
+
return;
|
|
126
|
+
}
|
|
127
|
+
let apiKey;
|
|
128
|
+
let headers;
|
|
129
|
+
try {
|
|
130
|
+
apiKey = await this.options.apiKey();
|
|
131
|
+
headers = await this.buildHeaders(apiKey);
|
|
132
|
+
if (!apiKey && !headers.has("x-goog-api-key")) {
|
|
133
|
+
yield {
|
|
134
|
+
type: "error",
|
|
135
|
+
message: "Google API key is missing",
|
|
136
|
+
code: "auth_missing"
|
|
137
|
+
};
|
|
138
|
+
return;
|
|
139
|
+
}
|
|
140
|
+
} catch (error) {
|
|
141
|
+
yield providerErrorFromUnknown(error, apiKey);
|
|
142
|
+
return;
|
|
143
|
+
}
|
|
144
|
+
try {
|
|
145
|
+
const response = await this.options.fetch(googleStreamUrl(this.options.baseUrl, request.modelId), {
|
|
146
|
+
method: "POST",
|
|
147
|
+
headers,
|
|
148
|
+
body: JSON.stringify(buildGoogleGenerateContentBody(request, this.options.request)),
|
|
149
|
+
signal: request.cancel
|
|
150
|
+
});
|
|
151
|
+
if (!response.ok) {
|
|
152
|
+
yield await httpRequestFailedEvent(response, apiKey, "Google");
|
|
153
|
+
return;
|
|
154
|
+
}
|
|
155
|
+
yield* mapGoogleContentStream(readServerSentEvents(response.body, request.cancel), request.cancel);
|
|
156
|
+
} catch (error) {
|
|
157
|
+
if (request.cancel.aborted || isAbortError(error)) {
|
|
158
|
+
yield { type: "abort" };
|
|
159
|
+
return;
|
|
160
|
+
}
|
|
161
|
+
yield providerErrorFromUnknown(error, apiKey);
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
async buildHeaders(apiKey) {
|
|
165
|
+
const headers = new Headers(await this.options.headers?.());
|
|
166
|
+
headers.set("accept", "text/event-stream");
|
|
167
|
+
headers.set("content-type", "application/json");
|
|
168
|
+
if (apiKey) headers.set("x-goog-api-key", apiKey);
|
|
169
|
+
return headers;
|
|
170
|
+
}
|
|
171
|
+
};
|
|
172
|
+
function createGoogleProvider(options = {}) {
|
|
173
|
+
const id = options.id ?? "google";
|
|
174
|
+
const displayName = options.displayName ?? "Google Gemini";
|
|
175
|
+
const envPrefix = options.envPrefix ?? "GOOGLE";
|
|
176
|
+
const baseUrl = normalizeBaseUrl(options.baseUrl ?? process.env[`${envPrefix}_BASE_URL`] ?? DEFAULT_GOOGLE_BASE_URL);
|
|
177
|
+
const apiKey = options.apiKey ?? (() => process.env[`${envPrefix}_API_KEY`]);
|
|
178
|
+
const fetchImpl = options.fetch ?? fetch;
|
|
179
|
+
const modelList = () => options.models ? modelListFromGoogleModels(options.models, {
|
|
180
|
+
providerId: id,
|
|
181
|
+
defaultModelId: options.defaultModelId ?? null
|
|
182
|
+
}) : withProviderId(googleDefaultModels(id), id);
|
|
183
|
+
const runtimeOptions = {
|
|
184
|
+
baseUrl,
|
|
185
|
+
apiKey,
|
|
186
|
+
headers: options.headers,
|
|
187
|
+
request: options.request,
|
|
188
|
+
fetch: fetchImpl
|
|
189
|
+
};
|
|
190
|
+
return defineProvider({
|
|
191
|
+
id,
|
|
192
|
+
displayName,
|
|
193
|
+
auth: { status: () => authStatusFromKey(apiKey, options.headers, "x-goog-api-key", "Google") },
|
|
194
|
+
state: () => ({
|
|
195
|
+
status: "ready",
|
|
196
|
+
message: "Uses the Gemini generateContent API"
|
|
197
|
+
}),
|
|
198
|
+
listModels: modelList,
|
|
199
|
+
createRuntime: (selection) => {
|
|
200
|
+
const outputLimit = modelList().models.find((model) => model.id === selection.model.model.id)?.outputLimit ?? null;
|
|
201
|
+
const request = {
|
|
202
|
+
...options.request,
|
|
203
|
+
maxOutputTokens: options.request?.maxOutputTokens ?? outputLimit ?? void 0
|
|
204
|
+
};
|
|
205
|
+
return new GoogleProvider({
|
|
206
|
+
...runtimeOptions,
|
|
207
|
+
request
|
|
208
|
+
});
|
|
209
|
+
}
|
|
210
|
+
});
|
|
211
|
+
}
|
|
212
|
+
function buildGoogleGenerateContentBody(request, options) {
|
|
213
|
+
const body = { contents: inferenceItemsToGoogleContents(request.items) };
|
|
214
|
+
if (request.systemPrompt.trim()) body.systemInstruction = { parts: [{ text: request.systemPrompt }] };
|
|
215
|
+
if (request.tools.length > 0) body.tools = [{ functionDeclarations: request.tools.map(toolToGoogleFunctionDeclaration) }];
|
|
216
|
+
const generationConfig = {};
|
|
217
|
+
const maxOutputTokens = options?.maxOutputTokens ?? DEFAULT_MAX_OUTPUT_TOKENS;
|
|
218
|
+
if (maxOutputTokens > 0) generationConfig.maxOutputTokens = maxOutputTokens;
|
|
219
|
+
const thinkingConfig = googleThinkingConfig(request.thinking, options);
|
|
220
|
+
if (thinkingConfig) generationConfig.thinkingConfig = thinkingConfig;
|
|
221
|
+
if (Object.keys(generationConfig).length > 0) body.generationConfig = generationConfig;
|
|
222
|
+
if (options?.extraBody) Object.assign(body, options.extraBody);
|
|
223
|
+
return body;
|
|
224
|
+
}
|
|
225
|
+
/**
|
|
226
|
+
* Maps any thinking config onto Gemini's `thinkingBudget`: budget configs pass
|
|
227
|
+
* through, effort configs resolve through the ladder (caller-overridable),
|
|
228
|
+
* disabled pins the budget to 0. `includeThoughts` defaults on — the model
|
|
229
|
+
* thinks either way and bills for it, so hiding the summaries only costs the
|
|
230
|
+
* product its "thinking…" surface.
|
|
231
|
+
*/
|
|
232
|
+
function googleThinkingConfig(thinking, options) {
|
|
233
|
+
const includeThoughts = options?.includeThoughts ?? true;
|
|
234
|
+
if (!thinking) return includeThoughts ? { includeThoughts: true } : null;
|
|
235
|
+
if (thinking.type === "disabled") return {
|
|
236
|
+
includeThoughts: false,
|
|
237
|
+
thinkingBudget: 0
|
|
238
|
+
};
|
|
239
|
+
const budget = thinking.type === "budget" ? thinking.budgetTokens : options?.effortBudgetTokens?.[thinking.effort] ?? DEFAULT_EFFORT_BUDGET_TOKENS[thinking.effort] ?? DEFAULT_EFFORT_BUDGET_TOKENS.medium;
|
|
240
|
+
return {
|
|
241
|
+
includeThoughts,
|
|
242
|
+
thinkingBudget: Math.max(0, budget)
|
|
243
|
+
};
|
|
244
|
+
}
|
|
245
|
+
/**
|
|
246
|
+
* Rebuilds the conversation as Gemini `contents`.
|
|
247
|
+
*
|
|
248
|
+
* The subtle part is `thoughtSignature`. Gemini hands one back on every
|
|
249
|
+
* `functionCall` part and REQUIRES it verbatim when that call is replayed —
|
|
250
|
+
* without it the API rejects the whole request ("Function call is missing a
|
|
251
|
+
* thought_signature in functionCall parts"), so an agent loop cannot survive
|
|
252
|
+
* its own second turn. demi's item model has no signature slot on `tool_use`,
|
|
253
|
+
* but it has one on `assistant_thinking`, and the transcript keeps items in
|
|
254
|
+
* order: the provider emits `thinking_start` + `thinking_signature` right
|
|
255
|
+
* before each `tool_call_requested`, so on replay the thinking item sitting
|
|
256
|
+
* immediately in front of a `tool_use` carries that call's signature. That
|
|
257
|
+
* keeps the signature in the persisted transcript (a runtime-local map would
|
|
258
|
+
* evaporate on session resume and 400 forever after) without touching core.
|
|
259
|
+
*/
|
|
260
|
+
function inferenceItemsToGoogleContents(items) {
|
|
261
|
+
const contents = [];
|
|
262
|
+
const toolNames = /* @__PURE__ */ new Map();
|
|
263
|
+
let pendingSignature = null;
|
|
264
|
+
const append = (role, parts) => {
|
|
265
|
+
if (parts.length === 0) return;
|
|
266
|
+
const last = contents[contents.length - 1];
|
|
267
|
+
if (last?.role === role) {
|
|
268
|
+
last.parts.push(...parts);
|
|
269
|
+
return;
|
|
270
|
+
}
|
|
271
|
+
contents.push({
|
|
272
|
+
role,
|
|
273
|
+
parts
|
|
274
|
+
});
|
|
275
|
+
};
|
|
276
|
+
for (const item of items) switch (item.type) {
|
|
277
|
+
case "user_message":
|
|
278
|
+
case "user_steer":
|
|
279
|
+
append("user", userContentToGoogle(item.content));
|
|
280
|
+
pendingSignature = null;
|
|
281
|
+
break;
|
|
282
|
+
case "assistant_text":
|
|
283
|
+
append("model", [{ text: item.text }]);
|
|
284
|
+
pendingSignature = null;
|
|
285
|
+
break;
|
|
286
|
+
case "assistant_thinking":
|
|
287
|
+
pendingSignature = item.signature;
|
|
288
|
+
break;
|
|
289
|
+
case "assistant_redacted_thinking": break;
|
|
290
|
+
case "tool_use": {
|
|
291
|
+
toolNames.set(item.toolUseId, item.toolName);
|
|
292
|
+
const call = { functionCall: {
|
|
293
|
+
name: item.toolName,
|
|
294
|
+
args: item.input ?? {},
|
|
295
|
+
id: item.toolUseId
|
|
296
|
+
} };
|
|
297
|
+
if (pendingSignature) call.thoughtSignature = pendingSignature;
|
|
298
|
+
append("model", [call]);
|
|
299
|
+
pendingSignature = null;
|
|
300
|
+
break;
|
|
301
|
+
}
|
|
302
|
+
case "tool_result":
|
|
303
|
+
append("user", toolResultToGoogle(item.toolUseId, toolNames.get(item.toolUseId) ?? "tool", item.output));
|
|
304
|
+
pendingSignature = null;
|
|
305
|
+
break;
|
|
306
|
+
}
|
|
307
|
+
return contents;
|
|
308
|
+
}
|
|
309
|
+
function userContentToGoogle(content) {
|
|
310
|
+
return content.flatMap((block) => {
|
|
311
|
+
if (block.type === "text") return [{ text: block.text }];
|
|
312
|
+
if (block.type === "reference") return [{ text: block.reference }];
|
|
313
|
+
if (block.type === "document") return [inlinePart(block.source.mediaType, block.source.data)];
|
|
314
|
+
if (block.source.type === "url") return [{ fileData: { fileUri: block.source.url } }];
|
|
315
|
+
return [inlinePart(block.source.mediaType, block.source.data)];
|
|
316
|
+
});
|
|
317
|
+
}
|
|
318
|
+
function inlinePart(mimeType, data) {
|
|
319
|
+
return { inlineData: {
|
|
320
|
+
mimeType,
|
|
321
|
+
data: Buffer.from(data).toString("base64")
|
|
322
|
+
} };
|
|
323
|
+
}
|
|
324
|
+
/**
|
|
325
|
+
* `functionResponse.response` is a JSON object, so images and video a tool
|
|
326
|
+
* returns cannot ride inside it. They follow as sibling inline parts in the
|
|
327
|
+
* same user content — which is how the model ends up actually seeing what a
|
|
328
|
+
* command printed.
|
|
329
|
+
*/
|
|
330
|
+
function toolResultToGoogle(toolUseId, toolName, output) {
|
|
331
|
+
const text = output.filter((block) => block.type === "text").map((block) => block.text).join("\n");
|
|
332
|
+
const media = output.filter((block) => block.type !== "text").map((block) => ({ inlineData: {
|
|
333
|
+
mimeType: block.source.mediaType,
|
|
334
|
+
data: block.source.data
|
|
335
|
+
} }));
|
|
336
|
+
return [{ functionResponse: {
|
|
337
|
+
name: toolName,
|
|
338
|
+
id: toolUseId,
|
|
339
|
+
response: { output: text }
|
|
340
|
+
} }, ...media];
|
|
341
|
+
}
|
|
342
|
+
function toolToGoogleFunctionDeclaration(tool) {
|
|
343
|
+
return {
|
|
344
|
+
name: tool.name,
|
|
345
|
+
description: tool.description,
|
|
346
|
+
parameters: tool.inputSchema
|
|
347
|
+
};
|
|
348
|
+
}
|
|
349
|
+
async function* mapGoogleContentStream(events, signal) {
|
|
350
|
+
let usage = zeroUsage();
|
|
351
|
+
let thinkingOpen = false;
|
|
352
|
+
for await (const event of events) {
|
|
353
|
+
if (signal?.aborted) {
|
|
354
|
+
yield { type: "abort" };
|
|
355
|
+
return;
|
|
356
|
+
}
|
|
357
|
+
for (const data of event.data) {
|
|
358
|
+
const value = parseJsonObject(data);
|
|
359
|
+
if (!value) continue;
|
|
360
|
+
if (isRecord(value.error)) {
|
|
361
|
+
const message = stringOrNull(value.error.message) ?? "Google API stream error";
|
|
362
|
+
yield {
|
|
363
|
+
type: "error",
|
|
364
|
+
message,
|
|
365
|
+
code: normalizeErrorCode(stringOrNull(value.error.status), message)
|
|
366
|
+
};
|
|
367
|
+
return;
|
|
368
|
+
}
|
|
369
|
+
if (isRecord(value.usageMetadata)) usage = googleUsage(value.usageMetadata);
|
|
370
|
+
const candidates = Array.isArray(value.candidates) ? value.candidates : [];
|
|
371
|
+
for (const candidate of candidates) {
|
|
372
|
+
if (!isRecord(candidate)) continue;
|
|
373
|
+
const content = isRecord(candidate.content) ? candidate.content : null;
|
|
374
|
+
const parts = content && Array.isArray(content.parts) ? content.parts : [];
|
|
375
|
+
for (const part of parts) {
|
|
376
|
+
if (!isRecord(part)) continue;
|
|
377
|
+
const functionCall = isRecord(part.functionCall) ? part.functionCall : null;
|
|
378
|
+
if (functionCall) {
|
|
379
|
+
const signature = stringOrNull(part.thoughtSignature);
|
|
380
|
+
if (signature) {
|
|
381
|
+
if (!thinkingOpen) yield { type: "thinking_start" };
|
|
382
|
+
thinkingOpen = true;
|
|
383
|
+
yield {
|
|
384
|
+
type: "thinking_signature",
|
|
385
|
+
signature
|
|
386
|
+
};
|
|
387
|
+
}
|
|
388
|
+
yield {
|
|
389
|
+
type: "tool_call_requested",
|
|
390
|
+
toolUseId: stringOrNull(functionCall.id) ?? `${stringOrNull(functionCall.name) ?? "tool"}_${nextFallbackToolId()}`,
|
|
391
|
+
toolName: stringOrNull(functionCall.name) ?? "",
|
|
392
|
+
input: functionCall.args ?? {}
|
|
393
|
+
};
|
|
394
|
+
thinkingOpen = false;
|
|
395
|
+
continue;
|
|
396
|
+
}
|
|
397
|
+
const text = stringOrNull(part.text);
|
|
398
|
+
if (part.thought === true) {
|
|
399
|
+
if (!thinkingOpen) {
|
|
400
|
+
yield { type: "thinking_start" };
|
|
401
|
+
thinkingOpen = true;
|
|
402
|
+
}
|
|
403
|
+
if (text) yield {
|
|
404
|
+
type: "thinking_delta",
|
|
405
|
+
text
|
|
406
|
+
};
|
|
407
|
+
continue;
|
|
408
|
+
}
|
|
409
|
+
const signature = stringOrNull(part.thoughtSignature);
|
|
410
|
+
if (signature && thinkingOpen) yield {
|
|
411
|
+
type: "thinking_signature",
|
|
412
|
+
signature
|
|
413
|
+
};
|
|
414
|
+
if (text) {
|
|
415
|
+
thinkingOpen = false;
|
|
416
|
+
yield {
|
|
417
|
+
type: "text_delta",
|
|
418
|
+
text
|
|
419
|
+
};
|
|
420
|
+
}
|
|
421
|
+
}
|
|
422
|
+
}
|
|
423
|
+
}
|
|
424
|
+
}
|
|
425
|
+
yield {
|
|
426
|
+
type: "response",
|
|
427
|
+
usage
|
|
428
|
+
};
|
|
429
|
+
}
|
|
430
|
+
let sequence = 0;
|
|
431
|
+
/** Fallback tool-call id when the API omits one; only needs to be unique per process. */
|
|
432
|
+
function nextFallbackToolId() {
|
|
433
|
+
sequence += 1;
|
|
434
|
+
return String(sequence);
|
|
435
|
+
}
|
|
436
|
+
/**
|
|
437
|
+
* Thinking is billed separately from the visible answer (`thoughtsTokenCount`
|
|
438
|
+
* alongside `candidatesTokenCount`); both are output tokens, so the agent's
|
|
439
|
+
* context estimate has to count them together.
|
|
440
|
+
*/
|
|
441
|
+
function googleUsage(usageMetadata) {
|
|
442
|
+
return {
|
|
443
|
+
inputTokens: numberOrZero(usageMetadata.promptTokenCount),
|
|
444
|
+
outputTokens: numberOrZero(usageMetadata.candidatesTokenCount) + numberOrZero(usageMetadata.thoughtsTokenCount),
|
|
445
|
+
cacheReadTokens: numberOrZero(usageMetadata.cachedContentTokenCount),
|
|
446
|
+
cacheWriteTokens: 0
|
|
447
|
+
};
|
|
448
|
+
}
|
|
449
|
+
async function* readServerSentEvents(body, signal) {
|
|
450
|
+
if (!body) return;
|
|
451
|
+
const reader = body.getReader();
|
|
452
|
+
const decoder = new TextDecoder();
|
|
453
|
+
let buffer = "";
|
|
454
|
+
let eventName = null;
|
|
455
|
+
let data = [];
|
|
456
|
+
const flush = function* () {
|
|
457
|
+
if (data.length === 0) return;
|
|
458
|
+
yield {
|
|
459
|
+
event: eventName,
|
|
460
|
+
data
|
|
461
|
+
};
|
|
462
|
+
eventName = null;
|
|
463
|
+
data = [];
|
|
464
|
+
};
|
|
465
|
+
try {
|
|
466
|
+
while (true) {
|
|
467
|
+
if (signal?.aborted) return;
|
|
468
|
+
const { value, done } = await reader.read();
|
|
469
|
+
if (done) break;
|
|
470
|
+
buffer += decoder.decode(value, { stream: true });
|
|
471
|
+
let newline = buffer.indexOf("\n");
|
|
472
|
+
while (newline !== -1) {
|
|
473
|
+
const raw = buffer.slice(0, newline);
|
|
474
|
+
buffer = buffer.slice(newline + 1);
|
|
475
|
+
const line = raw.endsWith("\r") ? raw.slice(0, -1) : raw;
|
|
476
|
+
if (line === "") yield* flush();
|
|
477
|
+
else if (line.startsWith("event:")) eventName = line.slice(6).trim();
|
|
478
|
+
else if (line.startsWith("data:")) data.push(line.slice(5).trimStart());
|
|
479
|
+
newline = buffer.indexOf("\n");
|
|
480
|
+
}
|
|
481
|
+
}
|
|
482
|
+
buffer += decoder.decode();
|
|
483
|
+
if (buffer) {
|
|
484
|
+
const line = buffer.endsWith("\r") ? buffer.slice(0, -1) : buffer;
|
|
485
|
+
if (line.startsWith("data:")) data.push(line.slice(5).trimStart());
|
|
486
|
+
else if (line.startsWith("event:")) eventName = line.slice(6).trim();
|
|
487
|
+
}
|
|
488
|
+
yield* flush();
|
|
489
|
+
} finally {
|
|
490
|
+
reader.releaseLock();
|
|
491
|
+
}
|
|
492
|
+
}
|
|
493
|
+
function googleStreamUrl(baseUrl, modelId) {
|
|
494
|
+
return `${normalizeBaseUrl(baseUrl)}/models/${encodeURIComponent(modelId)}:streamGenerateContent?alt=sse`;
|
|
495
|
+
}
|
|
496
|
+
//#endregion
|
|
497
|
+
export { createGoogleProvider, googleDefaultModels };
|
package/package.json
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@demicodes/provider-google",
|
|
3
|
+
"description": "Google Gemini API provider adapter for Demi.",
|
|
4
|
+
"version": "0.8.0",
|
|
5
|
+
"private": false,
|
|
6
|
+
"type": "module",
|
|
7
|
+
"exports": {
|
|
8
|
+
".": {
|
|
9
|
+
"types": "./dist/index.d.mts",
|
|
10
|
+
"import": "./dist/index.mjs"
|
|
11
|
+
}
|
|
12
|
+
},
|
|
13
|
+
"dependencies": {
|
|
14
|
+
"@demicodes/core": "^0.8.0",
|
|
15
|
+
"@demicodes/provider": "^0.8.0",
|
|
16
|
+
"@demicodes/utils": "^0.8.0"
|
|
17
|
+
},
|
|
18
|
+
"license": "Apache-2.0",
|
|
19
|
+
"main": "./dist/index.mjs",
|
|
20
|
+
"module": "./dist/index.mjs",
|
|
21
|
+
"types": "./dist/index.d.mts",
|
|
22
|
+
"files": [
|
|
23
|
+
"dist"
|
|
24
|
+
],
|
|
25
|
+
"scripts": {
|
|
26
|
+
"build": "tsdown"
|
|
27
|
+
},
|
|
28
|
+
"publishConfig": {
|
|
29
|
+
"access": "public"
|
|
30
|
+
},
|
|
31
|
+
"repository": {
|
|
32
|
+
"type": "git",
|
|
33
|
+
"url": "git+https://github.com/wspl/demi.git",
|
|
34
|
+
"directory": "packages/provider-google"
|
|
35
|
+
},
|
|
36
|
+
"homepage": "https://github.com/wspl/demi/tree/main/packages/provider-google#readme",
|
|
37
|
+
"bugs": "https://github.com/wspl/demi/issues"
|
|
38
|
+
}
|