@langchain/google 0.2.11 → 0.2.13
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +29 -0
- package/dist/chat_models/{api-types.d.ts → api_types/generate_content.d.cts} +198 -200
- package/dist/chat_models/{api-types.d.cts → api_types/generate_content.d.ts} +198 -200
- package/dist/chat_models/api_types/interactions.d.cts +1423 -0
- package/dist/chat_models/api_types/interactions.d.ts +1423 -0
- package/dist/chat_models/base.cjs +60 -403
- package/dist/chat_models/base.cjs.map +1 -1
- package/dist/chat_models/base.d.cts +13 -200
- package/dist/chat_models/base.d.ts +15 -202
- package/dist/chat_models/base.js +61 -402
- package/dist/chat_models/base.js.map +1 -1
- package/dist/chat_models/handlers/base.cjs +62 -0
- package/dist/chat_models/handlers/base.cjs.map +1 -0
- package/dist/chat_models/handlers/base.d.cts +46 -0
- package/dist/chat_models/handlers/base.d.ts +46 -0
- package/dist/chat_models/handlers/base.js +62 -0
- package/dist/chat_models/handlers/base.js.map +1 -0
- package/dist/chat_models/handlers/generate_content.cjs +344 -0
- package/dist/chat_models/handlers/generate_content.cjs.map +1 -0
- package/dist/chat_models/handlers/generate_content.d.cts +32 -0
- package/dist/chat_models/handlers/generate_content.d.ts +32 -0
- package/dist/chat_models/handlers/generate_content.js +344 -0
- package/dist/chat_models/handlers/generate_content.js.map +1 -0
- package/dist/chat_models/handlers/index.cjs +6 -0
- package/dist/chat_models/handlers/index.d.cts +4 -0
- package/dist/chat_models/handlers/index.d.ts +4 -0
- package/dist/chat_models/handlers/index.js +4 -0
- package/dist/chat_models/handlers/interactions.cjs +303 -0
- package/dist/chat_models/handlers/interactions.cjs.map +1 -0
- package/dist/chat_models/handlers/interactions.d.cts +33 -0
- package/dist/chat_models/handlers/interactions.d.ts +33 -0
- package/dist/chat_models/handlers/interactions.js +303 -0
- package/dist/chat_models/handlers/interactions.js.map +1 -0
- package/dist/chat_models/index.cjs +14 -6
- package/dist/chat_models/index.cjs.map +1 -1
- package/dist/chat_models/index.d.cts +7 -3
- package/dist/chat_models/index.d.ts +7 -3
- package/dist/chat_models/index.js +8 -4
- package/dist/chat_models/index.js.map +1 -1
- package/dist/chat_models/node.cjs +4 -5
- package/dist/chat_models/node.cjs.map +1 -1
- package/dist/chat_models/node.d.cts +1 -3
- package/dist/chat_models/node.d.ts +1 -3
- package/dist/chat_models/node.js +3 -4
- package/dist/chat_models/node.js.map +1 -1
- package/dist/chat_models/profiles.cjs +1 -2
- package/dist/chat_models/profiles.js +1 -2
- package/dist/chat_models/types.cjs +1 -2
- package/dist/chat_models/types.cjs.map +1 -1
- package/dist/chat_models/types.d.cts +776 -88
- package/dist/chat_models/types.d.ts +776 -88
- package/dist/chat_models/types.js +1 -2
- package/dist/chat_models/types.js.map +1 -1
- package/dist/clients/index.cjs +3 -4
- package/dist/clients/index.d.cts +0 -2
- package/dist/clients/index.d.ts +0 -2
- package/dist/clients/index.js +3 -4
- package/dist/clients/node.cjs +4 -5
- package/dist/clients/node.d.cts +0 -2
- package/dist/clients/node.d.ts +0 -2
- package/dist/clients/node.js +4 -5
- package/dist/const.cjs +1 -2
- package/dist/const.js +1 -2
- package/dist/converters/{messages.cjs → generate_content/messages.cjs} +4 -5
- package/dist/converters/generate_content/messages.cjs.map +1 -0
- package/dist/converters/{messages.js → generate_content/messages.js} +4 -5
- package/dist/converters/generate_content/messages.js.map +1 -0
- package/dist/converters/generate_content/params.cjs +135 -0
- package/dist/converters/generate_content/params.cjs.map +1 -0
- package/dist/converters/generate_content/params.js +131 -0
- package/dist/converters/generate_content/params.js.map +1 -0
- package/dist/{utils → converters/generate_content}/stream_events.cjs +2 -3
- package/dist/converters/generate_content/stream_events.cjs.map +1 -0
- package/dist/{utils → converters/generate_content}/stream_events.js +2 -3
- package/dist/converters/generate_content/stream_events.js.map +1 -0
- package/dist/converters/{tools.cjs → generate_content/tools.cjs} +4 -5
- package/dist/converters/generate_content/tools.cjs.map +1 -0
- package/dist/converters/{tools.js → generate_content/tools.js} +4 -5
- package/dist/converters/generate_content/tools.js.map +1 -0
- package/dist/converters/interactions/messages.cjs +766 -0
- package/dist/converters/interactions/messages.cjs.map +1 -0
- package/dist/converters/interactions/messages.js +759 -0
- package/dist/converters/interactions/messages.js.map +1 -0
- package/dist/converters/interactions/params.cjs +244 -0
- package/dist/converters/interactions/params.cjs.map +1 -0
- package/dist/converters/interactions/params.js +237 -0
- package/dist/converters/interactions/params.js.map +1 -0
- package/dist/converters/interactions/stream_events.cjs +769 -0
- package/dist/converters/interactions/stream_events.cjs.map +1 -0
- package/dist/converters/interactions/stream_events.js +768 -0
- package/dist/converters/interactions/stream_events.js.map +1 -0
- package/dist/converters/interactions/tools.cjs +229 -0
- package/dist/converters/interactions/tools.cjs.map +1 -0
- package/dist/converters/interactions/tools.js +228 -0
- package/dist/converters/interactions/tools.js.map +1 -0
- package/dist/converters/{params.cjs → shared/params.cjs} +8 -94
- package/dist/converters/shared/params.cjs.map +1 -0
- package/dist/converters/{params.js → shared/params.js} +8 -92
- package/dist/converters/shared/params.js.map +1 -0
- package/dist/index.cjs +8 -0
- package/dist/index.d.cts +6 -1
- package/dist/index.d.ts +6 -1
- package/dist/index.js +5 -1
- package/dist/node.cjs +1 -1
- package/dist/node.d.cts +1 -1
- package/dist/node.d.ts +1 -1
- package/dist/node.js +1 -1
- package/dist/utils/errors.cjs +1 -2
- package/dist/utils/errors.js +1 -2
- package/dist/utils/gcp-auth.cjs +3 -4
- package/dist/utils/gcp-auth.d.cts +0 -2
- package/dist/utils/gcp-auth.d.ts +0 -2
- package/dist/utils/gcp-auth.js +3 -4
- package/dist/utils/handler.cjs +1 -2
- package/dist/utils/handler.d.cts +0 -2
- package/dist/utils/handler.d.ts +0 -2
- package/dist/utils/handler.js +1 -2
- package/dist/utils/metadata.cjs +9 -2
- package/dist/utils/metadata.cjs.map +1 -1
- package/dist/utils/metadata.js +9 -3
- package/dist/utils/metadata.js.map +1 -1
- package/dist/utils/misc.cjs +1 -2
- package/dist/utils/misc.cjs.map +1 -1
- package/dist/utils/misc.d.cts +2 -3
- package/dist/utils/misc.d.ts +2 -3
- package/dist/utils/misc.js +1 -2
- package/dist/utils/misc.js.map +1 -1
- package/dist/utils/stream.cjs +1 -2
- package/dist/utils/stream.js +1 -2
- package/package.json +12 -10
- package/dist/converters/messages.cjs.map +0 -1
- package/dist/converters/messages.js.map +0 -1
- package/dist/converters/params.cjs.map +0 -1
- package/dist/converters/params.js.map +0 -1
- package/dist/converters/tools.cjs.map +0 -1
- package/dist/converters/tools.js.map +0 -1
- package/dist/utils/stream_events.cjs.map +0 -1
- package/dist/utils/stream_events.js.map +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"tools.js","names":[],"sources":["../../../src/converters/interactions/tools.ts"],"sourcesContent":["import { isLangChainTool } from \"@langchain/core/utils/function_calling\";\nimport { isOpenAITool } from \"@langchain/core/language_models/base\";\nimport { Converter } from \"@langchain/core/utils/format\";\nimport type {\n BindToolsInput,\n ToolChoice,\n} from \"@langchain/core/language_models/chat_models\";\nimport type { Gemini } from \"../../chat_models/types.js\";\nimport { InvalidToolError } from \"../../utils/errors.js\";\nimport { schemaToGeminiParameters } from \"../generate_content/tools.js\";\n\nconst INTERACTIONS_TOOL_TYPES = new Set([\n \"function\",\n \"google_search\",\n \"code_execution\",\n \"url_context\",\n \"computer_use\",\n \"file_search\",\n \"google_maps\",\n \"mcp_server\",\n \"retrieval\",\n]);\n\n/**\n * Type guard to check if a tool is already in Interactions API format.\n * Note: OpenAI tools also have `type: \"function\"`, so we exclude objects\n * that have an OpenAI-style nested `function` object.\n */\nfunction isInteractionsTool(\n tool: BindToolsInput\n): tool is Gemini.Interactions.Tool {\n if (typeof tool !== \"object\" || tool === null) {\n return false;\n }\n if (isOpenAITool(tool)) {\n return false;\n }\n if (!(\"type\" in tool) || typeof tool.type !== \"string\") {\n return false;\n }\n return INTERACTIONS_TOOL_TYPES.has(tool.type);\n}\n\n/**\n * Type guard to check if a tool is in GenerateContent `Gemini.Tool` format.\n */\nfunction isGenerateContentTool(tool: BindToolsInput): tool is Gemini.Tool {\n if (typeof tool !== \"object\" || tool === null) {\n return false;\n }\n\n const geminiToolAttributes = [\n \"functionDeclarations\",\n \"codeExecution\",\n \"googleSearch\",\n \"googleSearchRetrieval\",\n \"urlContext\",\n \"googleMaps\",\n \"fileSearch\",\n \"computerUse\",\n \"mcpServers\",\n \"retrieval\",\n ];\n\n return geminiToolAttributes.some((attr) => attr in tool);\n}\n\n/**\n * Converts a GenerateContent-formatted `Gemini.Tool` object into one or more\n * flat Interactions API `Gemini.Interactions.Tool` objects, translating\n * camelCase properties to snake_case where appropriate.\n */\nfunction convertGenerateContentToolToInteractionsTools(\n tool: Gemini.Tool & Record<string, unknown>\n): Gemini.Interactions.Tool[] {\n const results: Gemini.Interactions.Tool[] = [];\n\n if (\n \"functionDeclarations\" in tool &&\n Array.isArray(tool.functionDeclarations)\n ) {\n for (const decl of tool.functionDeclarations) {\n const parameters = (decl.parameters ?? decl.parametersJsonSchema) as\n | Record<string, unknown>\n | undefined;\n results.push({\n type: \"function\",\n name: decl.name ?? \"\",\n description: decl.description ?? \"A function available to call.\",\n ...(parameters ? { parameters } : {}),\n });\n }\n }\n\n if (\"googleSearch\" in tool && tool.googleSearch) {\n const gs = tool.googleSearch as Gemini.Tools.GoogleSearch &\n Record<string, unknown>;\n const searchTypes: Array<\n \"web_search\" | \"image_search\" | \"enterprise_web_search\"\n > = [];\n if (gs.searchTypes?.webSearch) {\n searchTypes.push(\"web_search\");\n }\n if (gs.searchTypes?.imageSearch) {\n searchTypes.push(\"image_search\");\n }\n const timeRangeFilter =\n (gs.time_range_filter as Gemini.Interactions.GoogleSearch[\"time_range_filter\"]) ??\n (gs.timeRangeFilter\n ? {\n start_time: gs.timeRangeFilter.startTime,\n end_time: gs.timeRangeFilter.endTime,\n }\n : undefined);\n\n results.push({\n type: \"google_search\",\n ...(searchTypes.length > 0 ? { search_types: searchTypes } : {}),\n ...(timeRangeFilter ? { time_range_filter: timeRangeFilter } : {}),\n });\n } else if (\"googleSearchRetrieval\" in tool) {\n results.push({\n type: \"google_search\",\n });\n }\n\n if (\"codeExecution\" in tool && tool.codeExecution) {\n results.push({\n type: \"code_execution\",\n });\n }\n\n if (\"urlContext\" in tool && tool.urlContext) {\n results.push({\n type: \"url_context\",\n });\n }\n\n if (\"googleMaps\" in tool && tool.googleMaps) {\n const gm = tool.googleMaps as Gemini.Tools.GoogleMaps &\n Record<string, unknown>;\n const enableWidget =\n (gm.enable_widget as boolean | undefined) ?? gm.enableWidget;\n results.push({\n type: \"google_maps\",\n ...(typeof enableWidget === \"boolean\"\n ? { enable_widget: enableWidget }\n : {}),\n ...(typeof gm.latitude === \"number\" ? { latitude: gm.latitude } : {}),\n ...(typeof gm.longitude === \"number\" ? { longitude: gm.longitude } : {}),\n });\n }\n\n if (\"fileSearch\" in tool && tool.fileSearch) {\n const fs = tool.fileSearch as Gemini.Tools.FileSearch &\n Record<string, unknown>;\n const storeNames =\n (fs.file_search_store_names as string[] | undefined) ??\n fs.fileSearchStoreNames;\n const topK = (fs.top_k as number | undefined) ?? fs.topK;\n const metadataFilter =\n (fs.metadata_filter as string | undefined) ?? fs.metadataFilter;\n results.push({\n type: \"file_search\",\n ...(storeNames ? { file_search_store_names: storeNames } : {}),\n ...(typeof topK === \"number\" ? { top_k: topK } : {}),\n ...(metadataFilter ? { metadata_filter: metadataFilter } : {}),\n });\n }\n\n if (\"computerUse\" in tool && tool.computerUse) {\n const cu = tool.computerUse as Gemini.Tools.ComputerUse &\n Record<string, unknown>;\n const rawEnv = cu.environment;\n const environment =\n rawEnv === \"ENVIRONMENT_BROWSER\" || rawEnv === \"browser\"\n ? (\"browser\" as const)\n : undefined;\n const excludedPredefinedFunctions =\n (cu.excluded_predefined_functions as string[] | undefined) ??\n cu.excludedPredefinedFunctions;\n results.push({\n type: \"computer_use\",\n ...(environment ? { environment } : {}),\n ...(excludedPredefinedFunctions\n ? { excluded_predefined_functions: excludedPredefinedFunctions }\n : {}),\n });\n }\n\n if (\"mcpServers\" in tool && Array.isArray(tool.mcpServers)) {\n for (const server of tool.mcpServers as Array<Record<string, unknown>>) {\n const transport = server.streamableHttpTransport as\n | Record<string, unknown>\n | undefined;\n const url = (server.url ?? transport?.url) as string | undefined;\n const headers = (server.headers ?? transport?.headers) as\n | Record<string, string>\n | undefined;\n const allowedTools = (server.allowed_tools ?? server.allowedTools) as\n | Gemini.Interactions.AllowedTools[]\n | undefined;\n results.push({\n type: \"mcp_server\",\n ...(typeof server.name === \"string\" ? { name: server.name } : {}),\n ...(url ? { url } : {}),\n ...(headers ? { headers } : {}),\n ...(allowedTools ? { allowed_tools: allowedTools } : {}),\n });\n }\n }\n\n if (\"retrieval\" in tool && tool.retrieval) {\n const ret = tool.retrieval as Record<string, unknown>;\n const vas = (ret.vertex_ai_search_config ?? ret.vertexAiSearch) as\n | Record<string, unknown>\n | undefined;\n const datastores = Array.isArray(vas?.datastores)\n ? (vas.datastores as string[])\n : typeof vas?.datastore === \"string\"\n ? [vas.datastore]\n : undefined;\n results.push({\n type: \"retrieval\",\n ...(vas\n ? {\n retrieval_types: [\"vertex_ai_search\"],\n vertex_ai_search_config: {\n ...(datastores ? { datastores } : {}),\n ...(typeof vas.engine === \"string\" ? { engine: vas.engine } : {}),\n },\n }\n : {}),\n });\n }\n\n return results;\n}\n\n/**\n * Converts an array of tools in any supported format (LangChain `StructuredTool`,\n * OpenAI tool, GenerateContent `Gemini.Tool`, raw `FunctionDeclaration`, or native\n * Interactions `Tool`) into flat `Gemini.Interactions.Tool[]` items.\n */\nexport const convertToolsToInteractionsTools: Converter<\n BindToolsInput[],\n Gemini.Interactions.Tool[]\n> = (tools) => {\n if (tools.length === 0) {\n return [];\n }\n\n const interactionsTools: Gemini.Interactions.Tool[] = [];\n\n for (const tool of tools) {\n if (isInteractionsTool(tool)) {\n interactionsTools.push(tool);\n continue;\n }\n\n if (isGenerateContentTool(tool)) {\n interactionsTools.push(\n ...convertGenerateContentToolToInteractionsTools(\n tool as Gemini.Tool & Record<string, unknown>\n )\n );\n continue;\n }\n\n if (isLangChainTool(tool)) {\n const jsonSchema = schemaToGeminiParameters(tool.schema);\n interactionsTools.push({\n type: \"function\",\n name: tool.name,\n description: tool.description ?? \"A function available to call.\",\n parameters: jsonSchema as unknown as Record<string, unknown>,\n });\n continue;\n }\n\n if (isOpenAITool(tool)) {\n interactionsTools.push({\n type: \"function\",\n name: tool.function.name,\n description:\n tool.function.description ?? \"A function available to call.\",\n parameters: tool.function.parameters\n ? (schemaToGeminiParameters(\n tool.function.parameters\n ) as unknown as Record<string, unknown>)\n : undefined,\n });\n continue;\n }\n\n if (\n typeof tool === \"object\" &&\n tool !== null &&\n \"name\" in tool &&\n typeof tool.name === \"string\"\n ) {\n const funcDecl = tool as Partial<Gemini.Tools.FunctionDeclaration>;\n interactionsTools.push({\n type: \"function\",\n name: funcDecl.name!,\n description: funcDecl.description ?? \"A function available to call.\",\n ...(funcDecl.parameters\n ? {\n parameters: funcDecl.parameters as unknown as Record<\n string,\n unknown\n >,\n }\n : {}),\n });\n continue;\n }\n\n throw new InvalidToolError(tool);\n }\n\n return interactionsTools;\n};\n\n/**\n * Converts LangChain's `tool_choice` option into the Interactions API\n * `generation_config.tool_choice` format (`ToolChoiceType | ToolChoiceConfig`).\n */\nexport function convertToolChoiceToInteractionsConfig(\n toolChoice: ToolChoice | undefined,\n hasTools: boolean\n): Gemini.Interactions.ToolChoice | undefined {\n if (!hasTools || toolChoice === undefined) {\n return undefined;\n }\n\n if (typeof toolChoice === \"object\" && toolChoice !== null) {\n if (\"allowed_tools\" in toolChoice) {\n return toolChoice as Gemini.Interactions.ToolChoiceConfig;\n }\n }\n\n let mode: Gemini.Interactions.ToolChoiceType | undefined;\n let allowedFunctionNames: string[] | undefined;\n\n let toolChoiceMode: string | undefined;\n let toolChoiceFunction: string | string[] | undefined;\n\n if (typeof toolChoice === \"object\" && toolChoice !== null) {\n const obj = toolChoice as {\n mode?: string;\n function?: { name?: string };\n allowedFunctionNames?: string[];\n };\n toolChoiceMode = obj.mode;\n toolChoiceFunction = obj.function?.name ?? obj.allowedFunctionNames;\n } else if (typeof toolChoice === \"string\") {\n toolChoiceMode = toolChoice;\n }\n\n const normalizedMode = toolChoiceMode?.toLowerCase();\n if (normalizedMode === \"auto\") {\n mode = \"auto\";\n } else if (normalizedMode === \"any\" || normalizedMode === \"required\") {\n mode = \"any\";\n } else if (normalizedMode === \"none\") {\n mode = \"none\";\n } else if (normalizedMode === \"validated\") {\n mode = \"validated\";\n } else if (typeof toolChoiceMode === \"string\" && toolChoiceMode.length > 0) {\n mode = \"any\";\n toolChoiceFunction = toolChoiceMode;\n }\n\n if (toolChoiceFunction) {\n allowedFunctionNames = Array.isArray(toolChoiceFunction)\n ? toolChoiceFunction\n : [toolChoiceFunction];\n }\n\n if (allowedFunctionNames && allowedFunctionNames.length > 0) {\n return {\n allowed_tools: {\n mode: mode ?? \"any\",\n tools: allowedFunctionNames,\n },\n };\n }\n\n return mode;\n}\n"],"mappings":"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"}
|
|
@@ -1,5 +1,4 @@
|
|
|
1
|
-
|
|
2
|
-
//#region src/converters/params.ts
|
|
1
|
+
// src/converters/shared/params.ts
|
|
3
2
|
/**
|
|
4
3
|
* Converts a reasoning "effort" level value (e.g., "minimal", "low", "medium", "high")
|
|
5
4
|
* to a corresponding reasoning token budget, depending on the target Gemini model.
|
|
@@ -72,7 +71,7 @@ function convertReasoningEffortToReasoningTokens(modelName, effort) {
|
|
|
72
71
|
* The Gemini model name (e.g., "gemini-3-pro"). Used for model-specific special cases.
|
|
73
72
|
* @param {number | undefined} reasoningTokens
|
|
74
73
|
* The token budget to convert. If undefined, the function returns undefined.
|
|
75
|
-
* @returns {Lowercase<Gemini.ThinkingLevel> | undefined}
|
|
74
|
+
* @returns {Lowercase<Gemini.Shared.ThinkingLevel> | undefined}
|
|
76
75
|
* The reasoning "effort" level ("minimal", "low", "medium", "high") or undefined if input is not valid.
|
|
77
76
|
*
|
|
78
77
|
* @example
|
|
@@ -143,101 +142,16 @@ function getModelSpecialty(model) {
|
|
|
143
142
|
else if (model.includes("tts")) return "tts";
|
|
144
143
|
else return "";
|
|
145
144
|
}
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
];
|
|
152
|
-
function supportsMinimalThinkingLevel(model) {
|
|
153
|
-
return MINIMAL_THINKING_LEVEL_MODELS.some((prefix) => model.startsWith(prefix));
|
|
145
|
+
function getGoogleChatModelParams(modelOrParams, paramsArg) {
|
|
146
|
+
return {
|
|
147
|
+
model: typeof modelOrParams === "string" ? modelOrParams : modelOrParams.model,
|
|
148
|
+
...typeof modelOrParams === "string" ? paramsArg : modelOrParams
|
|
149
|
+
};
|
|
154
150
|
}
|
|
155
|
-
/**
|
|
156
|
-
* Builds the `thinkingConfig` object for the Gemini `generationConfig`,
|
|
157
|
-
* translating user-facing reasoning fields into the wire format.
|
|
158
|
-
*
|
|
159
|
-
* @param model The full Gemini model name (e.g. "gemini-2.5-flash").
|
|
160
|
-
* @param fields The combined user/call-option fields.
|
|
161
|
-
* @returns A populated {@link Gemini.ThinkingConfig}, or `{}`
|
|
162
|
-
* when thinking should not be explicitly configured.
|
|
163
|
-
*/
|
|
164
|
-
function convertFieldsToThinkingConfig(model, fields) {
|
|
165
|
-
let includeThoughts = true;
|
|
166
|
-
let thinkingBudget = fields?.maxReasoningTokens ?? fields?.thinkingBudget ?? convertReasoningEffortToReasoningTokens(model, fields?.reasoningEffort ?? fields?.thinkingLevel);
|
|
167
|
-
if (thinkingBudget === 0 || model.includes("pro") && thinkingBudget === 128) includeThoughts = false;
|
|
168
|
-
if (model.startsWith("gemini-2.5-pro") && typeof thinkingBudget !== "undefined") {
|
|
169
|
-
if (thinkingBudget >= 0 && thinkingBudget < 128) thinkingBudget = 128;
|
|
170
|
-
}
|
|
171
|
-
let thinkingLevel = (fields?.reasoningEffort ?? fields?.thinkingLevel ?? convertReasoningTokensToReasoningEffort(model, fields?.maxReasoningTokens ?? fields?.thinkingBudget))?.toUpperCase();
|
|
172
|
-
if (thinkingLevel === "MINIMAL") includeThoughts = false;
|
|
173
|
-
if (thinkingLevel === "MINIMAL" && getModelFamily(model) === "gemini" && Number(getModelVersion(model)) >= 3 && !supportsMinimalThinkingLevel(model)) thinkingLevel = "LOW";
|
|
174
|
-
if (model.startsWith("gemini-3-pro") && thinkingLevel === "MEDIUM") thinkingLevel = "HIGH";
|
|
175
|
-
const modelVersion = getModelVersion(model);
|
|
176
|
-
const modelSpecialty = getModelSpecialty(model);
|
|
177
|
-
if (modelVersion === "2.5" && modelSpecialty === "image" || typeof thinkingBudget === "undefined" || typeof thinkingLevel === "undefined") return;
|
|
178
|
-
const thinkingConfig = { includeThoughts };
|
|
179
|
-
if (modelSpecialty === "") {
|
|
180
|
-
if (model.startsWith("gemini-2.5")) thinkingConfig.thinkingBudget = thinkingBudget;
|
|
181
|
-
else thinkingConfig.thinkingLevel = thinkingLevel;
|
|
182
|
-
}
|
|
183
|
-
return thinkingConfig;
|
|
184
|
-
}
|
|
185
|
-
/**
|
|
186
|
-
* Builds the `speechConfig` object for the Gemini `generationConfig`,
|
|
187
|
-
* normalising the user-friendly simplified forms into the wire format.
|
|
188
|
-
*
|
|
189
|
-
* @param fields The combined user/call-option fields.
|
|
190
|
-
* @returns A populated {@link Gemini.SpeechConfig}, or `{}`
|
|
191
|
-
* when no speech config was provided.
|
|
192
|
-
*/
|
|
193
|
-
function convertFieldsToSpeechConfig(fields) {
|
|
194
|
-
const config = fields.speechConfig;
|
|
195
|
-
if (typeof config === "undefined") return;
|
|
196
|
-
function isSpeechConfig(config) {
|
|
197
|
-
return typeof config === "object" && (Object.hasOwn(config, "voiceConfig") || Object.hasOwn(config, "multiSpeakerVoiceConfig"));
|
|
198
|
-
}
|
|
199
|
-
function hasLanguage(config) {
|
|
200
|
-
return typeof config === "object" && Object.hasOwn(config, "languageCode");
|
|
201
|
-
}
|
|
202
|
-
function hasVoice(config) {
|
|
203
|
-
return Object.hasOwn(config, "voice");
|
|
204
|
-
}
|
|
205
|
-
if (isSpeechConfig(config)) return config;
|
|
206
|
-
let languageCode;
|
|
207
|
-
let voice;
|
|
208
|
-
if (hasLanguage(config)) {
|
|
209
|
-
languageCode = config.languageCode;
|
|
210
|
-
voice = hasVoice(config) ? config.voice : config.voices;
|
|
211
|
-
} else {
|
|
212
|
-
languageCode = void 0;
|
|
213
|
-
voice = config;
|
|
214
|
-
}
|
|
215
|
-
let ret;
|
|
216
|
-
if (typeof voice === "string") ret = { voiceConfig: { prebuiltVoiceConfig: { voiceName: voice } } };
|
|
217
|
-
else ret = { multiSpeakerVoiceConfig: { speakerVoiceConfigs: (Array.isArray(voice) ? voice : [voice]).map((v) => ({
|
|
218
|
-
speaker: v.speaker,
|
|
219
|
-
voiceConfig: { prebuiltVoiceConfig: { voiceName: v.name } }
|
|
220
|
-
})) } };
|
|
221
|
-
if (languageCode) ret.languageCode = languageCode;
|
|
222
|
-
return ret;
|
|
223
|
-
}
|
|
224
|
-
/**
|
|
225
|
-
* Builds an object that can be included as part of the request
|
|
226
|
-
* which will add a `speechConfig` attribute if appropriate.
|
|
227
|
-
*/
|
|
228
|
-
function convertFieldsToServiceTier(platform, fields) {
|
|
229
|
-
if (platform === "gcp") return {};
|
|
230
|
-
const serviceTier = fields.serviceTier;
|
|
231
|
-
if (!serviceTier || !require_types.settableServiceTier.includes(serviceTier)) return {};
|
|
232
|
-
return { serviceTier };
|
|
233
|
-
}
|
|
234
|
-
//#endregion
|
|
235
|
-
exports.convertFieldsToServiceTier = convertFieldsToServiceTier;
|
|
236
|
-
exports.convertFieldsToSpeechConfig = convertFieldsToSpeechConfig;
|
|
237
|
-
exports.convertFieldsToThinkingConfig = convertFieldsToThinkingConfig;
|
|
238
151
|
exports.convertParamsToPlatformType = convertParamsToPlatformType;
|
|
239
152
|
exports.convertReasoningEffortToReasoningTokens = convertReasoningEffortToReasoningTokens;
|
|
240
153
|
exports.convertReasoningTokensToReasoningEffort = convertReasoningTokensToReasoningEffort;
|
|
154
|
+
exports.getGoogleChatModelParams = getGoogleChatModelParams;
|
|
241
155
|
exports.getModelFamily = getModelFamily;
|
|
242
156
|
exports.getModelLevel = getModelLevel;
|
|
243
157
|
exports.getModelSpecialty = getModelSpecialty;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"params.cjs","names":[],"sources":["../../../src/converters/shared/params.ts"],"sourcesContent":["import type {\n BaseChatGoogleParams,\n GooglePlatformType,\n Gemini,\n} from \"../../chat_models/types.js\";\n\n/**\n * Converts a reasoning \"effort\" level value (e.g., \"minimal\", \"low\", \"medium\", \"high\")\n * to a corresponding reasoning token budget, depending on the target Gemini model.\n *\n * This mapping is essential when configuring Google Gemini API calls with reasoning\n * effort/level fields (as in the Gemini OpenAI-compatible API) or when translating\n * user-friendly configuration to explicit token budgets.\n *\n * - The mapping is refined to reflect the constraints documented by Google:\n * - For \"gemini-2.5-flash\" models, token budgets may be set as low as 0 and up to 24k.\n * - For other Gemini models, minimum is 128, maximum is 32k.\n * - Standard effort levels and their token mappings:\n * - \"none\" / \"minimal\": lowest allowed (minTokens)\n * - \"low\": 1k tokens\n * - \"medium\": 8k tokens\n * - \"high\": maximum allowed for the model (maxTokens)\n * - See reference:\n * https://ai.google.dev/gemini-api/docs/thinking#thinking-levels\n * https://ai.google.dev/gemini-api/docs/openai#thinking\n *\n * @param {string | undefined} modelName\n * The Gemini model name (e.g., \"gemini-2.5-flash\"). Used to determine token range constraints.\n * @param {string | undefined} effort\n * The reasoning effort level: one of \"none\", \"minimal\", \"low\", \"medium\", \"high\"\n * (case-insensitive). If undefined, the function returns undefined.\n * @returns {number | undefined}\n * The corresponding token count for the given effort and model. Returns undefined if\n * the effort is not recognized or not provided.\n *\n * @example\n * convertReasoningEffortToReasoningTokens(\"gemini-2.5-flash\", \"medium\") // 8192\n * convertReasoningEffortToReasoningTokens(\"gemini-1.5-pro\", \"high\") // 32768\n * convertReasoningEffortToReasoningTokens(\"gemini-2.5-flash\", \"none\") // 0\n * convertReasoningEffortToReasoningTokens(undefined, \"low\") // 1024\n */\nexport function convertReasoningEffortToReasoningTokens(\n modelName?: string,\n effort?: string\n): number | undefined {\n if (effort === undefined) {\n return undefined;\n }\n\n // gemini-2.5-flash and -flash-lite can be disabled. Others can't.\n // https://ai.google.dev/gemini-api/docs/thinking#thinking-levels\n const minTokens: number = modelName?.startsWith(\"gemini-2.5-flash\") ? 0 : 128;\n const maxTokens: number = modelName?.startsWith(\"gemini-2.5-flash\")\n ? 24 * 1024\n : 32 * 1024;\n\n const normalizedEffort = effort.toLowerCase();\n switch (normalizedEffort) {\n case \"none\":\n case \"minimal\":\n return minTokens;\n case \"low\":\n // Defined as 1k by https://ai.google.dev/gemini-api/docs/openai#thinking\n return 1024;\n case \"medium\":\n // Defined as 8k by https://ai.google.dev/gemini-api/docs/openai#thinking\n return 8 * 1024;\n case \"high\":\n // Defined as 24k or 32k (model-dependent) by https://ai.google.dev/gemini-api/docs/openai#thinking\n return maxTokens;\n default:\n return undefined;\n }\n}\n\n/**\n * Converts a reasoning token budget (e.g., 0, 1024, 8192, 32768) to its corresponding\n * reasoning \"effort\" level, as used in the Google Gemini API (\"minimal\", \"low\", \"medium\", \"high\").\n *\n * This is the inverse of {@link convertReasoningEffortToReasoningTokens}. It is useful for\n * translating explicit numeric settings (often surfaced in raw API responses or configs)\n * into user-facing friendly reasoning levels/labels. The mapping relies on Google's\n * documented reasoning levels for different models:\n *\n * - -1 means default effort (per API documentation: this is \"minimal\" for flash-lite models\n * and \"high\" (dynamic) for others).\n * - 0 means \"minimal\" unless the model is \"gemini-3-pro\", for which it maps to \"low\".\n * - <= 1024 tokens: \"low\"\n * - <= 8192 tokens: \"medium\" (unless model is \"gemini-3-pro\", for which it reverts to \"low\")\n * - > 8192: \"high\"\n *\n * Reference:\n * https://ai.google.dev/gemini-api/docs/thinking#thinking-levels\n * https://ai.google.dev/gemini-api/docs/openai#thinking\n *\n * @param {string | undefined} model\n * The Gemini model name (e.g., \"gemini-3-pro\"). Used for model-specific special cases.\n * @param {number | undefined} reasoningTokens\n * The token budget to convert. If undefined, the function returns undefined.\n * @returns {Lowercase<Gemini.Shared.ThinkingLevel> | undefined}\n * The reasoning \"effort\" level (\"minimal\", \"low\", \"medium\", \"high\") or undefined if input is not valid.\n *\n * @example\n * convertReasoningTokensToReasoningEffort(\"gemini-3-pro\", 0) // \"low\"\n * convertReasoningTokensToReasoningEffort(\"gemini-1.5-pro\", 0) // \"minimal\"\n * convertReasoningTokensToReasoningEffort(undefined, 1024) // \"low\"\n * convertReasoningTokensToReasoningEffort(undefined, -1) // \"high\"\n * convertReasoningTokensToReasoningEffort(undefined, 9000) // \"high\"\n */\nexport function convertReasoningTokensToReasoningEffort(\n model?: string,\n reasoningTokens?: number\n): Gemini.Shared.ThinkingLevel | undefined {\n if (typeof reasoningTokens === \"undefined\") {\n return undefined;\n } else if (reasoningTokens === -1) {\n // -1 means \"minimal\" for flash-lite models and \"high\"/dynamic for others\n // (\"default\" per https://ai.google.dev/gemini-api/docs/thinking#thinking-levels)\n if (model && getModelLevel(model) === \"flash-lite\") {\n return \"minimal\";\n }\n return \"high\";\n } else if (reasoningTokens === 0) {\n if (model?.startsWith(\"gemini-3-pro\")) {\n return \"low\";\n } else {\n return \"minimal\";\n }\n } else if (reasoningTokens <= 1024) {\n return \"low\";\n } else if (reasoningTokens <= 8192) {\n if (model?.startsWith(\"gemini-3-pro\")) {\n return \"low\";\n } else {\n return \"medium\";\n }\n } else {\n return \"high\";\n }\n}\n\n/**\n * Infers and returns the Google platform type from the provided chat model parameters.\n *\n * This function helps determine which Google platform (e.g., Vertex AI on GCP or the public API)\n * should be used for calling Gemini/PaLM endpoints, based on the options provided in\n * {@link BaseChatGoogleParams} (such as model constructors or call options).\n */\nexport function convertParamsToPlatformType(params: {\n platformType?: GooglePlatformType;\n vertexai?: boolean;\n}): GooglePlatformType | undefined {\n if (typeof params === \"undefined\") {\n return undefined;\n }\n if (typeof params.platformType !== \"undefined\") {\n return params.platformType;\n }\n if (params.vertexai === true) {\n return \"gcp\";\n }\n return undefined;\n}\n\n/**\n * Returns the model family from a Gemini model name.\n * e.g. \"gemini-2.5-flash\" → \"gemini\"\n */\nexport function getModelFamily(model: string): string {\n return model.split(\"-\")[0];\n}\n\n/**\n * Returns the model version from a Gemini model name.\n * e.g. \"gemini-2.5-flash\" → \"2.5\"\n */\nexport function getModelVersion(model: string): string {\n return model.split(\"-\")[1];\n}\n\n/**\n * Returns the model level from a Gemini model name.\n * e.g. \"gemini-2.5-flash\" → \"flash\", \"gemini-2.5-flash-lite\" → \"flash-lite\"\n */\nexport function getModelLevel(model: string): string {\n const parts = model.split(\"-\");\n let ret = parts[2];\n if (ret === \"flash\" && parts[3] === \"lite\") {\n ret = \"flash-lite\";\n }\n return ret;\n}\n\n/**\n * Returns the model specialty from a Gemini model name.\n * e.g. \"gemini-2.5-flash-preview-image\" → \"image\",\n * \"gemini-2.5-flash-preview-tts\" → \"tts\",\n * \"gemini-2.5-flash\" → \"\"\n */\nexport function getModelSpecialty(model: string): string {\n if (model.includes(\"image\")) {\n return \"image\";\n } else if (model.includes(\"tts\")) {\n return \"tts\";\n } else {\n return \"\";\n }\n}\n\nexport function getGoogleChatModelParams<TParams extends BaseChatGoogleParams>(\n modelOrParams: string | TParams,\n paramsArg?: Omit<TParams, \"model\">\n): TParams {\n const model =\n typeof modelOrParams === \"string\" ? modelOrParams : modelOrParams.model;\n const params = typeof modelOrParams === \"string\" ? paramsArg : modelOrParams;\n return { model, ...params } as TParams;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAyCA,SAAgB,wCACd,WACA,QACoB;CACpB,IAAI,WAAW,KAAA,GACb;CAKF,MAAM,YAAoB,WAAW,WAAW,kBAAkB,IAAI,IAAI;CAC1E,MAAM,YAAoB,WAAW,WAAW,kBAAkB,IAC9D,QACA;CAGJ,QADyB,OAAO,YACT,GAAvB;EACE,KAAK;EACL,KAAK,WACH,OAAO;EACT,KAAK,OAEH,OAAO;EACT,KAAK,UAEH,OAAO;EACT,KAAK,QAEH,OAAO;EACT,SACE;CACJ;AACF;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAoCA,SAAgB,wCACd,OACA,iBACyC;CACzC,IAAI,OAAO,oBAAoB,aAC7B;MACK,IAAI,oBAAoB,IAAI;EAGjC,IAAI,SAAS,cAAc,KAAK,MAAM,cACpC,OAAO;EAET,OAAO;CACT,OAAO,IAAI,oBAAoB,GAAG;EAChC,IAAI,OAAO,WAAW,cAAc,GAClC,OAAO;OAEP,OAAO;CAEX,OAAO,IAAI,mBAAmB,MAC5B,OAAO;MACF,IAAI,mBAAmB,MAAM;EAClC,IAAI,OAAO,WAAW,cAAc,GAClC,OAAO;OAEP,OAAO;CAEX,OACE,OAAO;AAEX;;;;;;;;AASA,SAAgB,4BAA4B,QAGT;CACjC,IAAI,OAAO,WAAW,aACpB;CAEF,IAAI,OAAO,OAAO,iBAAiB,aACjC,OAAO,OAAO;CAEhB,IAAI,OAAO,aAAa,MACtB,OAAO;AAGX;;;;;AAMA,SAAgB,eAAe,OAAuB;CACpD,OAAO,MAAM,MAAM,GAAG,CAAC,CAAC;AAC1B;;;;;AAMA,SAAgB,gBAAgB,OAAuB;CACrD,OAAO,MAAM,MAAM,GAAG,CAAC,CAAC;AAC1B;;;;;AAMA,SAAgB,cAAc,OAAuB;CACnD,MAAM,QAAQ,MAAM,MAAM,GAAG;CAC7B,IAAI,MAAM,MAAM;CAChB,IAAI,QAAQ,WAAW,MAAM,OAAO,QAClC,MAAM;CAER,OAAO;AACT;;;;;;;AAQA,SAAgB,kBAAkB,OAAuB;CACvD,IAAI,MAAM,SAAS,OAAO,GACxB,OAAO;MACF,IAAI,MAAM,SAAS,KAAK,GAC7B,OAAO;MAEP,OAAO;AAEX;AAEA,SAAgB,yBACd,eACA,WACS;CAIT,OAAO;EAAE,OAFP,OAAO,kBAAkB,WAAW,gBAAgB,cAAc;EAEpD,GADD,OAAO,kBAAkB,WAAW,YAAY;CACrC;AAC5B"}
|
|
@@ -1,5 +1,4 @@
|
|
|
1
|
-
|
|
2
|
-
//#region src/converters/params.ts
|
|
1
|
+
// src/converters/shared/params.ts
|
|
3
2
|
/**
|
|
4
3
|
* Converts a reasoning "effort" level value (e.g., "minimal", "low", "medium", "high")
|
|
5
4
|
* to a corresponding reasoning token budget, depending on the target Gemini model.
|
|
@@ -72,7 +71,7 @@ function convertReasoningEffortToReasoningTokens(modelName, effort) {
|
|
|
72
71
|
* The Gemini model name (e.g., "gemini-3-pro"). Used for model-specific special cases.
|
|
73
72
|
* @param {number | undefined} reasoningTokens
|
|
74
73
|
* The token budget to convert. If undefined, the function returns undefined.
|
|
75
|
-
* @returns {Lowercase<Gemini.ThinkingLevel> | undefined}
|
|
74
|
+
* @returns {Lowercase<Gemini.Shared.ThinkingLevel> | undefined}
|
|
76
75
|
* The reasoning "effort" level ("minimal", "low", "medium", "high") or undefined if input is not valid.
|
|
77
76
|
*
|
|
78
77
|
* @example
|
|
@@ -143,95 +142,12 @@ function getModelSpecialty(model) {
|
|
|
143
142
|
else if (model.includes("tts")) return "tts";
|
|
144
143
|
else return "";
|
|
145
144
|
}
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
];
|
|
152
|
-
function supportsMinimalThinkingLevel(model) {
|
|
153
|
-
return MINIMAL_THINKING_LEVEL_MODELS.some((prefix) => model.startsWith(prefix));
|
|
145
|
+
function getGoogleChatModelParams(modelOrParams, paramsArg) {
|
|
146
|
+
return {
|
|
147
|
+
model: typeof modelOrParams === "string" ? modelOrParams : modelOrParams.model,
|
|
148
|
+
...typeof modelOrParams === "string" ? paramsArg : modelOrParams
|
|
149
|
+
};
|
|
154
150
|
}
|
|
155
|
-
|
|
156
|
-
* Builds the `thinkingConfig` object for the Gemini `generationConfig`,
|
|
157
|
-
* translating user-facing reasoning fields into the wire format.
|
|
158
|
-
*
|
|
159
|
-
* @param model The full Gemini model name (e.g. "gemini-2.5-flash").
|
|
160
|
-
* @param fields The combined user/call-option fields.
|
|
161
|
-
* @returns A populated {@link Gemini.ThinkingConfig}, or `{}`
|
|
162
|
-
* when thinking should not be explicitly configured.
|
|
163
|
-
*/
|
|
164
|
-
function convertFieldsToThinkingConfig(model, fields) {
|
|
165
|
-
let includeThoughts = true;
|
|
166
|
-
let thinkingBudget = fields?.maxReasoningTokens ?? fields?.thinkingBudget ?? convertReasoningEffortToReasoningTokens(model, fields?.reasoningEffort ?? fields?.thinkingLevel);
|
|
167
|
-
if (thinkingBudget === 0 || model.includes("pro") && thinkingBudget === 128) includeThoughts = false;
|
|
168
|
-
if (model.startsWith("gemini-2.5-pro") && typeof thinkingBudget !== "undefined") {
|
|
169
|
-
if (thinkingBudget >= 0 && thinkingBudget < 128) thinkingBudget = 128;
|
|
170
|
-
}
|
|
171
|
-
let thinkingLevel = (fields?.reasoningEffort ?? fields?.thinkingLevel ?? convertReasoningTokensToReasoningEffort(model, fields?.maxReasoningTokens ?? fields?.thinkingBudget))?.toUpperCase();
|
|
172
|
-
if (thinkingLevel === "MINIMAL") includeThoughts = false;
|
|
173
|
-
if (thinkingLevel === "MINIMAL" && getModelFamily(model) === "gemini" && Number(getModelVersion(model)) >= 3 && !supportsMinimalThinkingLevel(model)) thinkingLevel = "LOW";
|
|
174
|
-
if (model.startsWith("gemini-3-pro") && thinkingLevel === "MEDIUM") thinkingLevel = "HIGH";
|
|
175
|
-
const modelVersion = getModelVersion(model);
|
|
176
|
-
const modelSpecialty = getModelSpecialty(model);
|
|
177
|
-
if (modelVersion === "2.5" && modelSpecialty === "image" || typeof thinkingBudget === "undefined" || typeof thinkingLevel === "undefined") return;
|
|
178
|
-
const thinkingConfig = { includeThoughts };
|
|
179
|
-
if (modelSpecialty === "") {
|
|
180
|
-
if (model.startsWith("gemini-2.5")) thinkingConfig.thinkingBudget = thinkingBudget;
|
|
181
|
-
else thinkingConfig.thinkingLevel = thinkingLevel;
|
|
182
|
-
}
|
|
183
|
-
return thinkingConfig;
|
|
184
|
-
}
|
|
185
|
-
/**
|
|
186
|
-
* Builds the `speechConfig` object for the Gemini `generationConfig`,
|
|
187
|
-
* normalising the user-friendly simplified forms into the wire format.
|
|
188
|
-
*
|
|
189
|
-
* @param fields The combined user/call-option fields.
|
|
190
|
-
* @returns A populated {@link Gemini.SpeechConfig}, or `{}`
|
|
191
|
-
* when no speech config was provided.
|
|
192
|
-
*/
|
|
193
|
-
function convertFieldsToSpeechConfig(fields) {
|
|
194
|
-
const config = fields.speechConfig;
|
|
195
|
-
if (typeof config === "undefined") return;
|
|
196
|
-
function isSpeechConfig(config) {
|
|
197
|
-
return typeof config === "object" && (Object.hasOwn(config, "voiceConfig") || Object.hasOwn(config, "multiSpeakerVoiceConfig"));
|
|
198
|
-
}
|
|
199
|
-
function hasLanguage(config) {
|
|
200
|
-
return typeof config === "object" && Object.hasOwn(config, "languageCode");
|
|
201
|
-
}
|
|
202
|
-
function hasVoice(config) {
|
|
203
|
-
return Object.hasOwn(config, "voice");
|
|
204
|
-
}
|
|
205
|
-
if (isSpeechConfig(config)) return config;
|
|
206
|
-
let languageCode;
|
|
207
|
-
let voice;
|
|
208
|
-
if (hasLanguage(config)) {
|
|
209
|
-
languageCode = config.languageCode;
|
|
210
|
-
voice = hasVoice(config) ? config.voice : config.voices;
|
|
211
|
-
} else {
|
|
212
|
-
languageCode = void 0;
|
|
213
|
-
voice = config;
|
|
214
|
-
}
|
|
215
|
-
let ret;
|
|
216
|
-
if (typeof voice === "string") ret = { voiceConfig: { prebuiltVoiceConfig: { voiceName: voice } } };
|
|
217
|
-
else ret = { multiSpeakerVoiceConfig: { speakerVoiceConfigs: (Array.isArray(voice) ? voice : [voice]).map((v) => ({
|
|
218
|
-
speaker: v.speaker,
|
|
219
|
-
voiceConfig: { prebuiltVoiceConfig: { voiceName: v.name } }
|
|
220
|
-
})) } };
|
|
221
|
-
if (languageCode) ret.languageCode = languageCode;
|
|
222
|
-
return ret;
|
|
223
|
-
}
|
|
224
|
-
/**
|
|
225
|
-
* Builds an object that can be included as part of the request
|
|
226
|
-
* which will add a `speechConfig` attribute if appropriate.
|
|
227
|
-
*/
|
|
228
|
-
function convertFieldsToServiceTier(platform, fields) {
|
|
229
|
-
if (platform === "gcp") return {};
|
|
230
|
-
const serviceTier = fields.serviceTier;
|
|
231
|
-
if (!serviceTier || !settableServiceTier.includes(serviceTier)) return {};
|
|
232
|
-
return { serviceTier };
|
|
233
|
-
}
|
|
234
|
-
//#endregion
|
|
235
|
-
export { convertFieldsToServiceTier, convertFieldsToSpeechConfig, convertFieldsToThinkingConfig, convertParamsToPlatformType, convertReasoningEffortToReasoningTokens, convertReasoningTokensToReasoningEffort, getModelFamily, getModelLevel, getModelSpecialty, getModelVersion };
|
|
151
|
+
export { convertParamsToPlatformType, convertReasoningEffortToReasoningTokens, convertReasoningTokensToReasoningEffort, getGoogleChatModelParams, getModelFamily, getModelLevel, getModelSpecialty, getModelVersion };
|
|
236
152
|
|
|
237
153
|
//# sourceMappingURL=params.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"params.js","names":[],"sources":["../../../src/converters/shared/params.ts"],"sourcesContent":["import type {\n BaseChatGoogleParams,\n GooglePlatformType,\n Gemini,\n} from \"../../chat_models/types.js\";\n\n/**\n * Converts a reasoning \"effort\" level value (e.g., \"minimal\", \"low\", \"medium\", \"high\")\n * to a corresponding reasoning token budget, depending on the target Gemini model.\n *\n * This mapping is essential when configuring Google Gemini API calls with reasoning\n * effort/level fields (as in the Gemini OpenAI-compatible API) or when translating\n * user-friendly configuration to explicit token budgets.\n *\n * - The mapping is refined to reflect the constraints documented by Google:\n * - For \"gemini-2.5-flash\" models, token budgets may be set as low as 0 and up to 24k.\n * - For other Gemini models, minimum is 128, maximum is 32k.\n * - Standard effort levels and their token mappings:\n * - \"none\" / \"minimal\": lowest allowed (minTokens)\n * - \"low\": 1k tokens\n * - \"medium\": 8k tokens\n * - \"high\": maximum allowed for the model (maxTokens)\n * - See reference:\n * https://ai.google.dev/gemini-api/docs/thinking#thinking-levels\n * https://ai.google.dev/gemini-api/docs/openai#thinking\n *\n * @param {string | undefined} modelName\n * The Gemini model name (e.g., \"gemini-2.5-flash\"). Used to determine token range constraints.\n * @param {string | undefined} effort\n * The reasoning effort level: one of \"none\", \"minimal\", \"low\", \"medium\", \"high\"\n * (case-insensitive). If undefined, the function returns undefined.\n * @returns {number | undefined}\n * The corresponding token count for the given effort and model. Returns undefined if\n * the effort is not recognized or not provided.\n *\n * @example\n * convertReasoningEffortToReasoningTokens(\"gemini-2.5-flash\", \"medium\") // 8192\n * convertReasoningEffortToReasoningTokens(\"gemini-1.5-pro\", \"high\") // 32768\n * convertReasoningEffortToReasoningTokens(\"gemini-2.5-flash\", \"none\") // 0\n * convertReasoningEffortToReasoningTokens(undefined, \"low\") // 1024\n */\nexport function convertReasoningEffortToReasoningTokens(\n modelName?: string,\n effort?: string\n): number | undefined {\n if (effort === undefined) {\n return undefined;\n }\n\n // gemini-2.5-flash and -flash-lite can be disabled. Others can't.\n // https://ai.google.dev/gemini-api/docs/thinking#thinking-levels\n const minTokens: number = modelName?.startsWith(\"gemini-2.5-flash\") ? 0 : 128;\n const maxTokens: number = modelName?.startsWith(\"gemini-2.5-flash\")\n ? 24 * 1024\n : 32 * 1024;\n\n const normalizedEffort = effort.toLowerCase();\n switch (normalizedEffort) {\n case \"none\":\n case \"minimal\":\n return minTokens;\n case \"low\":\n // Defined as 1k by https://ai.google.dev/gemini-api/docs/openai#thinking\n return 1024;\n case \"medium\":\n // Defined as 8k by https://ai.google.dev/gemini-api/docs/openai#thinking\n return 8 * 1024;\n case \"high\":\n // Defined as 24k or 32k (model-dependent) by https://ai.google.dev/gemini-api/docs/openai#thinking\n return maxTokens;\n default:\n return undefined;\n }\n}\n\n/**\n * Converts a reasoning token budget (e.g., 0, 1024, 8192, 32768) to its corresponding\n * reasoning \"effort\" level, as used in the Google Gemini API (\"minimal\", \"low\", \"medium\", \"high\").\n *\n * This is the inverse of {@link convertReasoningEffortToReasoningTokens}. It is useful for\n * translating explicit numeric settings (often surfaced in raw API responses or configs)\n * into user-facing friendly reasoning levels/labels. The mapping relies on Google's\n * documented reasoning levels for different models:\n *\n * - -1 means default effort (per API documentation: this is \"minimal\" for flash-lite models\n * and \"high\" (dynamic) for others).\n * - 0 means \"minimal\" unless the model is \"gemini-3-pro\", for which it maps to \"low\".\n * - <= 1024 tokens: \"low\"\n * - <= 8192 tokens: \"medium\" (unless model is \"gemini-3-pro\", for which it reverts to \"low\")\n * - > 8192: \"high\"\n *\n * Reference:\n * https://ai.google.dev/gemini-api/docs/thinking#thinking-levels\n * https://ai.google.dev/gemini-api/docs/openai#thinking\n *\n * @param {string | undefined} model\n * The Gemini model name (e.g., \"gemini-3-pro\"). Used for model-specific special cases.\n * @param {number | undefined} reasoningTokens\n * The token budget to convert. If undefined, the function returns undefined.\n * @returns {Lowercase<Gemini.Shared.ThinkingLevel> | undefined}\n * The reasoning \"effort\" level (\"minimal\", \"low\", \"medium\", \"high\") or undefined if input is not valid.\n *\n * @example\n * convertReasoningTokensToReasoningEffort(\"gemini-3-pro\", 0) // \"low\"\n * convertReasoningTokensToReasoningEffort(\"gemini-1.5-pro\", 0) // \"minimal\"\n * convertReasoningTokensToReasoningEffort(undefined, 1024) // \"low\"\n * convertReasoningTokensToReasoningEffort(undefined, -1) // \"high\"\n * convertReasoningTokensToReasoningEffort(undefined, 9000) // \"high\"\n */\nexport function convertReasoningTokensToReasoningEffort(\n model?: string,\n reasoningTokens?: number\n): Gemini.Shared.ThinkingLevel | undefined {\n if (typeof reasoningTokens === \"undefined\") {\n return undefined;\n } else if (reasoningTokens === -1) {\n // -1 means \"minimal\" for flash-lite models and \"high\"/dynamic for others\n // (\"default\" per https://ai.google.dev/gemini-api/docs/thinking#thinking-levels)\n if (model && getModelLevel(model) === \"flash-lite\") {\n return \"minimal\";\n }\n return \"high\";\n } else if (reasoningTokens === 0) {\n if (model?.startsWith(\"gemini-3-pro\")) {\n return \"low\";\n } else {\n return \"minimal\";\n }\n } else if (reasoningTokens <= 1024) {\n return \"low\";\n } else if (reasoningTokens <= 8192) {\n if (model?.startsWith(\"gemini-3-pro\")) {\n return \"low\";\n } else {\n return \"medium\";\n }\n } else {\n return \"high\";\n }\n}\n\n/**\n * Infers and returns the Google platform type from the provided chat model parameters.\n *\n * This function helps determine which Google platform (e.g., Vertex AI on GCP or the public API)\n * should be used for calling Gemini/PaLM endpoints, based on the options provided in\n * {@link BaseChatGoogleParams} (such as model constructors or call options).\n */\nexport function convertParamsToPlatformType(params: {\n platformType?: GooglePlatformType;\n vertexai?: boolean;\n}): GooglePlatformType | undefined {\n if (typeof params === \"undefined\") {\n return undefined;\n }\n if (typeof params.platformType !== \"undefined\") {\n return params.platformType;\n }\n if (params.vertexai === true) {\n return \"gcp\";\n }\n return undefined;\n}\n\n/**\n * Returns the model family from a Gemini model name.\n * e.g. \"gemini-2.5-flash\" → \"gemini\"\n */\nexport function getModelFamily(model: string): string {\n return model.split(\"-\")[0];\n}\n\n/**\n * Returns the model version from a Gemini model name.\n * e.g. \"gemini-2.5-flash\" → \"2.5\"\n */\nexport function getModelVersion(model: string): string {\n return model.split(\"-\")[1];\n}\n\n/**\n * Returns the model level from a Gemini model name.\n * e.g. \"gemini-2.5-flash\" → \"flash\", \"gemini-2.5-flash-lite\" → \"flash-lite\"\n */\nexport function getModelLevel(model: string): string {\n const parts = model.split(\"-\");\n let ret = parts[2];\n if (ret === \"flash\" && parts[3] === \"lite\") {\n ret = \"flash-lite\";\n }\n return ret;\n}\n\n/**\n * Returns the model specialty from a Gemini model name.\n * e.g. \"gemini-2.5-flash-preview-image\" → \"image\",\n * \"gemini-2.5-flash-preview-tts\" → \"tts\",\n * \"gemini-2.5-flash\" → \"\"\n */\nexport function getModelSpecialty(model: string): string {\n if (model.includes(\"image\")) {\n return \"image\";\n } else if (model.includes(\"tts\")) {\n return \"tts\";\n } else {\n return \"\";\n }\n}\n\nexport function getGoogleChatModelParams<TParams extends BaseChatGoogleParams>(\n modelOrParams: string | TParams,\n paramsArg?: Omit<TParams, \"model\">\n): TParams {\n const model =\n typeof modelOrParams === \"string\" ? modelOrParams : modelOrParams.model;\n const params = typeof modelOrParams === \"string\" ? paramsArg : modelOrParams;\n return { model, ...params } as TParams;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAyCA,SAAgB,wCACd,WACA,QACoB;CACpB,IAAI,WAAW,KAAA,GACb;CAKF,MAAM,YAAoB,WAAW,WAAW,kBAAkB,IAAI,IAAI;CAC1E,MAAM,YAAoB,WAAW,WAAW,kBAAkB,IAC9D,QACA;CAGJ,QADyB,OAAO,YACT,GAAvB;EACE,KAAK;EACL,KAAK,WACH,OAAO;EACT,KAAK,OAEH,OAAO;EACT,KAAK,UAEH,OAAO;EACT,KAAK,QAEH,OAAO;EACT,SACE;CACJ;AACF;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAoCA,SAAgB,wCACd,OACA,iBACyC;CACzC,IAAI,OAAO,oBAAoB,aAC7B;MACK,IAAI,oBAAoB,IAAI;EAGjC,IAAI,SAAS,cAAc,KAAK,MAAM,cACpC,OAAO;EAET,OAAO;CACT,OAAO,IAAI,oBAAoB,GAAG;EAChC,IAAI,OAAO,WAAW,cAAc,GAClC,OAAO;OAEP,OAAO;CAEX,OAAO,IAAI,mBAAmB,MAC5B,OAAO;MACF,IAAI,mBAAmB,MAAM;EAClC,IAAI,OAAO,WAAW,cAAc,GAClC,OAAO;OAEP,OAAO;CAEX,OACE,OAAO;AAEX;;;;;;;;AASA,SAAgB,4BAA4B,QAGT;CACjC,IAAI,OAAO,WAAW,aACpB;CAEF,IAAI,OAAO,OAAO,iBAAiB,aACjC,OAAO,OAAO;CAEhB,IAAI,OAAO,aAAa,MACtB,OAAO;AAGX;;;;;AAMA,SAAgB,eAAe,OAAuB;CACpD,OAAO,MAAM,MAAM,GAAG,CAAC,CAAC;AAC1B;;;;;AAMA,SAAgB,gBAAgB,OAAuB;CACrD,OAAO,MAAM,MAAM,GAAG,CAAC,CAAC;AAC1B;;;;;AAMA,SAAgB,cAAc,OAAuB;CACnD,MAAM,QAAQ,MAAM,MAAM,GAAG;CAC7B,IAAI,MAAM,MAAM;CAChB,IAAI,QAAQ,WAAW,MAAM,OAAO,QAClC,MAAM;CAER,OAAO;AACT;;;;;;;AAQA,SAAgB,kBAAkB,OAAuB;CACvD,IAAI,MAAM,SAAS,OAAO,GACxB,OAAO;MACF,IAAI,MAAM,SAAS,KAAK,GAC7B,OAAO;MAEP,OAAO;AAEX;AAEA,SAAgB,yBACd,eACA,WACS;CAIT,OAAO;EAAE,OAFP,OAAO,kBAAkB,WAAW,gBAAgB,cAAc;EAEpD,GADD,OAAO,kBAAkB,WAAW,YAAY;CACrC;AAC5B"}
|
package/dist/index.cjs
CHANGED
|
@@ -1,7 +1,15 @@
|
|
|
1
1
|
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
2
|
+
const require_base = require("./chat_models/handlers/base.cjs");
|
|
3
|
+
const require_generate_content = require("./chat_models/handlers/generate_content.cjs");
|
|
4
|
+
const require_interactions = require("./chat_models/handlers/interactions.cjs");
|
|
5
|
+
const require_base$1 = require("./chat_models/base.cjs");
|
|
2
6
|
const require_index = require("./chat_models/index.cjs");
|
|
3
7
|
const require_handler = require("./utils/handler.cjs");
|
|
8
|
+
exports.BaseChatGoogle = require_base$1.BaseChatGoogle;
|
|
4
9
|
exports.ChatGoogle = require_index.ChatGoogle;
|
|
10
|
+
exports.GenerateContentApiHandler = require_generate_content.GenerateContentApiHandler;
|
|
11
|
+
exports.GoogleChatApiHandler = require_base.GoogleChatApiHandler;
|
|
5
12
|
exports.GoogleRequestCallbackHandler = require_handler.GoogleRequestCallbackHandler;
|
|
6
13
|
exports.GoogleRequestLogger = require_handler.GoogleRequestLogger;
|
|
7
14
|
exports.GoogleRequestRecorder = require_handler.GoogleRequestRecorder;
|
|
15
|
+
exports.InteractionsApiHandler = require_interactions.InteractionsApiHandler;
|
package/dist/index.d.cts
CHANGED
|
@@ -1,3 +1,8 @@
|
|
|
1
|
+
import { GoogleChatApiHandler } from "./chat_models/handlers/base.cjs";
|
|
2
|
+
import { BaseChatGoogleCallOptions, BaseChatGoogleFields, BaseChatGoogleParams, ChatGoogleFields, GenerateContentApiHandlerParams, GenerateContentFields, GenerateContentInvocationParams, GenerateContentSpecificFields, GoogleChatApiHandlerConfig, GoogleChatApiHandlerFactory, GoogleChatApiHandlerParams, InteractionsApiHandlerParams, InteractionsFields, InteractionsInvocationParams, InteractionsSpecificFields } from "./chat_models/types.cjs";
|
|
3
|
+
import { GenerateContentApiHandler } from "./chat_models/handlers/generate_content.cjs";
|
|
4
|
+
import { InteractionsApiHandler } from "./chat_models/handlers/interactions.cjs";
|
|
5
|
+
import { BaseChatGoogle } from "./chat_models/base.cjs";
|
|
1
6
|
import { ChatGoogle, ChatGoogleCallOptions, ChatGoogleParams } from "./chat_models/index.cjs";
|
|
2
7
|
import { GoogleCustomEventInfo, GoogleRequestCallbackHandler, GoogleRequestLogger, GoogleRequestRecorder } from "./utils/handler.cjs";
|
|
3
|
-
export { ChatGoogle, ChatGoogleCallOptions, ChatGoogleParams, GoogleCustomEventInfo, GoogleRequestCallbackHandler, GoogleRequestLogger, GoogleRequestRecorder };
|
|
8
|
+
export { BaseChatGoogle, type BaseChatGoogleCallOptions, type BaseChatGoogleFields, type BaseChatGoogleParams, ChatGoogle, ChatGoogleCallOptions, type ChatGoogleFields, ChatGoogleParams, GenerateContentApiHandler, type GenerateContentApiHandlerParams, type GenerateContentFields, type GenerateContentInvocationParams, type GenerateContentSpecificFields, GoogleChatApiHandler, type GoogleChatApiHandlerConfig, type GoogleChatApiHandlerFactory, type GoogleChatApiHandlerParams, GoogleCustomEventInfo, GoogleRequestCallbackHandler, GoogleRequestLogger, GoogleRequestRecorder, InteractionsApiHandler, type InteractionsApiHandlerParams, type InteractionsFields, type InteractionsInvocationParams, type InteractionsSpecificFields };
|
package/dist/index.d.ts
CHANGED
|
@@ -1,3 +1,8 @@
|
|
|
1
|
+
import { GoogleChatApiHandler } from "./chat_models/handlers/base.js";
|
|
2
|
+
import { BaseChatGoogleCallOptions, BaseChatGoogleFields, BaseChatGoogleParams, ChatGoogleFields, GenerateContentApiHandlerParams, GenerateContentFields, GenerateContentInvocationParams, GenerateContentSpecificFields, GoogleChatApiHandlerConfig, GoogleChatApiHandlerFactory, GoogleChatApiHandlerParams, InteractionsApiHandlerParams, InteractionsFields, InteractionsInvocationParams, InteractionsSpecificFields } from "./chat_models/types.js";
|
|
3
|
+
import { GenerateContentApiHandler } from "./chat_models/handlers/generate_content.js";
|
|
4
|
+
import { InteractionsApiHandler } from "./chat_models/handlers/interactions.js";
|
|
5
|
+
import { BaseChatGoogle } from "./chat_models/base.js";
|
|
1
6
|
import { ChatGoogle, ChatGoogleCallOptions, ChatGoogleParams } from "./chat_models/index.js";
|
|
2
7
|
import { GoogleCustomEventInfo, GoogleRequestCallbackHandler, GoogleRequestLogger, GoogleRequestRecorder } from "./utils/handler.js";
|
|
3
|
-
export { ChatGoogle, ChatGoogleCallOptions, ChatGoogleParams, GoogleCustomEventInfo, GoogleRequestCallbackHandler, GoogleRequestLogger, GoogleRequestRecorder };
|
|
8
|
+
export { BaseChatGoogle, type BaseChatGoogleCallOptions, type BaseChatGoogleFields, type BaseChatGoogleParams, ChatGoogle, ChatGoogleCallOptions, type ChatGoogleFields, ChatGoogleParams, GenerateContentApiHandler, type GenerateContentApiHandlerParams, type GenerateContentFields, type GenerateContentInvocationParams, type GenerateContentSpecificFields, GoogleChatApiHandler, type GoogleChatApiHandlerConfig, type GoogleChatApiHandlerFactory, type GoogleChatApiHandlerParams, GoogleCustomEventInfo, GoogleRequestCallbackHandler, GoogleRequestLogger, GoogleRequestRecorder, InteractionsApiHandler, type InteractionsApiHandlerParams, type InteractionsFields, type InteractionsInvocationParams, type InteractionsSpecificFields };
|
package/dist/index.js
CHANGED
|
@@ -1,3 +1,7 @@
|
|
|
1
|
+
import { GoogleChatApiHandler } from "./chat_models/handlers/base.js";
|
|
2
|
+
import { GenerateContentApiHandler } from "./chat_models/handlers/generate_content.js";
|
|
3
|
+
import { InteractionsApiHandler } from "./chat_models/handlers/interactions.js";
|
|
4
|
+
import { BaseChatGoogle } from "./chat_models/base.js";
|
|
1
5
|
import { ChatGoogle } from "./chat_models/index.js";
|
|
2
6
|
import { GoogleRequestCallbackHandler, GoogleRequestLogger, GoogleRequestRecorder } from "./utils/handler.js";
|
|
3
|
-
export { ChatGoogle, GoogleRequestCallbackHandler, GoogleRequestLogger, GoogleRequestRecorder };
|
|
7
|
+
export { BaseChatGoogle, ChatGoogle, GenerateContentApiHandler, GoogleChatApiHandler, GoogleRequestCallbackHandler, GoogleRequestLogger, GoogleRequestRecorder, InteractionsApiHandler };
|
package/dist/node.cjs
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
2
|
-
const require_handler = require("./utils/handler.cjs");
|
|
3
2
|
const require_node = require("./chat_models/node.cjs");
|
|
3
|
+
const require_handler = require("./utils/handler.cjs");
|
|
4
4
|
exports.ChatGoogle = require_node.ChatGoogle;
|
|
5
5
|
exports.GoogleRequestCallbackHandler = require_handler.GoogleRequestCallbackHandler;
|
|
6
6
|
exports.GoogleRequestLogger = require_handler.GoogleRequestLogger;
|
package/dist/node.d.cts
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import { GoogleCustomEventInfo, GoogleRequestCallbackHandler, GoogleRequestLogger, GoogleRequestRecorder } from "./utils/handler.cjs";
|
|
2
1
|
import { ChatGoogle as ChatGoogleNode, ChatGoogleParams as ChatGoogleNodeParams } from "./chat_models/node.cjs";
|
|
2
|
+
import { GoogleCustomEventInfo, GoogleRequestCallbackHandler, GoogleRequestLogger, GoogleRequestRecorder } from "./utils/handler.cjs";
|
|
3
3
|
export { ChatGoogleNode as ChatGoogle, type ChatGoogleNodeParams as ChatGoogleParams, GoogleCustomEventInfo, GoogleRequestCallbackHandler, GoogleRequestLogger, GoogleRequestRecorder };
|
package/dist/node.d.ts
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import { GoogleCustomEventInfo, GoogleRequestCallbackHandler, GoogleRequestLogger, GoogleRequestRecorder } from "./utils/handler.js";
|
|
2
1
|
import { ChatGoogle as ChatGoogleNode, ChatGoogleParams as ChatGoogleNodeParams } from "./chat_models/node.js";
|
|
2
|
+
import { GoogleCustomEventInfo, GoogleRequestCallbackHandler, GoogleRequestLogger, GoogleRequestRecorder } from "./utils/handler.js";
|
|
3
3
|
export { ChatGoogleNode as ChatGoogle, type ChatGoogleNodeParams as ChatGoogleParams, GoogleCustomEventInfo, GoogleRequestCallbackHandler, GoogleRequestLogger, GoogleRequestRecorder };
|
package/dist/node.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import { GoogleRequestCallbackHandler, GoogleRequestLogger, GoogleRequestRecorder } from "./utils/handler.js";
|
|
2
1
|
import { ChatGoogle as ChatGoogleNode } from "./chat_models/node.js";
|
|
2
|
+
import { GoogleRequestCallbackHandler, GoogleRequestLogger, GoogleRequestRecorder } from "./utils/handler.js";
|
|
3
3
|
export { ChatGoogleNode as ChatGoogle, GoogleRequestCallbackHandler, GoogleRequestLogger, GoogleRequestRecorder };
|
package/dist/utils/errors.cjs
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
const require_misc = require("./misc.cjs");
|
|
2
2
|
let _langchain_core_errors = require("@langchain/core/errors");
|
|
3
|
-
|
|
3
|
+
// src/utils/errors.ts
|
|
4
4
|
const ns = _langchain_core_errors.ns.sub("google");
|
|
5
5
|
const RETRYABLE_STATUS_CODES = [
|
|
6
6
|
408,
|
|
@@ -549,7 +549,6 @@ var InvalidInputError = class extends ns.brand(GoogleError, "invalid-input") {
|
|
|
549
549
|
(0, _langchain_core_errors.stampRetryable)(this, false);
|
|
550
550
|
}
|
|
551
551
|
};
|
|
552
|
-
//#endregion
|
|
553
552
|
exports.AuthError = AuthError;
|
|
554
553
|
exports.ConfigurationError = ConfigurationError;
|
|
555
554
|
exports.GoogleError = GoogleError;
|
package/dist/utils/errors.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { iife } from "./misc.js";
|
|
2
2
|
import { LangChainError, ns, stampRetryable } from "@langchain/core/errors";
|
|
3
|
-
|
|
3
|
+
// src/utils/errors.ts
|
|
4
4
|
const ns$1 = ns.sub("google");
|
|
5
5
|
const RETRYABLE_STATUS_CODES = [
|
|
6
6
|
408,
|
|
@@ -549,7 +549,6 @@ var InvalidInputError = class extends ns$1.brand(GoogleError, "invalid-input") {
|
|
|
549
549
|
stampRetryable(this, false);
|
|
550
550
|
}
|
|
551
551
|
};
|
|
552
|
-
//#endregion
|
|
553
552
|
export { AuthError, ConfigurationError, GoogleError, InvalidInputError, InvalidToolError, MalformedOutputError, NoCandidatesError, PromptBlockedError, RequestError, ToolCallNotFoundError };
|
|
554
553
|
|
|
555
554
|
//# sourceMappingURL=errors.js.map
|
package/dist/utils/gcp-auth.cjs
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
const require_const = require("../const.cjs");
|
|
2
|
-
const require_misc = require("./misc.cjs");
|
|
3
1
|
const require_errors = require("./errors.cjs");
|
|
4
|
-
|
|
2
|
+
const require_misc = require("./misc.cjs");
|
|
3
|
+
const require_const = require("../const.cjs");
|
|
4
|
+
// src/utils/gcp-auth.ts
|
|
5
5
|
/**
|
|
6
6
|
* GCP authentication utilities.
|
|
7
7
|
*
|
|
@@ -204,7 +204,6 @@ async function getGCPCredentialsAccessToken(credentials, scopes = require_const.
|
|
|
204
204
|
});
|
|
205
205
|
return await promise.then((data) => data.token);
|
|
206
206
|
}
|
|
207
|
-
//#endregion
|
|
208
207
|
exports.getGCPCredentialsAccessToken = getGCPCredentialsAccessToken;
|
|
209
208
|
exports.getGCPCustomToken = getGCPCustomToken;
|
|
210
209
|
exports.getGCPPrivateKey = getGCPPrivateKey;
|
|
@@ -1,4 +1,3 @@
|
|
|
1
|
-
//#region src/utils/gcp-auth.d.ts
|
|
2
1
|
/**
|
|
3
2
|
* GCP authentication utilities.
|
|
4
3
|
*
|
|
@@ -38,5 +37,4 @@ export interface GCPCredentials {
|
|
|
38
37
|
/** The URL for this service account's x509 certificate */
|
|
39
38
|
client_x509_cert_url: string;
|
|
40
39
|
}
|
|
41
|
-
//#endregion
|
|
42
40
|
//# sourceMappingURL=gcp-auth.d.cts.map
|
package/dist/utils/gcp-auth.d.ts
CHANGED
|
@@ -1,4 +1,3 @@
|
|
|
1
|
-
//#region src/utils/gcp-auth.d.ts
|
|
2
1
|
/**
|
|
3
2
|
* GCP authentication utilities.
|
|
4
3
|
*
|
|
@@ -38,5 +37,4 @@ export interface GCPCredentials {
|
|
|
38
37
|
/** The URL for this service account's x509 certificate */
|
|
39
38
|
client_x509_cert_url: string;
|
|
40
39
|
}
|
|
41
|
-
//#endregion
|
|
42
40
|
//# sourceMappingURL=gcp-auth.d.ts.map
|
package/dist/utils/gcp-auth.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import { VERTEX_AI_AUTH_SCOPES } from "../const.js";
|
|
2
|
-
import { iife } from "./misc.js";
|
|
3
1
|
import { AuthError } from "./errors.js";
|
|
4
|
-
|
|
2
|
+
import { iife } from "./misc.js";
|
|
3
|
+
import { VERTEX_AI_AUTH_SCOPES } from "../const.js";
|
|
4
|
+
// src/utils/gcp-auth.ts
|
|
5
5
|
/**
|
|
6
6
|
* GCP authentication utilities.
|
|
7
7
|
*
|
|
@@ -204,7 +204,6 @@ async function getGCPCredentialsAccessToken(credentials, scopes = VERTEX_AI_AUTH
|
|
|
204
204
|
});
|
|
205
205
|
return await promise.then((data) => data.token);
|
|
206
206
|
}
|
|
207
|
-
//#endregion
|
|
208
207
|
export { getGCPCredentialsAccessToken, getGCPCustomToken, getGCPPrivateKey, normalizeGCPCredentials };
|
|
209
208
|
|
|
210
209
|
//# sourceMappingURL=gcp-auth.js.map
|
package/dist/utils/handler.cjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
let _langchain_core_callbacks_base = require("@langchain/core/callbacks/base");
|
|
2
|
-
|
|
2
|
+
// src/utils/handler.ts
|
|
3
3
|
var GoogleRequestCallbackHandler = class extends _langchain_core_callbacks_base.BaseCallbackHandler {
|
|
4
4
|
customEventInfo(eventName) {
|
|
5
5
|
const names = eventName.split("-");
|
|
@@ -57,7 +57,6 @@ var GoogleRequestRecorder = class extends GoogleRequestCallbackHandler {
|
|
|
57
57
|
this.chunk.push(data);
|
|
58
58
|
}
|
|
59
59
|
};
|
|
60
|
-
//#endregion
|
|
61
60
|
exports.GoogleRequestCallbackHandler = GoogleRequestCallbackHandler;
|
|
62
61
|
exports.GoogleRequestLogger = GoogleRequestLogger;
|
|
63
62
|
exports.GoogleRequestRecorder = GoogleRequestRecorder;
|
package/dist/utils/handler.d.cts
CHANGED
|
@@ -1,5 +1,4 @@
|
|
|
1
1
|
import { BaseCallbackHandler } from "@langchain/core/callbacks/base";
|
|
2
|
-
//#region src/utils/handler.d.ts
|
|
3
2
|
export interface GoogleCustomEventInfo {
|
|
4
3
|
subEvent: string;
|
|
5
4
|
module: string;
|
|
@@ -28,5 +27,4 @@ export declare class GoogleRequestRecorder extends GoogleRequestCallbackHandler
|
|
|
28
27
|
handleCustomResponseEvent(_eventName: string, _eventInfo: GoogleCustomEventInfo, data: any, _runId: string, _tags?: string[], _metadata?: Record<string, any>): any;
|
|
29
28
|
handleCustomChunkEvent(_eventName: string, _eventInfo: GoogleCustomEventInfo, data: any, _runId: string, _tags?: string[], _metadata?: Record<string, any>): any;
|
|
30
29
|
}
|
|
31
|
-
//#endregion
|
|
32
30
|
//# sourceMappingURL=handler.d.cts.map
|
package/dist/utils/handler.d.ts
CHANGED
|
@@ -1,5 +1,4 @@
|
|
|
1
1
|
import { BaseCallbackHandler } from "@langchain/core/callbacks/base";
|
|
2
|
-
//#region src/utils/handler.d.ts
|
|
3
2
|
export interface GoogleCustomEventInfo {
|
|
4
3
|
subEvent: string;
|
|
5
4
|
module: string;
|
|
@@ -28,5 +27,4 @@ export declare class GoogleRequestRecorder extends GoogleRequestCallbackHandler
|
|
|
28
27
|
handleCustomResponseEvent(_eventName: string, _eventInfo: GoogleCustomEventInfo, data: any, _runId: string, _tags?: string[], _metadata?: Record<string, any>): any;
|
|
29
28
|
handleCustomChunkEvent(_eventName: string, _eventInfo: GoogleCustomEventInfo, data: any, _runId: string, _tags?: string[], _metadata?: Record<string, any>): any;
|
|
30
29
|
}
|
|
31
|
-
//#endregion
|
|
32
30
|
//# sourceMappingURL=handler.d.ts.map
|
package/dist/utils/handler.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { BaseCallbackHandler } from "@langchain/core/callbacks/base";
|
|
2
|
-
|
|
2
|
+
// src/utils/handler.ts
|
|
3
3
|
var GoogleRequestCallbackHandler = class extends BaseCallbackHandler {
|
|
4
4
|
customEventInfo(eventName) {
|
|
5
5
|
const names = eventName.split("-");
|
|
@@ -57,7 +57,6 @@ var GoogleRequestRecorder = class extends GoogleRequestCallbackHandler {
|
|
|
57
57
|
this.chunk.push(data);
|
|
58
58
|
}
|
|
59
59
|
};
|
|
60
|
-
//#endregion
|
|
61
60
|
export { GoogleRequestCallbackHandler, GoogleRequestLogger, GoogleRequestRecorder };
|
|
62
61
|
|
|
63
62
|
//# sourceMappingURL=handler.js.map
|
package/dist/utils/metadata.cjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
|
|
1
|
+
// src/utils/metadata.ts
|
|
2
2
|
/**
|
|
3
3
|
* Computes the delta between two token detail objects by subtracting
|
|
4
4
|
* each field in `previous` from the corresponding field in `current`.
|
|
@@ -50,7 +50,14 @@ function subtractUsageMetadata(current, previous) {
|
|
|
50
50
|
output_token_details: subtractTokenDetails(current.output_token_details, previous.output_token_details)
|
|
51
51
|
};
|
|
52
52
|
}
|
|
53
|
-
|
|
53
|
+
function usageMetadataToTokenUsage(usageMetadata) {
|
|
54
|
+
return {
|
|
55
|
+
promptTokens: usageMetadata.input_tokens,
|
|
56
|
+
completionTokens: usageMetadata.output_tokens,
|
|
57
|
+
totalTokens: usageMetadata.total_tokens
|
|
58
|
+
};
|
|
59
|
+
}
|
|
54
60
|
exports.subtractUsageMetadata = subtractUsageMetadata;
|
|
61
|
+
exports.usageMetadataToTokenUsage = usageMetadataToTokenUsage;
|
|
55
62
|
|
|
56
63
|
//# sourceMappingURL=metadata.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"metadata.cjs","names":[],"sources":["../../src/utils/metadata.ts"],"sourcesContent":["import type {\n UsageMetadata,\n InputTokenDetails,\n OutputTokenDetails,\n} from \"@langchain/core/messages\";\n\n/**\n * Computes the delta between two token detail objects by subtracting\n * each field in `previous` from the corresponding field in `current`.\n *\n * This is used to convert cumulative token detail counts (as reported\n * by the Gemini streaming API) into per-chunk deltas that can be\n * correctly summed by {@link mergeUsageMetadata} during chunk\n * concatenation.\n *\n * @param current - The cumulative token details from the current chunk.\n * @param previous - The cumulative token details from the previous chunk.\n * @returns The per-chunk delta, or `undefined` if `current` is undefined.\n */\nfunction subtractTokenDetails<T extends InputTokenDetails | OutputTokenDetails>(\n current?: T,\n previous?: T\n): T | undefined {\n if (!current) return undefined;\n if (!previous) return current;\n const result = {} as Record<string, number>;\n for (const key of Object.keys(current) as (keyof T)[]) {\n const cur = current[key] as number | undefined;\n const prev = previous[key] as number | undefined;\n if (cur !== undefined) {\n result[key as string] = cur - (prev ?? 0);\n }\n }\n return result as T;\n}\n\n/**\n * Computes the delta between two {@link UsageMetadata} objects by\n * subtracting each field in `previous` from the corresponding field in\n * `current`.\n *\n * The Gemini streaming API reports **cumulative** token counts on every\n * SSE chunk, but `@langchain/core`'s `mergeUsageMetadata` combines\n * values via addition. Emitting raw cumulative values on each\n * `AIMessageChunk` would therefore inflate the totals when chunks are\n * concatenated. This function converts cumulative values into per-chunk\n * deltas so that additive merging produces the correct final totals.\n *\n * @param current - The cumulative usage metadata from the current chunk.\n * @param previous - The cumulative usage metadata from the previous\n * chunk, or `undefined` for the first chunk in the stream.\n * @returns The per-chunk delta usage metadata.\n */\nexport function subtractUsageMetadata(\n current: UsageMetadata,\n previous?: UsageMetadata\n): UsageMetadata {\n if (!previous) return current;\n return {\n input_tokens: current.input_tokens - previous.input_tokens,\n output_tokens: current.output_tokens - previous.output_tokens,\n total_tokens: current.total_tokens - previous.total_tokens,\n input_token_details: subtractTokenDetails(\n current.input_token_details,\n previous.input_token_details\n ),\n output_token_details: subtractTokenDetails(\n current.output_token_details,\n previous.output_token_details\n ),\n };\n}\n"],"mappings":";;;;;;;;;;;;;;AAmBA,SAAS,qBACP,SACA,UACe;CACf,IAAI,CAAC,SAAS,OAAO,KAAA;CACrB,IAAI,CAAC,UAAU,OAAO;CACtB,MAAM,SAAS,CAAC;CAChB,KAAK,MAAM,OAAO,OAAO,KAAK,OAAO,GAAkB;EACrD,MAAM,MAAM,QAAQ;EACpB,MAAM,OAAO,SAAS;EACtB,IAAI,QAAQ,KAAA,GACV,OAAO,OAAiB,OAAO,QAAQ;CAE3C;CACA,OAAO;AACT;;;;;;;;;;;;;;;;;;AAmBA,SAAgB,sBACd,SACA,UACe;CACf,IAAI,CAAC,UAAU,OAAO;CACtB,OAAO;EACL,cAAc,QAAQ,eAAe,SAAS;EAC9C,eAAe,QAAQ,gBAAgB,SAAS;EAChD,cAAc,QAAQ,eAAe,SAAS;EAC9C,qBAAqB,qBACnB,QAAQ,qBACR,SAAS,mBACX;EACA,sBAAsB,qBACpB,QAAQ,sBACR,SAAS,oBACX;CACF;AACF"}
|
|
1
|
+
{"version":3,"file":"metadata.cjs","names":[],"sources":["../../src/utils/metadata.ts"],"sourcesContent":["import type {\n UsageMetadata,\n InputTokenDetails,\n OutputTokenDetails,\n} from \"@langchain/core/messages\";\n\n/**\n * Computes the delta between two token detail objects by subtracting\n * each field in `previous` from the corresponding field in `current`.\n *\n * This is used to convert cumulative token detail counts (as reported\n * by the Gemini streaming API) into per-chunk deltas that can be\n * correctly summed by {@link mergeUsageMetadata} during chunk\n * concatenation.\n *\n * @param current - The cumulative token details from the current chunk.\n * @param previous - The cumulative token details from the previous chunk.\n * @returns The per-chunk delta, or `undefined` if `current` is undefined.\n */\nfunction subtractTokenDetails<T extends InputTokenDetails | OutputTokenDetails>(\n current?: T,\n previous?: T\n): T | undefined {\n if (!current) return undefined;\n if (!previous) return current;\n const result = {} as Record<string, number>;\n for (const key of Object.keys(current) as (keyof T)[]) {\n const cur = current[key] as number | undefined;\n const prev = previous[key] as number | undefined;\n if (cur !== undefined) {\n result[key as string] = cur - (prev ?? 0);\n }\n }\n return result as T;\n}\n\n/**\n * Computes the delta between two {@link UsageMetadata} objects by\n * subtracting each field in `previous` from the corresponding field in\n * `current`.\n *\n * The Gemini streaming API reports **cumulative** token counts on every\n * SSE chunk, but `@langchain/core`'s `mergeUsageMetadata` combines\n * values via addition. Emitting raw cumulative values on each\n * `AIMessageChunk` would therefore inflate the totals when chunks are\n * concatenated. This function converts cumulative values into per-chunk\n * deltas so that additive merging produces the correct final totals.\n *\n * @param current - The cumulative usage metadata from the current chunk.\n * @param previous - The cumulative usage metadata from the previous\n * chunk, or `undefined` for the first chunk in the stream.\n * @returns The per-chunk delta usage metadata.\n */\nexport function subtractUsageMetadata(\n current: UsageMetadata,\n previous?: UsageMetadata\n): UsageMetadata {\n if (!previous) return current;\n return {\n input_tokens: current.input_tokens - previous.input_tokens,\n output_tokens: current.output_tokens - previous.output_tokens,\n total_tokens: current.total_tokens - previous.total_tokens,\n input_token_details: subtractTokenDetails(\n current.input_token_details,\n previous.input_token_details\n ),\n output_token_details: subtractTokenDetails(\n current.output_token_details,\n previous.output_token_details\n ),\n };\n}\n\nexport function usageMetadataToTokenUsage(usageMetadata: UsageMetadata) {\n return {\n promptTokens: usageMetadata.input_tokens,\n completionTokens: usageMetadata.output_tokens,\n totalTokens: usageMetadata.total_tokens,\n };\n}\n"],"mappings":";;;;;;;;;;;;;;AAmBA,SAAS,qBACP,SACA,UACe;CACf,IAAI,CAAC,SAAS,OAAO,KAAA;CACrB,IAAI,CAAC,UAAU,OAAO;CACtB,MAAM,SAAS,CAAC;CAChB,KAAK,MAAM,OAAO,OAAO,KAAK,OAAO,GAAkB;EACrD,MAAM,MAAM,QAAQ;EACpB,MAAM,OAAO,SAAS;EACtB,IAAI,QAAQ,KAAA,GACV,OAAO,OAAiB,OAAO,QAAQ;CAE3C;CACA,OAAO;AACT;;;;;;;;;;;;;;;;;;AAmBA,SAAgB,sBACd,SACA,UACe;CACf,IAAI,CAAC,UAAU,OAAO;CACtB,OAAO;EACL,cAAc,QAAQ,eAAe,SAAS;EAC9C,eAAe,QAAQ,gBAAgB,SAAS;EAChD,cAAc,QAAQ,eAAe,SAAS;EAC9C,qBAAqB,qBACnB,QAAQ,qBACR,SAAS,mBACX;EACA,sBAAsB,qBACpB,QAAQ,sBACR,SAAS,oBACX;CACF;AACF;AAEA,SAAgB,0BAA0B,eAA8B;CACtE,OAAO;EACL,cAAc,cAAc;EAC5B,kBAAkB,cAAc;EAChC,aAAa,cAAc;CAC7B;AACF"}
|