@warlock.js/ai-google 5.29.0 → 5.31.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/CHANGELOG.md +26 -1
- package/cjs/index.cjs +206 -31
- package/cjs/index.cjs.map +1 -1
- package/esm/config.type.d.mts +1 -1
- package/esm/config.type.d.mts.map +1 -1
- package/esm/embedder.mjs +1 -1
- package/esm/embedder.mjs.map +1 -1
- package/esm/gemini-image.d.mts +1 -1
- package/esm/gemini-image.d.mts.map +1 -1
- package/esm/gemini-image.mjs +1 -1
- package/esm/gemini-image.mjs.map +1 -1
- package/esm/image.d.mts +1 -1
- package/esm/image.d.mts.map +1 -1
- package/esm/image.mjs +1 -1
- package/esm/image.mjs.map +1 -1
- package/esm/index.d.mts +3 -1
- package/esm/index.mjs +2 -1
- package/esm/known-pricing.d.mts +33 -0
- package/esm/known-pricing.d.mts.map +1 -0
- package/esm/known-pricing.mjs +38 -0
- package/esm/known-pricing.mjs.map +1 -0
- package/esm/known-vision-models.mjs +1 -1
- package/esm/known-vision-models.mjs.map +1 -1
- package/esm/model.mjs +66 -10
- package/esm/model.mjs.map +1 -1
- package/esm/provider-options.d.mts +8 -0
- package/esm/provider-options.d.mts.map +1 -0
- package/esm/provider-options.mjs +36 -0
- package/esm/provider-options.mjs.map +1 -0
- package/esm/sdk.d.mts +4 -3
- package/esm/sdk.d.mts.map +1 -1
- package/esm/sdk.mjs +6 -4
- package/esm/sdk.mjs.map +1 -1
- package/esm/utils/apply-google-usage.mjs +6 -1
- package/esm/utils/apply-google-usage.mjs.map +1 -1
- package/esm/utils/map-finish-reason.mjs +1 -1
- package/esm/utils/map-finish-reason.mjs.map +1 -1
- package/esm/utils/to-google-contents.mjs +34 -2
- package/esm/utils/to-google-contents.mjs.map +1 -1
- package/esm/utils/to-google-tools.mjs +1 -1
- package/esm/utils/to-google-tools.mjs.map +1 -1
- package/esm/utils/wrap-google-error.mjs +22 -9
- package/esm/utils/wrap-google-error.mjs.map +1 -1
- package/llms-full.txt +113 -31
- package/llms.txt +1 -1
- package/package.json +5 -4
- package/skills/setup-google/SKILL.md +113 -31
package/esm/image.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"image.mjs","names":[],"sources":["
|
|
1
|
+
{"version":3,"file":"image.mjs","names":[],"sources":["../../../../../../../packages/ai-google/src/image.ts"],"sourcesContent":["import {\n ContentFilterError,\n ProviderError,\n type GeneratedImage,\n type ImageGenerationOptions,\n type ImageGenerationResponse,\n type ImageModelContract,\n type ImageModelPricing,\n} from \"@warlock.js/ai\";\nimport { log, type Logger } from \"@warlock.js/logger\";\nimport type { GenerateImagesConfig, GoogleGenAI } from \"@google/genai\";\nimport type { GoogleImageConfig } from \"./config.type\";\nimport { wrapGoogleError } from \"./utils\";\n\nconst LOG_MODULE = \"ai.google\";\n\n/** Map a neutral output container hint to an IANA media type. */\nfunction mediaTypeFor(format: string | undefined): string | undefined {\n switch (format) {\n case \"png\":\n return \"image/png\";\n case \"jpeg\":\n case \"jpg\":\n return \"image/jpeg\";\n case \"webp\":\n return \"image/webp\";\n default:\n return undefined;\n }\n}\n\n/**\n * Google Imagen-backed implementation of `ImageModelContract`, via\n * `ai.models.generateImages`. Imagen is per-image-metered and returns\n * base64 image bytes (no hosted URL, no token usage).\n *\n * **No model-id validation.** `config.name` is passed through to\n * `ai.models.generateImages` exactly as given — the constructor never\n * inspects it. Google adds and retires image model ids on its own\n * schedule, so an id this adapter does not recognize is not the\n * adapter's call to refuse; an unsupported id surfaces as a provider\n * error from Google (wrapped into the typed `AIError` hierarchy by\n * `generate()`), not as a local one.\n *\n * **Safety filtering.** When Imagen filters every candidate for safety\n * (`raiFilteredReason`), this surfaces a typed `ContentFilterError`\n * carrying the reason, rather than returning an empty success.\n *\n * @example\n * const model = new GoogleImageModel(ai, { name: \"imagen-4.0-generate-001\" }, \"google\");\n * const { images } = await model.generate(\"a watercolor lighthouse at dawn\");\n */\nexport class GoogleImageModel implements ImageModelContract {\n public readonly name: string;\n public readonly provider: string;\n public readonly pricing?: ImageModelPricing;\n\n private readonly ai: GoogleGenAI;\n private readonly logger: Logger = log;\n\n public constructor(ai: GoogleGenAI, config: GoogleImageConfig, provider: string = \"google\") {\n this.ai = ai;\n this.name = config.name;\n this.provider = provider;\n this.pricing = config.pricing;\n }\n\n public async generate(\n prompt: string,\n options?: ImageGenerationOptions,\n ): Promise<ImageGenerationResponse> {\n const config: GenerateImagesConfig = {};\n\n if (options?.count !== undefined) config.numberOfImages = options.count;\n if (options?.aspectRatio !== undefined) config.aspectRatio = options.aspectRatio;\n if (options?.negativePrompt !== undefined) config.negativePrompt = options.negativePrompt;\n if (options?.signal !== undefined) config.abortSignal = options.signal;\n\n const outputMimeType = mediaTypeFor(options?.format);\n if (outputMimeType !== undefined) config.outputMimeType = outputMimeType;\n\n // Imagen sizing is `imageSize` (\"1K\"/\"2K\") — a distinct concept from\n // OpenAI's WxH `size`, so we honor only an explicit passthrough.\n if (typeof options?.imageSize === \"string\") config.imageSize = options.imageSize;\n if (typeof options?.personGeneration === \"string\") {\n config.personGeneration =\n options.personGeneration as GenerateImagesConfig[\"personGeneration\"];\n }\n\n this.logger.debug(LOG_MODULE, \"image.request\", \"models.generateImages\", {\n model: this.name,\n count: options?.count ?? 1,\n });\n\n let response: Awaited<ReturnType<GoogleGenAI[\"models\"][\"generateImages\"]>>;\n\n try {\n response = await this.ai.models.generateImages({ model: this.name, prompt, config });\n } catch (thrown) {\n const wrapped = wrapGoogleError(thrown);\n\n this.logger.error(LOG_MODULE, \"image.error\", wrapped.message, {\n code: wrapped.code,\n context: wrapped.context,\n });\n\n throw wrapped;\n }\n\n const generated = response.generatedImages ?? [];\n const images: GeneratedImage[] = [];\n\n for (const candidate of generated) {\n const bytes = candidate.image?.imageBytes;\n if (!bytes) continue;\n\n images.push({\n type: \"base64\",\n base64: bytes,\n mediaType: candidate.image?.mimeType ?? outputMimeType ?? \"image/png\",\n ...(candidate.enhancedPrompt ? { revisedPrompt: candidate.enhancedPrompt } : {}),\n });\n }\n\n if (images.length === 0) {\n const filtered = generated.find((candidate) => candidate.raiFilteredReason);\n\n if (filtered?.raiFilteredReason) {\n throw new ContentFilterError(\n `Imagen filtered all candidates: ${filtered.raiFilteredReason}`,\n { reason: filtered.raiFilteredReason },\n );\n }\n\n throw new ProviderError(\"Imagen returned no images.\");\n }\n\n this.logger.debug(LOG_MODULE, \"image.response\", \"models.generateImages succeeded\", {\n images: images.length,\n });\n\n // Imagen returns no token usage — honest zero (priced per image).\n return { images, usage: { input: 0, output: 0, total: 0 } };\n }\n}\n"],"mappings":";;;;;;AAcA,MAAM,aAAa;;AAGnB,SAAS,aAAa,QAAgD;CACpE,QAAQ,QAAR;EACE,KAAK,OACH,OAAO;EACT,KAAK;EACL,KAAK,OACH,OAAO;EACT,KAAK,QACH,OAAO;EACT,SACE;CACJ;AACF;;;;;;;;;;;;;;;;;;;;;;AAuBA,IAAa,mBAAb,MAA4D;CAQ1D,AAAO,YAAY,IAAiB,QAA2B,WAAmB,UAAU;gBAF1D;EAGhC,KAAK,KAAK;EACV,KAAK,OAAO,OAAO;EACnB,KAAK,WAAW;EAChB,KAAK,UAAU,OAAO;CACxB;CAEA,MAAa,SACX,QACA,SACkC;EAClC,MAAM,SAA+B,CAAC;EAEtC,IAAI,SAAS,UAAU,QAAW,OAAO,iBAAiB,QAAQ;EAClE,IAAI,SAAS,gBAAgB,QAAW,OAAO,cAAc,QAAQ;EACrE,IAAI,SAAS,mBAAmB,QAAW,OAAO,iBAAiB,QAAQ;EAC3E,IAAI,SAAS,WAAW,QAAW,OAAO,cAAc,QAAQ;EAEhE,MAAM,iBAAiB,aAAa,SAAS,MAAM;EACnD,IAAI,mBAAmB,QAAW,OAAO,iBAAiB;EAI1D,IAAI,OAAO,SAAS,cAAc,UAAU,OAAO,YAAY,QAAQ;EACvE,IAAI,OAAO,SAAS,qBAAqB,UACvC,OAAO,mBACL,QAAQ;EAGZ,KAAK,OAA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s";
|
|
3
|
+
import { GOOGLE_MODEL_PRICING, googlePricingFor } from "./known-pricing.mjs";
|
|
3
4
|
import { GeminiImageModel } from "./gemini-image.mjs";
|
|
4
5
|
import { GoogleImageModel } from "./image.mjs";
|
|
5
|
-
|
|
6
|
+
import { GoogleCallOptions } from "./provider-options.mjs";
|
|
7
|
+
export { GOOGLE_MODEL_PRICING, GeminiImageModel, type GoogleCallOptions, type GoogleEmbedderConfig, type GoogleImageConfig, GoogleImageModel, type GoogleModelConfig, GoogleSDK, type GoogleSDKConfig, googlePricingFor };
|
package/esm/index.mjs
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { GeminiImageModel } from "./gemini-image.mjs";
|
|
2
2
|
import { GoogleImageModel } from "./image.mjs";
|
|
3
|
+
import { GOOGLE_MODEL_PRICING, googlePricingFor } from "./known-pricing.mjs";
|
|
3
4
|
import { GoogleSDK } from "./sdk.mjs";
|
|
4
5
|
|
|
5
|
-
export { GeminiImageModel, GoogleImageModel, GoogleSDK };
|
|
6
|
+
export { GOOGLE_MODEL_PRICING, GeminiImageModel, GoogleImageModel, GoogleSDK, googlePricingFor };
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import { ModelPricing } from "@warlock.js/ai";
|
|
2
|
+
|
|
3
|
+
//#region ../../packages/ai-google/src/known-pricing.d.ts
|
|
4
|
+
/**
|
|
5
|
+
* Built-in Gemini API list prices (paid tier, Standard), USD per
|
|
6
|
+
* 1,000,000 tokens, keyed by exact model id. `cachedInput` is the
|
|
7
|
+
* context-cache read rate; the hourly cache-storage charge is not a token
|
|
8
|
+
* rate and is never included.
|
|
9
|
+
*
|
|
10
|
+
* Source: https://ai.google.dev/gemini-api/docs/pricing, fetched
|
|
11
|
+
* 2026-10-17. Only models with one flat token price are listed. Left out
|
|
12
|
+
* on purpose — pass `pricing` yourself for them:
|
|
13
|
+
*
|
|
14
|
+
* - Models priced by prompt length (the Pro models, split at 200k
|
|
15
|
+
* prompt tokens).
|
|
16
|
+
* - Models with a higher audio-input rate (most Flash / Flash-Lite
|
|
17
|
+
* models): `Usage` does not split input by modality.
|
|
18
|
+
* - Models with a scheduled price change (gemini-4-argon, the 3.8 / 3.6
|
|
19
|
+
* Flash models).
|
|
20
|
+
*/
|
|
21
|
+
declare const GOOGLE_MODEL_PRICING: Readonly<Record<string, ModelPricing>>;
|
|
22
|
+
/**
|
|
23
|
+
* Look up the built-in list price for a Gemini model id (exact match),
|
|
24
|
+
* or `undefined` so cost stays unknown rather than wrong.
|
|
25
|
+
*
|
|
26
|
+
* @example
|
|
27
|
+
* googlePricingFor("gemini-3.5-flash-lite"); // { input: 0.3, output: 2.5, cachedInput: 0.03 }
|
|
28
|
+
* googlePricingFor("gemini-2.5-pro"); // undefined — priced by prompt length
|
|
29
|
+
*/
|
|
30
|
+
declare function googlePricingFor(modelName: string): ModelPricing | undefined;
|
|
31
|
+
//#endregion
|
|
32
|
+
export { GOOGLE_MODEL_PRICING, googlePricingFor };
|
|
33
|
+
//# sourceMappingURL=known-pricing.d.mts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"known-pricing.d.mts","names":[],"sources":["../../../../../../../packages/ai-google/src/known-pricing.ts"],"mappings":";;;;;AAmBA;;;;;;;;;;;;AAAuE;AAYvE;;cAZa,oBAAA,EAAsB,QAAA,CAAS,MAAA,SAAe,YAAA;;AAYM;;;;;;;iBAAjD,gBAAA,CAAiB,SAAA,WAAoB,YAAY"}
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
//#region ../../packages/ai-google/src/known-pricing.ts
|
|
2
|
+
/**
|
|
3
|
+
* Built-in Gemini API list prices (paid tier, Standard), USD per
|
|
4
|
+
* 1,000,000 tokens, keyed by exact model id. `cachedInput` is the
|
|
5
|
+
* context-cache read rate; the hourly cache-storage charge is not a token
|
|
6
|
+
* rate and is never included.
|
|
7
|
+
*
|
|
8
|
+
* Source: https://ai.google.dev/gemini-api/docs/pricing, fetched
|
|
9
|
+
* 2026-10-17. Only models with one flat token price are listed. Left out
|
|
10
|
+
* on purpose — pass `pricing` yourself for them:
|
|
11
|
+
*
|
|
12
|
+
* - Models priced by prompt length (the Pro models, split at 200k
|
|
13
|
+
* prompt tokens).
|
|
14
|
+
* - Models with a higher audio-input rate (most Flash / Flash-Lite
|
|
15
|
+
* models): `Usage` does not split input by modality.
|
|
16
|
+
* - Models with a scheduled price change (gemini-4-argon, the 3.8 / 3.6
|
|
17
|
+
* Flash models).
|
|
18
|
+
*/
|
|
19
|
+
const GOOGLE_MODEL_PRICING = { "gemini-3.5-flash-lite": {
|
|
20
|
+
input: .3,
|
|
21
|
+
output: 2.5,
|
|
22
|
+
cachedInput: .03
|
|
23
|
+
} };
|
|
24
|
+
/**
|
|
25
|
+
* Look up the built-in list price for a Gemini model id (exact match),
|
|
26
|
+
* or `undefined` so cost stays unknown rather than wrong.
|
|
27
|
+
*
|
|
28
|
+
* @example
|
|
29
|
+
* googlePricingFor("gemini-3.5-flash-lite"); // { input: 0.3, output: 2.5, cachedInput: 0.03 }
|
|
30
|
+
* googlePricingFor("gemini-2.5-pro"); // undefined — priced by prompt length
|
|
31
|
+
*/
|
|
32
|
+
function googlePricingFor(modelName) {
|
|
33
|
+
return GOOGLE_MODEL_PRICING[modelName];
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
//#endregion
|
|
37
|
+
export { GOOGLE_MODEL_PRICING, googlePricingFor };
|
|
38
|
+
//# sourceMappingURL=known-pricing.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"known-pricing.mjs","names":[],"sources":["../../../../../../../packages/ai-google/src/known-pricing.ts"],"sourcesContent":["import type { ModelPricing } from \"@warlock.js/ai\";\n\n/**\n * Built-in Gemini API list prices (paid tier, Standard), USD per\n * 1,000,000 tokens, keyed by exact model id. `cachedInput` is the\n * context-cache read rate; the hourly cache-storage charge is not a token\n * rate and is never included.\n *\n * Source: https://ai.google.dev/gemini-api/docs/pricing, fetched\n * 2026-10-17. Only models with one flat token price are listed. Left out\n * on purpose — pass `pricing` yourself for them:\n *\n * - Models priced by prompt length (the Pro models, split at 200k\n * prompt tokens).\n * - Models with a higher audio-input rate (most Flash / Flash-Lite\n * models): `Usage` does not split input by modality.\n * - Models with a scheduled price change (gemini-4-argon, the 3.8 / 3.6\n * Flash models).\n */\nexport const GOOGLE_MODEL_PRICING: Readonly<Record<string, ModelPricing>> = {\n \"gemini-3.5-flash-lite\": { input: 0.3, output: 2.5, cachedInput: 0.03 },\n};\n\n/**\n * Look up the built-in list price for a Gemini model id (exact match),\n * or `undefined` so cost stays unknown rather than wrong.\n *\n * @example\n * googlePricingFor(\"gemini-3.5-flash-lite\"); // { input: 0.3, output: 2.5, cachedInput: 0.03 }\n * googlePricingFor(\"gemini-2.5-pro\"); // undefined — priced by prompt length\n */\nexport function googlePricingFor(modelName: string): ModelPricing | undefined {\n return GOOGLE_MODEL_PRICING[modelName];\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAmBA,MAAa,uBAA+D,EAC1E,yBAAyB;CAAE,OAAO;CAAK,QAAQ;CAAK,aAAa;AAAK,EACxE;;;;;;;;;AAUA,SAAgB,iBAAiB,WAA6C;CAC5E,OAAO,qBAAqB;AAC9B"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"known-vision-models.mjs","names":[],"sources":["
|
|
1
|
+
{"version":3,"file":"known-vision-models.mjs","names":[],"sources":["../../../../../../../packages/ai-google/src/known-vision-models.ts"],"sourcesContent":["/**\n * Substrings identifying Gemini model ids whose family accepts image\n * input (vision).\n *\n * Every Gemini 1.5, 2.x, and 2.5 model is natively multimodal, as is\n * the legacy `gemini-pro-vision`. Only the original text-only\n * `gemini-pro` / `gemini-1.0-pro` is excluded. A substring match\n * tolerates the date/preview suffixes Google appends\n * (`gemini-2.5-flash-preview-05-20`). Override per-model via\n * `google.model({ name, vision: true | false })`.\n */\nconst VISION_CAPABLE_SUBSTRINGS = [\n \"gemini-1.5\",\n \"gemini-2\",\n \"gemini-exp\",\n \"gemini-pro-vision\",\n \"gemini-flash\",\n];\n\n/**\n * Infer whether a Gemini model id supports vision based on the known\n * multimodal-family substrings. Unknown ids default to `false` so\n * passing an image attachment to an unsupported model surfaces a\n * clear, agent-side capability error instead of an opaque Gemini 400.\n *\n * @example\n * inferVisionCapability(\"gemini-2.5-flash\"); // → true\n * inferVisionCapability(\"gemini-1.5-pro-002\"); // → true\n * inferVisionCapability(\"gemini-1.0-pro\"); // → false\n * inferVisionCapability(\"text-embedding-004\"); // → false\n */\nexport function inferVisionCapability(modelId: string): boolean {\n const normalized = modelId.toLowerCase();\n\n return VISION_CAPABLE_SUBSTRINGS.some((fragment) => normalized.includes(fragment));\n}\n"],"mappings":";;;;;;;;;;;;AAWA,MAAM,4BAA4B;CAChC;CACA;CACA;CACA;CACA;AACF;;;;;;;;;;;;;AAcA,SAAgB,sBAAsB,SAA0B;CAC9D,MAAM,aAAa,QAAQ,YAAY;CAEvC,OAAO,0BAA0B,MAAM,aAAa,WAAW,SAAS,QAAQ,CAAC;AACnF"}
|
package/esm/model.mjs
CHANGED
|
@@ -4,11 +4,15 @@ import { toGoogleContents } from "./utils/to-google-contents.mjs";
|
|
|
4
4
|
import { toGoogleTools } from "./utils/to-google-tools.mjs";
|
|
5
5
|
import { wrapGoogleError } from "./utils/wrap-google-error.mjs";
|
|
6
6
|
import "./utils/index.mjs";
|
|
7
|
+
import { mergeProviderBody } from "./provider-options.mjs";
|
|
7
8
|
import { inferVisionCapability } from "./known-vision-models.mjs";
|
|
9
|
+
import { InvalidRequestError, attachCost, resolveStreamChunks, selectProviderTools } from "@warlock.js/ai";
|
|
8
10
|
import { log } from "@warlock.js/logger";
|
|
9
11
|
|
|
10
|
-
//#region
|
|
12
|
+
//#region ../../packages/ai-google/src/model.ts
|
|
11
13
|
const LOG_MODULE = "ai.google";
|
|
14
|
+
/** `provider` value of `ai.providerTool()` entries this adapter sends verbatim. */
|
|
15
|
+
const GOOGLE_WIRE_FORMAT = "google";
|
|
12
16
|
/**
|
|
13
17
|
* Bucketed `thinkingBudget` (token caps) for the neutral
|
|
14
18
|
* `reasoning.effort` levels when the caller gives no explicit
|
|
@@ -102,7 +106,7 @@ var GoogleModel = class {
|
|
|
102
106
|
}
|
|
103
107
|
const toolCalls = this.extractToolCalls(response);
|
|
104
108
|
const finishReason = toolCalls ? "tool_calls" : mapFinishReason(response.candidates?.[0]?.finishReason);
|
|
105
|
-
const usage = this.extractUsage(response);
|
|
109
|
+
const usage = attachCost(this.extractUsage(response), this.pricing);
|
|
106
110
|
this.logger.debug(LOG_MODULE, "response", "generateContent call succeeded", {
|
|
107
111
|
finishReason,
|
|
108
112
|
usage
|
|
@@ -114,11 +118,39 @@ var GoogleModel = class {
|
|
|
114
118
|
toolCalls
|
|
115
119
|
};
|
|
116
120
|
}
|
|
121
|
+
/** Count native input tokens with the same converted content, system and tools. */
|
|
122
|
+
async countTokens(messages, options) {
|
|
123
|
+
const { systemInstruction, contents } = toGoogleContents(messages);
|
|
124
|
+
const config = this.buildConfig(systemInstruction, options);
|
|
125
|
+
if (!this.ai.vertexai && (config.systemInstruction !== void 0 || config.tools !== void 0)) throw new InvalidRequestError("The Google SDK countTokens endpoint in Developer API mode cannot count system instructions or tools. Use Vertex mode for this preflight, or SDK.count() for an offline estimate.");
|
|
126
|
+
if (config.cachedContent !== void 0) throw new InvalidRequestError("The Google SDK countTokens endpoint cannot count a cachedContent reference.");
|
|
127
|
+
try {
|
|
128
|
+
const response = await this.ai.models.countTokens({
|
|
129
|
+
model: this.name,
|
|
130
|
+
contents,
|
|
131
|
+
config: {
|
|
132
|
+
...config.systemInstruction !== void 0 ? { systemInstruction: config.systemInstruction } : {},
|
|
133
|
+
...config.tools !== void 0 ? { tools: config.tools } : {},
|
|
134
|
+
...config.abortSignal ? { abortSignal: config.abortSignal } : {},
|
|
135
|
+
...config.httpOptions ? { httpOptions: config.httpOptions } : {}
|
|
136
|
+
}
|
|
137
|
+
});
|
|
138
|
+
if (response.totalTokens === void 0) throw new InvalidRequestError("Google countTokens returned no totalTokens.");
|
|
139
|
+
return response.totalTokens;
|
|
140
|
+
} catch (thrown) {
|
|
141
|
+
throw this.logAndWrap(thrown);
|
|
142
|
+
}
|
|
143
|
+
}
|
|
117
144
|
/**
|
|
118
145
|
* Incremental streaming completion via `generateContentStream`.
|
|
119
146
|
* Yields neutral `ModelStreamChunk`s — `delta` for text, `tool-call`
|
|
120
147
|
* per function call (Gemini emits a fully-formed call, not partial
|
|
121
148
|
* JSON), and a terminal `done` with the final finish reason + usage.
|
|
149
|
+
*
|
|
150
|
+
* With `options.streamChunks` it also yields `reasoning` for thought
|
|
151
|
+
* parts (only sent when `thinkingConfig.includeThoughts` is on — set it
|
|
152
|
+
* through `providerOptions.google.body`) and `usage` whenever a chunk
|
|
153
|
+
* carries `usageMetadata`. No `tool-args`: calls arrive whole.
|
|
122
154
|
*/
|
|
123
155
|
async *stream(messages, options) {
|
|
124
156
|
this.logger.debug(LOG_MODULE, "request", "Starting generateContentStream call", {
|
|
@@ -145,8 +177,15 @@ var GoogleModel = class {
|
|
|
145
177
|
output: 0,
|
|
146
178
|
total: 0
|
|
147
179
|
};
|
|
180
|
+
const want = resolveStreamChunks(options);
|
|
148
181
|
try {
|
|
149
182
|
for await (const chunk of iterable) {
|
|
183
|
+
if (want.reasoning) {
|
|
184
|
+
for (const part of chunk.candidates?.[0]?.content?.parts ?? []) if (part.thought === true && typeof part.text === "string" && part.text !== "") yield {
|
|
185
|
+
type: "reasoning",
|
|
186
|
+
delta: part.text
|
|
187
|
+
};
|
|
188
|
+
}
|
|
150
189
|
const text = chunk.text;
|
|
151
190
|
if (text) yield {
|
|
152
191
|
type: "delta",
|
|
@@ -166,12 +205,19 @@ var GoogleModel = class {
|
|
|
166
205
|
}
|
|
167
206
|
const candidateFinish = chunk.candidates?.[0]?.finishReason;
|
|
168
207
|
if (candidateFinish) rawFinishReason = candidateFinish;
|
|
169
|
-
if (chunk.usageMetadata)
|
|
208
|
+
if (chunk.usageMetadata) {
|
|
209
|
+
applyGoogleUsage(usage, chunk.usageMetadata);
|
|
210
|
+
if (want.usage) yield {
|
|
211
|
+
type: "usage",
|
|
212
|
+
usage: { ...usage }
|
|
213
|
+
};
|
|
214
|
+
}
|
|
170
215
|
}
|
|
171
216
|
} catch (thrown) {
|
|
172
217
|
throw this.logAndWrap(thrown);
|
|
173
218
|
}
|
|
174
219
|
const finishReason = sawToolCall ? "tool_calls" : mapFinishReason(rawFinishReason);
|
|
220
|
+
attachCost(usage, this.pricing);
|
|
175
221
|
this.logger.debug(LOG_MODULE, "response", "generateContentStream call succeeded", {
|
|
176
222
|
finishReason,
|
|
177
223
|
usage
|
|
@@ -191,15 +237,15 @@ var GoogleModel = class {
|
|
|
191
237
|
buildConfig(systemInstruction, options) {
|
|
192
238
|
const temperature = options?.temperature ?? this.config.temperature;
|
|
193
239
|
const maxOutputTokens = options?.maxTokens ?? this.config.maxTokens;
|
|
194
|
-
return {
|
|
240
|
+
return mergeProviderBody({
|
|
195
241
|
...systemInstruction ? { systemInstruction } : {},
|
|
196
242
|
...temperature !== void 0 ? { temperature } : {},
|
|
197
243
|
...maxOutputTokens !== void 0 ? { maxOutputTokens } : {},
|
|
198
244
|
...options?.signal ? { abortSignal: options.signal } : {},
|
|
199
|
-
...this.buildTools(options
|
|
245
|
+
...this.buildTools(options),
|
|
200
246
|
...this.buildStructuredOutput(options?.responseSchema),
|
|
201
247
|
...this.buildThinking(options?.reasoning)
|
|
202
|
-
};
|
|
248
|
+
}, options);
|
|
203
249
|
}
|
|
204
250
|
/**
|
|
205
251
|
* Translate the neutral `reasoning` option into Gemini's
|
|
@@ -224,11 +270,21 @@ var GoogleModel = class {
|
|
|
224
270
|
}
|
|
225
271
|
/**
|
|
226
272
|
* Spread-friendly tools fragment. Empty object when no tools were
|
|
227
|
-
* supplied so the caller can unconditionally spread it.
|
|
273
|
+
* supplied so the caller can unconditionally spread it. Function tools
|
|
274
|
+
* come first; `ai.providerTool({ provider: "google" })` definitions
|
|
275
|
+
* (`{ googleSearch: {} }`, `{ codeExecution: {} }`, `{ urlContext: {} }`,
|
|
276
|
+
* …) follow verbatim as their own `Tool` entries. Other providers'
|
|
277
|
+
* definitions are skipped with a warning.
|
|
228
278
|
*/
|
|
229
|
-
buildTools(
|
|
230
|
-
const
|
|
231
|
-
|
|
279
|
+
buildTools(options) {
|
|
280
|
+
const { tools, definitions } = selectProviderTools(options, {
|
|
281
|
+
accepts: [GOOGLE_WIRE_FORMAT, this.provider],
|
|
282
|
+
module: LOG_MODULE,
|
|
283
|
+
model: this.name,
|
|
284
|
+
logger: this.logger
|
|
285
|
+
});
|
|
286
|
+
const mapped = [...toGoogleTools(tools) ?? [], ...definitions];
|
|
287
|
+
return mapped.length > 0 ? { tools: mapped } : {};
|
|
232
288
|
}
|
|
233
289
|
/**
|
|
234
290
|
* Translate the neutral `responseSchema` into Gemini's native JSON
|
package/esm/model.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"model.mjs","names":[],"sources":["../../../../../../ai-google/src/model.ts"],"sourcesContent":["import {\n type Message,\n type ModelCallOptions,\n type ModelCapabilities,\n type ModelContract,\n type ModelPricing,\n type ModelResponse,\n type ModelStreamChunk,\n type ModelToolCallRequest,\n type ReasoningEffort,\n type Usage,\n} from \"@warlock.js/ai\";\nimport { log, type Logger } from \"@warlock.js/logger\";\nimport type {\n GenerateContentConfig,\n GenerateContentResponse,\n GoogleGenAI,\n Part,\n} from \"@google/genai\";\nimport type { GoogleModelConfig } from \"./config.type\";\nimport { inferVisionCapability } from \"./known-vision-models\";\nimport {\n applyGoogleUsage,\n mapFinishReason,\n toGoogleContents,\n toGoogleTools,\n wrapGoogleError,\n} from \"./utils\";\n\nconst LOG_MODULE = \"ai.google\";\n\n/**\n * Bucketed `thinkingBudget` (token caps) for the neutral\n * `reasoning.effort` levels when the caller gives no explicit\n * `reasoning.maxTokens`. Gemini 2.5 accepts a positive budget as a cap\n * on the thinking phase; these mirror the spread the OpenAI\n * `reasoning_effort` low/medium/high tiers imply. The installed\n * `@google/genai` `ThinkingConfig` declaration documents that allowed\n * ranges are model-dependent, so retain the existing conservative 24,576\n * cap for the new tiers rather than sending a budget unsupported by Flash.\n */\nconst EFFORT_THINKING_BUDGET: Record<Exclude<ReasoningEffort, \"none\">, number> = {\n minimal: 1024,\n low: 1024,\n medium: 8192,\n high: 24576,\n xhigh: 24576,\n max: 24576,\n};\n\n/**\n * Google Gemini-backed implementation of `ModelContract`.\n *\n * **Role.** The provider-facing bridge between the vendor-neutral\n * `@warlock.js/ai` agent runtime and the `@google/genai` SDK\n * (`models.generateContent` / `generateContentStream`).\n *\n * **Responsibility.**\n * - Owns: a long-lived `GoogleGenAI` client + frozen `ModelConfig`\n * (name, temperature, maxTokens) used as per-call defaults.\n * - Owns: translating vendor-neutral `Message[]` / `ToolConfig[]` into\n * Gemini shapes (systemInstruction hoisting, `model` role,\n * `functionCall` / `functionResponse` parts, inline image bytes) on\n * the way out, and Gemini's candidate/parts response (text, function\n * calls, finish reason, token usage) back into neutral shapes on the\n * way in.\n * - Does NOT own: dispatching tools, looping, history, retries — those\n * are agent concerns. The model is a per-call protocol adapter.\n *\n * Modeled as a class (see §4.2 of code-style.md — \"long-lived state\n * across calls\"): the `GoogleGenAI` client is reused for the SDK's\n * lifetime.\n *\n * @example\n * import { GoogleGenAI } from \"@google/genai\";\n * const ai = new GoogleGenAI({ apiKey: process.env.GEMINI_API_KEY });\n * const model = new GoogleModel(ai, { name: \"gemini-2.5-flash\" });\n *\n * const myAgent = agent({ model, tools: [searchTool] });\n * const result = await myAgent.execute(\"Summarize today's news.\");\n */\nexport class GoogleModel implements ModelContract {\n public readonly name: string;\n public readonly provider: string;\n public readonly capabilities: ModelCapabilities;\n public readonly pricing?: ModelPricing;\n\n private readonly ai: GoogleGenAI;\n private readonly config: GoogleModelConfig;\n private readonly logger: Logger = log;\n\n public constructor(ai: GoogleGenAI, config: GoogleModelConfig, provider: string = \"google\") {\n this.ai = ai;\n this.config = config;\n this.name = config.name;\n this.provider = provider;\n this.pricing = config.pricing;\n const multimodal = config.vision ?? inferVisionCapability(config.name);\n\n this.capabilities = {\n structuredOutput: config.structuredOutput ?? true,\n vision: multimodal,\n // Every Gemini 2.5 model thinks; older families harmlessly ignore\n // an empty thinking budget. Defaulting `true` lets the agent\n // forward reasoning options; an explicit `false` opts a model out.\n reasoning: config.reasoning ?? true,\n // Gemini reports cache-read hits (`cachedContentTokenCount`) on\n // every call via implicit caching, and accepts explicit context\n // caching. Read-side accounting is always honored.\n promptCaching: true,\n // The multimodal Gemini families that accept images also accept\n // audio and PDF/document parts. Mirror the vision inference unless\n // explicitly overridden.\n audio: config.audio ?? multimodal,\n pdf: config.pdf ?? multimodal,\n };\n }\n\n /**\n * Single-shot completion. Sends the full message list to\n * `generateContent`, waits for the terminal response, and reshapes\n * it into a vendor-neutral `ModelResponse`. Per-call `options`\n * override the instance defaults for this call only.\n */\n public async complete(messages: Message[], options?: ModelCallOptions): Promise<ModelResponse> {\n this.logger.debug(LOG_MODULE, \"request\", \"Starting generateContent call\", {\n model: this.name,\n messageCount: messages.length,\n streaming: false,\n toolCount: options?.tools?.length ?? 0,\n });\n\n const { systemInstruction, contents } = toGoogleContents(messages);\n\n let response: GenerateContentResponse;\n\n try {\n response = await this.ai.models.generateContent({\n model: this.name,\n contents,\n config: this.buildConfig(systemInstruction, options),\n });\n } catch (thrown) {\n throw this.logAndWrap(thrown);\n }\n\n const toolCalls = this.extractToolCalls(response);\n const finishReason = toolCalls\n ? \"tool_calls\"\n : mapFinishReason(response.candidates?.[0]?.finishReason);\n const usage = this.extractUsage(response);\n\n this.logger.debug(LOG_MODULE, \"response\", \"generateContent call succeeded\", {\n finishReason,\n usage,\n });\n\n return {\n content: response.text ?? \"\",\n finishReason,\n usage,\n toolCalls,\n };\n }\n\n /**\n * Incremental streaming completion via `generateContentStream`.\n * Yields neutral `ModelStreamChunk`s — `delta` for text, `tool-call`\n * per function call (Gemini emits a fully-formed call, not partial\n * JSON), and a terminal `done` with the final finish reason + usage.\n */\n public async *stream(\n messages: Message[],\n options?: ModelCallOptions,\n ): AsyncIterable<ModelStreamChunk> {\n this.logger.debug(LOG_MODULE, \"request\", \"Starting generateContentStream call\", {\n model: this.name,\n messageCount: messages.length,\n streaming: true,\n toolCount: options?.tools?.length ?? 0,\n });\n\n const { systemInstruction, contents } = toGoogleContents(messages);\n\n let iterable: AsyncGenerator<GenerateContentResponse>;\n\n try {\n iterable = await this.ai.models.generateContentStream({\n model: this.name,\n contents,\n config: this.buildConfig(systemInstruction, options),\n });\n } catch (thrown) {\n throw this.logAndWrap(thrown);\n }\n\n let rawFinishReason: string | undefined;\n let sawToolCall = false;\n const usage: Usage = { input: 0, output: 0, total: 0 };\n\n try {\n for await (const chunk of iterable) {\n const text = chunk.text;\n\n if (text) {\n yield { type: \"delta\", content: text };\n }\n\n for (const part of chunk.candidates?.[0]?.content?.parts ?? []) {\n const toolCall = this.partToToolCall(part);\n\n if (!toolCall) {\n continue;\n }\n\n sawToolCall = true;\n\n yield {\n type: \"tool-call\",\n id: toolCall.id,\n name: toolCall.name,\n input: toolCall.input,\n ...(toolCall.providerMetadata\n ? { providerMetadata: toolCall.providerMetadata }\n : {}),\n };\n }\n\n const candidateFinish = chunk.candidates?.[0]?.finishReason;\n\n if (candidateFinish) {\n rawFinishReason = candidateFinish;\n }\n\n if (chunk.usageMetadata) {\n applyGoogleUsage(usage, chunk.usageMetadata);\n }\n }\n } catch (thrown) {\n throw this.logAndWrap(thrown);\n }\n\n const finishReason = sawToolCall ? \"tool_calls\" : mapFinishReason(rawFinishReason);\n\n this.logger.debug(LOG_MODULE, \"response\", \"generateContentStream call succeeded\", {\n finishReason,\n usage,\n });\n\n yield { type: \"done\", finishReason, usage };\n }\n\n /**\n * Assemble the `GenerateContentConfig` shared by `complete()` and\n * `stream()`: inference params, hoisted system instruction,\n * cancellation signal, and conditional tools + native structured\n * output.\n */\n private buildConfig(\n systemInstruction: string | undefined,\n options: ModelCallOptions | undefined,\n ): GenerateContentConfig {\n const temperature = options?.temperature ?? this.config.temperature;\n const maxOutputTokens = options?.maxTokens ?? this.config.maxTokens;\n\n return {\n ...(systemInstruction ? { systemInstruction } : {}),\n ...(temperature !== undefined ? { temperature } : {}),\n ...(maxOutputTokens !== undefined ? { maxOutputTokens } : {}),\n ...(options?.signal ? { abortSignal: options.signal } : {}),\n ...this.buildTools(options?.tools),\n ...this.buildStructuredOutput(options?.responseSchema),\n ...this.buildThinking(options?.reasoning),\n };\n }\n\n /**\n * Translate the neutral `reasoning` option into Gemini's\n * `thinkingConfig`. `reasoning.maxTokens` maps directly to\n * `thinkingBudget` (token cap on the thinking phase); when only\n * `reasoning.effort` is given it is bucketed into a budget. Emitted\n * only when the model is `reasoning`-capable — a `false` capability\n * (config override) drops it so a non-thinking model never receives\n * an unsupported `thinkingConfig`.\n *\n * Gemini's `thinkingBudget` semantics: `0` disables thinking, `-1`\n * lets the model decide automatically. A positive value caps the\n * thinking tokens. The neutral `effort: \"none\"` (\"run without\n * reasoning\") maps to `thinkingBudget: 0`.\n */\n private buildThinking(\n reasoning: ModelCallOptions[\"reasoning\"],\n ): Pick<GenerateContentConfig, \"thinkingConfig\"> {\n if (!reasoning || !this.capabilities.reasoning) {\n return {};\n }\n\n // `effort: \"none\"` = explicit \"run without reasoning\". Gemini disables\n // thinking with `thinkingBudget: 0` (its native off switch), so emit\n // that rather than omitting the config — an omitted config lets a\n // thinking model reason at its default budget.\n if (reasoning.effort === \"none\") {\n return { thinkingConfig: { thinkingBudget: 0 } };\n }\n\n const thinkingBudget =\n reasoning.maxTokens ?? (reasoning.effort ? EFFORT_THINKING_BUDGET[reasoning.effort] : undefined);\n\n if (thinkingBudget === undefined) {\n return {};\n }\n\n return { thinkingConfig: { thinkingBudget } };\n }\n\n /**\n * Spread-friendly tools fragment. Empty object when no tools were\n * supplied so the caller can unconditionally spread it.\n */\n private buildTools(tools: ModelCallOptions[\"tools\"]): Pick<GenerateContentConfig, \"tools\"> {\n const mapped = toGoogleTools(tools);\n\n return mapped ? { tools: mapped } : {};\n }\n\n /**\n * Translate the neutral `responseSchema` into Gemini's native JSON\n * structured output (`responseMimeType: \"application/json\"` +\n * `responseJsonSchema`, which takes a raw JSON Schema directly).\n * Emitted only when the model is `structuredOutput`-capable and the\n * schema is an object root — otherwise the agent's soft prompt hint\n * + client-side `validate()` carry shape.\n */\n private buildStructuredOutput(\n responseSchema: Record<string, unknown> | undefined,\n ): Pick<GenerateContentConfig, \"responseMimeType\" | \"responseJsonSchema\"> {\n if (!responseSchema || !this.capabilities.structuredOutput) {\n return {};\n }\n\n if (responseSchema.type !== \"object\" || typeof responseSchema.properties !== \"object\") {\n return {};\n }\n\n return {\n responseMimeType: \"application/json\",\n responseJsonSchema: responseSchema,\n };\n }\n\n /**\n * Reshape Gemini's function-call content parts into the neutral\n * `ModelToolCallRequest[]`. Returns `undefined` when the model\n * requested no functions so callers can branch on presence.\n *\n * Reads `candidates[0].content.parts` directly rather than the\n * `response.functionCalls` getter: the getter discards the\n * part-level `thoughtSignature`, and Gemini \"thinking\" models 400\n * the follow-up turn if that signature is not echoed back. See\n * `partToToolCall`.\n */\n private extractToolCalls(\n response: GenerateContentResponse,\n ): ModelToolCallRequest[] | undefined {\n const parts = response.candidates?.[0]?.content?.parts ?? [];\n const toolCalls = parts\n .map((part) => this.partToToolCall(part))\n .filter((call): call is ModelToolCallRequest => call !== undefined);\n\n return toolCalls.length > 0 ? toolCalls : undefined;\n }\n\n /**\n * Map a single Gemini `Part` to a neutral `ModelToolCallRequest`,\n * or `undefined` when the part is not a function call. The part's\n * `thoughtSignature` (opaque, set by thinking models) is carried on\n * `providerMetadata` so `toGoogleContents` can replay it on the\n * assistant turn — Gemini rejects the next request without it.\n */\n private partToToolCall(part: Part): ModelToolCallRequest | undefined {\n if (!part.functionCall) {\n return undefined;\n }\n\n const call = part.functionCall;\n\n return {\n // The Gemini Developer API does not assign function-call ids\n // (only Vertex parallel-calling does). Fall back to the function\n // name so the neutral `toolCallId` is non-empty and the echoed\n // `functionResponse.name` resolves — Gemini matches a result to\n // its call by name. See decisions §49.\n id: call.id ?? call.name ?? \"\",\n name: call.name ?? \"\",\n input: (call.args ?? {}) as Record<string, unknown>,\n ...(part.thoughtSignature\n ? { providerMetadata: { thoughtSignature: part.thoughtSignature } }\n : {}),\n };\n }\n\n /**\n * Normalize Gemini's `usageMetadata` into the neutral `Usage` shape\n * via the shared {@link applyGoogleUsage} mapper (the same one the\n * streaming loop and the Gemini image model use). Absent usage\n * collapses to zeros.\n */\n private extractUsage(response: GenerateContentResponse): Usage {\n const usage: Usage = { input: 0, output: 0, total: 0 };\n\n if (response.usageMetadata) {\n applyGoogleUsage(usage, response.usageMetadata);\n }\n\n return usage;\n }\n\n /**\n * Wrap a thrown provider error into the typed `AIError` hierarchy\n * and emit the standard error log line before it propagates.\n */\n private logAndWrap(thrown: unknown) {\n const wrapped = wrapGoogleError(thrown);\n\n this.logger.error(LOG_MODULE, \"error\", wrapped.message, {\n code: wrapped.code,\n context: wrapped.context,\n });\n\n return wrapped;\n }\n}\n"],"mappings":";;;;;;;;;;AA6BA,MAAM,aAAa;;;;;;;;;;;AAYnB,MAAM,yBAA2E;CAC/E,SAAS;CACT,KAAK;CACL,QAAQ;CACR,MAAM;CACN,OAAO;CACP,KAAK;AACP;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAiCA,IAAa,cAAb,MAAkD;CAUhD,AAAO,YAAY,IAAiB,QAA2B,WAAmB,UAAU;gBAF1D;EAGhC,KAAK,KAAK;EACV,KAAK,SAAS;EACd,KAAK,OAAO,OAAO;EACnB,KAAK,WAAW;EAChB,KAAK,UAAU,OAAO;EACtB,MAAM,aAAa,OAAO,UAAU,sBAAsB,OAAO,IAAI;EAErE,KAAK,eAAe;GAClB,kBAAkB,OAAO,oBAAoB;GAC7C,QAAQ;GAIR,WAAW,OAAO,aAAa;GAI/B,eAAe;GAIf,OAAO,OAAO,SAAS;GAC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AC7D,MAAM,QAAe;GAAE,OAAO;GAAG,QAAQ;GAAG,OAAO;EAAE;EAErD,IAAI,SAAS,eACX,iBAAiB,OAAO,SAAS,aAAa;EAGhD,OAAO;CACT;;;;;CAMA,AAAQ,WAAW,QAAiB;EAClC,MAAM,UAAU,gBAAgB,MAAM;EAEtC,KAAK,OAAO,MAAM,YAAY,SAAS,QAAQ,SAAS;GACtD,MAAM,QAAQ;GACd,SAAS,QAAQ;EACnB,CAAC;EAED,OAAO;CACT;AACF"}
|
|
1
|
+
{"version":3,"file":"model.mjs","names":[],"sources":["../../../../../../../packages/ai-google/src/model.ts"],"sourcesContent":["import {\n attachCost,\n InvalidRequestError,\n resolveStreamChunks,\n selectProviderTools,\n type Message,\n type ModelCallOptions,\n type ModelCapabilities,\n type ModelContract,\n type ModelPricing,\n type ModelResponse,\n type ModelStreamChunk,\n type ModelToolCallRequest,\n type ReasoningEffort,\n type Usage,\n} from \"@warlock.js/ai\";\nimport { log, type Logger } from \"@warlock.js/logger\";\nimport type {\n GenerateContentConfig,\n GenerateContentResponse,\n GoogleGenAI,\n Part,\n Tool,\n} from \"@google/genai\";\nimport { mergeProviderBody } from \"./provider-options\";\nimport type { GoogleModelConfig } from \"./config.type\";\nimport { inferVisionCapability } from \"./known-vision-models\";\nimport {\n applyGoogleUsage,\n mapFinishReason,\n toGoogleContents,\n toGoogleTools,\n wrapGoogleError,\n} from \"./utils\";\n\nconst LOG_MODULE = \"ai.google\";\n\n/** `provider` value of `ai.providerTool()` entries this adapter sends verbatim. */\nconst GOOGLE_WIRE_FORMAT = \"google\";\n\n/**\n * Bucketed `thinkingBudget` (token caps) for the neutral\n * `reasoning.effort` levels when the caller gives no explicit\n * `reasoning.maxTokens`. Gemini 2.5 accepts a positive budget as a cap\n * on the thinking phase; these mirror the spread the OpenAI\n * `reasoning_effort` low/medium/high tiers imply. The installed\n * `@google/genai` `ThinkingConfig` declaration documents that allowed\n * ranges are model-dependent, so retain the existing conservative 24,576\n * cap for the new tiers rather than sending a budget unsupported by Flash.\n */\nconst EFFORT_THINKING_BUDGET: Record<Exclude<ReasoningEffort, \"none\">, number> = {\n minimal: 1024,\n low: 1024,\n medium: 8192,\n high: 24576,\n xhigh: 24576,\n max: 24576,\n};\n\n/**\n * Google Gemini-backed implementation of `ModelContract`.\n *\n * **Role.** The provider-facing bridge between the vendor-neutral\n * `@warlock.js/ai` agent runtime and the `@google/genai` SDK\n * (`models.generateContent` / `generateContentStream`).\n *\n * **Responsibility.**\n * - Owns: a long-lived `GoogleGenAI` client + frozen `ModelConfig`\n * (name, temperature, maxTokens) used as per-call defaults.\n * - Owns: translating vendor-neutral `Message[]` / `ToolConfig[]` into\n * Gemini shapes (systemInstruction hoisting, `model` role,\n * `functionCall` / `functionResponse` parts, inline image bytes) on\n * the way out, and Gemini's candidate/parts response (text, function\n * calls, finish reason, token usage) back into neutral shapes on the\n * way in.\n * - Does NOT own: dispatching tools, looping, history, retries — those\n * are agent concerns. The model is a per-call protocol adapter.\n *\n * Modeled as a class (see §4.2 of code-style.md — \"long-lived state\n * across calls\"): the `GoogleGenAI` client is reused for the SDK's\n * lifetime.\n *\n * @example\n * import { GoogleGenAI } from \"@google/genai\";\n * const ai = new GoogleGenAI({ apiKey: process.env.GEMINI_API_KEY });\n * const model = new GoogleModel(ai, { name: \"gemini-2.5-flash\" });\n *\n * const myAgent = agent({ model, tools: [searchTool] });\n * const result = await myAgent.execute(\"Summarize today's news.\");\n */\nexport class GoogleModel implements ModelContract {\n public readonly name: string;\n public readonly provider: string;\n public readonly capabilities: ModelCapabilities;\n public readonly pricing?: ModelPricing;\n\n private readonly ai: GoogleGenAI;\n private readonly config: GoogleModelConfig;\n private readonly logger: Logger = log;\n\n public constructor(ai: GoogleGenAI, config: GoogleModelConfig, provider: string = \"google\") {\n this.ai = ai;\n this.config = config;\n this.name = config.name;\n this.provider = provider;\n this.pricing = config.pricing;\n const multimodal = config.vision ?? inferVisionCapability(config.name);\n\n this.capabilities = {\n structuredOutput: config.structuredOutput ?? true,\n vision: multimodal,\n // Every Gemini 2.5 model thinks; older families harmlessly ignore\n // an empty thinking budget. Defaulting `true` lets the agent\n // forward reasoning options; an explicit `false` opts a model out.\n reasoning: config.reasoning ?? true,\n // Gemini reports cache-read hits (`cachedContentTokenCount`) on\n // every call via implicit caching, and accepts explicit context\n // caching. Read-side accounting is always honored.\n promptCaching: true,\n // The multimodal Gemini families that accept images also accept\n // audio and PDF/document parts. Mirror the vision inference unless\n // explicitly overridden.\n audio: config.audio ?? multimodal,\n pdf: config.pdf ?? multimodal,\n };\n }\n\n /**\n * Single-shot completion. Sends the full message list to\n * `generateContent`, waits for the terminal response, and reshapes\n * it into a vendor-neutral `ModelResponse`. Per-call `options`\n * override the instance defaults for this call only.\n */\n public async complete(messages: Message[], options?: ModelCallOptions): Promise<ModelResponse> {\n this.logger.debug(LOG_MODULE, \"request\", \"Starting generateContent call\", {\n model: this.name,\n messageCount: messages.length,\n streaming: false,\n toolCount: options?.tools?.length ?? 0,\n });\n\n const { systemInstruction, contents } = toGoogleContents(messages);\n\n let response: GenerateContentResponse;\n\n try {\n response = await this.ai.models.generateContent({\n model: this.name,\n contents,\n config: this.buildConfig(systemInstruction, options),\n });\n } catch (thrown) {\n throw this.logAndWrap(thrown);\n }\n\n const toolCalls = this.extractToolCalls(response);\n const finishReason = toolCalls\n ? \"tool_calls\"\n : mapFinishReason(response.candidates?.[0]?.finishReason);\n const usage = attachCost(this.extractUsage(response), this.pricing);\n\n this.logger.debug(LOG_MODULE, \"response\", \"generateContent call succeeded\", {\n finishReason,\n usage,\n });\n\n return {\n content: response.text ?? \"\",\n finishReason,\n usage,\n toolCalls,\n };\n }\n\n /** Count native input tokens with the same converted content, system and tools. */\n public async countTokens(messages: Message[], options?: ModelCallOptions): Promise<number> {\n const { systemInstruction, contents } = toGoogleContents(messages);\n const config = this.buildConfig(systemInstruction, options);\n if (\n !this.ai.vertexai &&\n (config.systemInstruction !== undefined || config.tools !== undefined)\n ) {\n throw new InvalidRequestError(\n \"The Google SDK countTokens endpoint in Developer API mode cannot count system instructions or tools. Use Vertex mode for this preflight, or SDK.count() for an offline estimate.\",\n );\n }\n if (config.cachedContent !== undefined) {\n throw new InvalidRequestError(\n \"The Google SDK countTokens endpoint cannot count a cachedContent reference.\",\n );\n }\n try {\n const response = await this.ai.models.countTokens({\n model: this.name,\n contents,\n config: {\n ...(config.systemInstruction !== undefined\n ? { systemInstruction: config.systemInstruction }\n : {}),\n ...(config.tools !== undefined ? { tools: config.tools as Tool[] } : {}),\n ...(config.abortSignal ? { abortSignal: config.abortSignal } : {}),\n ...(config.httpOptions ? { httpOptions: config.httpOptions } : {}),\n },\n });\n if (response.totalTokens === undefined)\n throw new InvalidRequestError(\"Google countTokens returned no totalTokens.\");\n return response.totalTokens;\n } catch (thrown) {\n throw this.logAndWrap(thrown);\n }\n }\n\n /**\n * Incremental streaming completion via `generateContentStream`.\n * Yields neutral `ModelStreamChunk`s — `delta` for text, `tool-call`\n * per function call (Gemini emits a fully-formed call, not partial\n * JSON), and a terminal `done` with the final finish reason + usage.\n *\n * With `options.streamChunks` it also yields `reasoning` for thought\n * parts (only sent when `thinkingConfig.includeThoughts` is on — set it\n * through `providerOptions.google.body`) and `usage` whenever a chunk\n * carries `usageMetadata`. No `tool-args`: calls arrive whole.\n */\n public async *stream(\n messages: Message[],\n options?: ModelCallOptions,\n ): AsyncIterable<ModelStreamChunk> {\n this.logger.debug(LOG_MODULE, \"request\", \"Starting generateContentStream call\", {\n model: this.name,\n messageCount: messages.length,\n streaming: true,\n toolCount: options?.tools?.length ?? 0,\n });\n\n const { systemInstruction, contents } = toGoogleContents(messages);\n\n let iterable: AsyncGenerator<GenerateContentResponse>;\n\n try {\n iterable = await this.ai.models.generateContentStream({\n model: this.name,\n contents,\n config: this.buildConfig(systemInstruction, options),\n });\n } catch (thrown) {\n throw this.logAndWrap(thrown);\n }\n\n let rawFinishReason: string | undefined;\n let sawToolCall = false;\n const usage: Usage = { input: 0, output: 0, total: 0 };\n const want = resolveStreamChunks(options);\n\n try {\n for await (const chunk of iterable) {\n // Thought parts (`thought: true`, sent when `thinkingConfig.includeThoughts`\n // is on) carry the thought summary in `text`; the SDK's `chunk.text`\n // getter already leaves them out of the answer.\n if (want.reasoning) {\n for (const part of chunk.candidates?.[0]?.content?.parts ?? []) {\n if (part.thought === true && typeof part.text === \"string\" && part.text !== \"\") {\n yield { type: \"reasoning\", delta: part.text };\n }\n }\n }\n\n const text = chunk.text;\n\n if (text) {\n yield { type: \"delta\", content: text };\n }\n\n for (const part of chunk.candidates?.[0]?.content?.parts ?? []) {\n const toolCall = this.partToToolCall(part);\n\n if (!toolCall) {\n continue;\n }\n\n sawToolCall = true;\n\n yield {\n type: \"tool-call\",\n id: toolCall.id,\n name: toolCall.name,\n input: toolCall.input,\n ...(toolCall.providerMetadata ? { providerMetadata: toolCall.providerMetadata } : {}),\n };\n }\n\n const candidateFinish = chunk.candidates?.[0]?.finishReason;\n\n if (candidateFinish) {\n rawFinishReason = candidateFinish;\n }\n\n if (chunk.usageMetadata) {\n applyGoogleUsage(usage, chunk.usageMetadata);\n\n if (want.usage) {\n yield { type: \"usage\", usage: { ...usage } };\n }\n }\n }\n } catch (thrown) {\n throw this.logAndWrap(thrown);\n }\n\n const finishReason = sawToolCall ? \"tool_calls\" : mapFinishReason(rawFinishReason);\n\n attachCost(usage, this.pricing);\n\n this.logger.debug(LOG_MODULE, \"response\", \"generateContentStream call succeeded\", {\n finishReason,\n usage,\n });\n\n yield { type: \"done\", finishReason, usage };\n }\n\n /**\n * Assemble the `GenerateContentConfig` shared by `complete()` and\n * `stream()`: inference params, hoisted system instruction,\n * cancellation signal, and conditional tools + native structured\n * output.\n */\n private buildConfig(\n systemInstruction: string | undefined,\n options: ModelCallOptions | undefined,\n ): GenerateContentConfig {\n const temperature = options?.temperature ?? this.config.temperature;\n const maxOutputTokens = options?.maxTokens ?? this.config.maxTokens;\n\n return mergeProviderBody<GenerateContentConfig>(\n {\n ...(systemInstruction ? { systemInstruction } : {}),\n ...(temperature !== undefined ? { temperature } : {}),\n ...(maxOutputTokens !== undefined ? { maxOutputTokens } : {}),\n ...(options?.signal ? { abortSignal: options.signal } : {}),\n ...this.buildTools(options),\n ...this.buildStructuredOutput(options?.responseSchema),\n ...this.buildThinking(options?.reasoning),\n },\n options,\n );\n }\n\n /**\n * Translate the neutral `reasoning` option into Gemini's\n * `thinkingConfig`. `reasoning.maxTokens` maps directly to\n * `thinkingBudget` (token cap on the thinking phase); when only\n * `reasoning.effort` is given it is bucketed into a budget. Emitted\n * only when the model is `reasoning`-capable — a `false` capability\n * (config override) drops it so a non-thinking model never receives\n * an unsupported `thinkingConfig`.\n *\n * Gemini's `thinkingBudget` semantics: `0` disables thinking, `-1`\n * lets the model decide automatically. A positive value caps the\n * thinking tokens. The neutral `effort: \"none\"` (\"run without\n * reasoning\") maps to `thinkingBudget: 0`.\n */\n private buildThinking(\n reasoning: ModelCallOptions[\"reasoning\"],\n ): Pick<GenerateContentConfig, \"thinkingConfig\"> {\n if (!reasoning || !this.capabilities.reasoning) {\n return {};\n }\n\n // `effort: \"none\"` = explicit \"run without reasoning\". Gemini disables\n // thinking with `thinkingBudget: 0` (its native off switch), so emit\n // that rather than omitting the config — an omitted config lets a\n // thinking model reason at its default budget.\n if (reasoning.effort === \"none\") {\n return { thinkingConfig: { thinkingBudget: 0 } };\n }\n\n const thinkingBudget =\n reasoning.maxTokens ??\n (reasoning.effort ? EFFORT_THINKING_BUDGET[reasoning.effort] : undefined);\n\n if (thinkingBudget === undefined) {\n return {};\n }\n\n return { thinkingConfig: { thinkingBudget } };\n }\n\n /**\n * Spread-friendly tools fragment. Empty object when no tools were\n * supplied so the caller can unconditionally spread it. Function tools\n * come first; `ai.providerTool({ provider: \"google\" })` definitions\n * (`{ googleSearch: {} }`, `{ codeExecution: {} }`, `{ urlContext: {} }`,\n * …) follow verbatim as their own `Tool` entries. Other providers'\n * definitions are skipped with a warning.\n */\n private buildTools(options: ModelCallOptions | undefined): Pick<GenerateContentConfig, \"tools\"> {\n const { tools, definitions } = selectProviderTools(options, {\n accepts: [GOOGLE_WIRE_FORMAT, this.provider],\n module: LOG_MODULE,\n model: this.name,\n logger: this.logger,\n });\n const mapped: Tool[] = [...(toGoogleTools(tools) ?? []), ...(definitions as unknown as Tool[])];\n\n return mapped.length > 0 ? { tools: mapped } : {};\n }\n\n /**\n * Translate the neutral `responseSchema` into Gemini's native JSON\n * structured output (`responseMimeType: \"application/json\"` +\n * `responseJsonSchema`, which takes a raw JSON Schema directly).\n * Emitted only when the model is `structuredOutput`-capable and the\n * schema is an object root — otherwise the agent's soft prompt hint\n * + client-side `validate()` carry shape.\n */\n private buildStructuredOutput(\n responseSchema: Record<string, unknown> | undefined,\n ): Pick<GenerateContentConfig, \"responseMimeType\" | \"responseJsonSchema\"> {\n if (!responseSchema || !this.capabilities.structuredOutput) {\n return {};\n }\n\n if (responseSchema.type !== \"object\" || typeof responseSchema.properties !== \"object\") {\n return {};\n }\n\n return {\n responseMimeType: \"application/json\",\n responseJsonSchema: responseSchema,\n };\n }\n\n /**\n * Reshape Gemini's function-call content parts into the neutral\n * `ModelToolCallRequest[]`. Returns `undefined` when the model\n * requested no functions so callers can branch on presence.\n *\n * Reads `candidates[0].content.parts` directly rather than the\n * `response.functionCalls` getter: the getter discards the\n * part-level `thoughtSignature`, and Gemini \"thinking\" models 400\n * the follow-up turn if that signature is not echoed back. See\n * `partToToolCall`.\n */\n private extractToolCalls(response: GenerateContentResponse): ModelToolCallRequest[] | undefined {\n const parts = response.candidates?.[0]?.content?.parts ?? [];\n const toolCalls = parts\n .map((part) => this.partToToolCall(part))\n .filter((call): call is ModelToolCallRequest => call !== undefined);\n\n return toolCalls.length > 0 ? toolCalls : undefined;\n }\n\n /**\n * Map a single Gemini `Part` to a neutral `ModelToolCallRequest`,\n * or `undefined` when the part is not a function call. The part's\n * `thoughtSignature` (opaque, set by thinking models) is carried on\n * `providerMetadata` so `toGoogleContents` can replay it on the\n * assistant turn — Gemini rejects the next request without it.\n */\n private partToToolCall(part: Part): ModelToolCallRequest | undefined {\n if (!part.functionCall) {\n return undefined;\n }\n\n const call = part.functionCall;\n\n return {\n // The Gemini Developer API does not assign function-call ids\n // (only Vertex parallel-calling does). Fall back to the function\n // name so the neutral `toolCallId` is non-empty and the echoed\n // `functionResponse.name` resolves — Gemini matches a result to\n // its call by name. See decisions §49.\n id: call.id ?? call.name ?? \"\",\n name: call.name ?? \"\",\n input: (call.args ?? {}) as Record<string, unknown>,\n ...(part.thoughtSignature\n ? { providerMetadata: { thoughtSignature: part.thoughtSignature } }\n : {}),\n };\n }\n\n /**\n * Normalize Gemini's `usageMetadata` into the neutral `Usage` shape\n * via the shared {@link applyGoogleUsage} mapper (the same one the\n * streaming loop and the Gemini image model use). Absent usage\n * collapses to zeros.\n */\n private extractUsage(response: GenerateContentResponse): Usage {\n const usage: Usage = { input: 0, output: 0, total: 0 };\n\n if (response.usageMetadata) {\n applyGoogleUsage(usage, response.usageMetadata);\n }\n\n return usage;\n }\n\n /**\n * Wrap a thrown provider error into the typed `AIError` hierarchy\n * and emit the standard error log line before it propagates.\n */\n private logAndWrap(thrown: unknown) {\n const wrapped = wrapGoogleError(thrown);\n\n this.logger.error(LOG_MODULE, \"error\", wrapped.message, {\n code: wrapped.code,\n context: wrapped.context,\n });\n\n return wrapped;\n }\n}\n"],"mappings":";;;;;;;;;;;;AAmCA,MAAM,aAAa;;AAGnB,MAAM,qBAAqB;;;;;;;;;;;AAY3B,MAAM,yBAA2E;CAC/E,SAAS;CACT,KAAK;CACL,QAAQ;CACR,MAAM;CACN,OAAO;CACP,KAAK;AACP;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAiCA,IAAa,cAAb,MAAkD;CAUhD,AAAO,YAAY,IAAiB,QAA2B,WAAmB,UAAU;gBAF1D;EAGhC,KAAK,KAAK;EACV,KAAK,SAAS;EACd,KAAK,OAAO,OAAO;EACnB,KAAK,WAAW;EAChB,KAAK,UAAU,OAAO;EACt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AAO,UAAU,SAAS,IAAI,YAAY;CAC5C;;;;;;;;CASA,AAAQ,eAAe,MAA8C;EACnE,IAAI,CAAC,KAAK,cACR;EAGF,MAAM,OAAO,KAAK;EAElB,OAAO;GAML,IAAI,KAAK,MAAM,KAAK,QAAQ;GAC5B,MAAM,KAAK,QAAQ;GACnB,OAAQ,KAAK,QAAQ,CAAC;GACtB,GAAI,KAAK,mBACL,EAAE,kBAAkB,EAAE,kBAAkB,KAAK,iBAAiB,EAAE,IAChE,CAAC;EACP;CACF;;;;;;;CAQA,AAAQ,aAAa,UAA0C;EAC7D,MAAM,QAAe;GAAE,OAAO;GAAG,QAAQ;GAAG,OAAO;EAAE;EAErD,IAAI,SAAS,eACX,iBAAiB,OAAO,SAAS,aAAa;EAGhD,OAAO;CACT;;;;;CAMA,AAAQ,WAAW,QAAiB;EAClC,MAAM,UAAU,gBAAgB,MAAM;EAEtC,KAAK,OAAO,MAAM,YAAY,SAAS,QAAQ,SAAS;GACtD,MAAM,QAAQ;GACd,SAAS,QAAQ;EACnB,CAAC;EAED,OAAO;CACT;AACF"}
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
//#region ../../packages/ai-google/src/provider-options.d.ts
|
|
2
|
+
/** Adapter-only fields merged after the neutral request parameters. */
|
|
3
|
+
type GoogleCallOptions = {
|
|
4
|
+
body?: Record<string, unknown>;
|
|
5
|
+
};
|
|
6
|
+
//#endregion
|
|
7
|
+
export { GoogleCallOptions };
|
|
8
|
+
//# sourceMappingURL=provider-options.d.mts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"provider-options.d.mts","names":[],"sources":["../../../../../../../packages/ai-google/src/provider-options.ts"],"mappings":";;KAGY,iBAAA;EAAsB,IAAA,GAAO,MAAM;AAAA"}
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
import { InvalidRequestError } from "@warlock.js/ai";
|
|
2
|
+
|
|
3
|
+
//#region ../../packages/ai-google/src/provider-options.ts
|
|
4
|
+
const RESERVED_FIELDS = new Set([
|
|
5
|
+
"systemInstruction",
|
|
6
|
+
"tools",
|
|
7
|
+
"abortSignal",
|
|
8
|
+
"httpOptions"
|
|
9
|
+
]);
|
|
10
|
+
function mergeProviderBody(built, options) {
|
|
11
|
+
const body = (options?.providerOptions?.google)?.body ?? {};
|
|
12
|
+
const reserved = Object.keys(body).filter((key) => RESERVED_FIELDS.has(key));
|
|
13
|
+
if (reserved.length > 0) throw new InvalidRequestError(`providerOptions.google.body cannot set ${reserved.join(", ")}: use the call's messages, tools and model options.`, { context: { fields: reserved } });
|
|
14
|
+
const defaults = built;
|
|
15
|
+
const overrides = Object.fromEntries(Object.entries(body).map(([key, value]) => {
|
|
16
|
+
const previous = defaults[key];
|
|
17
|
+
return [key, isPlainObject(previous) && isPlainObject(value) ? {
|
|
18
|
+
...previous,
|
|
19
|
+
...value
|
|
20
|
+
} : value];
|
|
21
|
+
}));
|
|
22
|
+
return {
|
|
23
|
+
...built,
|
|
24
|
+
...overrides
|
|
25
|
+
};
|
|
26
|
+
}
|
|
27
|
+
/** Merge only plain objects; arrays, null and provider scalar values replace the field. */
|
|
28
|
+
function isPlainObject(value) {
|
|
29
|
+
if (value === null || typeof value !== "object") return false;
|
|
30
|
+
const prototype = Object.getPrototypeOf(value);
|
|
31
|
+
return prototype === Object.prototype || prototype === null;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
//#endregion
|
|
35
|
+
export { mergeProviderBody };
|
|
36
|
+
//# sourceMappingURL=provider-options.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"provider-options.mjs","names":[],"sources":["../../../../../../../packages/ai-google/src/provider-options.ts"],"sourcesContent":["import { InvalidRequestError, type ModelCallOptions } from \"@warlock.js/ai\";\n\n/** Adapter-only fields merged after the neutral request parameters. */\nexport type GoogleCallOptions = { body?: Record<string, unknown> };\n\nconst RESERVED_FIELDS = new Set([\"systemInstruction\", \"tools\", \"abortSignal\", \"httpOptions\"]);\n\nexport function mergeProviderBody<T extends object>(\n built: T,\n options: ModelCallOptions | undefined,\n): T {\n const provider = options?.providerOptions?.google as GoogleCallOptions | undefined;\n const body = provider?.body ?? {};\n const reserved = Object.keys(body).filter((key) => RESERVED_FIELDS.has(key));\n if (reserved.length > 0) {\n throw new InvalidRequestError(\n `providerOptions.google.body cannot set ${reserved.join(\", \")}: use the call's messages, tools and model options.`,\n { context: { fields: reserved } },\n );\n }\n const defaults = built as Record<string, unknown>;\n const overrides = Object.fromEntries(\n Object.entries(body).map(([key, value]) => {\n const previous = defaults[key];\n return [\n key,\n isPlainObject(previous) && isPlainObject(value) ? { ...previous, ...value } : value,\n ];\n }),\n );\n return { ...built, ...overrides };\n}\n\n/** Merge only plain objects; arrays, null and provider scalar values replace the field. */\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n if (value === null || typeof value !== \"object\") return false;\n const prototype = Object.getPrototypeOf(value);\n return prototype === Object.prototype || prototype === null;\n}\n"],"mappings":";;;AAKA,MAAM,kBAAkB,IAAI,IAAI;CAAC;CAAqB;CAAS;CAAe;AAAa,CAAC;AAE5F,SAAgB,kBACd,OACA,SACG;CAEH,MAAM,QADW,SAAS,iBAAiB,OACtB,EAAE,QAAQ,CAAC;CAChC,MAAM,WAAW,OAAO,KAAK,IAAI,CAAC,CAAC,QAAQ,QAAQ,gBAAgB,IAAI,GAAG,CAAC;CAC3E,IAAI,SAAS,SAAS,GACpB,MAAM,IAAI,oBACR,0CAA0C,SAAS,KAAK,IAAI,EAAE,sDAC9D,EAAE,SAAS,EAAE,QAAQ,SAAS,EAAE,CAClC;CAEF,MAAM,WAAW;CACjB,MAAM,YAAY,OAAO,YACvB,OAAO,QAAQ,IAAI,CAAC,CAAC,KAAK,CAAC,KAAK,WAAW;EACzC,MAAM,WAAW,SAAS;EAC1B,OAAO,CACL,KACA,cAAc,QAAQ,KAAK,cAAc,KAAK,IAAI;GAAE,GAAG;GAAU,GAAG;EAAM,IAAI,KAChF;CACF,CAAC,CACH;CACA,OAAO;EAAE,GAAG;EAAO,GAAG;CAAU;AAClC;;AAGA,SAAS,cAAc,OAAkD;CACvE,IAAI,UAAU,QAAQ,OAAO,UAAU,UAAU,OAAO;CACxD,MAAM,YAAY,OAAO,eAAe,KAAK;CAC7C,OAAO,cAAc,OAAO,aAAa,cAAc;AACzD"}
|
package/esm/sdk.d.mts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { GoogleEmbedderConfig, GoogleImageConfig, GoogleModelConfig, GoogleSDKConfig } from "./config.type.mjs";
|
|
2
2
|
import { EmbedderContract, ImageModelContract, ModelContract, SDKAdapterContract } from "@warlock.js/ai";
|
|
3
3
|
|
|
4
|
-
//#region
|
|
4
|
+
//#region ../../packages/ai-google/src/sdk.d.ts
|
|
5
5
|
/**
|
|
6
6
|
* Google Gemini-backed implementation of `SDKAdapterContract`.
|
|
7
7
|
*
|
|
@@ -37,8 +37,9 @@ declare class GoogleSDK implements SDKAdapterContract {
|
|
|
37
37
|
* `GoogleGenAI` client. The SDK's `provider` label is forwarded.
|
|
38
38
|
*
|
|
39
39
|
* Pricing resolution: per-model `config.pricing` wins; otherwise the
|
|
40
|
-
* SDK-level registry entry keyed by `config.name`; otherwise
|
|
41
|
-
* `
|
|
40
|
+
* SDK-level registry entry keyed by `config.name`; otherwise the
|
|
41
|
+
* built-in list price (`GOOGLE_MODEL_PRICING`); otherwise `undefined`
|
|
42
|
+
* (no cost computed).
|
|
42
43
|
*/
|
|
43
44
|
model(config: GoogleModelConfig): ModelContract;
|
|
44
45
|
/**
|
package/esm/sdk.d.mts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"sdk.d.mts","names":[],"sources":["
|
|
1
|
+
{"version":3,"file":"sdk.d.mts","names":[],"sources":["../../../../../../../packages/ai-google/src/sdk.ts"],"mappings":";;;;;;AA+EA;;;;;;;;;;;;;;;;;;;;;;cAAa,SAAA,YAAqB,kBAAA;EAAA,iBACf,EAAA;EAAA,iBACA,QAAA;EAAA,iBACA,OAAA;cAEE,MAAA,EAAQ,eAAA;EAiCM;;;;;;;;;;EAf1B,KAAA,CAAM,MAAA,EAAQ,iBAAA,GAAoB,aAAA;EAqDkB;;;;;;EAtC9C,KAAA,CAAM,IAAA,UAAc,MAAA,YAAkB,OAAA;;;;;;;;EAW5C,QAAA,CAAS,MAAA,EAAQ,oBAAA,GAAuB,gBAAA;;;;;;;;;;;;;;;;;;;;;;;;EA2BxC,KAAA,CAAM,MAAA,EAAQ,iBAAA,GAAoB,kBAAA;AAAA"}
|
package/esm/sdk.mjs
CHANGED
|
@@ -1,11 +1,12 @@
|
|
|
1
1
|
import { GoogleEmbedder } from "./embedder.mjs";
|
|
2
2
|
import { GeminiImageModel } from "./gemini-image.mjs";
|
|
3
3
|
import { GoogleImageModel } from "./image.mjs";
|
|
4
|
+
import { googlePricingFor } from "./known-pricing.mjs";
|
|
4
5
|
import { GoogleModel } from "./model.mjs";
|
|
5
6
|
import { GoogleGenAI } from "@google/genai";
|
|
6
7
|
import { approximateTokenCount } from "@warlock.js/ai";
|
|
7
8
|
|
|
8
|
-
//#region
|
|
9
|
+
//#region ../../packages/ai-google/src/sdk.ts
|
|
9
10
|
/**
|
|
10
11
|
* Pick the transport for an image model id.
|
|
11
12
|
*
|
|
@@ -73,11 +74,12 @@ var GoogleSDK = class {
|
|
|
73
74
|
* `GoogleGenAI` client. The SDK's `provider` label is forwarded.
|
|
74
75
|
*
|
|
75
76
|
* Pricing resolution: per-model `config.pricing` wins; otherwise the
|
|
76
|
-
* SDK-level registry entry keyed by `config.name`; otherwise
|
|
77
|
-
* `
|
|
77
|
+
* SDK-level registry entry keyed by `config.name`; otherwise the
|
|
78
|
+
* built-in list price (`GOOGLE_MODEL_PRICING`); otherwise `undefined`
|
|
79
|
+
* (no cost computed).
|
|
78
80
|
*/
|
|
79
81
|
model(config) {
|
|
80
|
-
const resolvedPricing = config.pricing ?? this.pricing?.[config.name];
|
|
82
|
+
const resolvedPricing = config.pricing ?? this.pricing?.[config.name] ?? googlePricingFor(config.name);
|
|
81
83
|
const resolvedConfig = resolvedPricing === config.pricing ? config : {
|
|
82
84
|
...config,
|
|
83
85
|
pricing: resolvedPricing
|
package/esm/sdk.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"sdk.mjs","names":[],"sources":["
|
|
1
|
+
{"version":3,"file":"sdk.mjs","names":[],"sources":["../../../../../../../packages/ai-google/src/sdk.ts"],"sourcesContent":["import { GoogleGenAI } from \"@google/genai\";\nimport type {\n EmbedderContract,\n ImageModelContract,\n ModelContract,\n ModelPricing,\n SDKAdapterContract,\n} from \"@warlock.js/ai\";\nimport { approximateTokenCount } from \"@warlock.js/ai\";\nimport type {\n GoogleEmbedderConfig,\n GoogleImageConfig,\n GoogleModelConfig,\n GoogleSDKConfig,\n} from \"./config.type\";\nimport { GoogleEmbedder } from \"./embedder\";\nimport { GeminiImageModel } from \"./gemini-image\";\nimport { GoogleImageModel } from \"./image\";\nimport { googlePricingFor } from \"./known-pricing\";\nimport { GoogleModel } from \"./model\";\n\n/**\n * Pick the transport for an image model id.\n *\n * `ai.models.generateImages` calls `{model}:predict`, and a `gemini-`\n * id sent there comes back `404 … is not supported for predict`\n * (observed verbatim from Google). `generateContent` is what the SDK\n * itself points `generateImages` users at — its deprecation notice\n * reads \"Please use the generateContent method with image models\n * instead\" — so the id has to choose the transport.\n *\n * Runs in this package establish where a `gemini-` id is ACCEPTED, not\n * what it returns: on this transport such an id got as far as a quota\n * error (HTTP 429) instead of the 404. That an image\n * comes back end-to-end once billing is enabled is reported by the\n * maintainer from a locally linked build, not measured here. Whether\n * these models report token usage is still unknown.\n *\n * This is ROUTING, not validation — no id is refused here. An id this\n * function does not recognize takes the `generateImages` route, the\n * only route that existed before Gemini image support landed, so every\n * id that reached Google before still reaches Google the same way and\n * still fails (or succeeds) at the provider.\n *\n * A leading `models/` resource prefix is tolerated, matching the id\n * shapes `inferVisionCapability` already accepts\n * (`models/gemini-1.5-flash-001`).\n */\nfunction usesGeminiImageTransport(name: string): boolean {\n return name\n .toLowerCase()\n .replace(/^models\\//, \"\")\n .startsWith(\"gemini-\");\n}\n\n/**\n * Google Gemini-backed implementation of `SDKAdapterContract`.\n *\n * **Role.** The package entry point for Gemini models via the\n * `@google/genai` SDK. A single `GoogleSDK` holds one live\n * `GoogleGenAI` client, shared by every `ModelContract` /\n * `EmbedderContract` it produces. Construct one SDK per\n * account/project and reuse it everywhere.\n *\n * **Responsibility.**\n * - Owns: a long-lived `GoogleGenAI` client (auth, Vertex vs Gemini\n * API) and its lifetime. Factory for `GoogleModel` /\n * `GoogleEmbedder` instances sharing that client.\n * - Does NOT own: anything per-call — those live in `GoogleModel` /\n * `GoogleEmbedder` and the agent runtime.\n *\n * Modeled as a class (see §4.2 of code-style.md — \"long-lived state\n * across many calls\"), fronted by FP usage like the other adapters.\n *\n * @example\n * const google = new GoogleSDK({ apiKey: process.env.GEMINI_API_KEY! });\n * const model = google.model({ name: \"gemini-2.5-flash\", temperature: 0.7 });\n * const embedder = google.embedder({ name: \"gemini-embedding-001\" });\n */\nexport class GoogleSDK implements SDKAdapterContract {\n private readonly ai: GoogleGenAI;\n private readonly provider: string;\n private readonly pricing?: Record<string, ModelPricing>;\n\n public constructor(config: GoogleSDKConfig) {\n const { provider, pricing, ...clientOptions } = config;\n\n this.ai = new GoogleGenAI(clientOptions);\n this.provider = provider ?? \"google\";\n this.pricing = pricing;\n }\n\n /**\n * Build a `GoogleModel` bound to this SDK's client. Each call\n * returns a fresh instance; all instances share the underlying\n * `GoogleGenAI` client. The SDK's `provider` label is forwarded.\n *\n * Pricing resolution: per-model `config.pricing` wins; otherwise the\n * SDK-level registry entry keyed by `config.name`; otherwise the\n * built-in list price (`GOOGLE_MODEL_PRICING`); otherwise `undefined`\n * (no cost computed).\n */\n public model(config: GoogleModelConfig): ModelContract {\n const resolvedPricing =\n config.pricing ?? this.pricing?.[config.name] ?? googlePricingFor(config.name);\n const resolvedConfig: GoogleModelConfig =\n resolvedPricing === config.pricing ? config : { ...config, pricing: resolvedPricing };\n\n return new GoogleModel(this.ai, resolvedConfig, this.provider);\n }\n\n /**\n * Rough token-count estimate. Uses the character-heuristic\n * (`approximateTokenCount`) from the core package — Gemini's\n * `countTokens` is a network round-trip; `count()` is intentionally\n * offline. Good for budgeting/quota guards, not billing.\n */\n public async count(text: string, _model?: string): Promise<number> {\n return approximateTokenCount(text);\n }\n\n /**\n * Build a `GoogleEmbedder` bound to this SDK's client.\n *\n * @example\n * const embedder = google.embedder({ name: \"gemini-embedding-001\" });\n * const { vector } = await embedder.embed(\"Hello world\");\n */\n public embedder(config: GoogleEmbedderConfig): EmbedderContract {\n return new GoogleEmbedder(this.ai, config, this.provider);\n }\n\n /**\n * Build an image model bound to this SDK's client for use with\n * `ai.image({ model, prompt })`. `config.name` decides the transport\n * (see {@link usesGeminiImageTransport}) — a `gemini-` id gets the\n * `generateContent` implementation, everything else the Imagen\n * `generateImages` one. No id is rejected locally either way, so an\n * unsupported model fails at Google, not here.\n *\n * The two differ in what usage they can report, which is what the\n * caller must price for: the Imagen path always returns a zero token\n * `Usage` (Imagen reports none — price with `{ perImage }`), while the\n * Gemini path passes through whatever `usageMetadata` Google attaches\n * (price with `{ input, output }` when tokens come back).\n *\n * Pricing resolution mirrors `model()`: per-model `config.pricing`\n * wins, otherwise the SDK-level registry entry keyed by `config.name`,\n * otherwise `undefined`.\n *\n * @example\n * const imagen = google.image({ name: \"imagen-4.0-generate-001\" });\n * const gemini = google.image({ name: \"gemini-3.1-flash-lite-image\" });\n * const { data } = await ai.image({ model: gemini, prompt: \"a red bicycle\" });\n */\n public image(config: GoogleImageConfig): ImageModelContract {\n const resolvedPricing = config.pricing ?? this.pricing?.[config.name];\n const resolvedConfig: GoogleImageConfig =\n resolvedPricing === config.pricing ? config : { ...config, pricing: resolvedPricing };\n\n if (usesGeminiImageTransport(config.name)) {\n return new GeminiImageModel(this.ai, resolvedConfig, this.provider);\n }\n\n return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
1
|
-
//#region
|
|
1
|
+
//#region ../../packages/ai-google/src/utils/apply-google-usage.ts
|
|
2
2
|
/**
|
|
3
3
|
* Fold a Gemini `usageMetadata` block into a running neutral `Usage`
|
|
4
4
|
* accumulator. Shared by every `generateContent`-backed surface — the
|
|
@@ -14,8 +14,13 @@
|
|
|
14
14
|
*
|
|
15
15
|
* `total` falls back to `input + output` when Google omits
|
|
16
16
|
* `totalTokenCount`.
|
|
17
|
+
*
|
|
18
|
+
* `promptTokenCount` "includes the number of tokens in the cached
|
|
19
|
+
* content" (https://ai.google.dev/api/generate-content#UsageMetadata), so
|
|
20
|
+
* the usage is marked `inputIncludesCache: true`.
|
|
17
21
|
*/
|
|
18
22
|
function applyGoogleUsage(usage, raw) {
|
|
23
|
+
usage.inputIncludesCache = true;
|
|
19
24
|
usage.input = raw.promptTokenCount ?? usage.input;
|
|
20
25
|
usage.output = raw.candidatesTokenCount ?? usage.output;
|
|
21
26
|
usage.total = raw.totalTokenCount ?? usage.input + usage.output;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"apply-google-usage.mjs","names":[],"sources":["
|
|
1
|
+
{"version":3,"file":"apply-google-usage.mjs","names":[],"sources":["../../../../../../../../packages/ai-google/src/utils/apply-google-usage.ts"],"sourcesContent":["import type { Usage } from \"@warlock.js/ai\";\nimport type { GenerateContentResponse } from \"@google/genai\";\n\n/** Gemini's per-response token accounting block, as the SDK types it. */\nexport type GoogleUsageMetadata = NonNullable<GenerateContentResponse[\"usageMetadata\"]>;\n\n/**\n * Fold a Gemini `usageMetadata` block into a running neutral `Usage`\n * accumulator. Shared by every `generateContent`-backed surface — the\n * chat model's `complete()`, its streaming loop (where the final chunk\n * carries cumulative totals), and the Gemini image model — so one\n * mapping decides what a Gemini token report means package-wide.\n *\n * Cache-read hits (`cachedContentTokenCount`, implicit or explicit\n * context caching) surface as `cachedTokens`; the thinking-phase tokens\n * of a reasoning model (`thoughtsTokenCount`) surface as\n * `reasoningTokens`. Both are emitted only when reported `> 0` so an\n * absent channel leaves the field undefined rather than a false zero.\n *\n * `total` falls back to `input + output` when Google omits\n * `totalTokenCount`.\n *\n * `promptTokenCount` \"includes the number of tokens in the cached\n * content\" (https://ai.google.dev/api/generate-content#UsageMetadata), so\n * the usage is marked `inputIncludesCache: true`.\n */\nexport function applyGoogleUsage(usage: Usage, raw: GoogleUsageMetadata): void {\n usage.inputIncludesCache = true;\n usage.input = raw.promptTokenCount ?? usage.input;\n usage.output = raw.candidatesTokenCount ?? usage.output;\n usage.total = raw.totalTokenCount ?? usage.input + usage.output;\n\n const cached = raw.cachedContentTokenCount;\n\n if (cached && cached > 0) {\n usage.cachedTokens = cached;\n }\n\n const reasoning = raw.thoughtsTokenCount;\n\n if (reasoning && reasoning > 0) {\n usage.reasoningTokens = reasoning;\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AA0BA,SAAgB,iBAAiB,OAAc,KAAgC;CAC7E,MAAM,qBAAqB;CAC3B,MAAM,QAAQ,IAAI,oBAAoB,MAAM;CAC5C,MAAM,SAAS,IAAI,wBAAwB,MAAM;CACjD,MAAM,QAAQ,IAAI,mBAAmB,MAAM,QAAQ,MAAM;CAEzD,MAAM,SAAS,IAAI;CAEnB,IAAI,UAAU,SAAS,GACrB,MAAM,eAAe;CAGvB,MAAM,YAAY,IAAI;CAEtB,IAAI,aAAa,YAAY,GAC3B,MAAM,kBAAkB;AAE5B"}
|