@langchain/google-common 2.1.23 → 2.1.25
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 +16 -0
- package/dist/chat_models.cjs +20 -36
- package/dist/chat_models.cjs.map +1 -1
- package/dist/chat_models.d.cts +3 -2
- package/dist/chat_models.d.cts.map +1 -1
- package/dist/chat_models.d.ts +4 -3
- package/dist/chat_models.d.ts.map +1 -1
- package/dist/chat_models.js +20 -36
- package/dist/chat_models.js.map +1 -1
- package/dist/llms.cjs +1 -1
- package/dist/llms.js +1 -1
- package/dist/output_parsers.d.ts +1 -1
- package/dist/utils/zod_to_gemini_parameters.cjs +2 -1
- package/dist/utils/zod_to_gemini_parameters.cjs.map +1 -1
- package/dist/utils/zod_to_gemini_parameters.d.cts +2 -1
- package/dist/utils/zod_to_gemini_parameters.d.cts.map +1 -1
- package/dist/utils/zod_to_gemini_parameters.d.ts +2 -1
- package/dist/utils/zod_to_gemini_parameters.d.ts.map +1 -1
- package/dist/utils/zod_to_gemini_parameters.js +2 -1
- package/dist/utils/zod_to_gemini_parameters.js.map +1 -1
- package/package.json +5 -5
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,21 @@
|
|
|
1
1
|
# @langchain/google-common
|
|
2
2
|
|
|
3
|
+
## 2.1.25
|
|
4
|
+
|
|
5
|
+
### Patch Changes
|
|
6
|
+
|
|
7
|
+
- Updated dependencies [[`26488b5`](https://github.com/langchain-ai/langchainjs/commit/26488b596f01b7b7fe2f1d97d07164e52365ade5), [`ca826f6`](https://github.com/langchain-ai/langchainjs/commit/ca826f6fecae6087bf0dee7781ee80b587396ec1), [`a602c42`](https://github.com/langchain-ai/langchainjs/commit/a602c42db75d7e7e01cab38b12e0b65b9c0cce95), [`db7d017`](https://github.com/langchain-ai/langchainjs/commit/db7d017f7ce13cb937147aabcbfa3847d80bde9d)]:
|
|
8
|
+
- @langchain/core@1.1.32
|
|
9
|
+
|
|
10
|
+
## 2.1.24
|
|
11
|
+
|
|
12
|
+
### Patch Changes
|
|
13
|
+
|
|
14
|
+
- [#10208](https://github.com/langchain-ai/langchainjs/pull/10208) [`745b09a`](https://github.com/langchain-ai/langchainjs/commit/745b09a1b0c92643cbc99e773012924948438629) Thanks [@colifran](https://github.com/colifran)! - feat(google-common): implement standard schema support for structured output
|
|
15
|
+
|
|
16
|
+
- Updated dependencies [[`96c630d`](https://github.com/langchain-ai/langchainjs/commit/96c630dfd009f2546d5bc36f5067ff868bb4067f), [`a8b9ccc`](https://github.com/langchain-ai/langchainjs/commit/a8b9ccca5a85984a5a30008acd09f9991e591638), [`a1f22bb`](https://github.com/langchain-ai/langchainjs/commit/a1f22bba907731a18dca23c31cec5333444a3f55)]:
|
|
17
|
+
- @langchain/core@1.1.30
|
|
18
|
+
|
|
3
19
|
## 2.1.23
|
|
4
20
|
|
|
5
21
|
### Patch Changes
|
package/dist/chat_models.cjs
CHANGED
|
@@ -9,11 +9,10 @@ let _langchain_core_utils_env = require("@langchain/core/utils/env");
|
|
|
9
9
|
let _langchain_core_language_models_chat_models = require("@langchain/core/language_models/chat_models");
|
|
10
10
|
let _langchain_core_outputs = require("@langchain/core/outputs");
|
|
11
11
|
let _langchain_core_messages = require("@langchain/core/messages");
|
|
12
|
-
let _langchain_core_runnables = require("@langchain/core/runnables");
|
|
13
|
-
let _langchain_core_output_parsers_openai_tools = require("@langchain/core/output_parsers/openai_tools");
|
|
14
|
-
let _langchain_core_output_parsers = require("@langchain/core/output_parsers");
|
|
15
12
|
let _langchain_core_utils_stream = require("@langchain/core/utils/stream");
|
|
16
13
|
let _langchain_core_utils_types = require("@langchain/core/utils/types");
|
|
14
|
+
let _langchain_core_utils_standard_schema = require("@langchain/core/utils/standard_schema");
|
|
15
|
+
let _langchain_core_language_models_structured_output = require("@langchain/core/language_models/structured_output");
|
|
17
16
|
|
|
18
17
|
//#region src/chat_models.ts
|
|
19
18
|
var ChatConnection = class extends require_connection.AbstractGoogleLLMConnection {
|
|
@@ -96,7 +95,7 @@ var ChatGoogleBase = class extends _langchain_core_language_models_chat_models.B
|
|
|
96
95
|
streamedConnection;
|
|
97
96
|
constructor(fields) {
|
|
98
97
|
super(require_failed_handler.ensureParams(fields));
|
|
99
|
-
this._addVersion("@langchain/google-common", "2.1.
|
|
98
|
+
this._addVersion("@langchain/google-common", "2.1.25");
|
|
100
99
|
require_common.copyAndValidateModelParamsInto(fields, this);
|
|
101
100
|
this.safetyHandler = fields?.safetyHandler ?? new require_gemini.DefaultGeminiSafetyHandler();
|
|
102
101
|
this.streamUsage = fields?.streamUsage ?? this.streamUsage;
|
|
@@ -222,49 +221,34 @@ var ChatGoogleBase = class extends _langchain_core_language_models_chat_models.B
|
|
|
222
221
|
let outputParser;
|
|
223
222
|
if (method === "functionCalling") {
|
|
224
223
|
let functionName = name ?? "extract";
|
|
225
|
-
let
|
|
226
|
-
if ((0, _langchain_core_utils_types.isInteropZodSchema)(schema)) {
|
|
224
|
+
let geminiFunctionDeclaration;
|
|
225
|
+
if ((0, _langchain_core_utils_types.isInteropZodSchema)(schema) || (0, _langchain_core_utils_standard_schema.isSerializableSchema)(schema)) {
|
|
227
226
|
const jsonSchema = require_zod_to_gemini_parameters.schemaToGeminiParameters(schema);
|
|
228
|
-
|
|
227
|
+
geminiFunctionDeclaration = {
|
|
229
228
|
name: functionName,
|
|
230
229
|
description: jsonSchema.description ?? "A function available to call.",
|
|
231
230
|
parameters: jsonSchema
|
|
232
|
-
}
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
zodSchema: schema
|
|
237
|
-
});
|
|
231
|
+
};
|
|
232
|
+
} else if (typeof schema.name === "string" && typeof schema.parameters === "object" && schema.parameters != null) {
|
|
233
|
+
geminiFunctionDeclaration = schema;
|
|
234
|
+
functionName = schema.name;
|
|
238
235
|
} else {
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
geminiFunctionDefinition = {
|
|
246
|
-
name: functionName,
|
|
247
|
-
description: schema.description ?? "",
|
|
248
|
-
parameters
|
|
249
|
-
};
|
|
250
|
-
}
|
|
251
|
-
tools = [{ functionDeclarations: [geminiFunctionDefinition] }];
|
|
252
|
-
outputParser = new _langchain_core_output_parsers_openai_tools.JsonOutputKeyToolsParser({
|
|
253
|
-
returnSingle: true,
|
|
254
|
-
keyName: functionName
|
|
255
|
-
});
|
|
236
|
+
const parameters = require_zod_to_gemini_parameters.removeAdditionalProperties(schema);
|
|
237
|
+
geminiFunctionDeclaration = {
|
|
238
|
+
name: functionName,
|
|
239
|
+
description: schema.description ?? "",
|
|
240
|
+
parameters
|
|
241
|
+
};
|
|
256
242
|
}
|
|
243
|
+
const tools = [{ functionDeclarations: [geminiFunctionDeclaration] }];
|
|
257
244
|
llm = this.bindTools(tools).withConfig({ tool_choice: functionName });
|
|
245
|
+
outputParser = (0, _langchain_core_language_models_structured_output.createFunctionCallingParser)(schema, functionName);
|
|
258
246
|
} else {
|
|
259
247
|
const jsonSchema = require_zod_to_gemini_parameters.schemaToGeminiParameters(schema);
|
|
260
248
|
llm = this.withConfig({ responseSchema: jsonSchema });
|
|
261
|
-
outputParser =
|
|
249
|
+
outputParser = (0, _langchain_core_language_models_structured_output.createContentParser)(schema);
|
|
262
250
|
}
|
|
263
|
-
|
|
264
|
-
const parserAssign = _langchain_core_runnables.RunnablePassthrough.assign({ parsed: (input, config) => outputParser.invoke(input.raw, config) });
|
|
265
|
-
const parserNone = _langchain_core_runnables.RunnablePassthrough.assign({ parsed: () => null });
|
|
266
|
-
const parsedWithFallback = parserAssign.withFallbacks({ fallbacks: [parserNone] });
|
|
267
|
-
return _langchain_core_runnables.RunnableSequence.from([{ raw: llm }, parsedWithFallback]).withConfig({ runName: "StructuredOutputRunnable" });
|
|
251
|
+
return (0, _langchain_core_language_models_structured_output.assembleStructuredOutputPipeline)(llm, outputParser, includeRaw, includeRaw ? "StructuredOutputRunnable" : "ChatGoogleStructuredOutput");
|
|
268
252
|
}
|
|
269
253
|
};
|
|
270
254
|
|
package/dist/chat_models.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"chat_models.cjs","names":["AbstractGoogleLLMConnection","getGeminiAPI","BaseChatModel","ensureParams","DefaultGeminiSafetyHandler","ApiKeyGoogleAuth","convertToGeminiTools","copyAIModelParams","ChatGenerationChunk","AIMessageChunk","PROFILES","schemaToGeminiParameters","JsonOutputKeyToolsParser","removeAdditionalProperties","JsonOutputParser","RunnablePassthrough","RunnableSequence"],"sources":["../src/chat_models.ts"],"sourcesContent":["import { getEnvironmentVariable } from \"@langchain/core/utils/env\";\nimport { UsageMetadata, type BaseMessage } from \"@langchain/core/messages\";\nimport { CallbackManagerForLLMRun } from \"@langchain/core/callbacks/manager\";\n\nimport {\n BaseChatModel,\n LangSmithParams,\n type BaseChatModelParams,\n} from \"@langchain/core/language_models/chat_models\";\nimport { ChatGenerationChunk, ChatResult } from \"@langchain/core/outputs\";\nimport { AIMessageChunk } from \"@langchain/core/messages\";\nimport {\n BaseLanguageModelInput,\n StructuredOutputMethodOptions,\n} from \"@langchain/core/language_models/base\";\nimport { type ModelProfile } from \"@langchain/core/language_models/profile\";\nimport {\n Runnable,\n RunnablePassthrough,\n RunnableSequence,\n} from \"@langchain/core/runnables\";\nimport { JsonOutputKeyToolsParser } from \"@langchain/core/output_parsers/openai_tools\";\nimport {\n BaseLLMOutputParser,\n JsonOutputParser,\n} from \"@langchain/core/output_parsers\";\nimport { AsyncCaller } from \"@langchain/core/utils/async_caller\";\nimport { concat } from \"@langchain/core/utils/stream\";\nimport {\n InteropZodType,\n isInteropZodSchema,\n} from \"@langchain/core/utils/types\";\nimport {\n GoogleAIBaseLLMInput,\n GoogleAIModelParams,\n GoogleAISafetySetting,\n GoogleConnectionParams,\n GooglePlatformType,\n GeminiTool,\n GoogleAIBaseLanguageModelCallOptions,\n GoogleAIAPI,\n GoogleAIAPIParams,\n GoogleSearchToolSetting,\n GoogleSpeechConfig,\n GeminiJsonSchema,\n} from \"./types.js\";\nimport {\n convertToGeminiTools,\n copyAIModelParams,\n copyAndValidateModelParamsInto,\n} from \"./utils/common.js\";\nimport { AbstractGoogleLLMConnection } from \"./connection.js\";\nimport { DefaultGeminiSafetyHandler, getGeminiAPI } from \"./utils/gemini.js\";\nimport { ApiKeyGoogleAuth, GoogleAbstractedClient } from \"./auth.js\";\nimport { JsonStream } from \"./utils/stream.js\";\nimport { ensureParams } from \"./utils/failed_handler.js\";\nimport type {\n GoogleBaseLLMInput,\n GoogleAISafetyHandler,\n GoogleAISafetyParams,\n GeminiFunctionDeclaration,\n GeminiFunctionSchema,\n GoogleAIToolType,\n GeminiAPIConfig,\n GoogleAIModelModality,\n} from \"./types.js\";\nimport {\n removeAdditionalProperties,\n schemaToGeminiParameters,\n} from \"./utils/zod_to_gemini_parameters.js\";\nimport PROFILES from \"./profiles.js\";\n\nexport class ChatConnection<AuthOptions> extends AbstractGoogleLLMConnection<\n BaseMessage[],\n AuthOptions\n> {\n convertSystemMessageToHumanContent: boolean | undefined;\n\n constructor(\n fields: GoogleAIBaseLLMInput<AuthOptions> | undefined,\n caller: AsyncCaller,\n client: GoogleAbstractedClient,\n streaming: boolean\n ) {\n super(fields, caller, client, streaming);\n this.convertSystemMessageToHumanContent =\n fields?.convertSystemMessageToHumanContent;\n }\n\n get useSystemInstruction(): boolean {\n return typeof this.convertSystemMessageToHumanContent === \"boolean\"\n ? !this.convertSystemMessageToHumanContent\n : this.computeUseSystemInstruction;\n }\n\n get computeUseSystemInstruction(): boolean {\n // This works on models from April 2024 and later\n // Vertex AI: gemini-1.5-pro and gemini-1.0-002 and later\n // AI Studio: gemini-1.5-pro-latest\n if (this.modelFamily === \"palm\") {\n return false;\n } else if (this.modelName === \"gemini-1.0-pro-001\") {\n return false;\n } else if (this.modelName.startsWith(\"gemini-pro-vision\")) {\n return false;\n } else if (this.modelName.startsWith(\"gemini-1.0-pro-vision\")) {\n return false;\n } else if (this.modelName === \"gemini-pro\" && this.platform === \"gai\") {\n // on AI Studio gemini-pro is still pointing at gemini-1.0-pro-001\n return false;\n } else if (this.modelFamily === \"gemma\") {\n // At least as of 12 Mar 2025 gemma 3 on AIS, trying to use system instructions yields an error:\n // \"Developer instruction is not enabled for models/gemma-3-27b-it\"\n return false;\n }\n return true;\n }\n\n computeGoogleSearchToolAdjustmentFromModel(): Exclude<\n GoogleSearchToolSetting,\n boolean\n > {\n if (this.modelName.startsWith(\"gemini-1.0\")) {\n return \"googleSearchRetrieval\";\n } else if (this.modelName.startsWith(\"gemini-1.5\")) {\n return \"googleSearchRetrieval\";\n } else {\n return \"googleSearch\";\n }\n }\n\n computeGoogleSearchToolAdjustment(\n apiConfig: GeminiAPIConfig\n ): Exclude<GoogleSearchToolSetting, true> {\n const adj = apiConfig.googleSearchToolAdjustment;\n if (adj === undefined || adj === true) {\n return this.computeGoogleSearchToolAdjustmentFromModel();\n } else {\n return adj;\n }\n }\n\n buildGeminiAPI(): GoogleAIAPI {\n const apiConfig: GeminiAPIConfig =\n (this.apiConfig as GeminiAPIConfig) ?? {};\n const googleSearchToolAdjustment =\n this.computeGoogleSearchToolAdjustment(apiConfig);\n const geminiConfig: GeminiAPIConfig = {\n useSystemInstruction: this.useSystemInstruction,\n googleSearchToolAdjustment,\n ...apiConfig,\n };\n return getGeminiAPI(geminiConfig);\n }\n\n get api(): GoogleAIAPI {\n switch (this.apiName) {\n case \"google\":\n return this.buildGeminiAPI();\n default:\n return super.api;\n }\n }\n}\n\n/**\n * Input to chat model class.\n */\nexport interface ChatGoogleBaseInput<AuthOptions>\n extends\n BaseChatModelParams,\n GoogleConnectionParams<AuthOptions>,\n GoogleAIModelParams,\n GoogleAISafetyParams,\n GoogleAIAPIParams,\n Pick<GoogleAIBaseLanguageModelCallOptions, \"streamUsage\"> {}\n\n/**\n * Integration with a Google chat model.\n */\nexport abstract class ChatGoogleBase<AuthOptions>\n extends BaseChatModel<GoogleAIBaseLanguageModelCallOptions, AIMessageChunk>\n implements ChatGoogleBaseInput<AuthOptions>\n{\n // Used for tracing, replace with the same name as your class\n static lc_name() {\n return \"ChatGoogle\";\n }\n\n get lc_secrets(): { [key: string]: string } | undefined {\n return {\n authOptions: \"GOOGLE_AUTH_OPTIONS\",\n };\n }\n\n lc_serializable = true;\n\n // Set based on modelName\n model: string;\n\n modelName = \"gemini-pro\";\n\n temperature: number;\n\n maxOutputTokens: number;\n\n maxReasoningTokens: number;\n\n topP: number;\n\n topK: number;\n\n seed: number;\n\n presencePenalty: number;\n\n frequencyPenalty: number;\n\n stopSequences: string[] = [];\n\n logprobs: boolean;\n\n topLogprobs: number = 0;\n\n safetySettings: GoogleAISafetySetting[] = [];\n\n responseModalities?: GoogleAIModelModality[];\n\n // May intentionally be undefined, meaning to compute this.\n convertSystemMessageToHumanContent: boolean | undefined;\n\n safetyHandler: GoogleAISafetyHandler;\n\n speechConfig: GoogleSpeechConfig;\n\n streamUsage = true;\n\n streaming = false;\n\n labels?: Record<string, string>;\n\n protected connection: ChatConnection<AuthOptions>;\n\n protected streamedConnection: ChatConnection<AuthOptions>;\n\n constructor(fields?: ChatGoogleBaseInput<AuthOptions>) {\n super(ensureParams(fields));\n this._addVersion(\"@langchain/google-common\", __PKG_VERSION__);\n\n copyAndValidateModelParamsInto(fields, this);\n this.safetyHandler =\n fields?.safetyHandler ?? new DefaultGeminiSafetyHandler();\n this.streamUsage = fields?.streamUsage ?? this.streamUsage;\n const client = this.buildClient(fields);\n this.buildConnection(fields ?? {}, client);\n }\n\n getLsParams(options: this[\"ParsedCallOptions\"]): LangSmithParams {\n const params = this.invocationParams(options);\n return {\n ls_provider: \"google_vertexai\",\n ls_model_name: this.model,\n ls_model_type: \"chat\",\n ls_temperature: params.temperature ?? undefined,\n ls_max_tokens: params.maxOutputTokens ?? undefined,\n ls_stop: options.stop,\n };\n }\n\n abstract buildAbstractedClient(\n fields?: GoogleAIBaseLLMInput<AuthOptions>\n ): GoogleAbstractedClient;\n\n buildApiKeyClient(apiKey: string): GoogleAbstractedClient {\n return new ApiKeyGoogleAuth(apiKey);\n }\n\n buildApiKey(fields?: GoogleAIBaseLLMInput<AuthOptions>): string | undefined {\n return fields?.apiKey ?? getEnvironmentVariable(\"GOOGLE_API_KEY\");\n }\n\n buildClient(\n fields?: GoogleAIBaseLLMInput<AuthOptions>\n ): GoogleAbstractedClient {\n const apiKey = this.buildApiKey(fields);\n if (apiKey) {\n return this.buildApiKeyClient(apiKey);\n } else {\n return this.buildAbstractedClient(fields);\n }\n }\n\n buildConnection(\n fields: GoogleBaseLLMInput<AuthOptions>,\n client: GoogleAbstractedClient\n ) {\n this.connection = new ChatConnection(\n { ...fields, ...this },\n this.caller,\n client,\n false\n );\n\n this.streamedConnection = new ChatConnection(\n { ...fields, ...this },\n this.caller,\n client,\n true\n );\n }\n\n get platform(): GooglePlatformType {\n return this.connection.platform;\n }\n\n override bindTools(\n tools: GoogleAIToolType[],\n kwargs?: Partial<GoogleAIBaseLanguageModelCallOptions>\n ): Runnable<\n BaseLanguageModelInput,\n AIMessageChunk,\n GoogleAIBaseLanguageModelCallOptions\n > {\n return this.withConfig({ tools: convertToGeminiTools(tools), ...kwargs });\n }\n\n _llmType() {\n return \"google\";\n }\n\n /**\n * Get the parameters used to invoke the model\n */\n override invocationParams(options?: this[\"ParsedCallOptions\"]) {\n return copyAIModelParams(this, options);\n }\n\n async _generate(\n messages: BaseMessage[],\n options: this[\"ParsedCallOptions\"],\n runManager: CallbackManagerForLLMRun | undefined\n ): Promise<ChatResult> {\n options.signal?.throwIfAborted();\n const parameters = this.invocationParams(options);\n if (this.streaming) {\n const stream = this._streamResponseChunks(messages, options, runManager);\n let finalChunk: ChatGenerationChunk | null = null;\n for await (const chunk of stream) {\n finalChunk = !finalChunk ? chunk : concat(finalChunk, chunk);\n }\n if (!finalChunk) {\n throw new Error(\"No chunks were returned from the stream.\");\n }\n return {\n generations: [finalChunk],\n };\n }\n\n const response = await this.connection.request(\n messages,\n parameters,\n options,\n runManager\n );\n const ret = this.connection.api.responseToChatResult(response);\n const chunk = ret?.generations?.[0];\n if (chunk) {\n await runManager?.handleLLMNewToken(chunk.text || \"\");\n }\n return ret;\n }\n\n async *_streamResponseChunks(\n _messages: BaseMessage[],\n options: this[\"ParsedCallOptions\"],\n runManager?: CallbackManagerForLLMRun\n ): AsyncGenerator<ChatGenerationChunk> {\n // Make the call as a streaming request\n const parameters = this.invocationParams(options);\n const response = await this.streamedConnection.request(\n _messages,\n parameters,\n options,\n runManager\n );\n\n // Get the streaming parser of the response\n const stream = response.data as JsonStream;\n let usageMetadata: UsageMetadata | undefined;\n // Loop until the end of the stream\n // During the loop, yield each time we get a chunk from the streaming parser\n // that is either available or added to the queue\n while (!stream.streamDone) {\n if (options.signal?.aborted) {\n return;\n }\n const output = await stream.nextChunk();\n await runManager?.handleCustomEvent(\n `google-chunk-${this.constructor.name}`,\n {\n output,\n }\n );\n if (\n output &&\n output.usageMetadata &&\n this.streamUsage !== false &&\n options.streamUsage !== false\n ) {\n usageMetadata = {\n input_tokens: output.usageMetadata.promptTokenCount,\n output_tokens: output.usageMetadata.candidatesTokenCount,\n total_tokens: output.usageMetadata.totalTokenCount,\n };\n }\n const chunk =\n output !== null\n ? this.connection.api.responseToChatGeneration({ data: output })\n : new ChatGenerationChunk({\n text: \"\",\n generationInfo: { finishReason: \"stop\" },\n message: new AIMessageChunk({\n content: \"\",\n usage_metadata: usageMetadata,\n }),\n });\n if (chunk) {\n yield chunk;\n await runManager?.handleLLMNewToken(\n chunk.text ?? \"\",\n undefined,\n undefined,\n undefined,\n undefined,\n { chunk }\n );\n }\n }\n }\n\n /** @ignore */\n _combineLLMOutput() {\n return [];\n }\n\n /**\n * Return profiling information for the model.\n *\n * Provides information about the model's capabilities and constraints,\n * including token limits, multimodal support, and advanced features like\n * tool calling and structured output.\n *\n * @returns {ModelProfile} An object describing the model's capabilities and constraints\n */\n get profile(): ModelProfile {\n return PROFILES[this.model] ?? {};\n }\n\n withStructuredOutput<\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n RunOutput extends Record<string, any> = Record<string, any>,\n >(\n outputSchema:\n | InteropZodType<RunOutput>\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n | Record<string, any>,\n config?: StructuredOutputMethodOptions<false>\n ): Runnable<BaseLanguageModelInput, RunOutput>;\n\n withStructuredOutput<\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n RunOutput extends Record<string, any> = Record<string, any>,\n >(\n outputSchema:\n | InteropZodType<RunOutput>\n // eslint-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 // eslint-disable-next-line @typescript-eslint/no-explicit-any\n RunOutput extends Record<string, any> = Record<string, any>,\n >(\n outputSchema:\n | InteropZodType<RunOutput>\n // eslint-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 // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const schema: InteropZodType<RunOutput> | Record<string, any> =\n outputSchema;\n const name = config?.name;\n const method = config?.method;\n const includeRaw = config?.includeRaw;\n if (method === \"jsonMode\") {\n throw new Error(\n `Google only supports \"jsonSchema\" or \"functionCalling\" as a method.`\n );\n }\n\n let llm;\n let outputParser: BaseLLMOutputParser<RunOutput>;\n if (method === \"functionCalling\") {\n let functionName = name ?? \"extract\";\n let tools: GeminiTool[];\n if (isInteropZodSchema(schema)) {\n const jsonSchema = schemaToGeminiParameters(schema);\n tools = [\n {\n functionDeclarations: [\n {\n name: functionName,\n description:\n jsonSchema.description ?? \"A function available to call.\",\n parameters: jsonSchema as GeminiFunctionSchema,\n },\n ],\n },\n ];\n outputParser = new JsonOutputKeyToolsParser({\n returnSingle: true,\n keyName: functionName,\n zodSchema: schema,\n });\n } else {\n let geminiFunctionDefinition: GeminiFunctionDeclaration;\n if (\n typeof schema.name === \"string\" &&\n typeof schema.parameters === \"object\" &&\n schema.parameters != null\n ) {\n geminiFunctionDefinition = schema as GeminiFunctionDeclaration;\n functionName = schema.name;\n } else {\n // We are providing the schema for *just* the parameters, probably\n const parameters: GeminiJsonSchema =\n removeAdditionalProperties(schema);\n geminiFunctionDefinition = {\n name: functionName,\n description: schema.description ?? \"\",\n parameters,\n };\n }\n tools = [\n {\n functionDeclarations: [geminiFunctionDefinition],\n },\n ];\n outputParser = new JsonOutputKeyToolsParser<RunOutput>({\n returnSingle: true,\n keyName: functionName,\n });\n }\n llm = this.bindTools(tools).withConfig({ tool_choice: functionName });\n } else {\n // Default to jsonSchema method\n const jsonSchema = schemaToGeminiParameters(schema);\n llm = this.withConfig({\n responseSchema: jsonSchema as GeminiJsonSchema,\n });\n outputParser = new JsonOutputParser();\n }\n\n if (!includeRaw) {\n return llm.pipe(outputParser).withConfig({\n runName: \"ChatGoogleStructuredOutput\",\n }) as Runnable<BaseLanguageModelInput, RunOutput>;\n }\n\n const parserAssign = RunnablePassthrough.assign({\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n parsed: (input: any, config) => outputParser.invoke(input.raw, config),\n });\n const parserNone = RunnablePassthrough.assign({\n parsed: () => null,\n });\n const parsedWithFallback = parserAssign.withFallbacks({\n fallbacks: [parserNone],\n });\n return RunnableSequence.from<\n BaseLanguageModelInput,\n { raw: BaseMessage; parsed: RunOutput }\n >([\n {\n raw: llm,\n },\n parsedWithFallback,\n ]).withConfig({\n runName: \"StructuredOutputRunnable\",\n });\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAwEA,IAAa,iBAAb,cAAiDA,+CAG/C;CACA;CAEA,YACE,QACA,QACA,QACA,WACA;AACA,QAAM,QAAQ,QAAQ,QAAQ,UAAU;AACxC,OAAK,qCACH,QAAQ;;CAGZ,IAAI,uBAAgC;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WAAW,EACvC,SAAS,8BACV,CAAC;EAGJ,MAAM,eAAeC,8CAAoB,OAAO,EAE9C,SAAS,OAAY,WAAW,aAAa,OAAO,MAAM,KAAK,OAAO,EACvE,CAAC;EACF,MAAM,aAAaA,8CAAoB,OAAO,EAC5C,cAAc,MACf,CAAC;EACF,MAAM,qBAAqB,aAAa,cAAc,EACpD,WAAW,CAAC,WAAW,EACxB,CAAC;AACF,SAAOC,2CAAiB,KAGtB,CACA,EACE,KAAK,KACN,EACD,mBACD,CAAC,CAAC,WAAW,EACZ,SAAS,4BACV,CAAC"}
|
|
1
|
+
{"version":3,"file":"chat_models.cjs","names":["AbstractGoogleLLMConnection","getGeminiAPI","BaseChatModel","ensureParams","DefaultGeminiSafetyHandler","ApiKeyGoogleAuth","convertToGeminiTools","copyAIModelParams","ChatGenerationChunk","AIMessageChunk","PROFILES","schemaToGeminiParameters","removeAdditionalProperties"],"sources":["../src/chat_models.ts"],"sourcesContent":["import { getEnvironmentVariable } from \"@langchain/core/utils/env\";\nimport { UsageMetadata, type BaseMessage } from \"@langchain/core/messages\";\nimport { CallbackManagerForLLMRun } from \"@langchain/core/callbacks/manager\";\n\nimport {\n BaseChatModel,\n LangSmithParams,\n type BaseChatModelParams,\n} from \"@langchain/core/language_models/chat_models\";\nimport { ChatGenerationChunk, ChatResult } from \"@langchain/core/outputs\";\nimport { AIMessageChunk } from \"@langchain/core/messages\";\nimport {\n BaseLanguageModelInput,\n StructuredOutputMethodOptions,\n} from \"@langchain/core/language_models/base\";\nimport { type ModelProfile } from \"@langchain/core/language_models/profile\";\nimport { Runnable } from \"@langchain/core/runnables\";\nimport { AsyncCaller } from \"@langchain/core/utils/async_caller\";\nimport { concat } from \"@langchain/core/utils/stream\";\nimport {\n InteropZodType,\n isInteropZodSchema,\n} from \"@langchain/core/utils/types\";\nimport {\n GoogleAIBaseLLMInput,\n GoogleAIModelParams,\n GoogleAISafetySetting,\n GoogleConnectionParams,\n GooglePlatformType,\n GeminiTool,\n GoogleAIBaseLanguageModelCallOptions,\n GoogleAIAPI,\n GoogleAIAPIParams,\n GoogleSearchToolSetting,\n GoogleSpeechConfig,\n GeminiJsonSchema,\n} from \"./types.js\";\nimport {\n convertToGeminiTools,\n copyAIModelParams,\n copyAndValidateModelParamsInto,\n} from \"./utils/common.js\";\nimport { AbstractGoogleLLMConnection } from \"./connection.js\";\nimport { DefaultGeminiSafetyHandler, getGeminiAPI } from \"./utils/gemini.js\";\nimport { ApiKeyGoogleAuth, GoogleAbstractedClient } from \"./auth.js\";\nimport { JsonStream } from \"./utils/stream.js\";\nimport { ensureParams } from \"./utils/failed_handler.js\";\nimport type {\n GoogleBaseLLMInput,\n GoogleAISafetyHandler,\n GoogleAISafetyParams,\n GeminiFunctionDeclaration,\n GeminiFunctionSchema,\n GoogleAIToolType,\n GeminiAPIConfig,\n GoogleAIModelModality,\n} from \"./types.js\";\nimport {\n removeAdditionalProperties,\n schemaToGeminiParameters,\n} from \"./utils/zod_to_gemini_parameters.js\";\nimport PROFILES from \"./profiles.js\";\nimport {\n isSerializableSchema,\n SerializableSchema,\n} from \"@langchain/core/utils/standard_schema\";\nimport {\n assembleStructuredOutputPipeline,\n createContentParser,\n createFunctionCallingParser,\n} from \"@langchain/core/language_models/structured_output\";\n\nexport class ChatConnection<AuthOptions> extends AbstractGoogleLLMConnection<\n BaseMessage[],\n AuthOptions\n> {\n convertSystemMessageToHumanContent: boolean | undefined;\n\n constructor(\n fields: GoogleAIBaseLLMInput<AuthOptions> | undefined,\n caller: AsyncCaller,\n client: GoogleAbstractedClient,\n streaming: boolean\n ) {\n super(fields, caller, client, streaming);\n this.convertSystemMessageToHumanContent =\n fields?.convertSystemMessageToHumanContent;\n }\n\n get useSystemInstruction(): boolean {\n return typeof this.convertSystemMessageToHumanContent === \"boolean\"\n ? !this.convertSystemMessageToHumanContent\n : this.computeUseSystemInstruction;\n }\n\n get computeUseSystemInstruction(): boolean {\n // This works on models from April 2024 and later\n // Vertex AI: gemini-1.5-pro and gemini-1.0-002 and later\n // AI Studio: gemini-1.5-pro-latest\n if (this.modelFamily === \"palm\") {\n return false;\n } else if (this.modelName === \"gemini-1.0-pro-001\") {\n return false;\n } else if (this.modelName.startsWith(\"gemini-pro-vision\")) {\n return false;\n } else if (this.modelName.startsWith(\"gemini-1.0-pro-vision\")) {\n return false;\n } else if (this.modelName === \"gemini-pro\" && this.platform === \"gai\") {\n // on AI Studio gemini-pro is still pointing at gemini-1.0-pro-001\n return false;\n } else if (this.modelFamily === \"gemma\") {\n // At least as of 12 Mar 2025 gemma 3 on AIS, trying to use system instructions yields an error:\n // \"Developer instruction is not enabled for models/gemma-3-27b-it\"\n return false;\n }\n return true;\n }\n\n computeGoogleSearchToolAdjustmentFromModel(): Exclude<\n GoogleSearchToolSetting,\n boolean\n > {\n if (this.modelName.startsWith(\"gemini-1.0\")) {\n return \"googleSearchRetrieval\";\n } else if (this.modelName.startsWith(\"gemini-1.5\")) {\n return \"googleSearchRetrieval\";\n } else {\n return \"googleSearch\";\n }\n }\n\n computeGoogleSearchToolAdjustment(\n apiConfig: GeminiAPIConfig\n ): Exclude<GoogleSearchToolSetting, true> {\n const adj = apiConfig.googleSearchToolAdjustment;\n if (adj === undefined || adj === true) {\n return this.computeGoogleSearchToolAdjustmentFromModel();\n } else {\n return adj;\n }\n }\n\n buildGeminiAPI(): GoogleAIAPI {\n const apiConfig: GeminiAPIConfig =\n (this.apiConfig as GeminiAPIConfig) ?? {};\n const googleSearchToolAdjustment =\n this.computeGoogleSearchToolAdjustment(apiConfig);\n const geminiConfig: GeminiAPIConfig = {\n useSystemInstruction: this.useSystemInstruction,\n googleSearchToolAdjustment,\n ...apiConfig,\n };\n return getGeminiAPI(geminiConfig);\n }\n\n get api(): GoogleAIAPI {\n switch (this.apiName) {\n case \"google\":\n return this.buildGeminiAPI();\n default:\n return super.api;\n }\n }\n}\n\n/**\n * Input to chat model class.\n */\nexport interface ChatGoogleBaseInput<AuthOptions>\n extends\n BaseChatModelParams,\n GoogleConnectionParams<AuthOptions>,\n GoogleAIModelParams,\n GoogleAISafetyParams,\n GoogleAIAPIParams,\n Pick<GoogleAIBaseLanguageModelCallOptions, \"streamUsage\"> {}\n\n/**\n * Integration with a Google chat model.\n */\nexport abstract class ChatGoogleBase<AuthOptions>\n extends BaseChatModel<GoogleAIBaseLanguageModelCallOptions, AIMessageChunk>\n implements ChatGoogleBaseInput<AuthOptions>\n{\n // Used for tracing, replace with the same name as your class\n static lc_name() {\n return \"ChatGoogle\";\n }\n\n get lc_secrets(): { [key: string]: string } | undefined {\n return {\n authOptions: \"GOOGLE_AUTH_OPTIONS\",\n };\n }\n\n lc_serializable = true;\n\n // Set based on modelName\n model: string;\n\n modelName = \"gemini-pro\";\n\n temperature: number;\n\n maxOutputTokens: number;\n\n maxReasoningTokens: number;\n\n topP: number;\n\n topK: number;\n\n seed: number;\n\n presencePenalty: number;\n\n frequencyPenalty: number;\n\n stopSequences: string[] = [];\n\n logprobs: boolean;\n\n topLogprobs: number = 0;\n\n safetySettings: GoogleAISafetySetting[] = [];\n\n responseModalities?: GoogleAIModelModality[];\n\n // May intentionally be undefined, meaning to compute this.\n convertSystemMessageToHumanContent: boolean | undefined;\n\n safetyHandler: GoogleAISafetyHandler;\n\n speechConfig: GoogleSpeechConfig;\n\n streamUsage = true;\n\n streaming = false;\n\n labels?: Record<string, string>;\n\n protected connection: ChatConnection<AuthOptions>;\n\n protected streamedConnection: ChatConnection<AuthOptions>;\n\n constructor(fields?: ChatGoogleBaseInput<AuthOptions>) {\n super(ensureParams(fields));\n this._addVersion(\"@langchain/google-common\", __PKG_VERSION__);\n\n copyAndValidateModelParamsInto(fields, this);\n this.safetyHandler =\n fields?.safetyHandler ?? new DefaultGeminiSafetyHandler();\n this.streamUsage = fields?.streamUsage ?? this.streamUsage;\n const client = this.buildClient(fields);\n this.buildConnection(fields ?? {}, client);\n }\n\n getLsParams(options: this[\"ParsedCallOptions\"]): LangSmithParams {\n const params = this.invocationParams(options);\n return {\n ls_provider: \"google_vertexai\",\n ls_model_name: this.model,\n ls_model_type: \"chat\",\n ls_temperature: params.temperature ?? undefined,\n ls_max_tokens: params.maxOutputTokens ?? undefined,\n ls_stop: options.stop,\n };\n }\n\n abstract buildAbstractedClient(\n fields?: GoogleAIBaseLLMInput<AuthOptions>\n ): GoogleAbstractedClient;\n\n buildApiKeyClient(apiKey: string): GoogleAbstractedClient {\n return new ApiKeyGoogleAuth(apiKey);\n }\n\n buildApiKey(fields?: GoogleAIBaseLLMInput<AuthOptions>): string | undefined {\n return fields?.apiKey ?? getEnvironmentVariable(\"GOOGLE_API_KEY\");\n }\n\n buildClient(\n fields?: GoogleAIBaseLLMInput<AuthOptions>\n ): GoogleAbstractedClient {\n const apiKey = this.buildApiKey(fields);\n if (apiKey) {\n return this.buildApiKeyClient(apiKey);\n } else {\n return this.buildAbstractedClient(fields);\n }\n }\n\n buildConnection(\n fields: GoogleBaseLLMInput<AuthOptions>,\n client: GoogleAbstractedClient\n ) {\n this.connection = new ChatConnection(\n { ...fields, ...this },\n this.caller,\n client,\n false\n );\n\n this.streamedConnection = new ChatConnection(\n { ...fields, ...this },\n this.caller,\n client,\n true\n );\n }\n\n get platform(): GooglePlatformType {\n return this.connection.platform;\n }\n\n override bindTools(\n tools: GoogleAIToolType[],\n kwargs?: Partial<GoogleAIBaseLanguageModelCallOptions>\n ): Runnable<\n BaseLanguageModelInput,\n AIMessageChunk,\n GoogleAIBaseLanguageModelCallOptions\n > {\n return this.withConfig({ tools: convertToGeminiTools(tools), ...kwargs });\n }\n\n _llmType() {\n return \"google\";\n }\n\n /**\n * Get the parameters used to invoke the model\n */\n override invocationParams(options?: this[\"ParsedCallOptions\"]) {\n return copyAIModelParams(this, options);\n }\n\n async _generate(\n messages: BaseMessage[],\n options: this[\"ParsedCallOptions\"],\n runManager: CallbackManagerForLLMRun | undefined\n ): Promise<ChatResult> {\n options.signal?.throwIfAborted();\n const parameters = this.invocationParams(options);\n if (this.streaming) {\n const stream = this._streamResponseChunks(messages, options, runManager);\n let finalChunk: ChatGenerationChunk | null = null;\n for await (const chunk of stream) {\n finalChunk = !finalChunk ? chunk : concat(finalChunk, chunk);\n }\n if (!finalChunk) {\n throw new Error(\"No chunks were returned from the stream.\");\n }\n return {\n generations: [finalChunk],\n };\n }\n\n const response = await this.connection.request(\n messages,\n parameters,\n options,\n runManager\n );\n const ret = this.connection.api.responseToChatResult(response);\n const chunk = ret?.generations?.[0];\n if (chunk) {\n await runManager?.handleLLMNewToken(chunk.text || \"\");\n }\n return ret;\n }\n\n async *_streamResponseChunks(\n _messages: BaseMessage[],\n options: this[\"ParsedCallOptions\"],\n runManager?: CallbackManagerForLLMRun\n ): AsyncGenerator<ChatGenerationChunk> {\n // Make the call as a streaming request\n const parameters = this.invocationParams(options);\n const response = await this.streamedConnection.request(\n _messages,\n parameters,\n options,\n runManager\n );\n\n // Get the streaming parser of the response\n const stream = response.data as JsonStream;\n let usageMetadata: UsageMetadata | undefined;\n // Loop until the end of the stream\n // During the loop, yield each time we get a chunk from the streaming parser\n // that is either available or added to the queue\n while (!stream.streamDone) {\n if (options.signal?.aborted) {\n return;\n }\n const output = await stream.nextChunk();\n await runManager?.handleCustomEvent(\n `google-chunk-${this.constructor.name}`,\n {\n output,\n }\n );\n if (\n output &&\n output.usageMetadata &&\n this.streamUsage !== false &&\n options.streamUsage !== false\n ) {\n usageMetadata = {\n input_tokens: output.usageMetadata.promptTokenCount,\n output_tokens: output.usageMetadata.candidatesTokenCount,\n total_tokens: output.usageMetadata.totalTokenCount,\n };\n }\n const chunk =\n output !== null\n ? this.connection.api.responseToChatGeneration({ data: output })\n : new ChatGenerationChunk({\n text: \"\",\n generationInfo: { finishReason: \"stop\" },\n message: new AIMessageChunk({\n content: \"\",\n usage_metadata: usageMetadata,\n }),\n });\n if (chunk) {\n yield chunk;\n await runManager?.handleLLMNewToken(\n chunk.text ?? \"\",\n undefined,\n undefined,\n undefined,\n undefined,\n { chunk }\n );\n }\n }\n }\n\n /** @ignore */\n _combineLLMOutput() {\n return [];\n }\n\n /**\n * Return profiling information for the model.\n *\n * Provides information about the model's capabilities and constraints,\n * including token limits, multimodal support, and advanced features like\n * tool calling and structured output.\n *\n * @returns {ModelProfile} An object describing the model's capabilities and constraints\n */\n get profile(): ModelProfile {\n return PROFILES[this.model] ?? {};\n }\n\n withStructuredOutput<\n // eslint-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 // eslint-disable-next-line @typescript-eslint/no-explicit-any\n | Record<string, any>,\n config?: StructuredOutputMethodOptions<false>\n ): Runnable<BaseLanguageModelInput, RunOutput>;\n\n withStructuredOutput<\n // eslint-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 // eslint-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 // eslint-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 // eslint-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 const schema = outputSchema;\n const name = config?.name;\n const method = config?.method;\n const includeRaw = config?.includeRaw;\n\n if (method === \"jsonMode\") {\n throw new Error(\n `Google only supports \"jsonSchema\" or \"functionCalling\" as a method.`\n );\n }\n\n let llm: Runnable<BaseLanguageModelInput>;\n let outputParser: Runnable<AIMessageChunk, RunOutput>;\n\n if (method === \"functionCalling\") {\n let functionName = name ?? \"extract\";\n let geminiFunctionDeclaration: GeminiFunctionDeclaration;\n if (isInteropZodSchema(schema) || isSerializableSchema(schema)) {\n const jsonSchema = schemaToGeminiParameters(schema);\n geminiFunctionDeclaration = {\n name: functionName,\n description:\n jsonSchema.description ?? \"A function available to call.\",\n parameters: jsonSchema as GeminiFunctionSchema,\n };\n } else if (\n typeof schema.name === \"string\" &&\n typeof schema.parameters === \"object\" &&\n schema.parameters != null\n ) {\n geminiFunctionDeclaration = schema as GeminiFunctionDeclaration;\n functionName = schema.name;\n } else {\n // We are providing the schema for *just* the parameters, probably\n const parameters: GeminiJsonSchema = removeAdditionalProperties(schema);\n geminiFunctionDeclaration = {\n name: functionName,\n description: schema.description ?? \"\",\n parameters,\n };\n }\n\n const tools: GeminiTool[] = [\n { functionDeclarations: [geminiFunctionDeclaration] },\n ];\n llm = this.bindTools(tools).withConfig({ tool_choice: functionName });\n\n outputParser = createFunctionCallingParser(schema, functionName);\n } else {\n // Default to jsonSchema method\n const jsonSchema = schemaToGeminiParameters(schema);\n llm = this.withConfig({\n responseSchema: jsonSchema as GeminiJsonSchema,\n });\n outputParser = createContentParser(schema);\n }\n\n return assembleStructuredOutputPipeline(\n llm,\n outputParser,\n includeRaw,\n includeRaw ? \"StructuredOutputRunnable\" : \"ChatGoogleStructuredOutput\"\n );\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AAwEA,IAAa,iBAAb,cAAiDA,+CAG/C;CACA;CAEA,YACE,QACA,QACA,QACA,WACA;AACA,QAAM,QAAQ,QAAQ,QAAQ,UAAU;AACxC,OAAK,qCACH,QAAQ;;CAGZ,IAAI,uBAAgC;AAClC,SAAO,OAAO,KAAK,uCAAuC,YACtD,CAAC,KAAK,qCACN,KAAK;;CAGX,IAAI,8BAAuC;AAIzC,MAAI,KAAK,gBAAgB,OACvB,QAAO;WACE,KAAK,cAAc,qBAC5B,QAAO;WACE,KAAK,UAAU,WAAW,oBAAoB,CACvD,QAAO;WACE,KAAK,UAAU,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AQ;EACrB,MAAM,SAAS,QAAQ;EACvB,MAAM,aAAa,QAAQ;AAE3B,MAAI,WAAW,WACb,OAAM,IAAI,MACR,sEACD;EAGH,IAAI;EACJ,IAAI;AAEJ,MAAI,WAAW,mBAAmB;GAChC,IAAI,eAAe,QAAQ;GAC3B,IAAI;AACJ,2DAAuB,OAAO,oEAAyB,OAAO,EAAE;IAC9D,MAAM,aAAaC,0DAAyB,OAAO;AACnD,gCAA4B;KAC1B,MAAM;KACN,aACE,WAAW,eAAe;KAC5B,YAAY;KACb;cAED,OAAO,OAAO,SAAS,YACvB,OAAO,OAAO,eAAe,YAC7B,OAAO,cAAc,MACrB;AACA,gCAA4B;AAC5B,mBAAe,OAAO;UACjB;IAEL,MAAM,aAA+BC,4DAA2B,OAAO;AACvE,gCAA4B;KAC1B,MAAM;KACN,aAAa,OAAO,eAAe;KACnC;KACD;;GAGH,MAAM,QAAsB,CAC1B,EAAE,sBAAsB,CAAC,0BAA0B,EAAE,CACtD;AACD,SAAM,KAAK,UAAU,MAAM,CAAC,WAAW,EAAE,aAAa,cAAc,CAAC;AAErE,qGAA2C,QAAQ,aAAa;SAC3D;GAEL,MAAM,aAAaD,0DAAyB,OAAO;AACnD,SAAM,KAAK,WAAW,EACpB,gBAAgB,YACjB,CAAC;AACF,6FAAmC,OAAO;;AAG5C,iGACE,KACA,cACA,YACA,aAAa,6BAA6B,6BAC3C"}
|
package/dist/chat_models.d.cts
CHANGED
|
@@ -10,6 +10,7 @@ import { CallbackManagerForLLMRun } from "@langchain/core/callbacks/manager";
|
|
|
10
10
|
import { ModelProfile } from "@langchain/core/language_models/profile";
|
|
11
11
|
import { Runnable } from "@langchain/core/runnables";
|
|
12
12
|
import { InteropZodType } from "@langchain/core/utils/types";
|
|
13
|
+
import { SerializableSchema } from "@langchain/core/utils/standard_schema";
|
|
13
14
|
|
|
14
15
|
//#region src/chat_models.d.ts
|
|
15
16
|
declare class ChatConnection<AuthOptions> extends AbstractGoogleLLMConnection<BaseMessage[], AuthOptions> {
|
|
@@ -86,8 +87,8 @@ declare abstract class ChatGoogleBase<AuthOptions> extends BaseChatModel<GoogleA
|
|
|
86
87
|
* @returns {ModelProfile} An object describing the model's capabilities and constraints
|
|
87
88
|
*/
|
|
88
89
|
get profile(): ModelProfile;
|
|
89
|
-
withStructuredOutput<RunOutput extends Record<string, any> = Record<string, any>>(outputSchema: InteropZodType<RunOutput> | Record<string, any>, config?: StructuredOutputMethodOptions<false>): Runnable<BaseLanguageModelInput, RunOutput>;
|
|
90
|
-
withStructuredOutput<RunOutput extends Record<string, any> = Record<string, any>>(outputSchema: InteropZodType<RunOutput> | Record<string, any>, config?: StructuredOutputMethodOptions<true>): Runnable<BaseLanguageModelInput, {
|
|
90
|
+
withStructuredOutput<RunOutput extends Record<string, any> = Record<string, any>>(outputSchema: InteropZodType<RunOutput> | SerializableSchema<RunOutput> | Record<string, any>, config?: StructuredOutputMethodOptions<false>): Runnable<BaseLanguageModelInput, RunOutput>;
|
|
91
|
+
withStructuredOutput<RunOutput extends Record<string, any> = Record<string, any>>(outputSchema: InteropZodType<RunOutput> | SerializableSchema<RunOutput> | Record<string, any>, config?: StructuredOutputMethodOptions<true>): Runnable<BaseLanguageModelInput, {
|
|
91
92
|
raw: BaseMessage;
|
|
92
93
|
parsed: RunOutput;
|
|
93
94
|
}>;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"chat_models.d.cts","names":[],"sources":["../src/chat_models.ts"],"mappings":"
|
|
1
|
+
{"version":3,"file":"chat_models.d.cts","names":[],"sources":["../src/chat_models.ts"],"mappings":";;;;;;;;;;;;;;;cAwEa,cAAA,sBAAoC,2BAAA,CAC/C,WAAA,IACA,WAAA;EAEA,kCAAA;EAEA,WAAA,CACE,MAAA,EAAQ,oBAAA,CAAqB,WAAA,eAC7B,MAAA,EAAQ,WAAA,EACR,MAAA,EAAQ,sBAAA,EACR,SAAA;EAAA,IAOE,oBAAA,CAAA;EAAA,IAMA,2BAAA,CAAA;E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,kBAAA,CAAmB,WAAA,GAC3B,MAAA,EAAQ,sBAAA;EAAA,IAiBN,QAAA,CAAA,GAAY,kBAAA;EAIP,SAAA,CACP,KAAA,EAAO,gBAAA,IACP,MAAA,GAAS,OAAA,CAAQ,oCAAA,IAChB,QAAA,CACD,sBAAA,EACA,cAAA,EACA,oCAAA;EAKF,QAAA,CAAA;EAzJE;;;EAgKO,gBAAA,CAAiB,OAAA,+BAff,0BAAA;EAmBL,SAAA,CACJ,QAAA,EAAU,WAAA,IACV,OAAA,6BACA,UAAA,EAAY,wBAAA,eACX,OAAA,CAAQ,UAAA;EA+BJ,qBAAA,CACL,SAAA,EAAW,WAAA,IACX,OAAA,6BACA,UAAA,GAAa,wBAAA,GACZ,cAAA,CAAe,mBAAA;EA9MhB;EA+QF,iBAAA,CAAA;EA9QyB;;;;;;;;AAS3B;EAT2B,IA2RrB,OAAA,CAAA,GAAW,YAAA;EAIf,oBAAA,mBAEoB,MAAA,gBAAsB,MAAA,cAAA,CAExC,YAAA,EACI,cAAA,CAAe,SAAA,IACf,kBAAA,CAAmB,SAAA,IAEnB,MAAA,eACJ,MAAA,GAAS,6BAAA,UACR,QAAA,CAAS,sBAAA,EAAwB,SAAA;EAEpC,oBAAA,mBAEoB,MAAA,gBAAsB,MAAA,cAAA,CAExC,YAAA,EACI,cAAA,CAAe,SAAA,IACf,kBAAA,CAAmB,SAAA,IAEnB,MAAA,eACJ,MAAA,GAAS,6BAAA,SACR,QAAA,CAAS,sBAAA;IAA0B,GAAA,EAAK,WAAA;IAAa,MAAA,EAAQ,SAAA;EAAA;AAAA"}
|
package/dist/chat_models.d.ts
CHANGED
|
@@ -4,12 +4,13 @@ import { AbstractGoogleLLMConnection } from "./connection.js";
|
|
|
4
4
|
import { BaseChatModel, BaseChatModelParams, LangSmithParams } from "@langchain/core/language_models/chat_models";
|
|
5
5
|
import { ChatGenerationChunk, ChatResult } from "@langchain/core/outputs";
|
|
6
6
|
import { AIMessageChunk, BaseMessage } from "@langchain/core/messages";
|
|
7
|
-
import { Runnable } from "@langchain/core/runnables";
|
|
8
7
|
import { InteropZodType } from "@langchain/core/utils/types";
|
|
9
8
|
import { BaseLanguageModelInput, StructuredOutputMethodOptions } from "@langchain/core/language_models/base";
|
|
9
|
+
import { SerializableSchema } from "@langchain/core/utils/standard_schema";
|
|
10
10
|
import { CallbackManagerForLLMRun } from "@langchain/core/callbacks/manager";
|
|
11
11
|
import { AsyncCaller } from "@langchain/core/utils/async_caller";
|
|
12
12
|
import { ModelProfile } from "@langchain/core/language_models/profile";
|
|
13
|
+
import { Runnable } from "@langchain/core/runnables";
|
|
13
14
|
|
|
14
15
|
//#region src/chat_models.d.ts
|
|
15
16
|
declare class ChatConnection<AuthOptions> extends AbstractGoogleLLMConnection<BaseMessage[], AuthOptions> {
|
|
@@ -86,8 +87,8 @@ declare abstract class ChatGoogleBase<AuthOptions> extends BaseChatModel<GoogleA
|
|
|
86
87
|
* @returns {ModelProfile} An object describing the model's capabilities and constraints
|
|
87
88
|
*/
|
|
88
89
|
get profile(): ModelProfile;
|
|
89
|
-
withStructuredOutput<RunOutput extends Record<string, any> = Record<string, any>>(outputSchema: InteropZodType<RunOutput> | Record<string, any>, config?: StructuredOutputMethodOptions<false>): Runnable<BaseLanguageModelInput, RunOutput>;
|
|
90
|
-
withStructuredOutput<RunOutput extends Record<string, any> = Record<string, any>>(outputSchema: InteropZodType<RunOutput> | Record<string, any>, config?: StructuredOutputMethodOptions<true>): Runnable<BaseLanguageModelInput, {
|
|
90
|
+
withStructuredOutput<RunOutput extends Record<string, any> = Record<string, any>>(outputSchema: InteropZodType<RunOutput> | SerializableSchema<RunOutput> | Record<string, any>, config?: StructuredOutputMethodOptions<false>): Runnable<BaseLanguageModelInput, RunOutput>;
|
|
91
|
+
withStructuredOutput<RunOutput extends Record<string, any> = Record<string, any>>(outputSchema: InteropZodType<RunOutput> | SerializableSchema<RunOutput> | Record<string, any>, config?: StructuredOutputMethodOptions<true>): Runnable<BaseLanguageModelInput, {
|
|
91
92
|
raw: BaseMessage;
|
|
92
93
|
parsed: RunOutput;
|
|
93
94
|
}>;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"chat_models.d.ts","names":[],"sources":["../src/chat_models.ts"],"mappings":"
|
|
1
|
+
{"version":3,"file":"chat_models.d.ts","names":[],"sources":["../src/chat_models.ts"],"mappings":";;;;;;;;;;;;;;;cAwEa,cAAA,sBAAoC,2BAAA,CAC/C,WAAA,IACA,WAAA;EAEA,kCAAA;EAEA,WAAA,CACE,MAAA,EAAQ,oBAAA,CAAqB,WAAA,eAC7B,MAAA,EAAQ,WAAA,EACR,MAAA,EAAQ,sBAAA,EACR,SAAA;EAAA,IAOE,oBAAA,CAAA;EAAA,IAMA,2BAAA,CAAA;EAuBJ,0CAAA,CAAA,GAA8C,OAAA,CAC5C,uBAAA;EAYF,iCAAA,CACE,SAAA,EAAW,eAAA,GACV,OAAA,CAAQ,uBAAA;EASX,cAAA,CAAA,GAAkB,WAAA;EAAA,IAad,GAAA,CAAA,GAAO,WAAA;AAAA;;;;UAaI,mBAAA,sBAEb,mBAAA,EACA,sBAAA,CAAuB,WAAA,GACvB,mBAAA,EACA,oBAAA,EACA,iBAAA,EACA,IAAA,CAAK,oCAAA;;;;uBAKa,cAAA,sBACZ,aAAA,CAAc,oCAAA,EAAsC,cAAA,aACjD,mBAAA,CAAoB,WAAA;EAAA,OAGxB,OAAA,CAAA;EAAA,IAIH,UAAA,CAAA;IAAA,CAAiB,GAAA;EAAA;EAMrB,eAAA;EAGA,KAAA;EAEA,SAAA;EAEA,WAAA;EAEA,eAAA;EAEA,kBAAA;EAEA,IAAA;EAEA,IAAA;EAEA,IAAA;EAEA,eAAA;EAEA,gBAAA;EAEA,aAAA;EAEA,QAAA;EAEA,WAAA;EAEA,cAAA,EAAgB,qBAAA;EAEhB,kBAAA,GAAqB,qBAAA;EAGrB,kCAAA;EAEA,aAAA,EAAe,qBAAA;EAEf,YAAA,EAAc,kBAAA;EAEd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EpC,oBAAA,mBAEoB,MAAA,gBAAsB,MAAA,cAAA,CAExC,YAAA,EACI,cAAA,CAAe,SAAA,IACf,kBAAA,CAAmB,SAAA,IAEnB,MAAA,eACJ,MAAA,GAAS,6BAAA,SACR,QAAA,CAAS,sBAAA;IAA0B,GAAA,EAAK,WAAA;IAAa,MAAA,EAAQ,SAAA;EAAA;AAAA"}
|
package/dist/chat_models.js
CHANGED
|
@@ -9,11 +9,10 @@ import { getEnvironmentVariable } from "@langchain/core/utils/env";
|
|
|
9
9
|
import { BaseChatModel } from "@langchain/core/language_models/chat_models";
|
|
10
10
|
import { ChatGenerationChunk } from "@langchain/core/outputs";
|
|
11
11
|
import { AIMessageChunk } from "@langchain/core/messages";
|
|
12
|
-
import { RunnablePassthrough, RunnableSequence } from "@langchain/core/runnables";
|
|
13
|
-
import { JsonOutputKeyToolsParser } from "@langchain/core/output_parsers/openai_tools";
|
|
14
|
-
import { JsonOutputParser } from "@langchain/core/output_parsers";
|
|
15
12
|
import { concat } from "@langchain/core/utils/stream";
|
|
16
13
|
import { isInteropZodSchema } from "@langchain/core/utils/types";
|
|
14
|
+
import { isSerializableSchema } from "@langchain/core/utils/standard_schema";
|
|
15
|
+
import { assembleStructuredOutputPipeline, createContentParser, createFunctionCallingParser } from "@langchain/core/language_models/structured_output";
|
|
17
16
|
|
|
18
17
|
//#region src/chat_models.ts
|
|
19
18
|
var ChatConnection = class extends AbstractGoogleLLMConnection {
|
|
@@ -96,7 +95,7 @@ var ChatGoogleBase = class extends BaseChatModel {
|
|
|
96
95
|
streamedConnection;
|
|
97
96
|
constructor(fields) {
|
|
98
97
|
super(ensureParams(fields));
|
|
99
|
-
this._addVersion("@langchain/google-common", "2.1.
|
|
98
|
+
this._addVersion("@langchain/google-common", "2.1.25");
|
|
100
99
|
copyAndValidateModelParamsInto(fields, this);
|
|
101
100
|
this.safetyHandler = fields?.safetyHandler ?? new DefaultGeminiSafetyHandler();
|
|
102
101
|
this.streamUsage = fields?.streamUsage ?? this.streamUsage;
|
|
@@ -222,49 +221,34 @@ var ChatGoogleBase = class extends BaseChatModel {
|
|
|
222
221
|
let outputParser;
|
|
223
222
|
if (method === "functionCalling") {
|
|
224
223
|
let functionName = name ?? "extract";
|
|
225
|
-
let
|
|
226
|
-
if (isInteropZodSchema(schema)) {
|
|
224
|
+
let geminiFunctionDeclaration;
|
|
225
|
+
if (isInteropZodSchema(schema) || isSerializableSchema(schema)) {
|
|
227
226
|
const jsonSchema = schemaToGeminiParameters(schema);
|
|
228
|
-
|
|
227
|
+
geminiFunctionDeclaration = {
|
|
229
228
|
name: functionName,
|
|
230
229
|
description: jsonSchema.description ?? "A function available to call.",
|
|
231
230
|
parameters: jsonSchema
|
|
232
|
-
}
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
zodSchema: schema
|
|
237
|
-
});
|
|
231
|
+
};
|
|
232
|
+
} else if (typeof schema.name === "string" && typeof schema.parameters === "object" && schema.parameters != null) {
|
|
233
|
+
geminiFunctionDeclaration = schema;
|
|
234
|
+
functionName = schema.name;
|
|
238
235
|
} else {
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
geminiFunctionDefinition = {
|
|
246
|
-
name: functionName,
|
|
247
|
-
description: schema.description ?? "",
|
|
248
|
-
parameters
|
|
249
|
-
};
|
|
250
|
-
}
|
|
251
|
-
tools = [{ functionDeclarations: [geminiFunctionDefinition] }];
|
|
252
|
-
outputParser = new JsonOutputKeyToolsParser({
|
|
253
|
-
returnSingle: true,
|
|
254
|
-
keyName: functionName
|
|
255
|
-
});
|
|
236
|
+
const parameters = removeAdditionalProperties(schema);
|
|
237
|
+
geminiFunctionDeclaration = {
|
|
238
|
+
name: functionName,
|
|
239
|
+
description: schema.description ?? "",
|
|
240
|
+
parameters
|
|
241
|
+
};
|
|
256
242
|
}
|
|
243
|
+
const tools = [{ functionDeclarations: [geminiFunctionDeclaration] }];
|
|
257
244
|
llm = this.bindTools(tools).withConfig({ tool_choice: functionName });
|
|
245
|
+
outputParser = createFunctionCallingParser(schema, functionName);
|
|
258
246
|
} else {
|
|
259
247
|
const jsonSchema = schemaToGeminiParameters(schema);
|
|
260
248
|
llm = this.withConfig({ responseSchema: jsonSchema });
|
|
261
|
-
outputParser =
|
|
249
|
+
outputParser = createContentParser(schema);
|
|
262
250
|
}
|
|
263
|
-
|
|
264
|
-
const parserAssign = RunnablePassthrough.assign({ parsed: (input, config) => outputParser.invoke(input.raw, config) });
|
|
265
|
-
const parserNone = RunnablePassthrough.assign({ parsed: () => null });
|
|
266
|
-
const parsedWithFallback = parserAssign.withFallbacks({ fallbacks: [parserNone] });
|
|
267
|
-
return RunnableSequence.from([{ raw: llm }, parsedWithFallback]).withConfig({ runName: "StructuredOutputRunnable" });
|
|
251
|
+
return assembleStructuredOutputPipeline(llm, outputParser, includeRaw, includeRaw ? "StructuredOutputRunnable" : "ChatGoogleStructuredOutput");
|
|
268
252
|
}
|
|
269
253
|
};
|
|
270
254
|
|
package/dist/chat_models.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"chat_models.js","names":[],"sources":["../src/chat_models.ts"],"sourcesContent":["import { getEnvironmentVariable } from \"@langchain/core/utils/env\";\nimport { UsageMetadata, type BaseMessage } from \"@langchain/core/messages\";\nimport { CallbackManagerForLLMRun } from \"@langchain/core/callbacks/manager\";\n\nimport {\n BaseChatModel,\n LangSmithParams,\n type BaseChatModelParams,\n} from \"@langchain/core/language_models/chat_models\";\nimport { ChatGenerationChunk, ChatResult } from \"@langchain/core/outputs\";\nimport { AIMessageChunk } from \"@langchain/core/messages\";\nimport {\n BaseLanguageModelInput,\n StructuredOutputMethodOptions,\n} from \"@langchain/core/language_models/base\";\nimport { type ModelProfile } from \"@langchain/core/language_models/profile\";\nimport {\n Runnable,\n RunnablePassthrough,\n RunnableSequence,\n} from \"@langchain/core/runnables\";\nimport { JsonOutputKeyToolsParser } from \"@langchain/core/output_parsers/openai_tools\";\nimport {\n BaseLLMOutputParser,\n JsonOutputParser,\n} from \"@langchain/core/output_parsers\";\nimport { AsyncCaller } from \"@langchain/core/utils/async_caller\";\nimport { concat } from \"@langchain/core/utils/stream\";\nimport {\n InteropZodType,\n isInteropZodSchema,\n} from \"@langchain/core/utils/types\";\nimport {\n GoogleAIBaseLLMInput,\n GoogleAIModelParams,\n GoogleAISafetySetting,\n GoogleConnectionParams,\n GooglePlatformType,\n GeminiTool,\n GoogleAIBaseLanguageModelCallOptions,\n GoogleAIAPI,\n GoogleAIAPIParams,\n GoogleSearchToolSetting,\n GoogleSpeechConfig,\n GeminiJsonSchema,\n} from \"./types.js\";\nimport {\n convertToGeminiTools,\n copyAIModelParams,\n copyAndValidateModelParamsInto,\n} from \"./utils/common.js\";\nimport { AbstractGoogleLLMConnection } from \"./connection.js\";\nimport { DefaultGeminiSafetyHandler, getGeminiAPI } from \"./utils/gemini.js\";\nimport { ApiKeyGoogleAuth, GoogleAbstractedClient } from \"./auth.js\";\nimport { JsonStream } from \"./utils/stream.js\";\nimport { ensureParams } from \"./utils/failed_handler.js\";\nimport type {\n GoogleBaseLLMInput,\n GoogleAISafetyHandler,\n GoogleAISafetyParams,\n GeminiFunctionDeclaration,\n GeminiFunctionSchema,\n GoogleAIToolType,\n GeminiAPIConfig,\n GoogleAIModelModality,\n} from \"./types.js\";\nimport {\n removeAdditionalProperties,\n schemaToGeminiParameters,\n} from \"./utils/zod_to_gemini_parameters.js\";\nimport PROFILES from \"./profiles.js\";\n\nexport class ChatConnection<AuthOptions> extends AbstractGoogleLLMConnection<\n BaseMessage[],\n AuthOptions\n> {\n convertSystemMessageToHumanContent: boolean | undefined;\n\n constructor(\n fields: GoogleAIBaseLLMInput<AuthOptions> | undefined,\n caller: AsyncCaller,\n client: GoogleAbstractedClient,\n streaming: boolean\n ) {\n super(fields, caller, client, streaming);\n this.convertSystemMessageToHumanContent =\n fields?.convertSystemMessageToHumanContent;\n }\n\n get useSystemInstruction(): boolean {\n return typeof this.convertSystemMessageToHumanContent === \"boolean\"\n ? !this.convertSystemMessageToHumanContent\n : this.computeUseSystemInstruction;\n }\n\n get computeUseSystemInstruction(): boolean {\n // This works on models from April 2024 and later\n // Vertex AI: gemini-1.5-pro and gemini-1.0-002 and later\n // AI Studio: gemini-1.5-pro-latest\n if (this.modelFamily === \"palm\") {\n return false;\n } else if (this.modelName === \"gemini-1.0-pro-001\") {\n return false;\n } else if (this.modelName.startsWith(\"gemini-pro-vision\")) {\n return false;\n } else if (this.modelName.startsWith(\"gemini-1.0-pro-vision\")) {\n return false;\n } else if (this.modelName === \"gemini-pro\" && this.platform === \"gai\") {\n // on AI Studio gemini-pro is still pointing at gemini-1.0-pro-001\n return false;\n } else if (this.modelFamily === \"gemma\") {\n // At least as of 12 Mar 2025 gemma 3 on AIS, trying to use system instructions yields an error:\n // \"Developer instruction is not enabled for models/gemma-3-27b-it\"\n return false;\n }\n return true;\n }\n\n computeGoogleSearchToolAdjustmentFromModel(): Exclude<\n GoogleSearchToolSetting,\n boolean\n > {\n if (this.modelName.startsWith(\"gemini-1.0\")) {\n return \"googleSearchRetrieval\";\n } else if (this.modelName.startsWith(\"gemini-1.5\")) {\n return \"googleSearchRetrieval\";\n } else {\n return \"googleSearch\";\n }\n }\n\n computeGoogleSearchToolAdjustment(\n apiConfig: GeminiAPIConfig\n ): Exclude<GoogleSearchToolSetting, true> {\n const adj = apiConfig.googleSearchToolAdjustment;\n if (adj === undefined || adj === true) {\n return this.computeGoogleSearchToolAdjustmentFromModel();\n } else {\n return adj;\n }\n }\n\n buildGeminiAPI(): GoogleAIAPI {\n const apiConfig: GeminiAPIConfig =\n (this.apiConfig as GeminiAPIConfig) ?? {};\n const googleSearchToolAdjustment =\n this.computeGoogleSearchToolAdjustment(apiConfig);\n const geminiConfig: GeminiAPIConfig = {\n useSystemInstruction: this.useSystemInstruction,\n googleSearchToolAdjustment,\n ...apiConfig,\n };\n return getGeminiAPI(geminiConfig);\n }\n\n get api(): GoogleAIAPI {\n switch (this.apiName) {\n case \"google\":\n return this.buildGeminiAPI();\n default:\n return super.api;\n }\n }\n}\n\n/**\n * Input to chat model class.\n */\nexport interface ChatGoogleBaseInput<AuthOptions>\n extends\n BaseChatModelParams,\n GoogleConnectionParams<AuthOptions>,\n GoogleAIModelParams,\n GoogleAISafetyParams,\n GoogleAIAPIParams,\n Pick<GoogleAIBaseLanguageModelCallOptions, \"streamUsage\"> {}\n\n/**\n * Integration with a Google chat model.\n */\nexport abstract class ChatGoogleBase<AuthOptions>\n extends BaseChatModel<GoogleAIBaseLanguageModelCallOptions, AIMessageChunk>\n implements ChatGoogleBaseInput<AuthOptions>\n{\n // Used for tracing, replace with the same name as your class\n static lc_name() {\n return \"ChatGoogle\";\n }\n\n get lc_secrets(): { [key: string]: string } | undefined {\n return {\n authOptions: \"GOOGLE_AUTH_OPTIONS\",\n };\n }\n\n lc_serializable = true;\n\n // Set based on modelName\n model: string;\n\n modelName = \"gemini-pro\";\n\n temperature: number;\n\n maxOutputTokens: number;\n\n maxReasoningTokens: number;\n\n topP: number;\n\n topK: number;\n\n seed: number;\n\n presencePenalty: number;\n\n frequencyPenalty: number;\n\n stopSequences: string[] = [];\n\n logprobs: boolean;\n\n topLogprobs: number = 0;\n\n safetySettings: GoogleAISafetySetting[] = [];\n\n responseModalities?: GoogleAIModelModality[];\n\n // May intentionally be undefined, meaning to compute this.\n convertSystemMessageToHumanContent: boolean | undefined;\n\n safetyHandler: GoogleAISafetyHandler;\n\n speechConfig: GoogleSpeechConfig;\n\n streamUsage = true;\n\n streaming = false;\n\n labels?: Record<string, string>;\n\n protected connection: ChatConnection<AuthOptions>;\n\n protected streamedConnection: ChatConnection<AuthOptions>;\n\n constructor(fields?: ChatGoogleBaseInput<AuthOptions>) {\n super(ensureParams(fields));\n this._addVersion(\"@langchain/google-common\", __PKG_VERSION__);\n\n copyAndValidateModelParamsInto(fields, this);\n this.safetyHandler =\n fields?.safetyHandler ?? new DefaultGeminiSafetyHandler();\n this.streamUsage = fields?.streamUsage ?? this.streamUsage;\n const client = this.buildClient(fields);\n this.buildConnection(fields ?? {}, client);\n }\n\n getLsParams(options: this[\"ParsedCallOptions\"]): LangSmithParams {\n const params = this.invocationParams(options);\n return {\n ls_provider: \"google_vertexai\",\n ls_model_name: this.model,\n ls_model_type: \"chat\",\n ls_temperature: params.temperature ?? undefined,\n ls_max_tokens: params.maxOutputTokens ?? undefined,\n ls_stop: options.stop,\n };\n }\n\n abstract buildAbstractedClient(\n fields?: GoogleAIBaseLLMInput<AuthOptions>\n ): GoogleAbstractedClient;\n\n buildApiKeyClient(apiKey: string): GoogleAbstractedClient {\n return new ApiKeyGoogleAuth(apiKey);\n }\n\n buildApiKey(fields?: GoogleAIBaseLLMInput<AuthOptions>): string | undefined {\n return fields?.apiKey ?? getEnvironmentVariable(\"GOOGLE_API_KEY\");\n }\n\n buildClient(\n fields?: GoogleAIBaseLLMInput<AuthOptions>\n ): GoogleAbstractedClient {\n const apiKey = this.buildApiKey(fields);\n if (apiKey) {\n return this.buildApiKeyClient(apiKey);\n } else {\n return this.buildAbstractedClient(fields);\n }\n }\n\n buildConnection(\n fields: GoogleBaseLLMInput<AuthOptions>,\n client: GoogleAbstractedClient\n ) {\n this.connection = new ChatConnection(\n { ...fields, ...this },\n this.caller,\n client,\n false\n );\n\n this.streamedConnection = new ChatConnection(\n { ...fields, ...this },\n this.caller,\n client,\n true\n );\n }\n\n get platform(): GooglePlatformType {\n return this.connection.platform;\n }\n\n override bindTools(\n tools: GoogleAIToolType[],\n kwargs?: Partial<GoogleAIBaseLanguageModelCallOptions>\n ): Runnable<\n BaseLanguageModelInput,\n AIMessageChunk,\n GoogleAIBaseLanguageModelCallOptions\n > {\n return this.withConfig({ tools: convertToGeminiTools(tools), ...kwargs });\n }\n\n _llmType() {\n return \"google\";\n }\n\n /**\n * Get the parameters used to invoke the model\n */\n override invocationParams(options?: this[\"ParsedCallOptions\"]) {\n return copyAIModelParams(this, options);\n }\n\n async _generate(\n messages: BaseMessage[],\n options: this[\"ParsedCallOptions\"],\n runManager: CallbackManagerForLLMRun | undefined\n ): Promise<ChatResult> {\n options.signal?.throwIfAborted();\n const parameters = this.invocationParams(options);\n if (this.streaming) {\n const stream = this._streamResponseChunks(messages, options, runManager);\n let finalChunk: ChatGenerationChunk | null = null;\n for await (const chunk of stream) {\n finalChunk = !finalChunk ? chunk : concat(finalChunk, chunk);\n }\n if (!finalChunk) {\n throw new Error(\"No chunks were returned from the stream.\");\n }\n return {\n generations: [finalChunk],\n };\n }\n\n const response = await this.connection.request(\n messages,\n parameters,\n options,\n runManager\n );\n const ret = this.connection.api.responseToChatResult(response);\n const chunk = ret?.generations?.[0];\n if (chunk) {\n await runManager?.handleLLMNewToken(chunk.text || \"\");\n }\n return ret;\n }\n\n async *_streamResponseChunks(\n _messages: BaseMessage[],\n options: this[\"ParsedCallOptions\"],\n runManager?: CallbackManagerForLLMRun\n ): AsyncGenerator<ChatGenerationChunk> {\n // Make the call as a streaming request\n const parameters = this.invocationParams(options);\n const response = await this.streamedConnection.request(\n _messages,\n parameters,\n options,\n runManager\n );\n\n // Get the streaming parser of the response\n const stream = response.data as JsonStream;\n let usageMetadata: UsageMetadata | undefined;\n // Loop until the end of the stream\n // During the loop, yield each time we get a chunk from the streaming parser\n // that is either available or added to the queue\n while (!stream.streamDone) {\n if (options.signal?.aborted) {\n return;\n }\n const output = await stream.nextChunk();\n await runManager?.handleCustomEvent(\n `google-chunk-${this.constructor.name}`,\n {\n output,\n }\n );\n if (\n output &&\n output.usageMetadata &&\n this.streamUsage !== false &&\n options.streamUsage !== false\n ) {\n usageMetadata = {\n input_tokens: output.usageMetadata.promptTokenCount,\n output_tokens: output.usageMetadata.candidatesTokenCount,\n total_tokens: output.usageMetadata.totalTokenCount,\n };\n }\n const chunk =\n output !== null\n ? this.connection.api.responseToChatGeneration({ data: output })\n : new ChatGenerationChunk({\n text: \"\",\n generationInfo: { finishReason: \"stop\" },\n message: new AIMessageChunk({\n content: \"\",\n usage_metadata: usageMetadata,\n }),\n });\n if (chunk) {\n yield chunk;\n await runManager?.handleLLMNewToken(\n chunk.text ?? \"\",\n undefined,\n undefined,\n undefined,\n undefined,\n { chunk }\n );\n }\n }\n }\n\n /** @ignore */\n _combineLLMOutput() {\n return [];\n }\n\n /**\n * Return profiling information for the model.\n *\n * Provides information about the model's capabilities and constraints,\n * including token limits, multimodal support, and advanced features like\n * tool calling and structured output.\n *\n * @returns {ModelProfile} An object describing the model's capabilities and constraints\n */\n get profile(): ModelProfile {\n return PROFILES[this.model] ?? {};\n }\n\n withStructuredOutput<\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n RunOutput extends Record<string, any> = Record<string, any>,\n >(\n outputSchema:\n | InteropZodType<RunOutput>\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n | Record<string, any>,\n config?: StructuredOutputMethodOptions<false>\n ): Runnable<BaseLanguageModelInput, RunOutput>;\n\n withStructuredOutput<\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n RunOutput extends Record<string, any> = Record<string, any>,\n >(\n outputSchema:\n | InteropZodType<RunOutput>\n // eslint-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 // eslint-disable-next-line @typescript-eslint/no-explicit-any\n RunOutput extends Record<string, any> = Record<string, any>,\n >(\n outputSchema:\n | InteropZodType<RunOutput>\n // eslint-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 // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const schema: InteropZodType<RunOutput> | Record<string, any> =\n outputSchema;\n const name = config?.name;\n const method = config?.method;\n const includeRaw = config?.includeRaw;\n if (method === \"jsonMode\") {\n throw new Error(\n `Google only supports \"jsonSchema\" or \"functionCalling\" as a method.`\n );\n }\n\n let llm;\n let outputParser: BaseLLMOutputParser<RunOutput>;\n if (method === \"functionCalling\") {\n let functionName = name ?? \"extract\";\n let tools: GeminiTool[];\n if (isInteropZodSchema(schema)) {\n const jsonSchema = schemaToGeminiParameters(schema);\n tools = [\n {\n functionDeclarations: [\n {\n name: functionName,\n description:\n jsonSchema.description ?? \"A function available to call.\",\n parameters: jsonSchema as GeminiFunctionSchema,\n },\n ],\n },\n ];\n outputParser = new JsonOutputKeyToolsParser({\n returnSingle: true,\n keyName: functionName,\n zodSchema: schema,\n });\n } else {\n let geminiFunctionDefinition: GeminiFunctionDeclaration;\n if (\n typeof schema.name === \"string\" &&\n typeof schema.parameters === \"object\" &&\n schema.parameters != null\n ) {\n geminiFunctionDefinition = schema as GeminiFunctionDeclaration;\n functionName = schema.name;\n } else {\n // We are providing the schema for *just* the parameters, probably\n const parameters: GeminiJsonSchema =\n removeAdditionalProperties(schema);\n geminiFunctionDefinition = {\n name: functionName,\n description: schema.description ?? \"\",\n parameters,\n };\n }\n tools = [\n {\n functionDeclarations: [geminiFunctionDefinition],\n },\n ];\n outputParser = new JsonOutputKeyToolsParser<RunOutput>({\n returnSingle: true,\n keyName: functionName,\n });\n }\n llm = this.bindTools(tools).withConfig({ tool_choice: functionName });\n } else {\n // Default to jsonSchema method\n const jsonSchema = schemaToGeminiParameters(schema);\n llm = this.withConfig({\n responseSchema: jsonSchema as GeminiJsonSchema,\n });\n outputParser = new JsonOutputParser();\n }\n\n if (!includeRaw) {\n return llm.pipe(outputParser).withConfig({\n runName: \"ChatGoogleStructuredOutput\",\n }) as Runnable<BaseLanguageModelInput, RunOutput>;\n }\n\n const parserAssign = RunnablePassthrough.assign({\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n parsed: (input: any, config) => outputParser.invoke(input.raw, config),\n });\n const parserNone = RunnablePassthrough.assign({\n parsed: () => null,\n });\n const parsedWithFallback = parserAssign.withFallbacks({\n fallbacks: [parserNone],\n });\n return RunnableSequence.from<\n BaseLanguageModelInput,\n { raw: BaseMessage; parsed: RunOutput }\n >([\n {\n raw: llm,\n },\n parsedWithFallback,\n ]).withConfig({\n runName: \"StructuredOutputRunnable\",\n });\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAwEA,IAAa,iBAAb,cAAiD,4BAG/C;CACA;CAEA,YACE,QACA,QACA,QACA,WACA;AACA,QAAM,QAAQ,QAAQ,QAAQ,UAAU;AACxC,OAAK,qCACH,QAAQ;;CAGZ,IAAI,uBAAgC;AAClC,SAAO,OAAO,KAAK,uCAAuC,YACtD,CAAC,KAAK,qCACN,KAAK;;CAGX,IAAI,8BAAuC;AAIzC,MAAI,KAAK,gBAAgB,OACvB,QAAO;WACE,KAAK,cAAc,qBAC5B,QAAO;WACE,KAAK,UAAU,WAAW,oBAAoB,CACvD,QAAO;WACE,KAAK,UAAU,WAAW,wBAAwB,CAC3D,QAAO;WACE,KAAK,cAAc,gBAAgB,KAAK,aAAa,MAE9D,QAAO;WACE,KAAK,gBAAgB,QAG9B,QAAO;AAET,SAAO;;CAGT,6CAGE;AACA,MAAI,KAAK,UAAU,WAAW,aAAa,CACzC,QAAO;WACE,KAAK,UAAU,WAAW,aAAa,CAChD,QAAO;MAEP,QAAO;;CAIX,kCACE,WACwC;EACxC,MAAM,MAAM,UAAU;AACtB,MAAI,QAAQ,UAAa,QAAQ,KAC/B,QAAO,KAAK,4CAA4C;MAExD,QAAO;;CAIX,iBAA8B;EAC5B,MAAM,YACH,KAAK,aAAiC,EAAE;EAC3C,MAAM,6BACJ,KAAK,kCAAkC,UAAU;AAMnD,SAAO,aAL+B;GACpC,sBAAsB,KAAK;GAC3B;GACA,GAAG;GACJ,CACgC;;CAGnC,IAAI,MAAmB;AACrB,UAAQ,KAAK,SAAb;GACE,KAAK,SACH,QAAO,KAAK,gBAAgB;GAC9B,QACE,QAAO,MAAM;;;;;;;AAoBr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,eAAe;MACnC;MACD;;AAEH,YAAQ,CACN,EACE,sBAAsB,CAAC,yBAAyB,EACjD,CACF;AACD,mBAAe,IAAI,yBAAoC;KACrD,cAAc;KACd,SAAS;KACV,CAAC;;AAEJ,SAAM,KAAK,UAAU,MAAM,CAAC,WAAW,EAAE,aAAa,cAAc,CAAC;SAChE;GAEL,MAAM,aAAa,yBAAyB,OAAO;AACnD,SAAM,KAAK,WAAW,EACpB,gBAAgB,YACjB,CAAC;AACF,kBAAe,IAAI,kBAAkB;;AAGvC,MAAI,CAAC,WACH,QAAO,IAAI,KAAK,aAAa,CAAC,WAAW,EACvC,SAAS,8BACV,CAAC;EAGJ,MAAM,eAAe,oBAAoB,OAAO,EAE9C,SAAS,OAAY,WAAW,aAAa,OAAO,MAAM,KAAK,OAAO,EACvE,CAAC;EACF,MAAM,aAAa,oBAAoB,OAAO,EAC5C,cAAc,MACf,CAAC;EACF,MAAM,qBAAqB,aAAa,cAAc,EACpD,WAAW,CAAC,WAAW,EACxB,CAAC;AACF,SAAO,iBAAiB,KAGtB,CACA,EACE,KAAK,KACN,EACD,mBACD,CAAC,CAAC,WAAW,EACZ,SAAS,4BACV,CAAC"}
|
|
1
|
+
{"version":3,"file":"chat_models.js","names":[],"sources":["../src/chat_models.ts"],"sourcesContent":["import { getEnvironmentVariable } from \"@langchain/core/utils/env\";\nimport { UsageMetadata, type BaseMessage } from \"@langchain/core/messages\";\nimport { CallbackManagerForLLMRun } from \"@langchain/core/callbacks/manager\";\n\nimport {\n BaseChatModel,\n LangSmithParams,\n type BaseChatModelParams,\n} from \"@langchain/core/language_models/chat_models\";\nimport { ChatGenerationChunk, ChatResult } from \"@langchain/core/outputs\";\nimport { AIMessageChunk } from \"@langchain/core/messages\";\nimport {\n BaseLanguageModelInput,\n StructuredOutputMethodOptions,\n} from \"@langchain/core/language_models/base\";\nimport { type ModelProfile } from \"@langchain/core/language_models/profile\";\nimport { Runnable } from \"@langchain/core/runnables\";\nimport { AsyncCaller } from \"@langchain/core/utils/async_caller\";\nimport { concat } from \"@langchain/core/utils/stream\";\nimport {\n InteropZodType,\n isInteropZodSchema,\n} from \"@langchain/core/utils/types\";\nimport {\n GoogleAIBaseLLMInput,\n GoogleAIModelParams,\n GoogleAISafetySetting,\n GoogleConnectionParams,\n GooglePlatformType,\n GeminiTool,\n GoogleAIBaseLanguageModelCallOptions,\n GoogleAIAPI,\n GoogleAIAPIParams,\n GoogleSearchToolSetting,\n GoogleSpeechConfig,\n GeminiJsonSchema,\n} from \"./types.js\";\nimport {\n convertToGeminiTools,\n copyAIModelParams,\n copyAndValidateModelParamsInto,\n} from \"./utils/common.js\";\nimport { AbstractGoogleLLMConnection } from \"./connection.js\";\nimport { DefaultGeminiSafetyHandler, getGeminiAPI } from \"./utils/gemini.js\";\nimport { ApiKeyGoogleAuth, GoogleAbstractedClient } from \"./auth.js\";\nimport { JsonStream } from \"./utils/stream.js\";\nimport { ensureParams } from \"./utils/failed_handler.js\";\nimport type {\n GoogleBaseLLMInput,\n GoogleAISafetyHandler,\n GoogleAISafetyParams,\n GeminiFunctionDeclaration,\n GeminiFunctionSchema,\n GoogleAIToolType,\n GeminiAPIConfig,\n GoogleAIModelModality,\n} from \"./types.js\";\nimport {\n removeAdditionalProperties,\n schemaToGeminiParameters,\n} from \"./utils/zod_to_gemini_parameters.js\";\nimport PROFILES from \"./profiles.js\";\nimport {\n isSerializableSchema,\n SerializableSchema,\n} from \"@langchain/core/utils/standard_schema\";\nimport {\n assembleStructuredOutputPipeline,\n createContentParser,\n createFunctionCallingParser,\n} from \"@langchain/core/language_models/structured_output\";\n\nexport class ChatConnection<AuthOptions> extends AbstractGoogleLLMConnection<\n BaseMessage[],\n AuthOptions\n> {\n convertSystemMessageToHumanContent: boolean | undefined;\n\n constructor(\n fields: GoogleAIBaseLLMInput<AuthOptions> | undefined,\n caller: AsyncCaller,\n client: GoogleAbstractedClient,\n streaming: boolean\n ) {\n super(fields, caller, client, streaming);\n this.convertSystemMessageToHumanContent =\n fields?.convertSystemMessageToHumanContent;\n }\n\n get useSystemInstruction(): boolean {\n return typeof this.convertSystemMessageToHumanContent === \"boolean\"\n ? !this.convertSystemMessageToHumanContent\n : this.computeUseSystemInstruction;\n }\n\n get computeUseSystemInstruction(): boolean {\n // This works on models from April 2024 and later\n // Vertex AI: gemini-1.5-pro and gemini-1.0-002 and later\n // AI Studio: gemini-1.5-pro-latest\n if (this.modelFamily === \"palm\") {\n return false;\n } else if (this.modelName === \"gemini-1.0-pro-001\") {\n return false;\n } else if (this.modelName.startsWith(\"gemini-pro-vision\")) {\n return false;\n } else if (this.modelName.startsWith(\"gemini-1.0-pro-vision\")) {\n return false;\n } else if (this.modelName === \"gemini-pro\" && this.platform === \"gai\") {\n // on AI Studio gemini-pro is still pointing at gemini-1.0-pro-001\n return false;\n } else if (this.modelFamily === \"gemma\") {\n // At least as of 12 Mar 2025 gemma 3 on AIS, trying to use system instructions yields an error:\n // \"Developer instruction is not enabled for models/gemma-3-27b-it\"\n return false;\n }\n return true;\n }\n\n computeGoogleSearchToolAdjustmentFromModel(): Exclude<\n GoogleSearchToolSetting,\n boolean\n > {\n if (this.modelName.startsWith(\"gemini-1.0\")) {\n return \"googleSearchRetrieval\";\n } else if (this.modelName.startsWith(\"gemini-1.5\")) {\n return \"googleSearchRetrieval\";\n } else {\n return \"googleSearch\";\n }\n }\n\n computeGoogleSearchToolAdjustment(\n apiConfig: GeminiAPIConfig\n ): Exclude<GoogleSearchToolSetting, true> {\n const adj = apiConfig.googleSearchToolAdjustment;\n if (adj === undefined || adj === true) {\n return this.computeGoogleSearchToolAdjustmentFromModel();\n } else {\n return adj;\n }\n }\n\n buildGeminiAPI(): GoogleAIAPI {\n const apiConfig: GeminiAPIConfig =\n (this.apiConfig as GeminiAPIConfig) ?? {};\n const googleSearchToolAdjustment =\n this.computeGoogleSearchToolAdjustment(apiConfig);\n const geminiConfig: GeminiAPIConfig = {\n useSystemInstruction: this.useSystemInstruction,\n googleSearchToolAdjustment,\n ...apiConfig,\n };\n return getGeminiAPI(geminiConfig);\n }\n\n get api(): GoogleAIAPI {\n switch (this.apiName) {\n case \"google\":\n return this.buildGeminiAPI();\n default:\n return super.api;\n }\n }\n}\n\n/**\n * Input to chat model class.\n */\nexport interface ChatGoogleBaseInput<AuthOptions>\n extends\n BaseChatModelParams,\n GoogleConnectionParams<AuthOptions>,\n GoogleAIModelParams,\n GoogleAISafetyParams,\n GoogleAIAPIParams,\n Pick<GoogleAIBaseLanguageModelCallOptions, \"streamUsage\"> {}\n\n/**\n * Integration with a Google chat model.\n */\nexport abstract class ChatGoogleBase<AuthOptions>\n extends BaseChatModel<GoogleAIBaseLanguageModelCallOptions, AIMessageChunk>\n implements ChatGoogleBaseInput<AuthOptions>\n{\n // Used for tracing, replace with the same name as your class\n static lc_name() {\n return \"ChatGoogle\";\n }\n\n get lc_secrets(): { [key: string]: string } | undefined {\n return {\n authOptions: \"GOOGLE_AUTH_OPTIONS\",\n };\n }\n\n lc_serializable = true;\n\n // Set based on modelName\n model: string;\n\n modelName = \"gemini-pro\";\n\n temperature: number;\n\n maxOutputTokens: number;\n\n maxReasoningTokens: number;\n\n topP: number;\n\n topK: number;\n\n seed: number;\n\n presencePenalty: number;\n\n frequencyPenalty: number;\n\n stopSequences: string[] = [];\n\n logprobs: boolean;\n\n topLogprobs: number = 0;\n\n safetySettings: GoogleAISafetySetting[] = [];\n\n responseModalities?: GoogleAIModelModality[];\n\n // May intentionally be undefined, meaning to compute this.\n convertSystemMessageToHumanContent: boolean | undefined;\n\n safetyHandler: GoogleAISafetyHandler;\n\n speechConfig: GoogleSpeechConfig;\n\n streamUsage = true;\n\n streaming = false;\n\n labels?: Record<string, string>;\n\n protected connection: ChatConnection<AuthOptions>;\n\n protected streamedConnection: ChatConnection<AuthOptions>;\n\n constructor(fields?: ChatGoogleBaseInput<AuthOptions>) {\n super(ensureParams(fields));\n this._addVersion(\"@langchain/google-common\", __PKG_VERSION__);\n\n copyAndValidateModelParamsInto(fields, this);\n this.safetyHandler =\n fields?.safetyHandler ?? new DefaultGeminiSafetyHandler();\n this.streamUsage = fields?.streamUsage ?? this.streamUsage;\n const client = this.buildClient(fields);\n this.buildConnection(fields ?? {}, client);\n }\n\n getLsParams(options: this[\"ParsedCallOptions\"]): LangSmithParams {\n const params = this.invocationParams(options);\n return {\n ls_provider: \"google_vertexai\",\n ls_model_name: this.model,\n ls_model_type: \"chat\",\n ls_temperature: params.temperature ?? undefined,\n ls_max_tokens: params.maxOutputTokens ?? undefined,\n ls_stop: options.stop,\n };\n }\n\n abstract buildAbstractedClient(\n fields?: GoogleAIBaseLLMInput<AuthOptions>\n ): GoogleAbstractedClient;\n\n buildApiKeyClient(apiKey: string): GoogleAbstractedClient {\n return new ApiKeyGoogleAuth(apiKey);\n }\n\n buildApiKey(fields?: GoogleAIBaseLLMInput<AuthOptions>): string | undefined {\n return fields?.apiKey ?? getEnvironmentVariable(\"GOOGLE_API_KEY\");\n }\n\n buildClient(\n fields?: GoogleAIBaseLLMInput<AuthOptions>\n ): GoogleAbstractedClient {\n const apiKey = this.buildApiKey(fields);\n if (apiKey) {\n return this.buildApiKeyClient(apiKey);\n } else {\n return this.buildAbstractedClient(fields);\n }\n }\n\n buildConnection(\n fields: GoogleBaseLLMInput<AuthOptions>,\n client: GoogleAbstractedClient\n ) {\n this.connection = new ChatConnection(\n { ...fields, ...this },\n this.caller,\n client,\n false\n );\n\n this.streamedConnection = new ChatConnection(\n { ...fields, ...this },\n this.caller,\n client,\n true\n );\n }\n\n get platform(): GooglePlatformType {\n return this.connection.platform;\n }\n\n override bindTools(\n tools: GoogleAIToolType[],\n kwargs?: Partial<GoogleAIBaseLanguageModelCallOptions>\n ): Runnable<\n BaseLanguageModelInput,\n AIMessageChunk,\n GoogleAIBaseLanguageModelCallOptions\n > {\n return this.withConfig({ tools: convertToGeminiTools(tools), ...kwargs });\n }\n\n _llmType() {\n return \"google\";\n }\n\n /**\n * Get the parameters used to invoke the model\n */\n override invocationParams(options?: this[\"ParsedCallOptions\"]) {\n return copyAIModelParams(this, options);\n }\n\n async _generate(\n messages: BaseMessage[],\n options: this[\"ParsedCallOptions\"],\n runManager: CallbackManagerForLLMRun | undefined\n ): Promise<ChatResult> {\n options.signal?.throwIfAborted();\n const parameters = this.invocationParams(options);\n if (this.streaming) {\n const stream = this._streamResponseChunks(messages, options, runManager);\n let finalChunk: ChatGenerationChunk | null = null;\n for await (const chunk of stream) {\n finalChunk = !finalChunk ? chunk : concat(finalChunk, chunk);\n }\n if (!finalChunk) {\n throw new Error(\"No chunks were returned from the stream.\");\n }\n return {\n generations: [finalChunk],\n };\n }\n\n const response = await this.connection.request(\n messages,\n parameters,\n options,\n runManager\n );\n const ret = this.connection.api.responseToChatResult(response);\n const chunk = ret?.generations?.[0];\n if (chunk) {\n await runManager?.handleLLMNewToken(chunk.text || \"\");\n }\n return ret;\n }\n\n async *_streamResponseChunks(\n _messages: BaseMessage[],\n options: this[\"ParsedCallOptions\"],\n runManager?: CallbackManagerForLLMRun\n ): AsyncGenerator<ChatGenerationChunk> {\n // Make the call as a streaming request\n const parameters = this.invocationParams(options);\n const response = await this.streamedConnection.request(\n _messages,\n parameters,\n options,\n runManager\n );\n\n // Get the streaming parser of the response\n const stream = response.data as JsonStream;\n let usageMetadata: UsageMetadata | undefined;\n // Loop until the end of the stream\n // During the loop, yield each time we get a chunk from the streaming parser\n // that is either available or added to the queue\n while (!stream.streamDone) {\n if (options.signal?.aborted) {\n return;\n }\n const output = await stream.nextChunk();\n await runManager?.handleCustomEvent(\n `google-chunk-${this.constructor.name}`,\n {\n output,\n }\n );\n if (\n output &&\n output.usageMetadata &&\n this.streamUsage !== false &&\n options.streamUsage !== false\n ) {\n usageMetadata = {\n input_tokens: output.usageMetadata.promptTokenCount,\n output_tokens: output.usageMetadata.candidatesTokenCount,\n total_tokens: output.usageMetadata.totalTokenCount,\n };\n }\n const chunk =\n output !== null\n ? this.connection.api.responseToChatGeneration({ data: output })\n : new ChatGenerationChunk({\n text: \"\",\n generationInfo: { finishReason: \"stop\" },\n message: new AIMessageChunk({\n content: \"\",\n usage_metadata: usageMetadata,\n }),\n });\n if (chunk) {\n yield chunk;\n await runManager?.handleLLMNewToken(\n chunk.text ?? \"\",\n undefined,\n undefined,\n undefined,\n undefined,\n { chunk }\n );\n }\n }\n }\n\n /** @ignore */\n _combineLLMOutput() {\n return [];\n }\n\n /**\n * Return profiling information for the model.\n *\n * Provides information about the model's capabilities and constraints,\n * including token limits, multimodal support, and advanced features like\n * tool calling and structured output.\n *\n * @returns {ModelProfile} An object describing the model's capabilities and constraints\n */\n get profile(): ModelProfile {\n return PROFILES[this.model] ?? {};\n }\n\n withStructuredOutput<\n // eslint-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 // eslint-disable-next-line @typescript-eslint/no-explicit-any\n | Record<string, any>,\n config?: StructuredOutputMethodOptions<false>\n ): Runnable<BaseLanguageModelInput, RunOutput>;\n\n withStructuredOutput<\n // eslint-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 // eslint-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 // eslint-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 // eslint-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 const schema = outputSchema;\n const name = config?.name;\n const method = config?.method;\n const includeRaw = config?.includeRaw;\n\n if (method === \"jsonMode\") {\n throw new Error(\n `Google only supports \"jsonSchema\" or \"functionCalling\" as a method.`\n );\n }\n\n let llm: Runnable<BaseLanguageModelInput>;\n let outputParser: Runnable<AIMessageChunk, RunOutput>;\n\n if (method === \"functionCalling\") {\n let functionName = name ?? \"extract\";\n let geminiFunctionDeclaration: GeminiFunctionDeclaration;\n if (isInteropZodSchema(schema) || isSerializableSchema(schema)) {\n const jsonSchema = schemaToGeminiParameters(schema);\n geminiFunctionDeclaration = {\n name: functionName,\n description:\n jsonSchema.description ?? \"A function available to call.\",\n parameters: jsonSchema as GeminiFunctionSchema,\n };\n } else if (\n typeof schema.name === \"string\" &&\n typeof schema.parameters === \"object\" &&\n schema.parameters != null\n ) {\n geminiFunctionDeclaration = schema as GeminiFunctionDeclaration;\n functionName = schema.name;\n } else {\n // We are providing the schema for *just* the parameters, probably\n const parameters: GeminiJsonSchema = removeAdditionalProperties(schema);\n geminiFunctionDeclaration = {\n name: functionName,\n description: schema.description ?? \"\",\n parameters,\n };\n }\n\n const tools: GeminiTool[] = [\n { functionDeclarations: [geminiFunctionDeclaration] },\n ];\n llm = this.bindTools(tools).withConfig({ tool_choice: functionName });\n\n outputParser = createFunctionCallingParser(schema, functionName);\n } else {\n // Default to jsonSchema method\n const jsonSchema = schemaToGeminiParameters(schema);\n llm = this.withConfig({\n responseSchema: jsonSchema as GeminiJsonSchema,\n });\n outputParser = createContentParser(schema);\n }\n\n return assembleStructuredOutputPipeline(\n llm,\n outputParser,\n includeRaw,\n includeRaw ? \"StructuredOutputRunnable\" : \"ChatGoogleStructuredOutput\"\n );\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AAwEA,IAAa,iBAAb,cAAiD,4BAG/C;CACA;CAEA,YACE,QACA,QACA,QACA,WACA;AACA,QAAM,QAAQ,QAAQ,QAAQ,UAAU;AACxC,OAAK,qCACH,QAAQ;;CAGZ,IAAI,uBAAgC;AAClC,SAAO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QACA,QACA,EAAE,OAAO,CACV;;;;;CAMP,oBAAoB;AAClB,SAAO,EAAE;;;;;;;;;;;CAYX,IAAI,UAAwB;AAC1B,SAAO,SAAS,KAAK,UAAU,EAAE;;CA2BnC,qBAIE,cAKA,QAMI;EACJ,MAAM,SAAS;EACf,MAAM,OAAO,QAAQ;EACrB,MAAM,SAAS,QAAQ;EACvB,MAAM,aAAa,QAAQ;AAE3B,MAAI,WAAW,WACb,OAAM,IAAI,MACR,sEACD;EAGH,IAAI;EACJ,IAAI;AAEJ,MAAI,WAAW,mBAAmB;GAChC,IAAI,eAAe,QAAQ;GAC3B,IAAI;AACJ,OAAI,mBAAmB,OAAO,IAAI,qBAAqB,OAAO,EAAE;IAC9D,MAAM,aAAa,yBAAyB,OAAO;AACnD,gCAA4B;KAC1B,MAAM;KACN,aACE,WAAW,eAAe;KAC5B,YAAY;KACb;cAED,OAAO,OAAO,SAAS,YACvB,OAAO,OAAO,eAAe,YAC7B,OAAO,cAAc,MACrB;AACA,gCAA4B;AAC5B,mBAAe,OAAO;UACjB;IAEL,MAAM,aAA+B,2BAA2B,OAAO;AACvE,gCAA4B;KAC1B,MAAM;KACN,aAAa,OAAO,eAAe;KACnC;KACD;;GAGH,MAAM,QAAsB,CAC1B,EAAE,sBAAsB,CAAC,0BAA0B,EAAE,CACtD;AACD,SAAM,KAAK,UAAU,MAAM,CAAC,WAAW,EAAE,aAAa,cAAc,CAAC;AAErE,kBAAe,4BAA4B,QAAQ,aAAa;SAC3D;GAEL,MAAM,aAAa,yBAAyB,OAAO;AACnD,SAAM,KAAK,WAAW,EACpB,gBAAgB,YACjB,CAAC;AACF,kBAAe,oBAAoB,OAAO;;AAG5C,SAAO,iCACL,KACA,cACA,YACA,aAAa,6BAA6B,6BAC3C"}
|
package/dist/llms.cjs
CHANGED
|
@@ -21,7 +21,7 @@ var GoogleLLMConnection = class extends require_connection.AbstractGoogleLLMConn
|
|
|
21
21
|
var ProxyChatGoogle = class extends require_chat_models.ChatGoogleBase {
|
|
22
22
|
constructor(fields) {
|
|
23
23
|
super(fields);
|
|
24
|
-
this._addVersion("@langchain/google-common", "2.1.
|
|
24
|
+
this._addVersion("@langchain/google-common", "2.1.25");
|
|
25
25
|
}
|
|
26
26
|
buildAbstractedClient(fields) {
|
|
27
27
|
return fields.connection.client;
|
package/dist/llms.js
CHANGED
|
@@ -21,7 +21,7 @@ var GoogleLLMConnection = class extends AbstractGoogleLLMConnection {
|
|
|
21
21
|
var ProxyChatGoogle = class extends ChatGoogleBase {
|
|
22
22
|
constructor(fields) {
|
|
23
23
|
super(fields);
|
|
24
|
-
this._addVersion("@langchain/google-common", "2.1.
|
|
24
|
+
this._addVersion("@langchain/google-common", "2.1.25");
|
|
25
25
|
}
|
|
26
26
|
buildAbstractedClient(fields) {
|
|
27
27
|
return fields.connection.client;
|
package/dist/output_parsers.d.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { GeminiGroundingChunk, GeminiGroundingMetadata, GeminiGroundingSupport } from "./types.js";
|
|
2
2
|
import { ChatGeneration, Generation } from "@langchain/core/outputs";
|
|
3
|
-
import { BaseLLMOutputParser } from "@langchain/core/output_parsers";
|
|
4
3
|
import { Callbacks } from "@langchain/core/callbacks/manager";
|
|
4
|
+
import { BaseLLMOutputParser } from "@langchain/core/output_parsers";
|
|
5
5
|
|
|
6
6
|
//#region src/output_parsers.d.ts
|
|
7
7
|
type Generations = Generation[] | ChatGeneration[];
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
let _langchain_core_utils_types = require("@langchain/core/utils/types");
|
|
2
2
|
let _langchain_core_utils_json_schema = require("@langchain/core/utils/json_schema");
|
|
3
|
+
let _langchain_core_utils_standard_schema = require("@langchain/core/utils/standard_schema");
|
|
3
4
|
|
|
4
5
|
//#region src/utils/zod_to_gemini_parameters.ts
|
|
5
6
|
function adjustObjectType(obj) {
|
|
@@ -49,7 +50,7 @@ function removeAdditionalProperties(obj) {
|
|
|
49
50
|
return obj;
|
|
50
51
|
}
|
|
51
52
|
function schemaToGeminiParameters(schema) {
|
|
52
|
-
const { $schema, ...rest } = removeAdditionalProperties((0, _langchain_core_utils_types.isInteropZodSchema)(schema) ? (0, _langchain_core_utils_json_schema.toJsonSchema)(schema) : schema);
|
|
53
|
+
const { $schema, ...rest } = removeAdditionalProperties((0, _langchain_core_utils_types.isInteropZodSchema)(schema) || (0, _langchain_core_utils_standard_schema.isSerializableSchema)(schema) ? (0, _langchain_core_utils_json_schema.toJsonSchema)(schema) : schema);
|
|
53
54
|
return rest;
|
|
54
55
|
}
|
|
55
56
|
function jsonSchemaToGeminiParameters(schema) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"zod_to_gemini_parameters.cjs","names":[],"sources":["../../src/utils/zod_to_gemini_parameters.ts"],"sourcesContent":["import {\n InteropZodType,\n isInteropZodSchema,\n} from \"@langchain/core/utils/types\";\nimport {\n type JsonSchema7Type,\n toJsonSchema,\n} from \"@langchain/core/utils/json_schema\";\nimport {\n GeminiFunctionSchema,\n GeminiJsonSchema,\n GeminiJsonSchemaDirty,\n} from \"../types.js\";\n\nexport function adjustObjectType(\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n obj: Record<string, any>\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n): Record<string, any> {\n if (!Array.isArray(obj.type)) {\n return obj;\n }\n\n const len = obj.type.length;\n const nullIndex = obj.type.indexOf(\"null\");\n if (len === 2 && nullIndex >= 0) {\n // There are only two values set for the type, and one of them is \"null\".\n // Set the type to the other one and set nullable to true.\n const typeIndex = nullIndex === 0 ? 1 : 0;\n obj.type = obj.type[typeIndex];\n obj.nullable = true;\n } else if (len === 1 && nullIndex === 0) {\n // This is nullable only without a type, which doesn't\n // make sense for Gemini\n throw new Error(\"zod_to_gemini_parameters: Gemini cannot handle null type\");\n } else if (len === 1) {\n // Although an array, it has only one value.\n // So set it to the string to match what Gemini expects.\n obj.type = obj?.type[0];\n } else {\n // Anything else could be a union type, so reject it.\n throw new Error(\n \"zod_to_gemini_parameters: Gemini cannot handle union types\"\n );\n }\n return obj;\n}\n\nexport function removeAdditionalProperties(\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n obj: Record<string, any>\n): GeminiJsonSchema {\n if (typeof obj === \"object\" && obj !== null) {\n const newObj = { ...obj };\n\n if (\"additionalProperties\" in newObj) {\n delete newObj.additionalProperties;\n }\n\n // Check for union types (anyOf, oneOf) which Gemini doesn't support\n if (\"anyOf\" in newObj || \"oneOf\" in newObj) {\n const unionTypes = newObj.anyOf || newObj.oneOf;\n\n // Check if this is a nullable union (e.g., T | null)\n // This is a 2-element array where one element is {type: \"null\"}\n if (Array.isArray(unionTypes) && unionTypes.length === 2) {\n const nullIndex = unionTypes.findIndex((t) => t.type === \"null\");\n\n if (nullIndex >= 0) {\n // This is a nullable union - extract the non-null type\n const nonNullType = unionTypes[nullIndex === 0 ? 1 : 0];\n delete newObj.anyOf;\n delete newObj.oneOf;\n // Merge the non-null type properties and add nullable: true\n for (const key in nonNullType) {\n if (key in nonNullType) {\n newObj[key] = nonNullType[key];\n }\n }\n newObj.nullable = true;\n } else {\n // Not a simple nullable union - reject it\n throw new Error(\n \"zod_to_gemini_parameters: Gemini cannot handle union types (discriminatedUnion, anyOf, oneOf). \" +\n \"Consider using a flat object structure with optional fields instead.\"\n );\n }\n } else {\n // Not a simple nullable union - reject it\n throw new Error(\n \"zod_to_gemini_parameters: Gemini cannot handle union types (discriminatedUnion, anyOf, oneOf). \" +\n \"Consider using a flat object structure with optional fields instead.\"\n );\n }\n }\n\n // Convert exclusiveMinimum (from .positive()) to minimum\n if (\"exclusiveMinimum\" in newObj && newObj.exclusiveMinimum === 0) {\n // Convert .positive() to .min(0.01)\n newObj.minimum = 0.01;\n delete newObj.exclusiveMinimum;\n } else if (\"exclusiveMinimum\" in newObj) {\n // Convert other exclusiveMinimum to minimum with a small increment\n newObj.minimum = newObj.exclusiveMinimum + 0.00001;\n delete newObj.exclusiveMinimum;\n }\n\n adjustObjectType(newObj);\n\n for (const key in newObj) {\n if (key in newObj) {\n if (Array.isArray(newObj[key])) {\n newObj[key] = newObj[key].map(removeAdditionalProperties);\n } else if (typeof newObj[key] === \"object\" && newObj[key] !== null) {\n newObj[key] = removeAdditionalProperties(newObj[key]);\n }\n }\n }\n\n return newObj as GeminiJsonSchema;\n }\n\n return obj as GeminiJsonSchema;\n}\n\nexport function schemaToGeminiParameters<\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n RunOutput extends Record<string, any> = Record<string, any>,\n>(schema
|
|
1
|
+
{"version":3,"file":"zod_to_gemini_parameters.cjs","names":[],"sources":["../../src/utils/zod_to_gemini_parameters.ts"],"sourcesContent":["import {\n InteropZodType,\n isInteropZodSchema,\n} from \"@langchain/core/utils/types\";\nimport {\n type JsonSchema7Type,\n toJsonSchema,\n} from \"@langchain/core/utils/json_schema\";\nimport {\n GeminiFunctionSchema,\n GeminiJsonSchema,\n GeminiJsonSchemaDirty,\n} from \"../types.js\";\nimport {\n isSerializableSchema,\n SerializableSchema,\n} from \"@langchain/core/utils/standard_schema\";\n\nexport function adjustObjectType(\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n obj: Record<string, any>\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n): Record<string, any> {\n if (!Array.isArray(obj.type)) {\n return obj;\n }\n\n const len = obj.type.length;\n const nullIndex = obj.type.indexOf(\"null\");\n if (len === 2 && nullIndex >= 0) {\n // There are only two values set for the type, and one of them is \"null\".\n // Set the type to the other one and set nullable to true.\n const typeIndex = nullIndex === 0 ? 1 : 0;\n obj.type = obj.type[typeIndex];\n obj.nullable = true;\n } else if (len === 1 && nullIndex === 0) {\n // This is nullable only without a type, which doesn't\n // make sense for Gemini\n throw new Error(\"zod_to_gemini_parameters: Gemini cannot handle null type\");\n } else if (len === 1) {\n // Although an array, it has only one value.\n // So set it to the string to match what Gemini expects.\n obj.type = obj?.type[0];\n } else {\n // Anything else could be a union type, so reject it.\n throw new Error(\n \"zod_to_gemini_parameters: Gemini cannot handle union types\"\n );\n }\n return obj;\n}\n\nexport function removeAdditionalProperties(\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n obj: Record<string, any>\n): GeminiJsonSchema {\n if (typeof obj === \"object\" && obj !== null) {\n const newObj = { ...obj };\n\n if (\"additionalProperties\" in newObj) {\n delete newObj.additionalProperties;\n }\n\n // Check for union types (anyOf, oneOf) which Gemini doesn't support\n if (\"anyOf\" in newObj || \"oneOf\" in newObj) {\n const unionTypes = newObj.anyOf || newObj.oneOf;\n\n // Check if this is a nullable union (e.g., T | null)\n // This is a 2-element array where one element is {type: \"null\"}\n if (Array.isArray(unionTypes) && unionTypes.length === 2) {\n const nullIndex = unionTypes.findIndex((t) => t.type === \"null\");\n\n if (nullIndex >= 0) {\n // This is a nullable union - extract the non-null type\n const nonNullType = unionTypes[nullIndex === 0 ? 1 : 0];\n delete newObj.anyOf;\n delete newObj.oneOf;\n // Merge the non-null type properties and add nullable: true\n for (const key in nonNullType) {\n if (key in nonNullType) {\n newObj[key] = nonNullType[key];\n }\n }\n newObj.nullable = true;\n } else {\n // Not a simple nullable union - reject it\n throw new Error(\n \"zod_to_gemini_parameters: Gemini cannot handle union types (discriminatedUnion, anyOf, oneOf). \" +\n \"Consider using a flat object structure with optional fields instead.\"\n );\n }\n } else {\n // Not a simple nullable union - reject it\n throw new Error(\n \"zod_to_gemini_parameters: Gemini cannot handle union types (discriminatedUnion, anyOf, oneOf). \" +\n \"Consider using a flat object structure with optional fields instead.\"\n );\n }\n }\n\n // Convert exclusiveMinimum (from .positive()) to minimum\n if (\"exclusiveMinimum\" in newObj && newObj.exclusiveMinimum === 0) {\n // Convert .positive() to .min(0.01)\n newObj.minimum = 0.01;\n delete newObj.exclusiveMinimum;\n } else if (\"exclusiveMinimum\" in newObj) {\n // Convert other exclusiveMinimum to minimum with a small increment\n newObj.minimum = newObj.exclusiveMinimum + 0.00001;\n delete newObj.exclusiveMinimum;\n }\n\n adjustObjectType(newObj);\n\n for (const key in newObj) {\n if (key in newObj) {\n if (Array.isArray(newObj[key])) {\n newObj[key] = newObj[key].map(removeAdditionalProperties);\n } else if (typeof newObj[key] === \"object\" && newObj[key] !== null) {\n newObj[key] = removeAdditionalProperties(newObj[key]);\n }\n }\n }\n\n return newObj as GeminiJsonSchema;\n }\n\n return obj as GeminiJsonSchema;\n}\n\nexport function schemaToGeminiParameters<\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n RunOutput extends Record<string, any> = Record<string, any>,\n>(\n schema:\n | SerializableSchema<RunOutput>\n | InteropZodType<RunOutput>\n | JsonSchema7Type\n): GeminiFunctionSchema {\n // Gemini doesn't accept either the $schema or additionalProperties\n // attributes, so we need to explicitly remove them.\n // Zod sometimes also makes an array of type (because of .nullish()),\n // which needs cleaning up.\n const jsonSchema = removeAdditionalProperties(\n isInteropZodSchema(schema) || isSerializableSchema(schema)\n ? toJsonSchema(schema)\n : schema\n );\n const { $schema, ...rest } = jsonSchema;\n return rest;\n}\n\nexport function jsonSchemaToGeminiParameters(\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n schema: Record<string, any>\n): GeminiFunctionSchema {\n // Gemini doesn't accept either the $schema or additionalProperties\n // attributes, so we need to explicitly remove them.\n const jsonSchema = removeAdditionalProperties(\n schema as GeminiJsonSchemaDirty\n );\n const { $schema, ...rest } = jsonSchema;\n\n return rest;\n}\n"],"mappings":";;;;;AAkBA,SAAgB,iBAEd,KAEqB;AACrB,KAAI,CAAC,MAAM,QAAQ,IAAI,KAAK,CAC1B,QAAO;CAGT,MAAM,MAAM,IAAI,KAAK;CACrB,MAAM,YAAY,IAAI,KAAK,QAAQ,OAAO;AAC1C,KAAI,QAAQ,KAAK,aAAa,GAAG;EAG/B,MAAM,YAAY,cAAc,IAAI,IAAI;AACxC,MAAI,OAAO,IAAI,KAAK;AACpB,MAAI,WAAW;YACN,QAAQ,KAAK,cAAc,EAGpC,OAAM,IAAI,MAAM,2DAA2D;UAClE,QAAQ,EAGjB,K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E,SAAS,GAAG,SAHD,2BACjB,OACD;AAGD,QAAO"}
|
|
@@ -1,11 +1,12 @@
|
|
|
1
1
|
import { GeminiFunctionSchema, GeminiJsonSchema } from "../types.cjs";
|
|
2
2
|
import { InteropZodType } from "@langchain/core/utils/types";
|
|
3
|
+
import { SerializableSchema } from "@langchain/core/utils/standard_schema";
|
|
3
4
|
import { JsonSchema7Type } from "@langchain/core/utils/json_schema";
|
|
4
5
|
|
|
5
6
|
//#region src/utils/zod_to_gemini_parameters.d.ts
|
|
6
7
|
declare function adjustObjectType(obj: Record<string, any>): Record<string, any>;
|
|
7
8
|
declare function removeAdditionalProperties(obj: Record<string, any>): GeminiJsonSchema;
|
|
8
|
-
declare function schemaToGeminiParameters<RunOutput extends Record<string, any> = Record<string, any>>(schema: InteropZodType<RunOutput> | JsonSchema7Type): GeminiFunctionSchema;
|
|
9
|
+
declare function schemaToGeminiParameters<RunOutput extends Record<string, any> = Record<string, any>>(schema: SerializableSchema<RunOutput> | InteropZodType<RunOutput> | JsonSchema7Type): GeminiFunctionSchema;
|
|
9
10
|
declare function jsonSchemaToGeminiParameters(schema: Record<string, any>): GeminiFunctionSchema;
|
|
10
11
|
//#endregion
|
|
11
12
|
export { adjustObjectType, jsonSchemaToGeminiParameters, removeAdditionalProperties, schemaToGeminiParameters };
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"zod_to_gemini_parameters.d.cts","names":[],"sources":["../../src/utils/zod_to_gemini_parameters.ts"],"mappings":"
|
|
1
|
+
{"version":3,"file":"zod_to_gemini_parameters.d.cts","names":[],"sources":["../../src/utils/zod_to_gemini_parameters.ts"],"mappings":";;;;;;iBAkBgB,gBAAA,CAEd,GAAA,EAAK,MAAA,gBAEJ,MAAA;AAAA,iBA8Ba,0BAAA,CAEd,GAAA,EAAK,MAAA,gBACJ,gBAAA;AAAA,iBA0Ea,wBAAA,mBAEI,MAAA,gBAAsB,MAAA,cAAA,CAExC,MAAA,EACI,kBAAA,CAAmB,SAAA,IACnB,cAAA,CAAe,SAAA,IACf,eAAA,GACH,oBAAA;AAAA,iBAca,4BAAA,CAEd,MAAA,EAAQ,MAAA,gBACP,oBAAA"}
|
|
@@ -1,11 +1,12 @@
|
|
|
1
1
|
import { GeminiFunctionSchema, GeminiJsonSchema } from "../types.js";
|
|
2
2
|
import { InteropZodType } from "@langchain/core/utils/types";
|
|
3
3
|
import { JsonSchema7Type } from "@langchain/core/utils/json_schema";
|
|
4
|
+
import { SerializableSchema } from "@langchain/core/utils/standard_schema";
|
|
4
5
|
|
|
5
6
|
//#region src/utils/zod_to_gemini_parameters.d.ts
|
|
6
7
|
declare function adjustObjectType(obj: Record<string, any>): Record<string, any>;
|
|
7
8
|
declare function removeAdditionalProperties(obj: Record<string, any>): GeminiJsonSchema;
|
|
8
|
-
declare function schemaToGeminiParameters<RunOutput extends Record<string, any> = Record<string, any>>(schema: InteropZodType<RunOutput> | JsonSchema7Type): GeminiFunctionSchema;
|
|
9
|
+
declare function schemaToGeminiParameters<RunOutput extends Record<string, any> = Record<string, any>>(schema: SerializableSchema<RunOutput> | InteropZodType<RunOutput> | JsonSchema7Type): GeminiFunctionSchema;
|
|
9
10
|
declare function jsonSchemaToGeminiParameters(schema: Record<string, any>): GeminiFunctionSchema;
|
|
10
11
|
//#endregion
|
|
11
12
|
export { adjustObjectType, jsonSchemaToGeminiParameters, removeAdditionalProperties, schemaToGeminiParameters };
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"zod_to_gemini_parameters.d.ts","names":[],"sources":["../../src/utils/zod_to_gemini_parameters.ts"],"mappings":"
|
|
1
|
+
{"version":3,"file":"zod_to_gemini_parameters.d.ts","names":[],"sources":["../../src/utils/zod_to_gemini_parameters.ts"],"mappings":";;;;;;iBAkBgB,gBAAA,CAEd,GAAA,EAAK,MAAA,gBAEJ,MAAA;AAAA,iBA8Ba,0BAAA,CAEd,GAAA,EAAK,MAAA,gBACJ,gBAAA;AAAA,iBA0Ea,wBAAA,mBAEI,MAAA,gBAAsB,MAAA,cAAA,CAExC,MAAA,EACI,kBAAA,CAAmB,SAAA,IACnB,cAAA,CAAe,SAAA,IACf,eAAA,GACH,oBAAA;AAAA,iBAca,4BAAA,CAEd,MAAA,EAAQ,MAAA,gBACP,oBAAA"}
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { isInteropZodSchema } from "@langchain/core/utils/types";
|
|
2
2
|
import { toJsonSchema } from "@langchain/core/utils/json_schema";
|
|
3
|
+
import { isSerializableSchema } from "@langchain/core/utils/standard_schema";
|
|
3
4
|
|
|
4
5
|
//#region src/utils/zod_to_gemini_parameters.ts
|
|
5
6
|
function adjustObjectType(obj) {
|
|
@@ -49,7 +50,7 @@ function removeAdditionalProperties(obj) {
|
|
|
49
50
|
return obj;
|
|
50
51
|
}
|
|
51
52
|
function schemaToGeminiParameters(schema) {
|
|
52
|
-
const { $schema, ...rest } = removeAdditionalProperties(isInteropZodSchema(schema) ? toJsonSchema(schema) : schema);
|
|
53
|
+
const { $schema, ...rest } = removeAdditionalProperties(isInteropZodSchema(schema) || isSerializableSchema(schema) ? toJsonSchema(schema) : schema);
|
|
53
54
|
return rest;
|
|
54
55
|
}
|
|
55
56
|
function jsonSchemaToGeminiParameters(schema) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"zod_to_gemini_parameters.js","names":[],"sources":["../../src/utils/zod_to_gemini_parameters.ts"],"sourcesContent":["import {\n InteropZodType,\n isInteropZodSchema,\n} from \"@langchain/core/utils/types\";\nimport {\n type JsonSchema7Type,\n toJsonSchema,\n} from \"@langchain/core/utils/json_schema\";\nimport {\n GeminiFunctionSchema,\n GeminiJsonSchema,\n GeminiJsonSchemaDirty,\n} from \"../types.js\";\n\nexport function adjustObjectType(\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n obj: Record<string, any>\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n): Record<string, any> {\n if (!Array.isArray(obj.type)) {\n return obj;\n }\n\n const len = obj.type.length;\n const nullIndex = obj.type.indexOf(\"null\");\n if (len === 2 && nullIndex >= 0) {\n // There are only two values set for the type, and one of them is \"null\".\n // Set the type to the other one and set nullable to true.\n const typeIndex = nullIndex === 0 ? 1 : 0;\n obj.type = obj.type[typeIndex];\n obj.nullable = true;\n } else if (len === 1 && nullIndex === 0) {\n // This is nullable only without a type, which doesn't\n // make sense for Gemini\n throw new Error(\"zod_to_gemini_parameters: Gemini cannot handle null type\");\n } else if (len === 1) {\n // Although an array, it has only one value.\n // So set it to the string to match what Gemini expects.\n obj.type = obj?.type[0];\n } else {\n // Anything else could be a union type, so reject it.\n throw new Error(\n \"zod_to_gemini_parameters: Gemini cannot handle union types\"\n );\n }\n return obj;\n}\n\nexport function removeAdditionalProperties(\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n obj: Record<string, any>\n): GeminiJsonSchema {\n if (typeof obj === \"object\" && obj !== null) {\n const newObj = { ...obj };\n\n if (\"additionalProperties\" in newObj) {\n delete newObj.additionalProperties;\n }\n\n // Check for union types (anyOf, oneOf) which Gemini doesn't support\n if (\"anyOf\" in newObj || \"oneOf\" in newObj) {\n const unionTypes = newObj.anyOf || newObj.oneOf;\n\n // Check if this is a nullable union (e.g., T | null)\n // This is a 2-element array where one element is {type: \"null\"}\n if (Array.isArray(unionTypes) && unionTypes.length === 2) {\n const nullIndex = unionTypes.findIndex((t) => t.type === \"null\");\n\n if (nullIndex >= 0) {\n // This is a nullable union - extract the non-null type\n const nonNullType = unionTypes[nullIndex === 0 ? 1 : 0];\n delete newObj.anyOf;\n delete newObj.oneOf;\n // Merge the non-null type properties and add nullable: true\n for (const key in nonNullType) {\n if (key in nonNullType) {\n newObj[key] = nonNullType[key];\n }\n }\n newObj.nullable = true;\n } else {\n // Not a simple nullable union - reject it\n throw new Error(\n \"zod_to_gemini_parameters: Gemini cannot handle union types (discriminatedUnion, anyOf, oneOf). \" +\n \"Consider using a flat object structure with optional fields instead.\"\n );\n }\n } else {\n // Not a simple nullable union - reject it\n throw new Error(\n \"zod_to_gemini_parameters: Gemini cannot handle union types (discriminatedUnion, anyOf, oneOf). \" +\n \"Consider using a flat object structure with optional fields instead.\"\n );\n }\n }\n\n // Convert exclusiveMinimum (from .positive()) to minimum\n if (\"exclusiveMinimum\" in newObj && newObj.exclusiveMinimum === 0) {\n // Convert .positive() to .min(0.01)\n newObj.minimum = 0.01;\n delete newObj.exclusiveMinimum;\n } else if (\"exclusiveMinimum\" in newObj) {\n // Convert other exclusiveMinimum to minimum with a small increment\n newObj.minimum = newObj.exclusiveMinimum + 0.00001;\n delete newObj.exclusiveMinimum;\n }\n\n adjustObjectType(newObj);\n\n for (const key in newObj) {\n if (key in newObj) {\n if (Array.isArray(newObj[key])) {\n newObj[key] = newObj[key].map(removeAdditionalProperties);\n } else if (typeof newObj[key] === \"object\" && newObj[key] !== null) {\n newObj[key] = removeAdditionalProperties(newObj[key]);\n }\n }\n }\n\n return newObj as GeminiJsonSchema;\n }\n\n return obj as GeminiJsonSchema;\n}\n\nexport function schemaToGeminiParameters<\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n RunOutput extends Record<string, any> = Record<string, any>,\n>(schema
|
|
1
|
+
{"version":3,"file":"zod_to_gemini_parameters.js","names":[],"sources":["../../src/utils/zod_to_gemini_parameters.ts"],"sourcesContent":["import {\n InteropZodType,\n isInteropZodSchema,\n} from \"@langchain/core/utils/types\";\nimport {\n type JsonSchema7Type,\n toJsonSchema,\n} from \"@langchain/core/utils/json_schema\";\nimport {\n GeminiFunctionSchema,\n GeminiJsonSchema,\n GeminiJsonSchemaDirty,\n} from \"../types.js\";\nimport {\n isSerializableSchema,\n SerializableSchema,\n} from \"@langchain/core/utils/standard_schema\";\n\nexport function adjustObjectType(\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n obj: Record<string, any>\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n): Record<string, any> {\n if (!Array.isArray(obj.type)) {\n return obj;\n }\n\n const len = obj.type.length;\n const nullIndex = obj.type.indexOf(\"null\");\n if (len === 2 && nullIndex >= 0) {\n // There are only two values set for the type, and one of them is \"null\".\n // Set the type to the other one and set nullable to true.\n const typeIndex = nullIndex === 0 ? 1 : 0;\n obj.type = obj.type[typeIndex];\n obj.nullable = true;\n } else if (len === 1 && nullIndex === 0) {\n // This is nullable only without a type, which doesn't\n // make sense for Gemini\n throw new Error(\"zod_to_gemini_parameters: Gemini cannot handle null type\");\n } else if (len === 1) {\n // Although an array, it has only one value.\n // So set it to the string to match what Gemini expects.\n obj.type = obj?.type[0];\n } else {\n // Anything else could be a union type, so reject it.\n throw new Error(\n \"zod_to_gemini_parameters: Gemini cannot handle union types\"\n );\n }\n return obj;\n}\n\nexport function removeAdditionalProperties(\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n obj: Record<string, any>\n): GeminiJsonSchema {\n if (typeof obj === \"object\" && obj !== null) {\n const newObj = { ...obj };\n\n if (\"additionalProperties\" in newObj) {\n delete newObj.additionalProperties;\n }\n\n // Check for union types (anyOf, oneOf) which Gemini doesn't support\n if (\"anyOf\" in newObj || \"oneOf\" in newObj) {\n const unionTypes = newObj.anyOf || newObj.oneOf;\n\n // Check if this is a nullable union (e.g., T | null)\n // This is a 2-element array where one element is {type: \"null\"}\n if (Array.isArray(unionTypes) && unionTypes.length === 2) {\n const nullIndex = unionTypes.findIndex((t) => t.type === \"null\");\n\n if (nullIndex >= 0) {\n // This is a nullable union - extract the non-null type\n const nonNullType = unionTypes[nullIndex === 0 ? 1 : 0];\n delete newObj.anyOf;\n delete newObj.oneOf;\n // Merge the non-null type properties and add nullable: true\n for (const key in nonNullType) {\n if (key in nonNullType) {\n newObj[key] = nonNullType[key];\n }\n }\n newObj.nullable = true;\n } else {\n // Not a simple nullable union - reject it\n throw new Error(\n \"zod_to_gemini_parameters: Gemini cannot handle union types (discriminatedUnion, anyOf, oneOf). \" +\n \"Consider using a flat object structure with optional fields instead.\"\n );\n }\n } else {\n // Not a simple nullable union - reject it\n throw new Error(\n \"zod_to_gemini_parameters: Gemini cannot handle union types (discriminatedUnion, anyOf, oneOf). \" +\n \"Consider using a flat object structure with optional fields instead.\"\n );\n }\n }\n\n // Convert exclusiveMinimum (from .positive()) to minimum\n if (\"exclusiveMinimum\" in newObj && newObj.exclusiveMinimum === 0) {\n // Convert .positive() to .min(0.01)\n newObj.minimum = 0.01;\n delete newObj.exclusiveMinimum;\n } else if (\"exclusiveMinimum\" in newObj) {\n // Convert other exclusiveMinimum to minimum with a small increment\n newObj.minimum = newObj.exclusiveMinimum + 0.00001;\n delete newObj.exclusiveMinimum;\n }\n\n adjustObjectType(newObj);\n\n for (const key in newObj) {\n if (key in newObj) {\n if (Array.isArray(newObj[key])) {\n newObj[key] = newObj[key].map(removeAdditionalProperties);\n } else if (typeof newObj[key] === \"object\" && newObj[key] !== null) {\n newObj[key] = removeAdditionalProperties(newObj[key]);\n }\n }\n }\n\n return newObj as GeminiJsonSchema;\n }\n\n return obj as GeminiJsonSchema;\n}\n\nexport function schemaToGeminiParameters<\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n RunOutput extends Record<string, any> = Record<string, any>,\n>(\n schema:\n | SerializableSchema<RunOutput>\n | InteropZodType<RunOutput>\n | JsonSchema7Type\n): GeminiFunctionSchema {\n // Gemini doesn't accept either the $schema or additionalProperties\n // attributes, so we need to explicitly remove them.\n // Zod sometimes also makes an array of type (because of .nullish()),\n // which needs cleaning up.\n const jsonSchema = removeAdditionalProperties(\n isInteropZodSchema(schema) || isSerializableSchema(schema)\n ? toJsonSchema(schema)\n : schema\n );\n const { $schema, ...rest } = jsonSchema;\n return rest;\n}\n\nexport function jsonSchemaToGeminiParameters(\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n schema: Record<string, any>\n): GeminiFunctionSchema {\n // Gemini doesn't accept either the $schema or additionalProperties\n // attributes, so we need to explicitly remove them.\n const jsonSchema = removeAdditionalProperties(\n schema as GeminiJsonSchemaDirty\n );\n const { $schema, ...rest } = jsonSchema;\n\n return rest;\n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,OAChB,KAAI,OAAO,QACT;OAAI,MAAM,QAAQ,OAAO,KAAK,CAC5B,QAAO,OAAO,OAAO,KAAK,IAAI,2BAA2B;YAChD,OAAO,OAAO,SAAS,YAAY,OAAO,SAAS,KAC5D,QAAO,OAAO,2BAA2B,OAAO,KAAK;;AAK3D,SAAO;;AAGT,QAAO;;AAGT,SAAgB,yBAId,QAIsB;CAUtB,MAAM,EAAE,SAAS,GAAG,SALD,2BACjB,mBAAmB,OAAO,IAAI,qBAAqB,OAAO,GACtD,aAAa,OAAO,GACpB,OACL;AAED,QAAO;;AAGT,SAAgB,6BAEd,QACsB;CAMtB,MAAM,EAAE,SAAS,GAAG,SAHD,2BACjB,OACD;AAGD,QAAO"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@langchain/google-common",
|
|
3
|
-
"version": "2.1.
|
|
3
|
+
"version": "2.1.25",
|
|
4
4
|
"description": "Core types and classes for Google services.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"engines": {
|
|
@@ -10,19 +10,19 @@
|
|
|
10
10
|
"type": "git",
|
|
11
11
|
"url": "git@github.com:langchain-ai/langchainjs.git"
|
|
12
12
|
},
|
|
13
|
-
"homepage": "https://github.com/langchain-ai/langchainjs/tree/main/libs/langchain-google-common/",
|
|
13
|
+
"homepage": "https://github.com/langchain-ai/langchainjs/tree/main/libs/providers/langchain-google-common/",
|
|
14
14
|
"author": "LangChain",
|
|
15
15
|
"license": "MIT",
|
|
16
16
|
"dependencies": {
|
|
17
17
|
"uuid": "^10.0.0"
|
|
18
18
|
},
|
|
19
19
|
"peerDependencies": {
|
|
20
|
-
"@langchain/core": "^1.1.
|
|
20
|
+
"@langchain/core": "^1.1.32"
|
|
21
21
|
},
|
|
22
22
|
"devDependencies": {
|
|
23
23
|
"@jest/globals": "^30.2.0",
|
|
24
24
|
"@types/uuid": "^10.0.0",
|
|
25
|
-
"@swc/core": "^1.15.
|
|
25
|
+
"@swc/core": "^1.15.18",
|
|
26
26
|
"@swc/jest": "^0.2.29",
|
|
27
27
|
"@tsconfig/recommended": "^1.0.3",
|
|
28
28
|
"dotenv": "^16.3.1",
|
|
@@ -34,7 +34,7 @@
|
|
|
34
34
|
"ts-jest": "^29.4.6",
|
|
35
35
|
"typescript": "~5.8.3",
|
|
36
36
|
"zod": "^3.25.76",
|
|
37
|
-
"@langchain/core": "^1.1.
|
|
37
|
+
"@langchain/core": "^1.1.32",
|
|
38
38
|
"@langchain/eslint": "0.1.1",
|
|
39
39
|
"@langchain/tsconfig": "0.0.1"
|
|
40
40
|
},
|