@langchain/google 0.2.12 → 0.2.14
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 +24 -0
- package/dist/chat_models/api_types/generate_content.d.cts +0 -2
- package/dist/chat_models/api_types/generate_content.d.ts +0 -2
- package/dist/chat_models/api_types/interactions.d.cts +1423 -0
- package/dist/chat_models/api_types/interactions.d.ts +1423 -0
- package/dist/chat_models/base.cjs +12 -11
- package/dist/chat_models/base.cjs.map +1 -1
- package/dist/chat_models/base.d.cts +3 -5
- package/dist/chat_models/base.d.ts +3 -5
- package/dist/chat_models/base.js +12 -11
- package/dist/chat_models/base.js.map +1 -1
- package/dist/chat_models/handlers/base.cjs +1 -2
- package/dist/chat_models/handlers/base.d.cts +0 -2
- package/dist/chat_models/handlers/base.d.ts +0 -2
- package/dist/chat_models/handlers/base.js +1 -2
- package/dist/chat_models/handlers/generate_content.cjs +7 -7
- package/dist/chat_models/handlers/generate_content.cjs.map +1 -1
- package/dist/chat_models/handlers/generate_content.d.cts +0 -2
- package/dist/chat_models/handlers/generate_content.d.ts +0 -2
- package/dist/chat_models/handlers/generate_content.js +7 -7
- package/dist/chat_models/handlers/generate_content.js.map +1 -1
- package/dist/chat_models/handlers/index.cjs +2 -0
- package/dist/chat_models/handlers/index.d.cts +2 -1
- package/dist/chat_models/handlers/index.d.ts +2 -1
- package/dist/chat_models/handlers/index.js +2 -1
- package/dist/chat_models/handlers/interactions.cjs +303 -0
- package/dist/chat_models/handlers/interactions.cjs.map +1 -0
- package/dist/chat_models/handlers/interactions.d.cts +33 -0
- package/dist/chat_models/handlers/interactions.d.ts +33 -0
- package/dist/chat_models/handlers/interactions.js +303 -0
- package/dist/chat_models/handlers/interactions.js.map +1 -0
- package/dist/chat_models/index.cjs +5 -4
- package/dist/chat_models/index.cjs.map +1 -1
- package/dist/chat_models/index.d.cts +4 -5
- package/dist/chat_models/index.d.ts +4 -5
- package/dist/chat_models/index.js +5 -5
- package/dist/chat_models/index.js.map +1 -1
- package/dist/chat_models/node.cjs +3 -4
- package/dist/chat_models/node.d.cts +1 -3
- package/dist/chat_models/node.d.ts +1 -3
- package/dist/chat_models/node.js +3 -4
- package/dist/chat_models/profiles.cjs +1 -2
- package/dist/chat_models/profiles.js +1 -2
- package/dist/chat_models/types.cjs +1 -2
- package/dist/chat_models/types.cjs.map +1 -1
- package/dist/chat_models/types.d.cts +524 -23
- package/dist/chat_models/types.d.ts +524 -23
- package/dist/chat_models/types.js +1 -2
- package/dist/chat_models/types.js.map +1 -1
- package/dist/clients/index.cjs +3 -4
- package/dist/clients/index.d.cts +0 -2
- package/dist/clients/index.d.ts +0 -2
- package/dist/clients/index.js +3 -4
- package/dist/clients/node.cjs +4 -5
- package/dist/clients/node.d.cts +0 -2
- package/dist/clients/node.d.ts +0 -2
- package/dist/clients/node.js +4 -5
- package/dist/const.cjs +1 -2
- package/dist/const.js +1 -2
- package/dist/converters/generate_content/messages.cjs +2 -2
- package/dist/converters/generate_content/messages.cjs.map +1 -1
- package/dist/converters/generate_content/messages.js +2 -2
- package/dist/converters/generate_content/messages.js.map +1 -1
- package/dist/converters/generate_content/params.cjs +1 -2
- package/dist/converters/generate_content/params.js +1 -2
- package/dist/converters/generate_content/stream_events.cjs +9 -3
- package/dist/converters/generate_content/stream_events.cjs.map +1 -1
- package/dist/converters/generate_content/stream_events.js +9 -3
- package/dist/converters/generate_content/stream_events.js.map +1 -1
- package/dist/converters/generate_content/tools.cjs +1 -2
- package/dist/converters/generate_content/tools.js +1 -2
- package/dist/converters/interactions/messages.cjs +766 -0
- package/dist/converters/interactions/messages.cjs.map +1 -0
- package/dist/converters/interactions/messages.js +759 -0
- package/dist/converters/interactions/messages.js.map +1 -0
- package/dist/converters/interactions/params.cjs +244 -0
- package/dist/converters/interactions/params.cjs.map +1 -0
- package/dist/converters/interactions/params.js +237 -0
- package/dist/converters/interactions/params.js.map +1 -0
- package/dist/converters/interactions/stream_events.cjs +769 -0
- package/dist/converters/interactions/stream_events.cjs.map +1 -0
- package/dist/converters/interactions/stream_events.js +768 -0
- package/dist/converters/interactions/stream_events.js.map +1 -0
- package/dist/converters/interactions/tools.cjs +229 -0
- package/dist/converters/interactions/tools.cjs.map +1 -0
- package/dist/converters/interactions/tools.js +228 -0
- package/dist/converters/interactions/tools.js.map +1 -0
- package/dist/converters/shared/params.cjs +1 -2
- package/dist/converters/shared/params.js +1 -2
- package/dist/index.cjs +2 -0
- package/dist/index.d.cts +3 -2
- package/dist/index.d.ts +3 -2
- package/dist/index.js +2 -1
- package/dist/node.cjs +1 -1
- package/dist/node.d.cts +1 -1
- package/dist/node.d.ts +1 -1
- package/dist/node.js +1 -1
- package/dist/utils/errors.cjs +22 -4
- package/dist/utils/errors.cjs.map +1 -1
- package/dist/utils/errors.js +22 -6
- package/dist/utils/errors.js.map +1 -1
- package/dist/utils/gcp-auth.cjs +3 -4
- package/dist/utils/gcp-auth.d.cts +0 -2
- package/dist/utils/gcp-auth.d.ts +0 -2
- package/dist/utils/gcp-auth.js +3 -4
- package/dist/utils/handler.cjs +1 -2
- package/dist/utils/handler.d.cts +0 -2
- package/dist/utils/handler.d.ts +0 -2
- package/dist/utils/handler.js +1 -2
- package/dist/utils/metadata.cjs +1 -2
- package/dist/utils/metadata.js +1 -2
- package/dist/utils/misc.cjs +1 -2
- package/dist/utils/misc.d.cts +0 -2
- package/dist/utils/misc.d.ts +0 -2
- package/dist/utils/misc.js +1 -2
- package/dist/utils/stream.cjs +1 -2
- package/dist/utils/stream.js +1 -2
- package/package.json +11 -9
|
@@ -1,9 +1,10 @@
|
|
|
1
|
-
const require_errors = require("../utils/errors.cjs");
|
|
2
1
|
const require_profiles = require("./profiles.cjs");
|
|
2
|
+
const require_errors = require("../utils/errors.cjs");
|
|
3
3
|
const require_metadata = require("../utils/metadata.cjs");
|
|
4
|
-
const require_params = require("../converters/shared/params.cjs");
|
|
5
|
-
const require_generate_content = require("./handlers/generate_content.cjs");
|
|
6
4
|
require("./handlers/index.cjs");
|
|
5
|
+
const require_generate_content = require("./handlers/generate_content.cjs");
|
|
6
|
+
const require_interactions = require("./handlers/interactions.cjs");
|
|
7
|
+
const require_params = require("../converters/shared/params.cjs");
|
|
7
8
|
let _langchain_core_utils_env = require("@langchain/core/utils/env");
|
|
8
9
|
let _langchain_core_language_models_chat_models = require("@langchain/core/language_models/chat_models");
|
|
9
10
|
let _langchain_core_messages = require("@langchain/core/messages");
|
|
@@ -11,7 +12,7 @@ let _langchain_core_utils_stream = require("@langchain/core/utils/stream");
|
|
|
11
12
|
let _langchain_core_runnables = require("@langchain/core/runnables");
|
|
12
13
|
let _langchain_core_language_models_structured_output = require("@langchain/core/language_models/structured_output");
|
|
13
14
|
let _langchain_core_utils_gateway = require("@langchain/core/utils/gateway");
|
|
14
|
-
|
|
15
|
+
// src/chat_models/base.ts
|
|
15
16
|
function hasVertexCredentials(params) {
|
|
16
17
|
return typeof params.credentials !== "undefined" || typeof params.googleAuthOptions !== "undefined" || typeof (0, _langchain_core_utils_env.getEnvironmentVariable)("GOOGLE_CLOUD_CREDENTIALS") !== "undefined";
|
|
17
18
|
}
|
|
@@ -19,11 +20,11 @@ function hasVertexCredentials(params) {
|
|
|
19
20
|
* Resolves LangSmith gateway routing for Google chat model params.
|
|
20
21
|
*
|
|
21
22
|
* The LangSmith gateway exposes direct paths for the Gemini Developer API and
|
|
22
|
-
* Vertex AI. An explicit `endpoint`
|
|
23
|
+
* Vertex AI. An explicit `endpoint` or explicit credentials (`apiKey`,
|
|
24
|
+
* `credentials`, `googleAuthOptions`) suppress gateway routing.
|
|
23
25
|
*
|
|
24
26
|
* When `LANGSMITH_GATEWAY` is set, this rewrites `endpoint` to the gateway
|
|
25
|
-
* host and
|
|
26
|
-
* then rides as the `x-goog-api-key` header via the ApiClient). The default
|
|
27
|
+
* host and uses the gateway key as the API key. The default
|
|
27
28
|
* `https` gateway host is written scheme-less (the URL builders prepend
|
|
28
29
|
* `https://`); a non-`https` custom gateway keeps its scheme so it is not
|
|
29
30
|
* forced to TLS.
|
|
@@ -36,7 +37,7 @@ function hasVertexCredentials(params) {
|
|
|
36
37
|
*/
|
|
37
38
|
function applyGeminiGatewayParams(params) {
|
|
38
39
|
const p = params;
|
|
39
|
-
if (typeof p.endpoint !== "undefined") return { ...params };
|
|
40
|
+
if (typeof p.endpoint !== "undefined" || typeof p.apiKey !== "undefined" || typeof p.credentials !== "undefined" || typeof p.googleAuthOptions !== "undefined") return { ...params };
|
|
40
41
|
const platform = require_params.convertParamsToPlatformType(p) ?? (hasVertexCredentials(p) ? "gcp" : "gai");
|
|
41
42
|
const gatewayConfig = (0, _langchain_core_utils_gateway.resolveLangSmithGatewayConfig)({ providerPath: platform === "gcp" ? "vertex" : "gemini" });
|
|
42
43
|
if (typeof gatewayConfig.baseURL === "undefined") return { ...params };
|
|
@@ -45,7 +46,7 @@ function applyGeminiGatewayParams(params) {
|
|
|
45
46
|
const endpoint = gatewayUrl.protocol === "https:" ? `${gatewayUrl.host}${path}` : `${gatewayUrl.protocol}//${gatewayUrl.host}${path}`;
|
|
46
47
|
return {
|
|
47
48
|
...params,
|
|
48
|
-
apiKey:
|
|
49
|
+
apiKey: gatewayConfig.apiKey,
|
|
49
50
|
endpoint,
|
|
50
51
|
platformType: platform
|
|
51
52
|
};
|
|
@@ -70,7 +71,7 @@ var BaseChatGoogle = class extends _langchain_core_language_models_chat_models.B
|
|
|
70
71
|
constructor(params) {
|
|
71
72
|
super(params);
|
|
72
73
|
this.params = params;
|
|
73
|
-
this._addVersion("@langchain/google", "0.2.
|
|
74
|
+
this._addVersion("@langchain/google", "0.2.14");
|
|
74
75
|
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.");
|
|
75
76
|
this.apiClient = params.apiClient;
|
|
76
77
|
this.model = params.model;
|
|
@@ -145,6 +146,7 @@ var BaseChatGoogle = class extends _langchain_core_language_models_chat_models.B
|
|
|
145
146
|
const handlerConfig = this.params.apiHandler ?? "generateContent";
|
|
146
147
|
if (typeof handlerConfig === "function") this._apiHandler = handlerConfig(handlerParams);
|
|
147
148
|
else if (handlerConfig === "generateContent") this._apiHandler = new require_generate_content.GenerateContentApiHandler(handlerParams);
|
|
149
|
+
else if (handlerConfig === "interactions") this._apiHandler = new require_interactions.InteractionsApiHandler(handlerParams);
|
|
148
150
|
else throw new require_errors.ConfigurationError(`Unknown apiHandler: ${handlerConfig}`);
|
|
149
151
|
}
|
|
150
152
|
return this._apiHandler;
|
|
@@ -258,7 +260,6 @@ var BaseChatGoogle = class extends _langchain_core_language_models_chat_models.B
|
|
|
258
260
|
return (0, _langchain_core_language_models_structured_output.assembleStructuredOutputPipeline)(llm, outputParser, includeRaw, includeRaw ? "ChatGoogleStructuredOutputRunnable" : "ChatGoogleStructuredOutput");
|
|
259
261
|
}
|
|
260
262
|
};
|
|
261
|
-
//#endregion
|
|
262
263
|
exports.BaseChatGoogle = BaseChatGoogle;
|
|
263
264
|
exports.applyGeminiGatewayParams = applyGeminiGatewayParams;
|
|
264
265
|
exports.getPlatformType = getPlatformType;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"base.cjs","names":["getEnvironmentVariable","convertParamsToPlatformType","resolveLangSmithGatewayConfig","BaseChatModel","ConfigurationError","GenerateContentApiHandler","PROFILES","concat","usageMetadataToTokenUsage","RunnableLambda","AIMessage","AIMessageChunk","MalformedOutputError","createContentParser","createFunctionCallingParser","assembleStructuredOutputPipeline"],"sources":["../../src/chat_models/base.ts"],"sourcesContent":["import {\n BaseChatModel,\n type LangSmithParams,\n} from \"@langchain/core/language_models/chat_models\";\nimport {\n AIMessage,\n AIMessageChunk,\n BaseMessage,\n} from \"@langchain/core/messages\";\nimport { CallbackManagerForLLMRun } from \"@langchain/core/callbacks/manager\";\nimport type { ChatModelStreamEvent } from \"@langchain/core/language_models/event\";\nimport { concat } from \"@langchain/core/utils/stream\";\nimport { ChatGenerationChunk, type ChatResult } from \"@langchain/core/outputs\";\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 type { InteropZodType } from \"@langchain/core/utils/types\";\nimport { ApiClient } from \"../clients/index.js\";\nimport type {\n BaseChatGoogleParams,\n BaseChatGoogleCallOptions,\n GooglePlatformType,\n GenerateContentApiHandlerParams,\n} from \"./types.js\";\nimport { ConfigurationError, MalformedOutputError } from \"../utils/errors.js\";\nimport { usageMetadataToTokenUsage } from \"../utils/metadata.js\";\nimport type { SerializableSchema } from \"@langchain/core/utils/standard_schema\";\nimport {\n assembleStructuredOutputPipeline,\n createContentParser,\n createFunctionCallingParser,\n} from \"@langchain/core/language_models/structured_output\";\nimport { resolveLangSmithGatewayConfig } from \"@langchain/core/utils/gateway\";\nimport { getEnvironmentVariable } from \"@langchain/core/utils/env\";\nimport {\n GoogleChatApiHandler,\n GenerateContentApiHandler,\n} from \"./handlers/index.js\";\nimport { convertParamsToPlatformType } from \"../converters/shared/params.js\";\n\nexport type {\n BaseChatGoogleParams,\n BaseChatGoogleCallOptions,\n GooglePlatformType,\n} from \"./types.js\";\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 exposes direct paths for the Gemini Developer API and\n * Vertex AI. An explicit `endpoint` suppresses gateway routing.\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<TParams extends object>(\n params: TParams\n): TParams & {\n apiKey?: string;\n endpoint?: string;\n platformType?: GooglePlatformType;\n} {\n const p = params as {\n apiKey?: string;\n endpoint?: string;\n platformType?: GooglePlatformType;\n vertexai?: boolean;\n credentials?: unknown;\n googleAuthOptions?: unknown;\n };\n if (typeof p.endpoint !== \"undefined\") {\n return { ...params };\n }\n const platform =\n convertParamsToPlatformType(p) ?? (hasVertexCredentials(p) ? \"gcp\" : \"gai\");\n const gatewayConfig = resolveLangSmithGatewayConfig({\n providerPath: platform === \"gcp\" ? \"vertex\" : \"gemini\",\n });\n if (typeof gatewayConfig.baseURL === \"undefined\") {\n return { ...params };\n }\n\n // 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: p.apiKey ?? gatewayConfig.apiKey,\n endpoint,\n platformType: platform,\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\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(\n protected params: BaseChatGoogleParams & {\n credentials?: unknown;\n googleAuthOptions?: unknown;\n }\n ) {\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 (\n this.platform === \"gcp\" &&\n this.apiClient.hasApiKey() &&\n !hasVertexCredentials(this.params)\n );\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 if (!this.location.includes(\"-\")) {\n return `aiplatform.${this.location}.rep.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 _apiHandler?: GoogleChatApiHandler;\n\n protected _handlerParams?: GenerateContentApiHandlerParams;\n\n protected syncHandlerParams(): GenerateContentApiHandlerParams {\n const nextParams: GenerateContentApiHandlerParams = {\n ...this.params,\n model: this.model,\n platform: this.platform,\n endpoint: this.endpoint,\n location: this.location,\n apiVersion: this.apiVersion,\n isVertexExpress: this.isVertexExpress,\n publisher: this.publisher,\n streaming: this.streaming,\n streamUsage: this.streamUsage,\n customHeaders: this._customHeaders,\n apiClient: this.apiClient,\n caller: this.caller,\n };\n if (this._handlerParams) {\n return Object.assign(this._handlerParams, nextParams);\n }\n this._handlerParams = nextParams;\n return this._handlerParams;\n }\n\n protected get apiHandler(): GoogleChatApiHandler {\n const handlerParams = this.syncHandlerParams();\n if (!this._apiHandler) {\n const handlerConfig = this.params.apiHandler ?? \"generateContent\";\n\n if (typeof handlerConfig === \"function\") {\n this._apiHandler = handlerConfig(handlerParams);\n } else if (handlerConfig === \"generateContent\") {\n this._apiHandler = new GenerateContentApiHandler(handlerParams);\n } else {\n throw new ConfigurationError(`Unknown apiHandler: ${handlerConfig}`);\n }\n }\n return this._apiHandler;\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 async buildUrl(urlMethod?: string): Promise<string> {\n return this.apiHandler.buildUrl(urlMethod);\n }\n\n override invocationParams(\n options: this[\"ParsedCallOptions\"]\n ): Record<string, unknown> {\n return this.apiHandler.invocationParams(options) as Record<string, unknown>;\n }\n\n getLsParams(options: this[\"ParsedCallOptions\"]): LangSmithParams {\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: options?.temperature ?? this.params.temperature,\n ls_max_tokens: options?.maxOutputTokens ?? this.params.maxOutputTokens,\n ls_stop:\n options?.stopSequences ?? options?.stop ?? this.params.stopSequences,\n };\n }\n\n getHeaders(options?: this[\"ParsedCallOptions\"]): HeadersInit {\n return this.apiHandler.getHeaders(options);\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 const usageMetadata = (finalChunk?.message as AIMessageChunk | undefined)\n ?.usage_metadata;\n return {\n generations: finalChunk ? [finalChunk] : [],\n ...(usageMetadata\n ? {\n llmOutput: {\n tokenUsage: usageMetadataToTokenUsage(usageMetadata),\n usageMetadata,\n },\n }\n : {}),\n };\n }\n\n return this.apiHandler.generate(messages, options, runManager);\n }\n\n override async *_streamChatModelEvents(\n messages: BaseMessage[],\n options: this[\"ParsedCallOptions\"],\n runManager?: CallbackManagerForLLMRun\n ): AsyncGenerator<ChatModelStreamEvent> {\n yield* this.apiHandler.streamChatModelEvents(messages, options, runManager);\n }\n\n async *_streamResponseChunks(\n messages: BaseMessage[],\n options: this[\"ParsedCallOptions\"],\n runManager?: CallbackManagerForLLMRun\n ): AsyncGenerator<ChatGenerationChunk> {\n yield* this.apiHandler.streamResponseChunks(messages, options, runManager);\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 const { tools, toolChoice, functionName } =\n this.apiHandler.formatStructuredOutputTool(schema, { name });\n\n llm = this.bindTools(tools).withConfig({\n tool_choice: toolChoice,\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"],"mappings":";;;;;;;;;;;;;;AAmDA,SAAS,qBAAqB,QAGlB;CACV,OACE,OAAO,OAAO,gBAAgB,eAC9B,OAAO,OAAO,sBAAsB,eACpC,QAAA,GAAOA,0BAAAA,uBAAAA,CAAuB,0BAA0B,MAAM;AAElE;;;;;;;;;;;;;;;;;;;;AAqBA,SAAgB,yBACd,QAKA;CACA,MAAM,IAAI;CAQV,IAAI,OAAO,EAAE,aAAa,aACxB,OAAO,EAAE,GAAG,OAAO;CAErB,MAAM,WACJC,eAAAA,4BAA4B,CAAC,MAAM,qBAAqB,CAAC,IAAI,QAAQ;CACvE,MAAM,iBAAA,GAAgBC,8BAAAA,8BAAAA,CAA8B,EAClD,cAAc,aAAa,QAAQ,WAAW,SAChD,CAAC;CACD,IAAI,OAAO,cAAc,YAAY,aACnC,OAAO,EAAE,GAAG,OAAO;CAIrB,MAAM,aAAa,IAAI,IAAI,cAAc,OAAO;CAChD,MAAM,OAAO,WAAW,SAAS,QAAQ,QAAQ,EAAE;CAOnD,MAAM,WACJ,WAAW,aAAa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s","names":["getEnvironmentVariable","convertParamsToPlatformType","resolveLangSmithGatewayConfig","BaseChatModel","ConfigurationError","GenerateContentApiHandler","InteractionsApiHandler","PROFILES","concat","usageMetadataToTokenUsage","RunnableLambda","AIMessage","AIMessageChunk","MalformedOutputError","createContentParser","createFunctionCallingParser","assembleStructuredOutputPipeline"],"sources":["../../src/chat_models/base.ts"],"sourcesContent":["import {\n BaseChatModel,\n type LangSmithParams,\n} from \"@langchain/core/language_models/chat_models\";\nimport {\n AIMessage,\n AIMessageChunk,\n BaseMessage,\n} from \"@langchain/core/messages\";\nimport { CallbackManagerForLLMRun } from \"@langchain/core/callbacks/manager\";\nimport type { ChatModelStreamEvent } from \"@langchain/core/language_models/event\";\nimport { concat } from \"@langchain/core/utils/stream\";\nimport { ChatGenerationChunk, type ChatResult } from \"@langchain/core/outputs\";\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 type { InteropZodType } from \"@langchain/core/utils/types\";\nimport { ApiClient } from \"../clients/index.js\";\nimport type {\n BaseChatGoogleParams,\n BaseChatGoogleCallOptions,\n GooglePlatformType,\n GenerateContentApiHandlerParams,\n InteractionsApiHandlerParams,\n} from \"./types.js\";\nimport { ConfigurationError, MalformedOutputError } from \"../utils/errors.js\";\nimport { usageMetadataToTokenUsage } from \"../utils/metadata.js\";\nimport type { SerializableSchema } from \"@langchain/core/utils/standard_schema\";\nimport {\n assembleStructuredOutputPipeline,\n createContentParser,\n createFunctionCallingParser,\n} from \"@langchain/core/language_models/structured_output\";\nimport { resolveLangSmithGatewayConfig } from \"@langchain/core/utils/gateway\";\nimport { getEnvironmentVariable } from \"@langchain/core/utils/env\";\nimport {\n GoogleChatApiHandler,\n GenerateContentApiHandler,\n InteractionsApiHandler,\n} from \"./handlers/index.js\";\nimport { convertParamsToPlatformType } from \"../converters/shared/params.js\";\n\nexport type {\n BaseChatGoogleParams,\n BaseChatGoogleCallOptions,\n GooglePlatformType,\n} from \"./types.js\";\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 exposes direct paths for the Gemini Developer API and\n * Vertex AI. An explicit `endpoint` or explicit credentials (`apiKey`,\n * `credentials`, `googleAuthOptions`) suppress gateway routing.\n *\n * When `LANGSMITH_GATEWAY` is set, this rewrites `endpoint` to the gateway\n * host and uses the gateway key as the API key. 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<TParams extends object>(\n params: TParams\n): TParams & {\n apiKey?: string;\n endpoint?: string;\n platformType?: GooglePlatformType;\n} {\n const p = params as {\n apiKey?: string;\n endpoint?: string;\n platformType?: GooglePlatformType;\n vertexai?: boolean;\n credentials?: unknown;\n googleAuthOptions?: unknown;\n };\n if (\n typeof p.endpoint !== \"undefined\" ||\n typeof p.apiKey !== \"undefined\" ||\n typeof p.credentials !== \"undefined\" ||\n typeof p.googleAuthOptions !== \"undefined\"\n ) {\n return { ...params };\n }\n const platform =\n convertParamsToPlatformType(p) ?? (hasVertexCredentials(p) ? \"gcp\" : \"gai\");\n const gatewayConfig = resolveLangSmithGatewayConfig({\n providerPath: platform === \"gcp\" ? \"vertex\" : \"gemini\",\n });\n if (typeof gatewayConfig.baseURL === \"undefined\") {\n return { ...params };\n }\n\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: gatewayConfig.apiKey,\n endpoint,\n platformType: platform,\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\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(\n protected params: BaseChatGoogleParams & {\n credentials?: unknown;\n googleAuthOptions?: unknown;\n }\n ) {\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 (\n this.platform === \"gcp\" &&\n this.apiClient.hasApiKey() &&\n !hasVertexCredentials(this.params)\n );\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 if (!this.location.includes(\"-\")) {\n return `aiplatform.${this.location}.rep.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 _apiHandler?: GoogleChatApiHandler;\n\n protected _handlerParams?: GenerateContentApiHandlerParams &\n InteractionsApiHandlerParams;\n\n protected syncHandlerParams(): GenerateContentApiHandlerParams &\n InteractionsApiHandlerParams {\n const nextParams: GenerateContentApiHandlerParams &\n InteractionsApiHandlerParams = {\n ...this.params,\n model: this.model,\n platform: this.platform,\n endpoint: this.endpoint,\n location: this.location,\n apiVersion: this.apiVersion,\n isVertexExpress: this.isVertexExpress,\n publisher: this.publisher,\n streaming: this.streaming,\n streamUsage: this.streamUsage,\n customHeaders: this._customHeaders,\n apiClient: this.apiClient,\n caller: this.caller,\n };\n if (this._handlerParams) {\n return Object.assign(this._handlerParams, nextParams);\n }\n this._handlerParams = nextParams;\n return this._handlerParams;\n }\n\n protected get apiHandler(): GoogleChatApiHandler {\n const handlerParams = this.syncHandlerParams();\n if (!this._apiHandler) {\n const handlerConfig = this.params.apiHandler ?? \"generateContent\";\n\n if (typeof handlerConfig === \"function\") {\n this._apiHandler = handlerConfig(handlerParams);\n } else if (handlerConfig === \"generateContent\") {\n this._apiHandler = new GenerateContentApiHandler(handlerParams);\n } else if (handlerConfig === \"interactions\") {\n this._apiHandler = new InteractionsApiHandler(handlerParams);\n } else {\n throw new ConfigurationError(`Unknown apiHandler: ${handlerConfig}`);\n }\n }\n return this._apiHandler;\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 async buildUrl(urlMethod?: string): Promise<string> {\n return this.apiHandler.buildUrl(urlMethod);\n }\n\n override invocationParams(\n options: this[\"ParsedCallOptions\"]\n ): Record<string, unknown> {\n return this.apiHandler.invocationParams(options) as Record<string, unknown>;\n }\n\n getLsParams(options: this[\"ParsedCallOptions\"]): LangSmithParams {\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: options?.temperature ?? this.params.temperature,\n ls_max_tokens: options?.maxOutputTokens ?? this.params.maxOutputTokens,\n ls_stop:\n options?.stopSequences ?? options?.stop ?? this.params.stopSequences,\n };\n }\n\n getHeaders(options?: this[\"ParsedCallOptions\"]): HeadersInit {\n return this.apiHandler.getHeaders(options);\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 const usageMetadata = (finalChunk?.message as AIMessageChunk | undefined)\n ?.usage_metadata;\n return {\n generations: finalChunk ? [finalChunk] : [],\n ...(usageMetadata\n ? {\n llmOutput: {\n tokenUsage: usageMetadataToTokenUsage(usageMetadata),\n usageMetadata,\n },\n }\n : {}),\n };\n }\n\n return this.apiHandler.generate(messages, options, runManager);\n }\n\n override async *_streamChatModelEvents(\n messages: BaseMessage[],\n options: this[\"ParsedCallOptions\"],\n runManager?: CallbackManagerForLLMRun\n ): AsyncGenerator<ChatModelStreamEvent> {\n yield* this.apiHandler.streamChatModelEvents(messages, options, runManager);\n }\n\n async *_streamResponseChunks(\n messages: BaseMessage[],\n options: this[\"ParsedCallOptions\"],\n runManager?: CallbackManagerForLLMRun\n ): AsyncGenerator<ChatGenerationChunk> {\n yield* this.apiHandler.streamResponseChunks(messages, options, runManager);\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 const { tools, toolChoice, functionName } =\n this.apiHandler.formatStructuredOutputTool(schema, { name });\n\n llm = this.bindTools(tools).withConfig({\n tool_choice: toolChoice,\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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AAK,WAAW,EACpB,gBAAgB,OAClB,CAAyB;GAEzB,eAAeC,0BAAAA,eAAe,KAC5B,OAAO,UAA2C;IAChD,IACE,CAACC,yBAAAA,UAAU,WAAW,KAAK,KAC3B,CAACC,yBAAAA,eAAe,WAAW,KAAK,GAEhC,MAAM,IAAIC,eAAAA,qBAAqB,EAC7B,SAAS,+CACX,CAAC;IAGH,IAAI,CAAC,MAAM,MACT,MAAM,IAAIA,eAAAA,qBAAqB,EAC7B,SACE,gEACJ,CAAC;IAKH,OAAO,OAAA,GADQC,kDAAAA,oBAAAA,CAAoB,MACjB,CAAC,CAAC,MAAM,MAAM,IAAI;GACtC,CACF;EACF,OAAO,IAAI,WAAW,mBAAmB;GACvC,MAAM,EAAE,OAAO,YAAY,iBACzB,KAAK,WAAW,2BAA2B,QAAQ,EAAE,KAAK,CAAC;GAE7D,MAAM,KAAK,UAAU,KAAK,CAAC,CAAC,WAAW,EACrC,aAAa,WACf,CAAyB;GAEzB,gBAAA,GAAeC,kDAAAA,4BAAAA,CAA4B,QAAQ,YAAY;EACjE,OACE,MAAM,IAAIX,eAAAA,mBACR,0CAA0C,OAAO,8CACnD;EAGF,QAAA,GAAOY,kDAAAA,iCAAAA,CACL,KACA,cACA,YACA,aACI,uCACA,4BACN;CACF;AACF"}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { ApiClient } from "../clients/index.cjs";
|
|
2
2
|
import { GoogleChatApiHandler } from "./handlers/base.cjs";
|
|
3
|
-
import { BaseChatGoogleCallOptions, BaseChatGoogleParams, GenerateContentApiHandlerParams, GooglePlatformType } from "./types.cjs";
|
|
3
|
+
import { BaseChatGoogleCallOptions, BaseChatGoogleParams, GenerateContentApiHandlerParams, GooglePlatformType, InteractionsApiHandlerParams } from "./types.cjs";
|
|
4
4
|
import "./handlers/index.cjs";
|
|
5
5
|
import { BaseChatModel, BindToolsInput, LangSmithParams } from "@langchain/core/language_models/chat_models";
|
|
6
6
|
import { AIMessageChunk, BaseMessage } from "@langchain/core/messages";
|
|
@@ -12,7 +12,6 @@ import { BaseLanguageModelInput, StructuredOutputMethodOptions } from "@langchai
|
|
|
12
12
|
import { Runnable } from "@langchain/core/runnables";
|
|
13
13
|
import { InteropZodType } from "@langchain/core/utils/types";
|
|
14
14
|
import { SerializableSchema } from "@langchain/core/utils/standard_schema";
|
|
15
|
-
//#region src/chat_models/base.d.ts
|
|
16
15
|
export declare abstract class BaseChatGoogle<CallOptions extends BaseChatGoogleCallOptions = BaseChatGoogleCallOptions> extends BaseChatModel<CallOptions, AIMessageChunk> {
|
|
17
16
|
protected params: BaseChatGoogleParams & {
|
|
18
17
|
credentials?: unknown;
|
|
@@ -41,8 +40,8 @@ export declare abstract class BaseChatGoogle<CallOptions extends BaseChatGoogleC
|
|
|
41
40
|
protected get endpoint(): string;
|
|
42
41
|
protected get publisher(): string;
|
|
43
42
|
protected _apiHandler?: GoogleChatApiHandler;
|
|
44
|
-
protected _handlerParams?: GenerateContentApiHandlerParams;
|
|
45
|
-
protected syncHandlerParams(): GenerateContentApiHandlerParams;
|
|
43
|
+
protected _handlerParams?: GenerateContentApiHandlerParams & InteractionsApiHandlerParams;
|
|
44
|
+
protected syncHandlerParams(): GenerateContentApiHandlerParams & InteractionsApiHandlerParams;
|
|
46
45
|
protected get apiHandler(): GoogleChatApiHandler;
|
|
47
46
|
/**
|
|
48
47
|
* Returns the model profile for this instance's model, describing its
|
|
@@ -83,6 +82,5 @@ export declare abstract class BaseChatGoogle<CallOptions extends BaseChatGoogleC
|
|
|
83
82
|
parsed: RunOutput;
|
|
84
83
|
}>;
|
|
85
84
|
}
|
|
86
|
-
//#endregion
|
|
87
85
|
export type { BaseChatGoogleCallOptions, BaseChatGoogleParams };
|
|
88
86
|
//# sourceMappingURL=base.d.cts.map
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { ApiClient } from "../clients/index.js";
|
|
2
2
|
import { GoogleChatApiHandler } from "./handlers/base.js";
|
|
3
|
-
import { BaseChatGoogleCallOptions, BaseChatGoogleParams, GenerateContentApiHandlerParams, GooglePlatformType } from "./types.js";
|
|
3
|
+
import { BaseChatGoogleCallOptions, BaseChatGoogleParams, GenerateContentApiHandlerParams, GooglePlatformType, InteractionsApiHandlerParams } from "./types.js";
|
|
4
4
|
import "./handlers/index.js";
|
|
5
5
|
import { BaseChatModel, BindToolsInput, LangSmithParams } from "@langchain/core/language_models/chat_models";
|
|
6
6
|
import { AIMessageChunk, BaseMessage } from "@langchain/core/messages";
|
|
@@ -12,7 +12,6 @@ import { BaseLanguageModelInput, StructuredOutputMethodOptions } from "@langchai
|
|
|
12
12
|
import { CallbackManagerForLLMRun } from "@langchain/core/callbacks/manager";
|
|
13
13
|
import { ChatModelStreamEvent } from "@langchain/core/language_models/event";
|
|
14
14
|
import { ModelProfile } from "@langchain/core/language_models/profile";
|
|
15
|
-
//#region src/chat_models/base.d.ts
|
|
16
15
|
export declare abstract class BaseChatGoogle<CallOptions extends BaseChatGoogleCallOptions = BaseChatGoogleCallOptions> extends BaseChatModel<CallOptions, AIMessageChunk> {
|
|
17
16
|
protected params: BaseChatGoogleParams & {
|
|
18
17
|
credentials?: unknown;
|
|
@@ -41,8 +40,8 @@ export declare abstract class BaseChatGoogle<CallOptions extends BaseChatGoogleC
|
|
|
41
40
|
protected get endpoint(): string;
|
|
42
41
|
protected get publisher(): string;
|
|
43
42
|
protected _apiHandler?: GoogleChatApiHandler;
|
|
44
|
-
protected _handlerParams?: GenerateContentApiHandlerParams;
|
|
45
|
-
protected syncHandlerParams(): GenerateContentApiHandlerParams;
|
|
43
|
+
protected _handlerParams?: GenerateContentApiHandlerParams & InteractionsApiHandlerParams;
|
|
44
|
+
protected syncHandlerParams(): GenerateContentApiHandlerParams & InteractionsApiHandlerParams;
|
|
46
45
|
protected get apiHandler(): GoogleChatApiHandler;
|
|
47
46
|
/**
|
|
48
47
|
* Returns the model profile for this instance's model, describing its
|
|
@@ -83,6 +82,5 @@ export declare abstract class BaseChatGoogle<CallOptions extends BaseChatGoogleC
|
|
|
83
82
|
parsed: RunOutput;
|
|
84
83
|
}>;
|
|
85
84
|
}
|
|
86
|
-
//#endregion
|
|
87
85
|
export type { BaseChatGoogleCallOptions, BaseChatGoogleParams };
|
|
88
86
|
//# sourceMappingURL=base.d.ts.map
|
package/dist/chat_models/base.js
CHANGED
|
@@ -1,9 +1,10 @@
|
|
|
1
|
-
import { ConfigurationError, MalformedOutputError } from "../utils/errors.js";
|
|
2
1
|
import PROFILES from "./profiles.js";
|
|
2
|
+
import { ConfigurationError, MalformedOutputError } from "../utils/errors.js";
|
|
3
3
|
import { usageMetadataToTokenUsage } from "../utils/metadata.js";
|
|
4
|
-
import { convertParamsToPlatformType } from "../converters/shared/params.js";
|
|
5
|
-
import { GenerateContentApiHandler } from "./handlers/generate_content.js";
|
|
6
4
|
import "./handlers/index.js";
|
|
5
|
+
import { GenerateContentApiHandler } from "./handlers/generate_content.js";
|
|
6
|
+
import { InteractionsApiHandler } from "./handlers/interactions.js";
|
|
7
|
+
import { convertParamsToPlatformType } from "../converters/shared/params.js";
|
|
7
8
|
import { getEnvironmentVariable } from "@langchain/core/utils/env";
|
|
8
9
|
import { BaseChatModel } from "@langchain/core/language_models/chat_models";
|
|
9
10
|
import { AIMessage, AIMessageChunk } from "@langchain/core/messages";
|
|
@@ -11,7 +12,7 @@ import { concat } from "@langchain/core/utils/stream";
|
|
|
11
12
|
import { RunnableLambda } from "@langchain/core/runnables";
|
|
12
13
|
import { assembleStructuredOutputPipeline, createContentParser, createFunctionCallingParser } from "@langchain/core/language_models/structured_output";
|
|
13
14
|
import { resolveLangSmithGatewayConfig } from "@langchain/core/utils/gateway";
|
|
14
|
-
|
|
15
|
+
// src/chat_models/base.ts
|
|
15
16
|
function hasVertexCredentials(params) {
|
|
16
17
|
return typeof params.credentials !== "undefined" || typeof params.googleAuthOptions !== "undefined" || typeof getEnvironmentVariable("GOOGLE_CLOUD_CREDENTIALS") !== "undefined";
|
|
17
18
|
}
|
|
@@ -19,11 +20,11 @@ function hasVertexCredentials(params) {
|
|
|
19
20
|
* Resolves LangSmith gateway routing for Google chat model params.
|
|
20
21
|
*
|
|
21
22
|
* The LangSmith gateway exposes direct paths for the Gemini Developer API and
|
|
22
|
-
* Vertex AI. An explicit `endpoint`
|
|
23
|
+
* Vertex AI. An explicit `endpoint` or explicit credentials (`apiKey`,
|
|
24
|
+
* `credentials`, `googleAuthOptions`) suppress gateway routing.
|
|
23
25
|
*
|
|
24
26
|
* When `LANGSMITH_GATEWAY` is set, this rewrites `endpoint` to the gateway
|
|
25
|
-
* host and
|
|
26
|
-
* then rides as the `x-goog-api-key` header via the ApiClient). The default
|
|
27
|
+
* host and uses the gateway key as the API key. The default
|
|
27
28
|
* `https` gateway host is written scheme-less (the URL builders prepend
|
|
28
29
|
* `https://`); a non-`https` custom gateway keeps its scheme so it is not
|
|
29
30
|
* forced to TLS.
|
|
@@ -36,7 +37,7 @@ function hasVertexCredentials(params) {
|
|
|
36
37
|
*/
|
|
37
38
|
function applyGeminiGatewayParams(params) {
|
|
38
39
|
const p = params;
|
|
39
|
-
if (typeof p.endpoint !== "undefined") return { ...params };
|
|
40
|
+
if (typeof p.endpoint !== "undefined" || typeof p.apiKey !== "undefined" || typeof p.credentials !== "undefined" || typeof p.googleAuthOptions !== "undefined") return { ...params };
|
|
40
41
|
const platform = convertParamsToPlatformType(p) ?? (hasVertexCredentials(p) ? "gcp" : "gai");
|
|
41
42
|
const gatewayConfig = resolveLangSmithGatewayConfig({ providerPath: platform === "gcp" ? "vertex" : "gemini" });
|
|
42
43
|
if (typeof gatewayConfig.baseURL === "undefined") return { ...params };
|
|
@@ -45,7 +46,7 @@ function applyGeminiGatewayParams(params) {
|
|
|
45
46
|
const endpoint = gatewayUrl.protocol === "https:" ? `${gatewayUrl.host}${path}` : `${gatewayUrl.protocol}//${gatewayUrl.host}${path}`;
|
|
46
47
|
return {
|
|
47
48
|
...params,
|
|
48
|
-
apiKey:
|
|
49
|
+
apiKey: gatewayConfig.apiKey,
|
|
49
50
|
endpoint,
|
|
50
51
|
platformType: platform
|
|
51
52
|
};
|
|
@@ -70,7 +71,7 @@ var BaseChatGoogle = class extends BaseChatModel {
|
|
|
70
71
|
constructor(params) {
|
|
71
72
|
super(params);
|
|
72
73
|
this.params = params;
|
|
73
|
-
this._addVersion("@langchain/google", "0.2.
|
|
74
|
+
this._addVersion("@langchain/google", "0.2.14");
|
|
74
75
|
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.");
|
|
75
76
|
this.apiClient = params.apiClient;
|
|
76
77
|
this.model = params.model;
|
|
@@ -145,6 +146,7 @@ var BaseChatGoogle = class extends BaseChatModel {
|
|
|
145
146
|
const handlerConfig = this.params.apiHandler ?? "generateContent";
|
|
146
147
|
if (typeof handlerConfig === "function") this._apiHandler = handlerConfig(handlerParams);
|
|
147
148
|
else if (handlerConfig === "generateContent") this._apiHandler = new GenerateContentApiHandler(handlerParams);
|
|
149
|
+
else if (handlerConfig === "interactions") this._apiHandler = new InteractionsApiHandler(handlerParams);
|
|
148
150
|
else throw new ConfigurationError(`Unknown apiHandler: ${handlerConfig}`);
|
|
149
151
|
}
|
|
150
152
|
return this._apiHandler;
|
|
@@ -258,7 +260,6 @@ var BaseChatGoogle = class extends BaseChatModel {
|
|
|
258
260
|
return assembleStructuredOutputPipeline(llm, outputParser, includeRaw, includeRaw ? "ChatGoogleStructuredOutputRunnable" : "ChatGoogleStructuredOutput");
|
|
259
261
|
}
|
|
260
262
|
};
|
|
261
|
-
//#endregion
|
|
262
263
|
export { BaseChatGoogle, applyGeminiGatewayParams, getPlatformType };
|
|
263
264
|
|
|
264
265
|
//# sourceMappingURL=base.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"base.js","names":[],"sources":["../../src/chat_models/base.ts"],"sourcesContent":["import {\n BaseChatModel,\n type LangSmithParams,\n} from \"@langchain/core/language_models/chat_models\";\nimport {\n AIMessage,\n AIMessageChunk,\n BaseMessage,\n} from \"@langchain/core/messages\";\nimport { CallbackManagerForLLMRun } from \"@langchain/core/callbacks/manager\";\nimport type { ChatModelStreamEvent } from \"@langchain/core/language_models/event\";\nimport { concat } from \"@langchain/core/utils/stream\";\nimport { ChatGenerationChunk, type ChatResult } from \"@langchain/core/outputs\";\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 type { InteropZodType } from \"@langchain/core/utils/types\";\nimport { ApiClient } from \"../clients/index.js\";\nimport type {\n BaseChatGoogleParams,\n BaseChatGoogleCallOptions,\n GooglePlatformType,\n GenerateContentApiHandlerParams,\n} from \"./types.js\";\nimport { ConfigurationError, MalformedOutputError } from \"../utils/errors.js\";\nimport { usageMetadataToTokenUsage } from \"../utils/metadata.js\";\nimport type { SerializableSchema } from \"@langchain/core/utils/standard_schema\";\nimport {\n assembleStructuredOutputPipeline,\n createContentParser,\n createFunctionCallingParser,\n} from \"@langchain/core/language_models/structured_output\";\nimport { resolveLangSmithGatewayConfig } from \"@langchain/core/utils/gateway\";\nimport { getEnvironmentVariable } from \"@langchain/core/utils/env\";\nimport {\n GoogleChatApiHandler,\n GenerateContentApiHandler,\n} from \"./handlers/index.js\";\nimport { convertParamsToPlatformType } from \"../converters/shared/params.js\";\n\nexport type {\n BaseChatGoogleParams,\n BaseChatGoogleCallOptions,\n GooglePlatformType,\n} from \"./types.js\";\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 exposes direct paths for the Gemini Developer API and\n * Vertex AI. An explicit `endpoint` suppresses gateway routing.\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<TParams extends object>(\n params: TParams\n): TParams & {\n apiKey?: string;\n endpoint?: string;\n platformType?: GooglePlatformType;\n} {\n const p = params as {\n apiKey?: string;\n endpoint?: string;\n platformType?: GooglePlatformType;\n vertexai?: boolean;\n credentials?: unknown;\n googleAuthOptions?: unknown;\n };\n if (typeof p.endpoint !== \"undefined\") {\n return { ...params };\n }\n const platform =\n convertParamsToPlatformType(p) ?? (hasVertexCredentials(p) ? \"gcp\" : \"gai\");\n const gatewayConfig = resolveLangSmithGatewayConfig({\n providerPath: platform === \"gcp\" ? \"vertex\" : \"gemini\",\n });\n if (typeof gatewayConfig.baseURL === \"undefined\") {\n return { ...params };\n }\n\n // 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: p.apiKey ?? gatewayConfig.apiKey,\n endpoint,\n platformType: platform,\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\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(\n protected params: BaseChatGoogleParams & {\n credentials?: unknown;\n googleAuthOptions?: unknown;\n }\n ) {\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 (\n this.platform === \"gcp\" &&\n this.apiClient.hasApiKey() &&\n !hasVertexCredentials(this.params)\n );\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 if (!this.location.includes(\"-\")) {\n return `aiplatform.${this.location}.rep.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 _apiHandler?: GoogleChatApiHandler;\n\n protected _handlerParams?: GenerateContentApiHandlerParams;\n\n protected syncHandlerParams(): GenerateContentApiHandlerParams {\n const nextParams: GenerateContentApiHandlerParams = {\n ...this.params,\n model: this.model,\n platform: this.platform,\n endpoint: this.endpoint,\n location: this.location,\n apiVersion: this.apiVersion,\n isVertexExpress: this.isVertexExpress,\n publisher: this.publisher,\n streaming: this.streaming,\n streamUsage: this.streamUsage,\n customHeaders: this._customHeaders,\n apiClient: this.apiClient,\n caller: this.caller,\n };\n if (this._handlerParams) {\n return Object.assign(this._handlerParams, nextParams);\n }\n this._handlerParams = nextParams;\n return this._handlerParams;\n }\n\n protected get apiHandler(): GoogleChatApiHandler {\n const handlerParams = this.syncHandlerParams();\n if (!this._apiHandler) {\n const handlerConfig = this.params.apiHandler ?? \"generateContent\";\n\n if (typeof handlerConfig === \"function\") {\n this._apiHandler = handlerConfig(handlerParams);\n } else if (handlerConfig === \"generateContent\") {\n this._apiHandler = new GenerateContentApiHandler(handlerParams);\n } else {\n throw new ConfigurationError(`Unknown apiHandler: ${handlerConfig}`);\n }\n }\n return this._apiHandler;\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 async buildUrl(urlMethod?: string): Promise<string> {\n return this.apiHandler.buildUrl(urlMethod);\n }\n\n override invocationParams(\n options: this[\"ParsedCallOptions\"]\n ): Record<string, unknown> {\n return this.apiHandler.invocationParams(options) as Record<string, unknown>;\n }\n\n getLsParams(options: this[\"ParsedCallOptions\"]): LangSmithParams {\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: options?.temperature ?? this.params.temperature,\n ls_max_tokens: options?.maxOutputTokens ?? this.params.maxOutputTokens,\n ls_stop:\n options?.stopSequences ?? options?.stop ?? this.params.stopSequences,\n };\n }\n\n getHeaders(options?: this[\"ParsedCallOptions\"]): HeadersInit {\n return this.apiHandler.getHeaders(options);\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 const usageMetadata = (finalChunk?.message as AIMessageChunk | undefined)\n ?.usage_metadata;\n return {\n generations: finalChunk ? [finalChunk] : [],\n ...(usageMetadata\n ? {\n llmOutput: {\n tokenUsage: usageMetadataToTokenUsage(usageMetadata),\n usageMetadata,\n },\n }\n : {}),\n };\n }\n\n return this.apiHandler.generate(messages, options, runManager);\n }\n\n override async *_streamChatModelEvents(\n messages: BaseMessage[],\n options: this[\"ParsedCallOptions\"],\n runManager?: CallbackManagerForLLMRun\n ): AsyncGenerator<ChatModelStreamEvent> {\n yield* this.apiHandler.streamChatModelEvents(messages, options, runManager);\n }\n\n async *_streamResponseChunks(\n messages: BaseMessage[],\n options: this[\"ParsedCallOptions\"],\n runManager?: CallbackManagerForLLMRun\n ): AsyncGenerator<ChatGenerationChunk> {\n yield* this.apiHandler.streamResponseChunks(messages, options, runManager);\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 const { tools, toolChoice, functionName } =\n this.apiHandler.formatStructuredOutputTool(schema, { name });\n\n llm = this.bindTools(tools).withConfig({\n tool_choice: toolChoice,\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"],"mappings":";;;;;;;;;;;;;;AAmDA,SAAS,qBAAqB,QAGlB;CACV,OACE,OAAO,OAAO,gBAAgB,eAC9B,OAAO,OAAO,sBAAsB,eACpC,OAAO,uBAAuB,0BAA0B,MAAM;AAElE;;;;;;;;;;;;;;;;;;;;AAqBA,SAAgB,yBACd,QAKA;CACA,MAAM,IAAI;CAQV,IAAI,OAAO,EAAE,aAAa,aACxB,OAAO,EAAE,GAAG,OAAO;CAErB,MAAM,WACJ,4BAA4B,CAAC,MAAM,qBAAqB,CAAC,IAAI,QAAQ;CACvE,MAAM,gBAAgB,8BAA8B,EAClD,cAAc,aAAa,QAAQ,WAAW,SAChD,CAAC;CACD,IAAI,OAAO,cAAc,YAAY,aACnC,OAAO,EAAE,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AU;CAC5E;CAEA,OAAO,sBACL,UACA,SACA,YACqC;EACrC,OAAO,KAAK,WAAW,qBAAqB,UAAU,SAAS,UAAU;CAC3E;;;;;;;;CASA,UACE,OACA,QACsD;EACtD,OAAO,KAAK,WAAW;GACrB,GAAG;GACH;EACF,CAAyB;CAC3B;;;;;;;;;;;;CAmDA,qBAIE,cAKA,QAMI;EACJ,IAAI;EACJ,IAAI;EAEJ,MAAM,EAAE,QAAQ,MAAM,eAAe;GACnC,GAAG;GACH,QAAQ;EACV;EACA,IAAI,SAAS,QAAQ,UAAU;EAE/B,IAAI,WAAW,YAAY;GACzB,QAAQ,KACN,8EACF;GACA,SAAS;EACX;EAEA,IAAI,WAAW,cAAc;GAE3B,MAAM,KAAK,WAAW,EACpB,gBAAgB,OAClB,CAAyB;GAEzB,eAAe,eAAe,KAC5B,OAAO,UAA2C;IAChD,IACE,CAAC,UAAU,WAAW,KAAK,KAC3B,CAAC,eAAe,WAAW,KAAK,GAEhC,MAAM,IAAI,qBAAqB,EAC7B,SAAS,+CACX,CAAC;IAGH,IAAI,CAAC,MAAM,MACT,MAAM,IAAI,qBAAqB,EAC7B,SACE,gEACJ,CAAC;IAKH,OAAO,MADQ,oBAAoB,MACjB,CAAC,CAAC,MAAM,MAAM,IAAI;GACtC,CACF;EACF,OAAO,IAAI,WAAW,mBAAmB;GACvC,MAAM,EAAE,OAAO,YAAY,iBACzB,KAAK,WAAW,2BAA2B,QAAQ,EAAE,KAAK,CAAC;GAE7D,MAAM,KAAK,UAAU,KAAK,CAAC,CAAC,WAAW,EACrC,aAAa,WACf,CAAyB;GAEzB,eAAe,4BAA4B,QAAQ,YAAY;EACjE,OACE,MAAM,IAAI,mBACR,0CAA0C,OAAO,8CACnD;EAGF,OAAO,iCACL,KACA,cACA,YACA,aACI,uCACA,4BACN;CACF;AACF"}
|
|
1
|
+
{"version":3,"file":"base.js","names":[],"sources":["../../src/chat_models/base.ts"],"sourcesContent":["import {\n BaseChatModel,\n type LangSmithParams,\n} from \"@langchain/core/language_models/chat_models\";\nimport {\n AIMessage,\n AIMessageChunk,\n BaseMessage,\n} from \"@langchain/core/messages\";\nimport { CallbackManagerForLLMRun } from \"@langchain/core/callbacks/manager\";\nimport type { ChatModelStreamEvent } from \"@langchain/core/language_models/event\";\nimport { concat } from \"@langchain/core/utils/stream\";\nimport { ChatGenerationChunk, type ChatResult } from \"@langchain/core/outputs\";\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 type { InteropZodType } from \"@langchain/core/utils/types\";\nimport { ApiClient } from \"../clients/index.js\";\nimport type {\n BaseChatGoogleParams,\n BaseChatGoogleCallOptions,\n GooglePlatformType,\n GenerateContentApiHandlerParams,\n InteractionsApiHandlerParams,\n} from \"./types.js\";\nimport { ConfigurationError, MalformedOutputError } from \"../utils/errors.js\";\nimport { usageMetadataToTokenUsage } from \"../utils/metadata.js\";\nimport type { SerializableSchema } from \"@langchain/core/utils/standard_schema\";\nimport {\n assembleStructuredOutputPipeline,\n createContentParser,\n createFunctionCallingParser,\n} from \"@langchain/core/language_models/structured_output\";\nimport { resolveLangSmithGatewayConfig } from \"@langchain/core/utils/gateway\";\nimport { getEnvironmentVariable } from \"@langchain/core/utils/env\";\nimport {\n GoogleChatApiHandler,\n GenerateContentApiHandler,\n InteractionsApiHandler,\n} from \"./handlers/index.js\";\nimport { convertParamsToPlatformType } from \"../converters/shared/params.js\";\n\nexport type {\n BaseChatGoogleParams,\n BaseChatGoogleCallOptions,\n GooglePlatformType,\n} from \"./types.js\";\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 exposes direct paths for the Gemini Developer API and\n * Vertex AI. An explicit `endpoint` or explicit credentials (`apiKey`,\n * `credentials`, `googleAuthOptions`) suppress gateway routing.\n *\n * When `LANGSMITH_GATEWAY` is set, this rewrites `endpoint` to the gateway\n * host and uses the gateway key as the API key. 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<TParams extends object>(\n params: TParams\n): TParams & {\n apiKey?: string;\n endpoint?: string;\n platformType?: GooglePlatformType;\n} {\n const p = params as {\n apiKey?: string;\n endpoint?: string;\n platformType?: GooglePlatformType;\n vertexai?: boolean;\n credentials?: unknown;\n googleAuthOptions?: unknown;\n };\n if (\n typeof p.endpoint !== \"undefined\" ||\n typeof p.apiKey !== \"undefined\" ||\n typeof p.credentials !== \"undefined\" ||\n typeof p.googleAuthOptions !== \"undefined\"\n ) {\n return { ...params };\n }\n const platform =\n convertParamsToPlatformType(p) ?? (hasVertexCredentials(p) ? \"gcp\" : \"gai\");\n const gatewayConfig = resolveLangSmithGatewayConfig({\n providerPath: platform === \"gcp\" ? \"vertex\" : \"gemini\",\n });\n if (typeof gatewayConfig.baseURL === \"undefined\") {\n return { ...params };\n }\n\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: gatewayConfig.apiKey,\n endpoint,\n platformType: platform,\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\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(\n protected params: BaseChatGoogleParams & {\n credentials?: unknown;\n googleAuthOptions?: unknown;\n }\n ) {\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 (\n this.platform === \"gcp\" &&\n this.apiClient.hasApiKey() &&\n !hasVertexCredentials(this.params)\n );\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 if (!this.location.includes(\"-\")) {\n return `aiplatform.${this.location}.rep.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 _apiHandler?: GoogleChatApiHandler;\n\n protected _handlerParams?: GenerateContentApiHandlerParams &\n InteractionsApiHandlerParams;\n\n protected syncHandlerParams(): GenerateContentApiHandlerParams &\n InteractionsApiHandlerParams {\n const nextParams: GenerateContentApiHandlerParams &\n InteractionsApiHandlerParams = {\n ...this.params,\n model: this.model,\n platform: this.platform,\n endpoint: this.endpoint,\n location: this.location,\n apiVersion: this.apiVersion,\n isVertexExpress: this.isVertexExpress,\n publisher: this.publisher,\n streaming: this.streaming,\n streamUsage: this.streamUsage,\n customHeaders: this._customHeaders,\n apiClient: this.apiClient,\n caller: this.caller,\n };\n if (this._handlerParams) {\n return Object.assign(this._handlerParams, nextParams);\n }\n this._handlerParams = nextParams;\n return this._handlerParams;\n }\n\n protected get apiHandler(): GoogleChatApiHandler {\n const handlerParams = this.syncHandlerParams();\n if (!this._apiHandler) {\n const handlerConfig = this.params.apiHandler ?? \"generateContent\";\n\n if (typeof handlerConfig === \"function\") {\n this._apiHandler = handlerConfig(handlerParams);\n } else if (handlerConfig === \"generateContent\") {\n this._apiHandler = new GenerateContentApiHandler(handlerParams);\n } else if (handlerConfig === \"interactions\") {\n this._apiHandler = new InteractionsApiHandler(handlerParams);\n } else {\n throw new ConfigurationError(`Unknown apiHandler: ${handlerConfig}`);\n }\n }\n return this._apiHandler;\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 async buildUrl(urlMethod?: string): Promise<string> {\n return this.apiHandler.buildUrl(urlMethod);\n }\n\n override invocationParams(\n options: this[\"ParsedCallOptions\"]\n ): Record<string, unknown> {\n return this.apiHandler.invocationParams(options) as Record<string, unknown>;\n }\n\n getLsParams(options: this[\"ParsedCallOptions\"]): LangSmithParams {\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: options?.temperature ?? this.params.temperature,\n ls_max_tokens: options?.maxOutputTokens ?? this.params.maxOutputTokens,\n ls_stop:\n options?.stopSequences ?? options?.stop ?? this.params.stopSequences,\n };\n }\n\n getHeaders(options?: this[\"ParsedCallOptions\"]): HeadersInit {\n return this.apiHandler.getHeaders(options);\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 const usageMetadata = (finalChunk?.message as AIMessageChunk | undefined)\n ?.usage_metadata;\n return {\n generations: finalChunk ? [finalChunk] : [],\n ...(usageMetadata\n ? {\n llmOutput: {\n tokenUsage: usageMetadataToTokenUsage(usageMetadata),\n usageMetadata,\n },\n }\n : {}),\n };\n }\n\n return this.apiHandler.generate(messages, options, runManager);\n }\n\n override async *_streamChatModelEvents(\n messages: BaseMessage[],\n options: this[\"ParsedCallOptions\"],\n runManager?: CallbackManagerForLLMRun\n ): AsyncGenerator<ChatModelStreamEvent> {\n yield* this.apiHandler.streamChatModelEvents(messages, options, runManager);\n }\n\n async *_streamResponseChunks(\n messages: BaseMessage[],\n options: this[\"ParsedCallOptions\"],\n runManager?: CallbackManagerForLLMRun\n ): AsyncGenerator<ChatGenerationChunk> {\n yield* this.apiHandler.streamResponseChunks(messages, options, runManager);\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 const { tools, toolChoice, functionName } =\n this.apiHandler.formatStructuredOutputTool(schema, { name });\n\n llm = this.bindTools(tools).withConfig({\n tool_choice: toolChoice,\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"],"mappings":";;;;;;;;;;;;;;;AAqDA,SAAS,qBAAqB,QAGlB;CACV,OACE,OAAO,OAAO,gBAAgB,eAC9B,OAAO,OAAO,sBAAsB,eACpC,OAAO,uBAAuB,0BAA0B,MAAM;AAElE;;;;;;;;;;;;;;;;;;;;AAqBA,SAAgB,yBACd,QAKA;CACA,MAAM,IAAI;CAQV,IACE,O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AAK,WAAW,2BAA2B,QAAQ,EAAE,KAAK,CAAC;GAE7D,MAAM,KAAK,UAAU,KAAK,CAAC,CAAC,WAAW,EACrC,aAAa,WACf,CAAyB;GAEzB,eAAe,4BAA4B,QAAQ,YAAY;EACjE,OACE,MAAM,IAAI,mBACR,0CAA0C,OAAO,8CACnD;EAGF,OAAO,iCACL,KACA,cACA,YACA,aACI,uCACA,4BACN;CACF;AACF"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
|
|
1
|
+
// src/chat_models/handlers/base.ts
|
|
2
2
|
/**
|
|
3
3
|
* Base abstract handler for Google Chat wire protocols.
|
|
4
4
|
*
|
|
@@ -57,7 +57,6 @@ var GoogleChatApiHandler = class {
|
|
|
57
57
|
};
|
|
58
58
|
}
|
|
59
59
|
};
|
|
60
|
-
//#endregion
|
|
61
60
|
exports.GoogleChatApiHandler = GoogleChatApiHandler;
|
|
62
61
|
|
|
63
62
|
//# sourceMappingURL=base.cjs.map
|
|
@@ -6,7 +6,6 @@ import { ChatModelStreamEvent } from "@langchain/core/language_models/event";
|
|
|
6
6
|
import { ChatGenerationChunk, ChatResult } from "@langchain/core/outputs";
|
|
7
7
|
import { InteropZodType } from "@langchain/core/utils/types";
|
|
8
8
|
import { SerializableSchema } from "@langchain/core/utils/standard_schema";
|
|
9
|
-
//#region src/chat_models/handlers/base.d.ts
|
|
10
9
|
/**
|
|
11
10
|
* Base abstract handler for Google Chat wire protocols.
|
|
12
11
|
*
|
|
@@ -44,5 +43,4 @@ export declare abstract class GoogleChatApiHandler<TInvocationParams extends obj
|
|
|
44
43
|
};
|
|
45
44
|
abstract streamChatModelEvents(messages: BaseMessage[], options?: BaseChatGoogleCallOptions, runManager?: CallbackManagerForLLMRun): AsyncGenerator<ChatModelStreamEvent>;
|
|
46
45
|
}
|
|
47
|
-
//#endregion
|
|
48
46
|
//# sourceMappingURL=base.d.cts.map
|
|
@@ -6,7 +6,6 @@ import { InteropZodType } from "@langchain/core/utils/types";
|
|
|
6
6
|
import { SerializableSchema } from "@langchain/core/utils/standard_schema";
|
|
7
7
|
import { CallbackManagerForLLMRun } from "@langchain/core/callbacks/manager";
|
|
8
8
|
import { ChatModelStreamEvent } from "@langchain/core/language_models/event";
|
|
9
|
-
//#region src/chat_models/handlers/base.d.ts
|
|
10
9
|
/**
|
|
11
10
|
* Base abstract handler for Google Chat wire protocols.
|
|
12
11
|
*
|
|
@@ -44,5 +43,4 @@ export declare abstract class GoogleChatApiHandler<TInvocationParams extends obj
|
|
|
44
43
|
};
|
|
45
44
|
abstract streamChatModelEvents(messages: BaseMessage[], options?: BaseChatGoogleCallOptions, runManager?: CallbackManagerForLLMRun): AsyncGenerator<ChatModelStreamEvent>;
|
|
46
45
|
}
|
|
47
|
-
//#endregion
|
|
48
46
|
//# sourceMappingURL=base.d.ts.map
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
|
|
1
|
+
// src/chat_models/handlers/base.ts
|
|
2
2
|
/**
|
|
3
3
|
* Base abstract handler for Google Chat wire protocols.
|
|
4
4
|
*
|
|
@@ -57,7 +57,6 @@ var GoogleChatApiHandler = class {
|
|
|
57
57
|
};
|
|
58
58
|
}
|
|
59
59
|
};
|
|
60
|
-
//#endregion
|
|
61
60
|
export { GoogleChatApiHandler };
|
|
62
61
|
|
|
63
62
|
//# sourceMappingURL=base.js.map
|
|
@@ -1,20 +1,20 @@
|
|
|
1
|
-
const require_misc = require("../../utils/misc.cjs");
|
|
2
|
-
const require_errors = require("../../utils/errors.cjs");
|
|
3
|
-
const require_metadata = require("../../utils/metadata.cjs");
|
|
4
1
|
const require_base = require("./base.cjs");
|
|
5
2
|
const require_stream = require("../../utils/stream.cjs");
|
|
3
|
+
const require_metadata = require("../../utils/metadata.cjs");
|
|
4
|
+
const require_misc = require("../../utils/misc.cjs");
|
|
5
|
+
const require_errors = require("../../utils/errors.cjs");
|
|
6
6
|
const require_messages = require("../../converters/generate_content/messages.cjs");
|
|
7
7
|
const require_tools = require("../../converters/generate_content/tools.cjs");
|
|
8
|
-
const require_types = require("../types.cjs");
|
|
9
8
|
const require_params = require("../../converters/generate_content/params.cjs");
|
|
10
9
|
const require_stream_events = require("../../converters/generate_content/stream_events.cjs");
|
|
10
|
+
const require_types = require("../types.cjs");
|
|
11
11
|
let _langchain_core_messages = require("@langchain/core/messages");
|
|
12
12
|
let _langchain_core_outputs = require("@langchain/core/outputs");
|
|
13
13
|
let _langchain_core_utils_types = require("@langchain/core/utils/types");
|
|
14
14
|
let _langchain_core_utils_standard_schema = require("@langchain/core/utils/standard_schema");
|
|
15
15
|
let _langchain_core_utils_json_schema = require("@langchain/core/utils/json_schema");
|
|
16
16
|
let eventsource_parser_stream = require("eventsource-parser/stream");
|
|
17
|
-
|
|
17
|
+
// src/chat_models/handlers/generate_content.ts
|
|
18
18
|
/**
|
|
19
19
|
* Concrete wire protocol handler for Google's Generate Content API
|
|
20
20
|
* (`/v1beta/models/{model}:generateContent` and `:streamGenerateContent`).
|
|
@@ -78,7 +78,7 @@ var GenerateContentApiHandler = class extends require_base.GoogleChatApiHandler
|
|
|
78
78
|
status: response.status,
|
|
79
79
|
statusText: response.statusText
|
|
80
80
|
});
|
|
81
|
-
if (data.promptFeedback?.blockReason) throw require_errors.
|
|
81
|
+
if (data.promptFeedback?.blockReason) throw require_errors.promptBlockedError(data.promptFeedback);
|
|
82
82
|
if (!data.candidates || data.candidates.length === 0) throw new require_errors.NoCandidatesError();
|
|
83
83
|
const candidate = data.candidates[0];
|
|
84
84
|
const message = require_messages.convertGeminiCandidateToAIMessage(candidate);
|
|
@@ -164,6 +164,7 @@ var GenerateContentApiHandler = class extends require_base.GoogleChatApiHandler
|
|
|
164
164
|
}));
|
|
165
165
|
return;
|
|
166
166
|
}
|
|
167
|
+
if (chunk.promptFeedback?.blockReason) throw require_errors.promptBlockedError(chunk.promptFeedback);
|
|
167
168
|
const candidate = chunk.candidates?.[0];
|
|
168
169
|
if (!candidate) {
|
|
169
170
|
if (chunk.usageMetadata && streamUsage) {
|
|
@@ -339,7 +340,6 @@ var GenerateContentApiHandler = class extends require_base.GoogleChatApiHandler
|
|
|
339
340
|
};
|
|
340
341
|
}
|
|
341
342
|
};
|
|
342
|
-
//#endregion
|
|
343
343
|
exports.GenerateContentApiHandler = GenerateContentApiHandler;
|
|
344
344
|
|
|
345
345
|
//# sourceMappingURL=generate_content.cjs.map
|