@warlock.js/ai-google 5.31.0 → 5.32.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 +14 -0
- package/cjs/index.cjs +85 -8
- package/cjs/index.cjs.map +1 -1
- package/esm/config.type.d.mts +4 -6
- package/esm/config.type.d.mts.map +1 -1
- package/esm/gemini-image.d.mts +1 -3
- 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 -3
- package/esm/image.d.mts.map +1 -1
- package/esm/index.d.mts +2 -2
- package/esm/index.mjs +2 -2
- package/esm/known-pricing.d.mts +8 -4
- package/esm/known-pricing.d.mts.map +1 -1
- package/esm/known-pricing.mjs +5 -1
- package/esm/known-pricing.mjs.map +1 -1
- package/esm/model.mjs +51 -6
- package/esm/model.mjs.map +1 -1
- package/esm/provider-options.d.mts +2 -2
- package/esm/provider-options.d.mts.map +1 -1
- package/esm/provider-options.mjs +1 -1
- package/esm/provider-options.mjs.map +1 -1
- package/esm/sdk.d.mts +1 -3
- package/esm/sdk.d.mts.map +1 -1
- package/esm/utils/grounding.mjs +30 -0
- package/esm/utils/grounding.mjs.map +1 -0
- package/esm/utils/index.mjs +1 -1
- package/llms-full.txt +60 -11
- package/package.json +3 -3
- package/skills/setup-google/SKILL.md +60 -11
package/esm/gemini-image.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"gemini-image.mjs","names":[],"sources":["../../../../../../../packages/ai-google/src/gemini-image.ts"],"sourcesContent":["import {\n ContentFilterError,\n ProviderError,\n type AIError,\n type GeneratedImage,\n type ImageGenerationOptions,\n type ImageGenerationResponse,\n type ImageModelContract,\n type ImageModelPricing,\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 ImageConfig,\n Part,\n} from \"@google/genai\";\nimport type { GoogleImageConfig } from \"./config.type\";\nimport { applyGoogleUsage, wrapGoogleError } from \"./utils\";\n\nconst LOG_MODULE = \"ai.google\";\n\n/**\n * Response modalities requested when the caller names none.\n *\n * `IMAGE` is the modality this adapter extracts; `TEXT` rides along so\n * a model that narrates what it drew is not answering outside the set\n * it was granted (the narration is then dropped — only inline image\n * parts become `GeneratedImage`s).\n *\n * *Unverified:* which pairing any individual Gemini image model\n * requires is not established here — no spec or run in this package\n * touches the live API. `options.responseModalities` replaces this list\n * verbatim for a model that wants something else.\n */\nconst DEFAULT_RESPONSE_MODALITIES = [\"TEXT\", \"IMAGE\"];\n\n/**\n * Gemini `finishReason` values that mean generation was stopped by a\n * safety / policy rule rather than by the model simply not drawing.\n * Taken from the `FinishReason` enum in `@google/genai`'s own type\n * declarations, whose doc comments describe each of these as content\n * or image generation being \"stopped\" for safety, prohibited content,\n * recitation, blocklist, or SPII.\n */\nconst FILTERED_FINISH_REASONS = new Set([\n \"SAFETY\",\n \"IMAGE_SAFETY\",\n \"PROHIBITED_CONTENT\",\n \"IMAGE_PROHIBITED_CONTENT\",\n \"RECITATION\",\n \"IMAGE_RECITATION\",\n \"BLOCKLIST\",\n \"SPII\",\n]);\n\n/** How much of a text-only answer to quote back inside the error message. */\nconst TEXT_EXCERPT_LIMIT = 200;\n\n/**\n * Gemini-native implementation of `ImageModelContract`, via\n * `ai.models.generateContent` with `config.responseModalities`\n * including `\"IMAGE\"`.\n *\n * **Why a second image adapter.** `GoogleImageModel` calls\n * `ai.models.generateImages`, which the `@google/genai` bundle routes\n * to `{model}:predict` (`generateImages` → `generateImagesInternal` →\n * `formatMap('{model}:predict', …)`). A Gemini image model is not\n * served there: asking for one returns Google's\n * `404 … is not found for API version v1beta, or is not supported for\n * predict`. `generateContent` is the SDK's own named replacement — its\n * runtime deprecation notice for `generateImages` reads \"Please use the\n * generateContent method with image models instead\" — so that is the\n * transport this class speaks, hence a separate class rather than a\n * branch inside `image.ts`.\n *\n * **Same envelope.** Inline image parts are mapped to the identical\n * `GeneratedImage[]` shape `GoogleImageModel` produces, so `ai.image()`\n * callers see no difference between the two paths.\n *\n * **Token usage is passed through, not zeroed.** The Imagen path\n * returns a hard `{ 0, 0, 0 }` because Imagen reports no tokens at all;\n * here, whatever `usageMetadata` Google attaches is mapped by the same\n * {@link applyGoogleUsage} the chat model uses, and only an absent\n * block collapses to zeros. Price accordingly.\n *\n * **No model-id validation.** `config.name` is forwarded to\n * `generateContent` exactly as given; nothing here inspects it. An id\n * Google does not serve fails at Google, wrapped into the typed\n * `AIError` hierarchy — never with a local throw.\n *\n * **Evidence, in two tiers.** No spec in this package calls Google.\n * *Measured here:* a `gemini-*` image id, which 404s on the `predict`\n * transport, reached the model on this one and came back with a quota\n * error (HTTP 429) — the endpoint accepts the id. *Reported by the\n * maintainer:* once billing was enabled on the project, an image came\n * back end-to-end from an application running a locally linked build.\n * *Still unestablished:* whether these models report token usage — no\n * `usageMetadata` from a successful image call has been observed, so\n * the pass-through above is untested against a real response.\n *\n * @example\n * const model = new GeminiImageModel(ai, { name: \"gemini-3.1-flash-lite-image\" });\n * const { images, usage } = await model.generate(\"a red bicycle on a white background\");\n */\nexport class GeminiImageModel 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 = this.buildConfig(options);\n\n this.logger.debug(LOG_MODULE, \"image.request\", \"models.generateContent\", {\n model: this.name,\n responseModalities: config.responseModalities,\n });\n\n let response: GenerateContentResponse;\n\n try {\n // `contents` takes a bare string: the SDK's own `generateContent`\n // example passes one (`contents: 'Why is the sky blue?'`).\n response = await this.ai.models.generateContent({\n model: this.name,\n contents: prompt,\n config,\n });\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 parts = collectParts(response);\n const images = toGeneratedImages(parts);\n\n if (images.length === 0) {\n throw this.noImageError(response, parts);\n }\n\n const usage: Usage = { input: 0, output: 0, total: 0 };\n\n if (response.usageMetadata) {\n applyGoogleUsage(usage, response.usageMetadata);\n }\n\n this.logger.debug(LOG_MODULE, \"image.response\", \"models.generateContent succeeded\", {\n images: images.length,\n usage,\n });\n\n return { images, usage };\n }\n\n /**\n * Assemble the `GenerateContentConfig` for an image turn: the\n * requested modalities, the image-specific knobs Gemini exposes under\n * `imageConfig`, and the cancellation handle.\n *\n * Three neutral options are deliberately NOT forwarded, because\n * `GenerateContentConfig` / `ImageConfig` in `@google/genai` expose\n * no equivalent for them on this path: `count` (no per-request image\n * count — every inline image part the model does return is mapped),\n * `negativePrompt` (an Imagen-only field), and `format`\n * (`ImageConfig.outputMimeType` is documented \"not supported in\n * Gemini API\"). Fold those intentions into the prompt instead.\n */\n private buildConfig(options: ImageGenerationOptions | undefined): GenerateContentConfig {\n const imageConfig: ImageConfig = {};\n\n if (options?.aspectRatio !== undefined) {\n imageConfig.aspectRatio = options.aspectRatio;\n }\n\n // Provider passthroughs off the neutral options' index signature —\n // forwarded verbatim, never re-spelled, so the value the caller\n // wrote is the value Google rules on. `ImageConfig` documents\n // `imageSize` as `1K`/`2K`/`4K` and `personGeneration` as\n // `ALLOW_ALL`/`ALLOW_ADULT`/`ALLOW_NONE`.\n if (typeof options?.imageSize === \"string\") {\n imageConfig.imageSize = options.imageSize;\n }\n\n if (typeof options?.personGeneration === \"string\") {\n imageConfig.personGeneration = options.personGeneration;\n }\n\n const requested = options?.responseModalities;\n const responseModalities = Array.isArray(requested)\n ? (requested as string[])\n : DEFAULT_RESPONSE_MODALITIES;\n\n return {\n responseModalities,\n ...(Object.keys(imageConfig).length > 0 ? { imageConfig } : {}),\n ...(options?.signal ? { abortSignal: options.signal } : {}),\n };\n }\n\n /**\n * Build the typed error for a response that carried no inline image\n * part. Never a silent empty success: the caller asked for an image\n * and got something else, so the error names what actually came back.\n *\n * - A blocked prompt (`promptFeedback.blockReason`) or a\n * safety/policy `finishReason` → `ContentFilterError` carrying the\n * reason, matching how the Imagen path reports `raiFilteredReason`.\n * - A text-only answer → `ProviderError` quoting the text, so the\n * log says what the model replied instead of guessing.\n * - Anything else → `ProviderError` naming the finish reason and how\n * many parts arrived.\n */\n private noImageError(response: GenerateContentResponse, parts: Part[]): AIError {\n const blockReason = response.promptFeedback?.blockReason;\n\n if (blockReason) {\n return new ContentFilterError(`Gemini blocked the prompt for ${this.name}: ${blockReason}`, {\n reason: blockReason,\n });\n }\n\n const finishReason = response.candidates?.[0]?.finishReason;\n\n if (finishReason && FILTERED_FINISH_REASONS.has(finishReason)) {\n return new ContentFilterError(`Gemini filtered the image for ${this.name}: ${finishReason}`, {\n reason: finishReason,\n });\n }\n\n const text = collectText(parts);\n\n if (text) {\n return new ProviderError(\n `Gemini returned no image for ${this.name} — the response was text only: \"${excerpt(text)}\"`,\n { context: { model: this.name, ...(finishReason ? { finishReason } : {}) } },\n );\n }\n\n return new ProviderError(\n `Gemini returned no image part for ${this.name} (parts: ${parts.length}${\n finishReason ? `, finishReason: ${finishReason}` : \"\"\n }).`,\n { context: { model: this.name, parts: parts.length } },\n );\n }\n}\n\n/**\n * Flatten every candidate's content parts into one list. Read off\n * `candidates[].content.parts` rather than the response's convenience\n * getters: `response.text` covers only the first candidate's text and\n * there is no getter for inline image data at all.\n */\nfunction collectParts(response: GenerateContentResponse): Part[] {\n const parts: Part[] = [];\n\n for (const candidate of response.candidates ?? []) {\n parts.push(...(candidate.content?.parts ?? []));\n }\n\n return parts;\n}\n\n/**\n * Map the inline image parts to the neutral `GeneratedImage[]` — the\n * same `{ type: \"base64\", base64, mediaType }` shape the Imagen path\n * emits, including its `image/png` fallback for a part that arrives\n * without a declared mime type.\n */\nfunction toGeneratedImages(parts: Part[]): GeneratedImage[] {\n const images: GeneratedImage[] = [];\n\n for (const part of parts) {\n const data = part.inlineData?.data;\n\n if (!data) {\n continue;\n }\n\n images.push({\n type: \"base64\",\n base64: data,\n mediaType: part.inlineData?.mimeType ?? \"image/png\",\n });\n }\n\n return images;\n}\n\n/** Join the text parts of a response — what the model said instead of drawing. */\nfunction collectText(parts: Part[]): string {\n return parts\n .map((part) => part.text)\n .filter((text): text is string => typeof text === \"string\" && text.length > 0)\n .join(\" \")\n .trim();\n}\n\n/** Trim a quoted model answer so an error message stays readable. */\nfunction excerpt(text: string): string {\n return text.length > TEXT_EXCERPT_LIMIT ? `${text.slice(0, TEXT_EXCERPT_LIMIT)}…` : text;\n}\n"],"mappings":";;;;;;;AAsBA,MAAM,aAAa;;;;;;;;;;;;;;AAenB,MAAM,8BAA8B,CAAC,QAAQ,OAAO;;;;;;;;;AAUpD,MAAM,0BAA0B,IAAI,IAAI;CACtC;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF,CAAC;;AAGD,MAAM,qBAAqB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAgD3B,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,SAAS,KAAK,YAAY,OAAO;EAEvC,KAAK,OAAO,MAAM,YAAY,iBAAiB,0BAA0B;GACvE,OAAO,KAAK;GACZ,oBAAoB,OAAO;EAC7B,CAAC;EAED,IAAI;EAEJ,IAAI;GAGF,WAAW,MAAM,KAAK,GAAG,OAAO,gBAAgB;IAC9C,OAAO,KAAK;IACZ,UAA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F"}
|
|
1
|
+
{"version":3,"file":"gemini-image.mjs","names":[],"sources":["../../../../../../../packages/ai-google/src/gemini-image.ts"],"sourcesContent":["import {\n ContentFilterError,\n ProviderError,\n type AIError,\n type GeneratedImage,\n type ImageGenerationOptions,\n type ImageGenerationResponse,\n type ImageModelContract,\n type ImageModelPricing,\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 ImageConfig,\n Part,\n} from \"@google/genai\";\nimport type { GoogleImageConfig } from \"./config.type\";\nimport { applyGoogleUsage, wrapGoogleError } from \"./utils\";\n\nconst LOG_MODULE = \"ai.google\";\n\n/**\n * Response modalities requested when the caller names none.\n *\n * `IMAGE` is the modality this adapter extracts; `TEXT` rides along so\n * a model that narrates what it drew is not answering outside the set\n * it was granted (the narration is then dropped — only inline image\n * parts become `GeneratedImage`s).\n *\n * *Unverified:* which pairing any individual Gemini image model\n * requires is not established here — no spec or run in this package\n * touches the live API. `options.responseModalities` replaces this list\n * verbatim for a model that wants something else.\n */\nconst DEFAULT_RESPONSE_MODALITIES = [\"TEXT\", \"IMAGE\"];\n\n/**\n * Gemini `finishReason` values that mean generation was stopped by a\n * safety / policy rule rather than by the model simply not drawing.\n * Taken from the `FinishReason` enum in `@google/genai`'s own type\n * declarations, whose doc comments describe each of these as content\n * or image generation being \"stopped\" for safety, prohibited content,\n * recitation, blocklist, or SPII.\n */\nconst FILTERED_FINISH_REASONS = new Set([\n \"SAFETY\",\n \"IMAGE_SAFETY\",\n \"PROHIBITED_CONTENT\",\n \"IMAGE_PROHIBITED_CONTENT\",\n \"RECITATION\",\n \"IMAGE_RECITATION\",\n \"BLOCKLIST\",\n \"SPII\",\n]);\n\n/** How much of a text-only answer to quote back inside the error message. */\nconst TEXT_EXCERPT_LIMIT = 200;\n\n/**\n * Gemini-native implementation of `ImageModelContract`, via\n * `ai.models.generateContent` with `config.responseModalities`\n * including `\"IMAGE\"`.\n *\n * **Why a second image adapter.** `GoogleImageModel` calls\n * `ai.models.generateImages`, which the `@google/genai` bundle routes\n * to `{model}:predict` (`generateImages` → `generateImagesInternal` →\n * `formatMap('{model}:predict', …)`). A Gemini image model is not\n * served there: asking for one returns Google's\n * `404 … is not found for API version v1beta, or is not supported for\n * predict`. `generateContent` is the SDK's own named replacement — its\n * runtime deprecation notice for `generateImages` reads \"Please use the\n * generateContent method with image models instead\" — so that is the\n * transport this class speaks, hence a separate class rather than a\n * branch inside `image.ts`.\n *\n * **Same envelope.** Inline image parts are mapped to the identical\n * `GeneratedImage[]` shape `GoogleImageModel` produces, so `ai.image()`\n * callers see no difference between the two paths.\n *\n * **Token usage is passed through, not zeroed.** The Imagen path\n * returns a hard `{ 0, 0, 0 }` because Imagen reports no tokens at all;\n * here, whatever `usageMetadata` Google attaches is mapped by the same\n * {@link applyGoogleUsage} the chat model uses, and only an absent\n * block collapses to zeros. Price accordingly.\n *\n * **No model-id validation.** `config.name` is forwarded to\n * `generateContent` exactly as given; nothing here inspects it. An id\n * Google does not serve fails at Google, wrapped into the typed\n * `AIError` hierarchy — never with a local throw.\n *\n * **Evidence, in two tiers.** No spec in this package calls Google.\n * *Measured here:* a `gemini-*` image id, which 404s on the `predict`\n * transport, reached the model on this one and came back with a quota\n * error (HTTP 429) — the endpoint accepts the id. *Reported by the\n * maintainer:* once billing was enabled on the project, an image came\n * back end-to-end from an application running a locally linked build.\n * *Still unestablished:* whether these models report token usage — no\n * `usageMetadata` from a successful image call has been observed, so\n * the pass-through above is untested against a real response.\n *\n * @example\n * const model = new GeminiImageModel(ai, { name: \"gemini-3.1-flash-lite-image\" });\n * const { images, usage } = await model.generate(\"a red bicycle on a white background\");\n */\nexport class GeminiImageModel 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 = this.buildConfig(options);\n\n this.logger.debug(LOG_MODULE, \"image.request\", \"models.generateContent\", {\n model: this.name,\n responseModalities: config.responseModalities,\n });\n\n let response: GenerateContentResponse;\n\n try {\n // `contents` takes a bare string: the SDK's own `generateContent`\n // example passes one (`contents: 'Why is the sky blue?'`).\n response = await this.ai.models.generateContent({\n model: this.name,\n contents: prompt,\n config,\n });\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 parts = collectParts(response);\n const images = toGeneratedImages(parts);\n\n if (images.length === 0) {\n throw this.noImageError(response, parts);\n }\n\n const usage: Usage = { input: 0, output: 0, total: 0 };\n\n if (response.usageMetadata) {\n applyGoogleUsage(usage, response.usageMetadata);\n }\n\n this.logger.debug(LOG_MODULE, \"image.response\", \"models.generateContent succeeded\", {\n images: images.length,\n usage,\n });\n\n return { images, usage };\n }\n\n /**\n * Assemble the `GenerateContentConfig` for an image turn: the\n * requested modalities, the image-specific knobs Gemini exposes under\n * `imageConfig`, and the cancellation handle.\n *\n * Three neutral options are deliberately NOT forwarded, because\n * `GenerateContentConfig` / `ImageConfig` in `@google/genai` expose\n * no equivalent for them on this path: `count` (no per-request image\n * count — every inline image part the model does return is mapped),\n * `negativePrompt` (an Imagen-only field), and `format`\n * (`ImageConfig.outputMimeType` is documented \"not supported in\n * Gemini API\"). Fold those intentions into the prompt instead.\n */\n private buildConfig(options: ImageGenerationOptions | undefined): GenerateContentConfig {\n const imageConfig: ImageConfig = {};\n\n if (options?.aspectRatio !== undefined) {\n imageConfig.aspectRatio = options.aspectRatio;\n }\n\n // Provider passthroughs off the neutral options' index signature —\n // forwarded verbatim, never re-spelled, so the value the caller\n // wrote is the value Google rules on. `ImageConfig` documents\n // `imageSize` as `1K`/`2K`/`4K` and `personGeneration` as\n // `ALLOW_ALL`/`ALLOW_ADULT`/`ALLOW_NONE`.\n if (typeof options?.imageSize === \"string\") {\n imageConfig.imageSize = options.imageSize;\n }\n\n if (typeof options?.personGeneration === \"string\") {\n imageConfig.personGeneration = options.personGeneration;\n }\n\n const requested = options?.responseModalities;\n const responseModalities = Array.isArray(requested)\n ? (requested as string[])\n : DEFAULT_RESPONSE_MODALITIES;\n\n return {\n responseModalities,\n ...(Object.keys(imageConfig).length > 0 ? { imageConfig } : {}),\n ...(options?.signal ? { abortSignal: options.signal } : {}),\n };\n }\n\n /**\n * Build the typed error for a response that carried no inline image\n * part. Never a silent empty success: the caller asked for an image\n * and got something else, so the error names what actually came back.\n *\n * - A blocked prompt (`promptFeedback.blockReason`) or a\n * safety/policy `finishReason` → `ContentFilterError` carrying the\n * reason, matching how the Imagen path reports `raiFilteredReason`.\n * - A text-only answer → `ProviderError` quoting the text, so the\n * log says what the model replied instead of guessing.\n * - Anything else → `ProviderError` naming the finish reason and how\n * many parts arrived.\n */\n private noImageError(response: GenerateContentResponse, parts: Part[]): AIError {\n const blockReason = response.promptFeedback?.blockReason;\n\n if (blockReason) {\n return new ContentFilterError(`Gemini blocked the prompt for ${this.name}: ${blockReason}`, {\n reason: blockReason,\n });\n }\n\n const finishReason = response.candidates?.[0]?.finishReason;\n\n if (finishReason && FILTERED_FINISH_REASONS.has(finishReason)) {\n return new ContentFilterError(`Gemini filtered the image for ${this.name}: ${finishReason}`, {\n reason: finishReason,\n });\n }\n\n const text = collectText(parts);\n\n if (text) {\n return new ProviderError(\n `Gemini returned no image for ${this.name} — the response was text only: \"${excerpt(text)}\"`,\n { context: { model: this.name, ...(finishReason ? { finishReason } : {}) } },\n );\n }\n\n return new ProviderError(\n `Gemini returned no image part for ${this.name} (parts: ${parts.length}${\n finishReason ? `, finishReason: ${finishReason}` : \"\"\n }).`,\n { context: { model: this.name, parts: parts.length } },\n );\n }\n}\n\n/**\n * Flatten every candidate's content parts into one list. Read off\n * `candidates[].content.parts` rather than the response's convenience\n * getters: `response.text` covers only the first candidate's text and\n * there is no getter for inline image data at all.\n */\nfunction collectParts(response: GenerateContentResponse): Part[] {\n const parts: Part[] = [];\n\n for (const candidate of response.candidates ?? []) {\n parts.push(...(candidate.content?.parts ?? []));\n }\n\n return parts;\n}\n\n/**\n * Map the inline image parts to the neutral `GeneratedImage[]` — the\n * same `{ type: \"base64\", base64, mediaType }` shape the Imagen path\n * emits, including its `image/png` fallback for a part that arrives\n * without a declared mime type.\n */\nfunction toGeneratedImages(parts: Part[]): GeneratedImage[] {\n const images: GeneratedImage[] = [];\n\n for (const part of parts) {\n const data = part.inlineData?.data;\n\n if (!data) {\n continue;\n }\n\n images.push({\n type: \"base64\",\n base64: data,\n mediaType: part.inlineData?.mimeType ?? \"image/png\",\n });\n }\n\n return images;\n}\n\n/** Join the text parts of a response — what the model said instead of drawing. */\nfunction collectText(parts: Part[]): string {\n return parts\n .map((part) => part.text)\n .filter((text): text is string => typeof text === \"string\" && text.length > 0)\n .join(\" \")\n .trim();\n}\n\n/** Trim a quoted model answer so an error message stays readable. */\nfunction excerpt(text: string): string {\n return text.length > TEXT_EXCERPT_LIMIT ? `${text.slice(0, TEXT_EXCERPT_LIMIT)}…` : text;\n}\n"],"mappings":";;;;;;;AAsBA,MAAM,aAAa;;;;;;;;;;;;;;AAenB,MAAM,8BAA8B,CAAC,QAAQ,OAAO;;;;;;;;;AAUpD,MAAM,0CAA0B,IAAI,IAAI;CACtC;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF,CAAC;;AAGD,MAAM,qBAAqB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAgD3B,IAAa,mBAAb,MAA4D;CAQ1D,AAAO,YAAY,IAAiB,QAA2B,WAAmB,UAAU;gBAF1D;EAGhC,KAAK,KAAK;EACV,KAAK,OAAO,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CAAC;CACH;CAEA,OAAO;AACT;;AAGA,SAAS,YAAY,OAAuB;CAC1C,OAAO,MACJ,KAAK,SAAS,KAAK,IAAI,CAAC,CACxB,QAAQ,SAAyB,OAAO,SAAS,YAAY,KAAK,SAAS,CAAC,CAAC,CAC7E,KAAK,GAAG,CAAC,CACT,KAAK;AACV;;AAGA,SAAS,QAAQ,MAAsB;CACrC,OAAO,KAAK,SAAS,qBAAqB,GAAG,KAAK,MAAM,GAAG,kBAAkB,EAAE,KAAK;AACtF"}
|
package/esm/image.d.mts
CHANGED
|
@@ -1,7 +1,6 @@
|
|
|
1
1
|
import { GoogleImageConfig } from "./config.type.mjs";
|
|
2
2
|
import { GoogleGenAI } from "@google/genai";
|
|
3
3
|
import { ImageGenerationOptions, ImageGenerationResponse, ImageModelContract, ImageModelPricing } from "@warlock.js/ai";
|
|
4
|
-
|
|
5
4
|
//#region ../../packages/ai-google/src/image.d.ts
|
|
6
5
|
/**
|
|
7
6
|
* Google Imagen-backed implementation of `ImageModelContract`, via
|
|
@@ -24,7 +23,7 @@ import { ImageGenerationOptions, ImageGenerationResponse, ImageModelContract, Im
|
|
|
24
23
|
* const model = new GoogleImageModel(ai, { name: "imagen-4.0-generate-001" }, "google");
|
|
25
24
|
* const { images } = await model.generate("a watercolor lighthouse at dawn");
|
|
26
25
|
*/
|
|
27
|
-
declare class GoogleImageModel implements ImageModelContract {
|
|
26
|
+
export declare class GoogleImageModel implements ImageModelContract {
|
|
28
27
|
readonly name: string;
|
|
29
28
|
readonly provider: string;
|
|
30
29
|
readonly pricing?: ImageModelPricing;
|
|
@@ -34,5 +33,4 @@ declare class GoogleImageModel implements ImageModelContract {
|
|
|
34
33
|
generate(prompt: string, options?: ImageGenerationOptions): Promise<ImageGenerationResponse>;
|
|
35
34
|
}
|
|
36
35
|
//#endregion
|
|
37
|
-
export { GoogleImageModel };
|
|
38
36
|
//# sourceMappingURL=image.d.mts.map
|
package/esm/image.d.mts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"image.d.mts","names":[],"sources":["../../../../../../../packages/ai-google/src/image.ts"],"mappings":"
|
|
1
|
+
{"version":3,"file":"image.d.mts","names":[],"sources":["../../../../../../../packages/ai-google/src/image.ts"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;qBAoDa,4BAA4B;WACvB;WACA;WACA,UAAU;mBAET;mBACA;EAEjB,YAAmB,IAAI,aAAa,QAAQ,mBAAmB;EAOlD,SACX,gBACA,UAAU,yBACT,QAAQ"}
|
package/esm/index.d.mts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { GoogleEmbedderConfig, GoogleImageConfig, GoogleModelConfig, GoogleSDKConfig } from "./config.type.mjs";
|
|
2
2
|
import { GoogleSDK } from "./sdk.mjs";
|
|
3
|
-
import { GOOGLE_MODEL_PRICING, googlePricingFor } from "./known-pricing.mjs";
|
|
3
|
+
import { GOOGLE_MODEL_PRICING, GOOGLE_SERVER_TOOL_PRICING, googlePricingFor } from "./known-pricing.mjs";
|
|
4
4
|
import { GeminiImageModel } from "./gemini-image.mjs";
|
|
5
5
|
import { GoogleImageModel } from "./image.mjs";
|
|
6
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 };
|
|
7
|
+
export { GOOGLE_MODEL_PRICING, GOOGLE_SERVER_TOOL_PRICING, GeminiImageModel, type GoogleCallOptions, type GoogleEmbedderConfig, type GoogleImageConfig, GoogleImageModel, type GoogleModelConfig, GoogleSDK, type GoogleSDKConfig, googlePricingFor };
|
package/esm/index.mjs
CHANGED
|
@@ -1,6 +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
|
+
import { GOOGLE_MODEL_PRICING, GOOGLE_SERVER_TOOL_PRICING, googlePricingFor } from "./known-pricing.mjs";
|
|
4
4
|
import { GoogleSDK } from "./sdk.mjs";
|
|
5
5
|
|
|
6
|
-
export { GOOGLE_MODEL_PRICING, GeminiImageModel, GoogleImageModel, GoogleSDK, googlePricingFor };
|
|
6
|
+
export { GOOGLE_MODEL_PRICING, GOOGLE_SERVER_TOOL_PRICING, GeminiImageModel, GoogleImageModel, GoogleSDK, googlePricingFor };
|
package/esm/known-pricing.d.mts
CHANGED
|
@@ -1,5 +1,4 @@
|
|
|
1
1
|
import { ModelPricing } from "@warlock.js/ai";
|
|
2
|
-
|
|
3
2
|
//#region ../../packages/ai-google/src/known-pricing.d.ts
|
|
4
3
|
/**
|
|
5
4
|
* Built-in Gemini API list prices (paid tier, Standard), USD per
|
|
@@ -18,7 +17,7 @@ import { ModelPricing } from "@warlock.js/ai";
|
|
|
18
17
|
* - Models with a scheduled price change (gemini-4-argon, the 3.8 / 3.6
|
|
19
18
|
* Flash models).
|
|
20
19
|
*/
|
|
21
|
-
declare const GOOGLE_MODEL_PRICING: Readonly<Record<string, ModelPricing>>;
|
|
20
|
+
export declare const GOOGLE_MODEL_PRICING: Readonly<Record<string, ModelPricing>>;
|
|
22
21
|
/**
|
|
23
22
|
* Look up the built-in list price for a Gemini model id (exact match),
|
|
24
23
|
* or `undefined` so cost stays unknown rather than wrong.
|
|
@@ -27,7 +26,12 @@ declare const GOOGLE_MODEL_PRICING: Readonly<Record<string, ModelPricing>>;
|
|
|
27
26
|
* googlePricingFor("gemini-3.5-flash-lite"); // { input: 0.3, output: 2.5, cachedInput: 0.03 }
|
|
28
27
|
* googlePricingFor("gemini-2.5-pro"); // undefined — priced by prompt length
|
|
29
28
|
*/
|
|
30
|
-
declare function googlePricingFor(modelName: string): ModelPricing | undefined;
|
|
29
|
+
export declare function googlePricingFor(modelName: string): ModelPricing | undefined;
|
|
30
|
+
/** USD per nonempty unique query for Gemini 3+, before free monthly allowances.
|
|
31
|
+
* Gemini 2.5 and older bill per grounded prompt; do not use this rate for them.
|
|
32
|
+
* https://ai.google.dev/gemini-api/docs/google-search#pricing — verified 2026-10-18. */
|
|
33
|
+
export declare const GOOGLE_SERVER_TOOL_PRICING: {
|
|
34
|
+
webSearch: number;
|
|
35
|
+
};
|
|
31
36
|
//#endregion
|
|
32
|
-
export { GOOGLE_MODEL_PRICING, googlePricingFor };
|
|
33
37
|
//# sourceMappingURL=known-pricing.d.mts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"known-pricing.d.mts","names":[],"sources":["../../../../../../../packages/ai-google/src/known-pricing.ts"],"mappings":"
|
|
1
|
+
{"version":3,"file":"known-pricing.d.mts","names":[],"sources":["../../../../../../../packages/ai-google/src/known-pricing.ts"],"mappings":";;;;;;;;;;;;;;;;;;;qBAmBa,sBAAsB,SAAS,eAAe;;;;;;;;;wBAY3C,iBAAiB,oBAAoB;;;;qBAOxC;EAA+B"}
|
package/esm/known-pricing.mjs
CHANGED
|
@@ -32,7 +32,11 @@ const GOOGLE_MODEL_PRICING = { "gemini-3.5-flash-lite": {
|
|
|
32
32
|
function googlePricingFor(modelName) {
|
|
33
33
|
return GOOGLE_MODEL_PRICING[modelName];
|
|
34
34
|
}
|
|
35
|
+
/** USD per nonempty unique query for Gemini 3+, before free monthly allowances.
|
|
36
|
+
* Gemini 2.5 and older bill per grounded prompt; do not use this rate for them.
|
|
37
|
+
* https://ai.google.dev/gemini-api/docs/google-search#pricing — verified 2026-10-18. */
|
|
38
|
+
const GOOGLE_SERVER_TOOL_PRICING = { webSearch: .014 };
|
|
35
39
|
|
|
36
40
|
//#endregion
|
|
37
|
-
export { GOOGLE_MODEL_PRICING, googlePricingFor };
|
|
41
|
+
export { GOOGLE_MODEL_PRICING, GOOGLE_SERVER_TOOL_PRICING, googlePricingFor };
|
|
38
42
|
//# sourceMappingURL=known-pricing.mjs.map
|
|
@@ -1 +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
|
+
{"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\n/** USD per nonempty unique query for Gemini 3+, before free monthly allowances.\n * Gemini 2.5 and older bill per grounded prompt; do not use this rate for them.\n * https://ai.google.dev/gemini-api/docs/google-search#pricing — verified 2026-10-18. */\nexport const GOOGLE_SERVER_TOOL_PRICING = { webSearch: 0.014 };\n"],"mappings":";;;;;;;;;;;;;;;;;;AAmBA,MAAa,uBAA+D,EAC1E,yBAAyB;CAAE,OAAO;CAAK,QAAQ;CAAK,aAAa;AAAK,EACxE;;;;;;;;;AAUA,SAAgB,iBAAiB,WAA6C;CAC5E,OAAO,qBAAqB;AAC9B;;;;AAKA,MAAa,6BAA6B,EAAE,WAAW,KAAM"}
|
package/esm/model.mjs
CHANGED
|
@@ -4,6 +4,7 @@ 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 { applyGrounding, groundingMetadata } from "./utils/grounding.mjs";
|
|
7
8
|
import { mergeProviderBody } from "./provider-options.mjs";
|
|
8
9
|
import { inferVisionCapability } from "./known-vision-models.mjs";
|
|
9
10
|
import { InvalidRequestError, attachCost, resolveStreamChunks, selectProviderTools } from "@warlock.js/ai";
|
|
@@ -106,12 +107,17 @@ var GoogleModel = class {
|
|
|
106
107
|
}
|
|
107
108
|
const toolCalls = this.extractToolCalls(response);
|
|
108
109
|
const finishReason = toolCalls ? "tool_calls" : mapFinishReason(response.candidates?.[0]?.finishReason);
|
|
109
|
-
const usage =
|
|
110
|
+
const usage = this.extractUsage(response);
|
|
111
|
+
const grounding = /* @__PURE__ */ new Map();
|
|
112
|
+
applyGrounding(usage, grounding, response);
|
|
113
|
+
const providerMetadata = groundingMetadata(grounding);
|
|
114
|
+
attachCost(usage, this.pricing);
|
|
110
115
|
this.logger.debug(LOG_MODULE, "response", "generateContent call succeeded", {
|
|
111
116
|
finishReason,
|
|
112
117
|
usage
|
|
113
118
|
});
|
|
114
119
|
return {
|
|
120
|
+
...providerMetadata ? { providerMetadata } : {},
|
|
115
121
|
content: response.text ?? "",
|
|
116
122
|
finishReason,
|
|
117
123
|
usage,
|
|
@@ -122,10 +128,9 @@ var GoogleModel = class {
|
|
|
122
128
|
async countTokens(messages, options) {
|
|
123
129
|
const { systemInstruction, contents } = toGoogleContents(messages);
|
|
124
130
|
const config = this.buildConfig(systemInstruction, options);
|
|
125
|
-
if (
|
|
126
|
-
if (config.cachedContent !== void 0) throw new InvalidRequestError("The Google SDK countTokens endpoint cannot count a cachedContent reference.");
|
|
131
|
+
if (config.cachedContent !== void 0) throw new InvalidRequestError("The Google SDK countTokens endpoint cannot count a cachedContent reference.", { reason: "count-unsupported" });
|
|
127
132
|
try {
|
|
128
|
-
const response = await this.ai.models.countTokens({
|
|
133
|
+
const response = this.ai.vertexai ? await this.ai.models.countTokens({
|
|
129
134
|
model: this.name,
|
|
130
135
|
contents,
|
|
131
136
|
config: {
|
|
@@ -134,7 +139,7 @@ var GoogleModel = class {
|
|
|
134
139
|
...config.abortSignal ? { abortSignal: config.abortSignal } : {},
|
|
135
140
|
...config.httpOptions ? { httpOptions: config.httpOptions } : {}
|
|
136
141
|
}
|
|
137
|
-
});
|
|
142
|
+
}) : await this.countDeveloperTokens(contents, config);
|
|
138
143
|
if (response.totalTokens === void 0) throw new InvalidRequestError("Google countTokens returned no totalTokens.");
|
|
139
144
|
return response.totalTokens;
|
|
140
145
|
} catch (thrown) {
|
|
@@ -142,6 +147,42 @@ var GoogleModel = class {
|
|
|
142
147
|
}
|
|
143
148
|
}
|
|
144
149
|
/**
|
|
150
|
+
* REST counts the full generation request, unlike the typed Developer API
|
|
151
|
+
* converter in @google/genai 2.19.0. See https://ai.google.dev/api/tokens.
|
|
152
|
+
* extraBody keeps the SDK's auth, fetch, base URL, retries and cancellation.
|
|
153
|
+
*/
|
|
154
|
+
countDeveloperTokens(contents, config) {
|
|
155
|
+
config.abortSignal?.throwIfAborted();
|
|
156
|
+
const { systemInstruction, serviceTier, tools, toolConfig, safetySettings, cachedContent, abortSignal, httpOptions, ...generationConfig } = config;
|
|
157
|
+
delete generationConfig.automaticFunctionCalling;
|
|
158
|
+
const model = this.name.startsWith("models/") ? this.name : `models/${this.name}`;
|
|
159
|
+
return this.ai.models.countTokens({
|
|
160
|
+
model: this.name,
|
|
161
|
+
contents,
|
|
162
|
+
config: {
|
|
163
|
+
abortSignal,
|
|
164
|
+
httpOptions: {
|
|
165
|
+
...httpOptions,
|
|
166
|
+
extraBody: {
|
|
167
|
+
...httpOptions?.extraBody,
|
|
168
|
+
contents: void 0,
|
|
169
|
+
generateContentRequest: {
|
|
170
|
+
model,
|
|
171
|
+
contents,
|
|
172
|
+
...serviceTier !== void 0 ? { serviceTier } : {},
|
|
173
|
+
...systemInstruction !== void 0 ? { systemInstruction: { parts: [{ text: systemInstruction }] } } : {},
|
|
174
|
+
...tools !== void 0 ? { tools } : {},
|
|
175
|
+
...toolConfig !== void 0 ? { toolConfig } : {},
|
|
176
|
+
...safetySettings !== void 0 ? { safetySettings } : {},
|
|
177
|
+
...cachedContent !== void 0 ? { cachedContent } : {},
|
|
178
|
+
...Object.keys(generationConfig).length > 0 ? { generationConfig } : {}
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
}
|
|
183
|
+
});
|
|
184
|
+
}
|
|
185
|
+
/**
|
|
145
186
|
* Incremental streaming completion via `generateContentStream`.
|
|
146
187
|
* Yields neutral `ModelStreamChunk`s — `delta` for text, `tool-call`
|
|
147
188
|
* per function call (Gemini emits a fully-formed call, not partial
|
|
@@ -178,8 +219,10 @@ var GoogleModel = class {
|
|
|
178
219
|
total: 0
|
|
179
220
|
};
|
|
180
221
|
const want = resolveStreamChunks(options);
|
|
222
|
+
const grounding = /* @__PURE__ */ new Map();
|
|
181
223
|
try {
|
|
182
224
|
for await (const chunk of iterable) {
|
|
225
|
+
applyGrounding(usage, grounding, chunk);
|
|
183
226
|
if (want.reasoning) {
|
|
184
227
|
for (const part of chunk.candidates?.[0]?.content?.parts ?? []) if (part.thought === true && typeof part.text === "string" && part.text !== "") yield {
|
|
185
228
|
type: "reasoning",
|
|
@@ -222,10 +265,12 @@ var GoogleModel = class {
|
|
|
222
265
|
finishReason,
|
|
223
266
|
usage
|
|
224
267
|
});
|
|
268
|
+
const providerMetadata = groundingMetadata(grounding);
|
|
225
269
|
yield {
|
|
226
270
|
type: "done",
|
|
227
271
|
finishReason,
|
|
228
|
-
usage
|
|
272
|
+
usage,
|
|
273
|
+
...providerMetadata ? { providerMetadata } : {}
|
|
229
274
|
};
|
|
230
275
|
}
|
|
231
276
|
/**
|
package/esm/model.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
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;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;GACvB,KAAK,OAAO,OAAO;EACrB;CACF;;;;;;;CAQA,MAAa,SAAS,UAAqB,SAAoD;EAC7F,KAAK,OAAO,MAAM,YAAY,WAAW,iCAAiC;GACxE,OAAO,KAAK;GACZ,cAAc,SAAS;GACvB,WAAW;GACX,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,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"}
|
|
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 GroundingMetadata,\n Part,\n Tool,\n} from \"@google/genai\";\nimport { applyGrounding, groundingMetadata } from \"./utils/grounding\";\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 = this.extractUsage(response);\n const grounding = new Map<number, GroundingMetadata>();\n applyGrounding(usage, grounding, response);\n const providerMetadata = groundingMetadata(grounding);\n attachCost(usage, this.pricing);\n\n this.logger.debug(LOG_MODULE, \"response\", \"generateContent call succeeded\", {\n finishReason,\n usage,\n });\n\n return {\n ...(providerMetadata ? { providerMetadata } : {}),\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 (config.cachedContent !== undefined) {\n throw new InvalidRequestError(\n \"The Google SDK countTokens endpoint cannot count a cachedContent reference.\",\n { reason: \"count-unsupported\" },\n );\n }\n try {\n const response = this.ai.vertexai\n ? 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 : await this.countDeveloperTokens(contents, config);\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 * REST counts the full generation request, unlike the typed Developer API\n * converter in @google/genai 2.19.0. See https://ai.google.dev/api/tokens.\n * extraBody keeps the SDK's auth, fetch, base URL, retries and cancellation.\n */\n private countDeveloperTokens(\n contents: ReturnType<typeof toGoogleContents>[\"contents\"],\n config: GenerateContentConfig,\n ) {\n config.abortSignal?.throwIfAborted();\n\n const {\n systemInstruction,\n serviceTier,\n tools,\n toolConfig,\n safetySettings,\n cachedContent,\n abortSignal,\n httpOptions,\n ...generationConfig\n } = config;\n // Automatic function calling is SDK-only, never a REST generation field.\n delete generationConfig.automaticFunctionCalling;\n const model = this.name.startsWith(\"models/\") ? this.name : `models/${this.name}`;\n\n return this.ai.models.countTokens({\n model: this.name,\n contents,\n config: {\n abortSignal,\n httpOptions: {\n ...httpOptions,\n extraBody: {\n ...httpOptions?.extraBody,\n // The SDK merges extraBody before JSON serialization. undefined\n // removes its contents field: REST accepts only one input form.\n contents: undefined,\n generateContentRequest: {\n model,\n contents,\n ...(serviceTier !== undefined ? { serviceTier } : {}),\n ...(systemInstruction !== undefined\n ? { systemInstruction: { parts: [{ text: systemInstruction }] } }\n : {}),\n ...(tools !== undefined ? { tools } : {}),\n ...(toolConfig !== undefined ? { toolConfig } : {}),\n ...(safetySettings !== undefined ? { safetySettings } : {}),\n ...(cachedContent !== undefined ? { cachedContent } : {}),\n ...(Object.keys(generationConfig).length > 0 ? { generationConfig } : {}),\n },\n },\n },\n },\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 const grounding = new Map<number, GroundingMetadata>();\n\n try {\n for await (const chunk of iterable) {\n applyGrounding(usage, grounding, chunk);\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 const providerMetadata = groundingMetadata(grounding);\n yield { type: \"done\", finishReason, usage, ...(providerMetadata ? { providerMetadata } : {}) };\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":";;;;;;;;;;;;;AAqCA,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;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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tB,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"}
|
|
@@ -1,8 +1,8 @@
|
|
|
1
|
+
import "@warlock.js/ai";
|
|
1
2
|
//#region ../../packages/ai-google/src/provider-options.d.ts
|
|
2
3
|
/** Adapter-only fields merged after the neutral request parameters. */
|
|
3
|
-
type GoogleCallOptions = {
|
|
4
|
+
export type GoogleCallOptions = {
|
|
4
5
|
body?: Record<string, unknown>;
|
|
5
6
|
};
|
|
6
7
|
//#endregion
|
|
7
|
-
export { GoogleCallOptions };
|
|
8
8
|
//# sourceMappingURL=provider-options.d.mts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"provider-options.d.mts","names":[],"sources":["../../../../../../../packages/ai-google/src/provider-options.ts"],"mappings":"
|
|
1
|
+
{"version":3,"file":"provider-options.d.mts","names":[],"sources":["../../../../../../../packages/ai-google/src/provider-options.ts"],"mappings":";;;YAGY;EAAsB,OAAO"}
|
package/esm/provider-options.mjs
CHANGED
|
@@ -1 +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,
|
|
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,kCAAkB,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,6 +1,5 @@
|
|
|
1
1
|
import { GoogleEmbedderConfig, GoogleImageConfig, GoogleModelConfig, GoogleSDKConfig } from "./config.type.mjs";
|
|
2
2
|
import { EmbedderContract, ImageModelContract, ModelContract, SDKAdapterContract } from "@warlock.js/ai";
|
|
3
|
-
|
|
4
3
|
//#region ../../packages/ai-google/src/sdk.d.ts
|
|
5
4
|
/**
|
|
6
5
|
* Google Gemini-backed implementation of `SDKAdapterContract`.
|
|
@@ -26,7 +25,7 @@ import { EmbedderContract, ImageModelContract, ModelContract, SDKAdapterContract
|
|
|
26
25
|
* const model = google.model({ name: "gemini-2.5-flash", temperature: 0.7 });
|
|
27
26
|
* const embedder = google.embedder({ name: "gemini-embedding-001" });
|
|
28
27
|
*/
|
|
29
|
-
declare class GoogleSDK implements SDKAdapterContract {
|
|
28
|
+
export declare class GoogleSDK implements SDKAdapterContract {
|
|
30
29
|
private readonly ai;
|
|
31
30
|
private readonly provider;
|
|
32
31
|
private readonly pricing?;
|
|
@@ -83,5 +82,4 @@ declare class GoogleSDK implements SDKAdapterContract {
|
|
|
83
82
|
image(config: GoogleImageConfig): ImageModelContract;
|
|
84
83
|
}
|
|
85
84
|
//#endregion
|
|
86
|
-
export { GoogleSDK };
|
|
87
85
|
//# sourceMappingURL=sdk.d.mts.map
|
package/esm/sdk.d.mts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"sdk.d.mts","names":[],"sources":["../../../../../../../packages/ai-google/src/sdk.ts"],"mappings":"
|
|
1
|
+
{"version":3,"file":"sdk.d.mts","names":[],"sources":["../../../../../../../packages/ai-google/src/sdk.ts"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;qBA+Ea,qBAAqB;mBACf;mBACA;mBACA;EAEjB,YAAmB,QAAQ;;;;;;;;;;;EAkBpB,MAAM,QAAQ,oBAAoB;;;;;;;EAe5B,MAAM,cAAc,kBAAkB;;;;;;;;EAW5C,SAAS,QAAQ,uBAAuB;;;;;;;;;;;;;;;;;;;;;;;;EA2BxC,MAAM,QAAQ,oBAAoB"}
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
//#region ../../packages/ai-google/src/utils/grounding.ts
|
|
2
|
+
/** Candidate snapshots are replaced, not added: streamed metadata may repeat.
|
|
3
|
+
* Installed @google/genai 2.19.0 GroundingMetadata.webSearchQueries; REST schema:
|
|
4
|
+
* https://ai.google.dev/api/generate-content#GroundingMetadata
|
|
5
|
+
* Billing ignores empty queries and counts unique queries for Gemini 3+:
|
|
6
|
+
* https://ai.google.dev/gemini-api/docs/google-search#pricing
|
|
7
|
+
* Gemini 2.5 and older bill per grounded prompt; this counter is NOT that unit. */
|
|
8
|
+
function applyGrounding(usage, snapshots, response) {
|
|
9
|
+
for (const [position, candidate] of (response.candidates ?? []).entries()) if (candidate.groundingMetadata) snapshots.set(candidate.index ?? position, candidate.groundingMetadata);
|
|
10
|
+
const reported = [...snapshots.values()].filter((metadata) => metadata.webSearchQueries !== void 0);
|
|
11
|
+
if (reported.length > 0) {
|
|
12
|
+
const queries = reported.flatMap((metadata) => metadata.webSearchQueries ?? []);
|
|
13
|
+
usage.serverToolUse = {
|
|
14
|
+
...usage.serverToolUse,
|
|
15
|
+
webSearchRequests: new Set(queries.filter((query) => query !== "")).size,
|
|
16
|
+
googleWebSearchQueries: queries.length
|
|
17
|
+
};
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
/** Retain chunks, supports, search entry point and queries without flattening them. */
|
|
21
|
+
function groundingMetadata(snapshots) {
|
|
22
|
+
return snapshots.size ? { google: { groundingMetadata: [...snapshots].map(([index, metadata]) => ({
|
|
23
|
+
index,
|
|
24
|
+
...metadata
|
|
25
|
+
})) } } : void 0;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
//#endregion
|
|
29
|
+
export { applyGrounding, groundingMetadata };
|
|
30
|
+
//# sourceMappingURL=grounding.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"grounding.mjs","names":[],"sources":["../../../../../../../../packages/ai-google/src/utils/grounding.ts"],"sourcesContent":["import type { GenerateContentResponse, GroundingMetadata } from \"@google/genai\";\nimport type { Usage } from \"@warlock.js/ai\";\n\n/** Candidate snapshots are replaced, not added: streamed metadata may repeat.\n * Installed @google/genai 2.19.0 GroundingMetadata.webSearchQueries; REST schema:\n * https://ai.google.dev/api/generate-content#GroundingMetadata\n * Billing ignores empty queries and counts unique queries for Gemini 3+:\n * https://ai.google.dev/gemini-api/docs/google-search#pricing\n * Gemini 2.5 and older bill per grounded prompt; this counter is NOT that unit. */\nexport function applyGrounding(\n usage: Usage,\n snapshots: Map<number, GroundingMetadata>,\n response: GenerateContentResponse,\n): void {\n for (const [position, candidate] of (response.candidates ?? []).entries()) {\n if (candidate.groundingMetadata)\n snapshots.set(candidate.index ?? position, candidate.groundingMetadata);\n }\n const reported = [...snapshots.values()].filter(\n (metadata) => metadata.webSearchQueries !== undefined,\n );\n if (reported.length > 0) {\n const queries = reported.flatMap((metadata) => metadata.webSearchQueries ?? []);\n usage.serverToolUse = {\n ...usage.serverToolUse,\n webSearchRequests: new Set(queries.filter((query) => query !== \"\")).size,\n googleWebSearchQueries: queries.length,\n };\n }\n}\n\n/** Retain chunks, supports, search entry point and queries without flattening them. */\nexport function groundingMetadata(\n snapshots: Map<number, GroundingMetadata>,\n): Record<string, unknown> | undefined {\n return snapshots.size\n ? {\n google: {\n groundingMetadata: [...snapshots].map(([index, metadata]) => ({ index, ...metadata })),\n },\n }\n : undefined;\n}\n"],"mappings":";;;;;;;AASA,SAAgB,eACd,OACA,WACA,UACM;CACN,KAAK,MAAM,CAAC,UAAU,eAAe,SAAS,cAAc,CAAC,EAAC,CAAE,QAAQ,GACtE,IAAI,UAAU,mBACZ,UAAU,IAAI,UAAU,SAAS,UAAU,UAAU,iBAAiB;CAE1E,MAAM,WAAW,CAAC,GAAG,UAAU,OAAO,CAAC,CAAC,CAAC,QACtC,aAAa,SAAS,qBAAqB,MAC9C;CACA,IAAI,SAAS,SAAS,GAAG;EACvB,MAAM,UAAU,SAAS,SAAS,aAAa,SAAS,oBAAoB,CAAC,CAAC;EAC9E,MAAM,gBAAgB;GACpB,GAAG,MAAM;GACT,mBAAmB,IAAI,IAAI,QAAQ,QAAQ,UAAU,UAAU,EAAE,CAAC,CAAC,CAAC;GACpE,wBAAwB,QAAQ;EAClC;CACF;AACF;;AAGA,SAAgB,kBACd,WACqC;CACrC,OAAO,UAAU,OACb,EACE,QAAQ,EACN,mBAAmB,CAAC,GAAG,SAAS,CAAC,CAAC,KAAK,CAAC,OAAO,eAAe;EAAE;EAAO,GAAG;CAAS,EAAE,EACvF,EACF,IACA;AACN"}
|
package/esm/utils/index.mjs
CHANGED
|
@@ -4,4 +4,4 @@ import { toGoogleContents } from "./to-google-contents.mjs";
|
|
|
4
4
|
import { toGoogleTools } from "./to-google-tools.mjs";
|
|
5
5
|
import { wrapGoogleError } from "./wrap-google-error.mjs";
|
|
6
6
|
|
|
7
|
-
export {
|
|
7
|
+
export { applyGoogleUsage, mapFinishReason, toGoogleContents, toGoogleTools, wrapGoogleError };
|