@langchain/google 0.2.3 → 0.2.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,45 @@
1
1
  # @langchain/google
2
2
 
3
+ ## 0.2.5
4
+
5
+ ### Patch Changes
6
+
7
+ - [#10047](https://github.com/langchain-ai/langchainjs/pull/10047) [`ff1248f`](https://github.com/langchain-ai/langchainjs/commit/ff1248fd49dacdb35f5da128278cd777068481d7) Thanks [@afirstenberg](https://github.com/afirstenberg)! - fix(core): BaseMessage.text use contentBlocks
8
+
9
+ - [#11574](https://github.com/langchain-ai/langchainjs/pull/11574) [`5c89094`](https://github.com/langchain-ai/langchainjs/commit/5c8909465416c4751a58552dbc29257e2f19b051) Thanks [@afirstenberg](https://github.com/afirstenberg)! - This addresses four specific issues:
10
+
11
+ - "thought" and "thoughtSignature" not being present in the conversation
12
+ history sent to Gemini when using v0 messages
13
+ - "thought" and "thoughtSignature" not being present in the conversation history sent to Gemini when using v1 messages
14
+ - "thoughtSignature" not being present in v1 tool calls specifically
15
+ - ContentBlock.Reasoning not being handled in v1 at all
16
+
17
+ It does so by, largely, keeping the existing logic converting from LangChain representation to a Google.Part in both the v0 (legacy) and v1 (standard) paths intact. (This is done in both in the messages.ts file.)
18
+
19
+ - In convertLegacyContentMessageToGeminiContent(), the conversion is moved to a new function: convertLegacyPartToGeminiPart() for consistency with the standard path and to standardize where and how the thought/thoughtSignature fields are added
20
+ - Both convertLegacyPartToGeminiPart() and convertStandardContentBlockToGeminiPart() get a baseGeminiPart() function that returns the Gemini.Part without the thought or thoughtSignature fields
21
+ - Both then add the additional fields, if necessary, independent of what the underlying Gemini.Part is.
22
+
23
+ The last point is done because Gemini can attach "thought" or "thoughtSignature" to any block type. Not just text.
24
+
25
+ ## 0.2.4
26
+
27
+ ### Patch Changes
28
+
29
+ - [#11426](https://github.com/langchain-ai/langchainjs/pull/11426) [`2e865ea`](https://github.com/langchain-ai/langchainjs/commit/2e865ea06047d6a71e9fb694dfb0dee5c1a46f4b) Thanks [@thushanth-bengre-langchain](https://github.com/thushanth-bengre-langchain)! - fix: keep image/audio/video content in ToolMessages as sibling Gemini parts instead of losing it inside functionResponse.response.result JSON, and stop double-stringifying non-string tool results ([#10297](https://github.com/langchain-ai/langchainjs/issues/10297), [#10439](https://github.com/langchain-ai/langchainjs/issues/10439))
30
+
31
+ - [#11477](https://github.com/langchain-ai/langchainjs/pull/11477) [`9a0f244`](https://github.com/langchain-ai/langchainjs/commit/9a0f244c161412ba54c7308e635ce773abc88c4a) Thanks [@hntrl](https://github.com/hntrl)! - Fix `convertMessagesToGeminiContents` merging a `ToolMessage` (functionResponse)
32
+ with a following `HumanMessage` (text) into one `user` content. Both map to the
33
+ `user` role, and Vertex/Gemini rejects a single `user` content that mixes a
34
+ `functionResponse` with text, so a tool result followed by a user message would
35
+ fail with a 400. Merging is now limited to runs of adjacent tool results
36
+ (parallel tool calls), which the API requires to be grouped into one content;
37
+ all other same-role contents stay separate.
38
+
39
+ Also fixes the v1 standard-content path, where a single `ToolMessage` could emit
40
+ a `user` content mixing its `functionResponse` part with text parts; tool turns
41
+ now carry only their functionResponse part(s), mirroring the legacy path.
42
+
3
43
  ## 0.2.3
4
44
 
5
45
  ### Patch Changes
@@ -107,7 +107,7 @@ var BaseChatGoogle = class extends _langchain_core_language_models_chat_models.B
107
107
  constructor(params) {
108
108
  super(params);
109
109
  this.params = params;
110
- this._addVersion("@langchain/google", "0.2.3");
110
+ this._addVersion("@langchain/google", "0.2.5");
111
111
  if (!params.apiClient) throw new require_errors.ConfigurationError("BaseChatGoogle requires an apiClient. This should be provided automatically by ChatGoogle constructors. If you're extending BaseChatGoogle directly, please provide an apiClient instance.");
112
112
  this.apiClient = params.apiClient;
113
113
  this.model = params.model;
@@ -1 +1 @@
1
- {"version":3,"file":"base.cjs","names":["convertParamsToPlatformType","BaseChatModel","ConfigurationError","PROFILES","convertToolsToGeminiTools","convertToolChoiceToGeminiConfig","convertFieldsToThinkingConfig","convertFieldsToSpeechConfig","convertFieldsToServiceTier","settableServiceTier","convertMessagesToGeminiSystemInstruction","convertMessagesToGeminiContents","RequestError","PromptBlockedError","NoCandidatesError","convertGeminiCandidateToAIMessage","convertAIMessageToText","convertGeminiGenerateContentResponseToUsageMetadata","iife","EventSourceParserStream","SafeJsonEventParserStream","convertGoogleGeminiStream","ChatGenerationChunk","AIMessageChunk","convertGeminiPartsToToolCalls","subtractUsageMetadata","RunnableLambda","AIMessage","MalformedOutputError","schemaToGeminiParameters"],"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 { resolveLangSmithGatewayConfig } from \"@langchain/core/utils/gateway\";\nimport { getEnvironmentVariable } from \"@langchain/core/utils/env\";\nimport ServiceTier = Gemini.ServiceTier;\n\nexport type GooglePlatformType = \"gai\" | \"gcp\";\n\n/**\n * Returns true when the params (or environment) configure Vertex AI /\n * service-account authentication, which the LangSmith gateway does not proxy.\n *\n * This covers the cases `convertParamsToPlatformType` cannot see: explicit\n * service-account `credentials`, the `GOOGLE_CLOUD_CREDENTIALS` env var, and\n * Node-only `googleAuthOptions` (Application Default Credentials). Without this\n * check a credentials-only model would resolve to `gcp` today, but injecting a\n * gateway API key below would flip it to `gai` and misroute the request to the\n * Gemini Developer API gateway path.\n */\nfunction hasVertexCredentials(params: {\n credentials?: unknown;\n googleAuthOptions?: unknown;\n}): boolean {\n return (\n typeof params.credentials !== \"undefined\" ||\n typeof params.googleAuthOptions !== \"undefined\" ||\n typeof getEnvironmentVariable(\"GOOGLE_CLOUD_CREDENTIALS\") !== \"undefined\"\n );\n}\n\n/**\n * Resolves LangSmith gateway routing for Google chat model params.\n *\n * The LangSmith gateway proxies the **Gemini Developer API** (the API-key,\n * `gai` platform), not Vertex AI. So this only applies when the resolved\n * platform is `gai` and the caller has not set an explicit `endpoint`. An\n * explicit `endpoint`, a Vertex configuration (`vertexai: true` /\n * `platformType: \"gcp\"`), or service-account credentials (`credentials`,\n * `googleAuthOptions`, or `GOOGLE_CLOUD_CREDENTIALS`) suppress gateway routing\n * entirely.\n *\n * When `LANGSMITH_GATEWAY` is set, this rewrites `endpoint` to the gateway\n * host and lets the gateway key take precedence over the provider key (which\n * then rides as the `x-goog-api-key` header via the ApiClient). The default\n * `https` gateway host is written scheme-less (the URL builders prepend\n * `https://`); a non-`https` custom gateway keeps its scheme so it is not\n * forced to TLS.\n *\n * This function is pure: it never mutates `params`. It returns a new object\n * with the gateway overrides applied when routing is active, or an unchanged\n * shallow copy otherwise.\n *\n * @returns a new params object with gateway routing applied when applicable.\n */\nexport function applyGeminiGatewayParams<\n TParams extends {\n apiKey?: string;\n endpoint?: string;\n platformType?: GooglePlatformType;\n vertexai?: boolean;\n credentials?: unknown;\n googleAuthOptions?: unknown;\n },\n>(params: TParams): TParams & { apiKey?: string; endpoint?: string } {\n // An explicit endpoint always wins; a Vertex config is out of scope (the\n // gateway proxies the Gemini Developer API, not Vertex AI).\n if (typeof params.endpoint !== \"undefined\") {\n return { ...params };\n }\n const explicitPlatform = convertParamsToPlatformType(params);\n if (explicitPlatform === \"gcp\" || hasVertexCredentials(params)) {\n return { ...params };\n }\n\n const gatewayConfig = resolveLangSmithGatewayConfig({\n providerPath: \"gemini\",\n });\n if (typeof gatewayConfig.baseURL === \"undefined\") {\n return { ...params };\n }\n\n // When routing through the gateway with no explicitly requested platform and\n // no credentials that would imply Vertex, treat this as a Gemini Developer\n // API (`gai`) call. A provider key still wins over the gateway key.\n const gatewayUrl = new URL(gatewayConfig.baseURL);\n const path = gatewayUrl.pathname.replace(/\\/+$/, \"\");\n // The URL builders compose `https://${endpoint}/${apiVersion}/...`. For the\n // default `https` gateway, keep the endpoint scheme-less (host + path) so the\n // builder's `https://` prefix produces the right URL. For a non-`https`\n // custom gateway (e.g. `http://localhost:8080`), keep the full scheme so the\n // builder does not force TLS; `buildUrlGemini` skips its prefix when the\n // endpoint already includes a scheme.\n const endpoint =\n gatewayUrl.protocol === \"https:\"\n ? `${gatewayUrl.host}${path}`\n : `${gatewayUrl.protocol}//${gatewayUrl.host}${path}`;\n return {\n ...params,\n apiKey: params.apiKey ?? gatewayConfig.apiKey,\n endpoint,\n };\n}\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 // `endpoint` is normally scheme-less (e.g. `generativelanguage.googleapis.com`)\n // and defaults to `https`, but a gateway endpoint may already carry a scheme\n // and a base path (e.g. a custom `http://` LangSmith gateway). Let `URL`\n // resolve the scheme so a custom `http://` gateway is not forced to TLS.\n const url = this.endpoint.includes(\"://\")\n ? new URL(this.endpoint)\n : new URL(`https://${this.endpoint}`);\n // `urlMethod` may include a query string (e.g. `streamGenerateContent?alt=sse`);\n // split it out so `URL` keeps it as a query rather than encoding the `?`.\n const [method, search] = (urlMethod ?? this.urlMethod).split(\"?\", 2);\n const basePath = url.pathname.replace(/\\/+$/, \"\");\n url.pathname = `${basePath}/${this.apiVersion}/models/${this.model}:${method}`;\n if (search) {\n url.search = search;\n }\n return url.toString();\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 let response: Response;\n try {\n response = await this.caller.callWithOptions(\n { signal: options.signal, maxRetries: options.maxRetries },\n async () => {\n const nextResponse = 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 (!nextResponse.ok) {\n throw await RequestError.fromResponse(nextResponse);\n }\n\n return nextResponse;\n }\n );\n } catch (error) {\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 let response: Response;\n try {\n response = await this.caller.callWithOptions(\n { signal: options.signal, maxRetries: options.maxRetries },\n async () => {\n const nextResponse = 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 (!nextResponse.ok) {\n throw await RequestError.fromResponse(nextResponse);\n }\n\n return nextResponse;\n }\n );\n } catch (error) {\n await runManager?.handleCustomEvent(`google-response-${moduleName}`, {\n error,\n });\n throw error;\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.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":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA8FA,SAAS,qBAAqB,QAGlB;CACV,OACE,OAAO,OAAO,gBAAgB,eAC9B,OAAO,OAAO,sBAAsB,eACpC,QAAA,GAAA,0BAAA,uBAAA,C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B,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;CAClC;CACA,IAAI,KAAK,SAAS,GAChB,OAAO,6BAA6B,UAAU,KAAK,IAAI,GAAG,KAAK,MAAM,CAAC,CAAC;CAEzE,OAAO;AACT;AAEA,SAAgB,yBACd,eACA,WACS;CAIT,OAAO;EAAE,OAFP,OAAO,kBAAkB,WAAW,gBAAgB,cAAc;EAEpD,GADD,OAAO,kBAAkB,WAAW,YAAY;CACrC;AAC5B"}
1
+ {"version":3,"file":"base.cjs","names":["getEnvironmentVariable","convertParamsToPlatformType","resolveLangSmithGatewayConfig","BaseChatModel","ConfigurationError","PROFILES","convertToolsToGeminiTools","convertToolChoiceToGeminiConfig","isInteropZodSchema","isSerializableSchema","toJsonSchema","convertFieldsToThinkingConfig","convertFieldsToSpeechConfig","convertFieldsToServiceTier","settableServiceTier","concat","convertMessagesToGeminiSystemInstruction","convertMessagesToGeminiContents","RequestError","PromptBlockedError","NoCandidatesError","convertGeminiCandidateToAIMessage","convertAIMessageToText","convertGeminiGenerateContentResponseToUsageMetadata","iife","EventSourceParserStream","SafeJsonEventParserStream","convertGoogleGeminiStream","ChatGenerationChunk","AIMessageChunk","convertGeminiPartsToToolCalls","subtractUsageMetadata","RunnableLambda","AIMessage","MalformedOutputError","createContentParser","schemaToGeminiParameters","createFunctionCallingParser","assembleStructuredOutputPipeline"],"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 { resolveLangSmithGatewayConfig } from \"@langchain/core/utils/gateway\";\nimport { getEnvironmentVariable } from \"@langchain/core/utils/env\";\nimport ServiceTier = Gemini.ServiceTier;\n\nexport type GooglePlatformType = \"gai\" | \"gcp\";\n\n/**\n * Returns true when the params (or environment) configure Vertex AI /\n * service-account authentication, which the LangSmith gateway does not proxy.\n *\n * This covers the cases `convertParamsToPlatformType` cannot see: explicit\n * service-account `credentials`, the `GOOGLE_CLOUD_CREDENTIALS` env var, and\n * Node-only `googleAuthOptions` (Application Default Credentials). Without this\n * check a credentials-only model would resolve to `gcp` today, but injecting a\n * gateway API key below would flip it to `gai` and misroute the request to the\n * Gemini Developer API gateway path.\n */\nfunction hasVertexCredentials(params: {\n credentials?: unknown;\n googleAuthOptions?: unknown;\n}): boolean {\n return (\n typeof params.credentials !== \"undefined\" ||\n typeof params.googleAuthOptions !== \"undefined\" ||\n typeof getEnvironmentVariable(\"GOOGLE_CLOUD_CREDENTIALS\") !== \"undefined\"\n );\n}\n\n/**\n * Resolves LangSmith gateway routing for Google chat model params.\n *\n * The LangSmith gateway proxies the **Gemini Developer API** (the API-key,\n * `gai` platform), not Vertex AI. So this only applies when the resolved\n * platform is `gai` and the caller has not set an explicit `endpoint`. An\n * explicit `endpoint`, a Vertex configuration (`vertexai: true` /\n * `platformType: \"gcp\"`), or service-account credentials (`credentials`,\n * `googleAuthOptions`, or `GOOGLE_CLOUD_CREDENTIALS`) suppress gateway routing\n * entirely.\n *\n * When `LANGSMITH_GATEWAY` is set, this rewrites `endpoint` to the gateway\n * host and lets the gateway key take precedence over the provider key (which\n * then rides as the `x-goog-api-key` header via the ApiClient). The default\n * `https` gateway host is written scheme-less (the URL builders prepend\n * `https://`); a non-`https` custom gateway keeps its scheme so it is not\n * forced to TLS.\n *\n * This function is pure: it never mutates `params`. It returns a new object\n * with the gateway overrides applied when routing is active, or an unchanged\n * shallow copy otherwise.\n *\n * @returns a new params object with gateway routing applied when applicable.\n */\nexport function applyGeminiGatewayParams<\n TParams extends {\n apiKey?: string;\n endpoint?: string;\n platformType?: GooglePlatformType;\n vertexai?: boolean;\n credentials?: unknown;\n googleAuthOptions?: unknown;\n },\n>(params: TParams): TParams & { apiKey?: string; endpoint?: string } {\n // An explicit endpoint always wins; a Vertex config is out of scope (the\n // gateway proxies the Gemini Developer API, not Vertex AI).\n if (typeof params.endpoint !== \"undefined\") {\n return { ...params };\n }\n const explicitPlatform = convertParamsToPlatformType(params);\n if (explicitPlatform === \"gcp\" || hasVertexCredentials(params)) {\n return { ...params };\n }\n\n const gatewayConfig = resolveLangSmithGatewayConfig({\n providerPath: \"gemini\",\n });\n if (typeof gatewayConfig.baseURL === \"undefined\") {\n return { ...params };\n }\n\n // When routing through the gateway with no explicitly requested platform and\n // no credentials that would imply Vertex, treat this as a Gemini Developer\n // API (`gai`) call. A provider key still wins over the gateway key.\n const gatewayUrl = new URL(gatewayConfig.baseURL);\n const path = gatewayUrl.pathname.replace(/\\/+$/, \"\");\n // The URL builders compose `https://${endpoint}/${apiVersion}/...`. For the\n // default `https` gateway, keep the endpoint scheme-less (host + path) so the\n // builder's `https://` prefix produces the right URL. For a non-`https`\n // custom gateway (e.g. `http://localhost:8080`), keep the full scheme so the\n // builder does not force TLS; `buildUrlGemini` skips its prefix when the\n // endpoint already includes a scheme.\n const endpoint =\n gatewayUrl.protocol === \"https:\"\n ? `${gatewayUrl.host}${path}`\n : `${gatewayUrl.protocol}//${gatewayUrl.host}${path}`;\n return {\n ...params,\n apiKey: params.apiKey ?? gatewayConfig.apiKey,\n endpoint,\n };\n}\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 // `endpoint` is normally scheme-less (e.g. `generativelanguage.googleapis.com`)\n // and defaults to `https`, but a gateway endpoint may already carry a scheme\n // and a base path (e.g. a custom `http://` LangSmith gateway). Let `URL`\n // resolve the scheme so a custom `http://` gateway is not forced to TLS.\n const url = this.endpoint.includes(\"://\")\n ? new URL(this.endpoint)\n : new URL(`https://${this.endpoint}`);\n // `urlMethod` may include a query string (e.g. `streamGenerateContent?alt=sse`);\n // split it out so `URL` keeps it as a query rather than encoding the `?`.\n const [method, search] = (urlMethod ?? this.urlMethod).split(\"?\", 2);\n const basePath = url.pathname.replace(/\\/+$/, \"\");\n url.pathname = `${basePath}/${this.apiVersion}/models/${this.model}:${method}`;\n if (search) {\n url.search = search;\n }\n return url.toString();\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 let response: Response;\n try {\n response = await this.caller.callWithOptions(\n { signal: options.signal, maxRetries: options.maxRetries },\n async () => {\n const nextResponse = 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 (!nextResponse.ok) {\n throw await RequestError.fromResponse(nextResponse);\n }\n\n return nextResponse;\n }\n );\n } catch (error) {\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 let response: Response;\n try {\n response = await this.caller.callWithOptions(\n { signal: options.signal, maxRetries: options.maxRetries },\n async () => {\n const nextResponse = 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 (!nextResponse.ok) {\n throw await RequestError.fromResponse(nextResponse);\n }\n\n return nextResponse;\n }\n );\n } catch (error) {\n await runManager?.handleCustomEvent(`google-response-${moduleName}`, {\n error,\n });\n throw error;\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.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":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA8FA,SAAS,qBAAqB,QAGlB;CACV,OACE,OAAO,OAAO,gBAAgB,eAC9B,OAAO,OAAO,sBAAsB,eACpC,QAAA,GAAOA,0BAAAA,uBAAAA,CAAuB,0BAA0B,MAAM;AAElE;;;;;;;;;;;;;;;;;;;;;;;;;AA0BA,SAAgB,yBASd,QAAmE;CAGnE,IAAI,OAAO,OAAO,aAAa,aAC7B,OAAO,EAAE,GAAG,OAAO;CAGrB,IADyBC,eAAAA,4BAA4B,MAClC,MAAM,SAAS,qBAAqB,MAAM,GAC3D,OAAO,EAAE,GAAG,OAAO;CAGrB,MAAM,iBAAA,GAAgBC,8BAAAA,8BAAAA,CAA8B,EAClD,cAAc,SAChB,CAAC;CACD,IAAI,OAAO,cAAc,YAAY,aACnC,OAAO,EAAE,GAAG,OAAO;CAMrB,MAAM,aAAa,IAAI,IAAI,cAAc,OAAO;CAChD,MAAM,OAAO,WAAW,SAAS,QAAQ,QAAQ,EAAE;CAOnD,MAAM,WACJ,WAAW,aAAa,WACpB,GAAG,WAAW,OAAO,SACrB,GAAG,WAAW,SAAS,IAAI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class extends BaseChatModel {
107
107
  constructor(params) {
108
108
  super(params);
109
109
  this.params = params;
110
- this._addVersion("@langchain/google", "0.2.3");
110
+ this._addVersion("@langchain/google", "0.2.5");
111
111
  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.");
112
112
  this.apiClient = params.apiClient;
113
113
  this.model = params.model;
@@ -1 +1 @@
1
- {"version":3,"file":"index.cjs","names":["BaseChatGoogle","getGoogleChatModelParams","applyGeminiGatewayParams","WebApiClient"],"sources":["../../src/chat_models/index.ts"],"sourcesContent":["import { getEnvironmentVariable } from \"@langchain/core/utils/env\";\nimport { WebApiClient } from \"../clients/index.js\";\nimport {\n applyGeminiGatewayParams,\n BaseChatGoogle,\n BaseChatGoogleCallOptions,\n BaseChatGoogleParams,\n getGoogleChatModelParams,\n} from \"./base.js\";\n\n/**\n * Configuration parameters for the ChatGoogle model.\n *\n * This interface extends the base Google chat model parameters and adds\n * specific configuration options for the Generative AI API.\n */\nexport interface ChatGoogleParams extends BaseChatGoogleParams {\n /**\n * Google API key for authentication with the Generative AI API.\n *\n * If not provided, the model will attempt to use the `GOOGLE_API_KEY`\n * environment variable. You can obtain an API key from the\n * [Google AI Studio](https://makersuite.google.com/app/apikey).\n */\n apiKey?: string;\n\n /** @deprecated Import from `@langchain/google/node` to configure google auth options */\n authOptions?: never;\n}\n\n/**\n * Call options for the ChatGoogle model.\n *\n * This interface extends the base Google chat model call options and provides\n * configuration for individual model invocations. These options can be passed\n * when calling methods like `invoke()`, `stream()`, or `batch()` to customize\n * the behavior of a specific request.\n */\nexport interface ChatGoogleCallOptions extends BaseChatGoogleCallOptions {}\n\nexport class ChatGoogle extends BaseChatGoogle<ChatGoogleCallOptions> {\n apiKey?: string;\n\n constructor(model: string, params?: Omit<ChatGoogleParams, \"model\">);\n constructor(params: ChatGoogleParams);\n constructor(\n modelOrParams: string | ChatGoogleParams,\n paramsArg?: Omit<ChatGoogleParams, \"model\">\n ) {\n let params = getGoogleChatModelParams(modelOrParams, paramsArg);\n // Route through the LangSmith gateway (Gemini Developer API path) when\n // configured, before falling back to the provider API-key env var so the\n // gateway key can take precedence.\n params = applyGeminiGatewayParams(params);\n params.apiKey = params?.apiKey ?? getEnvironmentVariable(\"GOOGLE_API_KEY\");\n const apiClient = params?.apiClient ?? new WebApiClient(params);\n super({ ...params, apiClient });\n\n this.apiKey = params.apiKey;\n }\n}\n"],"mappings":";;;;AAwCA,IAAa,aAAb,cAAgCA,aAAAA,eAAsC;CACpE;CAIA,YACE,eACA,WACA;EACA,IAAI,SAASC,aAAAA,yBAAyB,eAAe,SAAS;EAI9D,SAASC,aAAAA,yBAAyB,MAAM;EACxC,OAAO,SAAS,QAAQ,WAAA,GAAA,0BAAA,uBAAA,CAAiC,gBAAgB;EACzE,MAAM,YAAY,QAAQ,aAAa,IAAIC,cAAAA,aAAa,MAAM;EAC9D,MAAM;GAAE,GAAG;GAAQ;EAAU,CAAC;EAE9B,KAAK,SAAS,OAAO;CACvB;AACF"}
1
+ {"version":3,"file":"index.cjs","names":["BaseChatGoogle","getGoogleChatModelParams","applyGeminiGatewayParams","getEnvironmentVariable","WebApiClient"],"sources":["../../src/chat_models/index.ts"],"sourcesContent":["import { getEnvironmentVariable } from \"@langchain/core/utils/env\";\nimport { WebApiClient } from \"../clients/index.js\";\nimport {\n applyGeminiGatewayParams,\n BaseChatGoogle,\n BaseChatGoogleCallOptions,\n BaseChatGoogleParams,\n getGoogleChatModelParams,\n} from \"./base.js\";\n\n/**\n * Configuration parameters for the ChatGoogle model.\n *\n * This interface extends the base Google chat model parameters and adds\n * specific configuration options for the Generative AI API.\n */\nexport interface ChatGoogleParams extends BaseChatGoogleParams {\n /**\n * Google API key for authentication with the Generative AI API.\n *\n * If not provided, the model will attempt to use the `GOOGLE_API_KEY`\n * environment variable. You can obtain an API key from the\n * [Google AI Studio](https://makersuite.google.com/app/apikey).\n */\n apiKey?: string;\n\n /** @deprecated Import from `@langchain/google/node` to configure google auth options */\n authOptions?: never;\n}\n\n/**\n * Call options for the ChatGoogle model.\n *\n * This interface extends the base Google chat model call options and provides\n * configuration for individual model invocations. These options can be passed\n * when calling methods like `invoke()`, `stream()`, or `batch()` to customize\n * the behavior of a specific request.\n */\nexport interface ChatGoogleCallOptions extends BaseChatGoogleCallOptions {}\n\nexport class ChatGoogle extends BaseChatGoogle<ChatGoogleCallOptions> {\n apiKey?: string;\n\n constructor(model: string, params?: Omit<ChatGoogleParams, \"model\">);\n constructor(params: ChatGoogleParams);\n constructor(\n modelOrParams: string | ChatGoogleParams,\n paramsArg?: Omit<ChatGoogleParams, \"model\">\n ) {\n let params = getGoogleChatModelParams(modelOrParams, paramsArg);\n // Route through the LangSmith gateway (Gemini Developer API path) when\n // configured, before falling back to the provider API-key env var so the\n // gateway key can take precedence.\n params = applyGeminiGatewayParams(params);\n params.apiKey = params?.apiKey ?? getEnvironmentVariable(\"GOOGLE_API_KEY\");\n const apiClient = params?.apiClient ?? new WebApiClient(params);\n super({ ...params, apiClient });\n\n this.apiKey = params.apiKey;\n }\n}\n"],"mappings":";;;;AAwCA,IAAa,aAAb,cAAgCA,aAAAA,eAAsC;CACpE;CAIA,YACE,eACA,WACA;EACA,IAAI,SAASC,aAAAA,yBAAyB,eAAe,SAAS;EAI9D,SAASC,aAAAA,yBAAyB,MAAM;EACxC,OAAO,SAAS,QAAQ,WAAA,GAAUC,0BAAAA,uBAAAA,CAAuB,gBAAgB;EACzE,MAAM,YAAY,QAAQ,aAAa,IAAIC,cAAAA,aAAa,MAAM;EAC9D,MAAM;GAAE,GAAG;GAAQ;EAAU,CAAC;EAE9B,KAAK,SAAS,OAAO;CACvB;AACF"}
@@ -22,7 +22,8 @@ var ChatGoogleNode = class extends require_base.BaseChatGoogle {
22
22
  };
23
23
  function getRequiredAuthScopes(params) {
24
24
  const hasApiKey = typeof params.apiKey !== "undefined";
25
- switch (require_base.getPlatformType(require_params.convertParamsToPlatformType(params), hasApiKey)) {
25
+ const platformType = require_params.convertParamsToPlatformType(params);
26
+ switch (require_base.getPlatformType(platformType, hasApiKey)) {
26
27
  case "gai": return require_const.GENERATIVE_AI_AUTH_SCOPES;
27
28
  case "gcp": return require_const.VERTEX_AI_AUTH_SCOPES;
28
29
  default: return require_const.VERTEX_AI_AUTH_SCOPES;
@@ -1 +1 @@
1
- {"version":3,"file":"node.cjs","names":["BaseChatGoogle","getGoogleChatModelParams","applyGeminiGatewayParams","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 applyGeminiGatewayParams,\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 let params = getGoogleChatModelParams(modelOrParams, paramsArg);\n if (!params.googleAuthOptions) {\n // Route through the LangSmith gateway (Gemini Developer API path) when\n // configured, before falling back to the provider API-key env var so the\n // gateway key can take precedence. Skipped when Vertex OAuth\n // (`googleAuthOptions`) is used, which the gateway does not proxy.\n params = applyGeminiGatewayParams(params);\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":";;;;;;AAkBA,IAAM,iBAAN,cAA6BA,aAAAA,eAAe;CAG1C,YACE,eACA,WACA;EACA,IAAI,SAASC,aAAAA,yBAAyB,eAAe,SAAS;EAC9D,IAAI,CAAC,OAAO,mBAAmB;GAK7B,SAASC,aAAAA,yBAAyB,MAAM;GACxC,OAAO,SAAS,OAAO,WAAA,GAAA,0BAAA,uBAAA,CAAiC,gBAAgB;EAC1E;EACA,MAAM,iBAA2B,sBAAsB,MAAM;EAC7D,IAAI,OAAO,mBACT,OAAO,oBAAoBC,aAAAA,iBACzB,OAAO,mBACP,cACF;EAEF,MAAM,YAAY,QAAQ,aAAa,IAAIC,aAAAA,cAAc,MAAM;EAC/D,MAAM;GAAE,GAAG;GAAQ;EAAU,CAAC;CAChC;AACF;AAEA,SAAS,sBAAsB,QAAwC;CACrE,MAAM,YAAY,OAAO,OAAO,WAAW;CAG3C,QADiBC,aAAAA,gBADIC,eAAAA,4BAA4B,MACL,GAAG,SAChC,GAAf;EACE,KAAK,OACH,OAAOC,cAAAA;EACT,KAAK,OACH,OAAOC,cAAAA;EACT,SACE,OAAOA,cAAAA;CACX;AACF"}
1
+ {"version":3,"file":"node.cjs","names":["BaseChatGoogle","getGoogleChatModelParams","applyGeminiGatewayParams","getEnvironmentVariable","ensureAuthScopes","NodeApiClient","convertParamsToPlatformType","getPlatformType","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 applyGeminiGatewayParams,\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 let params = getGoogleChatModelParams(modelOrParams, paramsArg);\n if (!params.googleAuthOptions) {\n // Route through the LangSmith gateway (Gemini Developer API path) when\n // configured, before falling back to the provider API-key env var so the\n // gateway key can take precedence. Skipped when Vertex OAuth\n // (`googleAuthOptions`) is used, which the gateway does not proxy.\n params = applyGeminiGatewayParams(params);\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":";;;;;;AAkBA,IAAM,iBAAN,cAA6BA,aAAAA,eAAe;CAG1C,YACE,eACA,WACA;EACA,IAAI,SAASC,aAAAA,yBAAyB,eAAe,SAAS;EAC9D,IAAI,CAAC,OAAO,mBAAmB;GAK7B,SAASC,aAAAA,yBAAyB,MAAM;GACxC,OAAO,SAAS,OAAO,WAAA,GAAUC,0BAAAA,uBAAAA,CAAuB,gBAAgB;EAC1E;EACA,MAAM,iBAA2B,sBAAsB,MAAM;EAC7D,IAAI,OAAO,mBACT,OAAO,oBAAoBC,aAAAA,iBACzB,OAAO,mBACP,cACF;EAEF,MAAM,YAAY,QAAQ,aAAa,IAAIC,aAAAA,cAAc,MAAM;EAC/D,MAAM;GAAE,GAAG;GAAQ;EAAU,CAAC;CAChC;AACF;AAEA,SAAS,sBAAsB,QAAwC;CACrE,MAAM,YAAY,OAAO,OAAO,WAAW;CAC3C,MAAM,eAAeC,eAAAA,4BAA4B,MAAM;CAEvD,QADiBC,aAAAA,gBAAgB,cAAc,SAChC,GAAf;EACE,KAAK,OACH,OAAOC,cAAAA;EACT,KAAK,OACH,OAAOC,cAAAA;EACT,SACE,OAAOA,cAAAA;CACX;AACF"}
@@ -22,7 +22,8 @@ var ChatGoogleNode = class extends BaseChatGoogle {
22
22
  };
23
23
  function getRequiredAuthScopes(params) {
24
24
  const hasApiKey = typeof params.apiKey !== "undefined";
25
- switch (getPlatformType(convertParamsToPlatformType(params), hasApiKey)) {
25
+ const platformType = convertParamsToPlatformType(params);
26
+ switch (getPlatformType(platformType, hasApiKey)) {
26
27
  case "gai": return GENERATIVE_AI_AUTH_SCOPES;
27
28
  case "gcp": return VERTEX_AI_AUTH_SCOPES;
28
29
  default: return VERTEX_AI_AUTH_SCOPES;
@@ -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 applyGeminiGatewayParams,\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 let params = getGoogleChatModelParams(modelOrParams, paramsArg);\n if (!params.googleAuthOptions) {\n // Route through the LangSmith gateway (Gemini Developer API path) when\n // configured, before falling back to the provider API-key env var so the\n // gateway key can take precedence. Skipped when Vertex OAuth\n // (`googleAuthOptions`) is used, which the gateway does not proxy.\n params = applyGeminiGatewayParams(params);\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":";;;;;;AAkBA,IAAM,iBAAN,cAA6B,eAAe;CAG1C,YACE,eACA,WACA;EACA,IAAI,SAAS,yBAAyB,eAAe,SAAS;EAC9D,IAAI,CAAC,OAAO,mBAAmB;GAK7B,SAAS,yBAAyB,MAAM;GACxC,OAAO,SAAS,OAAO,UAAU,uBAAuB,gBAAgB;EAC1E;EACA,MAAM,iBAA2B,sBAAsB,MAAM;EAC7D,IAAI,OAAO,mBACT,OAAO,oBAAoB,iBACzB,OAAO,mBACP,cACF;EAEF,MAAM,YAAY,QAAQ,aAAa,IAAI,cAAc,MAAM;EAC/D,MAAM;GAAE,GAAG;GAAQ;EAAU,CAAC;CAChC;AACF;AAEA,SAAS,sBAAsB,QAAwC;CACrE,MAAM,YAAY,OAAO,OAAO,WAAW;CAG3C,QADiB,gBADI,4BAA4B,MACL,GAAG,SAChC,GAAf;EACE,KAAK,OACH,OAAO;EACT,KAAK,OACH,OAAO;EACT,SACE,OAAO;CACX;AACF"}
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 applyGeminiGatewayParams,\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 let params = getGoogleChatModelParams(modelOrParams, paramsArg);\n if (!params.googleAuthOptions) {\n // Route through the LangSmith gateway (Gemini Developer API path) when\n // configured, before falling back to the provider API-key env var so the\n // gateway key can take precedence. Skipped when Vertex OAuth\n // (`googleAuthOptions`) is used, which the gateway does not proxy.\n params = applyGeminiGatewayParams(params);\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":";;;;;;AAkBA,IAAM,iBAAN,cAA6B,eAAe;CAG1C,YACE,eACA,WACA;EACA,IAAI,SAAS,yBAAyB,eAAe,SAAS;EAC9D,IAAI,CAAC,OAAO,mBAAmB;GAK7B,SAAS,yBAAyB,MAAM;GACxC,OAAO,SAAS,OAAO,UAAU,uBAAuB,gBAAgB;EAC1E;EACA,MAAM,iBAA2B,sBAAsB,MAAM;EAC7D,IAAI,OAAO,mBACT,OAAO,oBAAoB,iBACzB,OAAO,mBACP,cACF;EAEF,MAAM,YAAY,QAAQ,aAAa,IAAI,cAAc,MAAM;EAC/D,MAAM;GAAE,GAAG;GAAQ;EAAU,CAAC;CAChC;AACF;AAEA,SAAS,sBAAsB,QAAwC;CACrE,MAAM,YAAY,OAAO,OAAO,WAAW;CAC3C,MAAM,eAAe,4BAA4B,MAAM;CAEvD,QADiB,gBAAgB,cAAc,SAChC,GAAf;EACE,KAAK,OACH,OAAO;EACT,KAAK,OACH,OAAO;EACT,SACE,OAAO;CACX;AACF"}
@@ -1 +1 @@
1
- {"version":3,"file":"index.cjs","names":["iife","normalizeGCPCredentials","AuthError","GOOGLE_API_KEY_HEADER","GCP_API_KEY_HEADER","getGCPCredentialsAccessToken"],"sources":["../../src/clients/index.ts"],"sourcesContent":["import { getEnvironmentVariable } from \"@langchain/core/utils/env\";\nimport { GCP_API_KEY_HEADER, GOOGLE_API_KEY_HEADER } from \"../const.js\";\nimport {\n GCPCredentials,\n getGCPCredentialsAccessToken,\n normalizeGCPCredentials,\n} from \"../utils/gcp-auth.js\";\nimport { AuthError } from \"../utils/errors.js\";\nimport { iife } from \"../utils/misc.js\";\n\n/**\n * Abstract base class for API clients that interact with Google services.\n *\n * This class defines the contract for API clients, requiring implementations\n * to provide a fetch method that handles HTTP requests with appropriate\n * authentication headers. Concrete implementations should handle different\n * authentication strategies (API keys, service account credentials, etc.)\n * based on the runtime environment.\n *\n * @abstract\n *\n * @example\n * ```typescript\n * class MyApiClient extends ApiClient {\n * async fetch(request: Request): Promise<Response> {\n * // Add authentication headers\n * request.headers.set('Authorization', 'Bearer token');\n * return fetch(request);\n * }\n * }\n * ```\n */\nexport abstract class ApiClient {\n /**\n * Has an API Key been set for this client?\n */\n abstract hasApiKey(): boolean;\n\n /**\n * For some credential methods, we know what the project ID is.\n * This is necessary for OAuth-based access to Vertex\n */\n async getProjectId(): Promise<string> {\n return \"unknown-project-id\";\n }\n\n /**\n * Executes an HTTP request with appropriate authentication.\n *\n * Implementations should add necessary authentication headers to the request\n * before forwarding it to the underlying fetch implementation.\n *\n * @param request - The HTTP request to execute\n * @returns A Promise that resolves to the HTTP response\n *\n * @abstract\n */\n abstract fetch(request: Request): Promise<Response>;\n}\n\n/**\n * Configuration parameters for the WebApiClient.\n *\n * This interface defines the authentication options available for web-based\n * API clients. Authentication can be provided via an API key or GCP service\n * account credentials. The client will automatically check environment variables\n * if explicit values are not provided.\n *\n * @interface\n */\nexport interface WebApiClientParams {\n /**\n * Google API key for authentication.\n *\n * If not provided, the client will attempt to read from the\n * `GOOGLE_API_KEY` environment variable.\n *\n * @see https://cloud.google.com/docs/authentication/api-keys\n */\n apiKey?: string;\n\n /**\n * GCP service account credentials for authentication.\n *\n * Can be provided as either:\n * - A JSON string containing the service account key\n * - A GCPCredentials object\n *\n * If not provided, the client will attempt to read from the\n * `GOOGLE_CLOUD_CREDENTIALS` environment variable.\n *\n * @see https://cloud.google.com/iam/docs/creating-managing-service-account-keys\n */\n credentials?: string | GCPCredentials;\n\n /**\n * Google Auth options configuration.\n *\n * @deprecated This option is not supported in web environments.\n * Import from `@langchain/google/node` to configure google auth options\n * using the NodeApiClient instead.\n */\n googleAuthOptions?: never;\n}\n\n/**\n * Web-compatible API client for Google services.\n *\n * This client provides authentication for Google API requests in web environments\n * (browsers, edge functions, etc.) where the google-auth-library is not available.\n * It supports two authentication methods:\n *\n * 1. **API Key Authentication**: Simple key-based authentication suitable for\n * public APIs and client-side applications.\n *\n * 2. **Service Account Credentials**: OAuth2-based authentication using GCP\n * service account keys. The client automatically handles token generation\n * and caching.\n *\n * The client follows this authentication priority:\n * 1. Explicit `apiKey` parameter\n * 2. `GOOGLE_API_KEY` environment variable\n * 3. Explicit `credentials` parameter\n * 4. `GOOGLE_CLOUD_CREDENTIALS` environment variable\n *\n * @extends ApiClient\n *\n * @example\n * ```typescript\n * // Using API key\n * const client = new WebApiClient({\n * apiKey: 'your-api-key'\n * });\n *\n * // Using service account credentials\n * const client = new WebApiClient({\n * credentials: {\n * type: \"service_account\",\n * project_id: \"my-project\",\n * private_key_id: \"key-id\",\n * private_key: \"-----BEGIN PRIVATE KEY-----\\n...\",\n * client_email: \"service-account@project.iam.gserviceaccount.com\",\n * // ... other required fields\n * }\n * });\n *\n * // Using environment variables\n * // Set GOOGLE_API_KEY or GOOGLE_CLOUD_CREDENTIALS\n * const client = new WebApiClient({});\n *\n * // Make authenticated requests\n * const request = new Request('https://api.google.com/...');\n * const response = await client.fetch(request);\n * ```\n *\n * @remarks\n * - API keys are added via the `X-Goog-Api-Key` header\n * - Service account tokens are added via the `Authorization` header with Bearer scheme\n * - Tokens are automatically cached and refreshed as needed\n * - For Node.js environments with advanced auth requirements, use NodeApiClient instead\n *\n * @see {@link NodeApiClient} for Node.js-specific authentication options\n * @see {@link GCPCredentials} for service account credential structure\n */\nexport class WebApiClient extends ApiClient {\n hasApiKey(): boolean {\n return typeof this.apiKey === \"string\" && this.apiKey !== \"\";\n }\n\n async getProjectId(): Promise<string> {\n if (typeof this.credentials !== \"undefined\") {\n return this.credentials.project_id;\n } else {\n return super.getProjectId();\n }\n }\n\n /**\n * The Google API key used for authentication, if provided.\n *\n * This value is resolved from either the constructor parameter or the\n * `GOOGLE_API_KEY` environment variable.\n *\n * @protected\n */\n protected apiKey?: string;\n\n /**\n * The normalized GCP service account credentials, if provided.\n *\n * This value is resolved from either the constructor parameter or the\n * `GOOGLE_CLOUD_CREDENTIALS` environment variable, and is normalized\n * to ensure immutability.\n *\n * @protected\n */\n protected credentials?: GCPCredentials;\n\n /**\n * Creates a new WebApiClient instance.\n *\n * The constructor initializes authentication credentials by checking:\n * 1. Explicit parameters passed to the constructor\n * 2. Environment variables (`GOOGLE_API_KEY`, `GOOGLE_CLOUD_CREDENTIALS`)\n *\n * Credentials are normalized and frozen to prevent accidental modification.\n *\n * @param params - Configuration parameters for the client\n *\n * @example\n * ```typescript\n * // Minimal configuration (uses environment variables)\n * const client = new WebApiClient({});\n *\n * // With explicit API key\n * const client = new WebApiClient({\n * apiKey: 'your-api-key'\n * });\n *\n * // With service account credentials as JSON string\n * const client = new WebApiClient({\n * credentials: '{\"type\":\"service_account\",...}'\n * });\n *\n * // With service account credentials as object\n * const client = new WebApiClient({\n * credentials: {\n * type: \"service_account\",\n * // ... other fields\n * }\n * });\n * ```\n */\n constructor(protected params: WebApiClientParams) {\n super();\n this.apiKey = params.apiKey ?? getEnvironmentVariable(\"GOOGLE_API_KEY\");\n this.credentials = iife(() => {\n if (params.credentials) {\n return normalizeGCPCredentials(params.credentials);\n }\n const credentialsVar = getEnvironmentVariable(\"GOOGLE_CLOUD_CREDENTIALS\");\n if (credentialsVar) {\n return normalizeGCPCredentials(credentialsVar);\n }\n return undefined;\n });\n }\n\n /**\n * Executes an HTTP request with appropriate Google API authentication.\n *\n * This method adds authentication headers to the request based on the\n * configured authentication method:\n *\n * - If an API key is configured, adds the `X-Goog-Api-Key` header\n * - If service account credentials are configured, generates an access token\n * and adds it via the `Authorization` header with Bearer scheme\n *\n * The authentication priority is:\n * 1. API key (if provided)\n * 2. Service account credentials (if provided)\n *\n * @param request - The HTTP request to execute. Headers will be modified\n * in-place to include authentication information.\n * @returns A Promise that resolves to the HTTP response\n *\n * @throws {AuthError} If no authentication method is available (neither apiKey\n * nor credentials), or if service account authentication\n * fails (e.g., invalid credentials, network error, or\n * token generation failure)\n *\n * @example\n * ```typescript\n * const client = new WebApiClient({ apiKey: 'your-key' });\n * const request = new Request('https://generativelanguage.googleapis.com/v1/models');\n * const response = await client.fetch(request);\n * const data = await response.json();\n * ```\n *\n * @remarks\n * - The request object is modified in-place by adding headers\n * - Service account tokens are automatically cached and refreshed\n * - If both API key and credentials are provided, API key takes precedence\n */\n async fetch(request: Request): Promise<Response> {\n if (!this.apiKey && !this.credentials) {\n throw new AuthError({\n message:\n \"No authentication method available. Please provide either an apiKey or credentials.\",\n });\n }\n if (this.apiKey) {\n request.headers.set(GOOGLE_API_KEY_HEADER, this.apiKey);\n }\n if (this.credentials) {\n request.headers.set(\n GCP_API_KEY_HEADER,\n `Bearer ${await getGCPCredentialsAccessToken(this.credentials)}`\n );\n }\n return fetch(request);\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAgCA,IAAsB,YAAtB,MAAgC;;;;;CAU9B,MAAM,eAAgC;EACpC,OAAO;CACT;AAcF;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA0GA,IAAa,eAAb,cAAkC,UAAU;CAqEpB;CApEtB,YAAqB;EACnB,OAAO,OAAO,KAAK,WAAW,YAAY,KAAK,WAAW;CAC5D;CAEA,MAAM,eAAgC;EACpC,IAAI,OAAO,KAAK,gBAAgB,aAC9B,OAAO,KAAK,YAAY;OAExB,OAAO,MAAM,aAAa;CAE9B;;;;;;;;;CAUA;;;;;;;;;;CAWA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAqCA,YAAY,QAAsC;EAChD,MAAM;EADc,KAAA,SAAA;EAEpB,KAAK,SAAS,OAAO,WAAA,GAAA,0BAAA,uBAAA,CAAiC,gBAAgB;EACtE,KAAK,cAAcA,aAAAA,WAAW;GAC5B,IAAI,OAAO,aACT,OAAOC,iBAAAA,wBAAwB,OAAO,WAAW;GAEnD,MAAM,kBAAA,GAAA,0BAAA,uBAAA,CAAwC,0BAA0B;GACxE,IAAI,gBACF,OAAOA,iBAAAA,wBAAwB,cAAc;EAGjD,CAAC;CACH;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAsCA,MAAM,MAAM,SAAqC;EAC/C,IAAI,CAAC,KAAK,UAAU,CAAC,KAAK,aACxB,MAAM,IAAIC,eAAAA,UAAU,EAClB,SACE,sFACJ,CAAC;EAEH,IAAI,KAAK,QACP,QAAQ,QAAQ,IAAIC,cAAAA,uBAAuB,KAAK,MAAM;EAExD,IAAI,KAAK,aACP,QAAQ,QAAQ,IACdC,cAAAA,oBACA,UAAU,MAAMC,iBAAAA,6BAA6B,KAAK,WAAW,GAC/D;EAEF,OAAO,MAAM,OAAO;CACtB;AACF"}
1
+ {"version":3,"file":"index.cjs","names":["getEnvironmentVariable","iife","normalizeGCPCredentials","AuthError","GOOGLE_API_KEY_HEADER","GCP_API_KEY_HEADER","getGCPCredentialsAccessToken"],"sources":["../../src/clients/index.ts"],"sourcesContent":["import { getEnvironmentVariable } from \"@langchain/core/utils/env\";\nimport { GCP_API_KEY_HEADER, GOOGLE_API_KEY_HEADER } from \"../const.js\";\nimport {\n GCPCredentials,\n getGCPCredentialsAccessToken,\n normalizeGCPCredentials,\n} from \"../utils/gcp-auth.js\";\nimport { AuthError } from \"../utils/errors.js\";\nimport { iife } from \"../utils/misc.js\";\n\n/**\n * Abstract base class for API clients that interact with Google services.\n *\n * This class defines the contract for API clients, requiring implementations\n * to provide a fetch method that handles HTTP requests with appropriate\n * authentication headers. Concrete implementations should handle different\n * authentication strategies (API keys, service account credentials, etc.)\n * based on the runtime environment.\n *\n * @abstract\n *\n * @example\n * ```typescript\n * class MyApiClient extends ApiClient {\n * async fetch(request: Request): Promise<Response> {\n * // Add authentication headers\n * request.headers.set('Authorization', 'Bearer token');\n * return fetch(request);\n * }\n * }\n * ```\n */\nexport abstract class ApiClient {\n /**\n * Has an API Key been set for this client?\n */\n abstract hasApiKey(): boolean;\n\n /**\n * For some credential methods, we know what the project ID is.\n * This is necessary for OAuth-based access to Vertex\n */\n async getProjectId(): Promise<string> {\n return \"unknown-project-id\";\n }\n\n /**\n * Executes an HTTP request with appropriate authentication.\n *\n * Implementations should add necessary authentication headers to the request\n * before forwarding it to the underlying fetch implementation.\n *\n * @param request - The HTTP request to execute\n * @returns A Promise that resolves to the HTTP response\n *\n * @abstract\n */\n abstract fetch(request: Request): Promise<Response>;\n}\n\n/**\n * Configuration parameters for the WebApiClient.\n *\n * This interface defines the authentication options available for web-based\n * API clients. Authentication can be provided via an API key or GCP service\n * account credentials. The client will automatically check environment variables\n * if explicit values are not provided.\n *\n * @interface\n */\nexport interface WebApiClientParams {\n /**\n * Google API key for authentication.\n *\n * If not provided, the client will attempt to read from the\n * `GOOGLE_API_KEY` environment variable.\n *\n * @see https://cloud.google.com/docs/authentication/api-keys\n */\n apiKey?: string;\n\n /**\n * GCP service account credentials for authentication.\n *\n * Can be provided as either:\n * - A JSON string containing the service account key\n * - A GCPCredentials object\n *\n * If not provided, the client will attempt to read from the\n * `GOOGLE_CLOUD_CREDENTIALS` environment variable.\n *\n * @see https://cloud.google.com/iam/docs/creating-managing-service-account-keys\n */\n credentials?: string | GCPCredentials;\n\n /**\n * Google Auth options configuration.\n *\n * @deprecated This option is not supported in web environments.\n * Import from `@langchain/google/node` to configure google auth options\n * using the NodeApiClient instead.\n */\n googleAuthOptions?: never;\n}\n\n/**\n * Web-compatible API client for Google services.\n *\n * This client provides authentication for Google API requests in web environments\n * (browsers, edge functions, etc.) where the google-auth-library is not available.\n * It supports two authentication methods:\n *\n * 1. **API Key Authentication**: Simple key-based authentication suitable for\n * public APIs and client-side applications.\n *\n * 2. **Service Account Credentials**: OAuth2-based authentication using GCP\n * service account keys. The client automatically handles token generation\n * and caching.\n *\n * The client follows this authentication priority:\n * 1. Explicit `apiKey` parameter\n * 2. `GOOGLE_API_KEY` environment variable\n * 3. Explicit `credentials` parameter\n * 4. `GOOGLE_CLOUD_CREDENTIALS` environment variable\n *\n * @extends ApiClient\n *\n * @example\n * ```typescript\n * // Using API key\n * const client = new WebApiClient({\n * apiKey: 'your-api-key'\n * });\n *\n * // Using service account credentials\n * const client = new WebApiClient({\n * credentials: {\n * type: \"service_account\",\n * project_id: \"my-project\",\n * private_key_id: \"key-id\",\n * private_key: \"-----BEGIN PRIVATE KEY-----\\n...\",\n * client_email: \"service-account@project.iam.gserviceaccount.com\",\n * // ... other required fields\n * }\n * });\n *\n * // Using environment variables\n * // Set GOOGLE_API_KEY or GOOGLE_CLOUD_CREDENTIALS\n * const client = new WebApiClient({});\n *\n * // Make authenticated requests\n * const request = new Request('https://api.google.com/...');\n * const response = await client.fetch(request);\n * ```\n *\n * @remarks\n * - API keys are added via the `X-Goog-Api-Key` header\n * - Service account tokens are added via the `Authorization` header with Bearer scheme\n * - Tokens are automatically cached and refreshed as needed\n * - For Node.js environments with advanced auth requirements, use NodeApiClient instead\n *\n * @see {@link NodeApiClient} for Node.js-specific authentication options\n * @see {@link GCPCredentials} for service account credential structure\n */\nexport class WebApiClient extends ApiClient {\n hasApiKey(): boolean {\n return typeof this.apiKey === \"string\" && this.apiKey !== \"\";\n }\n\n async getProjectId(): Promise<string> {\n if (typeof this.credentials !== \"undefined\") {\n return this.credentials.project_id;\n } else {\n return super.getProjectId();\n }\n }\n\n /**\n * The Google API key used for authentication, if provided.\n *\n * This value is resolved from either the constructor parameter or the\n * `GOOGLE_API_KEY` environment variable.\n *\n * @protected\n */\n protected apiKey?: string;\n\n /**\n * The normalized GCP service account credentials, if provided.\n *\n * This value is resolved from either the constructor parameter or the\n * `GOOGLE_CLOUD_CREDENTIALS` environment variable, and is normalized\n * to ensure immutability.\n *\n * @protected\n */\n protected credentials?: GCPCredentials;\n\n /**\n * Creates a new WebApiClient instance.\n *\n * The constructor initializes authentication credentials by checking:\n * 1. Explicit parameters passed to the constructor\n * 2. Environment variables (`GOOGLE_API_KEY`, `GOOGLE_CLOUD_CREDENTIALS`)\n *\n * Credentials are normalized and frozen to prevent accidental modification.\n *\n * @param params - Configuration parameters for the client\n *\n * @example\n * ```typescript\n * // Minimal configuration (uses environment variables)\n * const client = new WebApiClient({});\n *\n * // With explicit API key\n * const client = new WebApiClient({\n * apiKey: 'your-api-key'\n * });\n *\n * // With service account credentials as JSON string\n * const client = new WebApiClient({\n * credentials: '{\"type\":\"service_account\",...}'\n * });\n *\n * // With service account credentials as object\n * const client = new WebApiClient({\n * credentials: {\n * type: \"service_account\",\n * // ... other fields\n * }\n * });\n * ```\n */\n constructor(protected params: WebApiClientParams) {\n super();\n this.apiKey = params.apiKey ?? getEnvironmentVariable(\"GOOGLE_API_KEY\");\n this.credentials = iife(() => {\n if (params.credentials) {\n return normalizeGCPCredentials(params.credentials);\n }\n const credentialsVar = getEnvironmentVariable(\"GOOGLE_CLOUD_CREDENTIALS\");\n if (credentialsVar) {\n return normalizeGCPCredentials(credentialsVar);\n }\n return undefined;\n });\n }\n\n /**\n * Executes an HTTP request with appropriate Google API authentication.\n *\n * This method adds authentication headers to the request based on the\n * configured authentication method:\n *\n * - If an API key is configured, adds the `X-Goog-Api-Key` header\n * - If service account credentials are configured, generates an access token\n * and adds it via the `Authorization` header with Bearer scheme\n *\n * The authentication priority is:\n * 1. API key (if provided)\n * 2. Service account credentials (if provided)\n *\n * @param request - The HTTP request to execute. Headers will be modified\n * in-place to include authentication information.\n * @returns A Promise that resolves to the HTTP response\n *\n * @throws {AuthError} If no authentication method is available (neither apiKey\n * nor credentials), or if service account authentication\n * fails (e.g., invalid credentials, network error, or\n * token generation failure)\n *\n * @example\n * ```typescript\n * const client = new WebApiClient({ apiKey: 'your-key' });\n * const request = new Request('https://generativelanguage.googleapis.com/v1/models');\n * const response = await client.fetch(request);\n * const data = await response.json();\n * ```\n *\n * @remarks\n * - The request object is modified in-place by adding headers\n * - Service account tokens are automatically cached and refreshed\n * - If both API key and credentials are provided, API key takes precedence\n */\n async fetch(request: Request): Promise<Response> {\n if (!this.apiKey && !this.credentials) {\n throw new AuthError({\n message:\n \"No authentication method available. Please provide either an apiKey or credentials.\",\n });\n }\n if (this.apiKey) {\n request.headers.set(GOOGLE_API_KEY_HEADER, this.apiKey);\n }\n if (this.credentials) {\n request.headers.set(\n GCP_API_KEY_HEADER,\n `Bearer ${await getGCPCredentialsAccessToken(this.credentials)}`\n );\n }\n return fetch(request);\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAgCA,IAAsB,YAAtB,MAAgC;;;;;CAU9B,MAAM,eAAg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GCPCredentialsAccessToken","ConfigurationError"],"sources":["../../src/clients/node.ts"],"sourcesContent":["import { GoogleAuth, type GoogleAuthOptions } from \"google-auth-library\";\nimport { getEnvironmentVariable } from \"@langchain/core/utils/env\";\nimport { GCP_API_KEY_HEADER, GOOGLE_API_KEY_HEADER } from \"../const.js\";\nimport { ApiClient } from \"./index.js\";\nimport {\n GCPCredentials,\n getGCPCredentialsAccessToken,\n normalizeGCPCredentials,\n} from \"../utils/gcp-auth.js\";\nimport { ConfigurationError } from \"../utils/errors.js\";\nimport { iife } from \"../utils/misc.js\";\n\n/**\n * Configuration parameters for the NodeApiClient.\n *\n * This interface defines the authentication options available for Node.js-based\n * API clients. Authentication can be provided via an API key, GCP service\n * account credentials, or advanced Google Auth options. The client will\n * automatically check environment variables if explicit values are not provided.\n *\n * @interface\n */\nexport interface NodeApiClientParams {\n /**\n * Google API key for authentication.\n *\n * If not provided, the client will attempt to read from the\n * `GOOGLE_API_KEY` environment variable.\n *\n * @see https://cloud.google.com/docs/authentication/api-keys\n */\n apiKey?: string;\n\n /**\n * GCP service account credentials for authentication.\n *\n * Can be provided as either:\n * - A JSON string containing the service account key\n * - A GCPCredentials object\n *\n * If not provided, the client will attempt to read from the\n * `GOOGLE_CLOUD_CREDENTIALS` environment variable.\n *\n * @see https://cloud.google.com/iam/docs/creating-managing-service-account-keys\n */\n credentials?: string | GCPCredentials;\n\n /**\n * Google Auth options configuration.\n *\n * Provides fine-grained control over authentication behavior using the\n * google-auth-library. This option enables:\n * - Custom OAuth2 scopes\n * - Application Default Credentials (ADC)\n * - Impersonation and delegation\n * - Custom credential sources\n *\n * When provided, this takes precedence over simple credential-based auth\n * but is lower priority than API key authentication.\n *\n * @see https://github.com/googleapis/google-auth-library-nodejs\n * @see https://cloud.google.com/docs/authentication/application-default-credentials\n */\n googleAuthOptions?: GoogleAuthOptions;\n}\n\n/**\n * Node.js-specific API client for Google services.\n *\n * This client provides comprehensive authentication for Google API requests in\n * Node.js environments, leveraging the full capabilities of the google-auth-library.\n * It supports three authentication methods with the following priority:\n *\n * 1. **API Key Authentication**: Simple key-based authentication suitable for\n * public APIs and development environments.\n *\n * 2. **Service Account Credentials**: OAuth2-based authentication using GCP\n * service account keys. The client automatically handles token generation\n * and caching using a web-compatible implementation.\n *\n * 3. **Google Auth Library**: Advanced authentication using google-auth-library,\n * supporting Application Default Credentials (ADC), custom scopes, and\n * various credential sources.\n *\n * The client follows this authentication priority:\n * 1. Explicit `apiKey` parameter\n * 2. `GOOGLE_API_KEY` environment variable\n * 3. Explicit `credentials` parameter\n * 4. `GOOGLE_CLOUD_CREDENTIALS` environment variable\n * 5. `googleAuthOptions` parameter\n * 6. Application Default Credentials (if googleAuthOptions is provided without explicit credentials)\n *\n * @extends ApiClient\n *\n * @example\n * ```typescript\n * // Using API key\n * const client = new NodeApiClient({\n * apiKey: 'your-api-key'\n * });\n *\n * // Using service account credentials\n * const client = new NodeApiClient({\n * credentials: {\n * type: \"service_account\",\n * project_id: \"my-project\",\n * private_key_id: \"key-id\",\n * private_key: \"-----BEGIN PRIVATE KEY-----\\n...\",\n * client_email: \"service-account@project.iam.gserviceaccount.com\",\n * // ... other required fields\n * }\n * });\n *\n * // Using Google Auth with custom scopes\n * const client = new NodeApiClient({\n * googleAuthOptions: {\n * scopes: ['https://www.googleapis.com/auth/cloud-platform'],\n * keyFilename: '/path/to/service-account-key.json'\n * }\n * });\n *\n * // Using Application Default Credentials\n * const client = new NodeApiClient({\n * googleAuthOptions: {}\n * });\n *\n * // Using environment variables\n * // Set GOOGLE_API_KEY or GOOGLE_CLOUD_CREDENTIALS\n * const client = new NodeApiClient();\n *\n * // Make authenticated requests\n * const request = new Request('https://api.google.com/...');\n * const response = await client.fetch(request);\n * ```\n *\n * @remarks\n * - API keys are added via the `X-Goog-Api-Key` header\n * - Service account tokens are added via the `Authorization` header with Bearer scheme\n * - Google Auth headers are automatically generated and added by google-auth-library\n * - Tokens are automatically cached and refreshed as needed\n * - For web/edge environments without google-auth-library, use WebApiClient instead\n *\n * @see {@link WebApiClient} for web-compatible authentication without google-auth-library\n * @see {@link GCPCredentials} for service account credential structure\n * @see {@link GoogleAuthOptions} for advanced authentication configuration\n */\nexport class NodeApiClient extends ApiClient {\n hasApiKey(): boolean {\n return typeof this.apiKey === \"string\" && this.apiKey !== \"\";\n }\n\n async getProjectId(): Promise<string> {\n if (typeof this.credentials !== \"undefined\") {\n return this.credentials.project_id;\n } else if (typeof this.googleAuth !== \"undefined\") {\n return this.googleAuth.getProjectId();\n } else {\n return super.getProjectId();\n }\n }\n\n /**\n * The Google API key used for authentication, if provided.\n *\n * This value is resolved from either the constructor parameter or the\n * `GOOGLE_API_KEY` environment variable.\n *\n * @protected\n */\n protected apiKey?: string;\n\n /**\n * The normalized GCP service account credentials, if provided.\n *\n * This value is resolved from either the constructor parameter or the\n * `GOOGLE_CLOUD_CREDENTIALS` environment variable, and is normalized\n * to ensure immutability.\n *\n * @protected\n */\n protected credentials?: GCPCredentials;\n\n /**\n * The Google Auth instance for advanced authentication, if configured.\n *\n * This instance is created when `googleAuthOptions` is provided and\n * handles Application Default Credentials, custom scopes, and other\n * advanced authentication scenarios.\n *\n * @protected\n */\n protected googleAuth?: GoogleAuth;\n\n /**\n * Creates a new NodeApiClient instance.\n *\n * The constructor initializes authentication credentials by checking:\n * 1. Explicit parameters passed to the constructor\n * 2. Environment variables (`GOOGLE_API_KEY`, `GOOGLE_CLOUD_CREDENTIALS`)\n * 3. Application Default Credentials (if googleAuthOptions is provided)\n *\n * Credentials are normalized and frozen to prevent accidental modification.\n * The GoogleAuth instance is lazily initialized only when googleAuthOptions\n * is provided.\n *\n * @param params - Configuration parameters for the client. Defaults to an empty object.\n *\n * @example\n * ```typescript\n * // Minimal configuration (uses environment variables or ADC)\n * const client = new NodeApiClient();\n *\n * // With explicit API key\n * const client = new WebApiClient({\n * apiKey: 'your-api-key'\n * });\n *\n * // With service account credentials as JSON string\n * const client = new WebApiClient({\n * credentials: '{\"type\":\"service_account\",...}'\n * });\n *\n * // With service account credentials as object\n * const client = new NodeApiClient({\n * credentials: {\n * type: \"service_account\",\n * // ... other fields\n * }\n * });\n *\n * // With Google Auth options\n * const client = new NodeApiClient({\n * googleAuthOptions: {\n * scopes: ['https://www.googleapis.com/auth/cloud-platform'],\n * projectId: 'my-project'\n * }\n * });\n * ```\n */\n constructor(protected params: NodeApiClientParams = {}) {\n super();\n\n this.apiKey = params.apiKey ?? getEnvironmentVariable(\"GOOGLE_API_KEY\");\n this.credentials = iife(() => {\n if (params.credentials) {\n return normalizeGCPCredentials(params.credentials);\n }\n const credentialsVar = getEnvironmentVariable(\"GOOGLE_CLOUD_CREDENTIALS\");\n if (credentialsVar) {\n return normalizeGCPCredentials(credentialsVar);\n }\n return undefined;\n });\n this.googleAuth = iife(() => {\n if (params.googleAuthOptions) {\n return new GoogleAuth(params.googleAuthOptions);\n }\n if (!this.apiKey && !this.credentials) {\n return new GoogleAuth();\n }\n return undefined;\n });\n }\n\n /**\n * Executes an HTTP request with appropriate Google API authentication.\n *\n * This method adds authentication headers to the request based on the\n * configured authentication method, following this priority:\n *\n * 1. If an API key is configured, adds the `X-Goog-Api-Key` header\n * 2. If service account credentials are configured, generates an access token\n * and adds it via the `Authorization` header with Bearer scheme\n * 3. If Google Auth is configured, uses google-auth-library to generate\n * appropriate authentication headers (may include Authorization, x-goog-user-project, etc.)\n *\n * The authentication priority ensures that explicit API keys take precedence,\n * followed by service account credentials, and finally Google Auth options.\n *\n * @param request - The HTTP request to execute. Headers will be modified\n * in-place to include authentication information.\n * @returns A Promise that resolves to the HTTP response\n *\n * @throws {AuthError} If service account authentication fails (e.g., invalid\n * credentials, network error, or token generation failure)\n * @throws {Error} If Google Auth authentication fails (e.g., missing credentials,\n * invalid configuration, or ADC not available)\n *\n * @example\n * ```typescript\n * const client = new NodeApiClient({ apiKey: 'your-key' });\n * const request = new Request('https://generativelanguage.googleapis.com/v1/models');\n * const response = await client.fetch(request);\n * const data = await response.json();\n * ```\n *\n * @remarks\n * - The request object is modified in-place by adding headers\n * - Service account tokens are automatically cached and refreshed\n * - Google Auth tokens are managed by google-auth-library with automatic refresh\n * - Only one authentication method is used per request (based on priority)\n * - Google Auth may add multiple headers depending on the authentication type\n */\n async fetch(request: Request): Promise<Response> {\n if (this.apiKey) {\n request.headers.set(GOOGLE_API_KEY_HEADER, this.apiKey);\n } else if (this.credentials) {\n request.headers.set(\n GCP_API_KEY_HEADER,\n `Bearer ${getGCPCredentialsAccessToken(this.credentials)}`\n );\n } else if (this.googleAuth) {\n const authHeaders = await this.googleAuth.getRequestHeaders(request.url);\n authHeaders.forEach((value, key) => {\n if (value !== null) {\n request.headers.set(key, value);\n }\n });\n }\n return fetch(request);\n }\n}\n\n/**\n * Ensures that Google Auth options include required OAuth2 scopes.\n *\n * This utility function validates and augments GoogleAuthOptions to ensure\n * that all required OAuth2 scopes are present. It handles three scenarios:\n *\n * 1. **No auth options provided**: Creates new options with required scopes\n * 2. **Auth options without scopes**: Adds required scopes to existing options\n * 3. **Auth options with scopes**: Validates that all required scopes are present\n *\n * This is particularly useful when working with Google APIs that require specific\n * scopes for access, ensuring that authentication is properly configured before\n * making API requests.\n *\n * @param authOptions - The existing Google Auth options to validate/augment.\n * Can be undefined or an empty object.\n * @param requiredScopes - Array of OAuth2 scope URLs that must be present.\n * These are typically Google API scope URLs like\n * 'https://www.googleapis.com/auth/cloud-platform'\n * @returns The validated/augmented GoogleAuthOptions with all required scopes\n *\n * @throws {Error} If authOptions already has scopes but is missing any of the\n * required scopes. This prevents accidental scope reduction that\n * could break API access.\n *\n * @example\n * ```typescript\n * // Create new options with required scopes\n * const options = ensureAuthScopes(undefined, [\n * 'https://www.googleapis.com/auth/cloud-platform'\n * ]);\n * // Result: { scopes: ['https://www.googleapis.com/auth/cloud-platform'] }\n *\n * // Add scopes to existing options\n * const options = ensureAuthScopes(\n * { projectId: 'my-project' },\n * ['https://www.googleapis.com/auth/cloud-platform']\n * );\n * // Result: { projectId: 'my-project', scopes: [...] }\n *\n * // Validate existing scopes\n * const options = ensureAuthScopes(\n * { scopes: ['https://www.googleapis.com/auth/cloud-platform'] },\n * ['https://www.googleapis.com/auth/cloud-platform']\n * );\n * // Result: Original options (validation passed)\n *\n * // Error case - missing required scope\n * try {\n * ensureAuthScopes(\n * { scopes: ['https://www.googleapis.com/auth/userinfo.email'] },\n * ['https://www.googleapis.com/auth/cloud-platform']\n * );\n * } catch (error) {\n * // Error: Invalid auth scopes. Scopes must include ...\n * }\n * ```\n *\n * @remarks\n * - Scopes can be provided as a string or array of strings in GoogleAuthOptions\n * - The function normalizes single-string scopes to arrays for validation\n * - Required scopes are not automatically added if existing scopes are present;\n * instead, an error is thrown to prevent unintended scope changes\n * - This function does not modify the original authOptions object\n *\n * @see https://developers.google.com/identity/protocols/oauth2/scopes\n * @see {@link GoogleAuthOptions} for the full authentication configuration interface\n */\nexport function ensureAuthScopes(\n authOptions: GoogleAuthOptions,\n requiredScopes: string[]\n): GoogleAuthOptions {\n if (!authOptions) {\n return { scopes: requiredScopes };\n } else if (!authOptions.scopes) {\n return { ...authOptions, scopes: requiredScopes };\n } else {\n const existingScopes = Array.isArray(authOptions.scopes)\n ? authOptions.scopes\n : [authOptions.scopes];\n const missingScopes = requiredScopes.filter(\n (scope) => !existingScopes.includes(scope)\n );\n if (missingScopes.length > 0) {\n throw new ConfigurationError(\n `Invalid auth scopes. Scopes must include ${requiredScopes.join(\", \")}`\n );\n }\n }\n return authOptions;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAkJA,IAAa,gBAAb,cAAmCA,cAAAA,UAAU;CA6FrB;CA5FtB,YAAqB;EACnB,OAAO,OAAO,KAAK,WAAW,YAAY,KAAK,WAAW;CAC5D;CAEA,MAAM,eAAgC;EACpC,IAAI,OAAO,KAAK,gBAAgB,aAC9B,OAAO,KAAK,YAAY;OACnB,IAAI,OAAO,KA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;;;;;;;;;AAsEA,SAAgB,iBACd,aACA,gBACmB;CACnB,IAAI,CAAC,aACH,OAAO,EAAE,QAAQ,eAAe;MAC3B,IAAI,CAAC,YAAY,QACtB,OAAO;EAAE,GAAG;EAAa,QAAQ;CAAe;MAC3C;EACL,MAAM,iBAAiB,MAAM,QAAQ,YAAY,MAAM,IACnD,YAAY,SACZ,CAAC,YAAY,MAAM;EAIvB,IAHsB,eAAe,QAClC,UAAU,CAAC,eAAe,SAAS,KAAK,CAE3B,CAAC,CAAC,SAAS,GACzB,MAAM,IAAIC,eAAAA,mBACR,4CAA4C,eAAe,KAAK,IAAI,GACtE;CAEJ;CACA,OAAO;AACT"}
1
+ {"version":3,"file":"node.cjs","names":["ApiClient","getEnvironmentVariable","iife","normalizeGCPCredentials","GoogleAuth","GOOGLE_API_KEY_HEADER","GCP_API_KEY_HEADER","getGCPCredentialsAccessToken","ConfigurationError"],"sources":["../../src/clients/node.ts"],"sourcesContent":["import { GoogleAuth, type GoogleAuthOptions } from \"google-auth-library\";\nimport { getEnvironmentVariable } from \"@langchain/core/utils/env\";\nimport { GCP_API_KEY_HEADER, GOOGLE_API_KEY_HEADER } from \"../const.js\";\nimport { ApiClient } from \"./index.js\";\nimport {\n GCPCredentials,\n getGCPCredentialsAccessToken,\n normalizeGCPCredentials,\n} from \"../utils/gcp-auth.js\";\nimport { ConfigurationError } from \"../utils/errors.js\";\nimport { iife } from \"../utils/misc.js\";\n\n/**\n * Configuration parameters for the NodeApiClient.\n *\n * This interface defines the authentication options available for Node.js-based\n * API clients. Authentication can be provided via an API key, GCP service\n * account credentials, or advanced Google Auth options. The client will\n * automatically check environment variables if explicit values are not provided.\n *\n * @interface\n */\nexport interface NodeApiClientParams {\n /**\n * Google API key for authentication.\n *\n * If not provided, the client will attempt to read from the\n * `GOOGLE_API_KEY` environment variable.\n *\n * @see https://cloud.google.com/docs/authentication/api-keys\n */\n apiKey?: string;\n\n /**\n * GCP service account credentials for authentication.\n *\n * Can be provided as either:\n * - A JSON string containing the service account key\n * - A GCPCredentials object\n *\n * If not provided, the client will attempt to read from the\n * `GOOGLE_CLOUD_CREDENTIALS` environment variable.\n *\n * @see https://cloud.google.com/iam/docs/creating-managing-service-account-keys\n */\n credentials?: string | GCPCredentials;\n\n /**\n * Google Auth options configuration.\n *\n * Provides fine-grained control over authentication behavior using the\n * google-auth-library. This option enables:\n * - Custom OAuth2 scopes\n * - Application Default Credentials (ADC)\n * - Impersonation and delegation\n * - Custom credential sources\n *\n * When provided, this takes precedence over simple credential-based auth\n * but is lower priority than API key authentication.\n *\n * @see https://github.com/googleapis/google-auth-library-nodejs\n * @see https://cloud.google.com/docs/authentication/application-default-credentials\n */\n googleAuthOptions?: GoogleAuthOptions;\n}\n\n/**\n * Node.js-specific API client for Google services.\n *\n * This client provides comprehensive authentication for Google API requests in\n * Node.js environments, leveraging the full capabilities of the google-auth-library.\n * It supports three authentication methods with the following priority:\n *\n * 1. **API Key Authentication**: Simple key-based authentication suitable for\n * public APIs and development environments.\n *\n * 2. **Service Account Credentials**: OAuth2-based authentication using GCP\n * service account keys. The client automatically handles token generation\n * and caching using a web-compatible implementation.\n *\n * 3. **Google Auth Library**: Advanced authentication using google-auth-library,\n * supporting Application Default Credentials (ADC), custom scopes, and\n * various credential sources.\n *\n * The client follows this authentication priority:\n * 1. Explicit `apiKey` parameter\n * 2. `GOOGLE_API_KEY` environment variable\n * 3. Explicit `credentials` parameter\n * 4. `GOOGLE_CLOUD_CREDENTIALS` environment variable\n * 5. `googleAuthOptions` parameter\n * 6. Application Default Credentials (if googleAuthOptions is provided without explicit credentials)\n *\n * @extends ApiClient\n *\n * @example\n * ```typescript\n * // Using API key\n * const client = new NodeApiClient({\n * apiKey: 'your-api-key'\n * });\n *\n * // Using service account credentials\n * const client = new NodeApiClient({\n * credentials: {\n * type: \"service_account\",\n * project_id: \"my-project\",\n * private_key_id: \"key-id\",\n * private_key: \"-----BEGIN PRIVATE KEY-----\\n...\",\n * client_email: \"service-account@project.iam.gserviceaccount.com\",\n * // ... other required fields\n * }\n * });\n *\n * // Using Google Auth with custom scopes\n * const client = new NodeApiClient({\n * googleAuthOptions: {\n * scopes: ['https://www.googleapis.com/auth/cloud-platform'],\n * keyFilename: '/path/to/service-account-key.json'\n * }\n * });\n *\n * // Using Application Default Credentials\n * const client = new NodeApiClient({\n * googleAuthOptions: {}\n * });\n *\n * // Using environment variables\n * // Set GOOGLE_API_KEY or GOOGLE_CLOUD_CREDENTIALS\n * const client = new NodeApiClient();\n *\n * // Make authenticated requests\n * const request = new Request('https://api.google.com/...');\n * const response = await client.fetch(request);\n * ```\n *\n * @remarks\n * - API keys are added via the `X-Goog-Api-Key` header\n * - Service account tokens are added via the `Authorization` header with Bearer scheme\n * - Google Auth headers are automatically generated and added by google-auth-library\n * - Tokens are automatically cached and refreshed as needed\n * - For web/edge environments without google-auth-library, use WebApiClient instead\n *\n * @see {@link WebApiClient} for web-compatible authentication without google-auth-library\n * @see {@link GCPCredentials} for service account credential structure\n * @see {@link GoogleAuthOptions} for advanced authentication configuration\n */\nexport class NodeApiClient extends ApiClient {\n hasApiKey(): boolean {\n return typeof this.apiKey === \"string\" && this.apiKey !== \"\";\n }\n\n async getProjectId(): Promise<string> {\n if (typeof this.credentials !== \"undefined\") {\n return this.credentials.project_id;\n } else if (typeof this.googleAuth !== \"undefined\") {\n return this.googleAuth.getProjectId();\n } else {\n return super.getProjectId();\n }\n }\n\n /**\n * The Google API key used for authentication, if provided.\n *\n * This value is resolved from either the constructor parameter or the\n * `GOOGLE_API_KEY` environment variable.\n *\n * @protected\n */\n protected apiKey?: string;\n\n /**\n * The normalized GCP service account credentials, if provided.\n *\n * This value is resolved from either the constructor parameter or the\n * `GOOGLE_CLOUD_CREDENTIALS` environment variable, and is normalized\n * to ensure immutability.\n *\n * @protected\n */\n protected credentials?: GCPCredentials;\n\n /**\n * The Google Auth instance for advanced authentication, if configured.\n *\n * This instance is created when `googleAuthOptions` is provided and\n * handles Application Default Credentials, custom scopes, and other\n * advanced authentication scenarios.\n *\n * @protected\n */\n protected googleAuth?: GoogleAuth;\n\n /**\n * Creates a new NodeApiClient instance.\n *\n * The constructor initializes authentication credentials by checking:\n * 1. Explicit parameters passed to the constructor\n * 2. Environment variables (`GOOGLE_API_KEY`, `GOOGLE_CLOUD_CREDENTIALS`)\n * 3. Application Default Credentials (if googleAuthOptions is provided)\n *\n * Credentials are normalized and frozen to prevent accidental modification.\n * The GoogleAuth instance is lazily initialized only when googleAuthOptions\n * is provided.\n *\n * @param params - Configuration parameters for the client. Defaults to an empty object.\n *\n * @example\n * ```typescript\n * // Minimal configuration (uses environment variables or ADC)\n * const client = new NodeApiClient();\n *\n * // With explicit API key\n * const client = new WebApiClient({\n * apiKey: 'your-api-key'\n * });\n *\n * // With service account credentials as JSON string\n * const client = new WebApiClient({\n * credentials: '{\"type\":\"service_account\",...}'\n * });\n *\n * // With service account credentials as object\n * const client = new NodeApiClient({\n * credentials: {\n * type: \"service_account\",\n * // ... other fields\n * }\n * });\n *\n * // With Google Auth options\n * const client = new NodeApiClient({\n * googleAuthOptions: {\n * scopes: ['https://www.googleapis.com/auth/cloud-platform'],\n * projectId: 'my-project'\n * }\n * });\n * ```\n */\n constructor(protected params: NodeApiClientParams = {}) {\n super();\n\n this.apiKey = params.apiKey ?? getEnvironmentVariable(\"GOOGLE_API_KEY\");\n this.credentials = iife(() => {\n if (params.credentials) {\n return normalizeGCPCredentials(params.credentials);\n }\n const credentialsVar = getEnvironmentVariable(\"GOOGLE_CLOUD_CREDENTIALS\");\n if (credentialsVar) {\n return normalizeGCPCredentials(credentialsVar);\n }\n return undefined;\n });\n this.googleAuth = iife(() => {\n if (params.googleAuthOptions) {\n return new GoogleAuth(params.googleAuthOptions);\n }\n if (!this.apiKey && !this.credentials) {\n return new GoogleAuth();\n }\n return undefined;\n });\n }\n\n /**\n * Executes an HTTP request with appropriate Google API authentication.\n *\n * This method adds authentication headers to the request based on the\n * configured authentication method, following this priority:\n *\n * 1. If an API key is configured, adds the `X-Goog-Api-Key` header\n * 2. If service account credentials are configured, generates an access token\n * and adds it via the `Authorization` header with Bearer scheme\n * 3. If Google Auth is configured, uses google-auth-library to generate\n * appropriate authentication headers (may include Authorization, x-goog-user-project, etc.)\n *\n * The authentication priority ensures that explicit API keys take precedence,\n * followed by service account credentials, and finally Google Auth options.\n *\n * @param request - The HTTP request to execute. Headers will be modified\n * in-place to include authentication information.\n * @returns A Promise that resolves to the HTTP response\n *\n * @throws {AuthError} If service account authentication fails (e.g., invalid\n * credentials, network error, or token generation failure)\n * @throws {Error} If Google Auth authentication fails (e.g., missing credentials,\n * invalid configuration, or ADC not available)\n *\n * @example\n * ```typescript\n * const client = new NodeApiClient({ apiKey: 'your-key' });\n * const request = new Request('https://generativelanguage.googleapis.com/v1/models');\n * const response = await client.fetch(request);\n * const data = await response.json();\n * ```\n *\n * @remarks\n * - The request object is modified in-place by adding headers\n * - Service account tokens are automatically cached and refreshed\n * - Google Auth tokens are managed by google-auth-library with automatic refresh\n * - Only one authentication method is used per request (based on priority)\n * - Google Auth may add multiple headers depending on the authentication type\n */\n async fetch(request: Request): Promise<Response> {\n if (this.apiKey) {\n request.headers.set(GOOGLE_API_KEY_HEADER, this.apiKey);\n } else if (this.credentials) {\n request.headers.set(\n GCP_API_KEY_HEADER,\n `Bearer ${getGCPCredentialsAccessToken(this.credentials)}`\n );\n } else if (this.googleAuth) {\n const authHeaders = await this.googleAuth.getRequestHeaders(request.url);\n authHeaders.forEach((value, key) => {\n if (value !== null) {\n request.headers.set(key, value);\n }\n });\n }\n return fetch(request);\n }\n}\n\n/**\n * Ensures that Google Auth options include required OAuth2 scopes.\n *\n * This utility function validates and augments GoogleAuthOptions to ensure\n * that all required OAuth2 scopes are present. It handles three scenarios:\n *\n * 1. **No auth options provided**: Creates new options with required scopes\n * 2. **Auth options without scopes**: Adds required scopes to existing options\n * 3. **Auth options with scopes**: Validates that all required scopes are present\n *\n * This is particularly useful when working with Google APIs that require specific\n * scopes for access, ensuring that authentication is properly configured before\n * making API requests.\n *\n * @param authOptions - The existing Google Auth options to validate/augment.\n * Can be undefined or an empty object.\n * @param requiredScopes - Array of OAuth2 scope URLs that must be present.\n * These are typically Google API scope URLs like\n * 'https://www.googleapis.com/auth/cloud-platform'\n * @returns The validated/augmented GoogleAuthOptions with all required scopes\n *\n * @throws {Error} If authOptions already has scopes but is missing any of the\n * required scopes. This prevents accidental scope reduction that\n * could break API access.\n *\n * @example\n * ```typescript\n * // Create new options with required scopes\n * const options = ensureAuthScopes(undefined, [\n * 'https://www.googleapis.com/auth/cloud-platform'\n * ]);\n * // Result: { scopes: ['https://www.googleapis.com/auth/cloud-platform'] }\n *\n * // Add scopes to existing options\n * const options = ensureAuthScopes(\n * { projectId: 'my-project' },\n * ['https://www.googleapis.com/auth/cloud-platform']\n * );\n * // Result: { projectId: 'my-project', scopes: [...] }\n *\n * // Validate existing scopes\n * const options = ensureAuthScopes(\n * { scopes: ['https://www.googleapis.com/auth/cloud-platform'] },\n * ['https://www.googleapis.com/auth/cloud-platform']\n * );\n * // Result: Original options (validation passed)\n *\n * // Error case - missing required scope\n * try {\n * ensureAuthScopes(\n * { scopes: ['https://www.googleapis.com/auth/userinfo.email'] },\n * ['https://www.googleapis.com/auth/cloud-platform']\n * );\n * } catch (error) {\n * // Error: Invalid auth scopes. Scopes must include ...\n * }\n * ```\n *\n * @remarks\n * - Scopes can be provided as a string or array of strings in GoogleAuthOptions\n * - The function normalizes single-string scopes to arrays for validation\n * - Required scopes are not automatically added if existing scopes are present;\n * instead, an error is thrown to prevent unintended scope changes\n * - This function does not modify the original authOptions object\n *\n * @see https://developers.google.com/identity/protocols/oauth2/scopes\n * @see {@link GoogleAuthOptions} for the full authentication configuration interface\n */\nexport function ensureAuthScopes(\n authOptions: GoogleAuthOptions,\n requiredScopes: string[]\n): GoogleAuthOptions {\n if (!authOptions) {\n return { scopes: requiredScopes };\n } else if (!authOptions.scopes) {\n return { ...authOptions, scopes: requiredScopes };\n } else {\n const existingScopes = Array.isArray(authOptions.scopes)\n ? authOptions.scopes\n : [authOptions.scopes];\n const missingScopes = requiredScopes.filter(\n (scope) => !existingScopes.includes(scope)\n );\n if (missingScopes.length > 0) {\n throw new ConfigurationError(\n `Invalid auth scopes. Scopes must include ${requiredScopes.join(\", \")}`\n );\n }\n }\n return authOptions;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAkJA,IAAa,gBAAb,cAAmCA,cAAAA,UAAU;CA6FrB;CA5FtB,YAAqB;EACnB,OAAO,OAAO,KAAK,WAAW,YAAY,KAAK,WAAW;CAC5D;CAEA,MAAM,eAAgC;EACpC,IAAI,OAAO,KAAK,gBAAgB,aAC9B,OAAO,KAAK,YAAY;OACnB,IAAI,OAAO,KAAK,eAAe,aACpC,OAAO,KAAK,WAAW,aAAa;OAEpC,OAAO,MAAM,aAAa;CAE9B;;;;;;;;;CAUA;;;;;;;;;;CAWA;;;;;;;;;;CAWA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAgDA,YAAY,SAAwC,CAAC,GAAG;EACtD,MAAM;EADc,KAAA,SAAA;EAGpB,KAAK,SAAS,OAAO,WAAA,GAAUC,0BAAAA,uBAAAA,CAAuB,gBAAgB;EACtE,KAAK,cAAcC,aAAAA,WAAW;GAC5B,IAAI,OAAO,aACT,OAAOC,iBAAAA,wBAAwB,OAAO,WAAW;GAEnD,MAAM,kBAAA,GAAiBF,0BAAAA,uBAAAA,CAAuB,0BAA0B;GACxE,IAAI,gBACF,OAAOE,iBAAAA,wBAAwB,cAAc;EAGjD,CAAC;EACD,KAAK,aAAaD,aAAAA,WAAW;GAC3B,IAAI,OAAO,mBACT,OAAO,IAAIE,oBAAAA,WAAW,OAAO,iBAAiB;GAEhD,IAAI,CAAC,KAAK,UAAU,CAAC,KAAK,aACxB,OAAO,IAAIA,oBAAAA,W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