@langchain/google 0.1.12 → 0.2.0

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.
@@ -1 +1 @@
1
- {"version":3,"file":"base.js","names":[],"sources":["../../src/chat_models/base.ts"],"sourcesContent":["import {\n BaseChatModel,\n type BaseChatModelCallOptions,\n type LangSmithParams,\n type BaseChatModelParams,\n} from \"@langchain/core/language_models/chat_models\";\nimport {\n AIMessage,\n AIMessageChunk,\n AIMessageChunkFields,\n BaseMessage,\n type UsageMetadata,\n} from \"@langchain/core/messages\";\nimport { CallbackManagerForLLMRun } from \"@langchain/core/callbacks/manager\";\nimport { concat } from \"@langchain/core/utils/stream\";\nimport { ChatGenerationChunk, ChatResult } from \"@langchain/core/outputs\";\nimport { EventSourceParserStream } from \"eventsource-parser/stream\";\nimport type { BindToolsInput } from \"@langchain/core/language_models/chat_models\";\nimport type { ModelProfile } from \"@langchain/core/language_models/profile\";\nimport PROFILES from \"./profiles.js\";\nimport type {\n BaseLanguageModelInput,\n StructuredOutputMethodOptions,\n} from \"@langchain/core/language_models/base\";\nimport { Runnable, RunnableLambda } from \"@langchain/core/runnables\";\nimport {\n toJsonSchema,\n type JsonSchema7Type,\n} from \"@langchain/core/utils/json_schema\";\nimport {\n InteropZodType,\n isInteropZodSchema,\n} from \"@langchain/core/utils/types\";\n\nimport { ApiClient } from \"../clients/index.js\";\nimport { ChatGoogleFields, settableServiceTier } from \"./types.js\";\nimport { SafeJsonEventParserStream } from \"../utils/stream.js\";\nimport {\n convertAIMessageToText,\n convertGeminiCandidateToAIMessage,\n convertGeminiGenerateContentResponseToUsageMetadata,\n convertGeminiPartsToToolCalls,\n convertMessagesToGeminiContents,\n convertMessagesToGeminiSystemInstruction,\n} from \"../converters/messages.js\";\nimport {\n ConfigurationError,\n MalformedOutputError,\n NoCandidatesError,\n PromptBlockedError,\n RequestError,\n} from \"../utils/errors.js\";\nimport {\n convertToolsToGeminiTools,\n convertToolChoiceToGeminiConfig,\n schemaToGeminiParameters,\n} from \"../converters/tools.js\";\nimport {\n convertParamsToPlatformType,\n convertFieldsToSpeechConfig,\n convertFieldsToThinkingConfig,\n convertFieldsToServiceTier,\n} from \"../converters/params.js\";\nimport { Gemini } from \"./api-types.js\";\nimport { subtractUsageMetadata } from \"../utils/metadata.js\";\nimport {\n isSerializableSchema,\n SerializableSchema,\n} from \"@langchain/core/utils/standard_schema\";\nimport {\n assembleStructuredOutputPipeline,\n createContentParser,\n createFunctionCallingParser,\n} from \"@langchain/core/language_models/structured_output\";\nimport { iife } from \"../utils/misc\";\nimport ServiceTier = Gemini.ServiceTier;\n\nexport type GooglePlatformType = \"gai\" | \"gcp\";\n\nexport function getPlatformType(\n platform: GooglePlatformType | undefined,\n hasApiKey: boolean\n): GooglePlatformType {\n if (typeof platform !== \"undefined\") {\n return platform;\n } else if (hasApiKey) {\n return \"gai\";\n } else {\n return \"gcp\";\n }\n}\n\nfunction mapDetailToMediaResolution(\n detail?: ChatGoogleFields[\"detail\"]\n): Gemini.GenerationConfig[\"mediaResolution\"] | undefined {\n switch (detail) {\n case \"low\":\n return \"MEDIA_RESOLUTION_LOW\";\n case \"high\":\n return \"MEDIA_RESOLUTION_HIGH\";\n default:\n return undefined;\n }\n}\n\nexport interface BaseChatGoogleParams\n extends BaseChatModelParams, ChatGoogleFields {\n /**\n * The name of the Gemini model to use.\n *\n * Example: \"gemini-3-pro-preview\"\n */\n model: string;\n\n /**\n * Optional. The API client implementation for making HTTP requests to the Gemini API.\n * If not set, a default client will be used based on the runtime environment.\n */\n apiClient?: ApiClient;\n\n /**\n * Hostname for the API call (if this is running on GCP)\n * Usually this is computed based on location and platformType.\n **/\n endpoint?: string;\n\n /**\n * Region where the LLM is stored (if this is running on GCP)\n * Defaults to \"global\"\n **/\n location?: string;\n\n /**\n * The version of the API functions. Part of the path.\n * Usually this is computed based on platformType.\n **/\n apiVersion?: string;\n\n /**\n * What platform to run the service on.\n * If not specified, the class should determine this from other\n * means. Either way, the platform actually used will be in\n * the \"platform\" getter.\n */\n platformType?: GooglePlatformType;\n\n /**\n * For compatibility with Google's libraries, should this use Vertex?\n * The \"platformType\" parmeter takes precedence.\n */\n vertexai?: boolean;\n\n /**\n * Backwards compatibility.\n * @deprecated in favor of using `disableStreaming` or `.stream()`\n */\n streaming?: boolean;\n\n streamUsage?: boolean;\n}\n\nexport interface BaseChatGoogleCallOptions\n extends BaseChatModelCallOptions, ChatGoogleFields {}\n\nexport abstract class BaseChatGoogle<\n CallOptions extends BaseChatGoogleCallOptions = BaseChatGoogleCallOptions,\n> extends BaseChatModel<CallOptions, AIMessageChunk> {\n model: string;\n\n streaming: boolean;\n\n disableStreaming: boolean;\n\n streamUsage: boolean = true;\n\n protected _platform?: GooglePlatformType;\n\n protected _endpoint?: string;\n\n protected _customHeaders?: Record<string, string>;\n\n protected _location?: string;\n\n protected _apiVersion?: string;\n\n protected apiClient: ApiClient;\n\n constructor(protected params: BaseChatGoogleParams) {\n super(params);\n this._addVersion(\"@langchain/google\", __PKG_VERSION__);\n\n if (!params.apiClient) {\n throw new ConfigurationError(\n \"BaseChatGoogle requires an apiClient. This should be provided automatically by ChatGoogle constructors. If you're extending BaseChatGoogle directly, please provide an apiClient instance.\"\n );\n }\n this.apiClient = params.apiClient;\n\n this.model = params.model;\n this._platform = convertParamsToPlatformType(params);\n this._endpoint = params.endpoint;\n this._customHeaders = params.customHeaders;\n this._location = params.location;\n this._apiVersion = params.apiVersion;\n\n this.disableStreaming = params?.disableStreaming === true;\n this.streaming = params?.streaming === true;\n if (this.disableStreaming) this.streaming = false;\n // disable streaming in BaseChatModel if explicitly disabled\n if (params?.streaming === false) this.disableStreaming = true;\n\n this.streamUsage = params?.streamUsage ?? this.streamUsage;\n if (this.disableStreaming) this.streamUsage = false;\n }\n\n _llmType(): string {\n return \"google\";\n }\n\n protected get platformType(): GooglePlatformType | undefined {\n return this._platform;\n }\n\n protected get platform(): GooglePlatformType {\n return getPlatformType(this._platform, this.apiClient.hasApiKey());\n }\n\n protected get isVertexExpress(): boolean {\n return this.platform === \"gcp\" && this.apiClient.hasApiKey();\n }\n\n protected get apiVersion(): string {\n if (typeof this._apiVersion !== \"undefined\") {\n return this._apiVersion;\n } else if (this.platform === \"gai\") {\n return \"v1beta\";\n } else {\n return \"v1\";\n }\n }\n\n protected get location(): string {\n return this._location || \"global\";\n }\n\n protected get endpoint(): string {\n if (typeof this._endpoint !== \"undefined\") {\n return this._endpoint;\n } else if (this.platform === \"gai\") {\n return \"generativelanguage.googleapis.com\";\n } else if (this.isVertexExpress) {\n return \"aiplatform.googleapis.com\";\n } else if (this.location === \"global\") {\n // See https://docs.cloud.google.com/vertex-ai/generative-ai/docs/learn/locations#use_the_global_endpoint\n return \"aiplatform.googleapis.com\";\n } else {\n return `${this.location}-aiplatform.googleapis.com`;\n }\n }\n\n protected get publisher(): string {\n return \"google\";\n }\n\n protected get urlMethod(): string {\n return this.streaming ? \"streamGenerateContent?alt=sse\" : \"generateContent\";\n }\n\n /**\n * Returns the model profile for this instance's model, describing its\n * capabilities and constraints (e.g. max tokens, input/output modalities,\n * tool calling support).\n *\n * @example\n * ```typescript\n * const model = new ChatGoogle({ model: \"gemini-2.5-pro\" });\n * const profile = model.profile;\n * console.log(profile.maxInputTokens); // 1048576\n * console.log(profile.imageInputs); // true\n * ```\n */\n get profile(): ModelProfile {\n return PROFILES[this.model] ?? {};\n }\n\n protected async buildUrlGemini(urlMethod?: string): Promise<string> {\n return `https://${this.endpoint}/${this.apiVersion}/models/${this.model}:${\n urlMethod ?? this.urlMethod\n }`;\n }\n\n protected async buildUrlVertexExpress(urlMethod?: string): Promise<string> {\n return `https://${this.endpoint}/${this.apiVersion}/publishers/${\n this.publisher\n }/models/${this.model}:${urlMethod ?? this.urlMethod}`;\n }\n\n protected async buildUrlVertexLocation(urlMethod?: string): Promise<string> {\n const projectId = await this.apiClient.getProjectId();\n return `https://${this.endpoint}/${\n this.apiVersion\n }/projects/${projectId}/locations/${this.location}/publishers/${\n this.publisher\n }/models/${this.model}:${urlMethod ?? this.urlMethod}`;\n }\n\n protected async buildUrlVertex(urlMethod?: string): Promise<string> {\n if (this.isVertexExpress) {\n return this.buildUrlVertexExpress(urlMethod);\n } else {\n return this.buildUrlVertexLocation(urlMethod);\n }\n }\n\n protected async buildUrl(urlMethod?: string): Promise<string> {\n switch (this.platform) {\n case \"gai\":\n return this.buildUrlGemini(urlMethod);\n default:\n return this.buildUrlVertex(urlMethod);\n }\n }\n\n override invocationParams(options: this[\"ParsedCallOptions\"]) {\n const fields = combineGoogleChatModelFields(this.params, options);\n const mediaResolution =\n fields.mediaResolution ?? mapDetailToMediaResolution(fields.detail);\n\n // Convert tools to Gemini format\n const tools = fields.tools\n ? convertToolsToGeminiTools(fields.tools)\n : undefined;\n\n // Convert tool choice to Gemini function calling config\n const toolConfig = convertToolChoiceToGeminiConfig(\n options.tool_choice,\n !!(tools && tools.length > 0)\n );\n\n let responseJsonSchema:\n | JsonSchema7Type\n | Record<string, unknown>\n | undefined;\n let responseMimeType: string | undefined;\n\n if (fields.responseSchema) {\n // Convert Zod schema to JSON Schema if needed\n if (\n isInteropZodSchema(fields.responseSchema) ||\n isSerializableSchema(fields.responseSchema)\n ) {\n responseJsonSchema = toJsonSchema(fields.responseSchema);\n } else {\n responseJsonSchema = fields.responseSchema as Record<string, unknown>;\n }\n // Automatically set responseMimeType to \"application/json\" when schema is provided\n responseMimeType = \"application/json\";\n }\n\n return {\n ...(tools && tools.length > 0 ? { tools } : {}),\n ...(toolConfig ? { toolConfig } : {}),\n safetySettings: fields.safetySettings,\n generationConfig: {\n temperature: fields.temperature,\n topP: fields.topP,\n topK: fields.topK,\n maxOutputTokens: fields.maxOutputTokens,\n presencePenalty: fields.presencePenalty,\n frequencyPenalty: fields.frequencyPenalty,\n stopSequences: fields.stopSequences,\n ...(responseMimeType ? { responseMimeType } : {}),\n ...(responseJsonSchema ? { responseJsonSchema } : {}),\n ...(fields.responseModalities && fields.responseModalities.length > 0\n ? { responseModalities: fields.responseModalities }\n : {}),\n candidateCount: 1,\n seed: fields.seed,\n responseLogprobs: fields.responseLogprobs,\n logprobs: fields.logprobs,\n ...(fields.enableEnhancedCivicAnswers !== undefined\n ? { enableEnhancedCivicAnswers: fields.enableEnhancedCivicAnswers }\n : {}),\n thinkingConfig: convertFieldsToThinkingConfig(this.model, fields),\n speechConfig: convertFieldsToSpeechConfig(fields),\n ...(fields.imageConfig ? { imageConfig: fields.imageConfig } : {}),\n ...(mediaResolution ? { mediaResolution } : {}),\n },\n ...convertFieldsToServiceTier(this.platform, fields),\n };\n }\n\n getLsParams(options: this[\"ParsedCallOptions\"]): LangSmithParams {\n const params = this.invocationParams(options);\n return {\n ls_provider: this.platform === \"gcp\" ? \"google_vertexai\" : \"google_genai\",\n ls_model_name: this.model,\n ls_model_type: \"chat\",\n ls_temperature: params.generationConfig?.temperature ?? undefined,\n ls_max_tokens: params.generationConfig?.maxOutputTokens ?? undefined,\n ls_stop: options.stop,\n };\n }\n\n getHeaders(options: this[\"ParsedCallOptions\"]): HeadersInit {\n const fields = combineGoogleChatModelFields(this.params, options);\n\n // The priority type is set via header only for Vertex\n const priorityHeaders: Record<string, string> =\n this.platform === \"gcp\" &&\n typeof fields.serviceTier !== \"undefined\" &&\n settableServiceTier.includes(fields.serviceTier)\n ? { \"X-Vertex-AI-LLM-Shared-Request-Type\": fields.serviceTier }\n : {};\n\n return {\n \"Content-Type\": \"application/json\",\n ...priorityHeaders,\n ...this._customHeaders,\n ...options.customHeaders,\n };\n }\n\n async _generate(\n messages: BaseMessage[],\n options: this[\"ParsedCallOptions\"],\n runManager?: CallbackManagerForLLMRun\n ): Promise<ChatResult> {\n if (this.streaming) {\n const stream = await this._streamResponseChunks(\n messages,\n options,\n runManager\n );\n let finalChunk: ChatGenerationChunk | null = null;\n for await (const chunk of stream) {\n finalChunk = !finalChunk ? chunk : concat(finalChunk, chunk);\n }\n if (\n typeof finalChunk?.message?.content === \"string\" &&\n typeof (\n finalChunk?.message?.additional_kwargs\n ?.originalTextContentBlock as Record<string, unknown>\n )?.text === \"string\"\n ) {\n (\n finalChunk.message.additional_kwargs\n .originalTextContentBlock as Record<string, unknown>\n ).text = finalChunk.message.content;\n }\n return {\n generations: finalChunk ? [finalChunk] : [],\n };\n }\n\n const url = await this.buildUrl();\n const headers = this.getHeaders(options);\n const body = {\n ...this.invocationParams(options),\n systemInstruction: convertMessagesToGeminiSystemInstruction(messages),\n contents: convertMessagesToGeminiContents(messages),\n };\n\n const moduleName = this.constructor.name;\n await runManager?.handleCustomEvent(`google-request-${moduleName}`, {\n url,\n headers,\n body,\n });\n\n const response = await this.apiClient.fetch(\n new Request(url, {\n method: \"POST\",\n headers,\n body: JSON.stringify(body),\n signal: options.signal,\n })\n );\n\n if (!response.ok) {\n const error = await RequestError.fromResponse(response);\n await runManager?.handleCustomEvent(`google-response-${moduleName}`, {\n error,\n });\n throw error;\n }\n\n const data: Gemini.GenerateContentResponse = await response.json();\n await runManager?.handleCustomEvent(`google-response-${moduleName}`, {\n data,\n url: response.url,\n headers: Array.from(response.headers.entries()),\n status: response.status,\n statusText: response.statusText,\n });\n\n // Check for prompt feedback errors\n if (data.promptFeedback?.blockReason) {\n throw PromptBlockedError.fromPromptFeedback(data.promptFeedback);\n }\n\n // Check if we have candidates\n if (!data.candidates || data.candidates.length === 0) {\n throw new NoCandidatesError();\n }\n\n // Use the first candidate\n const candidate = data.candidates[0];\n const message = convertGeminiCandidateToAIMessage(candidate);\n\n // Extract text content from the message\n const text = convertAIMessageToText(message);\n\n const usageMetadata =\n convertGeminiGenerateContentResponseToUsageMetadata(data);\n message.usage_metadata = usageMetadata;\n\n const serviceTier: ServiceTier = iife((): ServiceTier => {\n // @ts-expect-error - trafficType is defined on Vertex, so isn't in the OpenAPI spec\n const trafficType: string | undefined = data.usageMetadata?.trafficType;\n\n // AI Studio replies with actual service type in the header\n const serviceTierHeader: string | null = response.headers.get(\n \"x-gemini-service-tier\"\n );\n\n if (trafficType?.startsWith(\"ON_DEMAND_\")) {\n return trafficType?.substring(\"ON_DEMAND_\".length).toLowerCase();\n }\n return serviceTierHeader || \"standard\";\n });\n\n return {\n generations: [\n {\n text,\n message,\n generationInfo: {\n finishReason: candidate.finishReason,\n finishMessage: candidate.finishMessage,\n safetyRatings: candidate.safetyRatings,\n citationMetadata: candidate.citationMetadata,\n tokenCount: candidate.tokenCount,\n },\n },\n ],\n llmOutput: {\n tokenUsage: usageMetadata,\n model: data.modelVersion,\n responseId: data.responseId,\n usageMetadata,\n serviceTier,\n },\n };\n }\n\n async *_streamResponseChunks(\n messages: BaseMessage[],\n options: this[\"ParsedCallOptions\"],\n runManager?: CallbackManagerForLLMRun\n ): AsyncGenerator<ChatGenerationChunk> {\n const streamUsage: boolean = this.streamUsage ?? true;\n\n const body = {\n ...this.invocationParams(options),\n systemInstruction: convertMessagesToGeminiSystemInstruction(messages),\n contents: convertMessagesToGeminiContents(messages),\n };\n\n const url = await this.buildUrl(\"streamGenerateContent?alt=sse\");\n const headers = this.getHeaders(options);\n const moduleName = this.constructor.name;\n await runManager?.handleCustomEvent(`google-request-${moduleName}`, {\n url,\n headers,\n body,\n });\n\n const response = await this.apiClient.fetch(\n new Request(url, {\n method: \"POST\",\n headers,\n body: JSON.stringify(body),\n signal: options.signal,\n })\n );\n\n await runManager?.handleCustomEvent(`google-response-${moduleName}`, {\n url: response.url,\n headers: Array.from(response.headers.entries()),\n status: response.status,\n statusText: response.statusText,\n });\n\n if (!response.ok) {\n const error = await RequestError.fromResponse(response);\n await runManager?.handleCustomEvent(`google-response-${moduleName}`, {\n error,\n });\n throw error;\n }\n\n if (response.body) {\n let previousUsage: UsageMetadata | undefined;\n const stream = response.body\n .pipeThrough(new TextDecoderStream())\n .pipeThrough(new EventSourceParserStream())\n .pipeThrough(\n new SafeJsonEventParserStream<Gemini.GenerateContentResponse>()\n )\n .pipeThrough(\n new TransformStream<\n Gemini.GenerateContentResponse,\n ChatGenerationChunk\n >({\n transform(chunk, controller) {\n // oxlint-disable-next-line no-void\n void runManager?.handleCustomEvent(`google-chunk-${moduleName}`, {\n chunk,\n });\n if (chunk === null) {\n controller.enqueue(\n new ChatGenerationChunk({\n text: \"\",\n message: new AIMessageChunk({ content: \"\" }),\n generationInfo: { finishReason: \"stop\" },\n })\n );\n return;\n }\n\n // Extract text delta from the chunk\n const candidate = chunk.candidates?.[0];\n if (!candidate) {\n return;\n }\n\n const message = convertGeminiCandidateToAIMessage(candidate);\n const text = convertAIMessageToText(message);\n\n const parts = candidate.content?.parts ?? [];\n const toolCalls = convertGeminiPartsToToolCalls(parts);\n\n // Only emit if we have content\n if (parts.length > 0 || candidate.finishReason) {\n const messageChunkParams: AIMessageChunkFields = {\n content: message.content,\n tool_calls: toolCalls,\n response_metadata: {\n model_provider: \"google\",\n },\n additional_kwargs: {\n ...(message.additional_kwargs.originalTextContentBlock\n ? {\n originalTextContentBlock:\n message.additional_kwargs.originalTextContentBlock,\n }\n : {}),\n ...(candidate.finishReason\n ? {\n finishReason: candidate.finishReason,\n finishMessage: candidate.finishMessage,\n }\n : {}),\n },\n };\n\n if (chunk?.usageMetadata && streamUsage) {\n const cumulative =\n convertGeminiGenerateContentResponseToUsageMetadata(chunk);\n messageChunkParams.usage_metadata = subtractUsageMetadata(\n cumulative,\n previousUsage\n );\n previousUsage = cumulative;\n }\n const messageChunk = new AIMessageChunk(messageChunkParams);\n\n controller.enqueue(\n new ChatGenerationChunk({\n text: text,\n message: messageChunk,\n generationInfo: {\n ...(candidate.finishReason && {\n finishReason: candidate.finishReason,\n finishMessage: candidate.finishMessage,\n }),\n ...(candidate.safetyRatings && {\n safetyRatings: candidate.safetyRatings,\n }),\n },\n })\n );\n }\n },\n })\n );\n\n const reader = stream.getReader();\n try {\n while (true) {\n const { done, value } = await reader.read();\n if (done) break;\n yield value;\n await runManager?.handleLLMNewToken(\n value.text ?? \"\",\n undefined,\n undefined,\n undefined,\n undefined,\n { chunk: value }\n );\n }\n } finally {\n reader.releaseLock();\n }\n }\n }\n\n /**\n * Bind tool-like objects to this chat model.\n *\n * @param tools A list of tool definitions to bind to this chat model.\n * Can be a structured tool, an OpenAI formatted tool, or a Gemini function declaration.\n * @param kwargs Any additional parameters to bind.\n */\n bindTools(\n tools: BindToolsInput[],\n kwargs?: Partial<CallOptions>\n ): Runnable<BaseMessage[], AIMessageChunk, CallOptions> {\n return this.withConfig({\n ...kwargs,\n tools,\n } as Partial<CallOptions>);\n }\n\n withStructuredOutput<\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n RunOutput extends Record<string, any> = Record<string, any>,\n >(\n outputSchema:\n | InteropZodType<RunOutput>\n | SerializableSchema<RunOutput>\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n | Record<string, any>,\n config?: StructuredOutputMethodOptions<false>\n ): Runnable<BaseLanguageModelInput, RunOutput>;\n\n withStructuredOutput<\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n RunOutput extends Record<string, any> = Record<string, any>,\n >(\n outputSchema:\n | InteropZodType<RunOutput>\n | SerializableSchema<RunOutput>\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n | Record<string, any>,\n config?: StructuredOutputMethodOptions<true>\n ): Runnable<BaseLanguageModelInput, { raw: BaseMessage; parsed: RunOutput }>;\n\n withStructuredOutput<\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n RunOutput extends Record<string, any> = Record<string, any>,\n >(\n outputSchema:\n | InteropZodType<RunOutput>\n | SerializableSchema<RunOutput>\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n | Record<string, any>,\n config?: StructuredOutputMethodOptions<boolean>\n ):\n | Runnable<BaseLanguageModelInput, RunOutput>\n | Runnable<BaseLanguageModelInput, { raw: BaseMessage; parsed: RunOutput }>;\n\n /**\n * Get structured output from the model based on a schema.\n *\n * This method supports two modes:\n * - `jsonMode`: Uses `responseSchema` to get JSON responses directly (preferred for structured outputs)\n * - `functionCalling`: Uses function calling with tools (default, for compatibility)\n *\n * @param outputSchema - The schema to use for structured output (Zod schema or JSON Schema)\n * @param config - Configuration options including method and whether to include raw response\n * @returns A Runnable that returns the parsed structured output\n */\n withStructuredOutput<\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n RunOutput extends Record<string, any> = Record<string, any>,\n >(\n outputSchema:\n | InteropZodType<RunOutput>\n | SerializableSchema<RunOutput>\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n | Record<string, any>,\n config?: StructuredOutputMethodOptions<boolean>\n ):\n | Runnable<BaseLanguageModelInput, RunOutput>\n | Runnable<\n BaseLanguageModelInput,\n { raw: BaseMessage; parsed: RunOutput }\n > {\n let llm: Runnable<BaseMessage[], AIMessageChunk, CallOptions>;\n let outputParser: Runnable<BaseMessage, RunOutput>;\n\n const { schema, name, includeRaw } = {\n ...config,\n schema: outputSchema,\n };\n let method = config?.method ?? \"functionCalling\";\n\n if (method === \"jsonMode\") {\n console.warn(\n `\"jsonMode\" is not supported for Google models. Falling back to \"jsonSchema\".`\n );\n method = \"jsonSchema\";\n }\n\n if (method === \"jsonSchema\") {\n // Use JSON mode with responseSchema\n llm = this.withConfig({\n responseSchema: schema,\n } as Partial<CallOptions>);\n\n outputParser = RunnableLambda.from<BaseMessage, RunOutput>(\n async (input: BaseMessage): Promise<RunOutput> => {\n if (\n !AIMessage.isInstance(input) &&\n !AIMessageChunk.isInstance(input)\n ) {\n throw new MalformedOutputError({\n message: \"Input is not an AIMessage or AIMessageChunk.\",\n });\n }\n\n if (!input.text) {\n throw new MalformedOutputError({\n message:\n \"No content found in response. Cannot parse structured output.\",\n });\n }\n\n // Parse JSON and validate with schema\n const parser = createContentParser(schema);\n return await parser.parse(input.text);\n }\n );\n } else if (method === \"functionCalling\") {\n // Use function calling mode\n let functionName = name ?? \"extract\";\n let geminiFunctionDeclaration: Gemini.Tools.FunctionDeclaration;\n\n if (isInteropZodSchema(schema) || isSerializableSchema(schema)) {\n const jsonSchema = schemaToGeminiParameters(schema);\n const description =\n typeof jsonSchema.description === \"string\"\n ? jsonSchema.description\n : \"A function available to call.\";\n geminiFunctionDeclaration = {\n name: functionName,\n description,\n parameters: jsonSchema as Gemini.Tools.Schema,\n };\n } else if (\n typeof schema.name === \"string\" &&\n typeof schema.parameters === \"object\" &&\n schema.parameters != null\n ) {\n geminiFunctionDeclaration = schema as Gemini.Tools.FunctionDeclaration;\n functionName = schema.name;\n } else {\n // We are providing the schema for *just* the parameters\n const parameters = schemaToGeminiParameters(schema);\n geminiFunctionDeclaration = {\n name: functionName,\n description: (schema as { description?: string }).description ?? \"\",\n parameters,\n };\n }\n\n const tools: Gemini.Tool[] = [\n {\n functionDeclarations: [geminiFunctionDeclaration],\n },\n ];\n llm = this.bindTools(tools).withConfig({\n tool_choice: functionName,\n } as Partial<CallOptions>);\n\n outputParser = createFunctionCallingParser(schema, functionName);\n } else {\n throw new ConfigurationError(\n `Unrecognized structured output method '${method}'. Expected 'functionCalling' or 'jsonSchema'`\n );\n }\n\n return assembleStructuredOutputPipeline(\n llm,\n outputParser,\n includeRaw,\n includeRaw\n ? \"ChatGoogleStructuredOutputRunnable\"\n : \"ChatGoogleStructuredOutput\"\n );\n }\n}\n\ntype CombinableFields = Omit<BaseChatGoogleParams, \"model\">;\n\nexport function combineGoogleChatModelFields(\n a: CombinableFields,\n b: CombinableFields,\n ...rest: CombinableFields[]\n): CombinableFields {\n const combined: CombinableFields = {\n temperature: b.temperature ?? a.temperature,\n topP: b.topP ?? a.topP,\n topK: b.topK ?? a.topK,\n maxOutputTokens: b.maxOutputTokens ?? a.maxOutputTokens,\n presencePenalty: b.presencePenalty ?? a.presencePenalty,\n frequencyPenalty: b.frequencyPenalty ?? a.frequencyPenalty,\n stopSequences: b.stopSequences ?? a.stopSequences,\n seed: b.seed ?? a.seed,\n responseLogprobs: b.responseLogprobs ?? a.responseLogprobs,\n logprobs: b.logprobs ?? a.logprobs,\n safetySettings: b.safetySettings ?? a.safetySettings,\n responseSchema: b.responseSchema ?? a.responseSchema,\n tools: b.tools ?? a.tools,\n responseModalities: b.responseModalities ?? a.responseModalities,\n enableEnhancedCivicAnswers:\n b.enableEnhancedCivicAnswers ?? a.enableEnhancedCivicAnswers,\n speechConfig: b.speechConfig ?? a.speechConfig,\n imageConfig: b.imageConfig ?? a.imageConfig,\n mediaResolution: b.mediaResolution ?? a.mediaResolution,\n detail: b.detail ?? a.detail,\n maxReasoningTokens: b.maxReasoningTokens ?? a.maxReasoningTokens,\n thinkingBudget: b.thinkingBudget ?? a.thinkingBudget,\n reasoningEffort: b.reasoningEffort ?? a.reasoningEffort,\n thinkingLevel: b.thinkingLevel ?? a.thinkingLevel,\n serviceTier: b.serviceTier ?? a.serviceTier,\n };\n if (rest.length > 0) {\n return combineGoogleChatModelFields(combined, rest[0], ...rest.slice(1));\n }\n return combined;\n}\n\nexport function getGoogleChatModelParams<TParams extends BaseChatGoogleParams>(\n modelOrParams: string | TParams,\n paramsArg?: Omit<TParams, \"model\">\n): TParams {\n const model =\n typeof modelOrParams === \"string\" ? modelOrParams : modelOrParams.model;\n const params = typeof modelOrParams === \"string\" ? paramsArg : modelOrParams;\n return { model, ...params } as TParams;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AA+EA,SAAgB,gBACd,UACA,WACoB;AACpB,KAAI,OAAO,aAAa,YACtB,QAAO;UACE,UACT,QAAO;KAEP,QAAO;;AAIX,SAAS,2BACP,QACwD;AACxD,SAAQ,QAAR;EACE,KAAK,MACH,QAAO;EACT,KAAK,OACH,QAAO;EACT,QACE;;;AA+DN,IAAsB,iBAAtB,cAEU,cAA2C;CACnD;CAEA;CAEA;CAEA,cAAuB;CAEvB;CAEA;CAEA;CAEA;CAEA;CAEA;CAEA,YAAY,QAAwC;AAClD,QAAM,OAAO;AADO,OAAA,SAAA;AAEpB,OAAK,YAAY,qBAAA,SAAqC;AAEtD,MAAI,CAAC,OAAO,UACV,OAAM,IAAI,mBACR,6LACD;AAEH,OAAK,YAAY,OAAO;AAExB,OAAK,QAAQ,OAAO;AACpB,OAAK,YAAY,4BAA4B,O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AClC,aAAa,EAAE,eAAe,EAAE;EAChC,iBAAiB,EAAE,mBAAmB,EAAE;EACxC,QAAQ,EAAE,UAAU,EAAE;EACtB,oBAAoB,EAAE,sBAAsB,EAAE;EAC9C,gBAAgB,EAAE,kBAAkB,EAAE;EACtC,iBAAiB,EAAE,mBAAmB,EAAE;EACxC,eAAe,EAAE,iBAAiB,EAAE;EACpC,aAAa,EAAE,eAAe,EAAE;EACjC;AACD,KAAI,KAAK,SAAS,EAChB,QAAO,6BAA6B,UAAU,KAAK,IAAI,GAAG,KAAK,MAAM,EAAE,CAAC;AAE1E,QAAO;;AAGT,SAAgB,yBACd,eACA,WACS;AAIT,QAAO;EAAE,OAFP,OAAO,kBAAkB,WAAW,gBAAgB,cAAc;EAEpD,GADD,OAAO,kBAAkB,WAAW,YAAY;EACpC"}
1
+ {"version":3,"file":"base.js","names":[],"sources":["../../src/chat_models/base.ts"],"sourcesContent":["import {\n BaseChatModel,\n type BaseChatModelCallOptions,\n type LangSmithParams,\n type BaseChatModelParams,\n} from \"@langchain/core/language_models/chat_models\";\nimport {\n AIMessage,\n AIMessageChunk,\n AIMessageChunkFields,\n BaseMessage,\n type UsageMetadata,\n} from \"@langchain/core/messages\";\nimport { CallbackManagerForLLMRun } from \"@langchain/core/callbacks/manager\";\nimport type { ChatModelStreamEvent } from \"@langchain/core/language_models/event\";\nimport { convertGoogleGeminiStream } from \"../utils/stream_events.js\";\nimport { concat } from \"@langchain/core/utils/stream\";\nimport { ChatGenerationChunk, ChatResult } from \"@langchain/core/outputs\";\nimport { EventSourceParserStream } from \"eventsource-parser/stream\";\nimport type { BindToolsInput } from \"@langchain/core/language_models/chat_models\";\nimport type { ModelProfile } from \"@langchain/core/language_models/profile\";\nimport PROFILES from \"./profiles.js\";\nimport type {\n BaseLanguageModelInput,\n StructuredOutputMethodOptions,\n} from \"@langchain/core/language_models/base\";\nimport { Runnable, RunnableLambda } from \"@langchain/core/runnables\";\nimport {\n toJsonSchema,\n type JsonSchema7Type,\n} from \"@langchain/core/utils/json_schema\";\nimport {\n InteropZodType,\n isInteropZodSchema,\n} from \"@langchain/core/utils/types\";\n\nimport { ApiClient } from \"../clients/index.js\";\nimport { ChatGoogleFields, settableServiceTier } from \"./types.js\";\nimport { SafeJsonEventParserStream } from \"../utils/stream.js\";\nimport {\n convertAIMessageToText,\n convertGeminiCandidateToAIMessage,\n convertGeminiGenerateContentResponseToUsageMetadata,\n convertGeminiPartsToToolCalls,\n convertMessagesToGeminiContents,\n convertMessagesToGeminiSystemInstruction,\n} from \"../converters/messages.js\";\nimport {\n ConfigurationError,\n MalformedOutputError,\n NoCandidatesError,\n PromptBlockedError,\n RequestError,\n} from \"../utils/errors.js\";\nimport {\n convertToolsToGeminiTools,\n convertToolChoiceToGeminiConfig,\n schemaToGeminiParameters,\n} from \"../converters/tools.js\";\nimport {\n convertParamsToPlatformType,\n convertFieldsToSpeechConfig,\n convertFieldsToThinkingConfig,\n convertFieldsToServiceTier,\n} from \"../converters/params.js\";\nimport { Gemini } from \"./api-types.js\";\nimport { subtractUsageMetadata } from \"../utils/metadata.js\";\nimport {\n isSerializableSchema,\n SerializableSchema,\n} from \"@langchain/core/utils/standard_schema\";\nimport {\n assembleStructuredOutputPipeline,\n createContentParser,\n createFunctionCallingParser,\n} from \"@langchain/core/language_models/structured_output\";\nimport { iife } from \"../utils/misc\";\nimport ServiceTier = Gemini.ServiceTier;\n\nexport type GooglePlatformType = \"gai\" | \"gcp\";\n\nexport function getPlatformType(\n platform: GooglePlatformType | undefined,\n hasApiKey: boolean\n): GooglePlatformType {\n if (typeof platform !== \"undefined\") {\n return platform;\n } else if (hasApiKey) {\n return \"gai\";\n } else {\n return \"gcp\";\n }\n}\n\nfunction usageMetadataToTokenUsage(usageMetadata: UsageMetadata) {\n return {\n promptTokens: usageMetadata.input_tokens,\n completionTokens: usageMetadata.output_tokens,\n totalTokens: usageMetadata.total_tokens,\n };\n}\n\nfunction mapDetailToMediaResolution(\n detail?: ChatGoogleFields[\"detail\"]\n): Gemini.GenerationConfig[\"mediaResolution\"] | undefined {\n switch (detail) {\n case \"low\":\n return \"MEDIA_RESOLUTION_LOW\";\n case \"high\":\n return \"MEDIA_RESOLUTION_HIGH\";\n default:\n return undefined;\n }\n}\n\nexport interface BaseChatGoogleParams\n extends BaseChatModelParams, ChatGoogleFields {\n /**\n * The name of the Gemini model to use.\n *\n * Example: \"gemini-3-pro-preview\"\n */\n model: string;\n\n /**\n * Optional. The API client implementation for making HTTP requests to the Gemini API.\n * If not set, a default client will be used based on the runtime environment.\n */\n apiClient?: ApiClient;\n\n /**\n * Hostname for the API call (if this is running on GCP)\n * Usually this is computed based on location and platformType.\n **/\n endpoint?: string;\n\n /**\n * Region where the LLM is stored (if this is running on GCP)\n * Defaults to \"global\"\n **/\n location?: string;\n\n /**\n * The version of the API functions. Part of the path.\n * Usually this is computed based on platformType.\n **/\n apiVersion?: string;\n\n /**\n * What platform to run the service on.\n * If not specified, the class should determine this from other\n * means. Either way, the platform actually used will be in\n * the \"platform\" getter.\n */\n platformType?: GooglePlatformType;\n\n /**\n * For compatibility with Google's libraries, should this use Vertex?\n * The \"platformType\" parmeter takes precedence.\n */\n vertexai?: boolean;\n\n /**\n * Backwards compatibility.\n * @deprecated in favor of using `disableStreaming` or `.stream()`\n */\n streaming?: boolean;\n\n streamUsage?: boolean;\n}\n\nexport interface BaseChatGoogleCallOptions\n extends BaseChatModelCallOptions, ChatGoogleFields {}\n\nexport abstract class BaseChatGoogle<\n CallOptions extends BaseChatGoogleCallOptions = BaseChatGoogleCallOptions,\n> extends BaseChatModel<CallOptions, AIMessageChunk> {\n model: string;\n\n streaming: boolean;\n\n disableStreaming: boolean;\n\n streamUsage: boolean = true;\n\n protected _platform?: GooglePlatformType;\n\n protected _endpoint?: string;\n\n protected _customHeaders?: Record<string, string>;\n\n protected _location?: string;\n\n protected _apiVersion?: string;\n\n protected apiClient: ApiClient;\n\n constructor(protected params: BaseChatGoogleParams) {\n super(params);\n this._addVersion(\"@langchain/google\", __PKG_VERSION__);\n\n if (!params.apiClient) {\n throw new ConfigurationError(\n \"BaseChatGoogle requires an apiClient. This should be provided automatically by ChatGoogle constructors. If you're extending BaseChatGoogle directly, please provide an apiClient instance.\"\n );\n }\n this.apiClient = params.apiClient;\n\n this.model = params.model;\n this._platform = convertParamsToPlatformType(params);\n this._endpoint = params.endpoint;\n this._customHeaders = params.customHeaders;\n this._location = params.location;\n this._apiVersion = params.apiVersion;\n\n this.disableStreaming = params?.disableStreaming === true;\n this.streaming = params?.streaming === true;\n if (this.disableStreaming) this.streaming = false;\n // disable streaming in BaseChatModel if explicitly disabled\n if (params?.streaming === false) this.disableStreaming = true;\n\n this.streamUsage = params?.streamUsage ?? this.streamUsage;\n if (this.disableStreaming) this.streamUsage = false;\n }\n\n _llmType(): string {\n return \"google\";\n }\n\n protected get platformType(): GooglePlatformType | undefined {\n return this._platform;\n }\n\n protected get platform(): GooglePlatformType {\n return getPlatformType(this._platform, this.apiClient.hasApiKey());\n }\n\n protected get isVertexExpress(): boolean {\n return this.platform === \"gcp\" && this.apiClient.hasApiKey();\n }\n\n protected get apiVersion(): string {\n if (typeof this._apiVersion !== \"undefined\") {\n return this._apiVersion;\n } else if (this.platform === \"gai\") {\n return \"v1beta\";\n } else {\n return \"v1\";\n }\n }\n\n protected get location(): string {\n return this._location || \"global\";\n }\n\n protected get endpoint(): string {\n if (typeof this._endpoint !== \"undefined\") {\n return this._endpoint;\n } else if (this.platform === \"gai\") {\n return \"generativelanguage.googleapis.com\";\n } else if (this.isVertexExpress) {\n return \"aiplatform.googleapis.com\";\n } else if (this.location === \"global\") {\n // See https://docs.cloud.google.com/vertex-ai/generative-ai/docs/learn/locations#use_the_global_endpoint\n return \"aiplatform.googleapis.com\";\n } else {\n return `${this.location}-aiplatform.googleapis.com`;\n }\n }\n\n protected get publisher(): string {\n return \"google\";\n }\n\n protected get urlMethod(): string {\n return this.streaming ? \"streamGenerateContent?alt=sse\" : \"generateContent\";\n }\n\n /**\n * Returns the model profile for this instance's model, describing its\n * capabilities and constraints (e.g. max tokens, input/output modalities,\n * tool calling support).\n *\n * @example\n * ```typescript\n * const model = new ChatGoogle({ model: \"gemini-2.5-pro\" });\n * const profile = model.profile;\n * console.log(profile.maxInputTokens); // 1048576\n * console.log(profile.imageInputs); // true\n * ```\n */\n get profile(): ModelProfile {\n return PROFILES[this.model] ?? {};\n }\n\n protected async buildUrlGemini(urlMethod?: string): Promise<string> {\n return `https://${this.endpoint}/${this.apiVersion}/models/${this.model}:${\n urlMethod ?? this.urlMethod\n }`;\n }\n\n protected async buildUrlVertexExpress(urlMethod?: string): Promise<string> {\n return `https://${this.endpoint}/${this.apiVersion}/publishers/${\n this.publisher\n }/models/${this.model}:${urlMethod ?? this.urlMethod}`;\n }\n\n protected async buildUrlVertexLocation(urlMethod?: string): Promise<string> {\n const projectId = await this.apiClient.getProjectId();\n return `https://${this.endpoint}/${\n this.apiVersion\n }/projects/${projectId}/locations/${this.location}/publishers/${\n this.publisher\n }/models/${this.model}:${urlMethod ?? this.urlMethod}`;\n }\n\n protected async buildUrlVertex(urlMethod?: string): Promise<string> {\n if (this.isVertexExpress) {\n return this.buildUrlVertexExpress(urlMethod);\n } else {\n return this.buildUrlVertexLocation(urlMethod);\n }\n }\n\n protected async buildUrl(urlMethod?: string): Promise<string> {\n switch (this.platform) {\n case \"gai\":\n return this.buildUrlGemini(urlMethod);\n default:\n return this.buildUrlVertex(urlMethod);\n }\n }\n\n override invocationParams(options: this[\"ParsedCallOptions\"]) {\n const fields = combineGoogleChatModelFields(this.params, options);\n const mediaResolution =\n fields.mediaResolution ?? mapDetailToMediaResolution(fields.detail);\n\n // Convert tools to Gemini format\n const tools = fields.tools\n ? convertToolsToGeminiTools(fields.tools)\n : undefined;\n\n // Convert tool choice to Gemini function calling config\n const toolConfig = convertToolChoiceToGeminiConfig(\n options.tool_choice,\n !!(tools && tools.length > 0)\n );\n\n let responseJsonSchema:\n | JsonSchema7Type\n | Record<string, unknown>\n | undefined;\n let responseMimeType: string | undefined;\n\n if (fields.responseSchema) {\n // Convert Zod schema to JSON Schema if needed\n if (\n isInteropZodSchema(fields.responseSchema) ||\n isSerializableSchema(fields.responseSchema)\n ) {\n responseJsonSchema = toJsonSchema(fields.responseSchema);\n } else {\n responseJsonSchema = fields.responseSchema as Record<string, unknown>;\n }\n // Automatically set responseMimeType to \"application/json\" when schema is provided\n responseMimeType = \"application/json\";\n }\n\n return {\n ...(tools && tools.length > 0 ? { tools } : {}),\n ...(toolConfig ? { toolConfig } : {}),\n safetySettings: fields.safetySettings,\n generationConfig: {\n temperature: fields.temperature,\n topP: fields.topP,\n topK: fields.topK,\n maxOutputTokens: fields.maxOutputTokens,\n presencePenalty: fields.presencePenalty,\n frequencyPenalty: fields.frequencyPenalty,\n stopSequences: fields.stopSequences,\n ...(responseMimeType ? { responseMimeType } : {}),\n ...(responseJsonSchema ? { responseJsonSchema } : {}),\n ...(fields.responseModalities && fields.responseModalities.length > 0\n ? { responseModalities: fields.responseModalities }\n : {}),\n candidateCount: 1,\n seed: fields.seed,\n responseLogprobs: fields.responseLogprobs,\n logprobs: fields.logprobs,\n ...(fields.enableEnhancedCivicAnswers !== undefined\n ? { enableEnhancedCivicAnswers: fields.enableEnhancedCivicAnswers }\n : {}),\n thinkingConfig: convertFieldsToThinkingConfig(this.model, fields),\n speechConfig: convertFieldsToSpeechConfig(fields),\n ...(fields.imageConfig ? { imageConfig: fields.imageConfig } : {}),\n ...(mediaResolution ? { mediaResolution } : {}),\n },\n ...convertFieldsToServiceTier(this.platform, fields),\n };\n }\n\n getLsParams(options: this[\"ParsedCallOptions\"]): LangSmithParams {\n const params = this.invocationParams(options);\n return {\n ls_provider: this.platform === \"gcp\" ? \"google_vertexai\" : \"google_genai\",\n ls_model_name: this.model,\n ls_model_type: \"chat\",\n ls_temperature: params.generationConfig?.temperature ?? undefined,\n ls_max_tokens: params.generationConfig?.maxOutputTokens ?? undefined,\n ls_stop: options.stop,\n };\n }\n\n getHeaders(options: this[\"ParsedCallOptions\"]): HeadersInit {\n const fields = combineGoogleChatModelFields(this.params, options);\n\n // The priority type is set via header only for Vertex\n const priorityHeaders: Record<string, string> =\n this.platform === \"gcp\" &&\n typeof fields.serviceTier !== \"undefined\" &&\n settableServiceTier.includes(fields.serviceTier)\n ? { \"X-Vertex-AI-LLM-Shared-Request-Type\": fields.serviceTier }\n : {};\n\n return {\n \"Content-Type\": \"application/json\",\n ...priorityHeaders,\n ...this._customHeaders,\n ...options.customHeaders,\n };\n }\n\n async _generate(\n messages: BaseMessage[],\n options: this[\"ParsedCallOptions\"],\n runManager?: CallbackManagerForLLMRun\n ): Promise<ChatResult> {\n if (this.streaming) {\n const stream = await this._streamResponseChunks(\n messages,\n options,\n runManager\n );\n let finalChunk: ChatGenerationChunk | null = null;\n for await (const chunk of stream) {\n finalChunk = !finalChunk ? chunk : concat(finalChunk, chunk);\n }\n if (\n typeof finalChunk?.message?.content === \"string\" &&\n typeof (\n finalChunk?.message?.additional_kwargs\n ?.originalTextContentBlock as Record<string, unknown>\n )?.text === \"string\"\n ) {\n (\n finalChunk.message.additional_kwargs\n .originalTextContentBlock as Record<string, unknown>\n ).text = finalChunk.message.content;\n }\n return {\n generations: finalChunk ? [finalChunk] : [],\n };\n }\n\n const url = await this.buildUrl();\n const headers = this.getHeaders(options);\n const body = {\n ...this.invocationParams(options),\n systemInstruction: convertMessagesToGeminiSystemInstruction(messages),\n contents: convertMessagesToGeminiContents(messages),\n };\n\n const moduleName = this.constructor.name;\n await runManager?.handleCustomEvent(`google-request-${moduleName}`, {\n url,\n headers,\n body,\n });\n\n const response = await this.apiClient.fetch(\n new Request(url, {\n method: \"POST\",\n headers,\n body: JSON.stringify(body),\n signal: options.signal,\n })\n );\n\n if (!response.ok) {\n const error = await RequestError.fromResponse(response);\n await runManager?.handleCustomEvent(`google-response-${moduleName}`, {\n error,\n });\n throw error;\n }\n\n const data: Gemini.GenerateContentResponse = await response.json();\n await runManager?.handleCustomEvent(`google-response-${moduleName}`, {\n data,\n url: response.url,\n headers: Array.from(response.headers.entries()),\n status: response.status,\n statusText: response.statusText,\n });\n\n // Check for prompt feedback errors\n if (data.promptFeedback?.blockReason) {\n throw PromptBlockedError.fromPromptFeedback(data.promptFeedback);\n }\n\n // Check if we have candidates\n if (!data.candidates || data.candidates.length === 0) {\n throw new NoCandidatesError();\n }\n\n // Use the first candidate\n const candidate = data.candidates[0];\n const message = convertGeminiCandidateToAIMessage(candidate);\n\n // Extract text content from the message\n const text = convertAIMessageToText(message);\n\n const usageMetadata =\n convertGeminiGenerateContentResponseToUsageMetadata(data);\n message.usage_metadata = usageMetadata;\n\n const serviceTier: ServiceTier = iife((): ServiceTier => {\n // @ts-expect-error - trafficType is defined on Vertex, so isn't in the OpenAPI spec\n const trafficType: string | undefined = data.usageMetadata?.trafficType;\n\n // AI Studio replies with actual service type in the header\n const serviceTierHeader: string | null = response.headers.get(\n \"x-gemini-service-tier\"\n );\n\n if (trafficType?.startsWith(\"ON_DEMAND_\")) {\n return trafficType?.substring(\"ON_DEMAND_\".length).toLowerCase();\n }\n return serviceTierHeader || \"standard\";\n });\n\n return {\n generations: [\n {\n text,\n message,\n generationInfo: {\n finishReason: candidate.finishReason,\n finishMessage: candidate.finishMessage,\n safetyRatings: candidate.safetyRatings,\n citationMetadata: candidate.citationMetadata,\n tokenCount: candidate.tokenCount,\n },\n },\n ],\n llmOutput: {\n tokenUsage: usageMetadataToTokenUsage(usageMetadata),\n model: data.modelVersion,\n responseId: data.responseId,\n usageMetadata,\n serviceTier,\n },\n };\n }\n\n async *_streamChatModelEvents(\n messages: BaseMessage[],\n options: this[\"ParsedCallOptions\"],\n _runManager?: CallbackManagerForLLMRun\n ): AsyncGenerator<ChatModelStreamEvent> {\n const body = {\n ...this.invocationParams(options),\n systemInstruction: convertMessagesToGeminiSystemInstruction(messages),\n contents: convertMessagesToGeminiContents(messages),\n };\n\n const url = await this.buildUrl(\"streamGenerateContent?alt=sse\");\n const headers = this.getHeaders(options);\n\n const response = await this.apiClient.fetch(\n new Request(url, {\n method: \"POST\",\n headers,\n body: JSON.stringify(body),\n signal: options.signal,\n })\n );\n\n if (!response.ok) {\n throw await RequestError.fromResponse(response);\n }\n\n if (!response.body) {\n return;\n }\n\n const eventStream = response.body\n .pipeThrough(new TextDecoderStream())\n .pipeThrough(new EventSourceParserStream())\n .pipeThrough(\n new SafeJsonEventParserStream<Gemini.GenerateContentResponse>()\n );\n\n const shouldStreamUsage =\n this.streamUsage !== false && options.streamUsage !== false;\n\n async function* geminiChunks(\n stream: ReadableStream<Gemini.GenerateContentResponse | null>,\n signal?: AbortSignal\n ) {\n const reader = stream.getReader();\n try {\n while (true) {\n if (signal?.aborted) {\n return;\n }\n const { done, value } = await reader.read();\n if (done) {\n break;\n }\n if (value !== null) {\n yield value;\n }\n }\n } finally {\n reader.releaseLock();\n }\n }\n\n yield* convertGoogleGeminiStream(\n geminiChunks(eventStream, options.signal),\n {\n streamUsage: shouldStreamUsage,\n }\n );\n }\n\n async *_streamResponseChunks(\n messages: BaseMessage[],\n options: this[\"ParsedCallOptions\"],\n runManager?: CallbackManagerForLLMRun\n ): AsyncGenerator<ChatGenerationChunk> {\n const streamUsage: boolean = this.streamUsage ?? true;\n\n const body = {\n ...this.invocationParams(options),\n systemInstruction: convertMessagesToGeminiSystemInstruction(messages),\n contents: convertMessagesToGeminiContents(messages),\n };\n\n const url = await this.buildUrl(\"streamGenerateContent?alt=sse\");\n const headers = this.getHeaders(options);\n const moduleName = this.constructor.name;\n await runManager?.handleCustomEvent(`google-request-${moduleName}`, {\n url,\n headers,\n body,\n });\n\n const response = await this.apiClient.fetch(\n new Request(url, {\n method: \"POST\",\n headers,\n body: JSON.stringify(body),\n signal: options.signal,\n })\n );\n\n await runManager?.handleCustomEvent(`google-response-${moduleName}`, {\n url: response.url,\n headers: Array.from(response.headers.entries()),\n status: response.status,\n statusText: response.statusText,\n });\n\n if (!response.ok) {\n const error = await RequestError.fromResponse(response);\n await runManager?.handleCustomEvent(`google-response-${moduleName}`, {\n error,\n });\n throw error;\n }\n\n if (response.body) {\n let previousUsage: UsageMetadata | undefined;\n const stream = response.body\n .pipeThrough(new TextDecoderStream())\n .pipeThrough(new EventSourceParserStream())\n .pipeThrough(\n new SafeJsonEventParserStream<Gemini.GenerateContentResponse>()\n )\n .pipeThrough(\n new TransformStream<\n Gemini.GenerateContentResponse,\n ChatGenerationChunk\n >({\n transform(chunk, controller) {\n // oxlint-disable-next-line no-void\n void runManager?.handleCustomEvent(`google-chunk-${moduleName}`, {\n chunk,\n });\n if (chunk === null) {\n controller.enqueue(\n new ChatGenerationChunk({\n text: \"\",\n message: new AIMessageChunk({ content: \"\" }),\n generationInfo: { finishReason: \"stop\" },\n })\n );\n return;\n }\n\n // Extract text delta from the chunk\n const candidate = chunk.candidates?.[0];\n if (!candidate) {\n return;\n }\n\n const message = convertGeminiCandidateToAIMessage(candidate);\n const text = convertAIMessageToText(message);\n\n const parts = candidate.content?.parts ?? [];\n const toolCalls = convertGeminiPartsToToolCalls(parts);\n\n // Only emit if we have content\n if (parts.length > 0 || candidate.finishReason) {\n const messageChunkParams: AIMessageChunkFields = {\n content: message.content,\n tool_calls: toolCalls,\n response_metadata: {\n model_provider: \"google\",\n },\n additional_kwargs: {\n ...(message.additional_kwargs.originalTextContentBlock\n ? {\n originalTextContentBlock:\n message.additional_kwargs.originalTextContentBlock,\n }\n : {}),\n ...(candidate.finishReason\n ? {\n finishReason: candidate.finishReason,\n finishMessage: candidate.finishMessage,\n }\n : {}),\n },\n };\n\n if (chunk?.usageMetadata && streamUsage) {\n const cumulative =\n convertGeminiGenerateContentResponseToUsageMetadata(chunk);\n messageChunkParams.usage_metadata = subtractUsageMetadata(\n cumulative,\n previousUsage\n );\n previousUsage = cumulative;\n }\n const messageChunk = new AIMessageChunk(messageChunkParams);\n\n controller.enqueue(\n new ChatGenerationChunk({\n text: text,\n message: messageChunk,\n generationInfo: {\n ...(candidate.finishReason && {\n finishReason: candidate.finishReason,\n finishMessage: candidate.finishMessage,\n }),\n ...(candidate.safetyRatings && {\n safetyRatings: candidate.safetyRatings,\n }),\n },\n })\n );\n }\n },\n })\n );\n\n const reader = stream.getReader();\n try {\n while (true) {\n const { done, value } = await reader.read();\n if (done) break;\n yield value;\n await runManager?.handleLLMNewToken(\n value.text ?? \"\",\n undefined,\n undefined,\n undefined,\n undefined,\n { chunk: value }\n );\n }\n } finally {\n reader.releaseLock();\n }\n }\n }\n\n /**\n * Bind tool-like objects to this chat model.\n *\n * @param tools A list of tool definitions to bind to this chat model.\n * Can be a structured tool, an OpenAI formatted tool, or a Gemini function declaration.\n * @param kwargs Any additional parameters to bind.\n */\n bindTools(\n tools: BindToolsInput[],\n kwargs?: Partial<CallOptions>\n ): Runnable<BaseMessage[], AIMessageChunk, CallOptions> {\n return this.withConfig({\n ...kwargs,\n tools,\n } as Partial<CallOptions>);\n }\n\n withStructuredOutput<\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n RunOutput extends Record<string, any> = Record<string, any>,\n >(\n outputSchema:\n | InteropZodType<RunOutput>\n | SerializableSchema<RunOutput>\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n | Record<string, any>,\n config?: StructuredOutputMethodOptions<false>\n ): Runnable<BaseLanguageModelInput, RunOutput>;\n\n withStructuredOutput<\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n RunOutput extends Record<string, any> = Record<string, any>,\n >(\n outputSchema:\n | InteropZodType<RunOutput>\n | SerializableSchema<RunOutput>\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n | Record<string, any>,\n config?: StructuredOutputMethodOptions<true>\n ): Runnable<BaseLanguageModelInput, { raw: BaseMessage; parsed: RunOutput }>;\n\n withStructuredOutput<\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n RunOutput extends Record<string, any> = Record<string, any>,\n >(\n outputSchema:\n | InteropZodType<RunOutput>\n | SerializableSchema<RunOutput>\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n | Record<string, any>,\n config?: StructuredOutputMethodOptions<boolean>\n ):\n | Runnable<BaseLanguageModelInput, RunOutput>\n | Runnable<BaseLanguageModelInput, { raw: BaseMessage; parsed: RunOutput }>;\n\n /**\n * Get structured output from the model based on a schema.\n *\n * This method supports two modes:\n * - `jsonMode`: Uses `responseSchema` to get JSON responses directly (preferred for structured outputs)\n * - `functionCalling`: Uses function calling with tools (default, for compatibility)\n *\n * @param outputSchema - The schema to use for structured output (Zod schema or JSON Schema)\n * @param config - Configuration options including method and whether to include raw response\n * @returns A Runnable that returns the parsed structured output\n */\n withStructuredOutput<\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n RunOutput extends Record<string, any> = Record<string, any>,\n >(\n outputSchema:\n | InteropZodType<RunOutput>\n | SerializableSchema<RunOutput>\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n | Record<string, any>,\n config?: StructuredOutputMethodOptions<boolean>\n ):\n | Runnable<BaseLanguageModelInput, RunOutput>\n | Runnable<\n BaseLanguageModelInput,\n { raw: BaseMessage; parsed: RunOutput }\n > {\n let llm: Runnable<BaseMessage[], AIMessageChunk, CallOptions>;\n let outputParser: Runnable<BaseMessage, RunOutput>;\n\n const { schema, name, includeRaw } = {\n ...config,\n schema: outputSchema,\n };\n let method = config?.method ?? \"functionCalling\";\n\n if (method === \"jsonMode\") {\n console.warn(\n `\"jsonMode\" is not supported for Google models. Falling back to \"jsonSchema\".`\n );\n method = \"jsonSchema\";\n }\n\n if (method === \"jsonSchema\") {\n // Use JSON mode with responseSchema\n llm = this.withConfig({\n responseSchema: schema,\n } as Partial<CallOptions>);\n\n outputParser = RunnableLambda.from<BaseMessage, RunOutput>(\n async (input: BaseMessage): Promise<RunOutput> => {\n if (\n !AIMessage.isInstance(input) &&\n !AIMessageChunk.isInstance(input)\n ) {\n throw new MalformedOutputError({\n message: \"Input is not an AIMessage or AIMessageChunk.\",\n });\n }\n\n if (!input.text) {\n throw new MalformedOutputError({\n message:\n \"No content found in response. Cannot parse structured output.\",\n });\n }\n\n // Parse JSON and validate with schema\n const parser = createContentParser(schema);\n return await parser.parse(input.text);\n }\n );\n } else if (method === \"functionCalling\") {\n // Use function calling mode\n let functionName = name ?? \"extract\";\n let geminiFunctionDeclaration: Gemini.Tools.FunctionDeclaration;\n\n if (isInteropZodSchema(schema) || isSerializableSchema(schema)) {\n const jsonSchema = schemaToGeminiParameters(schema);\n const description =\n typeof jsonSchema.description === \"string\"\n ? jsonSchema.description\n : \"A function available to call.\";\n geminiFunctionDeclaration = {\n name: functionName,\n description,\n parameters: jsonSchema as Gemini.Tools.Schema,\n };\n } else if (\n typeof schema.name === \"string\" &&\n typeof schema.parameters === \"object\" &&\n schema.parameters != null\n ) {\n geminiFunctionDeclaration = schema as Gemini.Tools.FunctionDeclaration;\n functionName = schema.name;\n } else {\n // We are providing the schema for *just* the parameters\n const parameters = schemaToGeminiParameters(schema);\n geminiFunctionDeclaration = {\n name: functionName,\n description: (schema as { description?: string }).description ?? \"\",\n parameters,\n };\n }\n\n const tools: Gemini.Tool[] = [\n {\n functionDeclarations: [geminiFunctionDeclaration],\n },\n ];\n llm = this.bindTools(tools).withConfig({\n tool_choice: functionName,\n } as Partial<CallOptions>);\n\n outputParser = createFunctionCallingParser(schema, functionName);\n } else {\n throw new ConfigurationError(\n `Unrecognized structured output method '${method}'. Expected 'functionCalling' or 'jsonSchema'`\n );\n }\n\n return assembleStructuredOutputPipeline(\n llm,\n outputParser,\n includeRaw,\n includeRaw\n ? \"ChatGoogleStructuredOutputRunnable\"\n : \"ChatGoogleStructuredOutput\"\n );\n }\n}\n\ntype CombinableFields = Omit<BaseChatGoogleParams, \"model\">;\n\nexport function combineGoogleChatModelFields(\n a: CombinableFields,\n b: CombinableFields,\n ...rest: CombinableFields[]\n): CombinableFields {\n const combined: CombinableFields = {\n temperature: b.temperature ?? a.temperature,\n topP: b.topP ?? a.topP,\n topK: b.topK ?? a.topK,\n maxOutputTokens: b.maxOutputTokens ?? a.maxOutputTokens,\n presencePenalty: b.presencePenalty ?? a.presencePenalty,\n frequencyPenalty: b.frequencyPenalty ?? a.frequencyPenalty,\n stopSequences: b.stopSequences ?? a.stopSequences,\n seed: b.seed ?? a.seed,\n responseLogprobs: b.responseLogprobs ?? a.responseLogprobs,\n logprobs: b.logprobs ?? a.logprobs,\n safetySettings: b.safetySettings ?? a.safetySettings,\n responseSchema: b.responseSchema ?? a.responseSchema,\n tools: b.tools ?? a.tools,\n responseModalities: b.responseModalities ?? a.responseModalities,\n enableEnhancedCivicAnswers:\n b.enableEnhancedCivicAnswers ?? a.enableEnhancedCivicAnswers,\n speechConfig: b.speechConfig ?? a.speechConfig,\n imageConfig: b.imageConfig ?? a.imageConfig,\n mediaResolution: b.mediaResolution ?? a.mediaResolution,\n detail: b.detail ?? a.detail,\n maxReasoningTokens: b.maxReasoningTokens ?? a.maxReasoningTokens,\n thinkingBudget: b.thinkingBudget ?? a.thinkingBudget,\n reasoningEffort: b.reasoningEffort ?? a.reasoningEffort,\n thinkingLevel: b.thinkingLevel ?? a.thinkingLevel,\n serviceTier: b.serviceTier ?? a.serviceTier,\n };\n if (rest.length > 0) {\n return combineGoogleChatModelFields(combined, rest[0], ...rest.slice(1));\n }\n return combined;\n}\n\nexport function getGoogleChatModelParams<TParams extends BaseChatGoogleParams>(\n modelOrParams: string | TParams,\n paramsArg?: Omit<TParams, \"model\">\n): TParams {\n const model =\n typeof modelOrParams === \"string\" ? modelOrParams : modelOrParams.model;\n const params = typeof modelOrParams === \"string\" ? paramsArg : modelOrParams;\n return { model, ...params } as TParams;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAiFA,SAAgB,gBACd,UACA,WACoB;AACpB,KAAI,OAAO,aAAa,YACtB,QAAO;UACE,UACT,QAAO;KAEP,QAAO;;AAIX,SAAS,0BAA0B,eAA8B;AAC/D,QAAO;EACL,cAAc,cAAc;EAC5B,kBAAkB,cAAc;EAChC,aAAa,cAAc;EAC5B;;AAGH,SAAS,2BACP,QACwD;AACxD,SAAQ,QAAR;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AAE;EACpB,oBAAoB,EAAE,sBAAsB,EAAE;EAC9C,4BACE,EAAE,8BAA8B,EAAE;EACpC,cAAc,EAAE,gBAAgB,EAAE;EAClC,aAAa,EAAE,eAAe,EAAE;EAChC,iBAAiB,EAAE,mBAAmB,EAAE;EACxC,QAAQ,EAAE,UAAU,EAAE;EACtB,oBAAoB,EAAE,sBAAsB,EAAE;EAC9C,gBAAgB,EAAE,kBAAkB,EAAE;EACtC,iBAAiB,EAAE,mBAAmB,EAAE;EACxC,eAAe,EAAE,iBAAiB,EAAE;EACpC,aAAa,EAAE,eAAe,EAAE;EACjC;AACD,KAAI,KAAK,SAAS,EAChB,QAAO,6BAA6B,UAAU,KAAK,IAAI,GAAG,KAAK,MAAM,EAAE,CAAC;AAE1E,QAAO;;AAGT,SAAgB,yBACd,eACA,WACS;AAIT,QAAO;EAAE,OAFP,OAAO,kBAAkB,WAAW,gBAAgB,cAAc;EAEpD,GADD,OAAO,kBAAkB,WAAW,YAAY;EACpC"}
@@ -1 +1 @@
1
- {"version":3,"file":"node.cjs","names":["BaseChatGoogle","getGoogleChatModelParams","ensureAuthScopes","NodeApiClient","getPlatformType","convertParamsToPlatformType","GENERATIVE_AI_AUTH_SCOPES","VERTEX_AI_AUTH_SCOPES"],"sources":["../../src/chat_models/node.ts"],"sourcesContent":["import { getEnvironmentVariable } from \"@langchain/core/utils/env\";\nimport { ChatGoogleParams } from \"./index.js\";\nimport {\n BaseChatGoogle,\n getGoogleChatModelParams,\n getPlatformType,\n} from \"./base.js\";\nimport { GENERATIVE_AI_AUTH_SCOPES, VERTEX_AI_AUTH_SCOPES } from \"../const.js\";\nimport {\n ensureAuthScopes,\n NodeApiClient,\n NodeApiClientParams,\n} from \"../clients/node.js\";\nimport { convertParamsToPlatformType } from \"../converters/params.js\";\n\ninterface ChatGoogleNodeParams extends NodeApiClientParams, ChatGoogleParams {}\n\nclass ChatGoogleNode extends BaseChatGoogle {\n constructor(model: string, params?: Omit<ChatGoogleNodeParams, \"model\">);\n constructor(params: ChatGoogleNodeParams);\n constructor(\n modelOrParams: string | ChatGoogleNodeParams,\n paramsArg?: Omit<ChatGoogleNodeParams, \"model\">\n ) {\n const params = getGoogleChatModelParams(modelOrParams, paramsArg);\n if (!params.googleAuthOptions) {\n params.apiKey = params.apiKey ?? getEnvironmentVariable(\"GOOGLE_API_KEY\");\n }\n const requiredScopes: string[] = getRequiredAuthScopes(params);\n if (params.googleAuthOptions) {\n params.googleAuthOptions = ensureAuthScopes(\n params.googleAuthOptions,\n requiredScopes\n );\n }\n const apiClient = params?.apiClient ?? new NodeApiClient(params);\n super({ ...params, apiClient });\n }\n}\n\nfunction getRequiredAuthScopes(params: ChatGoogleNodeParams): string[] {\n const hasApiKey = typeof params.apiKey !== \"undefined\";\n const platformType = convertParamsToPlatformType(params);\n const platform = getPlatformType(platformType, hasApiKey);\n switch (platform) {\n case \"gai\":\n return GENERATIVE_AI_AUTH_SCOPES;\n case \"gcp\":\n return VERTEX_AI_AUTH_SCOPES;\n default:\n return VERTEX_AI_AUTH_SCOPES;\n }\n}\n\nexport {\n type ChatGoogleNodeParams as ChatGoogleParams,\n ChatGoogleNode as ChatGoogle,\n};\n"],"mappings":";;;;;;AAiBA,IAAM,iBAAN,cAA6BA,aAAAA,eAAe;CAG1C,YACE,eACA,WACA;EACA,MAAM,SAASC,aAAAA,yBAAyB,eAAe,UAAU;AACjE,MAAI,CAAC,OAAO,kBACV,QAAO,SAAS,OAAO,WAAA,GAAA,0BAAA,wBAAiC,iBAAiB;EAE3E,MAAM,iBAA2B,sBAAsB,OAAO;AAC9D,MAAI,OAAO,kBACT,QAAO,oBAAoBC,aAAAA,iBACzB,OAAO,mBACP,eACD;EAEH,MAAM,YAAY,QAAQ,aAAa,IAAIC,aAAAA,cAAc,OAAO;AAChE,QAAM;GAAE,GAAG;GAAQ;GAAW,CAAC;;;AAInC,SAAS,sBAAsB,QAAwC;CACrE,MAAM,YAAY,OAAO,OAAO,WAAW;AAG3C,SADiBC,aAAAA,gBADIC,eAAAA,4BAA4B,OAAO,EACT,UAAU,EACzD;EACE,KAAK,MACH,QAAOC,cAAAA;EACT,KAAK,MACH,QAAOC,cAAAA;EACT,QACE,QAAOA,cAAAA"}
1
+ {"version":3,"file":"node.cjs","names":["BaseChatGoogle","getGoogleChatModelParams","ensureAuthScopes","NodeApiClient","getPlatformType","convertParamsToPlatformType","GENERATIVE_AI_AUTH_SCOPES","VERTEX_AI_AUTH_SCOPES"],"sources":["../../src/chat_models/node.ts"],"sourcesContent":["import { getEnvironmentVariable } from \"@langchain/core/utils/env\";\nimport { ChatGoogleParams } from \"./index.js\";\nimport {\n BaseChatGoogle,\n getGoogleChatModelParams,\n getPlatformType,\n} from \"./base.js\";\nimport { GENERATIVE_AI_AUTH_SCOPES, VERTEX_AI_AUTH_SCOPES } from \"../const.js\";\nimport {\n ensureAuthScopes,\n NodeApiClient,\n NodeApiClientParams,\n} from \"../clients/node.js\";\nimport { convertParamsToPlatformType } from \"../converters/params.js\";\n\ninterface ChatGoogleNodeParams extends NodeApiClientParams, ChatGoogleParams {}\n\nclass ChatGoogleNode extends BaseChatGoogle {\n constructor(model: string, params?: Omit<ChatGoogleNodeParams, \"model\">);\n constructor(params: ChatGoogleNodeParams);\n constructor(\n modelOrParams: string | ChatGoogleNodeParams,\n paramsArg?: Omit<ChatGoogleNodeParams, \"model\">\n ) {\n const params = getGoogleChatModelParams(modelOrParams, paramsArg);\n if (!params.googleAuthOptions) {\n params.apiKey = params.apiKey ?? getEnvironmentVariable(\"GOOGLE_API_KEY\");\n }\n const requiredScopes: string[] = getRequiredAuthScopes(params);\n if (params.googleAuthOptions) {\n params.googleAuthOptions = ensureAuthScopes(\n params.googleAuthOptions,\n requiredScopes\n );\n }\n const apiClient = params?.apiClient ?? new NodeApiClient(params);\n super({ ...params, apiClient });\n }\n}\n\nfunction getRequiredAuthScopes(params: ChatGoogleNodeParams): string[] {\n const hasApiKey = typeof params.apiKey !== \"undefined\";\n const platformType = convertParamsToPlatformType(params);\n const platform = getPlatformType(platformType, hasApiKey);\n switch (platform) {\n case \"gai\":\n return GENERATIVE_AI_AUTH_SCOPES;\n case \"gcp\":\n return VERTEX_AI_AUTH_SCOPES;\n default:\n return VERTEX_AI_AUTH_SCOPES;\n }\n}\n\nexport {\n type ChatGoogleNodeParams as ChatGoogleParams,\n ChatGoogleNode as ChatGoogle,\n};\n"],"mappings":";;;;;;AAiBA,IAAM,iBAAN,cAA6BA,aAAAA,eAAe;CAG1C,YACE,eACA,WACA;EACA,MAAM,SAASC,aAAAA,yBAAyB,eAAe,UAAU;AACjE,MAAI,CAAC,OAAO,kBACV,QAAO,SAAS,OAAO,WAAA,GAAA,0BAAA,wBAAiC,iBAAiB;EAE3E,MAAM,iBAA2B,sBAAsB,OAAO;AAC9D,MAAI,OAAO,kBACT,QAAO,oBAAoBC,aAAAA,iBACzB,OAAO,mBACP,eACD;EAEH,MAAM,YAAY,QAAQ,aAAa,IAAIC,aAAAA,cAAc,OAAO;AAChE,QAAM;GAAE,GAAG;GAAQ;GAAW,CAAC;;;AAInC,SAAS,sBAAsB,QAAwC;CACrE,MAAM,YAAY,OAAO,OAAO,WAAW;AAG3C,SADiBC,aAAAA,gBADIC,eAAAA,4BAA4B,OACJ,EAAE,UAC/B,EAAhB;EACE,KAAK,MACH,QAAOC,cAAAA;EACT,KAAK,MACH,QAAOC,cAAAA;EACT,QACE,QAAOA,cAAAA"}
@@ -1 +1 @@
1
- {"version":3,"file":"node.js","names":[],"sources":["../../src/chat_models/node.ts"],"sourcesContent":["import { getEnvironmentVariable } from \"@langchain/core/utils/env\";\nimport { ChatGoogleParams } from \"./index.js\";\nimport {\n BaseChatGoogle,\n getGoogleChatModelParams,\n getPlatformType,\n} from \"./base.js\";\nimport { GENERATIVE_AI_AUTH_SCOPES, VERTEX_AI_AUTH_SCOPES } from \"../const.js\";\nimport {\n ensureAuthScopes,\n NodeApiClient,\n NodeApiClientParams,\n} from \"../clients/node.js\";\nimport { convertParamsToPlatformType } from \"../converters/params.js\";\n\ninterface ChatGoogleNodeParams extends NodeApiClientParams, ChatGoogleParams {}\n\nclass ChatGoogleNode extends BaseChatGoogle {\n constructor(model: string, params?: Omit<ChatGoogleNodeParams, \"model\">);\n constructor(params: ChatGoogleNodeParams);\n constructor(\n modelOrParams: string | ChatGoogleNodeParams,\n paramsArg?: Omit<ChatGoogleNodeParams, \"model\">\n ) {\n const params = getGoogleChatModelParams(modelOrParams, paramsArg);\n if (!params.googleAuthOptions) {\n params.apiKey = params.apiKey ?? getEnvironmentVariable(\"GOOGLE_API_KEY\");\n }\n const requiredScopes: string[] = getRequiredAuthScopes(params);\n if (params.googleAuthOptions) {\n params.googleAuthOptions = ensureAuthScopes(\n params.googleAuthOptions,\n requiredScopes\n );\n }\n const apiClient = params?.apiClient ?? new NodeApiClient(params);\n super({ ...params, apiClient });\n }\n}\n\nfunction getRequiredAuthScopes(params: ChatGoogleNodeParams): string[] {\n const hasApiKey = typeof params.apiKey !== \"undefined\";\n const platformType = convertParamsToPlatformType(params);\n const platform = getPlatformType(platformType, hasApiKey);\n switch (platform) {\n case \"gai\":\n return GENERATIVE_AI_AUTH_SCOPES;\n case \"gcp\":\n return VERTEX_AI_AUTH_SCOPES;\n default:\n return VERTEX_AI_AUTH_SCOPES;\n }\n}\n\nexport {\n type ChatGoogleNodeParams as ChatGoogleParams,\n ChatGoogleNode as ChatGoogle,\n};\n"],"mappings":";;;;;;AAiBA,IAAM,iBAAN,cAA6B,eAAe;CAG1C,YACE,eACA,WACA;EACA,MAAM,SAAS,yBAAyB,eAAe,UAAU;AACjE,MAAI,CAAC,OAAO,kBACV,QAAO,SAAS,OAAO,UAAU,uBAAuB,iBAAiB;EAE3E,MAAM,iBAA2B,sBAAsB,OAAO;AAC9D,MAAI,OAAO,kBACT,QAAO,oBAAoB,iBACzB,OAAO,mBACP,eACD;EAEH,MAAM,YAAY,QAAQ,aAAa,IAAI,cAAc,OAAO;AAChE,QAAM;GAAE,GAAG;GAAQ;GAAW,CAAC;;;AAInC,SAAS,sBAAsB,QAAwC;CACrE,MAAM,YAAY,OAAO,OAAO,WAAW;AAG3C,SADiB,gBADI,4BAA4B,OAAO,EACT,UAAU,EACzD;EACE,KAAK,MACH,QAAO;EACT,KAAK,MACH,QAAO;EACT,QACE,QAAO"}
1
+ {"version":3,"file":"node.js","names":[],"sources":["../../src/chat_models/node.ts"],"sourcesContent":["import { getEnvironmentVariable } from \"@langchain/core/utils/env\";\nimport { ChatGoogleParams } from \"./index.js\";\nimport {\n BaseChatGoogle,\n getGoogleChatModelParams,\n getPlatformType,\n} from \"./base.js\";\nimport { GENERATIVE_AI_AUTH_SCOPES, VERTEX_AI_AUTH_SCOPES } from \"../const.js\";\nimport {\n ensureAuthScopes,\n NodeApiClient,\n NodeApiClientParams,\n} from \"../clients/node.js\";\nimport { convertParamsToPlatformType } from \"../converters/params.js\";\n\ninterface ChatGoogleNodeParams extends NodeApiClientParams, ChatGoogleParams {}\n\nclass ChatGoogleNode extends BaseChatGoogle {\n constructor(model: string, params?: Omit<ChatGoogleNodeParams, \"model\">);\n constructor(params: ChatGoogleNodeParams);\n constructor(\n modelOrParams: string | ChatGoogleNodeParams,\n paramsArg?: Omit<ChatGoogleNodeParams, \"model\">\n ) {\n const params = getGoogleChatModelParams(modelOrParams, paramsArg);\n if (!params.googleAuthOptions) {\n params.apiKey = params.apiKey ?? getEnvironmentVariable(\"GOOGLE_API_KEY\");\n }\n const requiredScopes: string[] = getRequiredAuthScopes(params);\n if (params.googleAuthOptions) {\n params.googleAuthOptions = ensureAuthScopes(\n params.googleAuthOptions,\n requiredScopes\n );\n }\n const apiClient = params?.apiClient ?? new NodeApiClient(params);\n super({ ...params, apiClient });\n }\n}\n\nfunction getRequiredAuthScopes(params: ChatGoogleNodeParams): string[] {\n const hasApiKey = typeof params.apiKey !== \"undefined\";\n const platformType = convertParamsToPlatformType(params);\n const platform = getPlatformType(platformType, hasApiKey);\n switch (platform) {\n case \"gai\":\n return GENERATIVE_AI_AUTH_SCOPES;\n case \"gcp\":\n return VERTEX_AI_AUTH_SCOPES;\n default:\n return VERTEX_AI_AUTH_SCOPES;\n }\n}\n\nexport {\n type ChatGoogleNodeParams as ChatGoogleParams,\n ChatGoogleNode as ChatGoogle,\n};\n"],"mappings":";;;;;;AAiBA,IAAM,iBAAN,cAA6B,eAAe;CAG1C,YACE,eACA,WACA;EACA,MAAM,SAAS,yBAAyB,eAAe,UAAU;AACjE,MAAI,CAAC,OAAO,kBACV,QAAO,SAAS,OAAO,UAAU,uBAAuB,iBAAiB;EAE3E,MAAM,iBAA2B,sBAAsB,OAAO;AAC9D,MAAI,OAAO,kBACT,QAAO,oBAAoB,iBACzB,OAAO,mBACP,eACD;EAEH,MAAM,YAAY,QAAQ,aAAa,IAAI,cAAc,OAAO;AAChE,QAAM;GAAE,GAAG;GAAQ;GAAW,CAAC;;;AAInC,SAAS,sBAAsB,QAAwC;CACrE,MAAM,YAAY,OAAO,OAAO,WAAW;AAG3C,SADiB,gBADI,4BAA4B,OACJ,EAAE,UAC/B,EAAhB;EACE,KAAK,MACH,QAAO;EACT,KAAK,MACH,QAAO;EACT,QACE,QAAO"}
@@ -1 +1 @@
1
- {"version":3,"file":"node.cjs","names":["ApiClient","iife","normalizeGCPCredentials","GoogleAuth","GOOGLE_API_KEY_HEADER","GCP_API_KEY_HEADER","getGCPCredentialsAccessToken","ConfigurationError"],"sources":["../../src/clients/node.ts"],"sourcesContent":["import { GoogleAuth, type GoogleAuthOptions } from \"google-auth-library\";\nimport { getEnvironmentVariable } from \"@langchain/core/utils/env\";\nimport { GCP_API_KEY_HEADER, GOOGLE_API_KEY_HEADER } from \"../const.js\";\nimport { ApiClient } from \"./index.js\";\nimport {\n GCPCredentials,\n getGCPCredentialsAccessToken,\n normalizeGCPCredentials,\n} from \"../utils/gcp-auth.js\";\nimport { ConfigurationError } from \"../utils/errors.js\";\nimport { iife } from \"../utils/misc.js\";\n\n/**\n * Configuration parameters for the NodeApiClient.\n *\n * This interface defines the authentication options available for Node.js-based\n * API clients. Authentication can be provided via an API key, GCP service\n * account credentials, or advanced Google Auth options. The client will\n * automatically check environment variables if explicit values are not provided.\n *\n * @interface\n */\nexport interface NodeApiClientParams {\n /**\n * Google API key for authentication.\n *\n * If not provided, the client will attempt to read from the\n * `GOOGLE_API_KEY` environment variable.\n *\n * @see https://cloud.google.com/docs/authentication/api-keys\n */\n apiKey?: string;\n\n /**\n * GCP service account credentials for authentication.\n *\n * Can be provided as either:\n * - A JSON string containing the service account key\n * - A GCPCredentials object\n *\n * If not provided, the client will attempt to read from the\n * `GOOGLE_CLOUD_CREDENTIALS` environment variable.\n *\n * @see https://cloud.google.com/iam/docs/creating-managing-service-account-keys\n */\n credentials?: string | GCPCredentials;\n\n /**\n * Google Auth options configuration.\n *\n * Provides fine-grained control over authentication behavior using the\n * google-auth-library. This option enables:\n * - Custom OAuth2 scopes\n * - Application Default Credentials (ADC)\n * - Impersonation and delegation\n * - Custom credential sources\n *\n * When provided, this takes precedence over simple credential-based auth\n * but is lower priority than API key authentication.\n *\n * @see https://github.com/googleapis/google-auth-library-nodejs\n * @see https://cloud.google.com/docs/authentication/application-default-credentials\n */\n googleAuthOptions?: GoogleAuthOptions;\n}\n\n/**\n * Node.js-specific API client for Google services.\n *\n * This client provides comprehensive authentication for Google API requests in\n * Node.js environments, leveraging the full capabilities of the google-auth-library.\n * It supports three authentication methods with the following priority:\n *\n * 1. **API Key Authentication**: Simple key-based authentication suitable for\n * public APIs and development environments.\n *\n * 2. **Service Account Credentials**: OAuth2-based authentication using GCP\n * service account keys. The client automatically handles token generation\n * and caching using a web-compatible implementation.\n *\n * 3. **Google Auth Library**: Advanced authentication using google-auth-library,\n * supporting Application Default Credentials (ADC), custom scopes, and\n * various credential sources.\n *\n * The client follows this authentication priority:\n * 1. Explicit `apiKey` parameter\n * 2. `GOOGLE_API_KEY` environment variable\n * 3. Explicit `credentials` parameter\n * 4. `GOOGLE_CLOUD_CREDENTIALS` environment variable\n * 5. `googleAuthOptions` parameter\n * 6. Application Default Credentials (if googleAuthOptions is provided without explicit credentials)\n *\n * @extends ApiClient\n *\n * @example\n * ```typescript\n * // Using API key\n * const client = new NodeApiClient({\n * apiKey: 'your-api-key'\n * });\n *\n * // Using service account credentials\n * const client = new NodeApiClient({\n * credentials: {\n * type: \"service_account\",\n * project_id: \"my-project\",\n * private_key_id: \"key-id\",\n * private_key: \"-----BEGIN PRIVATE KEY-----\\n...\",\n * client_email: \"service-account@project.iam.gserviceaccount.com\",\n * // ... other required fields\n * }\n * });\n *\n * // Using Google Auth with custom scopes\n * const client = new NodeApiClient({\n * googleAuthOptions: {\n * scopes: ['https://www.googleapis.com/auth/cloud-platform'],\n * keyFilename: '/path/to/service-account-key.json'\n * }\n * });\n *\n * // Using Application Default Credentials\n * const client = new NodeApiClient({\n * googleAuthOptions: {}\n * });\n *\n * // Using environment variables\n * // Set GOOGLE_API_KEY or GOOGLE_CLOUD_CREDENTIALS\n * const client = new NodeApiClient();\n *\n * // Make authenticated requests\n * const request = new Request('https://api.google.com/...');\n * const response = await client.fetch(request);\n * ```\n *\n * @remarks\n * - API keys are added via the `X-Goog-Api-Key` header\n * - Service account tokens are added via the `Authorization` header with Bearer scheme\n * - Google Auth headers are automatically generated and added by google-auth-library\n * - Tokens are automatically cached and refreshed as needed\n * - For web/edge environments without google-auth-library, use WebApiClient instead\n *\n * @see {@link WebApiClient} for web-compatible authentication without google-auth-library\n * @see {@link GCPCredentials} for service account credential structure\n * @see {@link GoogleAuthOptions} for advanced authentication configuration\n */\nexport class NodeApiClient extends ApiClient {\n hasApiKey(): boolean {\n return typeof this.apiKey === \"string\" && this.apiKey !== \"\";\n }\n\n async getProjectId(): Promise<string> {\n if (typeof this.credentials !== \"undefined\") {\n return this.credentials.project_id;\n } else if (typeof this.googleAuth !== \"undefined\") {\n return this.googleAuth.getProjectId();\n } else {\n return super.getProjectId();\n }\n }\n\n /**\n * The Google API key used for authentication, if provided.\n *\n * This value is resolved from either the constructor parameter or the\n * `GOOGLE_API_KEY` environment variable.\n *\n * @protected\n */\n protected apiKey?: string;\n\n /**\n * The normalized GCP service account credentials, if provided.\n *\n * This value is resolved from either the constructor parameter or the\n * `GOOGLE_CLOUD_CREDENTIALS` environment variable, and is normalized\n * to ensure immutability.\n *\n * @protected\n */\n protected credentials?: GCPCredentials;\n\n /**\n * The Google Auth instance for advanced authentication, if configured.\n *\n * This instance is created when `googleAuthOptions` is provided and\n * handles Application Default Credentials, custom scopes, and other\n * advanced authentication scenarios.\n *\n * @protected\n */\n protected googleAuth?: GoogleAuth;\n\n /**\n * Creates a new NodeApiClient instance.\n *\n * The constructor initializes authentication credentials by checking:\n * 1. Explicit parameters passed to the constructor\n * 2. Environment variables (`GOOGLE_API_KEY`, `GOOGLE_CLOUD_CREDENTIALS`)\n * 3. Application Default Credentials (if googleAuthOptions is provided)\n *\n * Credentials are normalized and frozen to prevent accidental modification.\n * The GoogleAuth instance is lazily initialized only when googleAuthOptions\n * is provided.\n *\n * @param params - Configuration parameters for the client. Defaults to an empty object.\n *\n * @example\n * ```typescript\n * // Minimal configuration (uses environment variables or ADC)\n * const client = new NodeApiClient();\n *\n * // With explicit API key\n * const client = new WebApiClient({\n * apiKey: 'your-api-key'\n * });\n *\n * // With service account credentials as JSON string\n * const client = new WebApiClient({\n * credentials: '{\"type\":\"service_account\",...}'\n * });\n *\n * // With service account credentials as object\n * const client = new NodeApiClient({\n * credentials: {\n * type: \"service_account\",\n * // ... other fields\n * }\n * });\n *\n * // With Google Auth options\n * const client = new NodeApiClient({\n * googleAuthOptions: {\n * scopes: ['https://www.googleapis.com/auth/cloud-platform'],\n * projectId: 'my-project'\n * }\n * });\n * ```\n */\n constructor(protected params: NodeApiClientParams = {}) {\n super();\n\n this.apiKey = params.apiKey ?? getEnvironmentVariable(\"GOOGLE_API_KEY\");\n this.credentials = iife(() => {\n if (params.credentials) {\n return normalizeGCPCredentials(params.credentials);\n }\n const credentialsVar = getEnvironmentVariable(\"GOOGLE_CLOUD_CREDENTIALS\");\n if (credentialsVar) {\n return normalizeGCPCredentials(credentialsVar);\n }\n return undefined;\n });\n this.googleAuth = iife(() => {\n if (params.googleAuthOptions) {\n return new GoogleAuth(params.googleAuthOptions);\n }\n if (!this.apiKey && !this.credentials) {\n return new GoogleAuth();\n }\n return undefined;\n });\n }\n\n /**\n * Executes an HTTP request with appropriate Google API authentication.\n *\n * This method adds authentication headers to the request based on the\n * configured authentication method, following this priority:\n *\n * 1. If an API key is configured, adds the `X-Goog-Api-Key` header\n * 2. If service account credentials are configured, generates an access token\n * and adds it via the `Authorization` header with Bearer scheme\n * 3. If Google Auth is configured, uses google-auth-library to generate\n * appropriate authentication headers (may include Authorization, x-goog-user-project, etc.)\n *\n * The authentication priority ensures that explicit API keys take precedence,\n * followed by service account credentials, and finally Google Auth options.\n *\n * @param request - The HTTP request to execute. Headers will be modified\n * in-place to include authentication information.\n * @returns A Promise that resolves to the HTTP response\n *\n * @throws {AuthError} If service account authentication fails (e.g., invalid\n * credentials, network error, or token generation failure)\n * @throws {Error} If Google Auth authentication fails (e.g., missing credentials,\n * invalid configuration, or ADC not available)\n *\n * @example\n * ```typescript\n * const client = new NodeApiClient({ apiKey: 'your-key' });\n * const request = new Request('https://generativelanguage.googleapis.com/v1/models');\n * const response = await client.fetch(request);\n * const data = await response.json();\n * ```\n *\n * @remarks\n * - The request object is modified in-place by adding headers\n * - Service account tokens are automatically cached and refreshed\n * - Google Auth tokens are managed by google-auth-library with automatic refresh\n * - Only one authentication method is used per request (based on priority)\n * - Google Auth may add multiple headers depending on the authentication type\n */\n async fetch(request: Request): Promise<Response> {\n if (this.apiKey) {\n request.headers.set(GOOGLE_API_KEY_HEADER, this.apiKey);\n } else if (this.credentials) {\n request.headers.set(\n GCP_API_KEY_HEADER,\n `Bearer ${getGCPCredentialsAccessToken(this.credentials)}`\n );\n } else if (this.googleAuth) {\n const authHeaders = await this.googleAuth.getRequestHeaders(request.url);\n authHeaders.forEach((value, key) => {\n if (value !== null) {\n request.headers.set(key, value);\n }\n });\n }\n return fetch(request);\n }\n}\n\n/**\n * Ensures that Google Auth options include required OAuth2 scopes.\n *\n * This utility function validates and augments GoogleAuthOptions to ensure\n * that all required OAuth2 scopes are present. It handles three scenarios:\n *\n * 1. **No auth options provided**: Creates new options with required scopes\n * 2. **Auth options without scopes**: Adds required scopes to existing options\n * 3. **Auth options with scopes**: Validates that all required scopes are present\n *\n * This is particularly useful when working with Google APIs that require specific\n * scopes for access, ensuring that authentication is properly configured before\n * making API requests.\n *\n * @param authOptions - The existing Google Auth options to validate/augment.\n * Can be undefined or an empty object.\n * @param requiredScopes - Array of OAuth2 scope URLs that must be present.\n * These are typically Google API scope URLs like\n * 'https://www.googleapis.com/auth/cloud-platform'\n * @returns The validated/augmented GoogleAuthOptions with all required scopes\n *\n * @throws {Error} If authOptions already has scopes but is missing any of the\n * required scopes. This prevents accidental scope reduction that\n * could break API access.\n *\n * @example\n * ```typescript\n * // Create new options with required scopes\n * const options = ensureAuthScopes(undefined, [\n * 'https://www.googleapis.com/auth/cloud-platform'\n * ]);\n * // Result: { scopes: ['https://www.googleapis.com/auth/cloud-platform'] }\n *\n * // Add scopes to existing options\n * const options = ensureAuthScopes(\n * { projectId: 'my-project' },\n * ['https://www.googleapis.com/auth/cloud-platform']\n * );\n * // Result: { projectId: 'my-project', scopes: [...] }\n *\n * // Validate existing scopes\n * const options = ensureAuthScopes(\n * { scopes: ['https://www.googleapis.com/auth/cloud-platform'] },\n * ['https://www.googleapis.com/auth/cloud-platform']\n * );\n * // Result: Original options (validation passed)\n *\n * // Error case - missing required scope\n * try {\n * ensureAuthScopes(\n * { scopes: ['https://www.googleapis.com/auth/userinfo.email'] },\n * ['https://www.googleapis.com/auth/cloud-platform']\n * );\n * } catch (error) {\n * // Error: Invalid auth scopes. Scopes must include ...\n * }\n * ```\n *\n * @remarks\n * - Scopes can be provided as a string or array of strings in GoogleAuthOptions\n * - The function normalizes single-string scopes to arrays for validation\n * - Required scopes are not automatically added if existing scopes are present;\n * instead, an error is thrown to prevent unintended scope changes\n * - This function does not modify the original authOptions object\n *\n * @see https://developers.google.com/identity/protocols/oauth2/scopes\n * @see {@link GoogleAuthOptions} for the full authentication configuration interface\n */\nexport function ensureAuthScopes(\n authOptions: GoogleAuthOptions,\n requiredScopes: string[]\n): GoogleAuthOptions {\n if (!authOptions) {\n return { scopes: requiredScopes };\n } else if (!authOptions.scopes) {\n return { ...authOptions, scopes: requiredScopes };\n } else {\n const existingScopes = Array.isArray(authOptions.scopes)\n ? authOptions.scopes\n : [authOptions.scopes];\n const missingScopes = requiredScopes.filter(\n (scope) => !existingScopes.includes(scope)\n );\n if (missingScopes.length > 0) {\n throw new ConfigurationError(\n `Invalid auth scopes. Scopes must include ${requiredScopes.join(\", \")}`\n );\n }\n }\n return authOptions;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAkJA,IAAa,gBAAb,cAAmCA,cAAAA,UAAU;CAC3C,YAAqB;AACnB,SAAO,OAAO,KAAK,WAAW,YAAY,KAAK,WAAW;;CAG5D,MAAM,eAAgC;AACpC,MAAI,OAAO,KAAK,gBAAgB,YAC9B,QAAO,KAAK,YAAY;WACf,OAAO,KAAK,eAAe,YACpC,QAAO,KAAK,WAAW,cAAc;MAErC,QAAO,MAAM,cAAc;;;;;;;;;;CAY/B;;;;;;;;;;CAWA;;;;;;;;;;CAWA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAgDA,YAAY,SAAwC,EAAE,EAAE;AACtD,SAAO;AADa,OAAA,SAAA;AAGpB,OAAK,SAAS,OAAO,WAAA,GAAA,0BAAA,wBAAiC,iBAAiB;AACvE,OAAK,cAAcC,aAAAA,WAAW;AAC5B,OAAI,OAAO,YACT,QAAOC,iBAAAA,wBAAwB,OAAO,YAAY;GAEpD,MAAM,kBAAA,GAAA,0BAAA,wBAAwC,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_API_KEY_HEADER","getGCPCredentialsAccessToken","ConfigurationError"],"sources":["../../src/clients/node.ts"],"sourcesContent":["import { GoogleAuth, type GoogleAuthOptions } from \"google-auth-library\";\nimport { getEnvironmentVariable } from \"@langchain/core/utils/env\";\nimport { GCP_API_KEY_HEADER, GOOGLE_API_KEY_HEADER } from \"../const.js\";\nimport { ApiClient } from \"./index.js\";\nimport {\n GCPCredentials,\n getGCPCredentialsAccessToken,\n normalizeGCPCredentials,\n} from \"../utils/gcp-auth.js\";\nimport { ConfigurationError } from \"../utils/errors.js\";\nimport { iife } from \"../utils/misc.js\";\n\n/**\n * Configuration parameters for the NodeApiClient.\n *\n * This interface defines the authentication options available for Node.js-based\n * API clients. Authentication can be provided via an API key, GCP service\n * account credentials, or advanced Google Auth options. The client will\n * automatically check environment variables if explicit values are not provided.\n *\n * @interface\n */\nexport interface NodeApiClientParams {\n /**\n * Google API key for authentication.\n *\n * If not provided, the client will attempt to read from the\n * `GOOGLE_API_KEY` environment variable.\n *\n * @see https://cloud.google.com/docs/authentication/api-keys\n */\n apiKey?: string;\n\n /**\n * GCP service account credentials for authentication.\n *\n * Can be provided as either:\n * - A JSON string containing the service account key\n * - A GCPCredentials object\n *\n * If not provided, the client will attempt to read from the\n * `GOOGLE_CLOUD_CREDENTIALS` environment variable.\n *\n * @see https://cloud.google.com/iam/docs/creating-managing-service-account-keys\n */\n credentials?: string | GCPCredentials;\n\n /**\n * Google Auth options configuration.\n *\n * Provides fine-grained control over authentication behavior using the\n * google-auth-library. This option enables:\n * - Custom OAuth2 scopes\n * - Application Default Credentials (ADC)\n * - Impersonation and delegation\n * - Custom credential sources\n *\n * When provided, this takes precedence over simple credential-based auth\n * but is lower priority than API key authentication.\n *\n * @see https://github.com/googleapis/google-auth-library-nodejs\n * @see https://cloud.google.com/docs/authentication/application-default-credentials\n */\n googleAuthOptions?: GoogleAuthOptions;\n}\n\n/**\n * Node.js-specific API client for Google services.\n *\n * This client provides comprehensive authentication for Google API requests in\n * Node.js environments, leveraging the full capabilities of the google-auth-library.\n * It supports three authentication methods with the following priority:\n *\n * 1. **API Key Authentication**: Simple key-based authentication suitable for\n * public APIs and development environments.\n *\n * 2. **Service Account Credentials**: OAuth2-based authentication using GCP\n * service account keys. The client automatically handles token generation\n * and caching using a web-compatible implementation.\n *\n * 3. **Google Auth Library**: Advanced authentication using google-auth-library,\n * supporting Application Default Credentials (ADC), custom scopes, and\n * various credential sources.\n *\n * The client follows this authentication priority:\n * 1. Explicit `apiKey` parameter\n * 2. `GOOGLE_API_KEY` environment variable\n * 3. Explicit `credentials` parameter\n * 4. `GOOGLE_CLOUD_CREDENTIALS` environment variable\n * 5. `googleAuthOptions` parameter\n * 6. Application Default Credentials (if googleAuthOptions is provided without explicit credentials)\n *\n * @extends ApiClient\n *\n * @example\n * ```typescript\n * // Using API key\n * const client = new NodeApiClient({\n * apiKey: 'your-api-key'\n * });\n *\n * // Using service account credentials\n * const client = new NodeApiClient({\n * credentials: {\n * type: \"service_account\",\n * project_id: \"my-project\",\n * private_key_id: \"key-id\",\n * private_key: \"-----BEGIN PRIVATE KEY-----\\n...\",\n * client_email: \"service-account@project.iam.gserviceaccount.com\",\n * // ... other required fields\n * }\n * });\n *\n * // Using Google Auth with custom scopes\n * const client = new NodeApiClient({\n * googleAuthOptions: {\n * scopes: ['https://www.googleapis.com/auth/cloud-platform'],\n * keyFilename: '/path/to/service-account-key.json'\n * }\n * });\n *\n * // Using Application Default Credentials\n * const client = new NodeApiClient({\n * googleAuthOptions: {}\n * });\n *\n * // Using environment variables\n * // Set GOOGLE_API_KEY or GOOGLE_CLOUD_CREDENTIALS\n * const client = new NodeApiClient();\n *\n * // Make authenticated requests\n * const request = new Request('https://api.google.com/...');\n * const response = await client.fetch(request);\n * ```\n *\n * @remarks\n * - API keys are added via the `X-Goog-Api-Key` header\n * - Service account tokens are added via the `Authorization` header with Bearer scheme\n * - Google Auth headers are automatically generated and added by google-auth-library\n * - Tokens are automatically cached and refreshed as needed\n * - For web/edge environments without google-auth-library, use WebApiClient instead\n *\n * @see {@link WebApiClient} for web-compatible authentication without google-auth-library\n * @see {@link GCPCredentials} for service account credential structure\n * @see {@link GoogleAuthOptions} for advanced authentication configuration\n */\nexport class NodeApiClient extends ApiClient {\n hasApiKey(): boolean {\n return typeof this.apiKey === \"string\" && this.apiKey !== \"\";\n }\n\n async getProjectId(): Promise<string> {\n if (typeof this.credentials !== \"undefined\") {\n return this.credentials.project_id;\n } else if (typeof this.googleAuth !== \"undefined\") {\n return this.googleAuth.getProjectId();\n } else {\n return super.getProjectId();\n }\n }\n\n /**\n * The Google API key used for authentication, if provided.\n *\n * This value is resolved from either the constructor parameter or the\n * `GOOGLE_API_KEY` environment variable.\n *\n * @protected\n */\n protected apiKey?: string;\n\n /**\n * The normalized GCP service account credentials, if provided.\n *\n * This value is resolved from either the constructor parameter or the\n * `GOOGLE_CLOUD_CREDENTIALS` environment variable, and is normalized\n * to ensure immutability.\n *\n * @protected\n */\n protected credentials?: GCPCredentials;\n\n /**\n * The Google Auth instance for advanced authentication, if configured.\n *\n * This instance is created when `googleAuthOptions` is provided and\n * handles Application Default Credentials, custom scopes, and other\n * advanced authentication scenarios.\n *\n * @protected\n */\n protected googleAuth?: GoogleAuth;\n\n /**\n * Creates a new NodeApiClient instance.\n *\n * The constructor initializes authentication credentials by checking:\n * 1. Explicit parameters passed to the constructor\n * 2. Environment variables (`GOOGLE_API_KEY`, `GOOGLE_CLOUD_CREDENTIALS`)\n * 3. Application Default Credentials (if googleAuthOptions is provided)\n *\n * Credentials are normalized and frozen to prevent accidental modification.\n * The GoogleAuth instance is lazily initialized only when googleAuthOptions\n * is provided.\n *\n * @param params - Configuration parameters for the client. Defaults to an empty object.\n *\n * @example\n * ```typescript\n * // Minimal configuration (uses environment variables or ADC)\n * const client = new NodeApiClient();\n *\n * // With explicit API key\n * const client = new WebApiClient({\n * apiKey: 'your-api-key'\n * });\n *\n * // With service account credentials as JSON string\n * const client = new WebApiClient({\n * credentials: '{\"type\":\"service_account\",...}'\n * });\n *\n * // With service account credentials as object\n * const client = new NodeApiClient({\n * credentials: {\n * type: \"service_account\",\n * // ... other fields\n * }\n * });\n *\n * // With Google Auth options\n * const client = new NodeApiClient({\n * googleAuthOptions: {\n * scopes: ['https://www.googleapis.com/auth/cloud-platform'],\n * projectId: 'my-project'\n * }\n * });\n * ```\n */\n constructor(protected params: NodeApiClientParams = {}) {\n super();\n\n this.apiKey = params.apiKey ?? getEnvironmentVariable(\"GOOGLE_API_KEY\");\n this.credentials = iife(() => {\n if (params.credentials) {\n return normalizeGCPCredentials(params.credentials);\n }\n const credentialsVar = getEnvironmentVariable(\"GOOGLE_CLOUD_CREDENTIALS\");\n if (credentialsVar) {\n return normalizeGCPCredentials(credentialsVar);\n }\n return undefined;\n });\n this.googleAuth = iife(() => {\n if (params.googleAuthOptions) {\n return new GoogleAuth(params.googleAuthOptions);\n }\n if (!this.apiKey && !this.credentials) {\n return new GoogleAuth();\n }\n return undefined;\n });\n }\n\n /**\n * Executes an HTTP request with appropriate Google API authentication.\n *\n * This method adds authentication headers to the request based on the\n * configured authentication method, following this priority:\n *\n * 1. If an API key is configured, adds the `X-Goog-Api-Key` header\n * 2. If service account credentials are configured, generates an access token\n * and adds it via the `Authorization` header with Bearer scheme\n * 3. If Google Auth is configured, uses google-auth-library to generate\n * appropriate authentication headers (may include Authorization, x-goog-user-project, etc.)\n *\n * The authentication priority ensures that explicit API keys take precedence,\n * followed by service account credentials, and finally Google Auth options.\n *\n * @param request - The HTTP request to execute. Headers will be modified\n * in-place to include authentication information.\n * @returns A Promise that resolves to the HTTP response\n *\n * @throws {AuthError} If service account authentication fails (e.g., invalid\n * credentials, network error, or token generation failure)\n * @throws {Error} If Google Auth authentication fails (e.g., missing credentials,\n * invalid configuration, or ADC not available)\n *\n * @example\n * ```typescript\n * const client = new NodeApiClient({ apiKey: 'your-key' });\n * const request = new Request('https://generativelanguage.googleapis.com/v1/models');\n * const response = await client.fetch(request);\n * const data = await response.json();\n * ```\n *\n * @remarks\n * - The request object is modified in-place by adding headers\n * - Service account tokens are automatically cached and refreshed\n * - Google Auth tokens are managed by google-auth-library with automatic refresh\n * - Only one authentication method is used per request (based on priority)\n * - Google Auth may add multiple headers depending on the authentication type\n */\n async fetch(request: Request): Promise<Response> {\n if (this.apiKey) {\n request.headers.set(GOOGLE_API_KEY_HEADER, this.apiKey);\n } else if (this.credentials) {\n request.headers.set(\n GCP_API_KEY_HEADER,\n `Bearer ${getGCPCredentialsAccessToken(this.credentials)}`\n );\n } else if (this.googleAuth) {\n const authHeaders = await this.googleAuth.getRequestHeaders(request.url);\n authHeaders.forEach((value, key) => {\n if (value !== null) {\n request.headers.set(key, value);\n }\n });\n }\n return fetch(request);\n }\n}\n\n/**\n * Ensures that Google Auth options include required OAuth2 scopes.\n *\n * This utility function validates and augments GoogleAuthOptions to ensure\n * that all required OAuth2 scopes are present. It handles three scenarios:\n *\n * 1. **No auth options provided**: Creates new options with required scopes\n * 2. **Auth options without scopes**: Adds required scopes to existing options\n * 3. **Auth options with scopes**: Validates that all required scopes are present\n *\n * This is particularly useful when working with Google APIs that require specific\n * scopes for access, ensuring that authentication is properly configured before\n * making API requests.\n *\n * @param authOptions - The existing Google Auth options to validate/augment.\n * Can be undefined or an empty object.\n * @param requiredScopes - Array of OAuth2 scope URLs that must be present.\n * These are typically Google API scope URLs like\n * 'https://www.googleapis.com/auth/cloud-platform'\n * @returns The validated/augmented GoogleAuthOptions with all required scopes\n *\n * @throws {Error} If authOptions already has scopes but is missing any of the\n * required scopes. This prevents accidental scope reduction that\n * could break API access.\n *\n * @example\n * ```typescript\n * // Create new options with required scopes\n * const options = ensureAuthScopes(undefined, [\n * 'https://www.googleapis.com/auth/cloud-platform'\n * ]);\n * // Result: { scopes: ['https://www.googleapis.com/auth/cloud-platform'] }\n *\n * // Add scopes to existing options\n * const options = ensureAuthScopes(\n * { projectId: 'my-project' },\n * ['https://www.googleapis.com/auth/cloud-platform']\n * );\n * // Result: { projectId: 'my-project', scopes: [...] }\n *\n * // Validate existing scopes\n * const options = ensureAuthScopes(\n * { scopes: ['https://www.googleapis.com/auth/cloud-platform'] },\n * ['https://www.googleapis.com/auth/cloud-platform']\n * );\n * // Result: Original options (validation passed)\n *\n * // Error case - missing required scope\n * try {\n * ensureAuthScopes(\n * { scopes: ['https://www.googleapis.com/auth/userinfo.email'] },\n * ['https://www.googleapis.com/auth/cloud-platform']\n * );\n * } catch (error) {\n * // Error: Invalid auth scopes. Scopes must include ...\n * }\n * ```\n *\n * @remarks\n * - Scopes can be provided as a string or array of strings in GoogleAuthOptions\n * - The function normalizes single-string scopes to arrays for validation\n * - Required scopes are not automatically added if existing scopes are present;\n * instead, an error is thrown to prevent unintended scope changes\n * - This function does not modify the original authOptions object\n *\n * @see https://developers.google.com/identity/protocols/oauth2/scopes\n * @see {@link GoogleAuthOptions} for the full authentication configuration interface\n */\nexport function ensureAuthScopes(\n authOptions: GoogleAuthOptions,\n requiredScopes: string[]\n): GoogleAuthOptions {\n if (!authOptions) {\n return { scopes: requiredScopes };\n } else if (!authOptions.scopes) {\n return { ...authOptions, scopes: requiredScopes };\n } else {\n const existingScopes = Array.isArray(authOptions.scopes)\n ? authOptions.scopes\n : [authOptions.scopes];\n const missingScopes = requiredScopes.filter(\n (scope) => !existingScopes.includes(scope)\n );\n if (missingScopes.length > 0) {\n throw new ConfigurationError(\n `Invalid auth scopes. Scopes must include ${requiredScopes.join(\", \")}`\n );\n }\n }\n return authOptions;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAkJA,IAAa,gBAAb,cAAmCA,cAAAA,UAAU;CAC3C,YAAqB;AACnB,SAAO,OAAO,KAAK,WAAW,YAAY,KAAK,WAAW;;CAG5D,MAAM,eAAgC;AACpC,MAAI,OAAO,KAAK,gBAAgB,YAC9B,QAAO,KAAK,YAAY;WACf,OAAO,KAAK,eA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,QAAO,EAAE,QAAQ,gBAAgB;UACxB,CAAC,YAAY,OACtB,QAAO;EAAE,GAAG;EAAa,QAAQ;EAAgB;MAC5C;EACL,MAAM,iBAAiB,MAAM,QAAQ,YAAY,OAAO,GACpD,YAAY,SACZ,CAAC,YAAY,OAAO;AAIxB,MAHsB,eAAe,QAClC,UAAU,CAAC,eAAe,SAAS,MAAM,CAE3B,CAAC,SAAS,EACzB,OAAM,IAAIC,eAAAA,mBACR,4CAA4C,eAAe,KAAK,KAAK,GACtE;;AAGL,QAAO"}
@@ -1 +1 @@
1
- {"version":3,"file":"node.js","names":[],"sources":["../../src/clients/node.ts"],"sourcesContent":["import { GoogleAuth, type GoogleAuthOptions } from \"google-auth-library\";\nimport { getEnvironmentVariable } from \"@langchain/core/utils/env\";\nimport { GCP_API_KEY_HEADER, GOOGLE_API_KEY_HEADER } from \"../const.js\";\nimport { ApiClient } from \"./index.js\";\nimport {\n GCPCredentials,\n getGCPCredentialsAccessToken,\n normalizeGCPCredentials,\n} from \"../utils/gcp-auth.js\";\nimport { ConfigurationError } from \"../utils/errors.js\";\nimport { iife } from \"../utils/misc.js\";\n\n/**\n * Configuration parameters for the NodeApiClient.\n *\n * This interface defines the authentication options available for Node.js-based\n * API clients. Authentication can be provided via an API key, GCP service\n * account credentials, or advanced Google Auth options. The client will\n * automatically check environment variables if explicit values are not provided.\n *\n * @interface\n */\nexport interface NodeApiClientParams {\n /**\n * Google API key for authentication.\n *\n * If not provided, the client will attempt to read from the\n * `GOOGLE_API_KEY` environment variable.\n *\n * @see https://cloud.google.com/docs/authentication/api-keys\n */\n apiKey?: string;\n\n /**\n * GCP service account credentials for authentication.\n *\n * Can be provided as either:\n * - A JSON string containing the service account key\n * - A GCPCredentials object\n *\n * If not provided, the client will attempt to read from the\n * `GOOGLE_CLOUD_CREDENTIALS` environment variable.\n *\n * @see https://cloud.google.com/iam/docs/creating-managing-service-account-keys\n */\n credentials?: string | GCPCredentials;\n\n /**\n * Google Auth options configuration.\n *\n * Provides fine-grained control over authentication behavior using the\n * google-auth-library. This option enables:\n * - Custom OAuth2 scopes\n * - Application Default Credentials (ADC)\n * - Impersonation and delegation\n * - Custom credential sources\n *\n * When provided, this takes precedence over simple credential-based auth\n * but is lower priority than API key authentication.\n *\n * @see https://github.com/googleapis/google-auth-library-nodejs\n * @see https://cloud.google.com/docs/authentication/application-default-credentials\n */\n googleAuthOptions?: GoogleAuthOptions;\n}\n\n/**\n * Node.js-specific API client for Google services.\n *\n * This client provides comprehensive authentication for Google API requests in\n * Node.js environments, leveraging the full capabilities of the google-auth-library.\n * It supports three authentication methods with the following priority:\n *\n * 1. **API Key Authentication**: Simple key-based authentication suitable for\n * public APIs and development environments.\n *\n * 2. **Service Account Credentials**: OAuth2-based authentication using GCP\n * service account keys. The client automatically handles token generation\n * and caching using a web-compatible implementation.\n *\n * 3. **Google Auth Library**: Advanced authentication using google-auth-library,\n * supporting Application Default Credentials (ADC), custom scopes, and\n * various credential sources.\n *\n * The client follows this authentication priority:\n * 1. Explicit `apiKey` parameter\n * 2. `GOOGLE_API_KEY` environment variable\n * 3. Explicit `credentials` parameter\n * 4. `GOOGLE_CLOUD_CREDENTIALS` environment variable\n * 5. `googleAuthOptions` parameter\n * 6. Application Default Credentials (if googleAuthOptions is provided without explicit credentials)\n *\n * @extends ApiClient\n *\n * @example\n * ```typescript\n * // Using API key\n * const client = new NodeApiClient({\n * apiKey: 'your-api-key'\n * });\n *\n * // Using service account credentials\n * const client = new NodeApiClient({\n * credentials: {\n * type: \"service_account\",\n * project_id: \"my-project\",\n * private_key_id: \"key-id\",\n * private_key: \"-----BEGIN PRIVATE KEY-----\\n...\",\n * client_email: \"service-account@project.iam.gserviceaccount.com\",\n * // ... other required fields\n * }\n * });\n *\n * // Using Google Auth with custom scopes\n * const client = new NodeApiClient({\n * googleAuthOptions: {\n * scopes: ['https://www.googleapis.com/auth/cloud-platform'],\n * keyFilename: '/path/to/service-account-key.json'\n * }\n * });\n *\n * // Using Application Default Credentials\n * const client = new NodeApiClient({\n * googleAuthOptions: {}\n * });\n *\n * // Using environment variables\n * // Set GOOGLE_API_KEY or GOOGLE_CLOUD_CREDENTIALS\n * const client = new NodeApiClient();\n *\n * // Make authenticated requests\n * const request = new Request('https://api.google.com/...');\n * const response = await client.fetch(request);\n * ```\n *\n * @remarks\n * - API keys are added via the `X-Goog-Api-Key` header\n * - Service account tokens are added via the `Authorization` header with Bearer scheme\n * - Google Auth headers are automatically generated and added by google-auth-library\n * - Tokens are automatically cached and refreshed as needed\n * - For web/edge environments without google-auth-library, use WebApiClient instead\n *\n * @see {@link WebApiClient} for web-compatible authentication without google-auth-library\n * @see {@link GCPCredentials} for service account credential structure\n * @see {@link GoogleAuthOptions} for advanced authentication configuration\n */\nexport class NodeApiClient extends ApiClient {\n hasApiKey(): boolean {\n return typeof this.apiKey === \"string\" && this.apiKey !== \"\";\n }\n\n async getProjectId(): Promise<string> {\n if (typeof this.credentials !== \"undefined\") {\n return this.credentials.project_id;\n } else if (typeof this.googleAuth !== \"undefined\") {\n return this.googleAuth.getProjectId();\n } else {\n return super.getProjectId();\n }\n }\n\n /**\n * The Google API key used for authentication, if provided.\n *\n * This value is resolved from either the constructor parameter or the\n * `GOOGLE_API_KEY` environment variable.\n *\n * @protected\n */\n protected apiKey?: string;\n\n /**\n * The normalized GCP service account credentials, if provided.\n *\n * This value is resolved from either the constructor parameter or the\n * `GOOGLE_CLOUD_CREDENTIALS` environment variable, and is normalized\n * to ensure immutability.\n *\n * @protected\n */\n protected credentials?: GCPCredentials;\n\n /**\n * The Google Auth instance for advanced authentication, if configured.\n *\n * This instance is created when `googleAuthOptions` is provided and\n * handles Application Default Credentials, custom scopes, and other\n * advanced authentication scenarios.\n *\n * @protected\n */\n protected googleAuth?: GoogleAuth;\n\n /**\n * Creates a new NodeApiClient instance.\n *\n * The constructor initializes authentication credentials by checking:\n * 1. Explicit parameters passed to the constructor\n * 2. Environment variables (`GOOGLE_API_KEY`, `GOOGLE_CLOUD_CREDENTIALS`)\n * 3. Application Default Credentials (if googleAuthOptions is provided)\n *\n * Credentials are normalized and frozen to prevent accidental modification.\n * The GoogleAuth instance is lazily initialized only when googleAuthOptions\n * is provided.\n *\n * @param params - Configuration parameters for the client. Defaults to an empty object.\n *\n * @example\n * ```typescript\n * // Minimal configuration (uses environment variables or ADC)\n * const client = new NodeApiClient();\n *\n * // With explicit API key\n * const client = new WebApiClient({\n * apiKey: 'your-api-key'\n * });\n *\n * // With service account credentials as JSON string\n * const client = new WebApiClient({\n * credentials: '{\"type\":\"service_account\",...}'\n * });\n *\n * // With service account credentials as object\n * const client = new NodeApiClient({\n * credentials: {\n * type: \"service_account\",\n * // ... other fields\n * }\n * });\n *\n * // With Google Auth options\n * const client = new NodeApiClient({\n * googleAuthOptions: {\n * scopes: ['https://www.googleapis.com/auth/cloud-platform'],\n * projectId: 'my-project'\n * }\n * });\n * ```\n */\n constructor(protected params: NodeApiClientParams = {}) {\n super();\n\n this.apiKey = params.apiKey ?? getEnvironmentVariable(\"GOOGLE_API_KEY\");\n this.credentials = iife(() => {\n if (params.credentials) {\n return normalizeGCPCredentials(params.credentials);\n }\n const credentialsVar = getEnvironmentVariable(\"GOOGLE_CLOUD_CREDENTIALS\");\n if (credentialsVar) {\n return normalizeGCPCredentials(credentialsVar);\n }\n return undefined;\n });\n this.googleAuth = iife(() => {\n if (params.googleAuthOptions) {\n return new GoogleAuth(params.googleAuthOptions);\n }\n if (!this.apiKey && !this.credentials) {\n return new GoogleAuth();\n }\n return undefined;\n });\n }\n\n /**\n * Executes an HTTP request with appropriate Google API authentication.\n *\n * This method adds authentication headers to the request based on the\n * configured authentication method, following this priority:\n *\n * 1. If an API key is configured, adds the `X-Goog-Api-Key` header\n * 2. If service account credentials are configured, generates an access token\n * and adds it via the `Authorization` header with Bearer scheme\n * 3. If Google Auth is configured, uses google-auth-library to generate\n * appropriate authentication headers (may include Authorization, x-goog-user-project, etc.)\n *\n * The authentication priority ensures that explicit API keys take precedence,\n * followed by service account credentials, and finally Google Auth options.\n *\n * @param request - The HTTP request to execute. Headers will be modified\n * in-place to include authentication information.\n * @returns A Promise that resolves to the HTTP response\n *\n * @throws {AuthError} If service account authentication fails (e.g., invalid\n * credentials, network error, or token generation failure)\n * @throws {Error} If Google Auth authentication fails (e.g., missing credentials,\n * invalid configuration, or ADC not available)\n *\n * @example\n * ```typescript\n * const client = new NodeApiClient({ apiKey: 'your-key' });\n * const request = new Request('https://generativelanguage.googleapis.com/v1/models');\n * const response = await client.fetch(request);\n * const data = await response.json();\n * ```\n *\n * @remarks\n * - The request object is modified in-place by adding headers\n * - Service account tokens are automatically cached and refreshed\n * - Google Auth tokens are managed by google-auth-library with automatic refresh\n * - Only one authentication method is used per request (based on priority)\n * - Google Auth may add multiple headers depending on the authentication type\n */\n async fetch(request: Request): Promise<Response> {\n if (this.apiKey) {\n request.headers.set(GOOGLE_API_KEY_HEADER, this.apiKey);\n } else if (this.credentials) {\n request.headers.set(\n GCP_API_KEY_HEADER,\n `Bearer ${getGCPCredentialsAccessToken(this.credentials)}`\n );\n } else if (this.googleAuth) {\n const authHeaders = await this.googleAuth.getRequestHeaders(request.url);\n authHeaders.forEach((value, key) => {\n if (value !== null) {\n request.headers.set(key, value);\n }\n });\n }\n return fetch(request);\n }\n}\n\n/**\n * Ensures that Google Auth options include required OAuth2 scopes.\n *\n * This utility function validates and augments GoogleAuthOptions to ensure\n * that all required OAuth2 scopes are present. It handles three scenarios:\n *\n * 1. **No auth options provided**: Creates new options with required scopes\n * 2. **Auth options without scopes**: Adds required scopes to existing options\n * 3. **Auth options with scopes**: Validates that all required scopes are present\n *\n * This is particularly useful when working with Google APIs that require specific\n * scopes for access, ensuring that authentication is properly configured before\n * making API requests.\n *\n * @param authOptions - The existing Google Auth options to validate/augment.\n * Can be undefined or an empty object.\n * @param requiredScopes - Array of OAuth2 scope URLs that must be present.\n * These are typically Google API scope URLs like\n * 'https://www.googleapis.com/auth/cloud-platform'\n * @returns The validated/augmented GoogleAuthOptions with all required scopes\n *\n * @throws {Error} If authOptions already has scopes but is missing any of the\n * required scopes. This prevents accidental scope reduction that\n * could break API access.\n *\n * @example\n * ```typescript\n * // Create new options with required scopes\n * const options = ensureAuthScopes(undefined, [\n * 'https://www.googleapis.com/auth/cloud-platform'\n * ]);\n * // Result: { scopes: ['https://www.googleapis.com/auth/cloud-platform'] }\n *\n * // Add scopes to existing options\n * const options = ensureAuthScopes(\n * { projectId: 'my-project' },\n * ['https://www.googleapis.com/auth/cloud-platform']\n * );\n * // Result: { projectId: 'my-project', scopes: [...] }\n *\n * // Validate existing scopes\n * const options = ensureAuthScopes(\n * { scopes: ['https://www.googleapis.com/auth/cloud-platform'] },\n * ['https://www.googleapis.com/auth/cloud-platform']\n * );\n * // Result: Original options (validation passed)\n *\n * // Error case - missing required scope\n * try {\n * ensureAuthScopes(\n * { scopes: ['https://www.googleapis.com/auth/userinfo.email'] },\n * ['https://www.googleapis.com/auth/cloud-platform']\n * );\n * } catch (error) {\n * // Error: Invalid auth scopes. Scopes must include ...\n * }\n * ```\n *\n * @remarks\n * - Scopes can be provided as a string or array of strings in GoogleAuthOptions\n * - The function normalizes single-string scopes to arrays for validation\n * - Required scopes are not automatically added if existing scopes are present;\n * instead, an error is thrown to prevent unintended scope changes\n * - This function does not modify the original authOptions object\n *\n * @see https://developers.google.com/identity/protocols/oauth2/scopes\n * @see {@link GoogleAuthOptions} for the full authentication configuration interface\n */\nexport function ensureAuthScopes(\n authOptions: GoogleAuthOptions,\n requiredScopes: string[]\n): GoogleAuthOptions {\n if (!authOptions) {\n return { scopes: requiredScopes };\n } else if (!authOptions.scopes) {\n return { ...authOptions, scopes: requiredScopes };\n } else {\n const existingScopes = Array.isArray(authOptions.scopes)\n ? authOptions.scopes\n : [authOptions.scopes];\n const missingScopes = requiredScopes.filter(\n (scope) => !existingScopes.includes(scope)\n );\n if (missingScopes.length > 0) {\n throw new ConfigurationError(\n `Invalid auth scopes. Scopes must include ${requiredScopes.join(\", \")}`\n );\n }\n }\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AU,KACZ,SAAQ,QAAQ,IAAI,KAAK,MAAM;IAEjC;AAEJ,SAAO,MAAM,QAAQ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAwEzB,SAAgB,iBACd,aACA,gBACmB;AACnB,KAAI,CAAC,YACH,QAAO,EAAE,QAAQ,gBAAgB;UACxB,CAAC,YAAY,OACtB,QAAO;EAAE,GAAG;EAAa,QAAQ;EAAgB;MAC5C;EACL,MAAM,iBAAiB,MAAM,QAAQ,YAAY,OAAO,GACpD,YAAY,SACZ,CAAC,YAAY,OAAO;AAIxB,MAHsB,eAAe,QAClC,UAAU,CAAC,eAAe,SAAS,MAAM,CAC3C,CACiB,SAAS,EACzB,OAAM,IAAI,mBACR,4CAA4C,eAAe,KAAK,KAAK,GACtE;;AAGL,QAAO"}
1
+ {"version":3,"file":"node.js","names":[],"sources":["../../src/clients/node.ts"],"sourcesContent":["import { GoogleAuth, type GoogleAuthOptions } from \"google-auth-library\";\nimport { getEnvironmentVariable } from \"@langchain/core/utils/env\";\nimport { GCP_API_KEY_HEADER, GOOGLE_API_KEY_HEADER } from \"../const.js\";\nimport { ApiClient } from \"./index.js\";\nimport {\n GCPCredentials,\n getGCPCredentialsAccessToken,\n normalizeGCPCredentials,\n} from \"../utils/gcp-auth.js\";\nimport { ConfigurationError } from \"../utils/errors.js\";\nimport { iife } from \"../utils/misc.js\";\n\n/**\n * Configuration parameters for the NodeApiClient.\n *\n * This interface defines the authentication options available for Node.js-based\n * API clients. Authentication can be provided via an API key, GCP service\n * account credentials, or advanced Google Auth options. The client will\n * automatically check environment variables if explicit values are not provided.\n *\n * @interface\n */\nexport interface NodeApiClientParams {\n /**\n * Google API key for authentication.\n *\n * If not provided, the client will attempt to read from the\n * `GOOGLE_API_KEY` environment variable.\n *\n * @see https://cloud.google.com/docs/authentication/api-keys\n */\n apiKey?: string;\n\n /**\n * GCP service account credentials for authentication.\n *\n * Can be provided as either:\n * - A JSON string containing the service account key\n * - A GCPCredentials object\n *\n * If not provided, the client will attempt to read from the\n * `GOOGLE_CLOUD_CREDENTIALS` environment variable.\n *\n * @see https://cloud.google.com/iam/docs/creating-managing-service-account-keys\n */\n credentials?: string | GCPCredentials;\n\n /**\n * Google Auth options configuration.\n *\n * Provides fine-grained control over authentication behavior using the\n * google-auth-library. This option enables:\n * - Custom OAuth2 scopes\n * - Application Default Credentials (ADC)\n * - Impersonation and delegation\n * - Custom credential sources\n *\n * When provided, this takes precedence over simple credential-based auth\n * but is lower priority than API key authentication.\n *\n * @see https://github.com/googleapis/google-auth-library-nodejs\n * @see https://cloud.google.com/docs/authentication/application-default-credentials\n */\n googleAuthOptions?: GoogleAuthOptions;\n}\n\n/**\n * Node.js-specific API client for Google services.\n *\n * This client provides comprehensive authentication for Google API requests in\n * Node.js environments, leveraging the full capabilities of the google-auth-library.\n * It supports three authentication methods with the following priority:\n *\n * 1. **API Key Authentication**: Simple key-based authentication suitable for\n * public APIs and development environments.\n *\n * 2. **Service Account Credentials**: OAuth2-based authentication using GCP\n * service account keys. The client automatically handles token generation\n * and caching using a web-compatible implementation.\n *\n * 3. **Google Auth Library**: Advanced authentication using google-auth-library,\n * supporting Application Default Credentials (ADC), custom scopes, and\n * various credential sources.\n *\n * The client follows this authentication priority:\n * 1. Explicit `apiKey` parameter\n * 2. `GOOGLE_API_KEY` environment variable\n * 3. Explicit `credentials` parameter\n * 4. `GOOGLE_CLOUD_CREDENTIALS` environment variable\n * 5. `googleAuthOptions` parameter\n * 6. Application Default Credentials (if googleAuthOptions is provided without explicit credentials)\n *\n * @extends ApiClient\n *\n * @example\n * ```typescript\n * // Using API key\n * const client = new NodeApiClient({\n * apiKey: 'your-api-key'\n * });\n *\n * // Using service account credentials\n * const client = new NodeApiClient({\n * credentials: {\n * type: \"service_account\",\n * project_id: \"my-project\",\n * private_key_id: \"key-id\",\n * private_key: \"-----BEGIN PRIVATE KEY-----\\n...\",\n * client_email: \"service-account@project.iam.gserviceaccount.com\",\n * // ... other required fields\n * }\n * });\n *\n * // Using Google Auth with custom scopes\n * const client = new NodeApiClient({\n * googleAuthOptions: {\n * scopes: ['https://www.googleapis.com/auth/cloud-platform'],\n * keyFilename: '/path/to/service-account-key.json'\n * }\n * });\n *\n * // Using Application Default Credentials\n * const client = new NodeApiClient({\n * googleAuthOptions: {}\n * });\n *\n * // Using environment variables\n * // Set GOOGLE_API_KEY or GOOGLE_CLOUD_CREDENTIALS\n * const client = new NodeApiClient();\n *\n * // Make authenticated requests\n * const request = new Request('https://api.google.com/...');\n * const response = await client.fetch(request);\n * ```\n *\n * @remarks\n * - API keys are added via the `X-Goog-Api-Key` header\n * - Service account tokens are added via the `Authorization` header with Bearer scheme\n * - Google Auth headers are automatically generated and added by google-auth-library\n * - Tokens are automatically cached and refreshed as needed\n * - For web/edge environments without google-auth-library, use WebApiClient instead\n *\n * @see {@link WebApiClient} for web-compatible authentication without google-auth-library\n * @see {@link GCPCredentials} for service account credential structure\n * @see {@link GoogleAuthOptions} for advanced authentication configuration\n */\nexport class NodeApiClient extends ApiClient {\n hasApiKey(): boolean {\n return typeof this.apiKey === \"string\" && this.apiKey !== \"\";\n }\n\n async getProjectId(): Promise<string> {\n if (typeof this.credentials !== \"undefined\") {\n return this.credentials.project_id;\n } else if (typeof this.googleAuth !== \"undefined\") {\n return this.googleAuth.getProjectId();\n } else {\n return super.getProjectId();\n }\n }\n\n /**\n * The Google API key used for authentication, if provided.\n *\n * This value is resolved from either the constructor parameter or the\n * `GOOGLE_API_KEY` environment variable.\n *\n * @protected\n */\n protected apiKey?: string;\n\n /**\n * The normalized GCP service account credentials, if provided.\n *\n * This value is resolved from either the constructor parameter or the\n * `GOOGLE_CLOUD_CREDENTIALS` environment variable, and is normalized\n * to ensure immutability.\n *\n * @protected\n */\n protected credentials?: GCPCredentials;\n\n /**\n * The Google Auth instance for advanced authentication, if configured.\n *\n * This instance is created when `googleAuthOptions` is provided and\n * handles Application Default Credentials, custom scopes, and other\n * advanced authentication scenarios.\n *\n * @protected\n */\n protected googleAuth?: GoogleAuth;\n\n /**\n * Creates a new NodeApiClient instance.\n *\n * The constructor initializes authentication credentials by checking:\n * 1. Explicit parameters passed to the constructor\n * 2. Environment variables (`GOOGLE_API_KEY`, `GOOGLE_CLOUD_CREDENTIALS`)\n * 3. Application Default Credentials (if googleAuthOptions is provided)\n *\n * Credentials are normalized and frozen to prevent accidental modification.\n * The GoogleAuth instance is lazily initialized only when googleAuthOptions\n * is provided.\n *\n * @param params - Configuration parameters for the client. Defaults to an empty object.\n *\n * @example\n * ```typescript\n * // Minimal configuration (uses environment variables or ADC)\n * const client = new NodeApiClient();\n *\n * // With explicit API key\n * const client = new WebApiClient({\n * apiKey: 'your-api-key'\n * });\n *\n * // With service account credentials as JSON string\n * const client = new WebApiClient({\n * credentials: '{\"type\":\"service_account\",...}'\n * });\n *\n * // With service account credentials as object\n * const client = new NodeApiClient({\n * credentials: {\n * type: \"service_account\",\n * // ... other fields\n * }\n * });\n *\n * // With Google Auth options\n * const client = new NodeApiClient({\n * googleAuthOptions: {\n * scopes: ['https://www.googleapis.com/auth/cloud-platform'],\n * projectId: 'my-project'\n * }\n * });\n * ```\n */\n constructor(protected params: NodeApiClientParams = {}) {\n super();\n\n this.apiKey = params.apiKey ?? getEnvironmentVariable(\"GOOGLE_API_KEY\");\n this.credentials = iife(() => {\n if (params.credentials) {\n return normalizeGCPCredentials(params.credentials);\n }\n const credentialsVar = getEnvironmentVariable(\"GOOGLE_CLOUD_CREDENTIALS\");\n if (credentialsVar) {\n return normalizeGCPCredentials(credentialsVar);\n }\n return undefined;\n });\n this.googleAuth = iife(() => {\n if (params.googleAuthOptions) {\n return new GoogleAuth(params.googleAuthOptions);\n }\n if (!this.apiKey && !this.credentials) {\n return new GoogleAuth();\n }\n return undefined;\n });\n }\n\n /**\n * Executes an HTTP request with appropriate Google API authentication.\n *\n * This method adds authentication headers to the request based on the\n * configured authentication method, following this priority:\n *\n * 1. If an API key is configured, adds the `X-Goog-Api-Key` header\n * 2. If service account credentials are configured, generates an access token\n * and adds it via the `Authorization` header with Bearer scheme\n * 3. If Google Auth is configured, uses google-auth-library to generate\n * appropriate authentication headers (may include Authorization, x-goog-user-project, etc.)\n *\n * The authentication priority ensures that explicit API keys take precedence,\n * followed by service account credentials, and finally Google Auth options.\n *\n * @param request - The HTTP request to execute. Headers will be modified\n * in-place to include authentication information.\n * @returns A Promise that resolves to the HTTP response\n *\n * @throws {AuthError} If service account authentication fails (e.g., invalid\n * credentials, network error, or token generation failure)\n * @throws {Error} If Google Auth authentication fails (e.g., missing credentials,\n * invalid configuration, or ADC not available)\n *\n * @example\n * ```typescript\n * const client = new NodeApiClient({ apiKey: 'your-key' });\n * const request = new Request('https://generativelanguage.googleapis.com/v1/models');\n * const response = await client.fetch(request);\n * const data = await response.json();\n * ```\n *\n * @remarks\n * - The request object is modified in-place by adding headers\n * - Service account tokens are automatically cached and refreshed\n * - Google Auth tokens are managed by google-auth-library with automatic refresh\n * - Only one authentication method is used per request (based on priority)\n * - Google Auth may add multiple headers depending on the authentication type\n */\n async fetch(request: Request): Promise<Response> {\n if (this.apiKey) {\n request.headers.set(GOOGLE_API_KEY_HEADER, this.apiKey);\n } else if (this.credentials) {\n request.headers.set(\n GCP_API_KEY_HEADER,\n `Bearer ${getGCPCredentialsAccessToken(this.credentials)}`\n );\n } else if (this.googleAuth) {\n const authHeaders = await this.googleAuth.getRequestHeaders(request.url);\n authHeaders.forEach((value, key) => {\n if (value !== null) {\n request.headers.set(key, value);\n }\n });\n }\n return fetch(request);\n }\n}\n\n/**\n * Ensures that Google Auth options include required OAuth2 scopes.\n *\n * This utility function validates and augments GoogleAuthOptions to ensure\n * that all required OAuth2 scopes are present. It handles three scenarios:\n *\n * 1. **No auth options provided**: Creates new options with required scopes\n * 2. **Auth options without scopes**: Adds required scopes to existing options\n * 3. **Auth options with scopes**: Validates that all required scopes are present\n *\n * This is particularly useful when working with Google APIs that require specific\n * scopes for access, ensuring that authentication is properly configured before\n * making API requests.\n *\n * @param authOptions - The existing Google Auth options to validate/augment.\n * Can be undefined or an empty object.\n * @param requiredScopes - Array of OAuth2 scope URLs that must be present.\n * These are typically Google API scope URLs like\n * 'https://www.googleapis.com/auth/cloud-platform'\n * @returns The validated/augmented GoogleAuthOptions with all required scopes\n *\n * @throws {Error} If authOptions already has scopes but is missing any of the\n * required scopes. This prevents accidental scope reduction that\n * could break API access.\n *\n * @example\n * ```typescript\n * // Create new options with required scopes\n * const options = ensureAuthScopes(undefined, [\n * 'https://www.googleapis.com/auth/cloud-platform'\n * ]);\n * // Result: { scopes: ['https://www.googleapis.com/auth/cloud-platform'] }\n *\n * // Add scopes to existing options\n * const options = ensureAuthScopes(\n * { projectId: 'my-project' },\n * ['https://www.googleapis.com/auth/cloud-platform']\n * );\n * // Result: { projectId: 'my-project', scopes: [...] }\n *\n * // Validate existing scopes\n * const options = ensureAuthScopes(\n * { scopes: ['https://www.googleapis.com/auth/cloud-platform'] },\n * ['https://www.googleapis.com/auth/cloud-platform']\n * );\n * // Result: Original options (validation passed)\n *\n * // Error case - missing required scope\n * try {\n * ensureAuthScopes(\n * { scopes: ['https://www.googleapis.com/auth/userinfo.email'] },\n * ['https://www.googleapis.com/auth/cloud-platform']\n * );\n * } catch (error) {\n * // Error: Invalid auth scopes. Scopes must include ...\n * }\n * ```\n *\n * @remarks\n * - Scopes can be provided as a string or array of strings in GoogleAuthOptions\n * - The function normalizes single-string scopes to arrays for validation\n * - Required scopes are not automatically added if existing scopes are present;\n * instead, an error is thrown to prevent unintended scope changes\n * - This function does not modify the original authOptions object\n *\n * @see https://developers.google.com/identity/protocols/oauth2/scopes\n * @see {@link GoogleAuthOptions} for the full authentication configuration interface\n */\nexport function ensureAuthScopes(\n authOptions: GoogleAuthOptions,\n requiredScopes: string[]\n): GoogleAuthOptions {\n if (!authOptions) {\n return { scopes: requiredScopes };\n } else if (!authOptions.scopes) {\n return { ...authOptions, scopes: requiredScopes };\n } else {\n const existingScopes = Array.isArray(authOptions.scopes)\n ? authOptions.scopes\n : [authOptions.scopes];\n const missingScopes = requiredScopes.filter(\n (scope) => !existingScopes.includes(scope)\n );\n if (missingScopes.length > 0) {\n throw new ConfigurationError(\n `Invalid auth scopes. Scopes must include ${requiredScopes.join(\", \")}`\n );\n }\n }\n return authOptions;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAkJA,IAAa,gBAAb,cAAmC,UAAU;CAC3C,YAAqB;AACnB,SAAO,OAAO,KAAK,WAAW,YAAY,KAAK,WAAW;;CAG5D,MAAM,eAAgC;AACpC,MAAI,OAAO,KAAK,gBAAgB,YAC9B,QAAO,KAAK,YAAY;WACf,OAAO,KAAK,eAAe,YACpC,QAAO,KAAK,WAAW,cAAc;MAErC,QAAO,MAAM,cAAc;;;;;;;;;;CAY/B;;;;;;;;;;CAWA;;;;;;;;;;CAWA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAgDA,YAAY,SAAwC,EAAE,EAAE;AACtD,SAAO;AADa,OAAA,SAAA;AAGpB,OAAK,SAAS,OAAO,UAAU,uBAAuB,iBAAiB;AACvE,OAAK,cAAc,WAAW;AAC5B,OAAI,OAAO,YACT,QAAO,wBAAwB,OAAO,YAAY;GAEpD,MAAM,iBAAiB,uBAAuB,2BAA2B;AACzE,OAAI,eACF,QAAO,wBAAwB,eAAe;IAGhD;AACF,OAAK,aAAa,WAAW;AAC3B,OAAI,OAAO,kBACT,QAAO,IAAI,WAAW,OAAO,kBAAkB;AAEjD,OAAI,CAAC,KAAK,UAAU,CAAC,KAAK,YACxB,QAAO,IAAI,YAAY;IAGzB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CA0CJ,MAAM,MAAM,SAAqC;AAC/C,MAAI,KAAK,OACP,SAAQ,QAAQ,IAAI,uBAAuB,KAAK,OAAO;WAC9C,KAAK,YACd,SAAQ,QAAQ,IACd,oBACA,UAAU,6BAA6B,KAAK,YAAY,GACzD;WACQ,KAAK,WAEd,EAAA,MAD0B,KAAK,WAAW,kBAAkB,QAAQ,IAAI,EAC5D,SAAS,OAAO,QAAQ;AAClC,OAAI,UAAU,KACZ,SAAQ,QAAQ,IAAI,KAAK,MAAM;IAEjC;AAEJ,SAAO,MAAM,QAAQ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAwEzB,SAAgB,iBACd,aACA,gBACmB;AACnB,KAAI,CAAC,YACH,QAAO,EAAE,QAAQ,gBAAgB;UACxB,CAAC,YAAY,OACtB,QAAO;EAAE,GAAG;EAAa,QAAQ;EAAgB;MAC5C;EACL,MAAM,iBAAiB,MAAM,QAAQ,YAAY,OAAO,GACpD,YAAY,SACZ,CAAC,YAAY,OAAO;AAIxB,MAHsB,eAAe,QAClC,UAAU,CAAC,eAAe,SAAS,MAAM,CAE3B,CAAC,SAAS,EACzB,OAAM,IAAI,mBACR,4CAA4C,eAAe,KAAK,KAAK,GACtE;;AAGL,QAAO"}
@@ -325,6 +325,18 @@ function convertLegacyContentMessageToGeminiContent(message, messages) {
325
325
  ...etc,
326
326
  functionCall
327
327
  });
328
+ } else if (item?.type === "executableCode") {
329
+ const { type, executableCode, ...etc } = item;
330
+ parts.push({
331
+ ...etc,
332
+ executableCode
333
+ });
334
+ } else if (item?.type === "codeExecutionResult") {
335
+ const { type, codeExecutionResult, ...etc } = item;
336
+ parts.push({
337
+ ...etc,
338
+ codeExecutionResult
339
+ });
328
340
  } else if (isMessageContentImageUrl(item)) parts.push(messageContentImageUrl(item));
329
341
  else if (isMessageContentMedia(item)) parts.push(messageContentMedia(item));
330
342
  else parts.push(item);