@langchain/google 0.1.11 → 0.2.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.
Files changed (40) hide show
  1. package/CHANGELOG.md +20 -0
  2. package/dist/chat_models/api-types.d.cts +257 -102
  3. package/dist/chat_models/api-types.d.ts +257 -102
  4. package/dist/chat_models/base.cjs +76 -9
  5. package/dist/chat_models/base.cjs.map +1 -1
  6. package/dist/chat_models/base.d.cts +5 -0
  7. package/dist/chat_models/base.d.ts +5 -0
  8. package/dist/chat_models/base.js +77 -10
  9. package/dist/chat_models/base.js.map +1 -1
  10. package/dist/chat_models/node.cjs.map +1 -1
  11. package/dist/chat_models/node.js.map +1 -1
  12. package/dist/chat_models/types.cjs +6 -0
  13. package/dist/chat_models/types.cjs.map +1 -0
  14. package/dist/chat_models/types.d.cts +13 -0
  15. package/dist/chat_models/types.d.ts +13 -0
  16. package/dist/chat_models/types.js +6 -0
  17. package/dist/chat_models/types.js.map +1 -0
  18. package/dist/clients/node.cjs.map +1 -1
  19. package/dist/clients/node.js.map +1 -1
  20. package/dist/converters/messages.cjs +12 -0
  21. package/dist/converters/messages.cjs.map +1 -1
  22. package/dist/converters/messages.js +12 -0
  23. package/dist/converters/messages.js.map +1 -1
  24. package/dist/converters/params.cjs +12 -0
  25. package/dist/converters/params.cjs.map +1 -1
  26. package/dist/converters/params.js +12 -1
  27. package/dist/converters/params.js.map +1 -1
  28. package/dist/converters/tools.cjs.map +1 -1
  29. package/dist/converters/tools.js.map +1 -1
  30. package/dist/utils/gcp-auth.cjs.map +1 -1
  31. package/dist/utils/gcp-auth.js.map +1 -1
  32. package/dist/utils/stream_events.cjs +173 -0
  33. package/dist/utils/stream_events.cjs.map +1 -0
  34. package/dist/utils/stream_events.js +173 -0
  35. package/dist/utils/stream_events.js.map +1 -0
  36. package/node.cjs +1 -0
  37. package/node.d.cts +1 -0
  38. package/node.d.ts +1 -0
  39. package/node.js +1 -0
  40. package/package.json +13 -8
@@ -1,9 +1,12 @@
1
+ import { iife } from "../utils/misc.js";
1
2
  import { ConfigurationError, MalformedOutputError, NoCandidatesError, PromptBlockedError, RequestError } from "../utils/errors.js";
3
+ import { convertGoogleGeminiStream } from "../utils/stream_events.js";
2
4
  import PROFILES from "./profiles.js";
5
+ import { settableServiceTier } from "./types.js";
3
6
  import { SafeJsonEventParserStream } from "../utils/stream.js";
4
7
  import { convertAIMessageToText, convertGeminiCandidateToAIMessage, convertGeminiGenerateContentResponseToUsageMetadata, convertGeminiPartsToToolCalls, convertMessagesToGeminiContents, convertMessagesToGeminiSystemInstruction } from "../converters/messages.js";
5
8
  import { convertToolChoiceToGeminiConfig, convertToolsToGeminiTools, schemaToGeminiParameters } from "../converters/tools.js";
6
- import { convertFieldsToSpeechConfig, convertFieldsToThinkingConfig, convertParamsToPlatformType } from "../converters/params.js";
9
+ import { convertFieldsToServiceTier, convertFieldsToSpeechConfig, convertFieldsToThinkingConfig, convertParamsToPlatformType } from "../converters/params.js";
7
10
  import { subtractUsageMetadata } from "../utils/metadata.js";
8
11
  import { BaseChatModel } from "@langchain/core/language_models/chat_models";
9
12
  import { AIMessage, AIMessageChunk } from "@langchain/core/messages";
@@ -21,6 +24,13 @@ function getPlatformType(platform, hasApiKey) {
21
24
  else if (hasApiKey) return "gai";
22
25
  else return "gcp";
23
26
  }
27
+ function usageMetadataToTokenUsage(usageMetadata) {
28
+ return {
29
+ promptTokens: usageMetadata.input_tokens,
30
+ completionTokens: usageMetadata.output_tokens,
31
+ totalTokens: usageMetadata.total_tokens
32
+ };
33
+ }
24
34
  function mapDetailToMediaResolution(detail) {
25
35
  switch (detail) {
26
36
  case "low": return "MEDIA_RESOLUTION_LOW";
@@ -35,18 +45,20 @@ var BaseChatGoogle = class extends BaseChatModel {
35
45
  streamUsage = true;
36
46
  _platform;
37
47
  _endpoint;
48
+ _customHeaders;
38
49
  _location;
39
50
  _apiVersion;
40
51
  apiClient;
41
52
  constructor(params) {
42
53
  super(params);
43
54
  this.params = params;
44
- this._addVersion("@langchain/google", "0.1.11");
55
+ this._addVersion("@langchain/google", "0.2.0");
45
56
  if (!params.apiClient) throw new ConfigurationError("BaseChatGoogle requires an apiClient. This should be provided automatically by ChatGoogle constructors. If you're extending BaseChatGoogle directly, please provide an apiClient instance.");
46
57
  this.apiClient = params.apiClient;
47
58
  this.model = params.model;
48
59
  this._platform = convertParamsToPlatformType(params);
49
60
  this._endpoint = params.endpoint;
61
+ this._customHeaders = params.customHeaders;
50
62
  this._location = params.location;
51
63
  this._apiVersion = params.apiVersion;
52
64
  this.disableStreaming = params?.disableStreaming === true;
@@ -161,7 +173,8 @@ var BaseChatGoogle = class extends BaseChatModel {
161
173
  speechConfig: convertFieldsToSpeechConfig(fields),
162
174
  ...fields.imageConfig ? { imageConfig: fields.imageConfig } : {},
163
175
  ...mediaResolution ? { mediaResolution } : {}
164
- }
176
+ },
177
+ ...convertFieldsToServiceTier(this.platform, fields)
165
178
  };
166
179
  }
167
180
  getLsParams(options) {
@@ -175,6 +188,15 @@ var BaseChatGoogle = class extends BaseChatModel {
175
188
  ls_stop: options.stop
176
189
  };
177
190
  }
191
+ getHeaders(options) {
192
+ const fields = combineGoogleChatModelFields(this.params, options);
193
+ return {
194
+ "Content-Type": "application/json",
195
+ ...this.platform === "gcp" && typeof fields.serviceTier !== "undefined" && settableServiceTier.includes(fields.serviceTier) ? { "X-Vertex-AI-LLM-Shared-Request-Type": fields.serviceTier } : {},
196
+ ...this._customHeaders,
197
+ ...options.customHeaders
198
+ };
199
+ }
178
200
  async _generate(messages, options, runManager) {
179
201
  if (this.streaming) {
180
202
  const stream = await this._streamResponseChunks(messages, options, runManager);
@@ -184,6 +206,7 @@ var BaseChatGoogle = class extends BaseChatModel {
184
206
  return { generations: finalChunk ? [finalChunk] : [] };
185
207
  }
186
208
  const url = await this.buildUrl();
209
+ const headers = this.getHeaders(options);
187
210
  const body = {
188
211
  ...this.invocationParams(options),
189
212
  systemInstruction: convertMessagesToGeminiSystemInstruction(messages),
@@ -192,11 +215,12 @@ var BaseChatGoogle = class extends BaseChatModel {
192
215
  const moduleName = this.constructor.name;
193
216
  await runManager?.handleCustomEvent(`google-request-${moduleName}`, {
194
217
  url,
218
+ headers,
195
219
  body
196
220
  });
197
221
  const response = await this.apiClient.fetch(new Request(url, {
198
222
  method: "POST",
199
- headers: { "Content-Type": "application/json" },
223
+ headers,
200
224
  body: JSON.stringify(body),
201
225
  signal: options.signal
202
226
  }));
@@ -209,7 +233,7 @@ var BaseChatGoogle = class extends BaseChatModel {
209
233
  await runManager?.handleCustomEvent(`google-response-${moduleName}`, {
210
234
  data,
211
235
  url: response.url,
212
- headers: response.headers,
236
+ headers: Array.from(response.headers.entries()),
213
237
  status: response.status,
214
238
  statusText: response.statusText
215
239
  });
@@ -220,6 +244,12 @@ var BaseChatGoogle = class extends BaseChatModel {
220
244
  const text = convertAIMessageToText(message);
221
245
  const usageMetadata = convertGeminiGenerateContentResponseToUsageMetadata(data);
222
246
  message.usage_metadata = usageMetadata;
247
+ const serviceTier = iife(() => {
248
+ const trafficType = data.usageMetadata?.trafficType;
249
+ const serviceTierHeader = response.headers.get("x-gemini-service-tier");
250
+ if (trafficType?.startsWith("ON_DEMAND_")) return trafficType?.substring(10).toLowerCase();
251
+ return serviceTierHeader || "standard";
252
+ });
223
253
  return {
224
254
  generations: [{
225
255
  text,
@@ -233,13 +263,47 @@ var BaseChatGoogle = class extends BaseChatModel {
233
263
  }
234
264
  }],
235
265
  llmOutput: {
236
- tokenUsage: usageMetadata,
266
+ tokenUsage: usageMetadataToTokenUsage(usageMetadata),
237
267
  model: data.modelVersion,
238
268
  responseId: data.responseId,
239
- usageMetadata
269
+ usageMetadata,
270
+ serviceTier
240
271
  }
241
272
  };
242
273
  }
274
+ async *_streamChatModelEvents(messages, options, _runManager) {
275
+ const body = {
276
+ ...this.invocationParams(options),
277
+ systemInstruction: convertMessagesToGeminiSystemInstruction(messages),
278
+ contents: convertMessagesToGeminiContents(messages)
279
+ };
280
+ const url = await this.buildUrl("streamGenerateContent?alt=sse");
281
+ const headers = this.getHeaders(options);
282
+ const response = await this.apiClient.fetch(new Request(url, {
283
+ method: "POST",
284
+ headers,
285
+ body: JSON.stringify(body),
286
+ signal: options.signal
287
+ }));
288
+ if (!response.ok) throw await RequestError.fromResponse(response);
289
+ if (!response.body) return;
290
+ const eventStream = response.body.pipeThrough(new TextDecoderStream()).pipeThrough(new EventSourceParserStream()).pipeThrough(new SafeJsonEventParserStream());
291
+ const shouldStreamUsage = this.streamUsage !== false && options.streamUsage !== false;
292
+ async function* geminiChunks(stream, signal) {
293
+ const reader = stream.getReader();
294
+ try {
295
+ while (true) {
296
+ if (signal?.aborted) return;
297
+ const { done, value } = await reader.read();
298
+ if (done) break;
299
+ if (value !== null) yield value;
300
+ }
301
+ } finally {
302
+ reader.releaseLock();
303
+ }
304
+ }
305
+ yield* convertGoogleGeminiStream(geminiChunks(eventStream, options.signal), { streamUsage: shouldStreamUsage });
306
+ }
243
307
  async *_streamResponseChunks(messages, options, runManager) {
244
308
  const streamUsage = this.streamUsage ?? true;
245
309
  const body = {
@@ -248,20 +312,22 @@ var BaseChatGoogle = class extends BaseChatModel {
248
312
  contents: convertMessagesToGeminiContents(messages)
249
313
  };
250
314
  const url = await this.buildUrl("streamGenerateContent?alt=sse");
315
+ const headers = this.getHeaders(options);
251
316
  const moduleName = this.constructor.name;
252
317
  await runManager?.handleCustomEvent(`google-request-${moduleName}`, {
253
318
  url,
319
+ headers,
254
320
  body
255
321
  });
256
322
  const response = await this.apiClient.fetch(new Request(url, {
257
323
  method: "POST",
258
- headers: { "Content-Type": "application/json" },
324
+ headers,
259
325
  body: JSON.stringify(body),
260
326
  signal: options.signal
261
327
  }));
262
328
  await runManager?.handleCustomEvent(`google-response-${moduleName}`, {
263
329
  url: response.url,
264
- headers: response.headers,
330
+ headers: Array.from(response.headers.entries()),
265
331
  status: response.status,
266
332
  statusText: response.statusText
267
333
  });
@@ -428,7 +494,8 @@ function combineGoogleChatModelFields(a, b, ...rest) {
428
494
  maxReasoningTokens: b.maxReasoningTokens ?? a.maxReasoningTokens,
429
495
  thinkingBudget: b.thinkingBudget ?? a.thinkingBudget,
430
496
  reasoningEffort: b.reasoningEffort ?? a.reasoningEffort,
431
- thinkingLevel: b.thinkingLevel ?? a.thinkingLevel
497
+ thinkingLevel: b.thinkingLevel ?? a.thinkingLevel,
498
+ serviceTier: b.serviceTier ?? a.serviceTier
432
499
  };
433
500
  if (rest.length > 0) return combineGoogleChatModelFields(combined, rest[0], ...rest.slice(1));
434
501
  return combined;
@@ -1 +1 @@
1
- {"version":3,"file":"base.js","names":[],"sources":["../../src/chat_models/base.ts"],"sourcesContent":["import {\n BaseChatModel,\n type BaseChatModelCallOptions,\n type LangSmithParams,\n type BaseChatModelParams,\n} from \"@langchain/core/language_models/chat_models\";\nimport {\n AIMessage,\n AIMessageChunk,\n AIMessageChunkFields,\n BaseMessage,\n type UsageMetadata,\n} from \"@langchain/core/messages\";\nimport { CallbackManagerForLLMRun } from \"@langchain/core/callbacks/manager\";\nimport { concat } from \"@langchain/core/utils/stream\";\nimport { ChatGenerationChunk, ChatResult } from \"@langchain/core/outputs\";\nimport { EventSourceParserStream } from \"eventsource-parser/stream\";\nimport type { BindToolsInput } from \"@langchain/core/language_models/chat_models\";\nimport type { ModelProfile } from \"@langchain/core/language_models/profile\";\nimport PROFILES from \"./profiles.js\";\nimport type {\n BaseLanguageModelInput,\n StructuredOutputMethodOptions,\n} from \"@langchain/core/language_models/base\";\nimport { Runnable, RunnableLambda } from \"@langchain/core/runnables\";\nimport {\n toJsonSchema,\n type JsonSchema7Type,\n} from \"@langchain/core/utils/json_schema\";\nimport {\n InteropZodType,\n isInteropZodSchema,\n} from \"@langchain/core/utils/types\";\n\nimport { ApiClient } from \"../clients/index.js\";\nimport type { ChatGoogleFields } from \"./types.js\";\nimport { SafeJsonEventParserStream } from \"../utils/stream.js\";\nimport {\n convertAIMessageToText,\n convertGeminiCandidateToAIMessage,\n convertGeminiGenerateContentResponseToUsageMetadata,\n convertGeminiPartsToToolCalls,\n convertMessagesToGeminiContents,\n convertMessagesToGeminiSystemInstruction,\n} from \"../converters/messages.js\";\nimport {\n ConfigurationError,\n MalformedOutputError,\n NoCandidatesError,\n PromptBlockedError,\n RequestError,\n} from \"../utils/errors.js\";\nimport {\n convertToolsToGeminiTools,\n convertToolChoiceToGeminiConfig,\n schemaToGeminiParameters,\n} from \"../converters/tools.js\";\nimport {\n convertParamsToPlatformType,\n convertFieldsToSpeechConfig,\n convertFieldsToThinkingConfig,\n} from \"../converters/params.js\";\nimport { Gemini } from \"./api-types.js\";\nimport { subtractUsageMetadata } from \"../utils/metadata.js\";\nimport {\n isSerializableSchema,\n SerializableSchema,\n} from \"@langchain/core/utils/standard_schema\";\nimport {\n assembleStructuredOutputPipeline,\n createContentParser,\n createFunctionCallingParser,\n} from \"@langchain/core/language_models/structured_output\";\n\nexport type GooglePlatformType = \"gai\" | \"gcp\";\n\nexport function getPlatformType(\n platform: GooglePlatformType | undefined,\n hasApiKey: boolean\n): GooglePlatformType {\n if (typeof platform !== \"undefined\") {\n return platform;\n } else if (hasApiKey) {\n return \"gai\";\n } else {\n return \"gcp\";\n }\n}\n\nfunction mapDetailToMediaResolution(\n detail?: ChatGoogleFields[\"detail\"]\n): Gemini.GenerationConfig[\"mediaResolution\"] | undefined {\n switch (detail) {\n case \"low\":\n return \"MEDIA_RESOLUTION_LOW\";\n case \"high\":\n return \"MEDIA_RESOLUTION_HIGH\";\n default:\n return undefined;\n }\n}\n\nexport interface BaseChatGoogleParams\n extends BaseChatModelParams, ChatGoogleFields {\n /**\n * The name of the Gemini model to use.\n *\n * Example: \"gemini-3-pro-preview\"\n */\n model: string;\n\n /**\n * Optional. The API client implementation for making HTTP requests to the Gemini API.\n * If not set, a default client will be used based on the runtime environment.\n */\n apiClient?: ApiClient;\n\n /**\n * Hostname for the API call (if this is running on GCP)\n * Usually this is computed based on location and platformType.\n **/\n endpoint?: string;\n\n /**\n * Region where the LLM is stored (if this is running on GCP)\n * Defaults to \"global\"\n **/\n location?: string;\n\n /**\n * The version of the API functions. Part of the path.\n * Usually this is computed based on platformType.\n **/\n apiVersion?: string;\n\n /**\n * What platform to run the service on.\n * If not specified, the class should determine this from other\n * means. Either way, the platform actually used will be in\n * the \"platform\" getter.\n */\n platformType?: GooglePlatformType;\n\n /**\n * For compatibility with Google's libraries, should this use Vertex?\n * The \"platformType\" parmeter takes precedence.\n */\n vertexai?: boolean;\n\n /**\n * Backwards compatibility.\n * @deprecated in favor of using `disableStreaming` or `.stream()`\n */\n streaming?: boolean;\n\n streamUsage?: boolean;\n}\n\nexport interface BaseChatGoogleCallOptions\n extends BaseChatModelCallOptions, ChatGoogleFields {}\n\nexport abstract class BaseChatGoogle<\n CallOptions extends BaseChatGoogleCallOptions = BaseChatGoogleCallOptions,\n> extends BaseChatModel<CallOptions, AIMessageChunk> {\n model: string;\n\n streaming: boolean;\n\n disableStreaming: boolean;\n\n streamUsage: boolean = true;\n\n protected _platform?: GooglePlatformType;\n\n protected _endpoint?: string;\n\n protected _location?: string;\n\n protected _apiVersion?: string;\n\n protected apiClient: ApiClient;\n\n constructor(protected params: BaseChatGoogleParams) {\n super(params);\n this._addVersion(\"@langchain/google\", __PKG_VERSION__);\n\n if (!params.apiClient) {\n throw new ConfigurationError(\n \"BaseChatGoogle requires an apiClient. This should be provided automatically by ChatGoogle constructors. If you're extending BaseChatGoogle directly, please provide an apiClient instance.\"\n );\n }\n this.apiClient = params.apiClient;\n\n this.model = params.model;\n this._platform = convertParamsToPlatformType(params);\n this._endpoint = params.endpoint;\n this._location = params.location;\n this._apiVersion = params.apiVersion;\n\n this.disableStreaming = params?.disableStreaming === true;\n this.streaming = params?.streaming === true;\n if (this.disableStreaming) this.streaming = false;\n // disable streaming in BaseChatModel if explicitly disabled\n if (params?.streaming === false) this.disableStreaming = true;\n\n this.streamUsage = params?.streamUsage ?? this.streamUsage;\n if (this.disableStreaming) this.streamUsage = false;\n }\n\n _llmType(): string {\n return \"google\";\n }\n\n protected get platformType(): GooglePlatformType | undefined {\n return this._platform;\n }\n\n protected get platform(): GooglePlatformType {\n return getPlatformType(this._platform, this.apiClient.hasApiKey());\n }\n\n protected get isVertexExpress(): boolean {\n return this.platform === \"gcp\" && this.apiClient.hasApiKey();\n }\n\n protected get apiVersion(): string {\n if (typeof this._apiVersion !== \"undefined\") {\n return this._apiVersion;\n } else if (this.platform === \"gai\") {\n return \"v1beta\";\n } else {\n return \"v1\";\n }\n }\n\n protected get location(): string {\n return this._location || \"global\";\n }\n\n protected get endpoint(): string {\n if (typeof this._endpoint !== \"undefined\") {\n return this._endpoint;\n } else if (this.platform === \"gai\") {\n return \"generativelanguage.googleapis.com\";\n } else if (this.isVertexExpress) {\n return \"aiplatform.googleapis.com\";\n } else if (this.location === \"global\") {\n // See https://docs.cloud.google.com/vertex-ai/generative-ai/docs/learn/locations#use_the_global_endpoint\n return \"aiplatform.googleapis.com\";\n } else {\n return `${this.location}-aiplatform.googleapis.com`;\n }\n }\n\n protected get publisher(): string {\n return \"google\";\n }\n\n protected get urlMethod(): string {\n return this.streaming ? \"streamGenerateContent?alt=sse\" : \"generateContent\";\n }\n\n /**\n * Returns the model profile for this instance's model, describing its\n * capabilities and constraints (e.g. max tokens, input/output modalities,\n * tool calling support).\n *\n * @example\n * ```typescript\n * const model = new ChatGoogle({ model: \"gemini-2.5-pro\" });\n * const profile = model.profile;\n * console.log(profile.maxInputTokens); // 1048576\n * console.log(profile.imageInputs); // true\n * ```\n */\n get profile(): ModelProfile {\n return PROFILES[this.model] ?? {};\n }\n\n protected async buildUrlGemini(urlMethod?: string): Promise<string> {\n return `https://${this.endpoint}/${this.apiVersion}/models/${this.model}:${\n urlMethod ?? this.urlMethod\n }`;\n }\n\n protected async buildUrlVertexExpress(urlMethod?: string): Promise<string> {\n return `https://${this.endpoint}/${this.apiVersion}/publishers/${\n this.publisher\n }/models/${this.model}:${urlMethod ?? this.urlMethod}`;\n }\n\n protected async buildUrlVertexLocation(urlMethod?: string): Promise<string> {\n const projectId = await this.apiClient.getProjectId();\n return `https://${this.endpoint}/${\n this.apiVersion\n }/projects/${projectId}/locations/${this.location}/publishers/${\n this.publisher\n }/models/${this.model}:${urlMethod ?? this.urlMethod}`;\n }\n\n protected async buildUrlVertex(urlMethod?: string): Promise<string> {\n if (this.isVertexExpress) {\n return this.buildUrlVertexExpress(urlMethod);\n } else {\n return this.buildUrlVertexLocation(urlMethod);\n }\n }\n\n protected async buildUrl(urlMethod?: string): Promise<string> {\n switch (this.platform) {\n case \"gai\":\n return this.buildUrlGemini(urlMethod);\n default:\n return this.buildUrlVertex(urlMethod);\n }\n }\n\n override invocationParams(options: this[\"ParsedCallOptions\"]) {\n const fields = combineGoogleChatModelFields(this.params, options);\n const mediaResolution =\n fields.mediaResolution ?? mapDetailToMediaResolution(fields.detail);\n\n // Convert tools to Gemini format\n const tools = fields.tools\n ? convertToolsToGeminiTools(fields.tools)\n : undefined;\n\n // Convert tool choice to Gemini function calling config\n const toolConfig = convertToolChoiceToGeminiConfig(\n options.tool_choice,\n !!(tools && tools.length > 0)\n );\n\n let responseJsonSchema:\n | JsonSchema7Type\n | Record<string, unknown>\n | undefined;\n let responseMimeType: string | undefined;\n\n if (fields.responseSchema) {\n // Convert Zod schema to JSON Schema if needed\n if (\n isInteropZodSchema(fields.responseSchema) ||\n isSerializableSchema(fields.responseSchema)\n ) {\n responseJsonSchema = toJsonSchema(fields.responseSchema);\n } else {\n responseJsonSchema = fields.responseSchema as Record<string, unknown>;\n }\n // Automatically set responseMimeType to \"application/json\" when schema is provided\n responseMimeType = \"application/json\";\n }\n\n return {\n ...(tools && tools.length > 0 ? { tools } : {}),\n ...(toolConfig ? { toolConfig } : {}),\n safetySettings: fields.safetySettings,\n generationConfig: {\n temperature: fields.temperature,\n topP: fields.topP,\n topK: fields.topK,\n maxOutputTokens: fields.maxOutputTokens,\n presencePenalty: fields.presencePenalty,\n frequencyPenalty: fields.frequencyPenalty,\n stopSequences: fields.stopSequences,\n ...(responseMimeType ? { responseMimeType } : {}),\n ...(responseJsonSchema ? { responseJsonSchema } : {}),\n ...(fields.responseModalities && fields.responseModalities.length > 0\n ? { responseModalities: fields.responseModalities }\n : {}),\n candidateCount: 1,\n seed: fields.seed,\n responseLogprobs: fields.responseLogprobs,\n logprobs: fields.logprobs,\n ...(fields.enableEnhancedCivicAnswers !== undefined\n ? { enableEnhancedCivicAnswers: fields.enableEnhancedCivicAnswers }\n : {}),\n thinkingConfig: convertFieldsToThinkingConfig(this.model, fields),\n speechConfig: convertFieldsToSpeechConfig(fields),\n ...(fields.imageConfig ? { imageConfig: fields.imageConfig } : {}),\n ...(mediaResolution ? { mediaResolution } : {}),\n },\n };\n }\n\n getLsParams(options: this[\"ParsedCallOptions\"]): LangSmithParams {\n const params = this.invocationParams(options);\n return {\n ls_provider: this.platform === \"gcp\" ? \"google_vertexai\" : \"google_genai\",\n ls_model_name: this.model,\n ls_model_type: \"chat\",\n ls_temperature: params.generationConfig?.temperature ?? undefined,\n ls_max_tokens: params.generationConfig?.maxOutputTokens ?? undefined,\n ls_stop: options.stop,\n };\n }\n\n async _generate(\n messages: BaseMessage[],\n options: this[\"ParsedCallOptions\"],\n runManager?: CallbackManagerForLLMRun\n ): Promise<ChatResult> {\n if (this.streaming) {\n const stream = await this._streamResponseChunks(\n messages,\n options,\n runManager\n );\n let finalChunk: ChatGenerationChunk | null = null;\n for await (const chunk of stream) {\n finalChunk = !finalChunk ? chunk : concat(finalChunk, chunk);\n }\n if (\n typeof finalChunk?.message?.content === \"string\" &&\n typeof (\n finalChunk?.message?.additional_kwargs\n ?.originalTextContentBlock as Record<string, unknown>\n )?.text === \"string\"\n ) {\n (\n finalChunk.message.additional_kwargs\n .originalTextContentBlock as Record<string, unknown>\n ).text = finalChunk.message.content;\n }\n return {\n generations: finalChunk ? [finalChunk] : [],\n };\n }\n\n const url = await this.buildUrl();\n const body = {\n ...this.invocationParams(options),\n systemInstruction: convertMessagesToGeminiSystemInstruction(messages),\n contents: convertMessagesToGeminiContents(messages),\n };\n\n const moduleName = this.constructor.name;\n await runManager?.handleCustomEvent(`google-request-${moduleName}`, {\n url,\n body,\n });\n\n const response = await this.apiClient.fetch(\n new Request(url, {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify(body),\n signal: options.signal,\n })\n );\n\n if (!response.ok) {\n const error = await RequestError.fromResponse(response);\n await runManager?.handleCustomEvent(`google-response-${moduleName}`, {\n error,\n });\n throw error;\n }\n\n const data: Gemini.GenerateContentResponse = await response.json();\n await runManager?.handleCustomEvent(`google-response-${moduleName}`, {\n data,\n url: response.url,\n headers: response.headers,\n status: response.status,\n statusText: response.statusText,\n });\n\n // Check for prompt feedback errors\n if (data.promptFeedback?.blockReason) {\n throw PromptBlockedError.fromPromptFeedback(data.promptFeedback);\n }\n\n // Check if we have candidates\n if (!data.candidates || data.candidates.length === 0) {\n throw new NoCandidatesError();\n }\n\n // Use the first candidate\n const candidate = data.candidates[0];\n const message = convertGeminiCandidateToAIMessage(candidate);\n\n // Extract text content from the message\n const text = convertAIMessageToText(message);\n\n const usageMetadata =\n convertGeminiGenerateContentResponseToUsageMetadata(data);\n message.usage_metadata = usageMetadata;\n\n return {\n generations: [\n {\n text,\n message,\n generationInfo: {\n finishReason: candidate.finishReason,\n finishMessage: candidate.finishMessage,\n safetyRatings: candidate.safetyRatings,\n citationMetadata: candidate.citationMetadata,\n tokenCount: candidate.tokenCount,\n },\n },\n ],\n llmOutput: {\n tokenUsage: usageMetadata,\n model: data.modelVersion,\n responseId: data.responseId,\n usageMetadata,\n },\n };\n }\n\n async *_streamResponseChunks(\n messages: BaseMessage[],\n options: this[\"ParsedCallOptions\"],\n runManager?: CallbackManagerForLLMRun\n ): AsyncGenerator<ChatGenerationChunk> {\n const streamUsage: boolean = this.streamUsage ?? true;\n\n const body = {\n ...this.invocationParams(options),\n systemInstruction: convertMessagesToGeminiSystemInstruction(messages),\n contents: convertMessagesToGeminiContents(messages),\n };\n\n const url = await this.buildUrl(\"streamGenerateContent?alt=sse\");\n const moduleName = this.constructor.name;\n await runManager?.handleCustomEvent(`google-request-${moduleName}`, {\n url,\n body,\n });\n\n const response = await this.apiClient.fetch(\n new Request(url, {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify(body),\n signal: options.signal,\n })\n );\n\n await runManager?.handleCustomEvent(`google-response-${moduleName}`, {\n url: response.url,\n headers: response.headers,\n status: response.status,\n statusText: response.statusText,\n });\n\n if (!response.ok) {\n const error = await RequestError.fromResponse(response);\n await runManager?.handleCustomEvent(`google-response-${moduleName}`, {\n error,\n });\n throw error;\n }\n\n if (response.body) {\n let previousUsage: UsageMetadata | undefined;\n const stream = response.body\n .pipeThrough(new TextDecoderStream())\n .pipeThrough(new EventSourceParserStream())\n .pipeThrough(\n new SafeJsonEventParserStream<Gemini.GenerateContentResponse>()\n )\n .pipeThrough(\n new TransformStream<\n Gemini.GenerateContentResponse,\n ChatGenerationChunk\n >({\n transform(chunk, controller) {\n // oxlint-disable-next-line no-void\n void runManager?.handleCustomEvent(`google-chunk-${moduleName}`, {\n chunk,\n });\n if (chunk === null) {\n controller.enqueue(\n new ChatGenerationChunk({\n text: \"\",\n message: new AIMessageChunk({ content: \"\" }),\n generationInfo: { finishReason: \"stop\" },\n })\n );\n return;\n }\n\n // Extract text delta from the chunk\n const candidate = chunk.candidates?.[0];\n if (!candidate) {\n return;\n }\n\n const message = convertGeminiCandidateToAIMessage(candidate);\n const text = convertAIMessageToText(message);\n\n const parts = candidate.content?.parts ?? [];\n const toolCalls = convertGeminiPartsToToolCalls(parts);\n\n // Only emit if we have content\n if (parts.length > 0 || candidate.finishReason) {\n const messageChunkParams: AIMessageChunkFields = {\n content: message.content,\n tool_calls: toolCalls,\n response_metadata: {\n model_provider: \"google\",\n },\n additional_kwargs: {\n ...(message.additional_kwargs.originalTextContentBlock\n ? {\n originalTextContentBlock:\n message.additional_kwargs.originalTextContentBlock,\n }\n : {}),\n ...(candidate.finishReason\n ? {\n finishReason: candidate.finishReason,\n finishMessage: candidate.finishMessage,\n }\n : {}),\n },\n };\n\n if (chunk?.usageMetadata && streamUsage) {\n const cumulative =\n convertGeminiGenerateContentResponseToUsageMetadata(chunk);\n messageChunkParams.usage_metadata = subtractUsageMetadata(\n cumulative,\n previousUsage\n );\n previousUsage = cumulative;\n }\n const messageChunk = new AIMessageChunk(messageChunkParams);\n\n controller.enqueue(\n new ChatGenerationChunk({\n text: text,\n message: messageChunk,\n generationInfo: {\n ...(candidate.finishReason && {\n finishReason: candidate.finishReason,\n finishMessage: candidate.finishMessage,\n }),\n ...(candidate.safetyRatings && {\n safetyRatings: candidate.safetyRatings,\n }),\n },\n })\n );\n }\n },\n })\n );\n\n const reader = stream.getReader();\n try {\n while (true) {\n const { done, value } = await reader.read();\n if (done) break;\n yield value;\n await runManager?.handleLLMNewToken(\n value.text ?? \"\",\n undefined,\n undefined,\n undefined,\n undefined,\n { chunk: value }\n );\n }\n } finally {\n reader.releaseLock();\n }\n }\n }\n\n /**\n * Bind tool-like objects to this chat model.\n *\n * @param tools A list of tool definitions to bind to this chat model.\n * Can be a structured tool, an OpenAI formatted tool, or a Gemini function declaration.\n * @param kwargs Any additional parameters to bind.\n */\n bindTools(\n tools: BindToolsInput[],\n kwargs?: Partial<CallOptions>\n ): Runnable<BaseMessage[], AIMessageChunk, CallOptions> {\n return this.withConfig({\n ...kwargs,\n tools,\n } as Partial<CallOptions>);\n }\n\n withStructuredOutput<\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n RunOutput extends Record<string, any> = Record<string, any>,\n >(\n outputSchema:\n | InteropZodType<RunOutput>\n | SerializableSchema<RunOutput>\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n | Record<string, any>,\n config?: StructuredOutputMethodOptions<false>\n ): Runnable<BaseLanguageModelInput, RunOutput>;\n\n withStructuredOutput<\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n RunOutput extends Record<string, any> = Record<string, any>,\n >(\n outputSchema:\n | InteropZodType<RunOutput>\n | SerializableSchema<RunOutput>\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n | Record<string, any>,\n config?: StructuredOutputMethodOptions<true>\n ): Runnable<BaseLanguageModelInput, { raw: BaseMessage; parsed: RunOutput }>;\n\n withStructuredOutput<\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n RunOutput extends Record<string, any> = Record<string, any>,\n >(\n outputSchema:\n | InteropZodType<RunOutput>\n | SerializableSchema<RunOutput>\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n | Record<string, any>,\n config?: StructuredOutputMethodOptions<boolean>\n ):\n | Runnable<BaseLanguageModelInput, RunOutput>\n | Runnable<BaseLanguageModelInput, { raw: BaseMessage; parsed: RunOutput }>;\n\n /**\n * Get structured output from the model based on a schema.\n *\n * This method supports two modes:\n * - `jsonMode`: Uses `responseSchema` to get JSON responses directly (preferred for structured outputs)\n * - `functionCalling`: Uses function calling with tools (default, for compatibility)\n *\n * @param outputSchema - The schema to use for structured output (Zod schema or JSON Schema)\n * @param config - Configuration options including method and whether to include raw response\n * @returns A Runnable that returns the parsed structured output\n */\n withStructuredOutput<\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n RunOutput extends Record<string, any> = Record<string, any>,\n >(\n outputSchema:\n | InteropZodType<RunOutput>\n | SerializableSchema<RunOutput>\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n | Record<string, any>,\n config?: StructuredOutputMethodOptions<boolean>\n ):\n | Runnable<BaseLanguageModelInput, RunOutput>\n | Runnable<\n BaseLanguageModelInput,\n { raw: BaseMessage; parsed: RunOutput }\n > {\n let llm: Runnable<BaseMessage[], AIMessageChunk, CallOptions>;\n let outputParser: Runnable<BaseMessage, RunOutput>;\n\n const { schema, name, includeRaw } = {\n ...config,\n schema: outputSchema,\n };\n let method = config?.method ?? \"functionCalling\";\n\n if (method === \"jsonMode\") {\n console.warn(\n `\"jsonMode\" is not supported for Google models. Falling back to \"jsonSchema\".`\n );\n method = \"jsonSchema\";\n }\n\n if (method === \"jsonSchema\") {\n // Use JSON mode with responseSchema\n llm = this.withConfig({\n responseSchema: schema,\n } as Partial<CallOptions>);\n\n outputParser = RunnableLambda.from<BaseMessage, RunOutput>(\n async (input: BaseMessage): Promise<RunOutput> => {\n if (\n !AIMessage.isInstance(input) &&\n !AIMessageChunk.isInstance(input)\n ) {\n throw new MalformedOutputError({\n message: \"Input is not an AIMessage or AIMessageChunk.\",\n });\n }\n\n if (!input.text) {\n throw new MalformedOutputError({\n message:\n \"No content found in response. Cannot parse structured output.\",\n });\n }\n\n // Parse JSON and validate with schema\n const parser = createContentParser(schema);\n return await parser.parse(input.text);\n }\n );\n } else if (method === \"functionCalling\") {\n // Use function calling mode\n let functionName = name ?? \"extract\";\n let geminiFunctionDeclaration: Gemini.Tools.FunctionDeclaration;\n\n if (isInteropZodSchema(schema) || isSerializableSchema(schema)) {\n const jsonSchema = schemaToGeminiParameters(schema);\n const description =\n typeof jsonSchema.description === \"string\"\n ? jsonSchema.description\n : \"A function available to call.\";\n geminiFunctionDeclaration = {\n name: functionName,\n description,\n parameters: jsonSchema as Gemini.Tools.Schema,\n };\n } else if (\n typeof schema.name === \"string\" &&\n typeof schema.parameters === \"object\" &&\n schema.parameters != null\n ) {\n geminiFunctionDeclaration = schema as Gemini.Tools.FunctionDeclaration;\n functionName = schema.name;\n } else {\n // We are providing the schema for *just* the parameters\n const parameters = schemaToGeminiParameters(schema);\n geminiFunctionDeclaration = {\n name: functionName,\n description: (schema as { description?: string }).description ?? \"\",\n parameters,\n };\n }\n\n const tools: Gemini.Tool[] = [\n {\n functionDeclarations: [geminiFunctionDeclaration],\n },\n ];\n llm = this.bindTools(tools).withConfig({\n tool_choice: functionName,\n } as Partial<CallOptions>);\n\n outputParser = createFunctionCallingParser(schema, functionName);\n } else {\n throw new ConfigurationError(\n `Unrecognized structured output method '${method}'. Expected 'functionCalling' or 'jsonSchema'`\n );\n }\n\n return assembleStructuredOutputPipeline(\n llm,\n outputParser,\n includeRaw,\n includeRaw\n ? \"ChatGoogleStructuredOutputRunnable\"\n : \"ChatGoogleStructuredOutput\"\n );\n }\n}\n\ntype CombinableFields = Omit<BaseChatGoogleParams, \"model\">;\n\nexport function combineGoogleChatModelFields(\n a: CombinableFields,\n b: CombinableFields,\n ...rest: CombinableFields[]\n): CombinableFields {\n const combined: CombinableFields = {\n temperature: b.temperature ?? a.temperature,\n topP: b.topP ?? a.topP,\n topK: b.topK ?? a.topK,\n maxOutputTokens: b.maxOutputTokens ?? a.maxOutputTokens,\n presencePenalty: b.presencePenalty ?? a.presencePenalty,\n frequencyPenalty: b.frequencyPenalty ?? a.frequencyPenalty,\n stopSequences: b.stopSequences ?? a.stopSequences,\n seed: b.seed ?? a.seed,\n responseLogprobs: b.responseLogprobs ?? a.responseLogprobs,\n logprobs: b.logprobs ?? a.logprobs,\n safetySettings: b.safetySettings ?? a.safetySettings,\n responseSchema: b.responseSchema ?? a.responseSchema,\n tools: b.tools ?? a.tools,\n responseModalities: b.responseModalities ?? a.responseModalities,\n enableEnhancedCivicAnswers:\n b.enableEnhancedCivicAnswers ?? a.enableEnhancedCivicAnswers,\n speechConfig: b.speechConfig ?? a.speechConfig,\n imageConfig: b.imageConfig ?? a.imageConfig,\n mediaResolution: b.mediaResolution ?? a.mediaResolution,\n detail: b.detail ?? a.detail,\n maxReasoningTokens: b.maxReasoningTokens ?? a.maxReasoningTokens,\n thinkingBudget: b.thinkingBudget ?? a.thinkingBudget,\n reasoningEffort: b.reasoningEffort ?? a.reasoningEffort,\n thinkingLevel: b.thinkingLevel ?? a.thinkingLevel,\n };\n if (rest.length > 0) {\n return combineGoogleChatModelFields(combined, rest[0], ...rest.slice(1));\n }\n return combined;\n}\n\nexport function getGoogleChatModelParams<TParams extends BaseChatGoogleParams>(\n modelOrParams: string | TParams,\n paramsArg?: Omit<TParams, \"model\">\n): TParams {\n const model =\n typeof modelOrParams === \"string\" ? modelOrParams : modelOrParams.model;\n const params = typeof modelOrParams === \"string\" ? paramsArg : modelOrParams;\n return { model, ...params } as TParams;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AA4EA,SAAgB,gBACd,UACA,WACoB;AACpB,KAAI,OAAO,aAAa,YACtB,QAAO;UACE,UACT,QAAO;KAEP,QAAO;;AAIX,SAAS,2BACP,QACwD;AACxD,SAAQ,QAAR;EACE,KAAK,MACH,QAAO;EACT,KAAK,OACH,QAAO;EACT,QACE;;;AA+DN,IAAsB,iBAAtB,cAEU,cAA2C;CACnD;CAEA;CAEA;CAEA,cAAuB;CAEvB;CAEA;CAEA;CAEA;CAEA;CAEA,YAAY,QAAwC;AAClD,QAAM,OAAO;AADO,OAAA,SAAA;AAEpB,OAAK,YAAY,qBAAA,SAAqC;AAEtD,MAAI,CAAC,OAAO,UACV,OAAM,IAAI,mBACR,6LACD;AAEH,OAAK,YAAY,OAAO;AAExB,OAAK,QAAQ,OAAO;AACpB,OAAK,YAAY,4BAA4B,OAAO;AACpD,OAAK,YAAY,OAAO;AACxB,OAAK,YAAY,OAAO;AACxB,OAAK,cAAc,OAAO;AAE1B,OAAK,mBAAmB,QAAQ,qBAAqB;AACrD,OAAK,YAAY,QAAQ,cAAc;AACvC,MAAI,KAAK,iBAAkB,MAAK,YAAY;AAE5C,MAAI,QAAQ,cAAc,MAAO,MAAK,mBAAmB;AAEzD,OAAK,cAAc,QAAQ,eAAe,KAAK;AAC/C,MAAI,KAAK,iBAAkB,MAAK,cAAc;;CAGhD,WAAmB;AACjB,SAAO;;CAGT,IAAc,eAA+C;AAC3D,SAAO,KAAK;;CAGd,IAAc,WAA+B;AAC3C,SAAO,gBAAgB,KAAK,WAAW,KAAK,UAAU,WAAW,CAAC;;CAGpE,IAAc,kBAA2B;AACvC,SAAO,KAAK,aAAa,SAAS,KAAK,UAAU,WAAW;;CAG9D,IAAc,aAAqB;AACjC,MAAI,OAAO,KAAK,gBAAgB,YAC9B,QAAO,KAAK;WACH,KAAK,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AAe,EAAE;EAChC,iBAAiB,EAAE,mBAAmB,EAAE;EACxC,QAAQ,EAAE,UAAU,EAAE;EACtB,oBAAoB,EAAE,sBAAsB,EAAE;EAC9C,gBAAgB,EAAE,kBAAkB,EAAE;EACtC,iBAAiB,EAAE,mBAAmB,EAAE;EACxC,eAAe,EAAE,iBAAiB,EAAE;EACrC;AACD,KAAI,KAAK,SAAS,EAChB,QAAO,6BAA6B,UAAU,KAAK,IAAI,GAAG,KAAK,MAAM,EAAE,CAAC;AAE1E,QAAO;;AAGT,SAAgB,yBACd,eACA,WACS;AAIT,QAAO;EAAE,OAFP,OAAO,kBAAkB,WAAW,gBAAgB,cAAc;EAEpD,GADD,OAAO,kBAAkB,WAAW,YAAY;EACpC"}
1
+ {"version":3,"file":"base.js","names":[],"sources":["../../src/chat_models/base.ts"],"sourcesContent":["import {\n BaseChatModel,\n type BaseChatModelCallOptions,\n type LangSmithParams,\n type BaseChatModelParams,\n} from \"@langchain/core/language_models/chat_models\";\nimport {\n AIMessage,\n AIMessageChunk,\n AIMessageChunkFields,\n BaseMessage,\n type UsageMetadata,\n} from \"@langchain/core/messages\";\nimport { CallbackManagerForLLMRun } from \"@langchain/core/callbacks/manager\";\nimport type { ChatModelStreamEvent } from \"@langchain/core/language_models/event\";\nimport { convertGoogleGeminiStream } from \"../utils/stream_events.js\";\nimport { concat } from \"@langchain/core/utils/stream\";\nimport { ChatGenerationChunk, ChatResult } from \"@langchain/core/outputs\";\nimport { EventSourceParserStream } from \"eventsource-parser/stream\";\nimport type { BindToolsInput } from \"@langchain/core/language_models/chat_models\";\nimport type { ModelProfile } from \"@langchain/core/language_models/profile\";\nimport PROFILES from \"./profiles.js\";\nimport type {\n BaseLanguageModelInput,\n StructuredOutputMethodOptions,\n} from \"@langchain/core/language_models/base\";\nimport { Runnable, RunnableLambda } from \"@langchain/core/runnables\";\nimport {\n toJsonSchema,\n type JsonSchema7Type,\n} from \"@langchain/core/utils/json_schema\";\nimport {\n InteropZodType,\n isInteropZodSchema,\n} from \"@langchain/core/utils/types\";\n\nimport { ApiClient } from \"../clients/index.js\";\nimport { ChatGoogleFields, settableServiceTier } from \"./types.js\";\nimport { SafeJsonEventParserStream } from \"../utils/stream.js\";\nimport {\n convertAIMessageToText,\n convertGeminiCandidateToAIMessage,\n convertGeminiGenerateContentResponseToUsageMetadata,\n convertGeminiPartsToToolCalls,\n convertMessagesToGeminiContents,\n convertMessagesToGeminiSystemInstruction,\n} from \"../converters/messages.js\";\nimport {\n ConfigurationError,\n MalformedOutputError,\n NoCandidatesError,\n PromptBlockedError,\n RequestError,\n} from \"../utils/errors.js\";\nimport {\n convertToolsToGeminiTools,\n convertToolChoiceToGeminiConfig,\n schemaToGeminiParameters,\n} from \"../converters/tools.js\";\nimport {\n convertParamsToPlatformType,\n convertFieldsToSpeechConfig,\n convertFieldsToThinkingConfig,\n convertFieldsToServiceTier,\n} from \"../converters/params.js\";\nimport { Gemini } from \"./api-types.js\";\nimport { subtractUsageMetadata } from \"../utils/metadata.js\";\nimport {\n isSerializableSchema,\n SerializableSchema,\n} from \"@langchain/core/utils/standard_schema\";\nimport {\n assembleStructuredOutputPipeline,\n createContentParser,\n createFunctionCallingParser,\n} from \"@langchain/core/language_models/structured_output\";\nimport { iife } from \"../utils/misc\";\nimport ServiceTier = Gemini.ServiceTier;\n\nexport type GooglePlatformType = \"gai\" | \"gcp\";\n\nexport function getPlatformType(\n platform: GooglePlatformType | undefined,\n hasApiKey: boolean\n): GooglePlatformType {\n if (typeof platform !== \"undefined\") {\n return platform;\n } else if (hasApiKey) {\n return \"gai\";\n } else {\n return \"gcp\";\n }\n}\n\nfunction usageMetadataToTokenUsage(usageMetadata: UsageMetadata) {\n return {\n promptTokens: usageMetadata.input_tokens,\n completionTokens: usageMetadata.output_tokens,\n totalTokens: usageMetadata.total_tokens,\n };\n}\n\nfunction mapDetailToMediaResolution(\n detail?: ChatGoogleFields[\"detail\"]\n): Gemini.GenerationConfig[\"mediaResolution\"] | undefined {\n switch (detail) {\n case \"low\":\n return \"MEDIA_RESOLUTION_LOW\";\n case \"high\":\n return \"MEDIA_RESOLUTION_HIGH\";\n default:\n return undefined;\n }\n}\n\nexport interface BaseChatGoogleParams\n extends BaseChatModelParams, ChatGoogleFields {\n /**\n * The name of the Gemini model to use.\n *\n * Example: \"gemini-3-pro-preview\"\n */\n model: string;\n\n /**\n * Optional. The API client implementation for making HTTP requests to the Gemini API.\n * If not set, a default client will be used based on the runtime environment.\n */\n apiClient?: ApiClient;\n\n /**\n * Hostname for the API call (if this is running on GCP)\n * Usually this is computed based on location and platformType.\n **/\n endpoint?: string;\n\n /**\n * Region where the LLM is stored (if this is running on GCP)\n * Defaults to \"global\"\n **/\n location?: string;\n\n /**\n * The version of the API functions. Part of the path.\n * Usually this is computed based on platformType.\n **/\n apiVersion?: string;\n\n /**\n * What platform to run the service on.\n * If not specified, the class should determine this from other\n * means. Either way, the platform actually used will be in\n * the \"platform\" getter.\n */\n platformType?: GooglePlatformType;\n\n /**\n * For compatibility with Google's libraries, should this use Vertex?\n * The \"platformType\" parmeter takes precedence.\n */\n vertexai?: boolean;\n\n /**\n * Backwards compatibility.\n * @deprecated in favor of using `disableStreaming` or `.stream()`\n */\n streaming?: boolean;\n\n streamUsage?: boolean;\n}\n\nexport interface BaseChatGoogleCallOptions\n extends BaseChatModelCallOptions, ChatGoogleFields {}\n\nexport abstract class BaseChatGoogle<\n CallOptions extends BaseChatGoogleCallOptions = BaseChatGoogleCallOptions,\n> extends BaseChatModel<CallOptions, AIMessageChunk> {\n model: string;\n\n streaming: boolean;\n\n disableStreaming: boolean;\n\n streamUsage: boolean = true;\n\n protected _platform?: GooglePlatformType;\n\n protected _endpoint?: string;\n\n protected _customHeaders?: Record<string, string>;\n\n protected _location?: string;\n\n protected _apiVersion?: string;\n\n protected apiClient: ApiClient;\n\n constructor(protected params: BaseChatGoogleParams) {\n super(params);\n this._addVersion(\"@langchain/google\", __PKG_VERSION__);\n\n if (!params.apiClient) {\n throw new ConfigurationError(\n \"BaseChatGoogle requires an apiClient. This should be provided automatically by ChatGoogle constructors. If you're extending BaseChatGoogle directly, please provide an apiClient instance.\"\n );\n }\n this.apiClient = params.apiClient;\n\n this.model = params.model;\n this._platform = convertParamsToPlatformType(params);\n this._endpoint = params.endpoint;\n this._customHeaders = params.customHeaders;\n this._location = params.location;\n this._apiVersion = params.apiVersion;\n\n this.disableStreaming = params?.disableStreaming === true;\n this.streaming = params?.streaming === true;\n if (this.disableStreaming) this.streaming = false;\n // disable streaming in BaseChatModel if explicitly disabled\n if (params?.streaming === false) this.disableStreaming = true;\n\n this.streamUsage = params?.streamUsage ?? this.streamUsage;\n if (this.disableStreaming) this.streamUsage = false;\n }\n\n _llmType(): string {\n return \"google\";\n }\n\n protected get platformType(): GooglePlatformType | undefined {\n return this._platform;\n }\n\n protected get platform(): GooglePlatformType {\n return getPlatformType(this._platform, this.apiClient.hasApiKey());\n }\n\n protected get isVertexExpress(): boolean {\n return this.platform === \"gcp\" && this.apiClient.hasApiKey();\n }\n\n protected get apiVersion(): string {\n if (typeof this._apiVersion !== \"undefined\") {\n return this._apiVersion;\n } else if (this.platform === \"gai\") {\n return \"v1beta\";\n } else {\n return \"v1\";\n }\n }\n\n protected get location(): string {\n return this._location || \"global\";\n }\n\n protected get endpoint(): string {\n if (typeof this._endpoint !== \"undefined\") {\n return this._endpoint;\n } else if (this.platform === \"gai\") {\n return \"generativelanguage.googleapis.com\";\n } else if (this.isVertexExpress) {\n return \"aiplatform.googleapis.com\";\n } else if (this.location === \"global\") {\n // See https://docs.cloud.google.com/vertex-ai/generative-ai/docs/learn/locations#use_the_global_endpoint\n return \"aiplatform.googleapis.com\";\n } else {\n return `${this.location}-aiplatform.googleapis.com`;\n }\n }\n\n protected get publisher(): string {\n return \"google\";\n }\n\n protected get urlMethod(): string {\n return this.streaming ? \"streamGenerateContent?alt=sse\" : \"generateContent\";\n }\n\n /**\n * Returns the model profile for this instance's model, describing its\n * capabilities and constraints (e.g. max tokens, input/output modalities,\n * tool calling support).\n *\n * @example\n * ```typescript\n * const model = new ChatGoogle({ model: \"gemini-2.5-pro\" });\n * const profile = model.profile;\n * console.log(profile.maxInputTokens); // 1048576\n * console.log(profile.imageInputs); // true\n * ```\n */\n get profile(): ModelProfile {\n return PROFILES[this.model] ?? {};\n }\n\n protected async buildUrlGemini(urlMethod?: string): Promise<string> {\n return `https://${this.endpoint}/${this.apiVersion}/models/${this.model}:${\n urlMethod ?? this.urlMethod\n }`;\n }\n\n protected async buildUrlVertexExpress(urlMethod?: string): Promise<string> {\n return `https://${this.endpoint}/${this.apiVersion}/publishers/${\n this.publisher\n }/models/${this.model}:${urlMethod ?? this.urlMethod}`;\n }\n\n protected async buildUrlVertexLocation(urlMethod?: string): Promise<string> {\n const projectId = await this.apiClient.getProjectId();\n return `https://${this.endpoint}/${\n this.apiVersion\n }/projects/${projectId}/locations/${this.location}/publishers/${\n this.publisher\n }/models/${this.model}:${urlMethod ?? this.urlMethod}`;\n }\n\n protected async buildUrlVertex(urlMethod?: string): Promise<string> {\n if (this.isVertexExpress) {\n return this.buildUrlVertexExpress(urlMethod);\n } else {\n return this.buildUrlVertexLocation(urlMethod);\n }\n }\n\n protected async buildUrl(urlMethod?: string): Promise<string> {\n switch (this.platform) {\n case \"gai\":\n return this.buildUrlGemini(urlMethod);\n default:\n return this.buildUrlVertex(urlMethod);\n }\n }\n\n override invocationParams(options: this[\"ParsedCallOptions\"]) {\n const fields = combineGoogleChatModelFields(this.params, options);\n const mediaResolution =\n fields.mediaResolution ?? mapDetailToMediaResolution(fields.detail);\n\n // Convert tools to Gemini format\n const tools = fields.tools\n ? convertToolsToGeminiTools(fields.tools)\n : undefined;\n\n // Convert tool choice to Gemini function calling config\n const toolConfig = convertToolChoiceToGeminiConfig(\n options.tool_choice,\n !!(tools && tools.length > 0)\n );\n\n let responseJsonSchema:\n | JsonSchema7Type\n | Record<string, unknown>\n | undefined;\n let responseMimeType: string | undefined;\n\n if (fields.responseSchema) {\n // Convert Zod schema to JSON Schema if needed\n if (\n isInteropZodSchema(fields.responseSchema) ||\n isSerializableSchema(fields.responseSchema)\n ) {\n responseJsonSchema = toJsonSchema(fields.responseSchema);\n } else {\n responseJsonSchema = fields.responseSchema as Record<string, unknown>;\n }\n // Automatically set responseMimeType to \"application/json\" when schema is provided\n responseMimeType = \"application/json\";\n }\n\n return {\n ...(tools && tools.length > 0 ? { tools } : {}),\n ...(toolConfig ? { toolConfig } : {}),\n safetySettings: fields.safetySettings,\n generationConfig: {\n temperature: fields.temperature,\n topP: fields.topP,\n topK: fields.topK,\n maxOutputTokens: fields.maxOutputTokens,\n presencePenalty: fields.presencePenalty,\n frequencyPenalty: fields.frequencyPenalty,\n stopSequences: fields.stopSequences,\n ...(responseMimeType ? { responseMimeType } : {}),\n ...(responseJsonSchema ? { responseJsonSchema } : {}),\n ...(fields.responseModalities && fields.responseModalities.length > 0\n ? { responseModalities: fields.responseModalities }\n : {}),\n candidateCount: 1,\n seed: fields.seed,\n responseLogprobs: fields.responseLogprobs,\n logprobs: fields.logprobs,\n ...(fields.enableEnhancedCivicAnswers !== undefined\n ? { enableEnhancedCivicAnswers: fields.enableEnhancedCivicAnswers }\n : {}),\n thinkingConfig: convertFieldsToThinkingConfig(this.model, fields),\n speechConfig: convertFieldsToSpeechConfig(fields),\n ...(fields.imageConfig ? { imageConfig: fields.imageConfig } : {}),\n ...(mediaResolution ? { mediaResolution } : {}),\n },\n ...convertFieldsToServiceTier(this.platform, fields),\n };\n }\n\n getLsParams(options: this[\"ParsedCallOptions\"]): LangSmithParams {\n const params = this.invocationParams(options);\n return {\n ls_provider: this.platform === \"gcp\" ? \"google_vertexai\" : \"google_genai\",\n ls_model_name: this.model,\n ls_model_type: \"chat\",\n ls_temperature: params.generationConfig?.temperature ?? undefined,\n ls_max_tokens: params.generationConfig?.maxOutputTokens ?? undefined,\n ls_stop: options.stop,\n };\n }\n\n getHeaders(options: this[\"ParsedCallOptions\"]): HeadersInit {\n const fields = combineGoogleChatModelFields(this.params, options);\n\n // The priority type is set via header only for Vertex\n const priorityHeaders: Record<string, string> =\n this.platform === \"gcp\" &&\n typeof fields.serviceTier !== \"undefined\" &&\n settableServiceTier.includes(fields.serviceTier)\n ? { \"X-Vertex-AI-LLM-Shared-Request-Type\": fields.serviceTier }\n : {};\n\n return {\n \"Content-Type\": \"application/json\",\n ...priorityHeaders,\n ...this._customHeaders,\n ...options.customHeaders,\n };\n }\n\n async _generate(\n messages: BaseMessage[],\n options: this[\"ParsedCallOptions\"],\n runManager?: CallbackManagerForLLMRun\n ): Promise<ChatResult> {\n if (this.streaming) {\n const stream = await this._streamResponseChunks(\n messages,\n options,\n runManager\n );\n let finalChunk: ChatGenerationChunk | null = null;\n for await (const chunk of stream) {\n finalChunk = !finalChunk ? chunk : concat(finalChunk, chunk);\n }\n if (\n typeof finalChunk?.message?.content === \"string\" &&\n typeof (\n finalChunk?.message?.additional_kwargs\n ?.originalTextContentBlock as Record<string, unknown>\n )?.text === \"string\"\n ) {\n (\n finalChunk.message.additional_kwargs\n .originalTextContentBlock as Record<string, unknown>\n ).text = finalChunk.message.content;\n }\n return {\n generations: finalChunk ? [finalChunk] : [],\n };\n }\n\n const url = await this.buildUrl();\n const headers = this.getHeaders(options);\n const body = {\n ...this.invocationParams(options),\n systemInstruction: convertMessagesToGeminiSystemInstruction(messages),\n contents: convertMessagesToGeminiContents(messages),\n };\n\n const moduleName = this.constructor.name;\n await runManager?.handleCustomEvent(`google-request-${moduleName}`, {\n url,\n headers,\n body,\n });\n\n const response = await this.apiClient.fetch(\n new Request(url, {\n method: \"POST\",\n headers,\n body: JSON.stringify(body),\n signal: options.signal,\n })\n );\n\n if (!response.ok) {\n const error = await RequestError.fromResponse(response);\n await runManager?.handleCustomEvent(`google-response-${moduleName}`, {\n error,\n });\n throw error;\n }\n\n const data: Gemini.GenerateContentResponse = await response.json();\n await runManager?.handleCustomEvent(`google-response-${moduleName}`, {\n data,\n url: response.url,\n headers: Array.from(response.headers.entries()),\n status: response.status,\n statusText: response.statusText,\n });\n\n // Check for prompt feedback errors\n if (data.promptFeedback?.blockReason) {\n throw PromptBlockedError.fromPromptFeedback(data.promptFeedback);\n }\n\n // Check if we have candidates\n if (!data.candidates || data.candidates.length === 0) {\n throw new NoCandidatesError();\n }\n\n // Use the first candidate\n const candidate = data.candidates[0];\n const message = convertGeminiCandidateToAIMessage(candidate);\n\n // Extract text content from the message\n const text = convertAIMessageToText(message);\n\n const usageMetadata =\n convertGeminiGenerateContentResponseToUsageMetadata(data);\n message.usage_metadata = usageMetadata;\n\n const serviceTier: ServiceTier = iife((): ServiceTier => {\n // @ts-expect-error - trafficType is defined on Vertex, so isn't in the OpenAPI spec\n const trafficType: string | undefined = data.usageMetadata?.trafficType;\n\n // AI Studio replies with actual service type in the header\n const serviceTierHeader: string | null = response.headers.get(\n \"x-gemini-service-tier\"\n );\n\n if (trafficType?.startsWith(\"ON_DEMAND_\")) {\n return trafficType?.substring(\"ON_DEMAND_\".length).toLowerCase();\n }\n return serviceTierHeader || \"standard\";\n });\n\n return {\n generations: [\n {\n text,\n message,\n generationInfo: {\n finishReason: candidate.finishReason,\n finishMessage: candidate.finishMessage,\n safetyRatings: candidate.safetyRatings,\n citationMetadata: candidate.citationMetadata,\n tokenCount: candidate.tokenCount,\n },\n },\n ],\n llmOutput: {\n tokenUsage: usageMetadataToTokenUsage(usageMetadata),\n model: data.modelVersion,\n responseId: data.responseId,\n usageMetadata,\n serviceTier,\n },\n };\n }\n\n async *_streamChatModelEvents(\n messages: BaseMessage[],\n options: this[\"ParsedCallOptions\"],\n _runManager?: CallbackManagerForLLMRun\n ): AsyncGenerator<ChatModelStreamEvent> {\n const body = {\n ...this.invocationParams(options),\n systemInstruction: convertMessagesToGeminiSystemInstruction(messages),\n contents: convertMessagesToGeminiContents(messages),\n };\n\n const url = await this.buildUrl(\"streamGenerateContent?alt=sse\");\n const headers = this.getHeaders(options);\n\n const response = await this.apiClient.fetch(\n new Request(url, {\n method: \"POST\",\n headers,\n body: JSON.stringify(body),\n signal: options.signal,\n })\n );\n\n if (!response.ok) {\n throw await RequestError.fromResponse(response);\n }\n\n if (!response.body) {\n return;\n }\n\n const eventStream = response.body\n .pipeThrough(new TextDecoderStream())\n .pipeThrough(new EventSourceParserStream())\n .pipeThrough(\n new SafeJsonEventParserStream<Gemini.GenerateContentResponse>()\n );\n\n const shouldStreamUsage =\n this.streamUsage !== false && options.streamUsage !== false;\n\n async function* geminiChunks(\n stream: ReadableStream<Gemini.GenerateContentResponse | null>,\n signal?: AbortSignal\n ) {\n const reader = stream.getReader();\n try {\n while (true) {\n if (signal?.aborted) {\n return;\n }\n const { done, value } = await reader.read();\n if (done) {\n break;\n }\n if (value !== null) {\n yield value;\n }\n }\n } finally {\n reader.releaseLock();\n }\n }\n\n yield* convertGoogleGeminiStream(\n geminiChunks(eventStream, options.signal),\n {\n streamUsage: shouldStreamUsage,\n }\n );\n }\n\n async *_streamResponseChunks(\n messages: BaseMessage[],\n options: this[\"ParsedCallOptions\"],\n runManager?: CallbackManagerForLLMRun\n ): AsyncGenerator<ChatGenerationChunk> {\n const streamUsage: boolean = this.streamUsage ?? true;\n\n const body = {\n ...this.invocationParams(options),\n systemInstruction: convertMessagesToGeminiSystemInstruction(messages),\n contents: convertMessagesToGeminiContents(messages),\n };\n\n const url = await this.buildUrl(\"streamGenerateContent?alt=sse\");\n const headers = this.getHeaders(options);\n const moduleName = this.constructor.name;\n await runManager?.handleCustomEvent(`google-request-${moduleName}`, {\n url,\n headers,\n body,\n });\n\n const response = await this.apiClient.fetch(\n new Request(url, {\n method: \"POST\",\n headers,\n body: JSON.stringify(body),\n signal: options.signal,\n })\n );\n\n await runManager?.handleCustomEvent(`google-response-${moduleName}`, {\n url: response.url,\n headers: Array.from(response.headers.entries()),\n status: response.status,\n statusText: response.statusText,\n });\n\n if (!response.ok) {\n const error = await RequestError.fromResponse(response);\n await runManager?.handleCustomEvent(`google-response-${moduleName}`, {\n error,\n });\n throw error;\n }\n\n if (response.body) {\n let previousUsage: UsageMetadata | undefined;\n const stream = response.body\n .pipeThrough(new TextDecoderStream())\n .pipeThrough(new EventSourceParserStream())\n .pipeThrough(\n new SafeJsonEventParserStream<Gemini.GenerateContentResponse>()\n )\n .pipeThrough(\n new TransformStream<\n Gemini.GenerateContentResponse,\n ChatGenerationChunk\n >({\n transform(chunk, controller) {\n // oxlint-disable-next-line no-void\n void runManager?.handleCustomEvent(`google-chunk-${moduleName}`, {\n chunk,\n });\n if (chunk === null) {\n controller.enqueue(\n new ChatGenerationChunk({\n text: \"\",\n message: new AIMessageChunk({ content: \"\" }),\n generationInfo: { finishReason: \"stop\" },\n })\n );\n return;\n }\n\n // Extract text delta from the chunk\n const candidate = chunk.candidates?.[0];\n if (!candidate) {\n return;\n }\n\n const message = convertGeminiCandidateToAIMessage(candidate);\n const text = convertAIMessageToText(message);\n\n const parts = candidate.content?.parts ?? [];\n const toolCalls = convertGeminiPartsToToolCalls(parts);\n\n // Only emit if we have content\n if (parts.length > 0 || candidate.finishReason) {\n const messageChunkParams: AIMessageChunkFields = {\n content: message.content,\n tool_calls: toolCalls,\n response_metadata: {\n model_provider: \"google\",\n },\n additional_kwargs: {\n ...(message.additional_kwargs.originalTextContentBlock\n ? {\n originalTextContentBlock:\n message.additional_kwargs.originalTextContentBlock,\n }\n : {}),\n ...(candidate.finishReason\n ? {\n finishReason: candidate.finishReason,\n finishMessage: candidate.finishMessage,\n }\n : {}),\n },\n };\n\n if (chunk?.usageMetadata && streamUsage) {\n const cumulative =\n convertGeminiGenerateContentResponseToUsageMetadata(chunk);\n messageChunkParams.usage_metadata = subtractUsageMetadata(\n cumulative,\n previousUsage\n );\n previousUsage = cumulative;\n }\n const messageChunk = new AIMessageChunk(messageChunkParams);\n\n controller.enqueue(\n new ChatGenerationChunk({\n text: text,\n message: messageChunk,\n generationInfo: {\n ...(candidate.finishReason && {\n finishReason: candidate.finishReason,\n finishMessage: candidate.finishMessage,\n }),\n ...(candidate.safetyRatings && {\n safetyRatings: candidate.safetyRatings,\n }),\n },\n })\n );\n }\n },\n })\n );\n\n const reader = stream.getReader();\n try {\n while (true) {\n const { done, value } = await reader.read();\n if (done) break;\n yield value;\n await runManager?.handleLLMNewToken(\n value.text ?? \"\",\n undefined,\n undefined,\n undefined,\n undefined,\n { chunk: value }\n );\n }\n } finally {\n reader.releaseLock();\n }\n }\n }\n\n /**\n * Bind tool-like objects to this chat model.\n *\n * @param tools A list of tool definitions to bind to this chat model.\n * Can be a structured tool, an OpenAI formatted tool, or a Gemini function declaration.\n * @param kwargs Any additional parameters to bind.\n */\n bindTools(\n tools: BindToolsInput[],\n kwargs?: Partial<CallOptions>\n ): Runnable<BaseMessage[], AIMessageChunk, CallOptions> {\n return this.withConfig({\n ...kwargs,\n tools,\n } as Partial<CallOptions>);\n }\n\n withStructuredOutput<\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n RunOutput extends Record<string, any> = Record<string, any>,\n >(\n outputSchema:\n | InteropZodType<RunOutput>\n | SerializableSchema<RunOutput>\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n | Record<string, any>,\n config?: StructuredOutputMethodOptions<false>\n ): Runnable<BaseLanguageModelInput, RunOutput>;\n\n withStructuredOutput<\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n RunOutput extends Record<string, any> = Record<string, any>,\n >(\n outputSchema:\n | InteropZodType<RunOutput>\n | SerializableSchema<RunOutput>\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n | Record<string, any>,\n config?: StructuredOutputMethodOptions<true>\n ): Runnable<BaseLanguageModelInput, { raw: BaseMessage; parsed: RunOutput }>;\n\n withStructuredOutput<\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n RunOutput extends Record<string, any> = Record<string, any>,\n >(\n outputSchema:\n | InteropZodType<RunOutput>\n | SerializableSchema<RunOutput>\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n | Record<string, any>,\n config?: StructuredOutputMethodOptions<boolean>\n ):\n | Runnable<BaseLanguageModelInput, RunOutput>\n | Runnable<BaseLanguageModelInput, { raw: BaseMessage; parsed: RunOutput }>;\n\n /**\n * Get structured output from the model based on a schema.\n *\n * This method supports two modes:\n * - `jsonMode`: Uses `responseSchema` to get JSON responses directly (preferred for structured outputs)\n * - `functionCalling`: Uses function calling with tools (default, for compatibility)\n *\n * @param outputSchema - The schema to use for structured output (Zod schema or JSON Schema)\n * @param config - Configuration options including method and whether to include raw response\n * @returns A Runnable that returns the parsed structured output\n */\n withStructuredOutput<\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n RunOutput extends Record<string, any> = Record<string, any>,\n >(\n outputSchema:\n | InteropZodType<RunOutput>\n | SerializableSchema<RunOutput>\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n | Record<string, any>,\n config?: StructuredOutputMethodOptions<boolean>\n ):\n | Runnable<BaseLanguageModelInput, RunOutput>\n | Runnable<\n BaseLanguageModelInput,\n { raw: BaseMessage; parsed: RunOutput }\n > {\n let llm: Runnable<BaseMessage[], AIMessageChunk, CallOptions>;\n let outputParser: Runnable<BaseMessage, RunOutput>;\n\n const { schema, name, includeRaw } = {\n ...config,\n schema: outputSchema,\n };\n let method = config?.method ?? \"functionCalling\";\n\n if (method === \"jsonMode\") {\n console.warn(\n `\"jsonMode\" is not supported for Google models. Falling back to \"jsonSchema\".`\n );\n method = \"jsonSchema\";\n }\n\n if (method === \"jsonSchema\") {\n // Use JSON mode with responseSchema\n llm = this.withConfig({\n responseSchema: schema,\n } as Partial<CallOptions>);\n\n outputParser = RunnableLambda.from<BaseMessage, RunOutput>(\n async (input: BaseMessage): Promise<RunOutput> => {\n if (\n !AIMessage.isInstance(input) &&\n !AIMessageChunk.isInstance(input)\n ) {\n throw new MalformedOutputError({\n message: \"Input is not an AIMessage or AIMessageChunk.\",\n });\n }\n\n if (!input.text) {\n throw new MalformedOutputError({\n message:\n \"No content found in response. Cannot parse structured output.\",\n });\n }\n\n // Parse JSON and validate with schema\n const parser = createContentParser(schema);\n return await parser.parse(input.text);\n }\n );\n } else if (method === \"functionCalling\") {\n // Use function calling mode\n let functionName = name ?? \"extract\";\n let geminiFunctionDeclaration: Gemini.Tools.FunctionDeclaration;\n\n if (isInteropZodSchema(schema) || isSerializableSchema(schema)) {\n const jsonSchema = schemaToGeminiParameters(schema);\n const description =\n typeof jsonSchema.description === \"string\"\n ? jsonSchema.description\n : \"A function available to call.\";\n geminiFunctionDeclaration = {\n name: functionName,\n description,\n parameters: jsonSchema as Gemini.Tools.Schema,\n };\n } else if (\n typeof schema.name === \"string\" &&\n typeof schema.parameters === \"object\" &&\n schema.parameters != null\n ) {\n geminiFunctionDeclaration = schema as Gemini.Tools.FunctionDeclaration;\n functionName = schema.name;\n } else {\n // We are providing the schema for *just* the parameters\n const parameters = schemaToGeminiParameters(schema);\n geminiFunctionDeclaration = {\n name: functionName,\n description: (schema as { description?: string }).description ?? \"\",\n parameters,\n };\n }\n\n const tools: Gemini.Tool[] = [\n {\n functionDeclarations: [geminiFunctionDeclaration],\n },\n ];\n llm = this.bindTools(tools).withConfig({\n tool_choice: functionName,\n } as Partial<CallOptions>);\n\n outputParser = createFunctionCallingParser(schema, functionName);\n } else {\n throw new ConfigurationError(\n `Unrecognized structured output method '${method}'. Expected 'functionCalling' or 'jsonSchema'`\n );\n }\n\n return assembleStructuredOutputPipeline(\n llm,\n outputParser,\n includeRaw,\n includeRaw\n ? \"ChatGoogleStructuredOutputRunnable\"\n : \"ChatGoogleStructuredOutput\"\n );\n }\n}\n\ntype CombinableFields = Omit<BaseChatGoogleParams, \"model\">;\n\nexport function combineGoogleChatModelFields(\n a: CombinableFields,\n b: CombinableFields,\n ...rest: CombinableFields[]\n): CombinableFields {\n const combined: CombinableFields = {\n temperature: b.temperature ?? a.temperature,\n topP: b.topP ?? a.topP,\n topK: b.topK ?? a.topK,\n maxOutputTokens: b.maxOutputTokens ?? a.maxOutputTokens,\n presencePenalty: b.presencePenalty ?? a.presencePenalty,\n frequencyPenalty: b.frequencyPenalty ?? a.frequencyPenalty,\n stopSequences: b.stopSequences ?? a.stopSequences,\n seed: b.seed ?? a.seed,\n responseLogprobs: b.responseLogprobs ?? a.responseLogprobs,\n logprobs: b.logprobs ?? a.logprobs,\n safetySettings: b.safetySettings ?? a.safetySettings,\n responseSchema: b.responseSchema ?? a.responseSchema,\n tools: b.tools ?? a.tools,\n responseModalities: b.responseModalities ?? a.responseModalities,\n enableEnhancedCivicAnswers:\n b.enableEnhancedCivicAnswers ?? a.enableEnhancedCivicAnswers,\n speechConfig: b.speechConfig ?? a.speechConfig,\n imageConfig: b.imageConfig ?? a.imageConfig,\n mediaResolution: b.mediaResolution ?? a.mediaResolution,\n detail: b.detail ?? a.detail,\n maxReasoningTokens: b.maxReasoningTokens ?? a.maxReasoningTokens,\n thinkingBudget: b.thinkingBudget ?? a.thinkingBudget,\n reasoningEffort: b.reasoningEffort ?? a.reasoningEffort,\n thinkingLevel: b.thinkingLevel ?? a.thinkingLevel,\n serviceTier: b.serviceTier ?? a.serviceTier,\n };\n if (rest.length > 0) {\n return combineGoogleChatModelFields(combined, rest[0], ...rest.slice(1));\n }\n return combined;\n}\n\nexport function getGoogleChatModelParams<TParams extends BaseChatGoogleParams>(\n modelOrParams: string | TParams,\n paramsArg?: Omit<TParams, \"model\">\n): TParams {\n const model =\n typeof modelOrParams === \"string\" ? modelOrParams : modelOrParams.model;\n const params = typeof modelOrParams === \"string\" ? paramsArg : modelOrParams;\n return { model, ...params } as TParams;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAiFA,SAAgB,gBACd,UACA,WACoB;AACpB,KAAI,OAAO,aAAa,YACtB,QAAO;UACE,UACT,QAAO;KAEP,QAAO;;AAIX,SAAS,0BAA0B,eAA8B;AAC/D,QAAO;EACL,cAAc,cAAc;EAC5B,kBAAkB,cAAc;EAChC,aAAa,cAAc;EAC5B;;AAGH,SAAS,2BACP,QACwD;AACxD,SAAQ,QAAR;EACE,KAAK,MACH,QAAO;EACT,KAAK,OACH,QAAO;EACT,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BACE,EAAE,8BAA8B,EAAE;EACpC,cAAc,EAAE,gBAAgB,EAAE;EAClC,aAAa,EAAE,eAAe,EAAE;EAChC,iBAAiB,EAAE,mBAAmB,EAAE;EACxC,QAAQ,EAAE,UAAU,EAAE;EACtB,oBAAoB,EAAE,sBAAsB,EAAE;EAC9C,gBAAgB,EAAE,kBAAkB,EAAE;EACtC,iBAAiB,EAAE,mBAAmB,EAAE;EACxC,eAAe,EAAE,iBAAiB,EAAE;EACpC,aAAa,EAAE,eAAe,EAAE;EACjC;AACD,KAAI,KAAK,SAAS,EAChB,QAAO,6BAA6B,UAAU,KAAK,IAAI,GAAG,KAAK,MAAM,EAAE,CAAC;AAE1E,QAAO;;AAGT,SAAgB,yBACd,eACA,WACS;AAIT,QAAO;EAAE,OAFP,OAAO,kBAAkB,WAAW,gBAAgB,cAAc;EAEpD,GADD,OAAO,kBAAkB,WAAW,YAAY;EACpC"}
@@ -1 +1 @@
1
- {"version":3,"file":"node.cjs","names":["BaseChatGoogle","getGoogleChatModelParams","ensureAuthScopes","NodeApiClient","getPlatformType","convertParamsToPlatformType","GENERATIVE_AI_AUTH_SCOPES","VERTEX_AI_AUTH_SCOPES"],"sources":["../../src/chat_models/node.ts"],"sourcesContent":["import { getEnvironmentVariable } from \"@langchain/core/utils/env\";\nimport { ChatGoogleParams } from \"./index.js\";\nimport {\n BaseChatGoogle,\n getGoogleChatModelParams,\n getPlatformType,\n} from \"./base.js\";\nimport { GENERATIVE_AI_AUTH_SCOPES, VERTEX_AI_AUTH_SCOPES } from \"../const.js\";\nimport {\n ensureAuthScopes,\n NodeApiClient,\n NodeApiClientParams,\n} from \"../clients/node.js\";\nimport { convertParamsToPlatformType } from \"../converters/params.js\";\n\ninterface ChatGoogleNodeParams extends NodeApiClientParams, ChatGoogleParams {}\n\nclass ChatGoogleNode extends BaseChatGoogle {\n constructor(model: string, params?: Omit<ChatGoogleNodeParams, \"model\">);\n constructor(params: ChatGoogleNodeParams);\n constructor(\n modelOrParams: string | ChatGoogleNodeParams,\n paramsArg?: Omit<ChatGoogleNodeParams, \"model\">\n ) {\n const params = getGoogleChatModelParams(modelOrParams, paramsArg);\n if (!params.googleAuthOptions) {\n params.apiKey = params.apiKey ?? getEnvironmentVariable(\"GOOGLE_API_KEY\");\n }\n const requiredScopes: string[] = getRequiredAuthScopes(params);\n if (params.googleAuthOptions) {\n params.googleAuthOptions = ensureAuthScopes(\n params.googleAuthOptions,\n requiredScopes\n );\n }\n const apiClient = params?.apiClient ?? new NodeApiClient(params);\n super({ ...params, apiClient });\n }\n}\n\nfunction getRequiredAuthScopes(params: ChatGoogleNodeParams): string[] {\n const hasApiKey = typeof params.apiKey !== \"undefined\";\n const platformType = convertParamsToPlatformType(params);\n const platform = getPlatformType(platformType, hasApiKey);\n switch (platform) {\n case \"gai\":\n return GENERATIVE_AI_AUTH_SCOPES;\n case \"gcp\":\n return VERTEX_AI_AUTH_SCOPES;\n default:\n return VERTEX_AI_AUTH_SCOPES;\n }\n}\n\nexport {\n type ChatGoogleNodeParams as ChatGoogleParams,\n ChatGoogleNode as ChatGoogle,\n};\n"],"mappings":";;;;;;AAiBA,IAAM,iBAAN,cAA6BA,aAAAA,eAAe;CAG1C,YACE,eACA,WACA;EACA,MAAM,SAASC,aAAAA,yBAAyB,eAAe,UAAU;AACjE,MAAI,CAAC,OAAO,kBACV,QAAO,SAAS,OAAO,WAAA,GAAA,0BAAA,wBAAiC,iBAAiB;EAE3E,MAAM,iBAA2B,sBAAsB,OAAO;AAC9D,MAAI,OAAO,kBACT,QAAO,oBAAoBC,aAAAA,iBACzB,OAAO,mBACP,eACD;EAEH,MAAM,YAAY,QAAQ,aAAa,IAAIC,aAAAA,cAAc,OAAO;AAChE,QAAM;GAAE,GAAG;GAAQ;GAAW,CAAC;;;AAInC,SAAS,sBAAsB,QAAwC;CACrE,MAAM,YAAY,OAAO,OAAO,WAAW;AAG3C,SADiBC,aAAAA,gBADIC,eAAAA,4BAA4B,OAAO,EACT,UAAU,EACzD;EACE,KAAK,MACH,QAAOC,cAAAA;EACT,KAAK,MACH,QAAOC,cAAAA;EACT,QACE,QAAOA,cAAAA"}
1
+ {"version":3,"file":"node.cjs","names":["BaseChatGoogle","getGoogleChatModelParams","ensureAuthScopes","NodeApiClient","getPlatformType","convertParamsToPlatformType","GENERATIVE_AI_AUTH_SCOPES","VERTEX_AI_AUTH_SCOPES"],"sources":["../../src/chat_models/node.ts"],"sourcesContent":["import { getEnvironmentVariable } from \"@langchain/core/utils/env\";\nimport { ChatGoogleParams } from \"./index.js\";\nimport {\n BaseChatGoogle,\n getGoogleChatModelParams,\n getPlatformType,\n} from \"./base.js\";\nimport { GENERATIVE_AI_AUTH_SCOPES, VERTEX_AI_AUTH_SCOPES } from \"../const.js\";\nimport {\n ensureAuthScopes,\n NodeApiClient,\n NodeApiClientParams,\n} from \"../clients/node.js\";\nimport { convertParamsToPlatformType } from \"../converters/params.js\";\n\ninterface ChatGoogleNodeParams extends NodeApiClientParams, ChatGoogleParams {}\n\nclass ChatGoogleNode extends BaseChatGoogle {\n constructor(model: string, params?: Omit<ChatGoogleNodeParams, \"model\">);\n constructor(params: ChatGoogleNodeParams);\n constructor(\n modelOrParams: string | ChatGoogleNodeParams,\n paramsArg?: Omit<ChatGoogleNodeParams, \"model\">\n ) {\n const params = getGoogleChatModelParams(modelOrParams, paramsArg);\n if (!params.googleAuthOptions) {\n params.apiKey = params.apiKey ?? getEnvironmentVariable(\"GOOGLE_API_KEY\");\n }\n const requiredScopes: string[] = getRequiredAuthScopes(params);\n if (params.googleAuthOptions) {\n params.googleAuthOptions = ensureAuthScopes(\n params.googleAuthOptions,\n requiredScopes\n );\n }\n const apiClient = params?.apiClient ?? new NodeApiClient(params);\n super({ ...params, apiClient });\n }\n}\n\nfunction getRequiredAuthScopes(params: ChatGoogleNodeParams): string[] {\n const hasApiKey = typeof params.apiKey !== \"undefined\";\n const platformType = convertParamsToPlatformType(params);\n const platform = getPlatformType(platformType, hasApiKey);\n switch (platform) {\n case \"gai\":\n return GENERATIVE_AI_AUTH_SCOPES;\n case \"gcp\":\n return VERTEX_AI_AUTH_SCOPES;\n default:\n return VERTEX_AI_AUTH_SCOPES;\n }\n}\n\nexport {\n type ChatGoogleNodeParams as ChatGoogleParams,\n ChatGoogleNode as ChatGoogle,\n};\n"],"mappings":";;;;;;AAiBA,IAAM,iBAAN,cAA6BA,aAAAA,eAAe;CAG1C,YACE,eACA,WACA;EACA,MAAM,SAASC,aAAAA,yBAAyB,eAAe,UAAU;AACjE,MAAI,CAAC,OAAO,kBACV,QAAO,SAAS,OAAO,WAAA,GAAA,0BAAA,wBAAiC,iBAAiB;EAE3E,MAAM,iBAA2B,sBAAsB,OAAO;AAC9D,MAAI,OAAO,kBACT,QAAO,oBAAoBC,aAAAA,iBACzB,OAAO,mBACP,eACD;EAEH,MAAM,YAAY,QAAQ,aAAa,IAAIC,aAAAA,cAAc,OAAO;AAChE,QAAM;GAAE,GAAG;GAAQ;GAAW,CAAC;;;AAInC,SAAS,sBAAsB,QAAwC;CACrE,MAAM,YAAY,OAAO,OAAO,WAAW;AAG3C,SADiBC,aAAAA,gBADIC,eAAAA,4BAA4B,OACJ,EAAE,UAC/B,EAAhB;EACE,KAAK,MACH,QAAOC,cAAAA;EACT,KAAK,MACH,QAAOC,cAAAA;EACT,QACE,QAAOA,cAAAA"}
@@ -1 +1 @@
1
- {"version":3,"file":"node.js","names":[],"sources":["../../src/chat_models/node.ts"],"sourcesContent":["import { getEnvironmentVariable } from \"@langchain/core/utils/env\";\nimport { ChatGoogleParams } from \"./index.js\";\nimport {\n BaseChatGoogle,\n getGoogleChatModelParams,\n getPlatformType,\n} from \"./base.js\";\nimport { GENERATIVE_AI_AUTH_SCOPES, VERTEX_AI_AUTH_SCOPES } from \"../const.js\";\nimport {\n ensureAuthScopes,\n NodeApiClient,\n NodeApiClientParams,\n} from \"../clients/node.js\";\nimport { convertParamsToPlatformType } from \"../converters/params.js\";\n\ninterface ChatGoogleNodeParams extends NodeApiClientParams, ChatGoogleParams {}\n\nclass ChatGoogleNode extends BaseChatGoogle {\n constructor(model: string, params?: Omit<ChatGoogleNodeParams, \"model\">);\n constructor(params: ChatGoogleNodeParams);\n constructor(\n modelOrParams: string | ChatGoogleNodeParams,\n paramsArg?: Omit<ChatGoogleNodeParams, \"model\">\n ) {\n const params = getGoogleChatModelParams(modelOrParams, paramsArg);\n if (!params.googleAuthOptions) {\n params.apiKey = params.apiKey ?? getEnvironmentVariable(\"GOOGLE_API_KEY\");\n }\n const requiredScopes: string[] = getRequiredAuthScopes(params);\n if (params.googleAuthOptions) {\n params.googleAuthOptions = ensureAuthScopes(\n params.googleAuthOptions,\n requiredScopes\n );\n }\n const apiClient = params?.apiClient ?? new NodeApiClient(params);\n super({ ...params, apiClient });\n }\n}\n\nfunction getRequiredAuthScopes(params: ChatGoogleNodeParams): string[] {\n const hasApiKey = typeof params.apiKey !== \"undefined\";\n const platformType = convertParamsToPlatformType(params);\n const platform = getPlatformType(platformType, hasApiKey);\n switch (platform) {\n case \"gai\":\n return GENERATIVE_AI_AUTH_SCOPES;\n case \"gcp\":\n return VERTEX_AI_AUTH_SCOPES;\n default:\n return VERTEX_AI_AUTH_SCOPES;\n }\n}\n\nexport {\n type ChatGoogleNodeParams as ChatGoogleParams,\n ChatGoogleNode as ChatGoogle,\n};\n"],"mappings":";;;;;;AAiBA,IAAM,iBAAN,cAA6B,eAAe;CAG1C,YACE,eACA,WACA;EACA,MAAM,SAAS,yBAAyB,eAAe,UAAU;AACjE,MAAI,CAAC,OAAO,kBACV,QAAO,SAAS,OAAO,UAAU,uBAAuB,iBAAiB;EAE3E,MAAM,iBAA2B,sBAAsB,OAAO;AAC9D,MAAI,OAAO,kBACT,QAAO,oBAAoB,iBACzB,OAAO,mBACP,eACD;EAEH,MAAM,YAAY,QAAQ,aAAa,IAAI,cAAc,OAAO;AAChE,QAAM;GAAE,GAAG;GAAQ;GAAW,CAAC;;;AAInC,SAAS,sBAAsB,QAAwC;CACrE,MAAM,YAAY,OAAO,OAAO,WAAW;AAG3C,SADiB,gBADI,4BAA4B,OAAO,EACT,UAAU,EACzD;EACE,KAAK,MACH,QAAO;EACT,KAAK,MACH,QAAO;EACT,QACE,QAAO"}
1
+ {"version":3,"file":"node.js","names":[],"sources":["../../src/chat_models/node.ts"],"sourcesContent":["import { getEnvironmentVariable } from \"@langchain/core/utils/env\";\nimport { ChatGoogleParams } from \"./index.js\";\nimport {\n BaseChatGoogle,\n getGoogleChatModelParams,\n getPlatformType,\n} from \"./base.js\";\nimport { GENERATIVE_AI_AUTH_SCOPES, VERTEX_AI_AUTH_SCOPES } from \"../const.js\";\nimport {\n ensureAuthScopes,\n NodeApiClient,\n NodeApiClientParams,\n} from \"../clients/node.js\";\nimport { convertParamsToPlatformType } from \"../converters/params.js\";\n\ninterface ChatGoogleNodeParams extends NodeApiClientParams, ChatGoogleParams {}\n\nclass ChatGoogleNode extends BaseChatGoogle {\n constructor(model: string, params?: Omit<ChatGoogleNodeParams, \"model\">);\n constructor(params: ChatGoogleNodeParams);\n constructor(\n modelOrParams: string | ChatGoogleNodeParams,\n paramsArg?: Omit<ChatGoogleNodeParams, \"model\">\n ) {\n const params = getGoogleChatModelParams(modelOrParams, paramsArg);\n if (!params.googleAuthOptions) {\n params.apiKey = params.apiKey ?? getEnvironmentVariable(\"GOOGLE_API_KEY\");\n }\n const requiredScopes: string[] = getRequiredAuthScopes(params);\n if (params.googleAuthOptions) {\n params.googleAuthOptions = ensureAuthScopes(\n params.googleAuthOptions,\n requiredScopes\n );\n }\n const apiClient = params?.apiClient ?? new NodeApiClient(params);\n super({ ...params, apiClient });\n }\n}\n\nfunction getRequiredAuthScopes(params: ChatGoogleNodeParams): string[] {\n const hasApiKey = typeof params.apiKey !== \"undefined\";\n const platformType = convertParamsToPlatformType(params);\n const platform = getPlatformType(platformType, hasApiKey);\n switch (platform) {\n case \"gai\":\n return GENERATIVE_AI_AUTH_SCOPES;\n case \"gcp\":\n return VERTEX_AI_AUTH_SCOPES;\n default:\n return VERTEX_AI_AUTH_SCOPES;\n }\n}\n\nexport {\n type ChatGoogleNodeParams as ChatGoogleParams,\n ChatGoogleNode as ChatGoogle,\n};\n"],"mappings":";;;;;;AAiBA,IAAM,iBAAN,cAA6B,eAAe;CAG1C,YACE,eACA,WACA;EACA,MAAM,SAAS,yBAAyB,eAAe,UAAU;AACjE,MAAI,CAAC,OAAO,kBACV,QAAO,SAAS,OAAO,UAAU,uBAAuB,iBAAiB;EAE3E,MAAM,iBAA2B,sBAAsB,OAAO;AAC9D,MAAI,OAAO,kBACT,QAAO,oBAAoB,iBACzB,OAAO,mBACP,eACD;EAEH,MAAM,YAAY,QAAQ,aAAa,IAAI,cAAc,OAAO;AAChE,QAAM;GAAE,GAAG;GAAQ;GAAW,CAAC;;;AAInC,SAAS,sBAAsB,QAAwC;CACrE,MAAM,YAAY,OAAO,OAAO,WAAW;AAG3C,SADiB,gBADI,4BAA4B,OACJ,EAAE,UAC/B,EAAhB;EACE,KAAK,MACH,QAAO;EACT,KAAK,MACH,QAAO;EACT,QACE,QAAO"}
@@ -0,0 +1,6 @@
1
+ //#region src/chat_models/types.ts
2
+ const settableServiceTier = ["flex", "priority"];
3
+ //#endregion
4
+ exports.settableServiceTier = settableServiceTier;
5
+
6
+ //# sourceMappingURL=types.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.cjs","names":[],"sources":["../../src/chat_models/types.ts"],"sourcesContent":["/* oxlint-disable @typescript-eslint/no-namespace */\n\nimport type { InteropZodType } from \"@langchain/core/utils/types\";\nimport type { BindToolsInput } from \"@langchain/core/language_models/chat_models\";\nimport type { Gemini as GeminiBase } from \"./api-types.js\";\nimport type { LowercaseLiteral, Prettify } from \"../utils/misc.js\";\n\nexport interface ChatGoogleFields {\n /**\n * The temperature is used for sampling during response generation, which\n * occurs when topP and topK are applied. Temperature controls the degree of\n * randomness in token selection. Lower temperatures are good for prompts that\n * require a less open-ended or creative response, while higher temperatures\n * can lead to more diverse or creative results.\n *\n * Specify a lower value for less random responses and a higher value for more\n * random responses.\n */\n temperature?: number;\n\n /**\n * Top-P changes how the model selects tokens for output. Tokens are selected\n * from the most probable to least probable until the sum of their\n * probabilities equals the top-P value.\n *\n * Specify a lower value for less random responses and a higher value for more\n * random responses.\n */\n topP?: number;\n\n /**\n * Top-K changes how the model selects tokens for output. A top-K of 1 means\n * the selected token is the most probable among all tokens in the model's\n * vocabulary (also called greedy decoding), while a top-K of 3 means that the\n * next token is selected from among the 3 most probable tokens (using\n * temperature).\n */\n topK?: number;\n\n /**\n * Maximum number of tokens that can be generated in the response. A token is\n * approximately four characters. 100 tokens correspond to roughly 60-80 words.\n * Specify a lower value for shorter responses and a higher value for\n * potentially longer responses.\n */\n maxOutputTokens?: number;\n\n /**\n * Positive values penalize tokens that already appear in the generated text,\n * increasing the probability of generating more diverse content.\n */\n presencePenalty?: number;\n\n /**\n * Positive values penalize tokens that repeatedly appear in the generated\n * text, decreasing the probability of repeating content.\n */\n frequencyPenalty?: number;\n\n /**\n * Specifies a list of strings that tells the model to stop generating text if\n * one of the strings is encountered in the response. If a string appears\n * multiple times in the response, then the response truncates where it's\n * first encountered. The strings are case-sensitive.\n */\n stopSequences?: string[];\n\n /**\n * When seed is fixed to a specific value, the model makes a best effort to\n * provide the same response for repeated requests. Deterministic output isn't\n * guaranteed. Also, changing the model or parameter settings, such as the\n * temperature, can cause variations in the response even when you use the\n * same seed value. By default, a random seed value is used.\n */\n seed?: number;\n\n /**\n * If true, returns the log probabilities of the tokens that were chosen by\n * the model at each step. By default, this parameter is set to false.\n */\n responseLogprobs?: boolean;\n\n /**\n * Returns the log probabilities of the top candidate tokens at each generation\n * step. The model's chosen token might not be the same as the top candidate\n * token at each step. Specify the number of candidates to return by using an\n * integer value in the range of 1-20.\n */\n logprobs?: number;\n\n /**\n * Per request settings for blocking unsafe content\n */\n safetySettings?: Prettify<GeminiBase.SafetySetting>[];\n\n /**\n * Configuration for the model's thinking process\n */\n thinkingConfig?: Prettify<GeminiBase.ThinkingConfig>;\n\n /**\n * The schema that the generated response should match.\n * Can be a Zod schema or a JSON Schema object.\n * When set, the response will be structured according to this schema\n * and `responseMimeType` will automatically be set to \"application/json\".\n */\n responseSchema?: InteropZodType | Record<string, unknown>;\n\n /**\n * A list of tools the model may use to generate the next response.\n * Can be LangChain tools, OpenAI tools, or Gemini function declarations.\n */\n tools?: BindToolsInput[];\n\n /**\n * The requested modalities of the response.\n * Represents the set of modalities that the model can return.\n * An empty list is equivalent to requesting only text.\n */\n responseModalities?: Prettify<GeminiBase.GenerativeLanguageModality>[];\n\n /**\n * If true, enables enhanced civic answers feature.\n */\n enableEnhancedCivicAnswers?: boolean;\n\n /**\n * Speech generation configuration.\n * You can use either Google's definition of the speech configuration,\n * or a simplified version we've defined (which can be as simple\n * as the name of a pre-defined voice).\n */\n speechConfig?: Prettify<GeminiBase.SpeechConfig> | SimplifiedSpeechConfig;\n\n /**\n * Configuration for image generation.\n */\n imageConfig?: Prettify<GeminiBase.ImageConfig>;\n\n /**\n * Media resolution for input media processing.\n *\n * This maps to `generationConfig.mediaResolution`, which is a scalar enum-like\n * string value in the Gemini API.\n */\n mediaResolution?: GeminiBase.GenerationConfig[\"mediaResolution\"];\n\n /**\n * OpenAI-compatible alias for media input detail level.\n *\n * This is mapped to `generationConfig.mediaResolution`:\n * - `\"auto\"` => default Gemini behavior (`mediaResolution` omitted)\n * - `\"low\"` => `\"MEDIA_RESOLUTION_LOW\"`\n * - `\"high\"` => `\"MEDIA_RESOLUTION_HIGH\"`\n *\n * If both `mediaResolution` and `detail` are provided, `mediaResolution` wins.\n */\n detail?: \"auto\" | \"low\" | \"high\";\n\n /**\n * The number of reasoning tokens that the model should generate.\n * If explicitly set, then the reasoning blocks will be returned.\n */\n maxReasoningTokens?: number;\n\n /**\n * An alias for `maxReasoningTokens` for compatibility.\n */\n thinkingBudget?: number;\n\n /**\n * An alias for `maxReasoningTokens` under Gemini 2.5 or\n * the primary thinking/reasoning setting for Gemini 3.\n * If explicitly set, then the reasoning blocks will be returned.\n */\n reasoningEffort?: GeminiBase.ThinkingLevel;\n\n /**\n * An alias for `reasoningEffort` for compatibility.\n */\n thinkingLevel?: GeminiBase.ThinkingLevel;\n\n /**\n * Inference service tiers.\n * \"priority\" offers highest reliability for higher rates.\n * \"flex\" offers a discount for preemptable processing.\n * Other values are treated as the standard service tier.\n */\n serviceTier?: GeminiBase.ServiceTier;\n\n /**\n * Custom / additional headers to include with every request to the API.\n * When set on both constructor params and per-invocation call options,\n * per-invocation headers take precidence for matching keys.\n */\n customHeaders?: Record<string, string>;\n}\n\nexport type GooglePlatformType = \"gai\" | \"gcp\";\n\n// These are service tiers that we specifically need to send.\n// Other values will be ignored, resulting in the default\n// or \"standard\" setting.\nexport const settableServiceTier: GeminiBase.ServiceTier[] = [\n \"flex\",\n \"priority\",\n];\n\nexport { type Gemini } from \"./api-types.js\";\n\n// There's a fair number of utilities that we need to extract from the base\n// Gemini OpenAPI types, Adding these directly to the base types\n// would pollute the typegen output, so we're adding them here instead.\ndeclare module \"./api-types.js\" {\n export namespace Gemini {\n // Gemini parts are contained as one intersecting type\n // in the spec, so we need to pick out the specific parts we need.\n export namespace Part {\n export type CodeExecutionResult = Pick<\n GeminiBase.Part,\n \"codeExecutionResult\"\n >;\n export type ExecutableCode = Pick<GeminiBase.Part, \"executableCode\">;\n export type FileData = Pick<\n GeminiBase.Part,\n \"fileData\" | \"videoMetadata\"\n >;\n export type FunctionCall = Required<\n Pick<GeminiBase.Part, \"functionCall\">\n > &\n Pick<GeminiBase.Part, \"thoughtSignature\">;\n export type FunctionResponse = Pick<GeminiBase.Part, \"functionResponse\">;\n export type InlineData = Pick<\n GeminiBase.Part,\n \"inlineData\" | \"videoMetadata\"\n >;\n export type MediaResolution = Pick<GeminiBase.Part, \"mediaResolution\">;\n export type PartMetadata = Pick<GeminiBase.Part, \"partMetadata\">;\n export type Text = Pick<GeminiBase.Part, \"text\">;\n export type Thought = Pick<GeminiBase.Part, \"thought\">;\n export type ThoughtSignature = Pick<GeminiBase.Part, \"thoughtSignature\">;\n }\n\n export namespace PrebuiltVoiceConfig {\n /**\n * The name of a prebuilt voice that can be used for speech synthesis.\n *\n * Extracted as a non-nullable type from the GeminiBase.PrebuiltVoiceConfig[\"voiceName\"] property.\n */\n export type VoiceName = NonNullable<\n GeminiBase.PrebuiltVoiceConfig[\"voiceName\"]\n >;\n }\n\n export namespace SpeakerVoiceConfig {\n /**\n * The speaker identifier for a custom or multi-speaker TTS configuration.\n *\n * Extracted as a non-nullable type from the GeminiBase.SpeakerVoiceConfig[\"speaker\"] property.\n */\n export type Speaker = NonNullable<\n GeminiBase.SpeakerVoiceConfig[\"speaker\"]\n >;\n }\n\n export namespace SpeechConfig {\n /**\n * The BCP-47 language code for speech synthesis (e.g., \"en-US\").\n *\n * Extracted as a non-nullable type from the GeminiBase.SpeechConfig[\"languageCode\"] property.\n */\n export type LanguageCode = NonNullable<\n GeminiBase.SpeechConfig[\"languageCode\"]\n >;\n }\n\n /**\n * The level of \"thinking\" or reasoning configured for the model.\n *\n * Extends GeminiBase.ThinkingConfig[\"thinkingLevel\"] to also accept\n * lowercase variants (e.g. \"high\" in addition to \"HIGH\").\n */\n export type ThinkingLevel =\n | GeminiBase.ThinkingConfig[\"thinkingLevel\"]\n | LowercaseLiteral<GeminiBase.ThinkingConfig[\"thinkingLevel\"]>;\n\n /**\n * The role of a content message. The spec types this as `string`, but\n * the API only accepts these specific values.\n */\n export type Role = \"user\" | \"model\" | \"function\";\n\n /**\n * Alias for the unwieldy generated grounding support type name.\n */\n export type GroundingSupport =\n GeminiBase.GoogleAiGenerativelanguageV1betaGroundingSupport;\n\n /**\n * Alias for the unwieldy generated segment type name.\n */\n export type Segment = GeminiBase.GoogleAiGenerativelanguageV1betaSegment;\n\n export namespace Tools {\n /**\n * The mode for function calling configuration, extracted from the\n * FunctionCallingConfig interface.\n */\n export type FunctionCallingConfigMode =\n GeminiBase.Tools.FunctionCallingConfig[\"mode\"];\n }\n\n /**\n * Legacy URL retrieval metadata (predecessor of UrlContextMetadata).\n * Not in the current OpenAPI spec but still returned by the API.\n */\n export interface UrlRetrievalMetadata {\n urlRetrievalContexts?: Array<GeminiBase.UrlMetadata>;\n }\n\n // Augment Candidate with legacy field the API still returns.\n export interface Candidate {\n /** @deprecated Use urlContextMetadata instead. */\n readonly urlRetrievalMetadata?: UrlRetrievalMetadata;\n }\n }\n}\n\n/**\n * Simplified speaker/name pair for multi-speaker config.\n * - `speaker` derived from SpeakerVoiceConfig[\"speaker\"]\n * - `name` is the prebuilt voice name\n */\nexport interface SpeechSpeakerName {\n speaker: GeminiBase.SpeakerVoiceConfig.Speaker;\n name: GeminiBase.PrebuiltVoiceConfig.VoiceName;\n}\n\n/** A voice can be a prebuilt voice name, a speaker/name pair, or an array of pairs */\nexport type SpeechVoice =\n | GeminiBase.PrebuiltVoiceConfig.VoiceName\n | SpeechSpeakerName\n | SpeechSpeakerName[];\n\n/** Voice with language code (derived from SpeechConfig's languageCode) */\nexport interface SpeechVoiceLanguage {\n voice: SpeechVoice;\n languageCode: GeminiBase.SpeechConfig.LanguageCode;\n}\n\n/** Voices with language code */\nexport interface SpeechVoicesLanguage {\n voices: SpeechVoice;\n languageCode: GeminiBase.SpeechConfig.LanguageCode;\n}\n\n/** Simplified language config (with voice or voices) */\nexport type SimplifiedSpeechLanguageConfig =\n | SpeechVoiceLanguage\n | SpeechVoicesLanguage;\n\n/** Top-level simplified config: just a voice, or voice+language */\nexport type SimplifiedSpeechConfig =\n | SpeechVoice\n | SimplifiedSpeechLanguageConfig;\n"],"mappings":";AA2MA,MAAa,sBAAgD,CAC3D,QACA,WACD"}
@@ -155,6 +155,19 @@ interface ChatGoogleFields {
155
155
  * An alias for `reasoningEffort` for compatibility.
156
156
  */
157
157
  thinkingLevel?: Gemini.ThinkingLevel;
158
+ /**
159
+ * Inference service tiers.
160
+ * "priority" offers highest reliability for higher rates.
161
+ * "flex" offers a discount for preemptable processing.
162
+ * Other values are treated as the standard service tier.
163
+ */
164
+ serviceTier?: Gemini.ServiceTier;
165
+ /**
166
+ * Custom / additional headers to include with every request to the API.
167
+ * When set on both constructor params and per-invocation call options,
168
+ * per-invocation headers take precidence for matching keys.
169
+ */
170
+ customHeaders?: Record<string, string>;
158
171
  }
159
172
  declare module "./api-types.js" {
160
173
  namespace Gemini {
@@ -155,6 +155,19 @@ interface ChatGoogleFields {
155
155
  * An alias for `reasoningEffort` for compatibility.
156
156
  */
157
157
  thinkingLevel?: Gemini.ThinkingLevel;
158
+ /**
159
+ * Inference service tiers.
160
+ * "priority" offers highest reliability for higher rates.
161
+ * "flex" offers a discount for preemptable processing.
162
+ * Other values are treated as the standard service tier.
163
+ */
164
+ serviceTier?: Gemini.ServiceTier;
165
+ /**
166
+ * Custom / additional headers to include with every request to the API.
167
+ * When set on both constructor params and per-invocation call options,
168
+ * per-invocation headers take precidence for matching keys.
169
+ */
170
+ customHeaders?: Record<string, string>;
158
171
  }
159
172
  declare module "./api-types.js" {
160
173
  namespace Gemini {
@@ -0,0 +1,6 @@
1
+ //#region src/chat_models/types.ts
2
+ const settableServiceTier = ["flex", "priority"];
3
+ //#endregion
4
+ export { settableServiceTier };
5
+
6
+ //# sourceMappingURL=types.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.js","names":[],"sources":["../../src/chat_models/types.ts"],"sourcesContent":["/* oxlint-disable @typescript-eslint/no-namespace */\n\nimport type { InteropZodType } from \"@langchain/core/utils/types\";\nimport type { BindToolsInput } from \"@langchain/core/language_models/chat_models\";\nimport type { Gemini as GeminiBase } from \"./api-types.js\";\nimport type { LowercaseLiteral, Prettify } from \"../utils/misc.js\";\n\nexport interface ChatGoogleFields {\n /**\n * The temperature is used for sampling during response generation, which\n * occurs when topP and topK are applied. Temperature controls the degree of\n * randomness in token selection. Lower temperatures are good for prompts that\n * require a less open-ended or creative response, while higher temperatures\n * can lead to more diverse or creative results.\n *\n * Specify a lower value for less random responses and a higher value for more\n * random responses.\n */\n temperature?: number;\n\n /**\n * Top-P changes how the model selects tokens for output. Tokens are selected\n * from the most probable to least probable until the sum of their\n * probabilities equals the top-P value.\n *\n * Specify a lower value for less random responses and a higher value for more\n * random responses.\n */\n topP?: number;\n\n /**\n * Top-K changes how the model selects tokens for output. A top-K of 1 means\n * the selected token is the most probable among all tokens in the model's\n * vocabulary (also called greedy decoding), while a top-K of 3 means that the\n * next token is selected from among the 3 most probable tokens (using\n * temperature).\n */\n topK?: number;\n\n /**\n * Maximum number of tokens that can be generated in the response. A token is\n * approximately four characters. 100 tokens correspond to roughly 60-80 words.\n * Specify a lower value for shorter responses and a higher value for\n * potentially longer responses.\n */\n maxOutputTokens?: number;\n\n /**\n * Positive values penalize tokens that already appear in the generated text,\n * increasing the probability of generating more diverse content.\n */\n presencePenalty?: number;\n\n /**\n * Positive values penalize tokens that repeatedly appear in the generated\n * text, decreasing the probability of repeating content.\n */\n frequencyPenalty?: number;\n\n /**\n * Specifies a list of strings that tells the model to stop generating text if\n * one of the strings is encountered in the response. If a string appears\n * multiple times in the response, then the response truncates where it's\n * first encountered. The strings are case-sensitive.\n */\n stopSequences?: string[];\n\n /**\n * When seed is fixed to a specific value, the model makes a best effort to\n * provide the same response for repeated requests. Deterministic output isn't\n * guaranteed. Also, changing the model or parameter settings, such as the\n * temperature, can cause variations in the response even when you use the\n * same seed value. By default, a random seed value is used.\n */\n seed?: number;\n\n /**\n * If true, returns the log probabilities of the tokens that were chosen by\n * the model at each step. By default, this parameter is set to false.\n */\n responseLogprobs?: boolean;\n\n /**\n * Returns the log probabilities of the top candidate tokens at each generation\n * step. The model's chosen token might not be the same as the top candidate\n * token at each step. Specify the number of candidates to return by using an\n * integer value in the range of 1-20.\n */\n logprobs?: number;\n\n /**\n * Per request settings for blocking unsafe content\n */\n safetySettings?: Prettify<GeminiBase.SafetySetting>[];\n\n /**\n * Configuration for the model's thinking process\n */\n thinkingConfig?: Prettify<GeminiBase.ThinkingConfig>;\n\n /**\n * The schema that the generated response should match.\n * Can be a Zod schema or a JSON Schema object.\n * When set, the response will be structured according to this schema\n * and `responseMimeType` will automatically be set to \"application/json\".\n */\n responseSchema?: InteropZodType | Record<string, unknown>;\n\n /**\n * A list of tools the model may use to generate the next response.\n * Can be LangChain tools, OpenAI tools, or Gemini function declarations.\n */\n tools?: BindToolsInput[];\n\n /**\n * The requested modalities of the response.\n * Represents the set of modalities that the model can return.\n * An empty list is equivalent to requesting only text.\n */\n responseModalities?: Prettify<GeminiBase.GenerativeLanguageModality>[];\n\n /**\n * If true, enables enhanced civic answers feature.\n */\n enableEnhancedCivicAnswers?: boolean;\n\n /**\n * Speech generation configuration.\n * You can use either Google's definition of the speech configuration,\n * or a simplified version we've defined (which can be as simple\n * as the name of a pre-defined voice).\n */\n speechConfig?: Prettify<GeminiBase.SpeechConfig> | SimplifiedSpeechConfig;\n\n /**\n * Configuration for image generation.\n */\n imageConfig?: Prettify<GeminiBase.ImageConfig>;\n\n /**\n * Media resolution for input media processing.\n *\n * This maps to `generationConfig.mediaResolution`, which is a scalar enum-like\n * string value in the Gemini API.\n */\n mediaResolution?: GeminiBase.GenerationConfig[\"mediaResolution\"];\n\n /**\n * OpenAI-compatible alias for media input detail level.\n *\n * This is mapped to `generationConfig.mediaResolution`:\n * - `\"auto\"` => default Gemini behavior (`mediaResolution` omitted)\n * - `\"low\"` => `\"MEDIA_RESOLUTION_LOW\"`\n * - `\"high\"` => `\"MEDIA_RESOLUTION_HIGH\"`\n *\n * If both `mediaResolution` and `detail` are provided, `mediaResolution` wins.\n */\n detail?: \"auto\" | \"low\" | \"high\";\n\n /**\n * The number of reasoning tokens that the model should generate.\n * If explicitly set, then the reasoning blocks will be returned.\n */\n maxReasoningTokens?: number;\n\n /**\n * An alias for `maxReasoningTokens` for compatibility.\n */\n thinkingBudget?: number;\n\n /**\n * An alias for `maxReasoningTokens` under Gemini 2.5 or\n * the primary thinking/reasoning setting for Gemini 3.\n * If explicitly set, then the reasoning blocks will be returned.\n */\n reasoningEffort?: GeminiBase.ThinkingLevel;\n\n /**\n * An alias for `reasoningEffort` for compatibility.\n */\n thinkingLevel?: GeminiBase.ThinkingLevel;\n\n /**\n * Inference service tiers.\n * \"priority\" offers highest reliability for higher rates.\n * \"flex\" offers a discount for preemptable processing.\n * Other values are treated as the standard service tier.\n */\n serviceTier?: GeminiBase.ServiceTier;\n\n /**\n * Custom / additional headers to include with every request to the API.\n * When set on both constructor params and per-invocation call options,\n * per-invocation headers take precidence for matching keys.\n */\n customHeaders?: Record<string, string>;\n}\n\nexport type GooglePlatformType = \"gai\" | \"gcp\";\n\n// These are service tiers that we specifically need to send.\n// Other values will be ignored, resulting in the default\n// or \"standard\" setting.\nexport const settableServiceTier: GeminiBase.ServiceTier[] = [\n \"flex\",\n \"priority\",\n];\n\nexport { type Gemini } from \"./api-types.js\";\n\n// There's a fair number of utilities that we need to extract from the base\n// Gemini OpenAPI types, Adding these directly to the base types\n// would pollute the typegen output, so we're adding them here instead.\ndeclare module \"./api-types.js\" {\n export namespace Gemini {\n // Gemini parts are contained as one intersecting type\n // in the spec, so we need to pick out the specific parts we need.\n export namespace Part {\n export type CodeExecutionResult = Pick<\n GeminiBase.Part,\n \"codeExecutionResult\"\n >;\n export type ExecutableCode = Pick<GeminiBase.Part, \"executableCode\">;\n export type FileData = Pick<\n GeminiBase.Part,\n \"fileData\" | \"videoMetadata\"\n >;\n export type FunctionCall = Required<\n Pick<GeminiBase.Part, \"functionCall\">\n > &\n Pick<GeminiBase.Part, \"thoughtSignature\">;\n export type FunctionResponse = Pick<GeminiBase.Part, \"functionResponse\">;\n export type InlineData = Pick<\n GeminiBase.Part,\n \"inlineData\" | \"videoMetadata\"\n >;\n export type MediaResolution = Pick<GeminiBase.Part, \"mediaResolution\">;\n export type PartMetadata = Pick<GeminiBase.Part, \"partMetadata\">;\n export type Text = Pick<GeminiBase.Part, \"text\">;\n export type Thought = Pick<GeminiBase.Part, \"thought\">;\n export type ThoughtSignature = Pick<GeminiBase.Part, \"thoughtSignature\">;\n }\n\n export namespace PrebuiltVoiceConfig {\n /**\n * The name of a prebuilt voice that can be used for speech synthesis.\n *\n * Extracted as a non-nullable type from the GeminiBase.PrebuiltVoiceConfig[\"voiceName\"] property.\n */\n export type VoiceName = NonNullable<\n GeminiBase.PrebuiltVoiceConfig[\"voiceName\"]\n >;\n }\n\n export namespace SpeakerVoiceConfig {\n /**\n * The speaker identifier for a custom or multi-speaker TTS configuration.\n *\n * Extracted as a non-nullable type from the GeminiBase.SpeakerVoiceConfig[\"speaker\"] property.\n */\n export type Speaker = NonNullable<\n GeminiBase.SpeakerVoiceConfig[\"speaker\"]\n >;\n }\n\n export namespace SpeechConfig {\n /**\n * The BCP-47 language code for speech synthesis (e.g., \"en-US\").\n *\n * Extracted as a non-nullable type from the GeminiBase.SpeechConfig[\"languageCode\"] property.\n */\n export type LanguageCode = NonNullable<\n GeminiBase.SpeechConfig[\"languageCode\"]\n >;\n }\n\n /**\n * The level of \"thinking\" or reasoning configured for the model.\n *\n * Extends GeminiBase.ThinkingConfig[\"thinkingLevel\"] to also accept\n * lowercase variants (e.g. \"high\" in addition to \"HIGH\").\n */\n export type ThinkingLevel =\n | GeminiBase.ThinkingConfig[\"thinkingLevel\"]\n | LowercaseLiteral<GeminiBase.ThinkingConfig[\"thinkingLevel\"]>;\n\n /**\n * The role of a content message. The spec types this as `string`, but\n * the API only accepts these specific values.\n */\n export type Role = \"user\" | \"model\" | \"function\";\n\n /**\n * Alias for the unwieldy generated grounding support type name.\n */\n export type GroundingSupport =\n GeminiBase.GoogleAiGenerativelanguageV1betaGroundingSupport;\n\n /**\n * Alias for the unwieldy generated segment type name.\n */\n export type Segment = GeminiBase.GoogleAiGenerativelanguageV1betaSegment;\n\n export namespace Tools {\n /**\n * The mode for function calling configuration, extracted from the\n * FunctionCallingConfig interface.\n */\n export type FunctionCallingConfigMode =\n GeminiBase.Tools.FunctionCallingConfig[\"mode\"];\n }\n\n /**\n * Legacy URL retrieval metadata (predecessor of UrlContextMetadata).\n * Not in the current OpenAPI spec but still returned by the API.\n */\n export interface UrlRetrievalMetadata {\n urlRetrievalContexts?: Array<GeminiBase.UrlMetadata>;\n }\n\n // Augment Candidate with legacy field the API still returns.\n export interface Candidate {\n /** @deprecated Use urlContextMetadata instead. */\n readonly urlRetrievalMetadata?: UrlRetrievalMetadata;\n }\n }\n}\n\n/**\n * Simplified speaker/name pair for multi-speaker config.\n * - `speaker` derived from SpeakerVoiceConfig[\"speaker\"]\n * - `name` is the prebuilt voice name\n */\nexport interface SpeechSpeakerName {\n speaker: GeminiBase.SpeakerVoiceConfig.Speaker;\n name: GeminiBase.PrebuiltVoiceConfig.VoiceName;\n}\n\n/** A voice can be a prebuilt voice name, a speaker/name pair, or an array of pairs */\nexport type SpeechVoice =\n | GeminiBase.PrebuiltVoiceConfig.VoiceName\n | SpeechSpeakerName\n | SpeechSpeakerName[];\n\n/** Voice with language code (derived from SpeechConfig's languageCode) */\nexport interface SpeechVoiceLanguage {\n voice: SpeechVoice;\n languageCode: GeminiBase.SpeechConfig.LanguageCode;\n}\n\n/** Voices with language code */\nexport interface SpeechVoicesLanguage {\n voices: SpeechVoice;\n languageCode: GeminiBase.SpeechConfig.LanguageCode;\n}\n\n/** Simplified language config (with voice or voices) */\nexport type SimplifiedSpeechLanguageConfig =\n | SpeechVoiceLanguage\n | SpeechVoicesLanguage;\n\n/** Top-level simplified config: just a voice, or voice+language */\nexport type SimplifiedSpeechConfig =\n | SpeechVoice\n | SimplifiedSpeechLanguageConfig;\n"],"mappings":";AA2MA,MAAa,sBAAgD,CAC3D,QACA,WACD"}