@librechat/agents 3.2.66 → 3.2.68
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/dist/cjs/hooks/createToolPolicyHook.cjs +5 -5
- package/dist/cjs/hooks/createToolPolicyHook.cjs.map +1 -1
- package/dist/cjs/llm/google/index.cjs +2 -0
- package/dist/cjs/llm/google/index.cjs.map +1 -1
- package/dist/cjs/llm/google/utils/common.cjs +28 -0
- package/dist/cjs/llm/google/utils/common.cjs.map +1 -1
- package/dist/cjs/tools/ToolSearch.cjs +59 -14
- package/dist/cjs/tools/ToolSearch.cjs.map +1 -1
- package/dist/cjs/tools/search/tool.cjs +5 -3
- package/dist/cjs/tools/search/tool.cjs.map +1 -1
- package/dist/esm/hooks/createToolPolicyHook.mjs +5 -5
- package/dist/esm/hooks/createToolPolicyHook.mjs.map +1 -1
- package/dist/esm/llm/google/index.mjs +3 -1
- package/dist/esm/llm/google/index.mjs.map +1 -1
- package/dist/esm/llm/google/utils/common.mjs +28 -1
- package/dist/esm/llm/google/utils/common.mjs.map +1 -1
- package/dist/esm/tools/ToolSearch.mjs +59 -14
- package/dist/esm/tools/ToolSearch.mjs.map +1 -1
- package/dist/esm/tools/search/tool.mjs +5 -3
- package/dist/esm/tools/search/tool.mjs.map +1 -1
- package/dist/types/hooks/createToolPolicyHook.d.ts +12 -15
- package/dist/types/llm/google/utils/common.d.ts +9 -0
- package/dist/types/tools/search/types.d.ts +2 -0
- package/package.json +1 -1
- package/src/hooks/__tests__/createToolPolicyHook.test.ts +13 -4
- package/src/hooks/createToolPolicyHook.ts +16 -19
- package/src/llm/google/index.ts +3 -0
- package/src/llm/google/utils/common.test.ts +57 -2
- package/src/llm/google/utils/common.ts +44 -0
- package/src/tools/ToolSearch.ts +81 -23
- package/src/tools/__tests__/ToolSearch.test.ts +151 -0
- package/src/tools/__tests__/hitl.test.ts +114 -1
- package/src/tools/search/source-processing.test.ts +57 -0
- package/src/tools/search/tool.ts +13 -1
- package/src/tools/search/types.ts +2 -0
|
@@ -39,12 +39,12 @@ function formatReason(template, toolName) {
|
|
|
39
39
|
* registry.register('PreToolUse', { hooks: [policyHook] });
|
|
40
40
|
* ```
|
|
41
41
|
*
|
|
42
|
-
*
|
|
42
|
+
* Explicit rules take precedence over fallback modes:
|
|
43
43
|
*
|
|
44
44
|
* 1. `deny` rule match → `'deny'` (always wins, even in `bypass`).
|
|
45
|
-
* 2. `
|
|
45
|
+
* 2. `ask` rule match → `'ask'`.
|
|
46
46
|
* 3. `allow` rule match → `'allow'`.
|
|
47
|
-
* 4. `
|
|
47
|
+
* 4. `mode === 'bypass'` → `'allow'`.
|
|
48
48
|
* 5. `mode === 'dontAsk'` → `'deny'`.
|
|
49
49
|
* 6. fallthrough → `'ask'`.
|
|
50
50
|
*
|
|
@@ -73,9 +73,9 @@ function createToolPolicyHook(config) {
|
|
|
73
73
|
}
|
|
74
74
|
function decide(toolName, mode, denyMatch, allowMatch, askMatch) {
|
|
75
75
|
if (denyMatch(toolName)) return "deny";
|
|
76
|
-
if (mode === "bypass") return "allow";
|
|
77
|
-
if (allowMatch(toolName)) return "allow";
|
|
78
76
|
if (askMatch(toolName)) return "ask";
|
|
77
|
+
if (allowMatch(toolName)) return "allow";
|
|
78
|
+
if (mode === "bypass") return "allow";
|
|
79
79
|
if (mode === "dontAsk") return "deny";
|
|
80
80
|
return "ask";
|
|
81
81
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"createToolPolicyHook.cjs","names":[],"sources":["../../../src/hooks/createToolPolicyHook.ts"],"sourcesContent":["/**\n * Declarative `PreToolUse` hook factory. Lets hosts express common\n * permission policies (allow / deny / ask lists + a global mode) without\n * hand-rolling matching, precedence, and decision logic per-host.\n *\n *
|
|
1
|
+
{"version":3,"file":"createToolPolicyHook.cjs","names":[],"sources":["../../../src/hooks/createToolPolicyHook.ts"],"sourcesContent":["/**\n * Declarative `PreToolUse` hook factory. Lets hosts express common\n * permission policies (allow / deny / ask lists + a global mode) without\n * hand-rolling matching, precedence, and decision logic per-host.\n *\n * Uses the Claude Code Agent SDK permission vocabulary (`allowed_tools` /\n * `disallowed_tools` / `permissionMode`) while treating modes as fallbacks\n * for calls that match no explicit rule. See the README's HITL section for\n * the cross-walk and `docs/hooks-design-report.md` for the broader hook\n * system context.\n */\n\nimport type { HookCallback, PreToolUseHookOutput, ToolDecision } from './types';\n\n/**\n * Permission mode controlling how tool calls that match no rule are\n * resolved. Mirrors Claude Code's `permissionMode`.\n *\n * - `default` — unmatched tools fall through to `'ask'` (interrupt).\n * - `dontAsk` — unmatched tools are denied; the human is never\n * prompted. Useful for headless / API agents where a\n * silent denial is preferable to a hung interrupt.\n * - `bypass` — unmatched tools are approved. Explicit `deny` and `ask`\n * rules still apply.\n */\nexport type ToolPolicyMode = 'default' | 'dontAsk' | 'bypass';\n\nexport interface ToolPolicyConfig {\n /**\n * Global mode applied to tools that don't match any rule.\n * Defaults to `'default'` (ask the human).\n */\n mode?: ToolPolicyMode;\n /**\n * Tool name patterns that are auto-approved without a prompt.\n * Patterns support glob `*` wildcards: `read_file`, `mcp:github:*`,\n * `*search*`. Match is anchored (`^pattern$`).\n */\n allow?: readonly string[];\n /**\n * Tool name patterns that are blocked outright. Wins over `allow`\n * and `ask`, and overrides `mode: 'bypass'` — a deny rule always\n * holds, matching Claude Code's \"deny rules are checked first\" guarantee.\n */\n deny?: readonly string[];\n /**\n * Tool name patterns that always trigger human approval. Wins over\n * `allow` and every mode, but not `deny`.\n */\n ask?: readonly string[];\n /**\n * Optional reason attached to the resulting `ask` / `deny` hook\n * decision so the host UI can render why approval is required.\n * The literal token `{tool}` is replaced with the tool name.\n */\n reason?: string;\n}\n\n/**\n * Compile a glob string with `*` wildcards into a single anchored\n * `RegExp`. Other regex metacharacters are escaped, so `read_file.md`\n * matches the literal dot. Patterns are short (tool names), so we do\n * not cache here — the registry's `matchesQuery` already caches its own\n * regex compilations and our patterns are evaluated once per ToolNode\n * batch, not once per stream chunk.\n */\nfunction globToRegex(pattern: string): RegExp {\n const escaped = pattern.replace(/[.+?^${}()|[\\]\\\\]/g, '\\\\$&');\n return new RegExp('^' + escaped.replace(/\\*/g, '.*') + '$');\n}\n\n/** Pre-compile a list of glob patterns into a single match function. */\nfunction compileMatchers(\n patterns: readonly string[] | undefined\n): (toolName: string) => boolean {\n if (patterns == null || patterns.length === 0) {\n return () => false;\n }\n const regexes = patterns.map(globToRegex);\n return (toolName: string): boolean => {\n for (const regex of regexes) {\n if (regex.test(toolName)) {\n return true;\n }\n }\n return false;\n };\n}\n\nfunction formatReason(\n template: string | undefined,\n toolName: string\n): string | undefined {\n if (template == null) {\n return undefined;\n }\n return template.replace(/\\{tool\\}/g, toolName);\n}\n\n/**\n * Build a `PreToolUse` hook callback that applies a declarative tool\n * permission policy. Register it with a `HookRegistry` and the SDK's\n * `humanInTheLoop` machinery handles the rest:\n *\n * ```ts\n * const policyHook = createToolPolicyHook({\n * mode: 'default',\n * allow: ['read_*', 'grep', 'glob'],\n * deny: ['delete_*'],\n * ask: ['execute_*', 'mcp:*'],\n * });\n * registry.register('PreToolUse', { hooks: [policyHook] });\n * ```\n *\n * Explicit rules take precedence over fallback modes:\n *\n * 1. `deny` rule match → `'deny'` (always wins, even in `bypass`).\n * 2. `ask` rule match → `'ask'`.\n * 3. `allow` rule match → `'allow'`.\n * 4. `mode === 'bypass'` → `'allow'`.\n * 5. `mode === 'dontAsk'` → `'deny'`.\n * 6. fallthrough → `'ask'`.\n *\n * The returned callback is a single `HookCallback`, not a `HookMatcher` —\n * register it under the matcher with the pattern you want (omit the\n * pattern to fire on every tool call, which is the typical case since\n * the policy itself does the filtering).\n */\nexport function createToolPolicyHook(\n config: ToolPolicyConfig\n): HookCallback<'PreToolUse'> {\n const denyMatcher = compileMatchers(config.deny);\n const allowMatcher = compileMatchers(config.allow);\n const askMatcher = compileMatchers(config.ask);\n const mode: ToolPolicyMode = config.mode ?? 'default';\n const reasonTemplate = config.reason;\n\n return async (input): Promise<PreToolUseHookOutput> => {\n const toolName = input.toolName;\n const decision = decide(\n toolName,\n mode,\n denyMatcher,\n allowMatcher,\n askMatcher\n );\n if (decision === 'allow') {\n return { decision };\n }\n const reason = formatReason(reasonTemplate, toolName);\n if (reason != null) {\n return { decision, reason };\n }\n return { decision };\n };\n}\n\nfunction decide(\n toolName: string,\n mode: ToolPolicyMode,\n denyMatch: (n: string) => boolean,\n allowMatch: (n: string) => boolean,\n askMatch: (n: string) => boolean\n): ToolDecision {\n if (denyMatch(toolName)) {\n return 'deny';\n }\n if (askMatch(toolName)) {\n return 'ask';\n }\n if (allowMatch(toolName)) {\n return 'allow';\n }\n if (mode === 'bypass') {\n return 'allow';\n }\n if (mode === 'dontAsk') {\n return 'deny';\n }\n return 'ask';\n}\n"],"mappings":";;;;;;;;;AAkEA,SAAS,YAAY,SAAyB;CAC5C,MAAM,UAAU,QAAQ,QAAQ,sBAAsB,MAAM;CAC5D,OAAO,IAAI,OAAO,MAAM,QAAQ,QAAQ,OAAO,IAAI,IAAI,GAAG;AAC5D;;AAGA,SAAS,gBACP,UAC+B;CAC/B,IAAI,YAAY,QAAQ,SAAS,WAAW,GAC1C,aAAa;CAEf,MAAM,UAAU,SAAS,IAAI,WAAW;CACxC,QAAQ,aAA8B;EACpC,KAAK,MAAM,SAAS,SAClB,IAAI,MAAM,KAAK,QAAQ,GACrB,OAAO;EAGX,OAAO;CACT;AACF;AAEA,SAAS,aACP,UACA,UACoB;CACpB,IAAI,YAAY,MACd;CAEF,OAAO,SAAS,QAAQ,aAAa,QAAQ;AAC/C;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA+BA,SAAgB,qBACd,QAC4B;CAC5B,MAAM,cAAc,gBAAgB,OAAO,IAAI;CAC/C,MAAM,eAAe,gBAAgB,OAAO,KAAK;CACjD,MAAM,aAAa,gBAAgB,OAAO,GAAG;CAC7C,MAAM,OAAuB,OAAO,QAAQ;CAC5C,MAAM,iBAAiB,OAAO;CAE9B,OAAO,OAAO,UAAyC;EACrD,MAAM,WAAW,MAAM;EACvB,MAAM,WAAW,OACf,UACA,MACA,aACA,cACA,UACF;EACA,IAAI,aAAa,SACf,OAAO,EAAE,SAAS;EAEpB,MAAM,SAAS,aAAa,gBAAgB,QAAQ;EACpD,IAAI,UAAU,MACZ,OAAO;GAAE;GAAU;EAAO;EAE5B,OAAO,EAAE,SAAS;CACpB;AACF;AAEA,SAAS,OACP,UACA,MACA,WACA,YACA,UACc;CACd,IAAI,UAAU,QAAQ,GACpB,OAAO;CAET,IAAI,SAAS,QAAQ,GACnB,OAAO;CAET,IAAI,WAAW,QAAQ,GACrB,OAAO;CAET,IAAI,SAAS,UACX,OAAO;CAET,IAAI,SAAS,WACX,OAAO;CAET,OAAO;AACT"}
|
|
@@ -120,6 +120,7 @@ var CustomChatGoogleGenerativeAI = class extends _langchain_google_genai.ChatGoo
|
|
|
120
120
|
this.client.systemInstruction = systemInstruction;
|
|
121
121
|
actualPrompt = prompt.slice(1);
|
|
122
122
|
}
|
|
123
|
+
actualPrompt = require_common.dropUnsupportedModelTurnPrefill(actualPrompt, this.model);
|
|
123
124
|
const request = {
|
|
124
125
|
...this.invocationParams(options),
|
|
125
126
|
contents: actualPrompt
|
|
@@ -143,6 +144,7 @@ var CustomChatGoogleGenerativeAI = class extends _langchain_google_genai.ChatGoo
|
|
|
143
144
|
this.client.systemInstruction = systemInstruction;
|
|
144
145
|
actualPrompt = prompt.slice(1);
|
|
145
146
|
}
|
|
147
|
+
actualPrompt = require_common.dropUnsupportedModelTurnPrefill(actualPrompt, this.model);
|
|
146
148
|
const request = {
|
|
147
149
|
...this.invocationParams(options),
|
|
148
150
|
contents: actualPrompt
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.cjs","names":["ChatGoogleGenerativeAI","GenerativeAI","FunctionCallingMode","convertBaseMessagesToContent","mapGenerateContentResultToChatResult","convertResponseContentToChatGenerationChunk","ChatGenerationChunk","AIMessageChunk"],"sources":["../../../../src/llm/google/index.ts"],"sourcesContent":["/* eslint-disable @typescript-eslint/ban-ts-comment */\nimport { AIMessageChunk } from '@langchain/core/messages';\nimport { ChatGenerationChunk } from '@langchain/core/outputs';\nimport { ChatGoogleGenerativeAI } from '@langchain/google-genai';\nimport { getEnvironmentVariable } from '@langchain/core/utils/env';\nimport {\n FunctionCallingMode,\n GoogleGenerativeAI as GenerativeAI,\n} from '@google/generative-ai';\nimport type {\n GenerateContentRequest,\n SafetySetting,\n ToolConfig,\n} from '@google/generative-ai';\nimport type { CallbackManagerForLLMRun } from '@langchain/core/callbacks/manager';\nimport type { BaseMessage, UsageMetadata } from '@langchain/core/messages';\nimport type { GeminiApiUsageMetadata, InputTokenDetails } from './types';\nimport type { GoogleClientOptions, GoogleThinkingConfig } from '@/types';\nimport {\n convertResponseContentToChatGenerationChunk,\n convertBaseMessagesToContent,\n mapGenerateContentResultToChatResult,\n} from './utils/common';\n\ntype GoogleToolConfigWithServerSideInvocations = ToolConfig & {\n includeServerSideToolInvocations?: boolean;\n functionCallingConfig?: Omit<\n NonNullable<ToolConfig['functionCallingConfig']>,\n 'mode'\n > & {\n mode?:\n | NonNullable<ToolConfig['functionCallingConfig']>['mode']\n | 'VALIDATED';\n };\n};\n\nexport class CustomChatGoogleGenerativeAI extends ChatGoogleGenerativeAI {\n thinkingConfig?: GoogleThinkingConfig;\n includeServerSideToolInvocations?: boolean;\n\n /**\n * Override to add gemini-3 model support for multimodal and function calling thought signatures\n */\n get _isMultimodalModel(): boolean {\n return (\n this.model.startsWith('gemini-1.5') ||\n this.model.startsWith('gemini-2') ||\n (this.model.startsWith('gemma-3-') &&\n !this.model.startsWith('gemma-3-1b')) ||\n this.model.startsWith('gemini-3')\n );\n }\n\n constructor(fields: GoogleClientOptions) {\n super(fields);\n\n this.model = fields.model.replace(/^models\\//, '');\n\n this.maxOutputTokens = fields.maxOutputTokens ?? this.maxOutputTokens;\n\n if (this.maxOutputTokens != null && this.maxOutputTokens < 0) {\n throw new Error('`maxOutputTokens` must be a positive integer');\n }\n\n this.temperature = fields.temperature ?? this.temperature;\n if (\n this.temperature != null &&\n (this.temperature < 0 || this.temperature > 2)\n ) {\n throw new Error('`temperature` must be in the range of [0.0,2.0]');\n }\n\n this.topP = fields.topP ?? this.topP;\n if (this.topP != null && this.topP < 0) {\n throw new Error('`topP` must be a positive integer');\n }\n\n if (this.topP != null && this.topP > 1) {\n throw new Error('`topP` must be below 1.');\n }\n\n this.topK = fields.topK ?? this.topK;\n if (this.topK != null && this.topK < 0) {\n throw new Error('`topK` must be a positive integer');\n }\n\n this.stopSequences = fields.stopSequences ?? this.stopSequences;\n\n this.apiKey = fields.apiKey ?? getEnvironmentVariable('GOOGLE_API_KEY');\n if (this.apiKey == null || this.apiKey === '') {\n throw new Error(\n 'Please set an API key for Google GenerativeAI ' +\n 'in the environment variable GOOGLE_API_KEY ' +\n 'or in the `apiKey` field of the ' +\n 'ChatGoogleGenerativeAI constructor'\n );\n }\n\n this.safetySettings = fields.safetySettings ?? this.safetySettings;\n if (this.safetySettings && this.safetySettings.length > 0) {\n const safetySettingsSet = new Set(\n this.safetySettings.map((s) => s.category)\n );\n if (safetySettingsSet.size !== this.safetySettings.length) {\n throw new Error(\n 'The categories in `safetySettings` array must be unique'\n );\n }\n }\n\n this.thinkingConfig = fields.thinkingConfig ?? this.thinkingConfig;\n this.includeServerSideToolInvocations =\n fields.includeServerSideToolInvocations ??\n this.includeServerSideToolInvocations;\n\n this.streaming = fields.streaming ?? this.streaming;\n this.json = fields.json;\n\n // @ts-ignore - Accessing private property from parent class\n this.client = new GenerativeAI(this.apiKey).getGenerativeModel(\n {\n model: this.model,\n safetySettings: this.safetySettings as SafetySetting[],\n generationConfig: {\n stopSequences: this.stopSequences,\n maxOutputTokens: this.maxOutputTokens,\n temperature: this.temperature,\n topP: this.topP,\n topK: this.topK,\n ...(this.json != null\n ? { responseMimeType: 'application/json' }\n : {}),\n },\n },\n {\n apiVersion: fields.apiVersion,\n baseUrl: fields.baseUrl,\n customHeaders: fields.customHeaders,\n }\n );\n this.streamUsage = fields.streamUsage ?? this.streamUsage;\n }\n\n static lc_name(): 'LibreChatGoogleGenerativeAI' {\n return 'LibreChatGoogleGenerativeAI';\n }\n\n /**\n * Helper function to convert Gemini API usage metadata to LangChain format\n * Includes support for cached tokens and tier-based tracking for gemini-3-pro-preview\n */\n private _convertToUsageMetadata(\n usageMetadata: GeminiApiUsageMetadata | undefined,\n model: string\n ): UsageMetadata | undefined {\n if (!usageMetadata) {\n return undefined;\n }\n\n const output: UsageMetadata = {\n input_tokens: usageMetadata.promptTokenCount ?? 0,\n output_tokens:\n (usageMetadata.candidatesTokenCount ?? 0) +\n (usageMetadata.thoughtsTokenCount ?? 0),\n total_tokens: usageMetadata.totalTokenCount ?? 0,\n };\n\n if (usageMetadata.cachedContentTokenCount) {\n output.input_token_details ??= {};\n output.input_token_details.cache_read =\n usageMetadata.cachedContentTokenCount;\n }\n\n // gemini-3-pro-preview has bracket based tracking of tokens per request\n if (model === 'gemini-3-pro-preview') {\n const over200k = Math.max(\n 0,\n (usageMetadata.promptTokenCount ?? 0) - 200000\n );\n const cachedOver200k = Math.max(\n 0,\n (usageMetadata.cachedContentTokenCount ?? 0) - 200000\n );\n if (over200k) {\n output.input_token_details = {\n ...output.input_token_details,\n over_200k: over200k,\n } as InputTokenDetails;\n }\n if (cachedOver200k) {\n output.input_token_details = {\n ...output.input_token_details,\n cache_read_over_200k: cachedOver200k,\n } as InputTokenDetails;\n }\n }\n\n return output;\n }\n\n invocationParams(\n options?: this['ParsedCallOptions']\n ): Omit<GenerateContentRequest, 'contents'> {\n const params = super.invocationParams(options);\n if (this.thinkingConfig) {\n /** @ts-ignore */\n this.client.generationConfig = {\n /** @ts-ignore */\n ...this.client.generationConfig,\n /** @ts-ignore */\n thinkingConfig: this.thinkingConfig,\n };\n }\n if (\n this.includeServerSideToolInvocations === true &&\n Array.isArray(params.tools) &&\n params.tools.length > 0\n ) {\n const toolConfig = params.toolConfig as\n | GoogleToolConfigWithServerSideInvocations\n | undefined;\n const functionCallingConfig = toolConfig?.functionCallingConfig;\n params.toolConfig = {\n ...toolConfig,\n ...(functionCallingConfig?.mode === FunctionCallingMode.AUTO\n ? {\n functionCallingConfig: {\n ...functionCallingConfig,\n mode: 'VALIDATED',\n },\n }\n : {}),\n includeServerSideToolInvocations: true,\n } as ToolConfig;\n }\n return params;\n }\n\n async _generate(\n messages: BaseMessage[],\n options: this['ParsedCallOptions'],\n runManager?: CallbackManagerForLLMRun\n ): Promise<import('@langchain/core/outputs').ChatResult> {\n const prompt = convertBaseMessagesToContent(\n messages,\n this._isMultimodalModel,\n this.useSystemInstruction,\n this.model\n );\n let actualPrompt = prompt;\n if (prompt?.[0].role === 'system') {\n const [systemInstruction] = prompt;\n /** @ts-ignore */\n this.client.systemInstruction = systemInstruction;\n actualPrompt = prompt.slice(1);\n }\n const parameters = this.invocationParams(options);\n const request = {\n ...parameters,\n contents: actualPrompt,\n };\n\n const res = await this.caller.callWithOptions(\n { signal: options.signal },\n async () =>\n /** @ts-ignore */\n this.client.generateContent(request)\n );\n\n const response = res.response;\n const usageMetadata = this._convertToUsageMetadata(\n /** @ts-ignore */\n response.usageMetadata,\n this.model\n );\n\n /** @ts-ignore */\n const generationResult = mapGenerateContentResultToChatResult(response, {\n usageMetadata,\n });\n\n await runManager?.handleLLMNewToken(\n generationResult.generations[0].text || '',\n undefined,\n undefined,\n undefined,\n undefined,\n undefined\n );\n return generationResult;\n }\n\n async *_streamResponseChunks(\n messages: BaseMessage[],\n options: this['ParsedCallOptions'],\n runManager?: CallbackManagerForLLMRun\n ): AsyncGenerator<ChatGenerationChunk> {\n const prompt = convertBaseMessagesToContent(\n messages,\n this._isMultimodalModel,\n this.useSystemInstruction,\n this.model\n );\n let actualPrompt = prompt;\n if (prompt?.[0].role === 'system') {\n const [systemInstruction] = prompt;\n /** @ts-ignore */\n this.client.systemInstruction = systemInstruction;\n actualPrompt = prompt.slice(1);\n }\n const parameters = this.invocationParams(options);\n const request = {\n ...parameters,\n contents: actualPrompt,\n };\n const stream = await this.caller.callWithOptions(\n { signal: options.signal },\n async () => {\n /** @ts-ignore */\n const { stream } = await this.client.generateContentStream(request);\n return stream;\n }\n );\n\n let index = 0;\n let lastUsageMetadata: UsageMetadata | undefined;\n for await (const response of stream) {\n if (\n 'usageMetadata' in response &&\n this.streamUsage !== false &&\n options.streamUsage !== false\n ) {\n lastUsageMetadata = this._convertToUsageMetadata(\n response.usageMetadata as GeminiApiUsageMetadata | undefined,\n this.model\n );\n }\n\n const chunk = convertResponseContentToChatGenerationChunk(response, {\n usageMetadata: undefined,\n index,\n });\n index += 1;\n if (!chunk) {\n continue;\n }\n\n yield chunk;\n await runManager?.handleLLMNewToken(\n chunk.text || '',\n undefined,\n undefined,\n undefined,\n undefined,\n { chunk }\n );\n }\n\n if (lastUsageMetadata) {\n const finalChunk = new ChatGenerationChunk({\n text: '',\n message: new AIMessageChunk({\n content: '',\n usage_metadata: lastUsageMetadata,\n }),\n });\n yield finalChunk;\n await runManager?.handleLLMNewToken(\n finalChunk.text || '',\n undefined,\n undefined,\n undefined,\n undefined,\n { chunk: finalChunk }\n );\n }\n }\n}\n"],"mappings":";;;;;;;AAoCA,IAAa,+BAAb,cAAkDA,wBAAAA,uBAAuB;CACvE;CACA;;;;CAKA,IAAI,qBAA8B;EAChC,OACE,KAAK,MAAM,WAAW,YAAY,KAClC,KAAK,MAAM,WAAW,UAAU,KAC/B,KAAK,MAAM,WAAW,UAAU,KAC/B,CAAC,KAAK,MAAM,WAAW,YAAY,KACrC,KAAK,MAAM,WAAW,UAAU;CAEpC;CAEA,YAAY,QAA6B;EACvC,MAAM,MAAM;EAEZ,KAAK,QAAQ,OAAO,MAAM,QAAQ,aAAa,EAAE;EAEjD,KAAK,kBAAkB,OAAO,mBAAmB,KAAK;EAEtD,IAAI,KAAK,mBAAmB,QAAQ,KAAK,kBAAkB,GACzD,MAAM,IAAI,MAAM,8CAA8C;EAGhE,KAAK,cAAc,OAAO,eAA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ACE,mBAAmB,YACnB,KAAK,gBAAgB,SACrB,QAAQ,gBAAgB,OAExB,oBAAoB,KAAK,wBACvB,SAAS,eACT,KAAK,KACP;GAGF,MAAM,QAAQE,eAAAA,4CAA4C,UAAU;IAClE,eAAe,KAAA;IACf;GACF,CAAC;GACD,SAAS;GACT,IAAI,CAAC,OACH;GAGF,MAAM;GACN,MAAM,YAAY,kBAChB,MAAM,QAAQ,IACd,KAAA,GACA,KAAA,GACA,KAAA,GACA,KAAA,GACA,EAAE,MAAM,CACV;EACF;EAEA,IAAI,mBAAmB;GACrB,MAAM,aAAa,IAAIC,wBAAAA,oBAAoB;IACzC,MAAM;IACN,SAAS,IAAIC,yBAAAA,eAAe;KAC1B,SAAS;KACT,gBAAgB;IAClB,CAAC;GACH,CAAC;GACD,MAAM;GACN,MAAM,YAAY,kBAChB,WAAW,QAAQ,IACnB,KAAA,GACA,KAAA,GACA,KAAA,GACA,KAAA,GACA,EAAE,OAAO,WAAW,CACtB;EACF;CACF;AACF"}
|
|
1
|
+
{"version":3,"file":"index.cjs","names":["ChatGoogleGenerativeAI","GenerativeAI","FunctionCallingMode","convertBaseMessagesToContent","dropUnsupportedModelTurnPrefill","mapGenerateContentResultToChatResult","convertResponseContentToChatGenerationChunk","ChatGenerationChunk","AIMessageChunk"],"sources":["../../../../src/llm/google/index.ts"],"sourcesContent":["/* eslint-disable @typescript-eslint/ban-ts-comment */\nimport { AIMessageChunk } from '@langchain/core/messages';\nimport { ChatGenerationChunk } from '@langchain/core/outputs';\nimport { ChatGoogleGenerativeAI } from '@langchain/google-genai';\nimport { getEnvironmentVariable } from '@langchain/core/utils/env';\nimport {\n FunctionCallingMode,\n GoogleGenerativeAI as GenerativeAI,\n} from '@google/generative-ai';\nimport type {\n GenerateContentRequest,\n SafetySetting,\n ToolConfig,\n} from '@google/generative-ai';\nimport type { CallbackManagerForLLMRun } from '@langchain/core/callbacks/manager';\nimport type { BaseMessage, UsageMetadata } from '@langchain/core/messages';\nimport type { GeminiApiUsageMetadata, InputTokenDetails } from './types';\nimport type { GoogleClientOptions, GoogleThinkingConfig } from '@/types';\nimport {\n convertResponseContentToChatGenerationChunk,\n convertBaseMessagesToContent,\n dropUnsupportedModelTurnPrefill,\n mapGenerateContentResultToChatResult,\n} from './utils/common';\n\ntype GoogleToolConfigWithServerSideInvocations = ToolConfig & {\n includeServerSideToolInvocations?: boolean;\n functionCallingConfig?: Omit<\n NonNullable<ToolConfig['functionCallingConfig']>,\n 'mode'\n > & {\n mode?:\n | NonNullable<ToolConfig['functionCallingConfig']>['mode']\n | 'VALIDATED';\n };\n};\n\nexport class CustomChatGoogleGenerativeAI extends ChatGoogleGenerativeAI {\n thinkingConfig?: GoogleThinkingConfig;\n includeServerSideToolInvocations?: boolean;\n\n /**\n * Override to add gemini-3 model support for multimodal and function calling thought signatures\n */\n get _isMultimodalModel(): boolean {\n return (\n this.model.startsWith('gemini-1.5') ||\n this.model.startsWith('gemini-2') ||\n (this.model.startsWith('gemma-3-') &&\n !this.model.startsWith('gemma-3-1b')) ||\n this.model.startsWith('gemini-3')\n );\n }\n\n constructor(fields: GoogleClientOptions) {\n super(fields);\n\n this.model = fields.model.replace(/^models\\//, '');\n\n this.maxOutputTokens = fields.maxOutputTokens ?? this.maxOutputTokens;\n\n if (this.maxOutputTokens != null && this.maxOutputTokens < 0) {\n throw new Error('`maxOutputTokens` must be a positive integer');\n }\n\n this.temperature = fields.temperature ?? this.temperature;\n if (\n this.temperature != null &&\n (this.temperature < 0 || this.temperature > 2)\n ) {\n throw new Error('`temperature` must be in the range of [0.0,2.0]');\n }\n\n this.topP = fields.topP ?? this.topP;\n if (this.topP != null && this.topP < 0) {\n throw new Error('`topP` must be a positive integer');\n }\n\n if (this.topP != null && this.topP > 1) {\n throw new Error('`topP` must be below 1.');\n }\n\n this.topK = fields.topK ?? this.topK;\n if (this.topK != null && this.topK < 0) {\n throw new Error('`topK` must be a positive integer');\n }\n\n this.stopSequences = fields.stopSequences ?? this.stopSequences;\n\n this.apiKey = fields.apiKey ?? getEnvironmentVariable('GOOGLE_API_KEY');\n if (this.apiKey == null || this.apiKey === '') {\n throw new Error(\n 'Please set an API key for Google GenerativeAI ' +\n 'in the environment variable GOOGLE_API_KEY ' +\n 'or in the `apiKey` field of the ' +\n 'ChatGoogleGenerativeAI constructor'\n );\n }\n\n this.safetySettings = fields.safetySettings ?? this.safetySettings;\n if (this.safetySettings && this.safetySettings.length > 0) {\n const safetySettingsSet = new Set(\n this.safetySettings.map((s) => s.category)\n );\n if (safetySettingsSet.size !== this.safetySettings.length) {\n throw new Error(\n 'The categories in `safetySettings` array must be unique'\n );\n }\n }\n\n this.thinkingConfig = fields.thinkingConfig ?? this.thinkingConfig;\n this.includeServerSideToolInvocations =\n fields.includeServerSideToolInvocations ??\n this.includeServerSideToolInvocations;\n\n this.streaming = fields.streaming ?? this.streaming;\n this.json = fields.json;\n\n // @ts-ignore - Accessing private property from parent class\n this.client = new GenerativeAI(this.apiKey).getGenerativeModel(\n {\n model: this.model,\n safetySettings: this.safetySettings as SafetySetting[],\n generationConfig: {\n stopSequences: this.stopSequences,\n maxOutputTokens: this.maxOutputTokens,\n temperature: this.temperature,\n topP: this.topP,\n topK: this.topK,\n ...(this.json != null\n ? { responseMimeType: 'application/json' }\n : {}),\n },\n },\n {\n apiVersion: fields.apiVersion,\n baseUrl: fields.baseUrl,\n customHeaders: fields.customHeaders,\n }\n );\n this.streamUsage = fields.streamUsage ?? this.streamUsage;\n }\n\n static lc_name(): 'LibreChatGoogleGenerativeAI' {\n return 'LibreChatGoogleGenerativeAI';\n }\n\n /**\n * Helper function to convert Gemini API usage metadata to LangChain format\n * Includes support for cached tokens and tier-based tracking for gemini-3-pro-preview\n */\n private _convertToUsageMetadata(\n usageMetadata: GeminiApiUsageMetadata | undefined,\n model: string\n ): UsageMetadata | undefined {\n if (!usageMetadata) {\n return undefined;\n }\n\n const output: UsageMetadata = {\n input_tokens: usageMetadata.promptTokenCount ?? 0,\n output_tokens:\n (usageMetadata.candidatesTokenCount ?? 0) +\n (usageMetadata.thoughtsTokenCount ?? 0),\n total_tokens: usageMetadata.totalTokenCount ?? 0,\n };\n\n if (usageMetadata.cachedContentTokenCount) {\n output.input_token_details ??= {};\n output.input_token_details.cache_read =\n usageMetadata.cachedContentTokenCount;\n }\n\n // gemini-3-pro-preview has bracket based tracking of tokens per request\n if (model === 'gemini-3-pro-preview') {\n const over200k = Math.max(\n 0,\n (usageMetadata.promptTokenCount ?? 0) - 200000\n );\n const cachedOver200k = Math.max(\n 0,\n (usageMetadata.cachedContentTokenCount ?? 0) - 200000\n );\n if (over200k) {\n output.input_token_details = {\n ...output.input_token_details,\n over_200k: over200k,\n } as InputTokenDetails;\n }\n if (cachedOver200k) {\n output.input_token_details = {\n ...output.input_token_details,\n cache_read_over_200k: cachedOver200k,\n } as InputTokenDetails;\n }\n }\n\n return output;\n }\n\n invocationParams(\n options?: this['ParsedCallOptions']\n ): Omit<GenerateContentRequest, 'contents'> {\n const params = super.invocationParams(options);\n if (this.thinkingConfig) {\n /** @ts-ignore */\n this.client.generationConfig = {\n /** @ts-ignore */\n ...this.client.generationConfig,\n /** @ts-ignore */\n thinkingConfig: this.thinkingConfig,\n };\n }\n if (\n this.includeServerSideToolInvocations === true &&\n Array.isArray(params.tools) &&\n params.tools.length > 0\n ) {\n const toolConfig = params.toolConfig as\n | GoogleToolConfigWithServerSideInvocations\n | undefined;\n const functionCallingConfig = toolConfig?.functionCallingConfig;\n params.toolConfig = {\n ...toolConfig,\n ...(functionCallingConfig?.mode === FunctionCallingMode.AUTO\n ? {\n functionCallingConfig: {\n ...functionCallingConfig,\n mode: 'VALIDATED',\n },\n }\n : {}),\n includeServerSideToolInvocations: true,\n } as ToolConfig;\n }\n return params;\n }\n\n async _generate(\n messages: BaseMessage[],\n options: this['ParsedCallOptions'],\n runManager?: CallbackManagerForLLMRun\n ): Promise<import('@langchain/core/outputs').ChatResult> {\n const prompt = convertBaseMessagesToContent(\n messages,\n this._isMultimodalModel,\n this.useSystemInstruction,\n this.model\n );\n let actualPrompt = prompt;\n if (prompt?.[0].role === 'system') {\n const [systemInstruction] = prompt;\n /** @ts-ignore */\n this.client.systemInstruction = systemInstruction;\n actualPrompt = prompt.slice(1);\n }\n actualPrompt = dropUnsupportedModelTurnPrefill(actualPrompt, this.model);\n const parameters = this.invocationParams(options);\n const request = {\n ...parameters,\n contents: actualPrompt,\n };\n\n const res = await this.caller.callWithOptions(\n { signal: options.signal },\n async () =>\n /** @ts-ignore */\n this.client.generateContent(request)\n );\n\n const response = res.response;\n const usageMetadata = this._convertToUsageMetadata(\n /** @ts-ignore */\n response.usageMetadata,\n this.model\n );\n\n /** @ts-ignore */\n const generationResult = mapGenerateContentResultToChatResult(response, {\n usageMetadata,\n });\n\n await runManager?.handleLLMNewToken(\n generationResult.generations[0].text || '',\n undefined,\n undefined,\n undefined,\n undefined,\n undefined\n );\n return generationResult;\n }\n\n async *_streamResponseChunks(\n messages: BaseMessage[],\n options: this['ParsedCallOptions'],\n runManager?: CallbackManagerForLLMRun\n ): AsyncGenerator<ChatGenerationChunk> {\n const prompt = convertBaseMessagesToContent(\n messages,\n this._isMultimodalModel,\n this.useSystemInstruction,\n this.model\n );\n let actualPrompt = prompt;\n if (prompt?.[0].role === 'system') {\n const [systemInstruction] = prompt;\n /** @ts-ignore */\n this.client.systemInstruction = systemInstruction;\n actualPrompt = prompt.slice(1);\n }\n actualPrompt = dropUnsupportedModelTurnPrefill(actualPrompt, this.model);\n const parameters = this.invocationParams(options);\n const request = {\n ...parameters,\n contents: actualPrompt,\n };\n const stream = await this.caller.callWithOptions(\n { signal: options.signal },\n async () => {\n /** @ts-ignore */\n const { stream } = await this.client.generateContentStream(request);\n return stream;\n }\n );\n\n let index = 0;\n let lastUsageMetadata: UsageMetadata | undefined;\n for await (const response of stream) {\n if (\n 'usageMetadata' in response &&\n this.streamUsage !== false &&\n options.streamUsage !== false\n ) {\n lastUsageMetadata = this._convertToUsageMetadata(\n response.usageMetadata as GeminiApiUsageMetadata | undefined,\n this.model\n );\n }\n\n const chunk = convertResponseContentToChatGenerationChunk(response, {\n usageMetadata: undefined,\n index,\n });\n index += 1;\n if (!chunk) {\n continue;\n }\n\n yield chunk;\n await runManager?.handleLLMNewToken(\n chunk.text || '',\n undefined,\n undefined,\n undefined,\n undefined,\n { chunk }\n );\n }\n\n if (lastUsageMetadata) {\n const finalChunk = new ChatGenerationChunk({\n text: '',\n message: new AIMessageChunk({\n content: '',\n usage_metadata: lastUsageMetadata,\n }),\n });\n yield finalChunk;\n await runManager?.handleLLMNewToken(\n finalChunk.text || '',\n undefined,\n undefined,\n undefined,\n undefined,\n { chunk: finalChunk }\n );\n }\n }\n}\n"],"mappings":";;;;;;;AAqCA,IAAa,+BAAb,cAAkDA,wBAAAA,uBAAuB;CACvE;CACA;;;;CAKA,IAAI,qBAA8B;EAChC,OACE,KAAK,MAAM,WAAW,YAAY,KAClC,KAAK,MAAM,WAAW,UAAU,KAC/B,KAAK,MAAM,WAAW,UAAU,KAC/B,CAAC,KAAK,MAAM,WAAW,YAAY,KACrC,KAAK,MAAM,WAAW,UAAU;CAEpC;CAEA,YAAY,QAA6B;EACvC,MAAM,MAAM;EAEZ,KAAK,QAAQ,OAAO,MAAM,QAAQ,aAAa,EAAE;EAEjD,KAAK,kBAAkB,OAAO,mBAAmB,KAAK;EAEtD,IAAI,KAAK,mBAAmB,QAAQ,KAAK,kBAAkB,GACzD,MAAM,IAAI,MAAM,8CAA8C;EAGhE,KAAK,cAAc,OAAO,eAAe,KAAK;EAC9C,IACE,KAAK,eAAe,SACnB,KAAK,cAAc,KAAK,KAAK,cAAc,IAE5C,MAAM,IAAI,MAAM,iDAAiD;EAGnE,KAAK,OAAO,OAAO,QAAQ,KAAK;EAChC,IAAI,KAAK,QAAQ,QAAQ,KAAK,OAAO,GACnC,MAAM,IAAI,MAAM,mCAAmC;EAGrD,IAAI,KAAK,QAAQ,QAAQ,KAAK,OAAO,GACnC,MAAM,IAAI,MAAM,yBAAyB;E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C,OACH;GAGF,MAAM;GACN,MAAM,YAAY,kBAChB,MAAM,QAAQ,IACd,KAAA,GACA,KAAA,GACA,KAAA,GACA,KAAA,GACA,EAAE,MAAM,CACV;EACF;EAEA,IAAI,mBAAmB;GACrB,MAAM,aAAa,IAAIC,wBAAAA,oBAAoB;IACzC,MAAM;IACN,SAAS,IAAIC,yBAAAA,eAAe;KAC1B,SAAS;KACT,gBAAgB;IAClB,CAAC;GACH,CAAC;GACD,MAAM;GACN,MAAM,YAAY,kBAChB,WAAW,QAAQ,IACnB,KAAA,GACA,KAAA,GACA,KAAA,GACA,KAAA,GACA,EAAE,OAAO,WAAW,CACtB;EACF;CACF;AACF"}
|
|
@@ -277,6 +277,33 @@ function convertBaseMessagesToContent(messages, isMultimodalModel, convertSystem
|
|
|
277
277
|
mergeWithPreviousContent: false
|
|
278
278
|
}).content;
|
|
279
279
|
}
|
|
280
|
+
/**
|
|
281
|
+
* Gemini models that reject a request whose `contents` end with a `model`-role
|
|
282
|
+
* turn (a "prefill"). Google enforces this on newer generations (Gemini 3.6
|
|
283
|
+
* Flash, Gemini 3.5 Flash-Lite) while older/sibling models still accept a
|
|
284
|
+
* trailing model turn, so the rule is model-scoped rather than version-wide.
|
|
285
|
+
* Extend this list as Google applies the restriction to further models.
|
|
286
|
+
* @see https://ai.google.dev/gemini-api/docs/latest-model#api-changes-and-parameter-updates
|
|
287
|
+
*/
|
|
288
|
+
const NO_PREFILL_GEMINI_MODELS = ["gemini-3.6-flash", "gemini-3.5-flash-lite"];
|
|
289
|
+
function rejectsModelTurnPrefill(model) {
|
|
290
|
+
if (model == null || model === "") return false;
|
|
291
|
+
const modelId = model.toLowerCase().split("/").pop() ?? "";
|
|
292
|
+
return NO_PREFILL_GEMINI_MODELS.some((id) => modelId === id || modelId.startsWith(`${id}-`));
|
|
293
|
+
}
|
|
294
|
+
/**
|
|
295
|
+
* Drops trailing `model`-role turns for models that reject prefill (see
|
|
296
|
+
* {@link rejectsModelTurnPrefill}). Such a turn is only produced by prefill
|
|
297
|
+
* flows (e.g. editing an assistant reply and resubmitting); these models return
|
|
298
|
+
* HTTP 400 for it, so we drop it and let the model generate fresh from the
|
|
299
|
+
* preceding user turn. No-op for every other model, preserving working prefill.
|
|
300
|
+
*/
|
|
301
|
+
function dropUnsupportedModelTurnPrefill(contents, model) {
|
|
302
|
+
if (contents == null || contents.length === 0 || !rejectsModelTurnPrefill(model)) return contents;
|
|
303
|
+
let end = contents.length;
|
|
304
|
+
while (end > 1 && contents[end - 1]?.role === "model") end -= 1;
|
|
305
|
+
return end === contents.length ? contents : contents.slice(0, end);
|
|
306
|
+
}
|
|
280
307
|
function convertResponseContentToChatGenerationChunk(response, extra) {
|
|
281
308
|
if (!response.candidates || response.candidates.length === 0) return null;
|
|
282
309
|
const [candidate] = response.candidates;
|
|
@@ -434,6 +461,7 @@ function mapGenerateContentResultToChatResult(response, extra) {
|
|
|
434
461
|
//#endregion
|
|
435
462
|
exports.convertBaseMessagesToContent = convertBaseMessagesToContent;
|
|
436
463
|
exports.convertResponseContentToChatGenerationChunk = convertResponseContentToChatGenerationChunk;
|
|
464
|
+
exports.dropUnsupportedModelTurnPrefill = dropUnsupportedModelTurnPrefill;
|
|
437
465
|
exports.mapGenerateContentResultToChatResult = mapGenerateContentResultToChatResult;
|
|
438
466
|
|
|
439
467
|
//# sourceMappingURL=common.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"common.cjs","names":["ChatMessage","toLangChainContent","STREAMED_TOOL_CALL_ADAPTER_METADATA_KEY","GOOGLE_STREAMED_TOOL_CALL_ADAPTER","STREAMED_TOOL_CALL_SEAL_METADATA_KEY","ChatGenerationChunk","AIMessageChunk","AIMessage"],"sources":["../../../../../src/llm/google/utils/common.ts"],"sourcesContent":["import { v4 as uuidv4 } from 'uuid';\nimport { ChatGenerationChunk } from '@langchain/core/outputs';\nimport { ToolCallChunk } from '@langchain/core/messages/tool';\nimport { isOpenAITool } from '@langchain/core/language_models/base';\nimport { isLangChainTool } from '@langchain/core/utils/function_calling';\nimport {\n AIMessage,\n AIMessageChunk,\n BaseMessage,\n ChatMessage,\n ToolMessage,\n ToolMessageChunk,\n MessageContent,\n MessageContentComplex,\n UsageMetadata,\n isAIMessage,\n isBaseMessage,\n isToolMessage,\n StandardContentBlockConverter,\n parseBase64DataUrl,\n convertToProviderContentBlock,\n isDataContentBlock,\n} from '@langchain/core/messages';\nimport {\n POSSIBLE_ROLES,\n type Part,\n type Content,\n type TextPart,\n type FileDataPart,\n type InlineDataPart,\n type FunctionCallPart,\n type GenerateContentCandidate,\n type EnhancedGenerateContentResponse,\n type FunctionDeclaration as GenerativeAIFunctionDeclaration,\n type FunctionDeclarationsTool as GoogleGenerativeAIFunctionDeclarationsTool,\n} from '@google/generative-ai';\nimport type { ChatGeneration, ChatResult } from '@langchain/core/outputs';\nimport {\n STREAMED_TOOL_CALL_SEAL_METADATA_KEY,\n STREAMED_TOOL_CALL_ADAPTER_METADATA_KEY,\n GOOGLE_STREAMED_TOOL_CALL_ADAPTER,\n} from '@/tools/streamedToolCallSeals';\nimport {\n jsonSchemaToGeminiParameters,\n schemaToGenerativeAIParameters,\n} from './zod_to_genai_parameters';\nimport { toLangChainContent } from '@/messages/langchain';\nimport { GoogleGenerativeAIToolType } from '../types';\n\nexport const _FUNCTION_CALL_THOUGHT_SIGNATURES_MAP_KEY =\n '__gemini_function_call_thought_signatures__';\n\nconst DUMMY_SIGNATURE =\n 'ErYCCrMCAdHtim9kOoOkrPiCNVsmlpMIKd7ZMxgiFbVQOkgp7nlLcDMzVsZwIzvuT7nQROivoXA72ccC2lSDvR0Gh7dkWaGuj7ctv6t7ZceHnecx0QYa+ix8tYpRfjhyWozQ49lWiws6+YGjCt10KRTyWsZ2h6O7iHTYJwKIRwGUHRKy/qK/6kFxJm5ML00gLq4D8s5Z6DBpp2ZlR+uF4G8jJgeWQgyHWVdx2wGYElaceVAc66tZdPQRdOHpWtgYSI1YdaXgVI8KHY3/EfNc2YqqMIulvkDBAnuMhkAjV9xmBa54Tq+ih3Im4+r3DzqhGqYdsSkhS0kZMwte4Hjs65dZzCw9lANxIqYi1DJ639WNPYihp/DCJCos7o+/EeSPJaio5sgWDyUnMGkY1atsJZ+m7pj7DD5tvQ==';\n\ntype GoogleServerSideToolPart = Part & {\n type?: 'toolCall' | 'toolResponse';\n toolCall?: object;\n toolResponse?: object;\n};\n\ntype GoogleServerSideToolPartMetadata = {\n thought?: boolean;\n thoughtSignature?: string;\n};\n\ntype GoogleFunctionCallWithId = FunctionCallPart['functionCall'] & {\n id?: string;\n};\n\ntype GoogleFunctionResponseWithId = {\n name: string;\n response: object;\n id?: string;\n};\n\nfunction getGoogleFunctionId(id?: string): string | undefined {\n return id != null && id !== '' ? id : undefined;\n}\n\nfunction createGoogleFunctionResponsePart({\n name,\n response,\n id,\n}: {\n name: string;\n response: object;\n id?: string;\n}): Part {\n const functionId = getGoogleFunctionId(id);\n const functionResponse: GoogleFunctionResponseWithId = {\n name,\n response,\n ...(functionId != null ? { id: functionId } : {}),\n };\n return { functionResponse };\n}\n\n/**\n * Executes a function immediately and returns its result.\n * Functional utility similar to an Immediately Invoked Function Expression (IIFE).\n * @param fn The function to execute.\n * @returns The result of invoking fn.\n */\nexport const iife = <T>(fn: () => T): T => fn();\n\nexport function getMessageAuthor(message: BaseMessage): string {\n const type = message._getType();\n if (ChatMessage.isInstance(message)) {\n return message.role;\n }\n if (type === 'tool') {\n return type;\n }\n return message.name ?? type;\n}\n\n/**\n * Maps a message type to a Google Generative AI chat author.\n * @param message The message to map.\n * @param model The model to use for mapping.\n * @returns The message type mapped to a Google Generative AI chat author.\n */\nexport function convertAuthorToRole(\n author: string\n): (typeof POSSIBLE_ROLES)[number] {\n switch (author) {\n /**\n * Note: Gemini currently is not supporting system messages\n * we will convert them to human messages and merge with following\n * */\n case 'supervisor':\n case 'ai':\n case 'model': // getMessageAuthor returns message.name. code ex.: return message.name ?? type;\n return 'model';\n case 'system':\n return 'system';\n case 'human':\n return 'user';\n case 'tool':\n case 'function':\n return 'function';\n default:\n throw new Error(`Unknown / unsupported author: ${author}`);\n }\n}\n\nfunction messageContentMedia(content: MessageContentComplex): Part {\n if ('mimeType' in content && 'data' in content) {\n return {\n inlineData: {\n mimeType: content.mimeType,\n data: content.data,\n },\n };\n }\n if ('mimeType' in content && 'fileUri' in content) {\n return {\n fileData: {\n mimeType: content.mimeType,\n fileUri: content.fileUri,\n },\n };\n }\n\n throw new Error('Invalid media content');\n}\n\nfunction isGoogleServerSideToolPart(\n content: MessageContentComplex\n): content is MessageContentComplex & GoogleServerSideToolPart {\n return (\n 'toolCall' in content ||\n 'toolResponse' in content ||\n content.type === 'toolCall' ||\n content.type === 'toolResponse'\n );\n}\n\nfunction convertGoogleServerSideToolPart(\n content: MessageContentComplex & GoogleServerSideToolPart\n): Part {\n const metadata: GoogleServerSideToolPartMetadata = {};\n if ('thought' in content && typeof content.thought === 'boolean') {\n metadata.thought = content.thought;\n }\n if (\n 'thoughtSignature' in content &&\n typeof content.thoughtSignature === 'string'\n ) {\n metadata.thoughtSignature = content.thoughtSignature;\n }\n if ('toolCall' in content && content.toolCall != null) {\n return { toolCall: content.toolCall, ...metadata } as unknown as Part;\n }\n if ('toolResponse' in content && content.toolResponse != null) {\n return {\n toolResponse: content.toolResponse,\n ...metadata,\n } as unknown as Part;\n }\n\n return content as Part;\n}\n\nfunction convertGoogleServerSideToolResponsePart(\n part: Part\n): GoogleServerSideToolPart | undefined {\n if (\n 'toolCall' in part &&\n typeof part.toolCall === 'object' &&\n part.toolCall != null\n ) {\n return { ...part, type: 'toolCall', toolCall: part.toolCall };\n }\n if (\n 'toolResponse' in part &&\n typeof part.toolResponse === 'object' &&\n part.toolResponse != null\n ) {\n return { ...part, type: 'toolResponse', toolResponse: part.toolResponse };\n }\n return undefined;\n}\n\nfunction inferToolNameFromPreviousMessages(\n message: ToolMessage | ToolMessageChunk,\n previousMessages: BaseMessage[]\n): string | undefined {\n return previousMessages\n .map((msg) => {\n if (isAIMessage(msg)) {\n return msg.tool_calls ?? [];\n }\n return [];\n })\n .flat()\n .find((toolCall) => {\n return toolCall.id === message.tool_call_id;\n })?.name;\n}\n\nfunction _getStandardContentBlockConverter(\n isMultimodalModel: boolean\n): StandardContentBlockConverter<{\n text: TextPart;\n image: FileDataPart | InlineDataPart;\n audio: FileDataPart | InlineDataPart;\n file: FileDataPart | InlineDataPart | TextPart;\n}> {\n const standardContentBlockConverter: StandardContentBlockConverter<{\n text: TextPart;\n image: FileDataPart | InlineDataPart;\n audio: FileDataPart | InlineDataPart;\n file: FileDataPart | InlineDataPart | TextPart;\n }> = {\n providerName: 'Google Gemini',\n\n fromStandardTextBlock(block) {\n return {\n text: block.text,\n };\n },\n\n fromStandardImageBlock(block): FileDataPart | InlineDataPart {\n if (!isMultimodalModel) {\n throw new Error('This model does not support images');\n }\n if (block.source_type === 'url') {\n const data = parseBase64DataUrl({ dataUrl: block.url });\n if (data) {\n return {\n inlineData: {\n mimeType: data.mime_type,\n data: data.data,\n },\n };\n } else {\n return {\n fileData: {\n mimeType: block.mime_type ?? '',\n fileUri: block.url,\n },\n };\n }\n }\n\n if (block.source_type === 'base64') {\n return {\n inlineData: {\n mimeType: block.mime_type ?? '',\n data: block.data,\n },\n };\n }\n\n throw new Error(`Unsupported source type: ${block.source_type}`);\n },\n\n fromStandardAudioBlock(block): FileDataPart | InlineDataPart {\n if (!isMultimodalModel) {\n throw new Error('This model does not support audio');\n }\n if (block.source_type === 'url') {\n const data = parseBase64DataUrl({ dataUrl: block.url });\n if (data) {\n return {\n inlineData: {\n mimeType: data.mime_type,\n data: data.data,\n },\n };\n } else {\n return {\n fileData: {\n mimeType: block.mime_type ?? '',\n fileUri: block.url,\n },\n };\n }\n }\n\n if (block.source_type === 'base64') {\n return {\n inlineData: {\n mimeType: block.mime_type ?? '',\n data: block.data,\n },\n };\n }\n\n throw new Error(`Unsupported source type: ${block.source_type}`);\n },\n\n fromStandardFileBlock(block): FileDataPart | InlineDataPart | TextPart {\n if (!isMultimodalModel) {\n throw new Error('This model does not support files');\n }\n if (block.source_type === 'text') {\n return {\n text: block.text,\n };\n }\n if (block.source_type === 'url') {\n const data = parseBase64DataUrl({ dataUrl: block.url });\n if (data) {\n return {\n inlineData: {\n mimeType: data.mime_type,\n data: data.data,\n },\n };\n } else {\n return {\n fileData: {\n mimeType: block.mime_type ?? '',\n fileUri: block.url,\n },\n };\n }\n }\n\n if (block.source_type === 'base64') {\n return {\n inlineData: {\n mimeType: block.mime_type ?? '',\n data: block.data,\n },\n };\n }\n throw new Error(`Unsupported source type: ${block.source_type}`);\n },\n };\n return standardContentBlockConverter;\n}\n\nfunction _convertLangChainContentToPart(\n content: MessageContentComplex,\n isMultimodalModel: boolean\n): Part | undefined {\n if (isDataContentBlock(content)) {\n return convertToProviderContentBlock(\n content,\n _getStandardContentBlockConverter(isMultimodalModel)\n );\n }\n\n if (isGoogleServerSideToolPart(content)) {\n return convertGoogleServerSideToolPart(content);\n }\n\n if (content.type === 'text') {\n return { text: content.text };\n } else if (content.type === 'executableCode') {\n return { executableCode: content.executableCode };\n } else if (content.type === 'codeExecutionResult') {\n return { codeExecutionResult: content.codeExecutionResult };\n } else if (content.type === 'image_url') {\n if (!isMultimodalModel) {\n throw new Error('This model does not support images');\n }\n let source: string;\n if (typeof content.image_url === 'string') {\n source = content.image_url;\n } else if (\n typeof content.image_url === 'object' &&\n 'url' in content.image_url\n ) {\n source = content.image_url.url;\n } else {\n throw new Error('Please provide image as base64 encoded data URL');\n }\n const [dm, data] = source.split(',');\n if (!dm.startsWith('data:')) {\n throw new Error('Please provide image as base64 encoded data URL');\n }\n\n const [mimeType, encoding] = dm.replace(/^data:/, '').split(';');\n if (encoding !== 'base64') {\n throw new Error('Please provide image as base64 encoded data URL');\n }\n\n return {\n inlineData: {\n data,\n mimeType,\n },\n };\n } else if (content.type === 'media') {\n return messageContentMedia(content);\n } else if (content.type === 'tool_use') {\n return {\n functionCall: {\n name: content.name,\n args: content.input,\n },\n };\n } else if (\n content.type?.includes('/') === true &&\n // Ensure it's a single slash.\n content.type.split('/').length === 2 &&\n 'data' in content &&\n typeof content.data === 'string'\n ) {\n return {\n inlineData: {\n mimeType: content.type,\n data: content.data,\n },\n };\n } else if ('functionCall' in content) {\n // No action needed here — function calls will be added later from message.tool_calls\n return undefined;\n } else {\n if ('type' in content) {\n throw new Error(`Unknown content type ${content.type}`);\n } else {\n throw new Error(`Unknown content ${JSON.stringify(content)}`);\n }\n }\n}\n\nexport function convertMessageContentToParts(\n message: BaseMessage,\n isMultimodalModel: boolean,\n previousMessages: BaseMessage[],\n model?: string\n): Part[] {\n if (isToolMessage(message)) {\n const messageName =\n message.name ??\n inferToolNameFromPreviousMessages(message, previousMessages);\n if (messageName === undefined) {\n throw new Error(\n `Google requires a tool name for each tool call response, and we could not infer a called tool name for ToolMessage \"${message.id}\" from your passed messages. Please populate a \"name\" field on that ToolMessage explicitly.`\n );\n }\n\n const result = Array.isArray(message.content)\n ? (message.content\n .map((c) => _convertLangChainContentToPart(c, isMultimodalModel))\n .filter((p) => p !== undefined) as Part[])\n : message.content;\n\n if (message.status === 'error') {\n return [\n createGoogleFunctionResponsePart({\n name: messageName,\n // The API expects an object with an `error` field if the function call fails.\n // `error` must be a valid object (not a string or array), so we wrap `message.content` here\n response: { error: { details: result } },\n id: message.tool_call_id,\n }),\n ];\n }\n\n return [\n createGoogleFunctionResponsePart({\n name: messageName,\n // again, can't have a string or array value for `response`, so we wrap it as an object here\n response: { result },\n id: message.tool_call_id,\n }),\n ];\n }\n\n let functionCalls: FunctionCallPart[] = [];\n const messageParts: Part[] = [];\n\n if (typeof message.content === 'string' && message.content) {\n messageParts.push({ text: message.content });\n }\n\n if (Array.isArray(message.content)) {\n messageParts.push(\n ...(message.content\n .map((c) => _convertLangChainContentToPart(c, isMultimodalModel))\n .filter((p) => p !== undefined) as Part[])\n );\n }\n\n const functionThoughtSignatures = (\n message.additional_kwargs as BaseMessage['additional_kwargs'] | undefined\n )?.[_FUNCTION_CALL_THOUGHT_SIGNATURES_MAP_KEY] as\n | Record<string, string>\n | undefined;\n\n if (isAIMessage(message) && (message.tool_calls?.length ?? 0) > 0) {\n functionCalls = (message.tool_calls ?? []).map((tc) => {\n const thoughtSignature = iife(() => {\n if (tc.id != null && tc.id !== '') {\n const signature = functionThoughtSignatures?.[tc.id];\n if (signature != null && signature !== '') {\n return signature;\n }\n }\n if (model?.includes('gemini-3') === true) {\n return DUMMY_SIGNATURE;\n }\n return '';\n });\n const functionId = getGoogleFunctionId(tc.id);\n const functionCall: GoogleFunctionCallWithId = {\n name: tc.name,\n args: tc.args,\n ...(functionId != null ? { id: functionId } : {}),\n };\n\n return {\n functionCall,\n ...(thoughtSignature ? { thoughtSignature } : {}),\n };\n });\n }\n\n return [...messageParts, ...functionCalls];\n}\n\nexport function convertBaseMessagesToContent(\n messages: BaseMessage[],\n isMultimodalModel: boolean,\n convertSystemMessageToHumanContent: boolean = false,\n\n model?: string\n): Content[] | undefined {\n return messages.reduce<{\n content: Content[] | undefined;\n mergeWithPreviousContent: boolean;\n }>(\n (acc, message, index) => {\n if (!isBaseMessage(message)) {\n throw new Error('Unsupported message input');\n }\n const author = getMessageAuthor(message);\n if (author === 'system' && index !== 0) {\n throw new Error('System message should be the first one');\n }\n const role = convertAuthorToRole(author);\n\n const prevContent = acc.content?.[acc.content.length];\n if (\n !acc.mergeWithPreviousContent &&\n prevContent &&\n prevContent.role === role\n ) {\n throw new Error(\n 'Google Generative AI requires alternate messages between authors'\n );\n }\n\n const parts = convertMessageContentToParts(\n message,\n isMultimodalModel,\n messages.slice(0, index),\n model\n );\n\n if (acc.mergeWithPreviousContent) {\n const prevContent = acc.content?.[acc.content.length - 1];\n if (!prevContent) {\n throw new Error(\n 'There was a problem parsing your system message. Please try a prompt without one.'\n );\n }\n prevContent.parts.push(...parts);\n\n return {\n mergeWithPreviousContent: false,\n content: acc.content,\n };\n }\n let actualRole = role;\n if (\n actualRole === 'function' ||\n (actualRole === 'system' && !convertSystemMessageToHumanContent)\n ) {\n // GenerativeAI API will throw an error if the role is not \"user\" or \"model.\"\n actualRole = 'user';\n }\n const content: Content = {\n role: actualRole,\n parts,\n };\n return {\n mergeWithPreviousContent:\n author === 'system' && !convertSystemMessageToHumanContent,\n content: [...(acc.content ?? []), content],\n };\n },\n { content: [], mergeWithPreviousContent: false }\n ).content;\n}\n\nexport function convertResponseContentToChatGenerationChunk(\n response: EnhancedGenerateContentResponse,\n extra: {\n usageMetadata?: UsageMetadata | undefined;\n index: number;\n }\n): ChatGenerationChunk | null {\n if (!response.candidates || response.candidates.length === 0) {\n return null;\n }\n const [candidate] = response.candidates as [\n Partial<GenerateContentCandidate> | undefined,\n ];\n const { content: candidateContent, ...generationInfo } = candidate ?? {};\n\n // Extract function calls directly from parts to preserve thoughtSignature\n const functionCalls =\n (candidateContent?.parts as Part[] | undefined)?.reduce(\n (acc, p) => {\n if ('functionCall' in p && p.functionCall) {\n acc.push({\n ...p,\n id:\n 'id' in p.functionCall && typeof p.functionCall.id === 'string'\n ? p.functionCall.id\n : uuidv4(),\n });\n }\n return acc;\n },\n [] as (\n | undefined\n | (FunctionCallPart & { id: string; thoughtSignature?: string })\n )[]\n ) ?? [];\n\n let content: MessageContent | undefined;\n // Checks if some parts do not have text. If false, it means that the content is a string.\n const reasoningParts: string[] = [];\n if (\n candidateContent != null &&\n Array.isArray(candidateContent.parts) &&\n candidateContent.parts.every((p) => 'text' in p)\n ) {\n // content = candidateContent.parts.map((p) => p.text).join('');\n const textParts: string[] = [];\n for (const part of candidateContent.parts) {\n if ('thought' in part && part.thought === true) {\n reasoningParts.push(part.text ?? '');\n continue;\n }\n textParts.push(part.text ?? '');\n }\n content = textParts.join('');\n } else if (candidateContent && Array.isArray(candidateContent.parts)) {\n content = toLangChainContent(\n candidateContent.parts\n .map((p) => {\n if ('text' in p && 'thought' in p && p.thought === true) {\n reasoningParts.push(p.text ?? '');\n return undefined;\n } else if ('text' in p) {\n return {\n type: 'text',\n text: p.text,\n };\n } else if ('executableCode' in p) {\n return {\n type: 'executableCode',\n executableCode: p.executableCode,\n };\n } else if ('codeExecutionResult' in p) {\n return {\n type: 'codeExecutionResult',\n codeExecutionResult: p.codeExecutionResult,\n };\n }\n const serverSideToolPart = convertGoogleServerSideToolResponsePart(p);\n if (serverSideToolPart !== undefined) {\n return serverSideToolPart;\n }\n return p;\n })\n .filter((p) => p !== undefined)\n );\n } else {\n // no content returned - likely due to abnormal stop reason, e.g. malformed function call\n content = [];\n }\n\n let text = '';\n if (typeof content === 'string' && content) {\n text = content;\n } else if (Array.isArray(content)) {\n const block = content.find((b) => 'text' in b) as\n | { text: string }\n | undefined;\n text = block?.text ?? '';\n }\n\n const toolCallChunks: ToolCallChunk[] = [];\n if (functionCalls.length > 0) {\n toolCallChunks.push(\n ...functionCalls.map((fc) => ({\n type: 'tool_call_chunk' as const,\n id: fc?.id,\n name: fc?.functionCall.name,\n args: JSON.stringify(fc?.functionCall.args),\n }))\n );\n }\n\n // Extract thought signatures from function calls for Gemini 3+\n const functionThoughtSignatures = functionCalls.reduce(\n (acc, fc) => {\n if (\n fc &&\n 'thoughtSignature' in fc &&\n typeof fc.thoughtSignature === 'string'\n ) {\n acc[fc.id] = fc.thoughtSignature;\n }\n return acc;\n },\n {} as Record<string, string>\n );\n\n const additional_kwargs: ChatGeneration['message']['additional_kwargs'] = {\n [_FUNCTION_CALL_THOUGHT_SIGNATURES_MAP_KEY]: functionThoughtSignatures,\n };\n\n if (reasoningParts.length > 0) {\n additional_kwargs.reasoning = reasoningParts.join('');\n }\n\n if (candidate?.groundingMetadata) {\n additional_kwargs.groundingMetadata = candidate.groundingMetadata;\n }\n\n const isFinalChunk =\n response.candidates[0]?.finishReason === 'STOP' ||\n response.candidates[0]?.finishReason === 'MAX_TOKENS' ||\n response.candidates[0]?.finishReason === 'SAFETY';\n\n // The GenAI API delivers function calls as complete objects (never partial\n // arg deltas), so every call on this chunk is sealed on arrival for eager\n // tool execution.\n const response_metadata: Record<string, unknown> | undefined =\n toolCallChunks.length > 0\n ? {\n [STREAMED_TOOL_CALL_ADAPTER_METADATA_KEY]:\n GOOGLE_STREAMED_TOOL_CALL_ADAPTER,\n [STREAMED_TOOL_CALL_SEAL_METADATA_KEY]: { kind: 'all' },\n }\n : undefined;\n\n return new ChatGenerationChunk({\n text,\n message: new AIMessageChunk({\n content: content,\n name: !candidateContent ? undefined : candidateContent.role,\n tool_call_chunks: toolCallChunks,\n // Each chunk can have unique \"generationInfo\", and merging strategy is unclear,\n // so leave blank for now.\n additional_kwargs,\n response_metadata,\n usage_metadata: isFinalChunk ? extra.usageMetadata : undefined,\n }),\n generationInfo,\n });\n}\n\n/**\n * Maps a Google GenerateContentResult to a LangChain ChatResult\n */\nexport function mapGenerateContentResultToChatResult(\n response: EnhancedGenerateContentResponse,\n extra?: {\n usageMetadata: UsageMetadata | undefined;\n }\n): ChatResult {\n if (!response.candidates || response.candidates.length === 0) {\n return {\n generations: [],\n llmOutput: {\n filters: response.promptFeedback,\n },\n };\n }\n const [candidate] = response.candidates as [\n Partial<GenerateContentCandidate> | undefined,\n ];\n const { content: candidateContent, ...generationInfo } = candidate ?? {};\n\n // Extract function calls directly from parts to preserve thoughtSignature\n const functionCalls =\n candidateContent?.parts.reduce(\n (acc, p) => {\n if ('functionCall' in p && p.functionCall) {\n acc.push({\n ...p,\n id:\n 'id' in p.functionCall && typeof p.functionCall.id === 'string'\n ? p.functionCall.id\n : uuidv4(),\n });\n }\n return acc;\n },\n [] as (FunctionCallPart & { id: string; thoughtSignature?: string })[]\n ) ?? [];\n\n let content: MessageContent | undefined;\n const reasoningParts: string[] = [];\n if (\n Array.isArray(candidateContent?.parts) &&\n candidateContent.parts.length === 1 &&\n (candidateContent.parts[0].text ?? '') !== '' &&\n !(\n 'thought' in candidateContent.parts[0] &&\n candidateContent.parts[0].thought === true\n )\n ) {\n content = candidateContent.parts[0].text;\n } else if (\n Array.isArray(candidateContent?.parts) &&\n candidateContent.parts.length > 0\n ) {\n content = toLangChainContent(\n candidateContent.parts\n .map((p) => {\n if ('text' in p && 'thought' in p && p.thought === true) {\n reasoningParts.push(p.text ?? '');\n return undefined;\n } else if ('text' in p) {\n return {\n type: 'text',\n text: p.text,\n };\n } else if ('executableCode' in p) {\n return {\n type: 'executableCode',\n executableCode: p.executableCode,\n };\n } else if ('codeExecutionResult' in p) {\n return {\n type: 'codeExecutionResult',\n codeExecutionResult: p.codeExecutionResult,\n };\n }\n const serverSideToolPart = convertGoogleServerSideToolResponsePart(p);\n if (serverSideToolPart !== undefined) {\n return serverSideToolPart;\n }\n return p;\n })\n .filter((p) => p !== undefined)\n );\n } else {\n content = [];\n }\n let text = '';\n if (typeof content === 'string') {\n text = content;\n } else if (Array.isArray(content) && content.length > 0) {\n const block = content.find((b) => 'text' in b) as\n | { text: string }\n | undefined;\n text = block?.text ?? text;\n }\n\n const additional_kwargs: ChatGeneration['message']['additional_kwargs'] = {\n ...generationInfo,\n };\n if (reasoningParts.length > 0) {\n additional_kwargs.reasoning = reasoningParts.join('');\n }\n\n // Extract thought signatures from function calls for Gemini 3+\n const functionThoughtSignatures = functionCalls.reduce(\n (acc, fc) => {\n if ('thoughtSignature' in fc && typeof fc.thoughtSignature === 'string') {\n acc[fc.id] = fc.thoughtSignature;\n }\n return acc;\n },\n {} as Record<string, string>\n );\n\n const tool_calls = functionCalls.map((fc) => ({\n type: 'tool_call' as const,\n id: fc.id,\n name: fc.functionCall.name,\n args: fc.functionCall.args,\n }));\n\n // Store thought signatures map for later retrieval\n additional_kwargs[_FUNCTION_CALL_THOUGHT_SIGNATURES_MAP_KEY] =\n functionThoughtSignatures;\n\n const generation: ChatGeneration = {\n text,\n message: new AIMessage({\n content,\n tool_calls,\n additional_kwargs,\n usage_metadata: extra?.usageMetadata,\n }),\n generationInfo,\n };\n return {\n generations: [generation],\n llmOutput: {\n tokenUsage: {\n promptTokens: extra?.usageMetadata?.input_tokens,\n completionTokens: extra?.usageMetadata?.output_tokens,\n totalTokens: extra?.usageMetadata?.total_tokens,\n },\n },\n };\n}\n\nexport function convertToGenerativeAITools(\n tools: GoogleGenerativeAIToolType[]\n): GoogleGenerativeAIFunctionDeclarationsTool[] {\n if (\n tools.every(\n (tool) =>\n 'functionDeclarations' in tool &&\n Array.isArray(tool.functionDeclarations)\n )\n ) {\n return tools as GoogleGenerativeAIFunctionDeclarationsTool[];\n }\n return [\n {\n functionDeclarations: tools.map(\n (tool): GenerativeAIFunctionDeclaration => {\n if (isLangChainTool(tool)) {\n const jsonSchema = schemaToGenerativeAIParameters(tool.schema);\n if (\n jsonSchema.type === 'object' &&\n 'properties' in jsonSchema &&\n Object.keys(jsonSchema.properties).length === 0\n ) {\n return {\n name: tool.name,\n description: tool.description,\n };\n }\n return {\n name: tool.name,\n description: tool.description,\n parameters: jsonSchema,\n };\n }\n if (isOpenAITool(tool)) {\n return {\n name: tool.function.name,\n description:\n tool.function.description ?? 'A function available to call.',\n parameters: jsonSchemaToGeminiParameters(\n tool.function.parameters\n ),\n };\n }\n return tool as unknown as GenerativeAIFunctionDeclaration;\n }\n ),\n },\n ];\n}\n"],"mappings":";;;;;;;;;AAiDA,MAAa,4CACX;AAEF,MAAM,kBACJ;AAuBF,SAAS,oBAAoB,IAAiC;CAC5D,OAAO,MAAM,QAAQ,OAAO,KAAK,KAAK,KAAA;AACxC;AAEA,SAAS,iCAAiC,EACxC,MACA,UACA,MAKO;CACP,MAAM,aAAa,oBAAoB,EAAE;CAMzC,OAAO,EAAE,kBAAA;EAJP;EACA;EACA,GAAI,cAAc,OAAO,EAAE,IAAI,WAAW,IAAI,CAAC;CAEzB,EAAE;AAC5B;;;;;;;AAQA,MAAa,QAAW,OAAmB,GAAG;AAE9C,SAAgB,iBAAiB,SAA8B;CAC7D,MAAM,OAAO,QAAQ,SAAS;CAC9B,IAAIA,yBAAAA,YAAY,WAAW,OAAO,GAChC,OAAO,QAAQ;CAEjB,IAAI,SAAS,QACX,OAAO;CAET,OAAO,QAAQ,QAAQ;AACzB;;;;;;;AAQA,SAA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OAAO;CACT,CAAC,CAAC,CACD,QAAQ,MAAM,MAAM,KAAA,CAAS,CAClC;MAEA,UAAU,CAAC;CAEb,IAAI,OAAO;CACX,IAAI,OAAO,YAAY,UACrB,OAAO;MACF,IAAI,MAAM,QAAQ,OAAO,KAAK,QAAQ,SAAS,GAIpD,OAHc,QAAQ,MAAM,MAAM,UAAU,CAGjC,CAAC,EAAE,QAAQ;CAGxB,MAAM,oBAAoE,EACxE,GAAG,eACL;CACA,IAAI,eAAe,SAAS,GAC1B,kBAAkB,YAAY,eAAe,KAAK,EAAE;CAItD,MAAM,4BAA4B,cAAc,QAC7C,KAAK,OAAO;EACX,IAAI,sBAAsB,MAAM,OAAO,GAAG,qBAAqB,UAC7D,IAAI,GAAG,MAAM,GAAG;EAElB,OAAO;CACT,GACA,CAAC,CACH;CAEA,MAAM,aAAa,cAAc,KAAK,QAAQ;EAC5C,MAAM;EACN,IAAI,GAAG;EACP,MAAM,GAAG,aAAa;EACtB,MAAM,GAAG,aAAa;CACxB,EAAE;CAGF,kBAAkB,6CAChB;CAYF,OAAO;EACL,aAAa,CAAC;GAVd;GACA,SAAS,IAAIM,yBAAAA,UAAU;IACrB;IACA;IACA;IACA,gBAAgB,OAAO;GACzB,CAAC;GACD;EAGuB,CAAC;EACxB,WAAW,EACT,YAAY;GACV,cAAc,OAAO,eAAe;GACpC,kBAAkB,OAAO,eAAe;GACxC,aAAa,OAAO,eAAe;EACrC,EACF;CACF;AACF"}
|
|
1
|
+
{"version":3,"file":"common.cjs","names":["ChatMessage","toLangChainContent","STREAMED_TOOL_CALL_ADAPTER_METADATA_KEY","GOOGLE_STREAMED_TOOL_CALL_ADAPTER","STREAMED_TOOL_CALL_SEAL_METADATA_KEY","ChatGenerationChunk","AIMessageChunk","AIMessage"],"sources":["../../../../../src/llm/google/utils/common.ts"],"sourcesContent":["import { v4 as uuidv4 } from 'uuid';\nimport { ChatGenerationChunk } from '@langchain/core/outputs';\nimport { ToolCallChunk } from '@langchain/core/messages/tool';\nimport { isOpenAITool } from '@langchain/core/language_models/base';\nimport { isLangChainTool } from '@langchain/core/utils/function_calling';\nimport {\n AIMessage,\n AIMessageChunk,\n BaseMessage,\n ChatMessage,\n ToolMessage,\n ToolMessageChunk,\n MessageContent,\n MessageContentComplex,\n UsageMetadata,\n isAIMessage,\n isBaseMessage,\n isToolMessage,\n StandardContentBlockConverter,\n parseBase64DataUrl,\n convertToProviderContentBlock,\n isDataContentBlock,\n} from '@langchain/core/messages';\nimport {\n POSSIBLE_ROLES,\n type Part,\n type Content,\n type TextPart,\n type FileDataPart,\n type InlineDataPart,\n type FunctionCallPart,\n type GenerateContentCandidate,\n type EnhancedGenerateContentResponse,\n type FunctionDeclaration as GenerativeAIFunctionDeclaration,\n type FunctionDeclarationsTool as GoogleGenerativeAIFunctionDeclarationsTool,\n} from '@google/generative-ai';\nimport type { ChatGeneration, ChatResult } from '@langchain/core/outputs';\nimport {\n STREAMED_TOOL_CALL_SEAL_METADATA_KEY,\n STREAMED_TOOL_CALL_ADAPTER_METADATA_KEY,\n GOOGLE_STREAMED_TOOL_CALL_ADAPTER,\n} from '@/tools/streamedToolCallSeals';\nimport {\n jsonSchemaToGeminiParameters,\n schemaToGenerativeAIParameters,\n} from './zod_to_genai_parameters';\nimport { toLangChainContent } from '@/messages/langchain';\nimport { GoogleGenerativeAIToolType } from '../types';\n\nexport const _FUNCTION_CALL_THOUGHT_SIGNATURES_MAP_KEY =\n '__gemini_function_call_thought_signatures__';\n\nconst DUMMY_SIGNATURE =\n 'ErYCCrMCAdHtim9kOoOkrPiCNVsmlpMIKd7ZMxgiFbVQOkgp7nlLcDMzVsZwIzvuT7nQROivoXA72ccC2lSDvR0Gh7dkWaGuj7ctv6t7ZceHnecx0QYa+ix8tYpRfjhyWozQ49lWiws6+YGjCt10KRTyWsZ2h6O7iHTYJwKIRwGUHRKy/qK/6kFxJm5ML00gLq4D8s5Z6DBpp2ZlR+uF4G8jJgeWQgyHWVdx2wGYElaceVAc66tZdPQRdOHpWtgYSI1YdaXgVI8KHY3/EfNc2YqqMIulvkDBAnuMhkAjV9xmBa54Tq+ih3Im4+r3DzqhGqYdsSkhS0kZMwte4Hjs65dZzCw9lANxIqYi1DJ639WNPYihp/DCJCos7o+/EeSPJaio5sgWDyUnMGkY1atsJZ+m7pj7DD5tvQ==';\n\ntype GoogleServerSideToolPart = Part & {\n type?: 'toolCall' | 'toolResponse';\n toolCall?: object;\n toolResponse?: object;\n};\n\ntype GoogleServerSideToolPartMetadata = {\n thought?: boolean;\n thoughtSignature?: string;\n};\n\ntype GoogleFunctionCallWithId = FunctionCallPart['functionCall'] & {\n id?: string;\n};\n\ntype GoogleFunctionResponseWithId = {\n name: string;\n response: object;\n id?: string;\n};\n\nfunction getGoogleFunctionId(id?: string): string | undefined {\n return id != null && id !== '' ? id : undefined;\n}\n\nfunction createGoogleFunctionResponsePart({\n name,\n response,\n id,\n}: {\n name: string;\n response: object;\n id?: string;\n}): Part {\n const functionId = getGoogleFunctionId(id);\n const functionResponse: GoogleFunctionResponseWithId = {\n name,\n response,\n ...(functionId != null ? { id: functionId } : {}),\n };\n return { functionResponse };\n}\n\n/**\n * Executes a function immediately and returns its result.\n * Functional utility similar to an Immediately Invoked Function Expression (IIFE).\n * @param fn The function to execute.\n * @returns The result of invoking fn.\n */\nexport const iife = <T>(fn: () => T): T => fn();\n\nexport function getMessageAuthor(message: BaseMessage): string {\n const type = message._getType();\n if (ChatMessage.isInstance(message)) {\n return message.role;\n }\n if (type === 'tool') {\n return type;\n }\n return message.name ?? type;\n}\n\n/**\n * Maps a message type to a Google Generative AI chat author.\n * @param message The message to map.\n * @param model The model to use for mapping.\n * @returns The message type mapped to a Google Generative AI chat author.\n */\nexport function convertAuthorToRole(\n author: string\n): (typeof POSSIBLE_ROLES)[number] {\n switch (author) {\n /**\n * Note: Gemini currently is not supporting system messages\n * we will convert them to human messages and merge with following\n * */\n case 'supervisor':\n case 'ai':\n case 'model': // getMessageAuthor returns message.name. code ex.: return message.name ?? type;\n return 'model';\n case 'system':\n return 'system';\n case 'human':\n return 'user';\n case 'tool':\n case 'function':\n return 'function';\n default:\n throw new Error(`Unknown / unsupported author: ${author}`);\n }\n}\n\nfunction messageContentMedia(content: MessageContentComplex): Part {\n if ('mimeType' in content && 'data' in content) {\n return {\n inlineData: {\n mimeType: content.mimeType,\n data: content.data,\n },\n };\n }\n if ('mimeType' in content && 'fileUri' in content) {\n return {\n fileData: {\n mimeType: content.mimeType,\n fileUri: content.fileUri,\n },\n };\n }\n\n throw new Error('Invalid media content');\n}\n\nfunction isGoogleServerSideToolPart(\n content: MessageContentComplex\n): content is MessageContentComplex & GoogleServerSideToolPart {\n return (\n 'toolCall' in content ||\n 'toolResponse' in content ||\n content.type === 'toolCall' ||\n content.type === 'toolResponse'\n );\n}\n\nfunction convertGoogleServerSideToolPart(\n content: MessageContentComplex & GoogleServerSideToolPart\n): Part {\n const metadata: GoogleServerSideToolPartMetadata = {};\n if ('thought' in content && typeof content.thought === 'boolean') {\n metadata.thought = content.thought;\n }\n if (\n 'thoughtSignature' in content &&\n typeof content.thoughtSignature === 'string'\n ) {\n metadata.thoughtSignature = content.thoughtSignature;\n }\n if ('toolCall' in content && content.toolCall != null) {\n return { toolCall: content.toolCall, ...metadata } as unknown as Part;\n }\n if ('toolResponse' in content && content.toolResponse != null) {\n return {\n toolResponse: content.toolResponse,\n ...metadata,\n } as unknown as Part;\n }\n\n return content as Part;\n}\n\nfunction convertGoogleServerSideToolResponsePart(\n part: Part\n): GoogleServerSideToolPart | undefined {\n if (\n 'toolCall' in part &&\n typeof part.toolCall === 'object' &&\n part.toolCall != null\n ) {\n return { ...part, type: 'toolCall', toolCall: part.toolCall };\n }\n if (\n 'toolResponse' in part &&\n typeof part.toolResponse === 'object' &&\n part.toolResponse != null\n ) {\n return { ...part, type: 'toolResponse', toolResponse: part.toolResponse };\n }\n return undefined;\n}\n\nfunction inferToolNameFromPreviousMessages(\n message: ToolMessage | ToolMessageChunk,\n previousMessages: BaseMessage[]\n): string | undefined {\n return previousMessages\n .map((msg) => {\n if (isAIMessage(msg)) {\n return msg.tool_calls ?? [];\n }\n return [];\n })\n .flat()\n .find((toolCall) => {\n return toolCall.id === message.tool_call_id;\n })?.name;\n}\n\nfunction _getStandardContentBlockConverter(\n isMultimodalModel: boolean\n): StandardContentBlockConverter<{\n text: TextPart;\n image: FileDataPart | InlineDataPart;\n audio: FileDataPart | InlineDataPart;\n file: FileDataPart | InlineDataPart | TextPart;\n}> {\n const standardContentBlockConverter: StandardContentBlockConverter<{\n text: TextPart;\n image: FileDataPart | InlineDataPart;\n audio: FileDataPart | InlineDataPart;\n file: FileDataPart | InlineDataPart | TextPart;\n }> = {\n providerName: 'Google Gemini',\n\n fromStandardTextBlock(block) {\n return {\n text: block.text,\n };\n },\n\n fromStandardImageBlock(block): FileDataPart | InlineDataPart {\n if (!isMultimodalModel) {\n throw new Error('This model does not support images');\n }\n if (block.source_type === 'url') {\n const data = parseBase64DataUrl({ dataUrl: block.url });\n if (data) {\n return {\n inlineData: {\n mimeType: data.mime_type,\n data: data.data,\n },\n };\n } else {\n return {\n fileData: {\n mimeType: block.mime_type ?? '',\n fileUri: block.url,\n },\n };\n }\n }\n\n if (block.source_type === 'base64') {\n return {\n inlineData: {\n mimeType: block.mime_type ?? '',\n data: block.data,\n },\n };\n }\n\n throw new Error(`Unsupported source type: ${block.source_type}`);\n },\n\n fromStandardAudioBlock(block): FileDataPart | InlineDataPart {\n if (!isMultimodalModel) {\n throw new Error('This model does not support audio');\n }\n if (block.source_type === 'url') {\n const data = parseBase64DataUrl({ dataUrl: block.url });\n if (data) {\n return {\n inlineData: {\n mimeType: data.mime_type,\n data: data.data,\n },\n };\n } else {\n return {\n fileData: {\n mimeType: block.mime_type ?? '',\n fileUri: block.url,\n },\n };\n }\n }\n\n if (block.source_type === 'base64') {\n return {\n inlineData: {\n mimeType: block.mime_type ?? '',\n data: block.data,\n },\n };\n }\n\n throw new Error(`Unsupported source type: ${block.source_type}`);\n },\n\n fromStandardFileBlock(block): FileDataPart | InlineDataPart | TextPart {\n if (!isMultimodalModel) {\n throw new Error('This model does not support files');\n }\n if (block.source_type === 'text') {\n return {\n text: block.text,\n };\n }\n if (block.source_type === 'url') {\n const data = parseBase64DataUrl({ dataUrl: block.url });\n if (data) {\n return {\n inlineData: {\n mimeType: data.mime_type,\n data: data.data,\n },\n };\n } else {\n return {\n fileData: {\n mimeType: block.mime_type ?? '',\n fileUri: block.url,\n },\n };\n }\n }\n\n if (block.source_type === 'base64') {\n return {\n inlineData: {\n mimeType: block.mime_type ?? '',\n data: block.data,\n },\n };\n }\n throw new Error(`Unsupported source type: ${block.source_type}`);\n },\n };\n return standardContentBlockConverter;\n}\n\nfunction _convertLangChainContentToPart(\n content: MessageContentComplex,\n isMultimodalModel: boolean\n): Part | undefined {\n if (isDataContentBlock(content)) {\n return convertToProviderContentBlock(\n content,\n _getStandardContentBlockConverter(isMultimodalModel)\n );\n }\n\n if (isGoogleServerSideToolPart(content)) {\n return convertGoogleServerSideToolPart(content);\n }\n\n if (content.type === 'text') {\n return { text: content.text };\n } else if (content.type === 'executableCode') {\n return { executableCode: content.executableCode };\n } else if (content.type === 'codeExecutionResult') {\n return { codeExecutionResult: content.codeExecutionResult };\n } else if (content.type === 'image_url') {\n if (!isMultimodalModel) {\n throw new Error('This model does not support images');\n }\n let source: string;\n if (typeof content.image_url === 'string') {\n source = content.image_url;\n } else if (\n typeof content.image_url === 'object' &&\n 'url' in content.image_url\n ) {\n source = content.image_url.url;\n } else {\n throw new Error('Please provide image as base64 encoded data URL');\n }\n const [dm, data] = source.split(',');\n if (!dm.startsWith('data:')) {\n throw new Error('Please provide image as base64 encoded data URL');\n }\n\n const [mimeType, encoding] = dm.replace(/^data:/, '').split(';');\n if (encoding !== 'base64') {\n throw new Error('Please provide image as base64 encoded data URL');\n }\n\n return {\n inlineData: {\n data,\n mimeType,\n },\n };\n } else if (content.type === 'media') {\n return messageContentMedia(content);\n } else if (content.type === 'tool_use') {\n return {\n functionCall: {\n name: content.name,\n args: content.input,\n },\n };\n } else if (\n content.type?.includes('/') === true &&\n // Ensure it's a single slash.\n content.type.split('/').length === 2 &&\n 'data' in content &&\n typeof content.data === 'string'\n ) {\n return {\n inlineData: {\n mimeType: content.type,\n data: content.data,\n },\n };\n } else if ('functionCall' in content) {\n // No action needed here — function calls will be added later from message.tool_calls\n return undefined;\n } else {\n if ('type' in content) {\n throw new Error(`Unknown content type ${content.type}`);\n } else {\n throw new Error(`Unknown content ${JSON.stringify(content)}`);\n }\n }\n}\n\nexport function convertMessageContentToParts(\n message: BaseMessage,\n isMultimodalModel: boolean,\n previousMessages: BaseMessage[],\n model?: string\n): Part[] {\n if (isToolMessage(message)) {\n const messageName =\n message.name ??\n inferToolNameFromPreviousMessages(message, previousMessages);\n if (messageName === undefined) {\n throw new Error(\n `Google requires a tool name for each tool call response, and we could not infer a called tool name for ToolMessage \"${message.id}\" from your passed messages. Please populate a \"name\" field on that ToolMessage explicitly.`\n );\n }\n\n const result = Array.isArray(message.content)\n ? (message.content\n .map((c) => _convertLangChainContentToPart(c, isMultimodalModel))\n .filter((p) => p !== undefined) as Part[])\n : message.content;\n\n if (message.status === 'error') {\n return [\n createGoogleFunctionResponsePart({\n name: messageName,\n // The API expects an object with an `error` field if the function call fails.\n // `error` must be a valid object (not a string or array), so we wrap `message.content` here\n response: { error: { details: result } },\n id: message.tool_call_id,\n }),\n ];\n }\n\n return [\n createGoogleFunctionResponsePart({\n name: messageName,\n // again, can't have a string or array value for `response`, so we wrap it as an object here\n response: { result },\n id: message.tool_call_id,\n }),\n ];\n }\n\n let functionCalls: FunctionCallPart[] = [];\n const messageParts: Part[] = [];\n\n if (typeof message.content === 'string' && message.content) {\n messageParts.push({ text: message.content });\n }\n\n if (Array.isArray(message.content)) {\n messageParts.push(\n ...(message.content\n .map((c) => _convertLangChainContentToPart(c, isMultimodalModel))\n .filter((p) => p !== undefined) as Part[])\n );\n }\n\n const functionThoughtSignatures = (\n message.additional_kwargs as BaseMessage['additional_kwargs'] | undefined\n )?.[_FUNCTION_CALL_THOUGHT_SIGNATURES_MAP_KEY] as\n | Record<string, string>\n | undefined;\n\n if (isAIMessage(message) && (message.tool_calls?.length ?? 0) > 0) {\n functionCalls = (message.tool_calls ?? []).map((tc) => {\n const thoughtSignature = iife(() => {\n if (tc.id != null && tc.id !== '') {\n const signature = functionThoughtSignatures?.[tc.id];\n if (signature != null && signature !== '') {\n return signature;\n }\n }\n if (model?.includes('gemini-3') === true) {\n return DUMMY_SIGNATURE;\n }\n return '';\n });\n const functionId = getGoogleFunctionId(tc.id);\n const functionCall: GoogleFunctionCallWithId = {\n name: tc.name,\n args: tc.args,\n ...(functionId != null ? { id: functionId } : {}),\n };\n\n return {\n functionCall,\n ...(thoughtSignature ? { thoughtSignature } : {}),\n };\n });\n }\n\n return [...messageParts, ...functionCalls];\n}\n\nexport function convertBaseMessagesToContent(\n messages: BaseMessage[],\n isMultimodalModel: boolean,\n convertSystemMessageToHumanContent: boolean = false,\n\n model?: string\n): Content[] | undefined {\n return messages.reduce<{\n content: Content[] | undefined;\n mergeWithPreviousContent: boolean;\n }>(\n (acc, message, index) => {\n if (!isBaseMessage(message)) {\n throw new Error('Unsupported message input');\n }\n const author = getMessageAuthor(message);\n if (author === 'system' && index !== 0) {\n throw new Error('System message should be the first one');\n }\n const role = convertAuthorToRole(author);\n\n const prevContent = acc.content?.[acc.content.length];\n if (\n !acc.mergeWithPreviousContent &&\n prevContent &&\n prevContent.role === role\n ) {\n throw new Error(\n 'Google Generative AI requires alternate messages between authors'\n );\n }\n\n const parts = convertMessageContentToParts(\n message,\n isMultimodalModel,\n messages.slice(0, index),\n model\n );\n\n if (acc.mergeWithPreviousContent) {\n const prevContent = acc.content?.[acc.content.length - 1];\n if (!prevContent) {\n throw new Error(\n 'There was a problem parsing your system message. Please try a prompt without one.'\n );\n }\n prevContent.parts.push(...parts);\n\n return {\n mergeWithPreviousContent: false,\n content: acc.content,\n };\n }\n let actualRole = role;\n if (\n actualRole === 'function' ||\n (actualRole === 'system' && !convertSystemMessageToHumanContent)\n ) {\n // GenerativeAI API will throw an error if the role is not \"user\" or \"model.\"\n actualRole = 'user';\n }\n const content: Content = {\n role: actualRole,\n parts,\n };\n return {\n mergeWithPreviousContent:\n author === 'system' && !convertSystemMessageToHumanContent,\n content: [...(acc.content ?? []), content],\n };\n },\n { content: [], mergeWithPreviousContent: false }\n ).content;\n}\n\n/**\n * Gemini models that reject a request whose `contents` end with a `model`-role\n * turn (a \"prefill\"). Google enforces this on newer generations (Gemini 3.6\n * Flash, Gemini 3.5 Flash-Lite) while older/sibling models still accept a\n * trailing model turn, so the rule is model-scoped rather than version-wide.\n * Extend this list as Google applies the restriction to further models.\n * @see https://ai.google.dev/gemini-api/docs/latest-model#api-changes-and-parameter-updates\n */\nconst NO_PREFILL_GEMINI_MODELS = [\n 'gemini-3.6-flash',\n 'gemini-3.5-flash-lite',\n] as const;\n\nexport function rejectsModelTurnPrefill(model?: string): boolean {\n if (model == null || model === '') {\n return false;\n }\n const modelId = model.toLowerCase().split('/').pop() ?? '';\n return NO_PREFILL_GEMINI_MODELS.some(\n (id) => modelId === id || modelId.startsWith(`${id}-`)\n );\n}\n\n/**\n * Drops trailing `model`-role turns for models that reject prefill (see\n * {@link rejectsModelTurnPrefill}). Such a turn is only produced by prefill\n * flows (e.g. editing an assistant reply and resubmitting); these models return\n * HTTP 400 for it, so we drop it and let the model generate fresh from the\n * preceding user turn. No-op for every other model, preserving working prefill.\n */\nexport function dropUnsupportedModelTurnPrefill(\n contents: Content[] | undefined,\n model?: string\n): Content[] | undefined {\n if (contents == null || contents.length === 0 || !rejectsModelTurnPrefill(model)) {\n return contents;\n }\n let end = contents.length;\n while (end > 1 && contents[end - 1]?.role === 'model') {\n end -= 1;\n }\n return end === contents.length ? contents : contents.slice(0, end);\n}\n\nexport function convertResponseContentToChatGenerationChunk(\n response: EnhancedGenerateContentResponse,\n extra: {\n usageMetadata?: UsageMetadata | undefined;\n index: number;\n }\n): ChatGenerationChunk | null {\n if (!response.candidates || response.candidates.length === 0) {\n return null;\n }\n const [candidate] = response.candidates as [\n Partial<GenerateContentCandidate> | undefined,\n ];\n const { content: candidateContent, ...generationInfo } = candidate ?? {};\n\n // Extract function calls directly from parts to preserve thoughtSignature\n const functionCalls =\n (candidateContent?.parts as Part[] | undefined)?.reduce(\n (acc, p) => {\n if ('functionCall' in p && p.functionCall) {\n acc.push({\n ...p,\n id:\n 'id' in p.functionCall && typeof p.functionCall.id === 'string'\n ? p.functionCall.id\n : uuidv4(),\n });\n }\n return acc;\n },\n [] as (\n | undefined\n | (FunctionCallPart & { id: string; thoughtSignature?: string })\n )[]\n ) ?? [];\n\n let content: MessageContent | undefined;\n // Checks if some parts do not have text. If false, it means that the content is a string.\n const reasoningParts: string[] = [];\n if (\n candidateContent != null &&\n Array.isArray(candidateContent.parts) &&\n candidateContent.parts.every((p) => 'text' in p)\n ) {\n // content = candidateContent.parts.map((p) => p.text).join('');\n const textParts: string[] = [];\n for (const part of candidateContent.parts) {\n if ('thought' in part && part.thought === true) {\n reasoningParts.push(part.text ?? '');\n continue;\n }\n textParts.push(part.text ?? '');\n }\n content = textParts.join('');\n } else if (candidateContent && Array.isArray(candidateContent.parts)) {\n content = toLangChainContent(\n candidateContent.parts\n .map((p) => {\n if ('text' in p && 'thought' in p && p.thought === true) {\n reasoningParts.push(p.text ?? '');\n return undefined;\n } else if ('text' in p) {\n return {\n type: 'text',\n text: p.text,\n };\n } else if ('executableCode' in p) {\n return {\n type: 'executableCode',\n executableCode: p.executableCode,\n };\n } else if ('codeExecutionResult' in p) {\n return {\n type: 'codeExecutionResult',\n codeExecutionResult: p.codeExecutionResult,\n };\n }\n const serverSideToolPart = convertGoogleServerSideToolResponsePart(p);\n if (serverSideToolPart !== undefined) {\n return serverSideToolPart;\n }\n return p;\n })\n .filter((p) => p !== undefined)\n );\n } else {\n // no content returned - likely due to abnormal stop reason, e.g. malformed function call\n content = [];\n }\n\n let text = '';\n if (typeof content === 'string' && content) {\n text = content;\n } else if (Array.isArray(content)) {\n const block = content.find((b) => 'text' in b) as\n | { text: string }\n | undefined;\n text = block?.text ?? '';\n }\n\n const toolCallChunks: ToolCallChunk[] = [];\n if (functionCalls.length > 0) {\n toolCallChunks.push(\n ...functionCalls.map((fc) => ({\n type: 'tool_call_chunk' as const,\n id: fc?.id,\n name: fc?.functionCall.name,\n args: JSON.stringify(fc?.functionCall.args),\n }))\n );\n }\n\n // Extract thought signatures from function calls for Gemini 3+\n const functionThoughtSignatures = functionCalls.reduce(\n (acc, fc) => {\n if (\n fc &&\n 'thoughtSignature' in fc &&\n typeof fc.thoughtSignature === 'string'\n ) {\n acc[fc.id] = fc.thoughtSignature;\n }\n return acc;\n },\n {} as Record<string, string>\n );\n\n const additional_kwargs: ChatGeneration['message']['additional_kwargs'] = {\n [_FUNCTION_CALL_THOUGHT_SIGNATURES_MAP_KEY]: functionThoughtSignatures,\n };\n\n if (reasoningParts.length > 0) {\n additional_kwargs.reasoning = reasoningParts.join('');\n }\n\n if (candidate?.groundingMetadata) {\n additional_kwargs.groundingMetadata = candidate.groundingMetadata;\n }\n\n const isFinalChunk =\n response.candidates[0]?.finishReason === 'STOP' ||\n response.candidates[0]?.finishReason === 'MAX_TOKENS' ||\n response.candidates[0]?.finishReason === 'SAFETY';\n\n // The GenAI API delivers function calls as complete objects (never partial\n // arg deltas), so every call on this chunk is sealed on arrival for eager\n // tool execution.\n const response_metadata: Record<string, unknown> | undefined =\n toolCallChunks.length > 0\n ? {\n [STREAMED_TOOL_CALL_ADAPTER_METADATA_KEY]:\n GOOGLE_STREAMED_TOOL_CALL_ADAPTER,\n [STREAMED_TOOL_CALL_SEAL_METADATA_KEY]: { kind: 'all' },\n }\n : undefined;\n\n return new ChatGenerationChunk({\n text,\n message: new AIMessageChunk({\n content: content,\n name: !candidateContent ? undefined : candidateContent.role,\n tool_call_chunks: toolCallChunks,\n // Each chunk can have unique \"generationInfo\", and merging strategy is unclear,\n // so leave blank for now.\n additional_kwargs,\n response_metadata,\n usage_metadata: isFinalChunk ? extra.usageMetadata : undefined,\n }),\n generationInfo,\n });\n}\n\n/**\n * Maps a Google GenerateContentResult to a LangChain ChatResult\n */\nexport function mapGenerateContentResultToChatResult(\n response: EnhancedGenerateContentResponse,\n extra?: {\n usageMetadata: UsageMetadata | undefined;\n }\n): ChatResult {\n if (!response.candidates || response.candidates.length === 0) {\n return {\n generations: [],\n llmOutput: {\n filters: response.promptFeedback,\n },\n };\n }\n const [candidate] = response.candidates as [\n Partial<GenerateContentCandidate> | undefined,\n ];\n const { content: candidateContent, ...generationInfo } = candidate ?? {};\n\n // Extract function calls directly from parts to preserve thoughtSignature\n const functionCalls =\n candidateContent?.parts.reduce(\n (acc, p) => {\n if ('functionCall' in p && p.functionCall) {\n acc.push({\n ...p,\n id:\n 'id' in p.functionCall && typeof p.functionCall.id === 'string'\n ? p.functionCall.id\n : uuidv4(),\n });\n }\n return acc;\n },\n [] as (FunctionCallPart & { id: string; thoughtSignature?: string })[]\n ) ?? [];\n\n let content: MessageContent | undefined;\n const reasoningParts: string[] = [];\n if (\n Array.isArray(candidateContent?.parts) &&\n candidateContent.parts.length === 1 &&\n (candidateContent.parts[0].text ?? '') !== '' &&\n !(\n 'thought' in candidateContent.parts[0] &&\n candidateContent.parts[0].thought === true\n )\n ) {\n content = candidateContent.parts[0].text;\n } else if (\n Array.isArray(candidateContent?.parts) &&\n candidateContent.parts.length > 0\n ) {\n content = toLangChainContent(\n candidateContent.parts\n .map((p) => {\n if ('text' in p && 'thought' in p && p.thought === true) {\n reasoningParts.push(p.text ?? '');\n return undefined;\n } else if ('text' in p) {\n return {\n type: 'text',\n text: p.text,\n };\n } else if ('executableCode' in p) {\n return {\n type: 'executableCode',\n executableCode: p.executableCode,\n };\n } else if ('codeExecutionResult' in p) {\n return {\n type: 'codeExecutionResult',\n codeExecutionResult: p.codeExecutionResult,\n };\n }\n const serverSideToolPart = convertGoogleServerSideToolResponsePart(p);\n if (serverSideToolPart !== undefined) {\n return serverSideToolPart;\n }\n return p;\n })\n .filter((p) => p !== undefined)\n );\n } else {\n content = [];\n }\n let text = '';\n if (typeof content === 'string') {\n text = content;\n } else if (Array.isArray(content) && content.length > 0) {\n const block = content.find((b) => 'text' in b) as\n | { text: string }\n | undefined;\n text = block?.text ?? text;\n }\n\n const additional_kwargs: ChatGeneration['message']['additional_kwargs'] = {\n ...generationInfo,\n };\n if (reasoningParts.length > 0) {\n additional_kwargs.reasoning = reasoningParts.join('');\n }\n\n // Extract thought signatures from function calls for Gemini 3+\n const functionThoughtSignatures = functionCalls.reduce(\n (acc, fc) => {\n if ('thoughtSignature' in fc && typeof fc.thoughtSignature === 'string') {\n acc[fc.id] = fc.thoughtSignature;\n }\n return acc;\n },\n {} as Record<string, string>\n );\n\n const tool_calls = functionCalls.map((fc) => ({\n type: 'tool_call' as const,\n id: fc.id,\n name: fc.functionCall.name,\n args: fc.functionCall.args,\n }));\n\n // Store thought signatures map for later retrieval\n additional_kwargs[_FUNCTION_CALL_THOUGHT_SIGNATURES_MAP_KEY] =\n functionThoughtSignatures;\n\n const generation: ChatGeneration = {\n text,\n message: new AIMessage({\n content,\n tool_calls,\n additional_kwargs,\n usage_metadata: extra?.usageMetadata,\n }),\n generationInfo,\n };\n return {\n generations: [generation],\n llmOutput: {\n tokenUsage: {\n promptTokens: extra?.usageMetadata?.input_tokens,\n completionTokens: extra?.usageMetadata?.output_tokens,\n totalTokens: extra?.usageMetadata?.total_tokens,\n },\n },\n };\n}\n\nexport function convertToGenerativeAITools(\n tools: GoogleGenerativeAIToolType[]\n): GoogleGenerativeAIFunctionDeclarationsTool[] {\n if (\n tools.every(\n (tool) =>\n 'functionDeclarations' in tool &&\n Array.isArray(tool.functionDeclarations)\n )\n ) {\n return tools as GoogleGenerativeAIFunctionDeclarationsTool[];\n }\n return [\n {\n functionDeclarations: tools.map(\n (tool): GenerativeAIFunctionDeclaration => {\n if (isLangChainTool(tool)) {\n const jsonSchema = schemaToGenerativeAIParameters(tool.schema);\n if (\n jsonSchema.type === 'object' &&\n 'properties' in jsonSchema &&\n Object.keys(jsonSchema.properties).length === 0\n ) {\n return {\n name: tool.name,\n description: tool.description,\n };\n }\n return {\n name: tool.name,\n description: tool.description,\n parameters: jsonSchema,\n };\n }\n if (isOpenAITool(tool)) {\n return {\n name: tool.function.name,\n description:\n tool.function.description ?? 'A function available to call.',\n parameters: jsonSchemaToGeminiParameters(\n tool.function.parameters\n ),\n };\n }\n return tool as unknown as GenerativeAIFunctionDeclaration;\n }\n ),\n },\n ];\n}\n"],"mappings":";;;;;;;;;AAiDA,MAAa,4CACX;AAEF,MAAM,kBACJ;AAuBF,SAAS,oBAAoB,IAAiC;CAC5D,OAAO,MAAM,QAAQ,OAAO,KAAK,KAAK,KAAA;AACxC;AAEA,SAAS,iCAAiC,EACxC,MACA,UACA,MAKO;CACP,MAAM,aAAa,oBAAoB,EAAE;CAMzC,OAAO,EAAE,kBAAA;EAJP;EACA;EACA,GAAI,cAAc,OAAO,EAAE,IAAI,WAAW,IAAI,CAAC;CAEzB,EAAE;AAC5B;;;;;;;AAQA,MAAa,QAAW,OAAmB,GAAG;AAE9C,SAAgB,iBAAiB,SAA8B;CAC7D,MAAM,OAAO,QAAQ,SAAS;CAC9B,IAAIA,yBAAAA,YAAY,WAAW,OAAO,GAChC,OAAO,QAAQ;CAEjB,IAAI,SAAS,QACX,OAAO;CAET,OAAO,QAAQ,QAAQ;AACzB;;;;;;;AAQA,SAAgB,oBACd,QACiC;CACjC,QAAQ,QAAR;;;;;EAKA,KAAK;EACL,KAAK;EACL,KAAK,SACH,OAAO;EACT,KAAK,UACH,OAAO;EACT,KAAK,SACH,OAAO;EACT,KAAK;EACL,KAAK,YACH,OAAO;EACT,SACE,MAAM,IAAI,MAAM,iCAAiC,QAAQ;CAC3D;AACF;AAEA,SAAS,oBAAoB,SAAsC;CACjE,IAAI,cAAc,WAAW,UAAU,SACrC,OAAO,EACL,YAAY;EACV,UAAU,QAAQ;EAClB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AAM;GACN,MAAM,EAAE;EACV;OACK,IAAI,oBAAoB,GAC7B,OAAO;GACL,MAAM;GACN,gBAAgB,EAAE;EACpB;OACK,IAAI,yBAAyB,GAClC,OAAO;GACL,MAAM;GACN,qBAAqB,EAAE;EACzB;EAEF,MAAM,qBAAqB,wCAAwC,CAAC;EACpE,IAAI,uBAAuB,KAAA,GACzB,OAAO;EAET,OAAO;CACT,CAAC,CAAC,CACD,QAAQ,MAAM,MAAM,KAAA,CAAS,CAClC;MAEA,UAAU,CAAC;CAEb,IAAI,OAAO;CACX,IAAI,OAAO,YAAY,UACrB,OAAO;MACF,IAAI,MAAM,QAAQ,OAAO,KAAK,QAAQ,SAAS,GAIpD,OAHc,QAAQ,MAAM,MAAM,UAAU,CAGjC,CAAC,EAAE,QAAQ;CAGxB,MAAM,oBAAoE,EACxE,GAAG,eACL;CACA,IAAI,eAAe,SAAS,GAC1B,kBAAkB,YAAY,eAAe,KAAK,EAAE;CAItD,MAAM,4BAA4B,cAAc,QAC7C,KAAK,OAAO;EACX,IAAI,sBAAsB,MAAM,OAAO,GAAG,qBAAqB,UAC7D,IAAI,GAAG,MAAM,GAAG;EAElB,OAAO;CACT,GACA,CAAC,CACH;CAEA,MAAM,aAAa,cAAc,KAAK,QAAQ;EAC5C,MAAM;EACN,IAAI,GAAG;EACP,MAAM,GAAG,aAAa;EACtB,MAAM,GAAG,aAAa;CACxB,EAAE;CAGF,kBAAkB,6CAChB;CAYF,OAAO;EACL,aAAa,CAAC;GAVd;GACA,SAAS,IAAIM,yBAAAA,UAAU;IACrB;IACA;IACA;IACA,gBAAgB,OAAO;GACzB,CAAC;GACD;EAGuB,CAAC;EACxB,WAAW,EACT,YAAY;GACV,cAAc,OAAO,eAAe;GACpC,kBAAkB,OAAO,eAAe;GACxC,aAAa,OAAO,eAAe;EACrC,EACF;CACF;AACF"}
|
|
@@ -269,13 +269,33 @@ function simplifyParametersForSearch(parameters) {
|
|
|
269
269
|
return { type: parameters.type };
|
|
270
270
|
}
|
|
271
271
|
/**
|
|
272
|
+
* Splits one alphanumeric identifier segment on case boundaries without
|
|
273
|
+
* emitting artificial one-character acronym fragments.
|
|
274
|
+
*/
|
|
275
|
+
function splitCaseSegment(segment) {
|
|
276
|
+
const splitTokens = segment.replace(/([a-z0-9])([A-Z])/g, "$1 $2").replace(/([A-Z]+)([A-Z][a-z])/g, "$1 $2").toLowerCase().split(/\s+/).filter(Boolean);
|
|
277
|
+
if (splitTokens.length < 2) return splitTokens;
|
|
278
|
+
const mergedTokens = [];
|
|
279
|
+
let prefix = "";
|
|
280
|
+
for (const token of splitTokens) {
|
|
281
|
+
if (token.length === 1) {
|
|
282
|
+
prefix += token;
|
|
283
|
+
continue;
|
|
284
|
+
}
|
|
285
|
+
mergedTokens.push(`${prefix}${token}`);
|
|
286
|
+
prefix = "";
|
|
287
|
+
}
|
|
288
|
+
if (prefix && mergedTokens.length > 0) mergedTokens[mergedTokens.length - 1] += prefix;
|
|
289
|
+
return mergedTokens.length > 0 ? mergedTokens : [prefix];
|
|
290
|
+
}
|
|
291
|
+
/**
|
|
272
292
|
* Tokenizes a string into lowercase words for BM25.
|
|
273
|
-
* Splits
|
|
293
|
+
* Splits camelCase, underscores, and non-alphanumeric characters for consistent matching.
|
|
274
294
|
* @param text - The text to tokenize
|
|
275
295
|
* @returns Array of lowercase tokens
|
|
276
296
|
*/
|
|
277
297
|
function tokenize(text) {
|
|
278
|
-
return text.
|
|
298
|
+
return text.split(/[^a-zA-Z0-9]+/).filter(Boolean).flatMap(splitCaseSegment);
|
|
279
299
|
}
|
|
280
300
|
/**
|
|
281
301
|
* Creates a searchable document string from tool metadata.
|
|
@@ -294,7 +314,7 @@ function createToolDocument(tool, fields) {
|
|
|
294
314
|
const paramNames = Object.keys(tool.parameters.properties).join(" ");
|
|
295
315
|
parts.push(paramNames);
|
|
296
316
|
}
|
|
297
|
-
return parts.join(" ");
|
|
317
|
+
return tokenize(parts.join(" ")).join(" ");
|
|
298
318
|
}
|
|
299
319
|
/**
|
|
300
320
|
* Determines which field had the best match for a query.
|
|
@@ -364,23 +384,48 @@ function performLocalSearch(tools, query, fields, maxResults) {
|
|
|
364
384
|
});
|
|
365
385
|
const maxScore = Math.max(...scores.filter((s) => s > 0), 1);
|
|
366
386
|
const queryLower = query.toLowerCase().trim();
|
|
387
|
+
const queryIdentifier = queryTokens.join("");
|
|
388
|
+
const matchesIdentifiers = fields.includes("name");
|
|
367
389
|
const results = [];
|
|
368
|
-
for (let i = 0; i < tools.length; i++)
|
|
390
|
+
for (let i = 0; i < tools.length; i++) {
|
|
391
|
+
const score = scores[i];
|
|
392
|
+
const hasSearchScore = Number.isFinite(score) && score > 0;
|
|
393
|
+
let identifierPriority = 0;
|
|
394
|
+
let normalizedScore = hasSearchScore ? Math.min(score / maxScore, 1) : 0;
|
|
395
|
+
if (matchesIdentifiers) {
|
|
396
|
+
const rawBaseName = getBaseToolName(tools[i].name).toLowerCase();
|
|
397
|
+
const rawFullName = tools[i].name.toLowerCase();
|
|
398
|
+
const baseIdentifier = tokenize(rawBaseName).join("");
|
|
399
|
+
const fullIdentifier = tokenize(rawFullName).join("");
|
|
400
|
+
if (rawFullName === queryLower) {
|
|
401
|
+
identifierPriority = 4;
|
|
402
|
+
normalizedScore = 1;
|
|
403
|
+
} else if (rawBaseName === queryLower) {
|
|
404
|
+
identifierPriority = 3;
|
|
405
|
+
normalizedScore = 1;
|
|
406
|
+
} else if (baseIdentifier === queryIdentifier || fullIdentifier === queryIdentifier) {
|
|
407
|
+
identifierPriority = 2;
|
|
408
|
+
normalizedScore = 1;
|
|
409
|
+
} else if (baseIdentifier.startsWith(queryIdentifier)) {
|
|
410
|
+
identifierPriority = 1;
|
|
411
|
+
normalizedScore = Math.max(normalizedScore, .95);
|
|
412
|
+
}
|
|
413
|
+
}
|
|
414
|
+
if (!hasSearchScore && identifierPriority === 0) continue;
|
|
369
415
|
const { field, snippet } = findMatchedField(tools[i], queryTokens, fields);
|
|
370
|
-
let normalizedScore = Math.min(scores[i] / maxScore, 1);
|
|
371
|
-
const baseName = getBaseToolName(tools[i].name).toLowerCase();
|
|
372
|
-
if (baseName === queryLower) normalizedScore = 1;
|
|
373
|
-
else if (baseName.startsWith(queryLower)) normalizedScore = Math.max(normalizedScore, .95);
|
|
374
416
|
results.push({
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
417
|
+
result: {
|
|
418
|
+
tool_name: tools[i].name,
|
|
419
|
+
match_score: normalizedScore,
|
|
420
|
+
matched_field: field,
|
|
421
|
+
snippet
|
|
422
|
+
},
|
|
423
|
+
identifierPriority
|
|
379
424
|
});
|
|
380
425
|
}
|
|
381
|
-
results.sort((a, b) => b.match_score - a.match_score);
|
|
426
|
+
results.sort((a, b) => b.identifierPriority - a.identifierPriority || b.result.match_score - a.result.match_score);
|
|
382
427
|
return {
|
|
383
|
-
tool_references: results.slice(0, maxResults),
|
|
428
|
+
tool_references: results.slice(0, maxResults).map(({ result }) => result),
|
|
384
429
|
total_tools_searched: tools.length,
|
|
385
430
|
pattern_used: query
|
|
386
431
|
};
|