@langchain/google-genai 2.0.4 → 2.0.5-dev-1765431816670
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/chat_models.d.cts +5 -13
- package/dist/chat_models.d.cts.map +1 -0
- package/dist/chat_models.d.ts +5 -13
- package/dist/chat_models.d.ts.map +1 -0
- package/dist/embeddings.d.cts +1 -1
- package/dist/embeddings.d.cts.map +1 -0
- package/dist/embeddings.d.ts +1 -1
- package/dist/embeddings.d.ts.map +1 -0
- package/dist/types.d.cts.map +1 -0
- package/dist/types.d.ts.map +1 -0
- package/dist/utils/common.cjs +3 -5
- package/dist/utils/common.cjs.map +1 -1
- package/dist/utils/common.js +3 -5
- package/dist/utils/common.js.map +1 -1
- package/package.json +7 -6
package/dist/chat_models.d.cts
CHANGED
|
@@ -518,10 +518,10 @@ declare class ChatGoogleGenerativeAI extends BaseChatModel<GoogleGenerativeAICha
|
|
|
518
518
|
apiKey: string;
|
|
519
519
|
};
|
|
520
520
|
model: string;
|
|
521
|
-
temperature?: number;
|
|
521
|
+
temperature?: number;
|
|
522
522
|
maxOutputTokens?: number;
|
|
523
|
-
topP?: number;
|
|
524
|
-
topK?: number;
|
|
523
|
+
topP?: number;
|
|
524
|
+
topK?: number;
|
|
525
525
|
stopSequences: string[];
|
|
526
526
|
safetySettings?: SafetySetting[];
|
|
527
527
|
apiKey?: string;
|
|
@@ -562,16 +562,8 @@ declare class ChatGoogleGenerativeAI extends BaseChatModel<GoogleGenerativeAICha
|
|
|
562
562
|
* ```
|
|
563
563
|
*/
|
|
564
564
|
get profile(): ModelProfile;
|
|
565
|
-
withStructuredOutput<
|
|
566
|
-
|
|
567
|
-
RunOutput extends Record<string, any> = Record<string, any>>(outputSchema: InteropZodType<RunOutput>
|
|
568
|
-
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
569
|
-
| Record<string, any>, config?: StructuredOutputMethodOptions<false>): Runnable<BaseLanguageModelInput, RunOutput>;
|
|
570
|
-
withStructuredOutput<
|
|
571
|
-
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
572
|
-
RunOutput extends Record<string, any> = Record<string, any>>(outputSchema: InteropZodType<RunOutput>
|
|
573
|
-
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
574
|
-
| Record<string, any>, config?: StructuredOutputMethodOptions<true>): Runnable<BaseLanguageModelInput, {
|
|
565
|
+
withStructuredOutput<RunOutput extends Record<string, any> = Record<string, any>>(outputSchema: InteropZodType<RunOutput> | Record<string, any>, config?: StructuredOutputMethodOptions<false>): Runnable<BaseLanguageModelInput, RunOutput>;
|
|
566
|
+
withStructuredOutput<RunOutput extends Record<string, any> = Record<string, any>>(outputSchema: InteropZodType<RunOutput> | Record<string, any>, config?: StructuredOutputMethodOptions<true>): Runnable<BaseLanguageModelInput, {
|
|
575
567
|
raw: BaseMessage;
|
|
576
568
|
parsed: RunOutput;
|
|
577
569
|
}>;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"chat_models.d.cts","names":["GenerateContentRequest","SafetySetting","Part","GenerativeAIPart","ModelParams","RequestOptions","CachedContent","Schema","CallbackManagerForLLMRun","AIMessageChunk","BaseMessage","ChatGenerationChunk","ChatResult","BaseChatModel","BaseChatModelCallOptions","LangSmithParams","BaseChatModelParams","ModelProfile","BaseLanguageModelInput","StructuredOutputMethodOptions","Runnable","InteropZodType","GoogleGenerativeAIThinkingConfig","GoogleGenerativeAIToolType","BaseMessageExamplePair","GoogleGenerativeAIChatCallOptions","GoogleGenerativeAIChatInput","Pick","ChatGoogleGenerativeAI","RunOutput","Partial","Omit","Promise","AsyncGenerator","_google_generative_ai0","GenerateContentResult","Record"],"sources":["../src/chat_models.d.ts"],"sourcesContent":["import { GenerateContentRequest, SafetySetting, Part as GenerativeAIPart, ModelParams, RequestOptions, type CachedContent, Schema } from \"@google/generative-ai\";\nimport { CallbackManagerForLLMRun } from \"@langchain/core/callbacks/manager\";\nimport { AIMessageChunk, BaseMessage } from \"@langchain/core/messages\";\nimport { ChatGenerationChunk, ChatResult } from \"@langchain/core/outputs\";\nimport { BaseChatModel, type BaseChatModelCallOptions, type LangSmithParams, type BaseChatModelParams } from \"@langchain/core/language_models/chat_models\";\nimport { ModelProfile } from \"@langchain/core/language_models/profile\";\nimport { BaseLanguageModelInput, StructuredOutputMethodOptions } from \"@langchain/core/language_models/base\";\nimport { Runnable } from \"@langchain/core/runnables\";\nimport { InteropZodType } from \"@langchain/core/utils/types\";\nimport { GoogleGenerativeAIThinkingConfig, GoogleGenerativeAIToolType } from \"./types.js\";\nexport type BaseMessageExamplePair = {\n input: BaseMessage;\n output: BaseMessage;\n};\nexport interface GoogleGenerativeAIChatCallOptions extends BaseChatModelCallOptions {\n tools?: GoogleGenerativeAIToolType[];\n /**\n * Allowed functions to call when the mode is \"any\".\n * If empty, any one of the provided functions are called.\n */\n allowedFunctionNames?: string[];\n /**\n * Whether or not to include usage data, like token counts\n * in the streamed response chunks.\n * @default true\n */\n streamUsage?: boolean;\n /**\n * JSON schema to be returned by the model.\n */\n responseSchema?: Schema;\n}\n/**\n * An interface defining the input to the ChatGoogleGenerativeAI class.\n */\nexport interface GoogleGenerativeAIChatInput extends BaseChatModelParams, Pick<GoogleGenerativeAIChatCallOptions, \"streamUsage\"> {\n /**\n * Model Name to use\n *\n * Note: The format must follow the pattern - `{model}`\n */\n model: string;\n /**\n * Controls the randomness of the output.\n *\n * Values can range from [0.0,2.0], inclusive. A value closer to 2.0\n * will produce responses that are more varied and creative, while\n * a value closer to 0.0 will typically result in less surprising\n * responses from the model.\n *\n * Note: The default value varies by model\n */\n temperature?: number;\n /**\n * Maximum number of tokens to generate in the completion.\n */\n maxOutputTokens?: number;\n /**\n * Top-p changes how the model selects tokens for output.\n *\n * Tokens are selected from most probable to least until the sum\n * of their probabilities equals the top-p value.\n *\n * For example, if tokens A, B, and C have a probability of\n * .3, .2, and .1 and the top-p value is .5, then the model will\n * select either A or B as the next token (using temperature).\n *\n * Note: The default value varies by model\n */\n topP?: number;\n /**\n * Top-k changes how the model selects tokens for output.\n *\n * A top-k of 1 means the selected token is the most probable among\n * all tokens in the model's vocabulary (also called greedy decoding),\n * while a top-k of 3 means that the next token is selected from\n * among the 3 most probable tokens (using temperature).\n *\n * Note: The default value varies by model\n */\n topK?: number;\n /**\n * The set of character sequences (up to 5) that will stop output generation.\n * If specified, the API will stop at the first appearance of a stop\n * sequence.\n *\n * Note: The stop sequence will not be included as part of the response.\n * Note: stopSequences is only supported for Gemini models\n */\n stopSequences?: string[];\n /**\n * A list of unique `SafetySetting` instances for blocking unsafe content. The API will block\n * any prompts and responses that fail to meet the thresholds set by these settings. If there\n * is no `SafetySetting` for a given `SafetyCategory` provided in the list, the API will use\n * the default safety setting for that category.\n */\n safetySettings?: SafetySetting[];\n /**\n * Google API key to use\n */\n apiKey?: string;\n /**\n * Google API version to use\n */\n apiVersion?: string;\n /**\n * Google API base URL to use\n */\n baseUrl?: string;\n /** Whether to stream the results or not */\n streaming?: boolean;\n /**\n * Whether or not to force the model to respond with JSON.\n * Available for `gemini-1.5` models and later.\n * @default false\n */\n json?: boolean;\n /**\n * Whether or not model supports system instructions.\n * The following models support system instructions:\n * - All Gemini 1.5 Pro model versions\n * - All Gemini 1.5 Flash model versions\n * - Gemini 1.0 Pro version gemini-1.0-pro-002\n */\n convertSystemMessageToHumanContent?: boolean | undefined;\n /**\n * Optional. Config for thinking features. An error will be returned if this\n * field is set for models that don't support thinking.\n */\n thinkingConfig?: GoogleGenerativeAIThinkingConfig;\n}\n/**\n * Google Generative AI chat model integration.\n *\n * Setup:\n * Install `@langchain/google-genai` and set an environment variable named `GOOGLE_API_KEY`.\n *\n * ```bash\n * npm install @langchain/google-genai\n * export GOOGLE_API_KEY=\"your-api-key\"\n * ```\n *\n * ## [Constructor args](https://api.js.langchain.com/classes/langchain_google_genai.ChatGoogleGenerativeAI.html#constructor)\n *\n * ## [Runtime args](https://api.js.langchain.com/interfaces/langchain_google_genai.GoogleGenerativeAIChatCallOptions.html)\n *\n * Runtime args can be passed as the second argument to any of the base runnable methods `.invoke`. `.stream`, `.batch`, etc.\n * They can also be passed via `.withConfig`, or the second arg in `.bindTools`, like shown in the examples below:\n *\n * ```typescript\n * // When calling `.withConfig`, call options should be passed via the first argument\n * const llmWithArgsBound = llm.withConfig({\n * stop: [\"\\n\"],\n * });\n *\n * // When calling `.bindTools`, call options should be passed via the second argument\n * const llmWithTools = llm.bindTools(\n * [...],\n * {\n * stop: [\"\\n\"],\n * }\n * );\n * ```\n *\n * ## Examples\n *\n * <details open>\n * <summary><strong>Instantiate</strong></summary>\n *\n * ```typescript\n * import { ChatGoogleGenerativeAI } from '@langchain/google-genai';\n *\n * const llm = new ChatGoogleGenerativeAI({\n * model: \"gemini-1.5-flash\",\n * temperature: 0,\n * maxRetries: 2,\n * // apiKey: \"...\",\n * // other params...\n * });\n * ```\n * </details>\n *\n * <br />\n *\n * <details>\n * <summary><strong>Invoking</strong></summary>\n *\n * ```typescript\n * const input = `Translate \"I love programming\" into French.`;\n *\n * // Models also accept a list of chat messages or a formatted prompt\n * const result = await llm.invoke(input);\n * console.log(result);\n * ```\n *\n * ```txt\n * AIMessage {\n * \"content\": \"There are a few ways to translate \\\"I love programming\\\" into French, depending on the level of formality and nuance you want to convey:\\n\\n**Formal:**\\n\\n* **J'aime la programmation.** (This is the most literal and formal translation.)\\n\\n**Informal:**\\n\\n* **J'adore programmer.** (This is a more enthusiastic and informal translation.)\\n* **J'aime beaucoup programmer.** (This is a slightly less enthusiastic but still informal translation.)\\n\\n**More specific:**\\n\\n* **J'aime beaucoup coder.** (This specifically refers to writing code.)\\n* **J'aime beaucoup développer des logiciels.** (This specifically refers to developing software.)\\n\\nThe best translation will depend on the context and your intended audience. \\n\",\n * \"response_metadata\": {\n * \"finishReason\": \"STOP\",\n * \"index\": 0,\n * \"safetyRatings\": [\n * {\n * \"category\": \"HARM_CATEGORY_SEXUALLY_EXPLICIT\",\n * \"probability\": \"NEGLIGIBLE\"\n * },\n * {\n * \"category\": \"HARM_CATEGORY_HATE_SPEECH\",\n * \"probability\": \"NEGLIGIBLE\"\n * },\n * {\n * \"category\": \"HARM_CATEGORY_HARASSMENT\",\n * \"probability\": \"NEGLIGIBLE\"\n * },\n * {\n * \"category\": \"HARM_CATEGORY_DANGEROUS_CONTENT\",\n * \"probability\": \"NEGLIGIBLE\"\n * }\n * ]\n * },\n * \"usage_metadata\": {\n * \"input_tokens\": 10,\n * \"output_tokens\": 149,\n * \"total_tokens\": 159\n * }\n * }\n * ```\n * </details>\n *\n * <br />\n *\n * <details>\n * <summary><strong>Streaming Chunks</strong></summary>\n *\n * ```typescript\n * for await (const chunk of await llm.stream(input)) {\n * console.log(chunk);\n * }\n * ```\n *\n * ```txt\n * AIMessageChunk {\n * \"content\": \"There\",\n * \"response_metadata\": {\n * \"index\": 0\n * }\n * \"usage_metadata\": {\n * \"input_tokens\": 10,\n * \"output_tokens\": 1,\n * \"total_tokens\": 11\n * }\n * }\n * AIMessageChunk {\n * \"content\": \" are a few ways to translate \\\"I love programming\\\" into French, depending on\",\n * }\n * AIMessageChunk {\n * \"content\": \" the level of formality and nuance you want to convey:\\n\\n**Formal:**\\n\\n\",\n * }\n * AIMessageChunk {\n * \"content\": \"* **J'aime la programmation.** (This is the most literal and formal translation.)\\n\\n**Informal:**\\n\\n* **J'adore programmer.** (This\",\n * }\n * AIMessageChunk {\n * \"content\": \" is a more enthusiastic and informal translation.)\\n* **J'aime beaucoup programmer.** (This is a slightly less enthusiastic but still informal translation.)\\n\\n**More\",\n * }\n * AIMessageChunk {\n * \"content\": \" specific:**\\n\\n* **J'aime beaucoup coder.** (This specifically refers to writing code.)\\n* **J'aime beaucoup développer des logiciels.** (This specifically refers to developing software.)\\n\\nThe best translation will depend on the context and\",\n * }\n * AIMessageChunk {\n * \"content\": \" your intended audience. \\n\",\n * }\n * ```\n * </details>\n *\n * <br />\n *\n * <details>\n * <summary><strong>Aggregate Streamed Chunks</strong></summary>\n *\n * ```typescript\n * import { AIMessageChunk } from '@langchain/core/messages';\n * import { concat } from '@langchain/core/utils/stream';\n *\n * const stream = await llm.stream(input);\n * let full: AIMessageChunk | undefined;\n * for await (const chunk of stream) {\n * full = !full ? chunk : concat(full, chunk);\n * }\n * console.log(full);\n * ```\n *\n * ```txt\n * AIMessageChunk {\n * \"content\": \"There are a few ways to translate \\\"I love programming\\\" into French, depending on the level of formality and nuance you want to convey:\\n\\n**Formal:**\\n\\n* **J'aime la programmation.** (This is the most literal and formal translation.)\\n\\n**Informal:**\\n\\n* **J'adore programmer.** (This is a more enthusiastic and informal translation.)\\n* **J'aime beaucoup programmer.** (This is a slightly less enthusiastic but still informal translation.)\\n\\n**More specific:**\\n\\n* **J'aime beaucoup coder.** (This specifically refers to writing code.)\\n* **J'aime beaucoup développer des logiciels.** (This specifically refers to developing software.)\\n\\nThe best translation will depend on the context and your intended audience. \\n\",\n * \"usage_metadata\": {\n * \"input_tokens\": 10,\n * \"output_tokens\": 277,\n * \"total_tokens\": 287\n * }\n * }\n * ```\n * </details>\n *\n * <br />\n *\n * <details>\n * <summary><strong>Bind tools</strong></summary>\n *\n * ```typescript\n * import { z } from 'zod';\n *\n * const GetWeather = {\n * name: \"GetWeather\",\n * description: \"Get the current weather in a given location\",\n * schema: z.object({\n * location: z.string().describe(\"The city and state, e.g. San Francisco, CA\")\n * }),\n * }\n *\n * const GetPopulation = {\n * name: \"GetPopulation\",\n * description: \"Get the current population in a given location\",\n * schema: z.object({\n * location: z.string().describe(\"The city and state, e.g. San Francisco, CA\")\n * }),\n * }\n *\n * const llmWithTools = llm.bindTools([GetWeather, GetPopulation]);\n * const aiMsg = await llmWithTools.invoke(\n * \"Which city is hotter today and which is bigger: LA or NY?\"\n * );\n * console.log(aiMsg.tool_calls);\n * ```\n *\n * ```txt\n * [\n * {\n * name: 'GetWeather',\n * args: { location: 'Los Angeles, CA' },\n * type: 'tool_call'\n * },\n * {\n * name: 'GetWeather',\n * args: { location: 'New York, NY' },\n * type: 'tool_call'\n * },\n * {\n * name: 'GetPopulation',\n * args: { location: 'Los Angeles, CA' },\n * type: 'tool_call'\n * },\n * {\n * name: 'GetPopulation',\n * args: { location: 'New York, NY' },\n * type: 'tool_call'\n * }\n * ]\n * ```\n * </details>\n *\n * <br />\n *\n * <details>\n * <summary><strong>Structured Output</strong></summary>\n *\n * ```typescript\n * const Joke = z.object({\n * setup: z.string().describe(\"The setup of the joke\"),\n * punchline: z.string().describe(\"The punchline to the joke\"),\n * rating: z.number().optional().describe(\"How funny the joke is, from 1 to 10\")\n * }).describe('Joke to tell user.');\n *\n * const structuredLlm = llm.withStructuredOutput(Joke, { name: \"Joke\" });\n * const jokeResult = await structuredLlm.invoke(\"Tell me a joke about cats\");\n * console.log(jokeResult);\n * ```\n *\n * ```txt\n * {\n * setup: \"Why don\\\\'t cats play poker?\",\n * punchline: \"Why don\\\\'t cats play poker? Because they always have an ace up their sleeve!\"\n * }\n * ```\n * </details>\n *\n * <br />\n *\n * <details>\n * <summary><strong>Multimodal</strong></summary>\n *\n * ```typescript\n * import { HumanMessage } from '@langchain/core/messages';\n *\n * const imageUrl = \"https://example.com/image.jpg\";\n * const imageData = await fetch(imageUrl).then(res => res.arrayBuffer());\n * const base64Image = Buffer.from(imageData).toString('base64');\n *\n * const message = new HumanMessage({\n * content: [\n * { type: \"text\", text: \"describe the weather in this image\" },\n * {\n * type: \"image_url\",\n * image_url: { url: `data:image/jpeg;base64,${base64Image}` },\n * },\n * ]\n * });\n *\n * const imageDescriptionAiMsg = await llm.invoke([message]);\n * console.log(imageDescriptionAiMsg.content);\n * ```\n *\n * ```txt\n * The weather in the image appears to be clear and sunny. The sky is mostly blue with a few scattered white clouds, indicating fair weather. The bright sunlight is casting shadows on the green, grassy hill, suggesting it is a pleasant day with good visibility. There are no signs of rain or stormy conditions.\n * ```\n * </details>\n *\n * <br />\n *\n * <details>\n * <summary><strong>Usage Metadata</strong></summary>\n *\n * ```typescript\n * const aiMsgForMetadata = await llm.invoke(input);\n * console.log(aiMsgForMetadata.usage_metadata);\n * ```\n *\n * ```txt\n * { input_tokens: 10, output_tokens: 149, total_tokens: 159 }\n * ```\n * </details>\n *\n * <br />\n *\n * <details>\n * <summary><strong>Response Metadata</strong></summary>\n *\n * ```typescript\n * const aiMsgForResponseMetadata = await llm.invoke(input);\n * console.log(aiMsgForResponseMetadata.response_metadata);\n * ```\n *\n * ```txt\n * {\n * finishReason: 'STOP',\n * index: 0,\n * safetyRatings: [\n * {\n * category: 'HARM_CATEGORY_SEXUALLY_EXPLICIT',\n * probability: 'NEGLIGIBLE'\n * },\n * {\n * category: 'HARM_CATEGORY_HATE_SPEECH',\n * probability: 'NEGLIGIBLE'\n * },\n * { category: 'HARM_CATEGORY_HARASSMENT', probability: 'NEGLIGIBLE' },\n * {\n * category: 'HARM_CATEGORY_DANGEROUS_CONTENT',\n * probability: 'NEGLIGIBLE'\n * }\n * ]\n * }\n * ```\n * </details>\n *\n * <br />\n *\n * <details>\n * <summary><strong>Document Messages</strong></summary>\n *\n * This example will show you how to pass documents such as PDFs to Google\n * Generative AI through messages.\n *\n * ```typescript\n * const pdfPath = \"/Users/my_user/Downloads/invoice.pdf\";\n * const pdfBase64 = await fs.readFile(pdfPath, \"base64\");\n *\n * const response = await llm.invoke([\n * [\"system\", \"Use the provided documents to answer the question\"],\n * [\n * \"user\",\n * [\n * {\n * type: \"application/pdf\", // If the `type` field includes a single slash (`/`), it will be treated as inline data.\n * data: pdfBase64,\n * },\n * {\n * type: \"text\",\n * text: \"Summarize the contents of this PDF\",\n * },\n * ],\n * ],\n * ]);\n *\n * console.log(response.content);\n * ```\n *\n * ```txt\n * This is a billing invoice from Twitter Developers for X API Basic Access. The transaction date is January 7, 2025,\n * and the amount is $194.34, which has been paid. The subscription period is from January 7, 2025 21:02 to February 7, 2025 00:00 (UTC).\n * The tax is $0.00, with a tax rate of 0%. The total amount is $194.34. The payment was made using a Visa card ending in 7022,\n * expiring in 12/2026. The billing address is Brace Sproul, 1234 Main Street, San Francisco, CA, US 94103. The company being billed is\n * X Corp, located at 865 FM 1209 Building 2, Bastrop, TX, US 78602. Terms and conditions apply.\n * ```\n * </details>\n *\n * <br />\n */\nexport declare class ChatGoogleGenerativeAI extends BaseChatModel<GoogleGenerativeAIChatCallOptions, AIMessageChunk> implements GoogleGenerativeAIChatInput {\n static lc_name(): string;\n lc_serializable: boolean;\n get lc_secrets(): {\n [key: string]: string;\n } | undefined;\n lc_namespace: string[];\n get lc_aliases(): {\n apiKey: string;\n };\n model: string;\n temperature?: number;\n maxOutputTokens?: number;\n topP?: number;\n topK?: number;\n stopSequences: string[];\n safetySettings?: SafetySetting[];\n apiKey?: string;\n streaming: boolean;\n json?: boolean;\n streamUsage: boolean;\n convertSystemMessageToHumanContent: boolean | undefined;\n thinkingConfig?: GoogleGenerativeAIThinkingConfig;\n private client;\n get _isMultimodalModel(): boolean;\n constructor(fields: GoogleGenerativeAIChatInput);\n useCachedContent(cachedContent: CachedContent, modelParams?: ModelParams, requestOptions?: RequestOptions): void;\n get useSystemInstruction(): boolean;\n get computeUseSystemInstruction(): boolean;\n getLsParams(options: this[\"ParsedCallOptions\"]): LangSmithParams;\n _combineLLMOutput(): never[];\n _llmType(): string;\n bindTools(tools: GoogleGenerativeAIToolType[], kwargs?: Partial<GoogleGenerativeAIChatCallOptions>): Runnable<BaseLanguageModelInput, AIMessageChunk, GoogleGenerativeAIChatCallOptions>;\n invocationParams(options?: this[\"ParsedCallOptions\"]): Omit<GenerateContentRequest, \"contents\">;\n _generate(messages: BaseMessage[], options: this[\"ParsedCallOptions\"], runManager?: CallbackManagerForLLMRun): Promise<ChatResult>;\n _streamResponseChunks(messages: BaseMessage[], options: this[\"ParsedCallOptions\"], runManager?: CallbackManagerForLLMRun): AsyncGenerator<ChatGenerationChunk>;\n completionWithRetry(request: string | GenerateContentRequest | (string | GenerativeAIPart)[], options?: this[\"ParsedCallOptions\"]): Promise<import(\"@google/generative-ai\").GenerateContentResult>;\n /**\n * Return profiling information for the model.\n *\n * Provides information about the model's capabilities and constraints,\n * including token limits, multimodal support, and advanced features like\n * tool calling and structured output.\n *\n * @returns {ModelProfile} An object describing the model's capabilities and constraints\n *\n * @example\n * ```typescript\n * const model = new ChatGoogleGenerativeAI({ model: \"gemini-1.5-flash\" });\n * const profile = model.profile;\n * console.log(profile.maxInputTokens); // 2000000\n * console.log(profile.imageInputs); // true\n * ```\n */\n get profile(): ModelProfile;\n withStructuredOutput<RunOutput extends Record<string, any> = Record<string, any>>(outputSchema: InteropZodType<RunOutput> | Record<string, any>, config?: StructuredOutputMethodOptions<false>): Runnable<BaseLanguageModelInput, RunOutput>;\n withStructuredOutput<RunOutput extends Record<string, any> = Record<string, any>>(outputSchema: InteropZodType<RunOutput> | Record<string, any>, config?: StructuredOutputMethodOptions<true>): Runnable<BaseLanguageModelInput, {\n raw: BaseMessage;\n parsed: RunOutput;\n }>;\n}\n//# sourceMappingURL=chat_models.d.ts.map"],"mappings":";;;;;;;;;;;;;KAUYwB,sBAAAA;SACDd;UACCA;AAFZ,CAAA;AAIiBe,UAAAA,iCAAAA,SAA0CX,wBAAT,CAAA;EACtCS,KAAAA,CAAAA,EAAAA,0BAAAA,EAAAA;EAeShB;;AAhB8D;AAqBnF;EAA+EkB,oBAAAA,CAAAA,EAAAA,MAAAA,EAAAA;EA6D1DxB;;;;AA7DyD;EAudzD2B,WAAAA,CAAAA,EAAAA,OAAAA;EAA6CH;;;EAsB7CH,cAAAA,CAAAA,EAlfAf,MAkfAe;;;;;AAOgCP,UApfpCW,2BAAAA,SAAoCV,mBAofAD,EApfqBY,IAofrBZ,CApf0BU,iCAof1BV,EAAAA,aAAAA,CAAAA,CAAAA;EAGhCQ;;;;;EAAqIE,KAAAA,EAAAA,MAAAA;EAAjDL;;;;;;;;;;EAGsBa,WAAAA,CAAAA,EAAAA,MAAAA;EACrFjC;;;EAA8FgC,eAAAA,CAAAA,EAAAA,MAAAA;EAkBrHf;;;;;;;;;;;;EAEgGY,IAAAA,CAAAA,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GenerativeAICha
|
|
|
518
518
|
apiKey: string;
|
|
519
519
|
};
|
|
520
520
|
model: string;
|
|
521
|
-
temperature?: number;
|
|
521
|
+
temperature?: number;
|
|
522
522
|
maxOutputTokens?: number;
|
|
523
|
-
topP?: number;
|
|
524
|
-
topK?: number;
|
|
523
|
+
topP?: number;
|
|
524
|
+
topK?: number;
|
|
525
525
|
stopSequences: string[];
|
|
526
526
|
safetySettings?: SafetySetting[];
|
|
527
527
|
apiKey?: string;
|
|
@@ -562,16 +562,8 @@ declare class ChatGoogleGenerativeAI extends BaseChatModel<GoogleGenerativeAICha
|
|
|
562
562
|
* ```
|
|
563
563
|
*/
|
|
564
564
|
get profile(): ModelProfile;
|
|
565
|
-
withStructuredOutput<
|
|
566
|
-
|
|
567
|
-
RunOutput extends Record<string, any> = Record<string, any>>(outputSchema: InteropZodType<RunOutput>
|
|
568
|
-
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
569
|
-
| Record<string, any>, config?: StructuredOutputMethodOptions<false>): Runnable<BaseLanguageModelInput, RunOutput>;
|
|
570
|
-
withStructuredOutput<
|
|
571
|
-
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
572
|
-
RunOutput extends Record<string, any> = Record<string, any>>(outputSchema: InteropZodType<RunOutput>
|
|
573
|
-
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
574
|
-
| Record<string, any>, config?: StructuredOutputMethodOptions<true>): Runnable<BaseLanguageModelInput, {
|
|
565
|
+
withStructuredOutput<RunOutput extends Record<string, any> = Record<string, any>>(outputSchema: InteropZodType<RunOutput> | Record<string, any>, config?: StructuredOutputMethodOptions<false>): Runnable<BaseLanguageModelInput, RunOutput>;
|
|
566
|
+
withStructuredOutput<RunOutput extends Record<string, any> = Record<string, any>>(outputSchema: InteropZodType<RunOutput> | Record<string, any>, config?: StructuredOutputMethodOptions<true>): Runnable<BaseLanguageModelInput, {
|
|
575
567
|
raw: BaseMessage;
|
|
576
568
|
parsed: RunOutput;
|
|
577
569
|
}>;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"chat_models.d.ts","names":["GenerateContentRequest","SafetySetting","Part","GenerativeAIPart","ModelParams","RequestOptions","CachedContent","Schema","CallbackManagerForLLMRun","AIMessageChunk","BaseMessage","ChatGenerationChunk","ChatResult","BaseChatModel","BaseChatModelCallOptions","LangSmithParams","BaseChatModelParams","ModelProfile","BaseLanguageModelInput","StructuredOutputMethodOptions","Runnable","InteropZodType","GoogleGenerativeAIThinkingConfig","GoogleGenerativeAIToolType","BaseMessageExamplePair","GoogleGenerativeAIChatCallOptions","GoogleGenerativeAIChatInput","Pick","ChatGoogleGenerativeAI","RunOutput","Partial","Omit","Promise","AsyncGenerator","_google_generative_ai0","GenerateContentResult","Record"],"sources":["../src/chat_models.d.ts"],"sourcesContent":["import { GenerateContentRequest, SafetySetting, Part as GenerativeAIPart, ModelParams, RequestOptions, type CachedContent, Schema } from \"@google/generative-ai\";\nimport { CallbackManagerForLLMRun } from \"@langchain/core/callbacks/manager\";\nimport { AIMessageChunk, BaseMessage } from \"@langchain/core/messages\";\nimport { ChatGenerationChunk, ChatResult } from \"@langchain/core/outputs\";\nimport { BaseChatModel, type BaseChatModelCallOptions, type LangSmithParams, type BaseChatModelParams } from \"@langchain/core/language_models/chat_models\";\nimport { ModelProfile } from \"@langchain/core/language_models/profile\";\nimport { BaseLanguageModelInput, StructuredOutputMethodOptions } from \"@langchain/core/language_models/base\";\nimport { Runnable } from \"@langchain/core/runnables\";\nimport { InteropZodType } from \"@langchain/core/utils/types\";\nimport { GoogleGenerativeAIThinkingConfig, GoogleGenerativeAIToolType } from \"./types.js\";\nexport type BaseMessageExamplePair = {\n input: BaseMessage;\n output: BaseMessage;\n};\nexport interface GoogleGenerativeAIChatCallOptions extends BaseChatModelCallOptions {\n tools?: GoogleGenerativeAIToolType[];\n /**\n * Allowed functions to call when the mode is \"any\".\n * If empty, any one of the provided functions are called.\n */\n allowedFunctionNames?: string[];\n /**\n * Whether or not to include usage data, like token counts\n * in the streamed response chunks.\n * @default true\n */\n streamUsage?: boolean;\n /**\n * JSON schema to be returned by the model.\n */\n responseSchema?: Schema;\n}\n/**\n * An interface defining the input to the ChatGoogleGenerativeAI class.\n */\nexport interface GoogleGenerativeAIChatInput extends BaseChatModelParams, Pick<GoogleGenerativeAIChatCallOptions, \"streamUsage\"> {\n /**\n * Model Name to use\n *\n * Note: The format must follow the pattern - `{model}`\n */\n model: string;\n /**\n * Controls the randomness of the output.\n *\n * Values can range from [0.0,2.0], inclusive. A value closer to 2.0\n * will produce responses that are more varied and creative, while\n * a value closer to 0.0 will typically result in less surprising\n * responses from the model.\n *\n * Note: The default value varies by model\n */\n temperature?: number;\n /**\n * Maximum number of tokens to generate in the completion.\n */\n maxOutputTokens?: number;\n /**\n * Top-p changes how the model selects tokens for output.\n *\n * Tokens are selected from most probable to least until the sum\n * of their probabilities equals the top-p value.\n *\n * For example, if tokens A, B, and C have a probability of\n * .3, .2, and .1 and the top-p value is .5, then the model will\n * select either A or B as the next token (using temperature).\n *\n * Note: The default value varies by model\n */\n topP?: number;\n /**\n * Top-k changes how the model selects tokens for output.\n *\n * A top-k of 1 means the selected token is the most probable among\n * all tokens in the model's vocabulary (also called greedy decoding),\n * while a top-k of 3 means that the next token is selected from\n * among the 3 most probable tokens (using temperature).\n *\n * Note: The default value varies by model\n */\n topK?: number;\n /**\n * The set of character sequences (up to 5) that will stop output generation.\n * If specified, the API will stop at the first appearance of a stop\n * sequence.\n *\n * Note: The stop sequence will not be included as part of the response.\n * Note: stopSequences is only supported for Gemini models\n */\n stopSequences?: string[];\n /**\n * A list of unique `SafetySetting` instances for blocking unsafe content. The API will block\n * any prompts and responses that fail to meet the thresholds set by these settings. If there\n * is no `SafetySetting` for a given `SafetyCategory` provided in the list, the API will use\n * the default safety setting for that category.\n */\n safetySettings?: SafetySetting[];\n /**\n * Google API key to use\n */\n apiKey?: string;\n /**\n * Google API version to use\n */\n apiVersion?: string;\n /**\n * Google API base URL to use\n */\n baseUrl?: string;\n /** Whether to stream the results or not */\n streaming?: boolean;\n /**\n * Whether or not to force the model to respond with JSON.\n * Available for `gemini-1.5` models and later.\n * @default false\n */\n json?: boolean;\n /**\n * Whether or not model supports system instructions.\n * The following models support system instructions:\n * - All Gemini 1.5 Pro model versions\n * - All Gemini 1.5 Flash model versions\n * - Gemini 1.0 Pro version gemini-1.0-pro-002\n */\n convertSystemMessageToHumanContent?: boolean | undefined;\n /**\n * Optional. Config for thinking features. An error will be returned if this\n * field is set for models that don't support thinking.\n */\n thinkingConfig?: GoogleGenerativeAIThinkingConfig;\n}\n/**\n * Google Generative AI chat model integration.\n *\n * Setup:\n * Install `@langchain/google-genai` and set an environment variable named `GOOGLE_API_KEY`.\n *\n * ```bash\n * npm install @langchain/google-genai\n * export GOOGLE_API_KEY=\"your-api-key\"\n * ```\n *\n * ## [Constructor args](https://api.js.langchain.com/classes/langchain_google_genai.ChatGoogleGenerativeAI.html#constructor)\n *\n * ## [Runtime args](https://api.js.langchain.com/interfaces/langchain_google_genai.GoogleGenerativeAIChatCallOptions.html)\n *\n * Runtime args can be passed as the second argument to any of the base runnable methods `.invoke`. `.stream`, `.batch`, etc.\n * They can also be passed via `.withConfig`, or the second arg in `.bindTools`, like shown in the examples below:\n *\n * ```typescript\n * // When calling `.withConfig`, call options should be passed via the first argument\n * const llmWithArgsBound = llm.withConfig({\n * stop: [\"\\n\"],\n * });\n *\n * // When calling `.bindTools`, call options should be passed via the second argument\n * const llmWithTools = llm.bindTools(\n * [...],\n * {\n * stop: [\"\\n\"],\n * }\n * );\n * ```\n *\n * ## Examples\n *\n * <details open>\n * <summary><strong>Instantiate</strong></summary>\n *\n * ```typescript\n * import { ChatGoogleGenerativeAI } from '@langchain/google-genai';\n *\n * const llm = new ChatGoogleGenerativeAI({\n * model: \"gemini-1.5-flash\",\n * temperature: 0,\n * maxRetries: 2,\n * // apiKey: \"...\",\n * // other params...\n * });\n * ```\n * </details>\n *\n * <br />\n *\n * <details>\n * <summary><strong>Invoking</strong></summary>\n *\n * ```typescript\n * const input = `Translate \"I love programming\" into French.`;\n *\n * // Models also accept a list of chat messages or a formatted prompt\n * const result = await llm.invoke(input);\n * console.log(result);\n * ```\n *\n * ```txt\n * AIMessage {\n * \"content\": \"There are a few ways to translate \\\"I love programming\\\" into French, depending on the level of formality and nuance you want to convey:\\n\\n**Formal:**\\n\\n* **J'aime la programmation.** (This is the most literal and formal translation.)\\n\\n**Informal:**\\n\\n* **J'adore programmer.** (This is a more enthusiastic and informal translation.)\\n* **J'aime beaucoup programmer.** (This is a slightly less enthusiastic but still informal translation.)\\n\\n**More specific:**\\n\\n* **J'aime beaucoup coder.** (This specifically refers to writing code.)\\n* **J'aime beaucoup développer des logiciels.** (This specifically refers to developing software.)\\n\\nThe best translation will depend on the context and your intended audience. \\n\",\n * \"response_metadata\": {\n * \"finishReason\": \"STOP\",\n * \"index\": 0,\n * \"safetyRatings\": [\n * {\n * \"category\": \"HARM_CATEGORY_SEXUALLY_EXPLICIT\",\n * \"probability\": \"NEGLIGIBLE\"\n * },\n * {\n * \"category\": \"HARM_CATEGORY_HATE_SPEECH\",\n * \"probability\": \"NEGLIGIBLE\"\n * },\n * {\n * \"category\": \"HARM_CATEGORY_HARASSMENT\",\n * \"probability\": \"NEGLIGIBLE\"\n * },\n * {\n * \"category\": \"HARM_CATEGORY_DANGEROUS_CONTENT\",\n * \"probability\": \"NEGLIGIBLE\"\n * }\n * ]\n * },\n * \"usage_metadata\": {\n * \"input_tokens\": 10,\n * \"output_tokens\": 149,\n * \"total_tokens\": 159\n * }\n * }\n * ```\n * </details>\n *\n * <br />\n *\n * <details>\n * <summary><strong>Streaming Chunks</strong></summary>\n *\n * ```typescript\n * for await (const chunk of await llm.stream(input)) {\n * console.log(chunk);\n * }\n * ```\n *\n * ```txt\n * AIMessageChunk {\n * \"content\": \"There\",\n * \"response_metadata\": {\n * \"index\": 0\n * }\n * \"usage_metadata\": {\n * \"input_tokens\": 10,\n * \"output_tokens\": 1,\n * \"total_tokens\": 11\n * }\n * }\n * AIMessageChunk {\n * \"content\": \" are a few ways to translate \\\"I love programming\\\" into French, depending on\",\n * }\n * AIMessageChunk {\n * \"content\": \" the level of formality and nuance you want to convey:\\n\\n**Formal:**\\n\\n\",\n * }\n * AIMessageChunk {\n * \"content\": \"* **J'aime la programmation.** (This is the most literal and formal translation.)\\n\\n**Informal:**\\n\\n* **J'adore programmer.** (This\",\n * }\n * AIMessageChunk {\n * \"content\": \" is a more enthusiastic and informal translation.)\\n* **J'aime beaucoup programmer.** (This is a slightly less enthusiastic but still informal translation.)\\n\\n**More\",\n * }\n * AIMessageChunk {\n * \"content\": \" specific:**\\n\\n* **J'aime beaucoup coder.** (This specifically refers to writing code.)\\n* **J'aime beaucoup développer des logiciels.** (This specifically refers to developing software.)\\n\\nThe best translation will depend on the context and\",\n * }\n * AIMessageChunk {\n * \"content\": \" your intended audience. \\n\",\n * }\n * ```\n * </details>\n *\n * <br />\n *\n * <details>\n * <summary><strong>Aggregate Streamed Chunks</strong></summary>\n *\n * ```typescript\n * import { AIMessageChunk } from '@langchain/core/messages';\n * import { concat } from '@langchain/core/utils/stream';\n *\n * const stream = await llm.stream(input);\n * let full: AIMessageChunk | undefined;\n * for await (const chunk of stream) {\n * full = !full ? chunk : concat(full, chunk);\n * }\n * console.log(full);\n * ```\n *\n * ```txt\n * AIMessageChunk {\n * \"content\": \"There are a few ways to translate \\\"I love programming\\\" into French, depending on the level of formality and nuance you want to convey:\\n\\n**Formal:**\\n\\n* **J'aime la programmation.** (This is the most literal and formal translation.)\\n\\n**Informal:**\\n\\n* **J'adore programmer.** (This is a more enthusiastic and informal translation.)\\n* **J'aime beaucoup programmer.** (This is a slightly less enthusiastic but still informal translation.)\\n\\n**More specific:**\\n\\n* **J'aime beaucoup coder.** (This specifically refers to writing code.)\\n* **J'aime beaucoup développer des logiciels.** (This specifically refers to developing software.)\\n\\nThe best translation will depend on the context and your intended audience. \\n\",\n * \"usage_metadata\": {\n * \"input_tokens\": 10,\n * \"output_tokens\": 277,\n * \"total_tokens\": 287\n * }\n * }\n * ```\n * </details>\n *\n * <br />\n *\n * <details>\n * <summary><strong>Bind tools</strong></summary>\n *\n * ```typescript\n * import { z } from 'zod';\n *\n * const GetWeather = {\n * name: \"GetWeather\",\n * description: \"Get the current weather in a given location\",\n * schema: z.object({\n * location: z.string().describe(\"The city and state, e.g. San Francisco, CA\")\n * }),\n * }\n *\n * const GetPopulation = {\n * name: \"GetPopulation\",\n * description: \"Get the current population in a given location\",\n * schema: z.object({\n * location: z.string().describe(\"The city and state, e.g. San Francisco, CA\")\n * }),\n * }\n *\n * const llmWithTools = llm.bindTools([GetWeather, GetPopulation]);\n * const aiMsg = await llmWithTools.invoke(\n * \"Which city is hotter today and which is bigger: LA or NY?\"\n * );\n * console.log(aiMsg.tool_calls);\n * ```\n *\n * ```txt\n * [\n * {\n * name: 'GetWeather',\n * args: { location: 'Los Angeles, CA' },\n * type: 'tool_call'\n * },\n * {\n * name: 'GetWeather',\n * args: { location: 'New York, NY' },\n * type: 'tool_call'\n * },\n * {\n * name: 'GetPopulation',\n * args: { location: 'Los Angeles, CA' },\n * type: 'tool_call'\n * },\n * {\n * name: 'GetPopulation',\n * args: { location: 'New York, NY' },\n * type: 'tool_call'\n * }\n * ]\n * ```\n * </details>\n *\n * <br />\n *\n * <details>\n * <summary><strong>Structured Output</strong></summary>\n *\n * ```typescript\n * const Joke = z.object({\n * setup: z.string().describe(\"The setup of the joke\"),\n * punchline: z.string().describe(\"The punchline to the joke\"),\n * rating: z.number().optional().describe(\"How funny the joke is, from 1 to 10\")\n * }).describe('Joke to tell user.');\n *\n * const structuredLlm = llm.withStructuredOutput(Joke, { name: \"Joke\" });\n * const jokeResult = await structuredLlm.invoke(\"Tell me a joke about cats\");\n * console.log(jokeResult);\n * ```\n *\n * ```txt\n * {\n * setup: \"Why don\\\\'t cats play poker?\",\n * punchline: \"Why don\\\\'t cats play poker? Because they always have an ace up their sleeve!\"\n * }\n * ```\n * </details>\n *\n * <br />\n *\n * <details>\n * <summary><strong>Multimodal</strong></summary>\n *\n * ```typescript\n * import { HumanMessage } from '@langchain/core/messages';\n *\n * const imageUrl = \"https://example.com/image.jpg\";\n * const imageData = await fetch(imageUrl).then(res => res.arrayBuffer());\n * const base64Image = Buffer.from(imageData).toString('base64');\n *\n * const message = new HumanMessage({\n * content: [\n * { type: \"text\", text: \"describe the weather in this image\" },\n * {\n * type: \"image_url\",\n * image_url: { url: `data:image/jpeg;base64,${base64Image}` },\n * },\n * ]\n * });\n *\n * const imageDescriptionAiMsg = await llm.invoke([message]);\n * console.log(imageDescriptionAiMsg.content);\n * ```\n *\n * ```txt\n * The weather in the image appears to be clear and sunny. The sky is mostly blue with a few scattered white clouds, indicating fair weather. The bright sunlight is casting shadows on the green, grassy hill, suggesting it is a pleasant day with good visibility. There are no signs of rain or stormy conditions.\n * ```\n * </details>\n *\n * <br />\n *\n * <details>\n * <summary><strong>Usage Metadata</strong></summary>\n *\n * ```typescript\n * const aiMsgForMetadata = await llm.invoke(input);\n * console.log(aiMsgForMetadata.usage_metadata);\n * ```\n *\n * ```txt\n * { input_tokens: 10, output_tokens: 149, total_tokens: 159 }\n * ```\n * </details>\n *\n * <br />\n *\n * <details>\n * <summary><strong>Response Metadata</strong></summary>\n *\n * ```typescript\n * const aiMsgForResponseMetadata = await llm.invoke(input);\n * console.log(aiMsgForResponseMetadata.response_metadata);\n * ```\n *\n * ```txt\n * {\n * finishReason: 'STOP',\n * index: 0,\n * safetyRatings: [\n * {\n * category: 'HARM_CATEGORY_SEXUALLY_EXPLICIT',\n * probability: 'NEGLIGIBLE'\n * },\n * {\n * category: 'HARM_CATEGORY_HATE_SPEECH',\n * probability: 'NEGLIGIBLE'\n * },\n * { category: 'HARM_CATEGORY_HARASSMENT', probability: 'NEGLIGIBLE' },\n * {\n * category: 'HARM_CATEGORY_DANGEROUS_CONTENT',\n * probability: 'NEGLIGIBLE'\n * }\n * ]\n * }\n * ```\n * </details>\n *\n * <br />\n *\n * <details>\n * <summary><strong>Document Messages</strong></summary>\n *\n * This example will show you how to pass documents such as PDFs to Google\n * Generative AI through messages.\n *\n * ```typescript\n * const pdfPath = \"/Users/my_user/Downloads/invoice.pdf\";\n * const pdfBase64 = await fs.readFile(pdfPath, \"base64\");\n *\n * const response = await llm.invoke([\n * [\"system\", \"Use the provided documents to answer the question\"],\n * [\n * \"user\",\n * [\n * {\n * type: \"application/pdf\", // If the `type` field includes a single slash (`/`), it will be treated as inline data.\n * data: pdfBase64,\n * },\n * {\n * type: \"text\",\n * text: \"Summarize the contents of this PDF\",\n * },\n * ],\n * ],\n * ]);\n *\n * console.log(response.content);\n * ```\n *\n * ```txt\n * This is a billing invoice from Twitter Developers for X API Basic Access. The transaction date is January 7, 2025,\n * and the amount is $194.34, which has been paid. The subscription period is from January 7, 2025 21:02 to February 7, 2025 00:00 (UTC).\n * The tax is $0.00, with a tax rate of 0%. The total amount is $194.34. The payment was made using a Visa card ending in 7022,\n * expiring in 12/2026. The billing address is Brace Sproul, 1234 Main Street, San Francisco, CA, US 94103. The company being billed is\n * X Corp, located at 865 FM 1209 Building 2, Bastrop, TX, US 78602. Terms and conditions apply.\n * ```\n * </details>\n *\n * <br />\n */\nexport declare class ChatGoogleGenerativeAI extends BaseChatModel<GoogleGenerativeAIChatCallOptions, AIMessageChunk> implements GoogleGenerativeAIChatInput {\n static lc_name(): string;\n lc_serializable: boolean;\n get lc_secrets(): {\n [key: string]: string;\n } | undefined;\n lc_namespace: string[];\n get lc_aliases(): {\n apiKey: string;\n };\n model: string;\n temperature?: number;\n maxOutputTokens?: number;\n topP?: number;\n topK?: number;\n stopSequences: string[];\n safetySettings?: SafetySetting[];\n apiKey?: string;\n streaming: boolean;\n json?: boolean;\n streamUsage: boolean;\n convertSystemMessageToHumanContent: boolean | undefined;\n thinkingConfig?: GoogleGenerativeAIThinkingConfig;\n private client;\n get _isMultimodalModel(): boolean;\n constructor(fields: GoogleGenerativeAIChatInput);\n useCachedContent(cachedContent: CachedContent, modelParams?: ModelParams, requestOptions?: RequestOptions): void;\n get useSystemInstruction(): boolean;\n get computeUseSystemInstruction(): boolean;\n getLsParams(options: this[\"ParsedCallOptions\"]): LangSmithParams;\n _combineLLMOutput(): never[];\n _llmType(): string;\n bindTools(tools: GoogleGenerativeAIToolType[], kwargs?: Partial<GoogleGenerativeAIChatCallOptions>): Runnable<BaseLanguageModelInput, AIMessageChunk, GoogleGenerativeAIChatCallOptions>;\n invocationParams(options?: this[\"ParsedCallOptions\"]): Omit<GenerateContentRequest, \"contents\">;\n _generate(messages: BaseMessage[], options: this[\"ParsedCallOptions\"], runManager?: CallbackManagerForLLMRun): Promise<ChatResult>;\n _streamResponseChunks(messages: BaseMessage[], options: this[\"ParsedCallOptions\"], runManager?: CallbackManagerForLLMRun): AsyncGenerator<ChatGenerationChunk>;\n completionWithRetry(request: string | GenerateContentRequest | (string | GenerativeAIPart)[], options?: this[\"ParsedCallOptions\"]): Promise<import(\"@google/generative-ai\").GenerateContentResult>;\n /**\n * Return profiling information for the model.\n *\n * Provides information about the model's capabilities and constraints,\n * including token limits, multimodal support, and advanced features like\n * tool calling and structured output.\n *\n * @returns {ModelProfile} An object describing the model's capabilities and constraints\n *\n * @example\n * ```typescript\n * const model = new ChatGoogleGenerativeAI({ model: \"gemini-1.5-flash\" });\n * const profile = model.profile;\n * console.log(profile.maxInputTokens); // 2000000\n * console.log(profile.imageInputs); // true\n * ```\n */\n get profile(): ModelProfile;\n withStructuredOutput<RunOutput extends Record<string, any> = Record<string, any>>(outputSchema: InteropZodType<RunOutput> | Record<string, any>, config?: StructuredOutputMethodOptions<false>): Runnable<BaseLanguageModelInput, RunOutput>;\n withStructuredOutput<RunOutput extends Record<string, any> = Record<string, any>>(outputSchema: InteropZodType<RunOutput> | Record<string, any>, config?: StructuredOutputMethodOptions<true>): Runnable<BaseLanguageModelInput, {\n raw: BaseMessage;\n parsed: RunOutput;\n }>;\n}\n//# sourceMappingURL=chat_models.d.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XAM,sBAAAA,SAA+Bf,cAAcY,mCAAmChB,2BAA2BiB;;;;;;;;;;;;;;;;mBAgB3GzB;;;;;;mBAMAqB;;;sBAGGI;kCACYpB,6BAA6BF,8BAA8BC;;;mDAG1CU;;;mBAGhCQ,uCAAuCO,QAAQL,qCAAqCL,SAASF,wBAAwBT,gBAAgBgB;yDAC/FM,KAAK/B;sBACxCU,gEAAgEF,2BAA2BwB,QAAQpB;kCACvFF,gEAAgEF,2BAA2ByB,eAAetB;wCACpGX,mCAAmCG,+CAA2D6B,QAA3CE,sBAAAA,CAAmFC,qBAAAA;;;;;;;;;;;;;;;;;;iBAkB7JlB;yCACwBmB,sBAAsBA,mCAAmCf,eAAeQ,aAAaO,8BAA8BjB,uCAAuCC,SAASF,wBAAwBW;yCAC3LO,sBAAsBA,mCAAmCf,eAAeQ,aAAaO,8BAA8BjB,sCAAsCC,SAASF;SAChMR;YACGmB"}
|
package/dist/embeddings.d.cts
CHANGED
|
@@ -76,7 +76,7 @@ declare class GoogleGenerativeAIEmbeddings extends Embeddings implements GoogleG
|
|
|
76
76
|
taskType?: TaskType;
|
|
77
77
|
title?: string;
|
|
78
78
|
stripNewLines: boolean;
|
|
79
|
-
maxBatchSize: number;
|
|
79
|
+
maxBatchSize: number;
|
|
80
80
|
private client;
|
|
81
81
|
constructor(fields?: GoogleGenerativeAIEmbeddingsParams);
|
|
82
82
|
private _convertToContent;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"embeddings.d.cts","names":["TaskType","Embeddings","EmbeddingsParams","GoogleGenerativeAIEmbeddingsParams","GoogleGenerativeAIEmbeddings","Promise"],"sources":["../src/embeddings.d.ts"],"sourcesContent":["import type { TaskType } from \"@google/generative-ai\";\nimport { Embeddings, EmbeddingsParams } from \"@langchain/core/embeddings\";\n/**\n * Interface that extends EmbeddingsParams and defines additional\n * parameters specific to the GoogleGenerativeAIEmbeddings class.\n */\nexport interface GoogleGenerativeAIEmbeddingsParams extends EmbeddingsParams {\n /**\n * Model Name to use\n *\n * Alias for `model`\n *\n * Note: The format must follow the pattern - `{model}`\n */\n modelName?: string;\n /**\n * Model Name to use\n *\n * Note: The format must follow the pattern - `{model}`\n */\n model?: string;\n /**\n * Type of task for which the embedding will be used\n *\n * Note: currently only supported by `embedding-001` model\n */\n taskType?: TaskType;\n /**\n * An optional title for the text. Only applicable when TaskType is\n * `RETRIEVAL_DOCUMENT`\n *\n * Note: currently only supported by `embedding-001` model\n */\n title?: string;\n /**\n * Whether to strip new lines from the input text. Default to true\n */\n stripNewLines?: boolean;\n /**\n * Google API key to use\n */\n apiKey?: string;\n /**\n * Google API base URL to use\n */\n baseUrl?: string;\n}\n/**\n * Class that extends the Embeddings class and provides methods for\n * generating embeddings using the Google Palm API.\n * @example\n * ```typescript\n * const model = new GoogleGenerativeAIEmbeddings({\n * apiKey: \"<YOUR API KEY>\",\n * modelName: \"embedding-001\",\n * });\n *\n * // Embed a single query\n * const res = await model.embedQuery(\n * \"What would be a good company name for a company that makes colorful socks?\"\n * );\n * console.log({ res });\n *\n * // Embed multiple documents\n * const documentRes = await model.embedDocuments([\"Hello world\", \"Bye bye\"]);\n * console.log({ documentRes });\n * ```\n */\nexport declare class GoogleGenerativeAIEmbeddings extends Embeddings implements GoogleGenerativeAIEmbeddingsParams {\n apiKey?: string;\n modelName: string;\n model: string;\n taskType?: TaskType;\n title?: string;\n stripNewLines: boolean;\n maxBatchSize: number;\n private client;\n constructor(fields?: GoogleGenerativeAIEmbeddingsParams);\n private _convertToContent;\n protected _embedQueryContent(text: string): Promise<number[]>;\n protected _embedDocumentsContent(documents: string[]): Promise<number[][]>;\n /**\n * Method that takes a document as input and returns a promise that\n * resolves to an embedding for the document. It calls the _embedText\n * method with the document as the input.\n * @param document Document for which to generate an embedding.\n * @returns Promise that resolves to an embedding for the input document.\n */\n embedQuery(document: string): Promise<number[]>;\n /**\n * Method that takes an array of documents as input and returns a promise\n * that resolves to a 2D array of embeddings for each document. It calls\n * the _embedText method for each document in the array.\n * @param documents Array of documents for which to generate embeddings.\n * @returns Promise that resolves to a 2D array of embeddings for each input document.\n */\n embedDocuments(documents: string[]): Promise<number[][]>;\n}\n//# sourceMappingURL=embeddings.d.ts.map"],"mappings":";;;;;;;AAMA;AA8DA;AAIeA,UAlEEG,kCAAAA,SAA2CD,gBAkE7CF,CAAAA;EAKUG;;;;;;;EATyF,SAAA,CAAA,EAAA,MAAA;;;;;;;;;;;;aA1CnGH;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;cA0CMI,4BAAAA,SAAqCH,UAAAA,YAAsBE;;;;aAIjEH;;;;;uBAKUG;;8CAEuBE;yDACWA;;;;;;;;gCAQzBA;;;;;;;;uCAQOA"}
|
package/dist/embeddings.d.ts
CHANGED
|
@@ -76,7 +76,7 @@ declare class GoogleGenerativeAIEmbeddings extends Embeddings implements GoogleG
|
|
|
76
76
|
taskType?: TaskType;
|
|
77
77
|
title?: string;
|
|
78
78
|
stripNewLines: boolean;
|
|
79
|
-
maxBatchSize: number;
|
|
79
|
+
maxBatchSize: number;
|
|
80
80
|
private client;
|
|
81
81
|
constructor(fields?: GoogleGenerativeAIEmbeddingsParams);
|
|
82
82
|
private _convertToContent;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"embeddings.d.ts","names":["TaskType","Embeddings","EmbeddingsParams","GoogleGenerativeAIEmbeddingsParams","GoogleGenerativeAIEmbeddings","Promise"],"sources":["../src/embeddings.d.ts"],"sourcesContent":["import type { TaskType } from \"@google/generative-ai\";\nimport { Embeddings, EmbeddingsParams } from \"@langchain/core/embeddings\";\n/**\n * Interface that extends EmbeddingsParams and defines additional\n * parameters specific to the GoogleGenerativeAIEmbeddings class.\n */\nexport interface GoogleGenerativeAIEmbeddingsParams extends EmbeddingsParams {\n /**\n * Model Name to use\n *\n * Alias for `model`\n *\n * Note: The format must follow the pattern - `{model}`\n */\n modelName?: string;\n /**\n * Model Name to use\n *\n * Note: The format must follow the pattern - `{model}`\n */\n model?: string;\n /**\n * Type of task for which the embedding will be used\n *\n * Note: currently only supported by `embedding-001` model\n */\n taskType?: TaskType;\n /**\n * An optional title for the text. Only applicable when TaskType is\n * `RETRIEVAL_DOCUMENT`\n *\n * Note: currently only supported by `embedding-001` model\n */\n title?: string;\n /**\n * Whether to strip new lines from the input text. Default to true\n */\n stripNewLines?: boolean;\n /**\n * Google API key to use\n */\n apiKey?: string;\n /**\n * Google API base URL to use\n */\n baseUrl?: string;\n}\n/**\n * Class that extends the Embeddings class and provides methods for\n * generating embeddings using the Google Palm API.\n * @example\n * ```typescript\n * const model = new GoogleGenerativeAIEmbeddings({\n * apiKey: \"<YOUR API KEY>\",\n * modelName: \"embedding-001\",\n * });\n *\n * // Embed a single query\n * const res = await model.embedQuery(\n * \"What would be a good company name for a company that makes colorful socks?\"\n * );\n * console.log({ res });\n *\n * // Embed multiple documents\n * const documentRes = await model.embedDocuments([\"Hello world\", \"Bye bye\"]);\n * console.log({ documentRes });\n * ```\n */\nexport declare class GoogleGenerativeAIEmbeddings extends Embeddings implements GoogleGenerativeAIEmbeddingsParams {\n apiKey?: string;\n modelName: string;\n model: string;\n taskType?: TaskType;\n title?: string;\n stripNewLines: boolean;\n maxBatchSize: number;\n private client;\n constructor(fields?: GoogleGenerativeAIEmbeddingsParams);\n private _convertToContent;\n protected _embedQueryContent(text: string): Promise<number[]>;\n protected _embedDocumentsContent(documents: string[]): Promise<number[][]>;\n /**\n * Method that takes a document as input and returns a promise that\n * resolves to an embedding for the document. It calls the _embedText\n * method with the document as the input.\n * @param document Document for which to generate an embedding.\n * @returns Promise that resolves to an embedding for the input document.\n */\n embedQuery(document: string): Promise<number[]>;\n /**\n * Method that takes an array of documents as input and returns a promise\n * that resolves to a 2D array of embeddings for each document. It calls\n * the _embedText method for each document in the array.\n * @param documents Array of documents for which to generate embeddings.\n * @returns Promise that resolves to a 2D array of embeddings for each input document.\n */\n embedDocuments(documents: string[]): Promise<number[][]>;\n}\n//# sourceMappingURL=embeddings.d.ts.map"],"mappings":";;;;;;;AAMA;AA8DA;AAIeA,UAlEEG,kCAAAA,SAA2CD,gBAkE7CF,CAAAA;EAKUG;;;;;;;EATyF,SAAA,CAAA,EAAA,MAAA;;;;;;;;;;;;aA1CnGH;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;cA0CMI,4BAAAA,SAAqCH,UAAAA,YAAsBE;;;;aAIjEH;;;;;uBAKUG;;8CAEuBE;yDACWA;;;;;;;;gCAQzBA;;;;;;;;uCAQOA"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"types.d.cts","names":["CodeExecutionTool","FunctionDeclarationsTool","GoogleGenerativeAIFunctionDeclarationsTool","GoogleSearchRetrievalTool","BindToolsInput","GoogleGenerativeAIToolType","GoogleGenerativeAIThinkingConfig","GoogleGenerativeAIThinkingLevel"],"sources":["../src/types.d.ts"],"sourcesContent":["import { CodeExecutionTool, FunctionDeclarationsTool as GoogleGenerativeAIFunctionDeclarationsTool, GoogleSearchRetrievalTool } from \"@google/generative-ai\";\nimport { BindToolsInput } from \"@langchain/core/language_models/chat_models\";\nexport type GoogleGenerativeAIToolType = BindToolsInput | GoogleGenerativeAIFunctionDeclarationsTool | CodeExecutionTool | GoogleSearchRetrievalTool;\nexport type GoogleGenerativeAIThinkingConfig = {\n /** Indicates whether to include thoughts in the response. If true, thoughts are returned only when available. */\n includeThoughts?: boolean;\n /** The number of thoughts tokens that the model should generate. */\n thinkingBudget?: number;\n /** Optional. The level of thoughts tokens that the model should generate. */\n thinkingLevel?: GoogleGenerativeAIThinkingLevel;\n};\nexport type GoogleGenerativeAIThinkingLevel = \"THINKING_LEVEL_UNSPECIFIED\" | \"LOW\" | \"HIGH\";\n//# sourceMappingURL=types.d.ts.map"],"mappings":";;;;KAEYK,0BAAAA,GAA6BD,iBAAiBF,2BAA6CF,oBAAoBG;KAC/GG,gCAAAA;EADAD;EAA6BD,eAAAA,CAAAA,EAAAA,OAAAA;EAAiBF;EAA6CF,cAAAA,CAAAA,EAAAA,MAAAA;EAAoBG;EAAyB,aAAA,CAAA,EAOhII,+BAPgI;AACpJ,CAAA;AAQYA,KAAAA,+BAAAA,GAA+B,4BAAA,GAAA,KAAA,GAAA,MAAA"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"types.d.ts","names":["CodeExecutionTool","FunctionDeclarationsTool","GoogleGenerativeAIFunctionDeclarationsTool","GoogleSearchRetrievalTool","BindToolsInput","GoogleGenerativeAIToolType","GoogleGenerativeAIThinkingConfig","GoogleGenerativeAIThinkingLevel"],"sources":["../src/types.d.ts"],"sourcesContent":["import { CodeExecutionTool, FunctionDeclarationsTool as GoogleGenerativeAIFunctionDeclarationsTool, GoogleSearchRetrievalTool } from \"@google/generative-ai\";\nimport { BindToolsInput } from \"@langchain/core/language_models/chat_models\";\nexport type GoogleGenerativeAIToolType = BindToolsInput | GoogleGenerativeAIFunctionDeclarationsTool | CodeExecutionTool | GoogleSearchRetrievalTool;\nexport type GoogleGenerativeAIThinkingConfig = {\n /** Indicates whether to include thoughts in the response. If true, thoughts are returned only when available. */\n includeThoughts?: boolean;\n /** The number of thoughts tokens that the model should generate. */\n thinkingBudget?: number;\n /** Optional. The level of thoughts tokens that the model should generate. */\n thinkingLevel?: GoogleGenerativeAIThinkingLevel;\n};\nexport type GoogleGenerativeAIThinkingLevel = \"THINKING_LEVEL_UNSPECIFIED\" | \"LOW\" | \"HIGH\";\n//# sourceMappingURL=types.d.ts.map"],"mappings":";;;;KAEYK,0BAAAA,GAA6BD,iBAAiBF,2BAA6CF,oBAAoBG;KAC/GG,gCAAAA;EADAD;EAA6BD,eAAAA,CAAAA,EAAAA,OAAAA;EAAiBF;EAA6CF,cAAAA,CAAAA,EAAAA,MAAAA;EAAoBG;EAAyB,aAAA,CAAA,EAOhII,+BAPgI;AACpJ,CAAA;AAQYA,KAAAA,+BAAAA,GAA+B,4BAAA,GAAA,KAAA,GAAA,MAAA"}
|
package/dist/utils/common.cjs
CHANGED
|
@@ -11,10 +11,8 @@ const _FUNCTION_CALL_THOUGHT_SIGNATURES_MAP_KEY = "__gemini_function_call_though
|
|
|
11
11
|
const DUMMY_SIGNATURE = "ErYCCrMCAdHtim9kOoOkrPiCNVsmlpMIKd7ZMxgiFbVQOkgp7nlLcDMzVsZwIzvuT7nQROivoXA72ccC2lSDvR0Gh7dkWaGuj7ctv6t7ZceHnecx0QYa+ix8tYpRfjhyWozQ49lWiws6+YGjCt10KRTyWsZ2h6O7iHTYJwKIRwGUHRKy/qK/6kFxJm5ML00gLq4D8s5Z6DBpp2ZlR+uF4G8jJgeWQgyHWVdx2wGYElaceVAc66tZdPQRdOHpWtgYSI1YdaXgVI8KHY3/EfNc2YqqMIulvkDBAnuMhkAjV9xmBa54Tq+ih3Im4+r3DzqhGqYdsSkhS0kZMwte4Hjs65dZzCw9lANxIqYi1DJ639WNPYihp/DCJCos7o+/EeSPJaio5sgWDyUnMGkY1atsJZ+m7pj7DD5tvQ==";
|
|
12
12
|
const iife = (fn) => fn();
|
|
13
13
|
function getMessageAuthor(message) {
|
|
14
|
-
const type = message._getType();
|
|
15
14
|
if (__langchain_core_messages.ChatMessage.isInstance(message)) return message.role;
|
|
16
|
-
|
|
17
|
-
return message.name ?? type;
|
|
15
|
+
return message.type;
|
|
18
16
|
}
|
|
19
17
|
/**
|
|
20
18
|
* Maps a message type to a Google Generative AI chat author.
|
|
@@ -230,7 +228,7 @@ function mapGenerateContentResultToChatResult(response, extra) {
|
|
|
230
228
|
};
|
|
231
229
|
const [candidate] = response.candidates;
|
|
232
230
|
const { content: candidateContent,...generationInfo } = candidate;
|
|
233
|
-
const functionCalls = candidateContent.parts
|
|
231
|
+
const functionCalls = candidateContent.parts?.reduce((acc, p) => {
|
|
234
232
|
if ("functionCall" in p && p.functionCall) acc.push({
|
|
235
233
|
...p,
|
|
236
234
|
id: "id" in p.functionCall && typeof p.functionCall.id === "string" ? p.functionCall.id : (0, uuid.v4)()
|
|
@@ -312,7 +310,7 @@ function convertResponseContentToChatGenerationChunk(response, extra) {
|
|
|
312
310
|
if (!response.candidates || response.candidates.length === 0) return null;
|
|
313
311
|
const [candidate] = response.candidates;
|
|
314
312
|
const { content: candidateContent,...generationInfo } = candidate;
|
|
315
|
-
const functionCalls = candidateContent.parts
|
|
313
|
+
const functionCalls = candidateContent.parts?.reduce((acc, p) => {
|
|
316
314
|
if ("functionCall" in p && p.functionCall) acc.push({
|
|
317
315
|
...p,
|
|
318
316
|
id: "id" in p.functionCall && typeof p.functionCall.id === "string" ? p.functionCall.id : (0, uuid.v4)()
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"common.cjs","names":["fn: () => string","message: BaseMessage","ChatMessage","author: string","content: MessageContentComplex","message: ToolMessage | ToolMessageChunk","previousMessages: BaseMessage[]","isMultimodalModel: boolean","standardContentBlockConverter: StandardContentBlockConverter<{\n text: TextPart;\n image: FileDataPart | InlineDataPart;\n audio: FileDataPart | InlineDataPart;\n file: FileDataPart | InlineDataPart | TextPart;\n }>","model?: string","functionCalls: FunctionCallPart[]","messageParts: Part[]","messages: BaseMessage[]","convertSystemMessageToHumanContent: boolean","model: string","prevContent","content: Content","response: EnhancedGenerateContentResponse","extra?: {\n usageMetadata: UsageMetadata | undefined;\n }","content: MessageContent | undefined","generation: ChatGeneration","AIMessage","extra: {\n usageMetadata?: UsageMetadata | undefined;\n index: number;\n }","toolCallChunks: ToolCallChunk[]","ChatGenerationChunk","AIMessageChunk","tools: GoogleGenerativeAIToolType[]","schemaToGenerativeAIParameters","jsonSchemaToGeminiParameters","usageMetadata: GenerateContentResponse[\"usageMetadata\"]","output: UsageMetadata"],"sources":["../../src/utils/common.ts"],"sourcesContent":["import {\n EnhancedGenerateContentResponse,\n Content,\n Part,\n type FunctionDeclarationsTool as GoogleGenerativeAIFunctionDeclarationsTool,\n type FunctionDeclaration as GenerativeAIFunctionDeclaration,\n POSSIBLE_ROLES,\n FunctionCallPart,\n TextPart,\n FileDataPart,\n InlineDataPart,\n type GenerateContentResponse,\n} from \"@google/generative-ai\";\nimport {\n AIMessage,\n AIMessageChunk,\n BaseMessage,\n ChatMessage,\n ToolMessage,\n ToolMessageChunk,\n MessageContent,\n MessageContentComplex,\n UsageMetadata,\n isAIMessage,\n isBaseMessage,\n isToolMessage,\n StandardContentBlockConverter,\n parseBase64DataUrl,\n convertToProviderContentBlock,\n isDataContentBlock,\n InputTokenDetails,\n} from \"@langchain/core/messages\";\nimport {\n ChatGeneration,\n ChatGenerationChunk,\n ChatResult,\n} from \"@langchain/core/outputs\";\nimport { isLangChainTool } from \"@langchain/core/utils/function_calling\";\nimport { isOpenAITool } from \"@langchain/core/language_models/base\";\nimport { ToolCallChunk } from \"@langchain/core/messages/tool\";\nimport { v4 as uuidv4 } from \"uuid\";\nimport {\n jsonSchemaToGeminiParameters,\n schemaToGenerativeAIParameters,\n} from \"./zod_to_genai_parameters.js\";\nimport { GoogleGenerativeAIToolType } from \"../types.js\";\n\nexport const _FUNCTION_CALL_THOUGHT_SIGNATURES_MAP_KEY =\n \"__gemini_function_call_thought_signatures__\";\nconst DUMMY_SIGNATURE =\n \"ErYCCrMCAdHtim9kOoOkrPiCNVsmlpMIKd7ZMxgiFbVQOkgp7nlLcDMzVsZwIzvuT7nQROivoXA72ccC2lSDvR0Gh7dkWaGuj7ctv6t7ZceHnecx0QYa+ix8tYpRfjhyWozQ49lWiws6+YGjCt10KRTyWsZ2h6O7iHTYJwKIRwGUHRKy/qK/6kFxJm5ML00gLq4D8s5Z6DBpp2ZlR+uF4G8jJgeWQgyHWVdx2wGYElaceVAc66tZdPQRdOHpWtgYSI1YdaXgVI8KHY3/EfNc2YqqMIulvkDBAnuMhkAjV9xmBa54Tq+ih3Im4+r3DzqhGqYdsSkhS0kZMwte4Hjs65dZzCw9lANxIqYi1DJ639WNPYihp/DCJCos7o+/EeSPJaio5sgWDyUnMGkY1atsJZ+m7pj7DD5tvQ==\";\n\nconst iife = (fn: () => string) => fn();\n\nexport function getMessageAuthor(message: BaseMessage) {\n const type = message._getType();\n if (ChatMessage.isInstance(message)) {\n return message.role;\n }\n if (type === \"tool\") {\n return type;\n }\n return message.name ?? type;\n}\n\n/**\n * Maps a message type to a Google Generative AI chat author.\n * @param message The message to map.\n * @param model The model to use for mapping.\n * @returns The message type mapped to a Google Generative AI chat author.\n */\nexport function convertAuthorToRole(\n author: string\n): (typeof POSSIBLE_ROLES)[number] {\n switch (author) {\n /**\n * Note: Gemini currently is not supporting system messages\n * we will convert them to human messages and merge with following\n * */\n case \"supervisor\":\n case \"ai\":\n case \"model\": // getMessageAuthor returns message.name. code ex.: return message.name ?? type;\n return \"model\";\n case \"system\":\n return \"system\";\n case \"human\":\n return \"user\";\n case \"tool\":\n case \"function\":\n return \"function\";\n default:\n throw new Error(`Unknown / unsupported author: ${author}`);\n }\n}\n\nfunction messageContentMedia(content: MessageContentComplex): Part {\n if (\"mimeType\" in content && \"data\" in content) {\n return {\n inlineData: {\n mimeType: content.mimeType,\n data: content.data,\n },\n };\n }\n if (\"mimeType\" in content && \"fileUri\" in content) {\n return {\n fileData: {\n mimeType: content.mimeType,\n fileUri: content.fileUri,\n },\n };\n }\n\n throw new Error(\"Invalid media content\");\n}\n\nfunction inferToolNameFromPreviousMessages(\n message: ToolMessage | ToolMessageChunk,\n previousMessages: BaseMessage[]\n): string | undefined {\n return previousMessages\n .map((msg) => {\n if (isAIMessage(msg)) {\n return msg.tool_calls ?? [];\n }\n return [];\n })\n .flat()\n .find((toolCall) => {\n return toolCall.id === message.tool_call_id;\n })?.name;\n}\n\nfunction _getStandardContentBlockConverter(isMultimodalModel: boolean) {\n const standardContentBlockConverter: StandardContentBlockConverter<{\n text: TextPart;\n image: FileDataPart | InlineDataPart;\n audio: FileDataPart | InlineDataPart;\n file: FileDataPart | InlineDataPart | TextPart;\n }> = {\n providerName: \"Google Gemini\",\n\n fromStandardTextBlock(block) {\n return {\n text: block.text,\n };\n },\n\n fromStandardImageBlock(block): FileDataPart | InlineDataPart {\n if (!isMultimodalModel) {\n throw new Error(\"This model does not support images\");\n }\n if (block.source_type === \"url\") {\n const data = parseBase64DataUrl({ dataUrl: block.url });\n if (data) {\n return {\n inlineData: {\n mimeType: data.mime_type,\n data: data.data,\n },\n };\n } else {\n return {\n fileData: {\n mimeType: block.mime_type ?? \"\",\n fileUri: block.url,\n },\n };\n }\n }\n\n if (block.source_type === \"base64\") {\n return {\n inlineData: {\n mimeType: block.mime_type ?? \"\",\n data: block.data,\n },\n };\n }\n\n throw new Error(`Unsupported source type: ${block.source_type}`);\n },\n\n fromStandardAudioBlock(block): FileDataPart | InlineDataPart {\n if (!isMultimodalModel) {\n throw new Error(\"This model does not support audio\");\n }\n if (block.source_type === \"url\") {\n const data = parseBase64DataUrl({ dataUrl: block.url });\n if (data) {\n return {\n inlineData: {\n mimeType: data.mime_type,\n data: data.data,\n },\n };\n } else {\n return {\n fileData: {\n mimeType: block.mime_type ?? \"\",\n fileUri: block.url,\n },\n };\n }\n }\n\n if (block.source_type === \"base64\") {\n return {\n inlineData: {\n mimeType: block.mime_type ?? \"\",\n data: block.data,\n },\n };\n }\n\n throw new Error(`Unsupported source type: ${block.source_type}`);\n },\n\n fromStandardFileBlock(block): FileDataPart | InlineDataPart | TextPart {\n if (!isMultimodalModel) {\n throw new Error(\"This model does not support files\");\n }\n if (block.source_type === \"text\") {\n return {\n text: block.text,\n };\n }\n if (block.source_type === \"url\") {\n const data = parseBase64DataUrl({ dataUrl: block.url });\n if (data) {\n return {\n inlineData: {\n mimeType: data.mime_type,\n data: data.data,\n },\n };\n } else {\n return {\n fileData: {\n mimeType: block.mime_type ?? \"\",\n fileUri: block.url,\n },\n };\n }\n }\n\n if (block.source_type === \"base64\") {\n return {\n inlineData: {\n mimeType: block.mime_type ?? \"\",\n data: block.data,\n },\n };\n }\n throw new Error(`Unsupported source type: ${block.source_type}`);\n },\n };\n return standardContentBlockConverter;\n}\n\nfunction _convertLangChainContentToPart(\n content: MessageContentComplex,\n isMultimodalModel: boolean\n): Part | undefined {\n if (isDataContentBlock(content)) {\n return convertToProviderContentBlock(\n content,\n _getStandardContentBlockConverter(isMultimodalModel)\n );\n }\n\n if (content.type === \"text\") {\n return { text: content.text };\n } else if (content.type === \"executableCode\") {\n return { executableCode: content.executableCode };\n } else if (content.type === \"codeExecutionResult\") {\n return { codeExecutionResult: content.codeExecutionResult };\n } else if (content.type === \"image_url\") {\n if (!isMultimodalModel) {\n throw new Error(`This model does not support images`);\n }\n let source;\n if (typeof content.image_url === \"string\") {\n source = content.image_url;\n } else if (\n typeof content.image_url === \"object\" &&\n \"url\" in content.image_url\n ) {\n source = content.image_url.url;\n } else {\n throw new Error(\"Please provide image as base64 encoded data URL\");\n }\n const [dm, data] = source.split(\",\");\n if (!dm.startsWith(\"data:\")) {\n throw new Error(\"Please provide image as base64 encoded data URL\");\n }\n\n const [mimeType, encoding] = dm.replace(/^data:/, \"\").split(\";\");\n if (encoding !== \"base64\") {\n throw new Error(\"Please provide image as base64 encoded data URL\");\n }\n\n return {\n inlineData: {\n data,\n mimeType,\n },\n };\n } else if (content.type === \"media\") {\n return messageContentMedia(content);\n } else if (content.type === \"tool_use\") {\n return {\n functionCall: {\n name: content.name,\n args: content.input,\n },\n };\n } else if (\n content.type?.includes(\"/\") &&\n // Ensure it's a single slash.\n content.type.split(\"/\").length === 2 &&\n \"data\" in content &&\n typeof content.data === \"string\"\n ) {\n return {\n inlineData: {\n mimeType: content.type,\n data: content.data,\n },\n };\n } else if (\"functionCall\" in content) {\n // No action needed here — function calls will be added later from message.tool_calls\n return undefined;\n } else {\n if (\"type\" in content) {\n throw new Error(`Unknown content type ${content.type}`);\n } else {\n throw new Error(`Unknown content ${JSON.stringify(content)}`);\n }\n }\n}\n\nexport function convertMessageContentToParts(\n message: BaseMessage,\n isMultimodalModel: boolean,\n previousMessages: BaseMessage[],\n model?: string\n): Part[] {\n if (isToolMessage(message)) {\n const messageName =\n message.name ??\n inferToolNameFromPreviousMessages(message, previousMessages);\n if (messageName === undefined) {\n throw new Error(\n `Google requires a tool name for each tool call response, and we could not infer a called tool name for ToolMessage \"${message.id}\" from your passed messages. Please populate a \"name\" field on that ToolMessage explicitly.`\n );\n }\n\n const result = Array.isArray(message.content)\n ? (message.content\n .map((c) => _convertLangChainContentToPart(c, isMultimodalModel))\n .filter((p) => p !== undefined) as Part[])\n : message.content;\n\n if (message.status === \"error\") {\n return [\n {\n functionResponse: {\n name: messageName,\n // The API expects an object with an `error` field if the function call fails.\n // `error` must be a valid object (not a string or array), so we wrap `message.content` here\n response: { error: { details: result } },\n },\n },\n ];\n }\n\n return [\n {\n functionResponse: {\n name: messageName,\n // again, can't have a string or array value for `response`, so we wrap it as an object here\n response: { result },\n },\n },\n ];\n }\n\n let functionCalls: FunctionCallPart[] = [];\n const messageParts: Part[] = [];\n\n if (typeof message.content === \"string\" && message.content) {\n messageParts.push({ text: message.content });\n }\n\n if (Array.isArray(message.content)) {\n messageParts.push(\n ...(message.content\n .map((c) => _convertLangChainContentToPart(c, isMultimodalModel))\n .filter((p) => p !== undefined) as Part[])\n );\n }\n\n const functionThoughtSignatures = message.additional_kwargs?.[\n _FUNCTION_CALL_THOUGHT_SIGNATURES_MAP_KEY\n ] as Record<string, string>;\n\n if (isAIMessage(message) && message.tool_calls?.length) {\n functionCalls = message.tool_calls.map((tc) => {\n const thoughtSignature = iife(() => {\n if (tc.id) {\n const signature = functionThoughtSignatures?.[tc.id];\n if (signature) {\n return signature;\n }\n }\n if (model?.includes(\"gemini-3\")) {\n return DUMMY_SIGNATURE;\n }\n return \"\";\n });\n return {\n functionCall: {\n name: tc.name,\n args: tc.args,\n },\n ...(thoughtSignature ? { thoughtSignature } : {}),\n };\n });\n }\n\n return [...messageParts, ...functionCalls];\n}\n\nexport function convertBaseMessagesToContent(\n messages: BaseMessage[],\n isMultimodalModel: boolean,\n convertSystemMessageToHumanContent: boolean = false,\n model: string\n) {\n return messages.reduce<{\n content: Content[];\n mergeWithPreviousContent: boolean;\n }>(\n (acc, message, index) => {\n if (!isBaseMessage(message)) {\n throw new Error(\"Unsupported message input\");\n }\n const author = getMessageAuthor(message);\n if (author === \"system\" && index !== 0) {\n throw new Error(\"System message should be the first one\");\n }\n const role = convertAuthorToRole(author);\n\n const prevContent = acc.content[acc.content.length];\n if (\n !acc.mergeWithPreviousContent &&\n prevContent &&\n prevContent.role === role\n ) {\n throw new Error(\n \"Google Generative AI requires alternate messages between authors\"\n );\n }\n\n const parts = convertMessageContentToParts(\n message,\n isMultimodalModel,\n messages.slice(0, index),\n model\n );\n\n if (acc.mergeWithPreviousContent) {\n const prevContent = acc.content[acc.content.length - 1];\n if (!prevContent) {\n throw new Error(\n \"There was a problem parsing your system message. Please try a prompt without one.\"\n );\n }\n prevContent.parts.push(...parts);\n\n return {\n mergeWithPreviousContent: false,\n content: acc.content,\n };\n }\n let actualRole = role;\n if (\n actualRole === \"function\" ||\n (actualRole === \"system\" && !convertSystemMessageToHumanContent)\n ) {\n // GenerativeAI API will throw an error if the role is not \"user\" or \"model.\"\n actualRole = \"user\";\n }\n const content: Content = {\n role: actualRole,\n parts,\n };\n return {\n mergeWithPreviousContent:\n author === \"system\" && !convertSystemMessageToHumanContent,\n content: [...acc.content, content],\n };\n },\n { content: [], mergeWithPreviousContent: false }\n ).content;\n}\n\nexport function mapGenerateContentResultToChatResult(\n response: EnhancedGenerateContentResponse,\n extra?: {\n usageMetadata: UsageMetadata | undefined;\n }\n): ChatResult {\n // if rejected or error, return empty generations with reason in filters\n if (\n !response.candidates ||\n response.candidates.length === 0 ||\n !response.candidates[0]\n ) {\n return {\n generations: [],\n llmOutput: {\n filters: response.promptFeedback,\n },\n };\n }\n const [candidate] = response.candidates;\n const { content: candidateContent, ...generationInfo } = candidate;\n const functionCalls = candidateContent.parts.reduce((acc, p) => {\n if (\"functionCall\" in p && p.functionCall) {\n acc.push({\n ...p,\n id:\n \"id\" in p.functionCall && typeof p.functionCall.id === \"string\"\n ? p.functionCall.id\n : uuidv4(),\n });\n }\n return acc;\n }, [] as (FunctionCallPart & { id: string })[]);\n let content: MessageContent | undefined;\n\n if (\n Array.isArray(candidateContent?.parts) &&\n candidateContent.parts.length === 1 &&\n candidateContent.parts[0].text\n ) {\n content = candidateContent.parts[0].text;\n } else if (\n Array.isArray(candidateContent?.parts) &&\n candidateContent.parts.length > 0\n ) {\n content = candidateContent.parts.map((p) => {\n if (\"text\" in p) {\n return {\n type: \"text\",\n text: p.text,\n };\n } else if (\"inlineData\" in p) {\n return {\n type: \"inlineData\",\n inlineData: p.inlineData,\n };\n } else if (\"functionCall\" in p) {\n return {\n type: \"functionCall\",\n functionCall: p.functionCall,\n };\n } else if (\"functionResponse\" in p) {\n return {\n type: \"functionResponse\",\n functionResponse: p.functionResponse,\n };\n } else if (\"fileData\" in p) {\n return {\n type: \"fileData\",\n fileData: p.fileData,\n };\n } else if (\"executableCode\" in p) {\n return {\n type: \"executableCode\",\n executableCode: p.executableCode,\n };\n } else if (\"codeExecutionResult\" in p) {\n return {\n type: \"codeExecutionResult\",\n codeExecutionResult: p.codeExecutionResult,\n };\n }\n return p;\n });\n } else {\n // no content returned - likely due to abnormal stop reason, e.g. malformed function call\n content = [];\n }\n\n const functionThoughtSignatures = functionCalls?.reduce((acc, fc) => {\n if (\"thoughtSignature\" in fc && typeof fc.thoughtSignature === \"string\") {\n acc[fc.id] = fc.thoughtSignature;\n }\n return acc;\n }, {} as Record<string, string>);\n\n let text = \"\";\n if (typeof content === \"string\") {\n text = content;\n } else if (Array.isArray(content) && content.length > 0) {\n const block = content.find((b) => \"text\" in b) as\n | { text: string }\n | undefined;\n text = block?.text ?? text;\n }\n\n const generation: ChatGeneration = {\n text,\n message: new AIMessage({\n content: content ?? \"\",\n tool_calls: functionCalls?.map((fc) => ({\n type: \"tool_call\",\n id: fc.id,\n name: fc.functionCall.name,\n args: fc.functionCall.args,\n })),\n additional_kwargs: {\n ...generationInfo,\n [_FUNCTION_CALL_THOUGHT_SIGNATURES_MAP_KEY]: functionThoughtSignatures,\n },\n usage_metadata: extra?.usageMetadata,\n }),\n generationInfo,\n };\n\n return {\n generations: [generation],\n llmOutput: {\n tokenUsage: {\n promptTokens: extra?.usageMetadata?.input_tokens,\n completionTokens: extra?.usageMetadata?.output_tokens,\n totalTokens: extra?.usageMetadata?.total_tokens,\n },\n },\n };\n}\n\nexport function convertResponseContentToChatGenerationChunk(\n response: EnhancedGenerateContentResponse,\n extra: {\n usageMetadata?: UsageMetadata | undefined;\n index: number;\n }\n): ChatGenerationChunk | null {\n if (!response.candidates || response.candidates.length === 0) {\n return null;\n }\n const [candidate] = response.candidates;\n const { content: candidateContent, ...generationInfo } = candidate;\n const functionCalls = candidateContent.parts.reduce((acc, p) => {\n if (\"functionCall\" in p && p.functionCall) {\n acc.push({\n ...p,\n id:\n \"id\" in p.functionCall && typeof p.functionCall.id === \"string\"\n ? p.functionCall.id\n : uuidv4(),\n });\n }\n return acc;\n }, [] as (FunctionCallPart & { id: string })[]);\n let content: MessageContent | undefined;\n // Checks if some parts do not have text. If false, it means that the content is a string.\n if (\n Array.isArray(candidateContent?.parts) &&\n candidateContent.parts.every((p) => \"text\" in p)\n ) {\n content = candidateContent.parts.map((p) => p.text).join(\"\");\n } else if (Array.isArray(candidateContent?.parts)) {\n content = candidateContent.parts.map((p) => {\n if (\"text\" in p) {\n return {\n type: \"text\",\n text: p.text,\n };\n } else if (\"inlineData\" in p) {\n return {\n type: \"inlineData\",\n inlineData: p.inlineData,\n };\n } else if (\"functionCall\" in p) {\n return {\n type: \"functionCall\",\n functionCall: p.functionCall,\n };\n } else if (\"functionResponse\" in p) {\n return {\n type: \"functionResponse\",\n functionResponse: p.functionResponse,\n };\n } else if (\"fileData\" in p) {\n return {\n type: \"fileData\",\n fileData: p.fileData,\n };\n } else if (\"executableCode\" in p) {\n return {\n type: \"executableCode\",\n executableCode: p.executableCode,\n };\n } else if (\"codeExecutionResult\" in p) {\n return {\n type: \"codeExecutionResult\",\n codeExecutionResult: p.codeExecutionResult,\n };\n }\n return p;\n });\n } else {\n // no content returned - likely due to abnormal stop reason, e.g. malformed function call\n content = [];\n }\n\n let text = \"\";\n if (content && typeof content === \"string\") {\n text = content;\n } else if (Array.isArray(content)) {\n const block = content.find((b) => \"text\" in b) as\n | { text: string }\n | undefined;\n text = block?.text ?? \"\";\n }\n\n const toolCallChunks: ToolCallChunk[] = [];\n if (functionCalls) {\n toolCallChunks.push(\n ...functionCalls.map((fc) => ({\n type: \"tool_call_chunk\" as const,\n id: fc.id,\n name: fc.functionCall.name,\n args: JSON.stringify(fc.functionCall.args),\n }))\n );\n }\n\n const functionThoughtSignatures = functionCalls?.reduce((acc, fc) => {\n if (\"thoughtSignature\" in fc && typeof fc.thoughtSignature === \"string\") {\n acc[fc.id] = fc.thoughtSignature;\n }\n return acc;\n }, {} as Record<string, string>);\n\n return new ChatGenerationChunk({\n text,\n message: new AIMessageChunk({\n content: content || \"\",\n name: !candidateContent ? undefined : candidateContent.role,\n tool_call_chunks: toolCallChunks,\n // Each chunk can have unique \"generationInfo\", and merging strategy is unclear,\n // so leave blank for now.\n additional_kwargs: {\n [_FUNCTION_CALL_THOUGHT_SIGNATURES_MAP_KEY]: functionThoughtSignatures,\n },\n response_metadata: {\n model_provider: \"google-genai\",\n },\n usage_metadata: extra.usageMetadata,\n }),\n generationInfo,\n });\n}\n\nexport function convertToGenerativeAITools(\n tools: GoogleGenerativeAIToolType[]\n): GoogleGenerativeAIFunctionDeclarationsTool[] {\n if (\n tools.every(\n (tool) =>\n \"functionDeclarations\" in tool &&\n Array.isArray(tool.functionDeclarations)\n )\n ) {\n return tools as GoogleGenerativeAIFunctionDeclarationsTool[];\n }\n return [\n {\n functionDeclarations: tools.map(\n (tool): GenerativeAIFunctionDeclaration => {\n if (isLangChainTool(tool)) {\n const jsonSchema = schemaToGenerativeAIParameters(tool.schema);\n if (\n jsonSchema.type === \"object\" &&\n \"properties\" in jsonSchema &&\n Object.keys(jsonSchema.properties).length === 0\n ) {\n return {\n name: tool.name,\n description: tool.description,\n };\n }\n return {\n name: tool.name,\n description: tool.description,\n parameters: jsonSchema,\n };\n }\n if (isOpenAITool(tool)) {\n return {\n name: tool.function.name,\n description:\n tool.function.description ?? `A function available to call.`,\n parameters: jsonSchemaToGeminiParameters(\n tool.function.parameters\n ),\n };\n }\n return tool as unknown as GenerativeAIFunctionDeclaration;\n }\n ),\n },\n ];\n}\n\nexport function convertUsageMetadata(\n usageMetadata: GenerateContentResponse[\"usageMetadata\"],\n model: string\n): UsageMetadata {\n const output: UsageMetadata = {\n input_tokens: usageMetadata?.promptTokenCount ?? 0,\n output_tokens: usageMetadata?.candidatesTokenCount ?? 0,\n total_tokens: usageMetadata?.totalTokenCount ?? 0,\n };\n if (usageMetadata?.cachedContentTokenCount) {\n output.input_token_details ??= {};\n output.input_token_details.cache_read =\n usageMetadata.cachedContentTokenCount;\n }\n // gemini-3-pro-preview has bracket based tracking of tokens per request\n // FIXME(hntrl): move this usageMetadata calculation elsewhere\n if (model === \"gemini-3-pro-preview\") {\n const over200k = Math.max(0, usageMetadata?.promptTokenCount ?? 0 - 200000);\n const cachedOver200k = Math.max(\n 0,\n usageMetadata?.cachedContentTokenCount ?? 0 - 200000\n );\n if (over200k) {\n output.input_token_details = {\n ...output.input_token_details,\n over_200k: over200k,\n } as InputTokenDetails;\n }\n if (cachedOver200k) {\n output.input_token_details = {\n ...output.input_token_details,\n cache_read_over_200k: cachedOver200k,\n } as InputTokenDetails;\n }\n }\n return output;\n}\n"],"mappings":";;;;;;;;;AA+CA,MAAa,4CACX;AACF,MAAM,kBACJ;AAEF,MAAM,OAAO,CAACA,OAAqB,IAAI;AAEvC,SAAgB,iBAAiBC,SAAsB;CACrD,MAAM,OAAO,QAAQ,UAAU;AAC/B,KAAIC,sCAAY,WAAW,QAAQ,CACjC,QAAO,QAAQ;AAEjB,KAAI,SAAS,OACX,QAAO;AAET,QAAO,QAAQ,QAAQ;AACxB;;;;;;;AAQD,SAAgB,oBACdC,QACiC;AACjC,SAAQ,QAAR;EAKE,KAA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"file":"common.cjs","names":["fn: () => string","message: BaseMessage","ChatMessage","author: string","content: MessageContentComplex","message: ToolMessage | ToolMessageChunk","previousMessages: BaseMessage[]","isMultimodalModel: boolean","standardContentBlockConverter: StandardContentBlockConverter<{\n text: TextPart;\n image: FileDataPart | InlineDataPart;\n audio: FileDataPart | InlineDataPart;\n file: FileDataPart | InlineDataPart | TextPart;\n }>","model?: string","functionCalls: FunctionCallPart[]","messageParts: Part[]","messages: BaseMessage[]","convertSystemMessageToHumanContent: boolean","model: string","prevContent","content: Content","response: EnhancedGenerateContentResponse","extra?: {\n usageMetadata: UsageMetadata | undefined;\n }","content: MessageContent | undefined","generation: ChatGeneration","AIMessage","extra: {\n usageMetadata?: UsageMetadata | undefined;\n index: number;\n }","toolCallChunks: ToolCallChunk[]","ChatGenerationChunk","AIMessageChunk","tools: GoogleGenerativeAIToolType[]","schemaToGenerativeAIParameters","jsonSchemaToGeminiParameters","usageMetadata: GenerateContentResponse[\"usageMetadata\"]","output: UsageMetadata"],"sources":["../../src/utils/common.ts"],"sourcesContent":["import {\n EnhancedGenerateContentResponse,\n Content,\n Part,\n type FunctionDeclarationsTool as GoogleGenerativeAIFunctionDeclarationsTool,\n type FunctionDeclaration as GenerativeAIFunctionDeclaration,\n POSSIBLE_ROLES,\n FunctionCallPart,\n TextPart,\n FileDataPart,\n InlineDataPart,\n type GenerateContentResponse,\n} from \"@google/generative-ai\";\nimport {\n AIMessage,\n AIMessageChunk,\n BaseMessage,\n ChatMessage,\n ToolMessage,\n ToolMessageChunk,\n MessageContent,\n MessageContentComplex,\n UsageMetadata,\n isAIMessage,\n isBaseMessage,\n isToolMessage,\n StandardContentBlockConverter,\n parseBase64DataUrl,\n convertToProviderContentBlock,\n isDataContentBlock,\n InputTokenDetails,\n} from \"@langchain/core/messages\";\nimport {\n ChatGeneration,\n ChatGenerationChunk,\n ChatResult,\n} from \"@langchain/core/outputs\";\nimport { isLangChainTool } from \"@langchain/core/utils/function_calling\";\nimport { isOpenAITool } from \"@langchain/core/language_models/base\";\nimport { ToolCallChunk } from \"@langchain/core/messages/tool\";\nimport { v4 as uuidv4 } from \"uuid\";\nimport {\n jsonSchemaToGeminiParameters,\n schemaToGenerativeAIParameters,\n} from \"./zod_to_genai_parameters.js\";\nimport { GoogleGenerativeAIToolType } from \"../types.js\";\n\nexport const _FUNCTION_CALL_THOUGHT_SIGNATURES_MAP_KEY =\n \"__gemini_function_call_thought_signatures__\";\nconst DUMMY_SIGNATURE =\n \"ErYCCrMCAdHtim9kOoOkrPiCNVsmlpMIKd7ZMxgiFbVQOkgp7nlLcDMzVsZwIzvuT7nQROivoXA72ccC2lSDvR0Gh7dkWaGuj7ctv6t7ZceHnecx0QYa+ix8tYpRfjhyWozQ49lWiws6+YGjCt10KRTyWsZ2h6O7iHTYJwKIRwGUHRKy/qK/6kFxJm5ML00gLq4D8s5Z6DBpp2ZlR+uF4G8jJgeWQgyHWVdx2wGYElaceVAc66tZdPQRdOHpWtgYSI1YdaXgVI8KHY3/EfNc2YqqMIulvkDBAnuMhkAjV9xmBa54Tq+ih3Im4+r3DzqhGqYdsSkhS0kZMwte4Hjs65dZzCw9lANxIqYi1DJ639WNPYihp/DCJCos7o+/EeSPJaio5sgWDyUnMGkY1atsJZ+m7pj7DD5tvQ==\";\n\nconst iife = (fn: () => string) => fn();\n\nexport function getMessageAuthor(message: BaseMessage) {\n if (ChatMessage.isInstance(message)) {\n return message.role;\n }\n return message.type;\n}\n\n/**\n * Maps a message type to a Google Generative AI chat author.\n * @param message The message to map.\n * @param model The model to use for mapping.\n * @returns The message type mapped to a Google Generative AI chat author.\n */\nexport function convertAuthorToRole(\n author: string\n): (typeof POSSIBLE_ROLES)[number] {\n switch (author) {\n /**\n * Note: Gemini currently is not supporting system messages\n * we will convert them to human messages and merge with following\n * */\n case \"supervisor\":\n case \"ai\":\n case \"model\":\n return \"model\";\n case \"system\":\n return \"system\";\n case \"human\":\n return \"user\";\n case \"tool\":\n case \"function\":\n return \"function\";\n default:\n throw new Error(`Unknown / unsupported author: ${author}`);\n }\n}\n\nfunction messageContentMedia(content: MessageContentComplex): Part {\n if (\"mimeType\" in content && \"data\" in content) {\n return {\n inlineData: {\n mimeType: content.mimeType,\n data: content.data,\n },\n };\n }\n if (\"mimeType\" in content && \"fileUri\" in content) {\n return {\n fileData: {\n mimeType: content.mimeType,\n fileUri: content.fileUri,\n },\n };\n }\n\n throw new Error(\"Invalid media content\");\n}\n\nfunction inferToolNameFromPreviousMessages(\n message: ToolMessage | ToolMessageChunk,\n previousMessages: BaseMessage[]\n): string | undefined {\n return previousMessages\n .map((msg) => {\n if (isAIMessage(msg)) {\n return msg.tool_calls ?? [];\n }\n return [];\n })\n .flat()\n .find((toolCall) => {\n return toolCall.id === message.tool_call_id;\n })?.name;\n}\n\nfunction _getStandardContentBlockConverter(isMultimodalModel: boolean) {\n const standardContentBlockConverter: StandardContentBlockConverter<{\n text: TextPart;\n image: FileDataPart | InlineDataPart;\n audio: FileDataPart | InlineDataPart;\n file: FileDataPart | InlineDataPart | TextPart;\n }> = {\n providerName: \"Google Gemini\",\n\n fromStandardTextBlock(block) {\n return {\n text: block.text,\n };\n },\n\n fromStandardImageBlock(block): FileDataPart | InlineDataPart {\n if (!isMultimodalModel) {\n throw new Error(\"This model does not support images\");\n }\n if (block.source_type === \"url\") {\n const data = parseBase64DataUrl({ dataUrl: block.url });\n if (data) {\n return {\n inlineData: {\n mimeType: data.mime_type,\n data: data.data,\n },\n };\n } else {\n return {\n fileData: {\n mimeType: block.mime_type ?? \"\",\n fileUri: block.url,\n },\n };\n }\n }\n\n if (block.source_type === \"base64\") {\n return {\n inlineData: {\n mimeType: block.mime_type ?? \"\",\n data: block.data,\n },\n };\n }\n\n throw new Error(`Unsupported source type: ${block.source_type}`);\n },\n\n fromStandardAudioBlock(block): FileDataPart | InlineDataPart {\n if (!isMultimodalModel) {\n throw new Error(\"This model does not support audio\");\n }\n if (block.source_type === \"url\") {\n const data = parseBase64DataUrl({ dataUrl: block.url });\n if (data) {\n return {\n inlineData: {\n mimeType: data.mime_type,\n data: data.data,\n },\n };\n } else {\n return {\n fileData: {\n mimeType: block.mime_type ?? \"\",\n fileUri: block.url,\n },\n };\n }\n }\n\n if (block.source_type === \"base64\") {\n return {\n inlineData: {\n mimeType: block.mime_type ?? \"\",\n data: block.data,\n },\n };\n }\n\n throw new Error(`Unsupported source type: ${block.source_type}`);\n },\n\n fromStandardFileBlock(block): FileDataPart | InlineDataPart | TextPart {\n if (!isMultimodalModel) {\n throw new Error(\"This model does not support files\");\n }\n if (block.source_type === \"text\") {\n return {\n text: block.text,\n };\n }\n if (block.source_type === \"url\") {\n const data = parseBase64DataUrl({ dataUrl: block.url });\n if (data) {\n return {\n inlineData: {\n mimeType: data.mime_type,\n data: data.data,\n },\n };\n } else {\n return {\n fileData: {\n mimeType: block.mime_type ?? \"\",\n fileUri: block.url,\n },\n };\n }\n }\n\n if (block.source_type === \"base64\") {\n return {\n inlineData: {\n mimeType: block.mime_type ?? \"\",\n data: block.data,\n },\n };\n }\n throw new Error(`Unsupported source type: ${block.source_type}`);\n },\n };\n return standardContentBlockConverter;\n}\n\nfunction _convertLangChainContentToPart(\n content: MessageContentComplex,\n isMultimodalModel: boolean\n): Part | undefined {\n if (isDataContentBlock(content)) {\n return convertToProviderContentBlock(\n content,\n _getStandardContentBlockConverter(isMultimodalModel)\n );\n }\n\n if (content.type === \"text\") {\n return { text: content.text };\n } else if (content.type === \"executableCode\") {\n return { executableCode: content.executableCode };\n } else if (content.type === \"codeExecutionResult\") {\n return { codeExecutionResult: content.codeExecutionResult };\n } else if (content.type === \"image_url\") {\n if (!isMultimodalModel) {\n throw new Error(`This model does not support images`);\n }\n let source;\n if (typeof content.image_url === \"string\") {\n source = content.image_url;\n } else if (\n typeof content.image_url === \"object\" &&\n \"url\" in content.image_url\n ) {\n source = content.image_url.url;\n } else {\n throw new Error(\"Please provide image as base64 encoded data URL\");\n }\n const [dm, data] = source.split(\",\");\n if (!dm.startsWith(\"data:\")) {\n throw new Error(\"Please provide image as base64 encoded data URL\");\n }\n\n const [mimeType, encoding] = dm.replace(/^data:/, \"\").split(\";\");\n if (encoding !== \"base64\") {\n throw new Error(\"Please provide image as base64 encoded data URL\");\n }\n\n return {\n inlineData: {\n data,\n mimeType,\n },\n };\n } else if (content.type === \"media\") {\n return messageContentMedia(content);\n } else if (content.type === \"tool_use\") {\n return {\n functionCall: {\n name: content.name,\n args: content.input,\n },\n };\n } else if (\n content.type?.includes(\"/\") &&\n // Ensure it's a single slash.\n content.type.split(\"/\").length === 2 &&\n \"data\" in content &&\n typeof content.data === \"string\"\n ) {\n return {\n inlineData: {\n mimeType: content.type,\n data: content.data,\n },\n };\n } else if (\"functionCall\" in content) {\n // No action needed here — function calls will be added later from message.tool_calls\n return undefined;\n } else {\n if (\"type\" in content) {\n throw new Error(`Unknown content type ${content.type}`);\n } else {\n throw new Error(`Unknown content ${JSON.stringify(content)}`);\n }\n }\n}\n\nexport function convertMessageContentToParts(\n message: BaseMessage,\n isMultimodalModel: boolean,\n previousMessages: BaseMessage[],\n model?: string\n): Part[] {\n if (isToolMessage(message)) {\n const messageName =\n message.name ??\n inferToolNameFromPreviousMessages(message, previousMessages);\n if (messageName === undefined) {\n throw new Error(\n `Google requires a tool name for each tool call response, and we could not infer a called tool name for ToolMessage \"${message.id}\" from your passed messages. Please populate a \"name\" field on that ToolMessage explicitly.`\n );\n }\n\n const result = Array.isArray(message.content)\n ? (message.content\n .map((c) => _convertLangChainContentToPart(c, isMultimodalModel))\n .filter((p) => p !== undefined) as Part[])\n : message.content;\n\n if (message.status === \"error\") {\n return [\n {\n functionResponse: {\n name: messageName,\n // The API expects an object with an `error` field if the function call fails.\n // `error` must be a valid object (not a string or array), so we wrap `message.content` here\n response: { error: { details: result } },\n },\n },\n ];\n }\n\n return [\n {\n functionResponse: {\n name: messageName,\n // again, can't have a string or array value for `response`, so we wrap it as an object here\n response: { result },\n },\n },\n ];\n }\n\n let functionCalls: FunctionCallPart[] = [];\n const messageParts: Part[] = [];\n\n if (typeof message.content === \"string\" && message.content) {\n messageParts.push({ text: message.content });\n }\n\n if (Array.isArray(message.content)) {\n messageParts.push(\n ...(message.content\n .map((c) => _convertLangChainContentToPart(c, isMultimodalModel))\n .filter((p) => p !== undefined) as Part[])\n );\n }\n\n const functionThoughtSignatures = message.additional_kwargs?.[\n _FUNCTION_CALL_THOUGHT_SIGNATURES_MAP_KEY\n ] as Record<string, string>;\n\n if (isAIMessage(message) && message.tool_calls?.length) {\n functionCalls = message.tool_calls.map((tc) => {\n const thoughtSignature = iife(() => {\n if (tc.id) {\n const signature = functionThoughtSignatures?.[tc.id];\n if (signature) {\n return signature;\n }\n }\n if (model?.includes(\"gemini-3\")) {\n return DUMMY_SIGNATURE;\n }\n return \"\";\n });\n return {\n functionCall: {\n name: tc.name,\n args: tc.args,\n },\n ...(thoughtSignature ? { thoughtSignature } : {}),\n };\n });\n }\n\n return [...messageParts, ...functionCalls];\n}\n\nexport function convertBaseMessagesToContent(\n messages: BaseMessage[],\n isMultimodalModel: boolean,\n convertSystemMessageToHumanContent: boolean = false,\n model: string\n) {\n return messages.reduce<{\n content: Content[];\n mergeWithPreviousContent: boolean;\n }>(\n (acc, message, index) => {\n if (!isBaseMessage(message)) {\n throw new Error(\"Unsupported message input\");\n }\n const author = getMessageAuthor(message);\n if (author === \"system\" && index !== 0) {\n throw new Error(\"System message should be the first one\");\n }\n const role = convertAuthorToRole(author);\n\n const prevContent = acc.content[acc.content.length];\n if (\n !acc.mergeWithPreviousContent &&\n prevContent &&\n prevContent.role === role\n ) {\n throw new Error(\n \"Google Generative AI requires alternate messages between authors\"\n );\n }\n\n const parts = convertMessageContentToParts(\n message,\n isMultimodalModel,\n messages.slice(0, index),\n model\n );\n\n if (acc.mergeWithPreviousContent) {\n const prevContent = acc.content[acc.content.length - 1];\n if (!prevContent) {\n throw new Error(\n \"There was a problem parsing your system message. Please try a prompt without one.\"\n );\n }\n prevContent.parts.push(...parts);\n\n return {\n mergeWithPreviousContent: false,\n content: acc.content,\n };\n }\n let actualRole = role;\n if (\n actualRole === \"function\" ||\n (actualRole === \"system\" && !convertSystemMessageToHumanContent)\n ) {\n // GenerativeAI API will throw an error if the role is not \"user\" or \"model.\"\n actualRole = \"user\";\n }\n const content: Content = {\n role: actualRole,\n parts,\n };\n return {\n mergeWithPreviousContent:\n author === \"system\" && !convertSystemMessageToHumanContent,\n content: [...acc.content, content],\n };\n },\n { content: [], mergeWithPreviousContent: false }\n ).content;\n}\n\nexport function mapGenerateContentResultToChatResult(\n response: EnhancedGenerateContentResponse,\n extra?: {\n usageMetadata: UsageMetadata | undefined;\n }\n): ChatResult {\n // if rejected or error, return empty generations with reason in filters\n if (\n !response.candidates ||\n response.candidates.length === 0 ||\n !response.candidates[0]\n ) {\n return {\n generations: [],\n llmOutput: {\n filters: response.promptFeedback,\n },\n };\n }\n const [candidate] = response.candidates;\n const { content: candidateContent, ...generationInfo } = candidate;\n const functionCalls = candidateContent.parts?.reduce((acc, p) => {\n if (\"functionCall\" in p && p.functionCall) {\n acc.push({\n ...p,\n id:\n \"id\" in p.functionCall && typeof p.functionCall.id === \"string\"\n ? p.functionCall.id\n : uuidv4(),\n });\n }\n return acc;\n }, [] as (FunctionCallPart & { id: string })[]);\n let content: MessageContent | undefined;\n\n if (\n Array.isArray(candidateContent?.parts) &&\n candidateContent.parts.length === 1 &&\n candidateContent.parts[0].text\n ) {\n content = candidateContent.parts[0].text;\n } else if (\n Array.isArray(candidateContent?.parts) &&\n candidateContent.parts.length > 0\n ) {\n content = candidateContent.parts.map((p) => {\n if (\"text\" in p) {\n return {\n type: \"text\",\n text: p.text,\n };\n } else if (\"inlineData\" in p) {\n return {\n type: \"inlineData\",\n inlineData: p.inlineData,\n };\n } else if (\"functionCall\" in p) {\n return {\n type: \"functionCall\",\n functionCall: p.functionCall,\n };\n } else if (\"functionResponse\" in p) {\n return {\n type: \"functionResponse\",\n functionResponse: p.functionResponse,\n };\n } else if (\"fileData\" in p) {\n return {\n type: \"fileData\",\n fileData: p.fileData,\n };\n } else if (\"executableCode\" in p) {\n return {\n type: \"executableCode\",\n executableCode: p.executableCode,\n };\n } else if (\"codeExecutionResult\" in p) {\n return {\n type: \"codeExecutionResult\",\n codeExecutionResult: p.codeExecutionResult,\n };\n }\n return p;\n });\n } else {\n // no content returned - likely due to abnormal stop reason, e.g. malformed function call\n content = [];\n }\n\n const functionThoughtSignatures = functionCalls?.reduce((acc, fc) => {\n if (\"thoughtSignature\" in fc && typeof fc.thoughtSignature === \"string\") {\n acc[fc.id] = fc.thoughtSignature;\n }\n return acc;\n }, {} as Record<string, string>);\n\n let text = \"\";\n if (typeof content === \"string\") {\n text = content;\n } else if (Array.isArray(content) && content.length > 0) {\n const block = content.find((b) => \"text\" in b) as\n | { text: string }\n | undefined;\n text = block?.text ?? text;\n }\n\n const generation: ChatGeneration = {\n text,\n message: new AIMessage({\n content: content ?? \"\",\n tool_calls: functionCalls?.map((fc) => ({\n type: \"tool_call\",\n id: fc.id,\n name: fc.functionCall.name,\n args: fc.functionCall.args,\n })),\n additional_kwargs: {\n ...generationInfo,\n [_FUNCTION_CALL_THOUGHT_SIGNATURES_MAP_KEY]: functionThoughtSignatures,\n },\n usage_metadata: extra?.usageMetadata,\n }),\n generationInfo,\n };\n\n return {\n generations: [generation],\n llmOutput: {\n tokenUsage: {\n promptTokens: extra?.usageMetadata?.input_tokens,\n completionTokens: extra?.usageMetadata?.output_tokens,\n totalTokens: extra?.usageMetadata?.total_tokens,\n },\n },\n };\n}\n\nexport function convertResponseContentToChatGenerationChunk(\n response: EnhancedGenerateContentResponse,\n extra: {\n usageMetadata?: UsageMetadata | undefined;\n index: number;\n }\n): ChatGenerationChunk | null {\n if (!response.candidates || response.candidates.length === 0) {\n return null;\n }\n const [candidate] = response.candidates;\n const { content: candidateContent, ...generationInfo } = candidate;\n const functionCalls = candidateContent.parts?.reduce((acc, p) => {\n if (\"functionCall\" in p && p.functionCall) {\n acc.push({\n ...p,\n id:\n \"id\" in p.functionCall && typeof p.functionCall.id === \"string\"\n ? p.functionCall.id\n : uuidv4(),\n });\n }\n return acc;\n }, [] as (FunctionCallPart & { id: string })[]);\n let content: MessageContent | undefined;\n // Checks if some parts do not have text. If false, it means that the content is a string.\n if (\n Array.isArray(candidateContent?.parts) &&\n candidateContent.parts.every((p) => \"text\" in p)\n ) {\n content = candidateContent.parts.map((p) => p.text).join(\"\");\n } else if (Array.isArray(candidateContent?.parts)) {\n content = candidateContent.parts.map((p) => {\n if (\"text\" in p) {\n return {\n type: \"text\",\n text: p.text,\n };\n } else if (\"inlineData\" in p) {\n return {\n type: \"inlineData\",\n inlineData: p.inlineData,\n };\n } else if (\"functionCall\" in p) {\n return {\n type: \"functionCall\",\n functionCall: p.functionCall,\n };\n } else if (\"functionResponse\" in p) {\n return {\n type: \"functionResponse\",\n functionResponse: p.functionResponse,\n };\n } else if (\"fileData\" in p) {\n return {\n type: \"fileData\",\n fileData: p.fileData,\n };\n } else if (\"executableCode\" in p) {\n return {\n type: \"executableCode\",\n executableCode: p.executableCode,\n };\n } else if (\"codeExecutionResult\" in p) {\n return {\n type: \"codeExecutionResult\",\n codeExecutionResult: p.codeExecutionResult,\n };\n }\n return p;\n });\n } else {\n // no content returned - likely due to abnormal stop reason, e.g. malformed function call\n content = [];\n }\n\n let text = \"\";\n if (content && typeof content === \"string\") {\n text = content;\n } else if (Array.isArray(content)) {\n const block = content.find((b) => \"text\" in b) as\n | { text: string }\n | undefined;\n text = block?.text ?? \"\";\n }\n\n const toolCallChunks: ToolCallChunk[] = [];\n if (functionCalls) {\n toolCallChunks.push(\n ...functionCalls.map((fc) => ({\n type: \"tool_call_chunk\" as const,\n id: fc.id,\n name: fc.functionCall.name,\n args: JSON.stringify(fc.functionCall.args),\n }))\n );\n }\n\n const functionThoughtSignatures = functionCalls?.reduce((acc, fc) => {\n if (\"thoughtSignature\" in fc && typeof fc.thoughtSignature === \"string\") {\n acc[fc.id] = fc.thoughtSignature;\n }\n return acc;\n }, {} as Record<string, string>);\n\n return new ChatGenerationChunk({\n text,\n message: new AIMessageChunk({\n content: content || \"\",\n name: !candidateContent ? undefined : candidateContent.role,\n tool_call_chunks: toolCallChunks,\n // Each chunk can have unique \"generationInfo\", and merging strategy is unclear,\n // so leave blank for now.\n additional_kwargs: {\n [_FUNCTION_CALL_THOUGHT_SIGNATURES_MAP_KEY]: functionThoughtSignatures,\n },\n response_metadata: {\n model_provider: \"google-genai\",\n },\n usage_metadata: extra.usageMetadata,\n }),\n generationInfo,\n });\n}\n\nexport function convertToGenerativeAITools(\n tools: GoogleGenerativeAIToolType[]\n): GoogleGenerativeAIFunctionDeclarationsTool[] {\n if (\n tools.every(\n (tool) =>\n \"functionDeclarations\" in tool &&\n Array.isArray(tool.functionDeclarations)\n )\n ) {\n return tools as GoogleGenerativeAIFunctionDeclarationsTool[];\n }\n return [\n {\n functionDeclarations: tools.map(\n (tool): GenerativeAIFunctionDeclaration => {\n if (isLangChainTool(tool)) {\n const jsonSchema = schemaToGenerativeAIParameters(tool.schema);\n if (\n jsonSchema.type === \"object\" &&\n \"properties\" in jsonSchema &&\n Object.keys(jsonSchema.properties).length === 0\n ) {\n return {\n name: tool.name,\n description: tool.description,\n };\n }\n return {\n name: tool.name,\n description: tool.description,\n parameters: jsonSchema,\n };\n }\n if (isOpenAITool(tool)) {\n return {\n name: tool.function.name,\n description:\n tool.function.description ?? `A function available to call.`,\n parameters: jsonSchemaToGeminiParameters(\n tool.function.parameters\n ),\n };\n }\n return tool as unknown as GenerativeAIFunctionDeclaration;\n }\n ),\n },\n ];\n}\n\nexport function convertUsageMetadata(\n usageMetadata: GenerateContentResponse[\"usageMetadata\"],\n model: string\n): UsageMetadata {\n const output: UsageMetadata = {\n input_tokens: usageMetadata?.promptTokenCount ?? 0,\n output_tokens: usageMetadata?.candidatesTokenCount ?? 0,\n total_tokens: usageMetadata?.totalTokenCount ?? 0,\n };\n if (usageMetadata?.cachedContentTokenCount) {\n output.input_token_details ??= {};\n output.input_token_details.cache_read =\n usageMetadata.cachedContentTokenCount;\n }\n // gemini-3-pro-preview has bracket based tracking of tokens per request\n // FIXME(hntrl): move this usageMetadata calculation elsewhere\n if (model === \"gemini-3-pro-preview\") {\n const over200k = Math.max(0, usageMetadata?.promptTokenCount ?? 0 - 200000);\n const cachedOver200k = Math.max(\n 0,\n usageMetadata?.cachedContentTokenCount ?? 0 - 200000\n );\n if (over200k) {\n output.input_token_details = {\n ...output.input_token_details,\n over_200k: over200k,\n } as InputTokenDetails;\n }\n if (cachedOver200k) {\n output.input_token_details = {\n ...output.input_token_details,\n cache_read_over_200k: cachedOver200k,\n } as InputTokenDetails;\n }\n }\n return output;\n}\n"],"mappings":";;;;;;;;;AA+CA,MAAa,4CACX;AACF,MAAM,kBACJ;AAEF,MAAM,OAAO,CAACA,OAAqB,IAAI;AAEvC,SAAgB,iBAAiBC,SAAsB;AACrD,KAAIC,sCAAY,WAAW,QAAQ,CACjC,QAAO,QAAQ;AAEjB,QAAO,QAAQ;AAChB;;;;;;;AAQD,SAAgB,oBACdC,QACiC;AACjC,SAAQ,QAAR;EAKE,KAAK;EACL,KAAK;EACL,KAAK,QACH,QAAO;EACT,KAAK,SACH,QAAO;EACT,KAAK,QACH,QAAO;EACT,KAAK;EACL,KAAK,WACH,QAAO;EACT,QACE,OAAM,IAAI,MAAM,CAAC,8BAA8B,EAAE,QAAQ;CAC5D;AACF;AAED,SAAS,oBAAoBC,SAAsC;AACjE,KAAI,cAAc,WAAW,UAAU,QACrC,QAAO,EACL,YAAY;EACV,UAAU,QAAQ;EAClB,MAAM,QAAQ;CACf,EACF;AAEH,KAAI,cAAc,WAAW,aAAa,QACxC,QAAO,EACL,UAAU;EACR,UAAU,QAAQ;EAClB,SAAS,QAAQ;CAClB,EACF;AAGH,OAAM,IAAI,MAAM;AACjB;AAED,SAAS,kCACPC,SACAC,kBACoB;AACpB,QAAO,iBACJ,IAAI,CAAC,QAAQ;AACZ,iDAAgB,IAAI,CAClB,QAAO,IAAI,cAAc,CAA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,aACE,KAAK,SAAS,eAAe,CAAC,6BAA6B,CAAC;GAC9D,YAAYC,6DACV,KAAK,SAAS,WACf;EACF;AAEH,SAAO;CACR,EACF,CACF,CACF;AACF;AAED,SAAgB,qBACdC,eACAf,OACe;CACf,MAAMgB,SAAwB;EAC5B,cAAc,eAAe,oBAAoB;EACjD,eAAe,eAAe,wBAAwB;EACtD,cAAc,eAAe,mBAAmB;CACjD;AACD,KAAI,eAAe,yBAAyB;EAC1C,OAAO,wBAAwB,CAAE;EACjC,OAAO,oBAAoB,aACzB,cAAc;CACjB;AAGD,KAAI,UAAU,wBAAwB;EACpC,MAAM,WAAW,KAAK,IAAI,GAAG,eAAe,oBAAoB,KAAW;EAC3E,MAAM,iBAAiB,KAAK,IAC1B,GACA,eAAe,2BAA2B,KAC3C;AACD,MAAI,UACF,OAAO,sBAAsB;GAC3B,GAAG,OAAO;GACV,WAAW;EACZ;AAEH,MAAI,gBACF,OAAO,sBAAsB;GAC3B,GAAG,OAAO;GACV,sBAAsB;EACvB;CAEJ;AACD,QAAO;AACR"}
|
package/dist/utils/common.js
CHANGED
|
@@ -10,10 +10,8 @@ const _FUNCTION_CALL_THOUGHT_SIGNATURES_MAP_KEY = "__gemini_function_call_though
|
|
|
10
10
|
const DUMMY_SIGNATURE = "ErYCCrMCAdHtim9kOoOkrPiCNVsmlpMIKd7ZMxgiFbVQOkgp7nlLcDMzVsZwIzvuT7nQROivoXA72ccC2lSDvR0Gh7dkWaGuj7ctv6t7ZceHnecx0QYa+ix8tYpRfjhyWozQ49lWiws6+YGjCt10KRTyWsZ2h6O7iHTYJwKIRwGUHRKy/qK/6kFxJm5ML00gLq4D8s5Z6DBpp2ZlR+uF4G8jJgeWQgyHWVdx2wGYElaceVAc66tZdPQRdOHpWtgYSI1YdaXgVI8KHY3/EfNc2YqqMIulvkDBAnuMhkAjV9xmBa54Tq+ih3Im4+r3DzqhGqYdsSkhS0kZMwte4Hjs65dZzCw9lANxIqYi1DJ639WNPYihp/DCJCos7o+/EeSPJaio5sgWDyUnMGkY1atsJZ+m7pj7DD5tvQ==";
|
|
11
11
|
const iife = (fn) => fn();
|
|
12
12
|
function getMessageAuthor(message) {
|
|
13
|
-
const type = message._getType();
|
|
14
13
|
if (ChatMessage.isInstance(message)) return message.role;
|
|
15
|
-
|
|
16
|
-
return message.name ?? type;
|
|
14
|
+
return message.type;
|
|
17
15
|
}
|
|
18
16
|
/**
|
|
19
17
|
* Maps a message type to a Google Generative AI chat author.
|
|
@@ -229,7 +227,7 @@ function mapGenerateContentResultToChatResult(response, extra) {
|
|
|
229
227
|
};
|
|
230
228
|
const [candidate] = response.candidates;
|
|
231
229
|
const { content: candidateContent,...generationInfo } = candidate;
|
|
232
|
-
const functionCalls = candidateContent.parts
|
|
230
|
+
const functionCalls = candidateContent.parts?.reduce((acc, p) => {
|
|
233
231
|
if ("functionCall" in p && p.functionCall) acc.push({
|
|
234
232
|
...p,
|
|
235
233
|
id: "id" in p.functionCall && typeof p.functionCall.id === "string" ? p.functionCall.id : v4()
|
|
@@ -311,7 +309,7 @@ function convertResponseContentToChatGenerationChunk(response, extra) {
|
|
|
311
309
|
if (!response.candidates || response.candidates.length === 0) return null;
|
|
312
310
|
const [candidate] = response.candidates;
|
|
313
311
|
const { content: candidateContent,...generationInfo } = candidate;
|
|
314
|
-
const functionCalls = candidateContent.parts
|
|
312
|
+
const functionCalls = candidateContent.parts?.reduce((acc, p) => {
|
|
315
313
|
if ("functionCall" in p && p.functionCall) acc.push({
|
|
316
314
|
...p,
|
|
317
315
|
id: "id" in p.functionCall && typeof p.functionCall.id === "string" ? p.functionCall.id : v4()
|
package/dist/utils/common.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"common.js","names":["fn: () => string","message: BaseMessage","author: string","content: MessageContentComplex","message: ToolMessage | ToolMessageChunk","previousMessages: BaseMessage[]","isMultimodalModel: boolean","standardContentBlockConverter: StandardContentBlockConverter<{\n text: TextPart;\n image: FileDataPart | InlineDataPart;\n audio: FileDataPart | InlineDataPart;\n file: FileDataPart | InlineDataPart | TextPart;\n }>","model?: string","functionCalls: FunctionCallPart[]","messageParts: Part[]","messages: BaseMessage[]","convertSystemMessageToHumanContent: boolean","model: string","prevContent","content: Content","response: EnhancedGenerateContentResponse","extra?: {\n usageMetadata: UsageMetadata | undefined;\n }","uuidv4","content: MessageContent | undefined","generation: ChatGeneration","extra: {\n usageMetadata?: UsageMetadata | undefined;\n index: number;\n }","toolCallChunks: ToolCallChunk[]","tools: GoogleGenerativeAIToolType[]","usageMetadata: GenerateContentResponse[\"usageMetadata\"]","output: UsageMetadata"],"sources":["../../src/utils/common.ts"],"sourcesContent":["import {\n EnhancedGenerateContentResponse,\n Content,\n Part,\n type FunctionDeclarationsTool as GoogleGenerativeAIFunctionDeclarationsTool,\n type FunctionDeclaration as GenerativeAIFunctionDeclaration,\n POSSIBLE_ROLES,\n FunctionCallPart,\n TextPart,\n FileDataPart,\n InlineDataPart,\n type GenerateContentResponse,\n} from \"@google/generative-ai\";\nimport {\n AIMessage,\n AIMessageChunk,\n BaseMessage,\n ChatMessage,\n ToolMessage,\n ToolMessageChunk,\n MessageContent,\n MessageContentComplex,\n UsageMetadata,\n isAIMessage,\n isBaseMessage,\n isToolMessage,\n StandardContentBlockConverter,\n parseBase64DataUrl,\n convertToProviderContentBlock,\n isDataContentBlock,\n InputTokenDetails,\n} from \"@langchain/core/messages\";\nimport {\n ChatGeneration,\n ChatGenerationChunk,\n ChatResult,\n} from \"@langchain/core/outputs\";\nimport { isLangChainTool } from \"@langchain/core/utils/function_calling\";\nimport { isOpenAITool } from \"@langchain/core/language_models/base\";\nimport { ToolCallChunk } from \"@langchain/core/messages/tool\";\nimport { v4 as uuidv4 } from \"uuid\";\nimport {\n jsonSchemaToGeminiParameters,\n schemaToGenerativeAIParameters,\n} from \"./zod_to_genai_parameters.js\";\nimport { GoogleGenerativeAIToolType } from \"../types.js\";\n\nexport const _FUNCTION_CALL_THOUGHT_SIGNATURES_MAP_KEY =\n \"__gemini_function_call_thought_signatures__\";\nconst DUMMY_SIGNATURE =\n \"ErYCCrMCAdHtim9kOoOkrPiCNVsmlpMIKd7ZMxgiFbVQOkgp7nlLcDMzVsZwIzvuT7nQROivoXA72ccC2lSDvR0Gh7dkWaGuj7ctv6t7ZceHnecx0QYa+ix8tYpRfjhyWozQ49lWiws6+YGjCt10KRTyWsZ2h6O7iHTYJwKIRwGUHRKy/qK/6kFxJm5ML00gLq4D8s5Z6DBpp2ZlR+uF4G8jJgeWQgyHWVdx2wGYElaceVAc66tZdPQRdOHpWtgYSI1YdaXgVI8KHY3/EfNc2YqqMIulvkDBAnuMhkAjV9xmBa54Tq+ih3Im4+r3DzqhGqYdsSkhS0kZMwte4Hjs65dZzCw9lANxIqYi1DJ639WNPYihp/DCJCos7o+/EeSPJaio5sgWDyUnMGkY1atsJZ+m7pj7DD5tvQ==\";\n\nconst iife = (fn: () => string) => fn();\n\nexport function getMessageAuthor(message: BaseMessage) {\n const type = message._getType();\n if (ChatMessage.isInstance(message)) {\n return message.role;\n }\n if (type === \"tool\") {\n return type;\n }\n return message.name ?? type;\n}\n\n/**\n * Maps a message type to a Google Generative AI chat author.\n * @param message The message to map.\n * @param model The model to use for mapping.\n * @returns The message type mapped to a Google Generative AI chat author.\n */\nexport function convertAuthorToRole(\n author: string\n): (typeof POSSIBLE_ROLES)[number] {\n switch (author) {\n /**\n * Note: Gemini currently is not supporting system messages\n * we will convert them to human messages and merge with following\n * */\n case \"supervisor\":\n case \"ai\":\n case \"model\": // getMessageAuthor returns message.name. code ex.: return message.name ?? type;\n return \"model\";\n case \"system\":\n return \"system\";\n case \"human\":\n return \"user\";\n case \"tool\":\n case \"function\":\n return \"function\";\n default:\n throw new Error(`Unknown / unsupported author: ${author}`);\n }\n}\n\nfunction messageContentMedia(content: MessageContentComplex): Part {\n if (\"mimeType\" in content && \"data\" in content) {\n return {\n inlineData: {\n mimeType: content.mimeType,\n data: content.data,\n },\n };\n }\n if (\"mimeType\" in content && \"fileUri\" in content) {\n return {\n fileData: {\n mimeType: content.mimeType,\n fileUri: content.fileUri,\n },\n };\n }\n\n throw new Error(\"Invalid media content\");\n}\n\nfunction inferToolNameFromPreviousMessages(\n message: ToolMessage | ToolMessageChunk,\n previousMessages: BaseMessage[]\n): string | undefined {\n return previousMessages\n .map((msg) => {\n if (isAIMessage(msg)) {\n return msg.tool_calls ?? [];\n }\n return [];\n })\n .flat()\n .find((toolCall) => {\n return toolCall.id === message.tool_call_id;\n })?.name;\n}\n\nfunction _getStandardContentBlockConverter(isMultimodalModel: boolean) {\n const standardContentBlockConverter: StandardContentBlockConverter<{\n text: TextPart;\n image: FileDataPart | InlineDataPart;\n audio: FileDataPart | InlineDataPart;\n file: FileDataPart | InlineDataPart | TextPart;\n }> = {\n providerName: \"Google Gemini\",\n\n fromStandardTextBlock(block) {\n return {\n text: block.text,\n };\n },\n\n fromStandardImageBlock(block): FileDataPart | InlineDataPart {\n if (!isMultimodalModel) {\n throw new Error(\"This model does not support images\");\n }\n if (block.source_type === \"url\") {\n const data = parseBase64DataUrl({ dataUrl: block.url });\n if (data) {\n return {\n inlineData: {\n mimeType: data.mime_type,\n data: data.data,\n },\n };\n } else {\n return {\n fileData: {\n mimeType: block.mime_type ?? \"\",\n fileUri: block.url,\n },\n };\n }\n }\n\n if (block.source_type === \"base64\") {\n return {\n inlineData: {\n mimeType: block.mime_type ?? \"\",\n data: block.data,\n },\n };\n }\n\n throw new Error(`Unsupported source type: ${block.source_type}`);\n },\n\n fromStandardAudioBlock(block): FileDataPart | InlineDataPart {\n if (!isMultimodalModel) {\n throw new Error(\"This model does not support audio\");\n }\n if (block.source_type === \"url\") {\n const data = parseBase64DataUrl({ dataUrl: block.url });\n if (data) {\n return {\n inlineData: {\n mimeType: data.mime_type,\n data: data.data,\n },\n };\n } else {\n return {\n fileData: {\n mimeType: block.mime_type ?? \"\",\n fileUri: block.url,\n },\n };\n }\n }\n\n if (block.source_type === \"base64\") {\n return {\n inlineData: {\n mimeType: block.mime_type ?? \"\",\n data: block.data,\n },\n };\n }\n\n throw new Error(`Unsupported source type: ${block.source_type}`);\n },\n\n fromStandardFileBlock(block): FileDataPart | InlineDataPart | TextPart {\n if (!isMultimodalModel) {\n throw new Error(\"This model does not support files\");\n }\n if (block.source_type === \"text\") {\n return {\n text: block.text,\n };\n }\n if (block.source_type === \"url\") {\n const data = parseBase64DataUrl({ dataUrl: block.url });\n if (data) {\n return {\n inlineData: {\n mimeType: data.mime_type,\n data: data.data,\n },\n };\n } else {\n return {\n fileData: {\n mimeType: block.mime_type ?? \"\",\n fileUri: block.url,\n },\n };\n }\n }\n\n if (block.source_type === \"base64\") {\n return {\n inlineData: {\n mimeType: block.mime_type ?? \"\",\n data: block.data,\n },\n };\n }\n throw new Error(`Unsupported source type: ${block.source_type}`);\n },\n };\n return standardContentBlockConverter;\n}\n\nfunction _convertLangChainContentToPart(\n content: MessageContentComplex,\n isMultimodalModel: boolean\n): Part | undefined {\n if (isDataContentBlock(content)) {\n return convertToProviderContentBlock(\n content,\n _getStandardContentBlockConverter(isMultimodalModel)\n );\n }\n\n if (content.type === \"text\") {\n return { text: content.text };\n } else if (content.type === \"executableCode\") {\n return { executableCode: content.executableCode };\n } else if (content.type === \"codeExecutionResult\") {\n return { codeExecutionResult: content.codeExecutionResult };\n } else if (content.type === \"image_url\") {\n if (!isMultimodalModel) {\n throw new Error(`This model does not support images`);\n }\n let source;\n if (typeof content.image_url === \"string\") {\n source = content.image_url;\n } else if (\n typeof content.image_url === \"object\" &&\n \"url\" in content.image_url\n ) {\n source = content.image_url.url;\n } else {\n throw new Error(\"Please provide image as base64 encoded data URL\");\n }\n const [dm, data] = source.split(\",\");\n if (!dm.startsWith(\"data:\")) {\n throw new Error(\"Please provide image as base64 encoded data URL\");\n }\n\n const [mimeType, encoding] = dm.replace(/^data:/, \"\").split(\";\");\n if (encoding !== \"base64\") {\n throw new Error(\"Please provide image as base64 encoded data URL\");\n }\n\n return {\n inlineData: {\n data,\n mimeType,\n },\n };\n } else if (content.type === \"media\") {\n return messageContentMedia(content);\n } else if (content.type === \"tool_use\") {\n return {\n functionCall: {\n name: content.name,\n args: content.input,\n },\n };\n } else if (\n content.type?.includes(\"/\") &&\n // Ensure it's a single slash.\n content.type.split(\"/\").length === 2 &&\n \"data\" in content &&\n typeof content.data === \"string\"\n ) {\n return {\n inlineData: {\n mimeType: content.type,\n data: content.data,\n },\n };\n } else if (\"functionCall\" in content) {\n // No action needed here — function calls will be added later from message.tool_calls\n return undefined;\n } else {\n if (\"type\" in content) {\n throw new Error(`Unknown content type ${content.type}`);\n } else {\n throw new Error(`Unknown content ${JSON.stringify(content)}`);\n }\n }\n}\n\nexport function convertMessageContentToParts(\n message: BaseMessage,\n isMultimodalModel: boolean,\n previousMessages: BaseMessage[],\n model?: string\n): Part[] {\n if (isToolMessage(message)) {\n const messageName =\n message.name ??\n inferToolNameFromPreviousMessages(message, previousMessages);\n if (messageName === undefined) {\n throw new Error(\n `Google requires a tool name for each tool call response, and we could not infer a called tool name for ToolMessage \"${message.id}\" from your passed messages. Please populate a \"name\" field on that ToolMessage explicitly.`\n );\n }\n\n const result = Array.isArray(message.content)\n ? (message.content\n .map((c) => _convertLangChainContentToPart(c, isMultimodalModel))\n .filter((p) => p !== undefined) as Part[])\n : message.content;\n\n if (message.status === \"error\") {\n return [\n {\n functionResponse: {\n name: messageName,\n // The API expects an object with an `error` field if the function call fails.\n // `error` must be a valid object (not a string or array), so we wrap `message.content` here\n response: { error: { details: result } },\n },\n },\n ];\n }\n\n return [\n {\n functionResponse: {\n name: messageName,\n // again, can't have a string or array value for `response`, so we wrap it as an object here\n response: { result },\n },\n },\n ];\n }\n\n let functionCalls: FunctionCallPart[] = [];\n const messageParts: Part[] = [];\n\n if (typeof message.content === \"string\" && message.content) {\n messageParts.push({ text: message.content });\n }\n\n if (Array.isArray(message.content)) {\n messageParts.push(\n ...(message.content\n .map((c) => _convertLangChainContentToPart(c, isMultimodalModel))\n .filter((p) => p !== undefined) as Part[])\n );\n }\n\n const functionThoughtSignatures = message.additional_kwargs?.[\n _FUNCTION_CALL_THOUGHT_SIGNATURES_MAP_KEY\n ] as Record<string, string>;\n\n if (isAIMessage(message) && message.tool_calls?.length) {\n functionCalls = message.tool_calls.map((tc) => {\n const thoughtSignature = iife(() => {\n if (tc.id) {\n const signature = functionThoughtSignatures?.[tc.id];\n if (signature) {\n return signature;\n }\n }\n if (model?.includes(\"gemini-3\")) {\n return DUMMY_SIGNATURE;\n }\n return \"\";\n });\n return {\n functionCall: {\n name: tc.name,\n args: tc.args,\n },\n ...(thoughtSignature ? { thoughtSignature } : {}),\n };\n });\n }\n\n return [...messageParts, ...functionCalls];\n}\n\nexport function convertBaseMessagesToContent(\n messages: BaseMessage[],\n isMultimodalModel: boolean,\n convertSystemMessageToHumanContent: boolean = false,\n model: string\n) {\n return messages.reduce<{\n content: Content[];\n mergeWithPreviousContent: boolean;\n }>(\n (acc, message, index) => {\n if (!isBaseMessage(message)) {\n throw new Error(\"Unsupported message input\");\n }\n const author = getMessageAuthor(message);\n if (author === \"system\" && index !== 0) {\n throw new Error(\"System message should be the first one\");\n }\n const role = convertAuthorToRole(author);\n\n const prevContent = acc.content[acc.content.length];\n if (\n !acc.mergeWithPreviousContent &&\n prevContent &&\n prevContent.role === role\n ) {\n throw new Error(\n \"Google Generative AI requires alternate messages between authors\"\n );\n }\n\n const parts = convertMessageContentToParts(\n message,\n isMultimodalModel,\n messages.slice(0, index),\n model\n );\n\n if (acc.mergeWithPreviousContent) {\n const prevContent = acc.content[acc.content.length - 1];\n if (!prevContent) {\n throw new Error(\n \"There was a problem parsing your system message. Please try a prompt without one.\"\n );\n }\n prevContent.parts.push(...parts);\n\n return {\n mergeWithPreviousContent: false,\n content: acc.content,\n };\n }\n let actualRole = role;\n if (\n actualRole === \"function\" ||\n (actualRole === \"system\" && !convertSystemMessageToHumanContent)\n ) {\n // GenerativeAI API will throw an error if the role is not \"user\" or \"model.\"\n actualRole = \"user\";\n }\n const content: Content = {\n role: actualRole,\n parts,\n };\n return {\n mergeWithPreviousContent:\n author === \"system\" && !convertSystemMessageToHumanContent,\n content: [...acc.content, content],\n };\n },\n { content: [], mergeWithPreviousContent: false }\n ).content;\n}\n\nexport function mapGenerateContentResultToChatResult(\n response: EnhancedGenerateContentResponse,\n extra?: {\n usageMetadata: UsageMetadata | undefined;\n }\n): ChatResult {\n // if rejected or error, return empty generations with reason in filters\n if (\n !response.candidates ||\n response.candidates.length === 0 ||\n !response.candidates[0]\n ) {\n return {\n generations: [],\n llmOutput: {\n filters: response.promptFeedback,\n },\n };\n }\n const [candidate] = response.candidates;\n const { content: candidateContent, ...generationInfo } = candidate;\n const functionCalls = candidateContent.parts.reduce((acc, p) => {\n if (\"functionCall\" in p && p.functionCall) {\n acc.push({\n ...p,\n id:\n \"id\" in p.functionCall && typeof p.functionCall.id === \"string\"\n ? p.functionCall.id\n : uuidv4(),\n });\n }\n return acc;\n }, [] as (FunctionCallPart & { id: string })[]);\n let content: MessageContent | undefined;\n\n if (\n Array.isArray(candidateContent?.parts) &&\n candidateContent.parts.length === 1 &&\n candidateContent.parts[0].text\n ) {\n content = candidateContent.parts[0].text;\n } else if (\n Array.isArray(candidateContent?.parts) &&\n candidateContent.parts.length > 0\n ) {\n content = candidateContent.parts.map((p) => {\n if (\"text\" in p) {\n return {\n type: \"text\",\n text: p.text,\n };\n } else if (\"inlineData\" in p) {\n return {\n type: \"inlineData\",\n inlineData: p.inlineData,\n };\n } else if (\"functionCall\" in p) {\n return {\n type: \"functionCall\",\n functionCall: p.functionCall,\n };\n } else if (\"functionResponse\" in p) {\n return {\n type: \"functionResponse\",\n functionResponse: p.functionResponse,\n };\n } else if (\"fileData\" in p) {\n return {\n type: \"fileData\",\n fileData: p.fileData,\n };\n } else if (\"executableCode\" in p) {\n return {\n type: \"executableCode\",\n executableCode: p.executableCode,\n };\n } else if (\"codeExecutionResult\" in p) {\n return {\n type: \"codeExecutionResult\",\n codeExecutionResult: p.codeExecutionResult,\n };\n }\n return p;\n });\n } else {\n // no content returned - likely due to abnormal stop reason, e.g. malformed function call\n content = [];\n }\n\n const functionThoughtSignatures = functionCalls?.reduce((acc, fc) => {\n if (\"thoughtSignature\" in fc && typeof fc.thoughtSignature === \"string\") {\n acc[fc.id] = fc.thoughtSignature;\n }\n return acc;\n }, {} as Record<string, string>);\n\n let text = \"\";\n if (typeof content === \"string\") {\n text = content;\n } else if (Array.isArray(content) && content.length > 0) {\n const block = content.find((b) => \"text\" in b) as\n | { text: string }\n | undefined;\n text = block?.text ?? text;\n }\n\n const generation: ChatGeneration = {\n text,\n message: new AIMessage({\n content: content ?? \"\",\n tool_calls: functionCalls?.map((fc) => ({\n type: \"tool_call\",\n id: fc.id,\n name: fc.functionCall.name,\n args: fc.functionCall.args,\n })),\n additional_kwargs: {\n ...generationInfo,\n [_FUNCTION_CALL_THOUGHT_SIGNATURES_MAP_KEY]: functionThoughtSignatures,\n },\n usage_metadata: extra?.usageMetadata,\n }),\n generationInfo,\n };\n\n return {\n generations: [generation],\n llmOutput: {\n tokenUsage: {\n promptTokens: extra?.usageMetadata?.input_tokens,\n completionTokens: extra?.usageMetadata?.output_tokens,\n totalTokens: extra?.usageMetadata?.total_tokens,\n },\n },\n };\n}\n\nexport function convertResponseContentToChatGenerationChunk(\n response: EnhancedGenerateContentResponse,\n extra: {\n usageMetadata?: UsageMetadata | undefined;\n index: number;\n }\n): ChatGenerationChunk | null {\n if (!response.candidates || response.candidates.length === 0) {\n return null;\n }\n const [candidate] = response.candidates;\n const { content: candidateContent, ...generationInfo } = candidate;\n const functionCalls = candidateContent.parts.reduce((acc, p) => {\n if (\"functionCall\" in p && p.functionCall) {\n acc.push({\n ...p,\n id:\n \"id\" in p.functionCall && typeof p.functionCall.id === \"string\"\n ? p.functionCall.id\n : uuidv4(),\n });\n }\n return acc;\n }, [] as (FunctionCallPart & { id: string })[]);\n let content: MessageContent | undefined;\n // Checks if some parts do not have text. If false, it means that the content is a string.\n if (\n Array.isArray(candidateContent?.parts) &&\n candidateContent.parts.every((p) => \"text\" in p)\n ) {\n content = candidateContent.parts.map((p) => p.text).join(\"\");\n } else if (Array.isArray(candidateContent?.parts)) {\n content = candidateContent.parts.map((p) => {\n if (\"text\" in p) {\n return {\n type: \"text\",\n text: p.text,\n };\n } else if (\"inlineData\" in p) {\n return {\n type: \"inlineData\",\n inlineData: p.inlineData,\n };\n } else if (\"functionCall\" in p) {\n return {\n type: \"functionCall\",\n functionCall: p.functionCall,\n };\n } else if (\"functionResponse\" in p) {\n return {\n type: \"functionResponse\",\n functionResponse: p.functionResponse,\n };\n } else if (\"fileData\" in p) {\n return {\n type: \"fileData\",\n fileData: p.fileData,\n };\n } else if (\"executableCode\" in p) {\n return {\n type: \"executableCode\",\n executableCode: p.executableCode,\n };\n } else if (\"codeExecutionResult\" in p) {\n return {\n type: \"codeExecutionResult\",\n codeExecutionResult: p.codeExecutionResult,\n };\n }\n return p;\n });\n } else {\n // no content returned - likely due to abnormal stop reason, e.g. malformed function call\n content = [];\n }\n\n let text = \"\";\n if (content && typeof content === \"string\") {\n text = content;\n } else if (Array.isArray(content)) {\n const block = content.find((b) => \"text\" in b) as\n | { text: string }\n | undefined;\n text = block?.text ?? \"\";\n }\n\n const toolCallChunks: ToolCallChunk[] = [];\n if (functionCalls) {\n toolCallChunks.push(\n ...functionCalls.map((fc) => ({\n type: \"tool_call_chunk\" as const,\n id: fc.id,\n name: fc.functionCall.name,\n args: JSON.stringify(fc.functionCall.args),\n }))\n );\n }\n\n const functionThoughtSignatures = functionCalls?.reduce((acc, fc) => {\n if (\"thoughtSignature\" in fc && typeof fc.thoughtSignature === \"string\") {\n acc[fc.id] = fc.thoughtSignature;\n }\n return acc;\n }, {} as Record<string, string>);\n\n return new ChatGenerationChunk({\n text,\n message: new AIMessageChunk({\n content: content || \"\",\n name: !candidateContent ? undefined : candidateContent.role,\n tool_call_chunks: toolCallChunks,\n // Each chunk can have unique \"generationInfo\", and merging strategy is unclear,\n // so leave blank for now.\n additional_kwargs: {\n [_FUNCTION_CALL_THOUGHT_SIGNATURES_MAP_KEY]: functionThoughtSignatures,\n },\n response_metadata: {\n model_provider: \"google-genai\",\n },\n usage_metadata: extra.usageMetadata,\n }),\n generationInfo,\n });\n}\n\nexport function convertToGenerativeAITools(\n tools: GoogleGenerativeAIToolType[]\n): GoogleGenerativeAIFunctionDeclarationsTool[] {\n if (\n tools.every(\n (tool) =>\n \"functionDeclarations\" in tool &&\n Array.isArray(tool.functionDeclarations)\n )\n ) {\n return tools as GoogleGenerativeAIFunctionDeclarationsTool[];\n }\n return [\n {\n functionDeclarations: tools.map(\n (tool): GenerativeAIFunctionDeclaration => {\n if (isLangChainTool(tool)) {\n const jsonSchema = schemaToGenerativeAIParameters(tool.schema);\n if (\n jsonSchema.type === \"object\" &&\n \"properties\" in jsonSchema &&\n Object.keys(jsonSchema.properties).length === 0\n ) {\n return {\n name: tool.name,\n description: tool.description,\n };\n }\n return {\n name: tool.name,\n description: tool.description,\n parameters: jsonSchema,\n };\n }\n if (isOpenAITool(tool)) {\n return {\n name: tool.function.name,\n description:\n tool.function.description ?? `A function available to call.`,\n parameters: jsonSchemaToGeminiParameters(\n tool.function.parameters\n ),\n };\n }\n return tool as unknown as GenerativeAIFunctionDeclaration;\n }\n ),\n },\n ];\n}\n\nexport function convertUsageMetadata(\n usageMetadata: GenerateContentResponse[\"usageMetadata\"],\n model: string\n): UsageMetadata {\n const output: UsageMetadata = {\n input_tokens: usageMetadata?.promptTokenCount ?? 0,\n output_tokens: usageMetadata?.candidatesTokenCount ?? 0,\n total_tokens: usageMetadata?.totalTokenCount ?? 0,\n };\n if (usageMetadata?.cachedContentTokenCount) {\n output.input_token_details ??= {};\n output.input_token_details.cache_read =\n usageMetadata.cachedContentTokenCount;\n }\n // gemini-3-pro-preview has bracket based tracking of tokens per request\n // FIXME(hntrl): move this usageMetadata calculation elsewhere\n if (model === \"gemini-3-pro-preview\") {\n const over200k = Math.max(0, usageMetadata?.promptTokenCount ?? 0 - 200000);\n const cachedOver200k = Math.max(\n 0,\n usageMetadata?.cachedContentTokenCount ?? 0 - 200000\n );\n if (over200k) {\n output.input_token_details = {\n ...output.input_token_details,\n over_200k: over200k,\n } as InputTokenDetails;\n }\n if (cachedOver200k) {\n output.input_token_details = {\n ...output.input_token_details,\n cache_read_over_200k: cachedOver200k,\n } as InputTokenDetails;\n }\n }\n return output;\n}\n"],"mappings":";;;;;;;;AA+CA,MAAa,4CACX;AACF,MAAM,kBACJ;AAEF,MAAM,OAAO,CAACA,OAAqB,IAAI;AAEvC,SAAgB,iBAAiBC,SAAsB;CACrD,MAAM,OAAO,QAAQ,UAAU;AAC/B,KAAI,YAAY,WAAW,QAAQ,CACjC,QAAO,QAAQ;AAEjB,KAAI,SAAS,OACX,QAAO;AAET,QAAO,QAAQ,QAAQ;AACxB;;;;;;;AAQD,SAAgB,oBACdC,QACiC;AACjC,SAAQ,QAAR;EAKE,KAAK;EACL,KAAK;EACL,KAAK,QACH,QAAO;EACT,KAAK,SACH,QAAO;EACT,KAAK,QACH,QAAO;EACT,KAAK;EACL,KAAK,WACH,QAAO;EACT,QACE,OAAM,IAAI,MAAM,CAAC,8BAA8B,EAAE,QAAQ;CAC5D;AACF;AAED,SAAS,oBAAoBC,SAAsC;AACjE,KAAI,cAAc,WAAW,UAAU,QACrC,QAAO,EACL,YAAY;EACV,UAAU,QAAQ;EAClB,MAAM,QAAQ;CACf,EACF;AAEH,KAAI,cAAc,WAAW,aAAa,QACxC,QAAO,EACL,UAAU;EACR,UAAU,QAAQ;EAClB,SAAS,QAAQ;CAClB,EACF;AAGH,OAAM,IAAI,MAAM;AACjB;AAED,SAAS,kCACPC,SACAC,kBACoB;AACpB,QAAO,iBACJ,IAAI,CAAC,QAAQ;AACZ,MAAI,YAAY,IAAI,CAClB,QAAO,IAAI,cAAc,CAAE;AAE7B,SAAO,CAAE;CACV,EAAC,CACD,MAAM,CACN,KAAK,CAAC,aAAa;AAClB,SAAO,SAAS,OAAO,QAAQ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,CAAC;GAC9D,YAAY,6BACV,KAAK,SAAS,WACf;EACF;AAEH,SAAO;CACR,EACF,CACF,CACF;AACF;AAED,SAAgB,qBACdC,eACAX,OACe;CACf,MAAMY,SAAwB;EAC5B,cAAc,eAAe,oBAAoB;EACjD,eAAe,eAAe,wBAAwB;EACtD,cAAc,eAAe,mBAAmB;CACjD;AACD,KAAI,eAAe,yBAAyB;EAC1C,OAAO,wBAAwB,CAAE;EACjC,OAAO,oBAAoB,aACzB,cAAc;CACjB;AAGD,KAAI,UAAU,wBAAwB;EACpC,MAAM,WAAW,KAAK,IAAI,GAAG,eAAe,oBAAoB,KAAW;EAC3E,MAAM,iBAAiB,KAAK,IAC1B,GACA,eAAe,2BAA2B,KAC3C;AACD,MAAI,UACF,OAAO,sBAAsB;GAC3B,GAAG,OAAO;GACV,WAAW;EACZ;AAEH,MAAI,gBACF,OAAO,sBAAsB;GAC3B,GAAG,OAAO;GACV,sBAAsB;EACvB;CAEJ;AACD,QAAO;AACR"}
|
|
1
|
+
{"version":3,"file":"common.js","names":["fn: () => string","message: BaseMessage","author: string","content: MessageContentComplex","message: ToolMessage | ToolMessageChunk","previousMessages: BaseMessage[]","isMultimodalModel: boolean","standardContentBlockConverter: StandardContentBlockConverter<{\n text: TextPart;\n image: FileDataPart | InlineDataPart;\n audio: FileDataPart | InlineDataPart;\n file: FileDataPart | InlineDataPart | TextPart;\n }>","model?: string","functionCalls: FunctionCallPart[]","messageParts: Part[]","messages: BaseMessage[]","convertSystemMessageToHumanContent: boolean","model: string","prevContent","content: Content","response: EnhancedGenerateContentResponse","extra?: {\n usageMetadata: UsageMetadata | undefined;\n }","uuidv4","content: MessageContent | undefined","generation: ChatGeneration","extra: {\n usageMetadata?: UsageMetadata | undefined;\n index: number;\n }","toolCallChunks: ToolCallChunk[]","tools: GoogleGenerativeAIToolType[]","usageMetadata: GenerateContentResponse[\"usageMetadata\"]","output: UsageMetadata"],"sources":["../../src/utils/common.ts"],"sourcesContent":["import {\n EnhancedGenerateContentResponse,\n Content,\n Part,\n type FunctionDeclarationsTool as GoogleGenerativeAIFunctionDeclarationsTool,\n type FunctionDeclaration as GenerativeAIFunctionDeclaration,\n POSSIBLE_ROLES,\n FunctionCallPart,\n TextPart,\n FileDataPart,\n InlineDataPart,\n type GenerateContentResponse,\n} from \"@google/generative-ai\";\nimport {\n AIMessage,\n AIMessageChunk,\n BaseMessage,\n ChatMessage,\n ToolMessage,\n ToolMessageChunk,\n MessageContent,\n MessageContentComplex,\n UsageMetadata,\n isAIMessage,\n isBaseMessage,\n isToolMessage,\n StandardContentBlockConverter,\n parseBase64DataUrl,\n convertToProviderContentBlock,\n isDataContentBlock,\n InputTokenDetails,\n} from \"@langchain/core/messages\";\nimport {\n ChatGeneration,\n ChatGenerationChunk,\n ChatResult,\n} from \"@langchain/core/outputs\";\nimport { isLangChainTool } from \"@langchain/core/utils/function_calling\";\nimport { isOpenAITool } from \"@langchain/core/language_models/base\";\nimport { ToolCallChunk } from \"@langchain/core/messages/tool\";\nimport { v4 as uuidv4 } from \"uuid\";\nimport {\n jsonSchemaToGeminiParameters,\n schemaToGenerativeAIParameters,\n} from \"./zod_to_genai_parameters.js\";\nimport { GoogleGenerativeAIToolType } from \"../types.js\";\n\nexport const _FUNCTION_CALL_THOUGHT_SIGNATURES_MAP_KEY =\n \"__gemini_function_call_thought_signatures__\";\nconst DUMMY_SIGNATURE =\n \"ErYCCrMCAdHtim9kOoOkrPiCNVsmlpMIKd7ZMxgiFbVQOkgp7nlLcDMzVsZwIzvuT7nQROivoXA72ccC2lSDvR0Gh7dkWaGuj7ctv6t7ZceHnecx0QYa+ix8tYpRfjhyWozQ49lWiws6+YGjCt10KRTyWsZ2h6O7iHTYJwKIRwGUHRKy/qK/6kFxJm5ML00gLq4D8s5Z6DBpp2ZlR+uF4G8jJgeWQgyHWVdx2wGYElaceVAc66tZdPQRdOHpWtgYSI1YdaXgVI8KHY3/EfNc2YqqMIulvkDBAnuMhkAjV9xmBa54Tq+ih3Im4+r3DzqhGqYdsSkhS0kZMwte4Hjs65dZzCw9lANxIqYi1DJ639WNPYihp/DCJCos7o+/EeSPJaio5sgWDyUnMGkY1atsJZ+m7pj7DD5tvQ==\";\n\nconst iife = (fn: () => string) => fn();\n\nexport function getMessageAuthor(message: BaseMessage) {\n if (ChatMessage.isInstance(message)) {\n return message.role;\n }\n return message.type;\n}\n\n/**\n * Maps a message type to a Google Generative AI chat author.\n * @param message The message to map.\n * @param model The model to use for mapping.\n * @returns The message type mapped to a Google Generative AI chat author.\n */\nexport function convertAuthorToRole(\n author: string\n): (typeof POSSIBLE_ROLES)[number] {\n switch (author) {\n /**\n * Note: Gemini currently is not supporting system messages\n * we will convert them to human messages and merge with following\n * */\n case \"supervisor\":\n case \"ai\":\n case \"model\":\n return \"model\";\n case \"system\":\n return \"system\";\n case \"human\":\n return \"user\";\n case \"tool\":\n case \"function\":\n return \"function\";\n default:\n throw new Error(`Unknown / unsupported author: ${author}`);\n }\n}\n\nfunction messageContentMedia(content: MessageContentComplex): Part {\n if (\"mimeType\" in content && \"data\" in content) {\n return {\n inlineData: {\n mimeType: content.mimeType,\n data: content.data,\n },\n };\n }\n if (\"mimeType\" in content && \"fileUri\" in content) {\n return {\n fileData: {\n mimeType: content.mimeType,\n fileUri: content.fileUri,\n },\n };\n }\n\n throw new Error(\"Invalid media content\");\n}\n\nfunction inferToolNameFromPreviousMessages(\n message: ToolMessage | ToolMessageChunk,\n previousMessages: BaseMessage[]\n): string | undefined {\n return previousMessages\n .map((msg) => {\n if (isAIMessage(msg)) {\n return msg.tool_calls ?? [];\n }\n return [];\n })\n .flat()\n .find((toolCall) => {\n return toolCall.id === message.tool_call_id;\n })?.name;\n}\n\nfunction _getStandardContentBlockConverter(isMultimodalModel: boolean) {\n const standardContentBlockConverter: StandardContentBlockConverter<{\n text: TextPart;\n image: FileDataPart | InlineDataPart;\n audio: FileDataPart | InlineDataPart;\n file: FileDataPart | InlineDataPart | TextPart;\n }> = {\n providerName: \"Google Gemini\",\n\n fromStandardTextBlock(block) {\n return {\n text: block.text,\n };\n },\n\n fromStandardImageBlock(block): FileDataPart | InlineDataPart {\n if (!isMultimodalModel) {\n throw new Error(\"This model does not support images\");\n }\n if (block.source_type === \"url\") {\n const data = parseBase64DataUrl({ dataUrl: block.url });\n if (data) {\n return {\n inlineData: {\n mimeType: data.mime_type,\n data: data.data,\n },\n };\n } else {\n return {\n fileData: {\n mimeType: block.mime_type ?? \"\",\n fileUri: block.url,\n },\n };\n }\n }\n\n if (block.source_type === \"base64\") {\n return {\n inlineData: {\n mimeType: block.mime_type ?? \"\",\n data: block.data,\n },\n };\n }\n\n throw new Error(`Unsupported source type: ${block.source_type}`);\n },\n\n fromStandardAudioBlock(block): FileDataPart | InlineDataPart {\n if (!isMultimodalModel) {\n throw new Error(\"This model does not support audio\");\n }\n if (block.source_type === \"url\") {\n const data = parseBase64DataUrl({ dataUrl: block.url });\n if (data) {\n return {\n inlineData: {\n mimeType: data.mime_type,\n data: data.data,\n },\n };\n } else {\n return {\n fileData: {\n mimeType: block.mime_type ?? \"\",\n fileUri: block.url,\n },\n };\n }\n }\n\n if (block.source_type === \"base64\") {\n return {\n inlineData: {\n mimeType: block.mime_type ?? \"\",\n data: block.data,\n },\n };\n }\n\n throw new Error(`Unsupported source type: ${block.source_type}`);\n },\n\n fromStandardFileBlock(block): FileDataPart | InlineDataPart | TextPart {\n if (!isMultimodalModel) {\n throw new Error(\"This model does not support files\");\n }\n if (block.source_type === \"text\") {\n return {\n text: block.text,\n };\n }\n if (block.source_type === \"url\") {\n const data = parseBase64DataUrl({ dataUrl: block.url });\n if (data) {\n return {\n inlineData: {\n mimeType: data.mime_type,\n data: data.data,\n },\n };\n } else {\n return {\n fileData: {\n mimeType: block.mime_type ?? \"\",\n fileUri: block.url,\n },\n };\n }\n }\n\n if (block.source_type === \"base64\") {\n return {\n inlineData: {\n mimeType: block.mime_type ?? \"\",\n data: block.data,\n },\n };\n }\n throw new Error(`Unsupported source type: ${block.source_type}`);\n },\n };\n return standardContentBlockConverter;\n}\n\nfunction _convertLangChainContentToPart(\n content: MessageContentComplex,\n isMultimodalModel: boolean\n): Part | undefined {\n if (isDataContentBlock(content)) {\n return convertToProviderContentBlock(\n content,\n _getStandardContentBlockConverter(isMultimodalModel)\n );\n }\n\n if (content.type === \"text\") {\n return { text: content.text };\n } else if (content.type === \"executableCode\") {\n return { executableCode: content.executableCode };\n } else if (content.type === \"codeExecutionResult\") {\n return { codeExecutionResult: content.codeExecutionResult };\n } else if (content.type === \"image_url\") {\n if (!isMultimodalModel) {\n throw new Error(`This model does not support images`);\n }\n let source;\n if (typeof content.image_url === \"string\") {\n source = content.image_url;\n } else if (\n typeof content.image_url === \"object\" &&\n \"url\" in content.image_url\n ) {\n source = content.image_url.url;\n } else {\n throw new Error(\"Please provide image as base64 encoded data URL\");\n }\n const [dm, data] = source.split(\",\");\n if (!dm.startsWith(\"data:\")) {\n throw new Error(\"Please provide image as base64 encoded data URL\");\n }\n\n const [mimeType, encoding] = dm.replace(/^data:/, \"\").split(\";\");\n if (encoding !== \"base64\") {\n throw new Error(\"Please provide image as base64 encoded data URL\");\n }\n\n return {\n inlineData: {\n data,\n mimeType,\n },\n };\n } else if (content.type === \"media\") {\n return messageContentMedia(content);\n } else if (content.type === \"tool_use\") {\n return {\n functionCall: {\n name: content.name,\n args: content.input,\n },\n };\n } else if (\n content.type?.includes(\"/\") &&\n // Ensure it's a single slash.\n content.type.split(\"/\").length === 2 &&\n \"data\" in content &&\n typeof content.data === \"string\"\n ) {\n return {\n inlineData: {\n mimeType: content.type,\n data: content.data,\n },\n };\n } else if (\"functionCall\" in content) {\n // No action needed here — function calls will be added later from message.tool_calls\n return undefined;\n } else {\n if (\"type\" in content) {\n throw new Error(`Unknown content type ${content.type}`);\n } else {\n throw new Error(`Unknown content ${JSON.stringify(content)}`);\n }\n }\n}\n\nexport function convertMessageContentToParts(\n message: BaseMessage,\n isMultimodalModel: boolean,\n previousMessages: BaseMessage[],\n model?: string\n): Part[] {\n if (isToolMessage(message)) {\n const messageName =\n message.name ??\n inferToolNameFromPreviousMessages(message, previousMessages);\n if (messageName === undefined) {\n throw new Error(\n `Google requires a tool name for each tool call response, and we could not infer a called tool name for ToolMessage \"${message.id}\" from your passed messages. Please populate a \"name\" field on that ToolMessage explicitly.`\n );\n }\n\n const result = Array.isArray(message.content)\n ? (message.content\n .map((c) => _convertLangChainContentToPart(c, isMultimodalModel))\n .filter((p) => p !== undefined) as Part[])\n : message.content;\n\n if (message.status === \"error\") {\n return [\n {\n functionResponse: {\n name: messageName,\n // The API expects an object with an `error` field if the function call fails.\n // `error` must be a valid object (not a string or array), so we wrap `message.content` here\n response: { error: { details: result } },\n },\n },\n ];\n }\n\n return [\n {\n functionResponse: {\n name: messageName,\n // again, can't have a string or array value for `response`, so we wrap it as an object here\n response: { result },\n },\n },\n ];\n }\n\n let functionCalls: FunctionCallPart[] = [];\n const messageParts: Part[] = [];\n\n if (typeof message.content === \"string\" && message.content) {\n messageParts.push({ text: message.content });\n }\n\n if (Array.isArray(message.content)) {\n messageParts.push(\n ...(message.content\n .map((c) => _convertLangChainContentToPart(c, isMultimodalModel))\n .filter((p) => p !== undefined) as Part[])\n );\n }\n\n const functionThoughtSignatures = message.additional_kwargs?.[\n _FUNCTION_CALL_THOUGHT_SIGNATURES_MAP_KEY\n ] as Record<string, string>;\n\n if (isAIMessage(message) && message.tool_calls?.length) {\n functionCalls = message.tool_calls.map((tc) => {\n const thoughtSignature = iife(() => {\n if (tc.id) {\n const signature = functionThoughtSignatures?.[tc.id];\n if (signature) {\n return signature;\n }\n }\n if (model?.includes(\"gemini-3\")) {\n return DUMMY_SIGNATURE;\n }\n return \"\";\n });\n return {\n functionCall: {\n name: tc.name,\n args: tc.args,\n },\n ...(thoughtSignature ? { thoughtSignature } : {}),\n };\n });\n }\n\n return [...messageParts, ...functionCalls];\n}\n\nexport function convertBaseMessagesToContent(\n messages: BaseMessage[],\n isMultimodalModel: boolean,\n convertSystemMessageToHumanContent: boolean = false,\n model: string\n) {\n return messages.reduce<{\n content: Content[];\n mergeWithPreviousContent: boolean;\n }>(\n (acc, message, index) => {\n if (!isBaseMessage(message)) {\n throw new Error(\"Unsupported message input\");\n }\n const author = getMessageAuthor(message);\n if (author === \"system\" && index !== 0) {\n throw new Error(\"System message should be the first one\");\n }\n const role = convertAuthorToRole(author);\n\n const prevContent = acc.content[acc.content.length];\n if (\n !acc.mergeWithPreviousContent &&\n prevContent &&\n prevContent.role === role\n ) {\n throw new Error(\n \"Google Generative AI requires alternate messages between authors\"\n );\n }\n\n const parts = convertMessageContentToParts(\n message,\n isMultimodalModel,\n messages.slice(0, index),\n model\n );\n\n if (acc.mergeWithPreviousContent) {\n const prevContent = acc.content[acc.content.length - 1];\n if (!prevContent) {\n throw new Error(\n \"There was a problem parsing your system message. Please try a prompt without one.\"\n );\n }\n prevContent.parts.push(...parts);\n\n return {\n mergeWithPreviousContent: false,\n content: acc.content,\n };\n }\n let actualRole = role;\n if (\n actualRole === \"function\" ||\n (actualRole === \"system\" && !convertSystemMessageToHumanContent)\n ) {\n // GenerativeAI API will throw an error if the role is not \"user\" or \"model.\"\n actualRole = \"user\";\n }\n const content: Content = {\n role: actualRole,\n parts,\n };\n return {\n mergeWithPreviousContent:\n author === \"system\" && !convertSystemMessageToHumanContent,\n content: [...acc.content, content],\n };\n },\n { content: [], mergeWithPreviousContent: false }\n ).content;\n}\n\nexport function mapGenerateContentResultToChatResult(\n response: EnhancedGenerateContentResponse,\n extra?: {\n usageMetadata: UsageMetadata | undefined;\n }\n): ChatResult {\n // if rejected or error, return empty generations with reason in filters\n if (\n !response.candidates ||\n response.candidates.length === 0 ||\n !response.candidates[0]\n ) {\n return {\n generations: [],\n llmOutput: {\n filters: response.promptFeedback,\n },\n };\n }\n const [candidate] = response.candidates;\n const { content: candidateContent, ...generationInfo } = candidate;\n const functionCalls = candidateContent.parts?.reduce((acc, p) => {\n if (\"functionCall\" in p && p.functionCall) {\n acc.push({\n ...p,\n id:\n \"id\" in p.functionCall && typeof p.functionCall.id === \"string\"\n ? p.functionCall.id\n : uuidv4(),\n });\n }\n return acc;\n }, [] as (FunctionCallPart & { id: string })[]);\n let content: MessageContent | undefined;\n\n if (\n Array.isArray(candidateContent?.parts) &&\n candidateContent.parts.length === 1 &&\n candidateContent.parts[0].text\n ) {\n content = candidateContent.parts[0].text;\n } else if (\n Array.isArray(candidateContent?.parts) &&\n candidateContent.parts.length > 0\n ) {\n content = candidateContent.parts.map((p) => {\n if (\"text\" in p) {\n return {\n type: \"text\",\n text: p.text,\n };\n } else if (\"inlineData\" in p) {\n return {\n type: \"inlineData\",\n inlineData: p.inlineData,\n };\n } else if (\"functionCall\" in p) {\n return {\n type: \"functionCall\",\n functionCall: p.functionCall,\n };\n } else if (\"functionResponse\" in p) {\n return {\n type: \"functionResponse\",\n functionResponse: p.functionResponse,\n };\n } else if (\"fileData\" in p) {\n return {\n type: \"fileData\",\n fileData: p.fileData,\n };\n } else if (\"executableCode\" in p) {\n return {\n type: \"executableCode\",\n executableCode: p.executableCode,\n };\n } else if (\"codeExecutionResult\" in p) {\n return {\n type: \"codeExecutionResult\",\n codeExecutionResult: p.codeExecutionResult,\n };\n }\n return p;\n });\n } else {\n // no content returned - likely due to abnormal stop reason, e.g. malformed function call\n content = [];\n }\n\n const functionThoughtSignatures = functionCalls?.reduce((acc, fc) => {\n if (\"thoughtSignature\" in fc && typeof fc.thoughtSignature === \"string\") {\n acc[fc.id] = fc.thoughtSignature;\n }\n return acc;\n }, {} as Record<string, string>);\n\n let text = \"\";\n if (typeof content === \"string\") {\n text = content;\n } else if (Array.isArray(content) && content.length > 0) {\n const block = content.find((b) => \"text\" in b) as\n | { text: string }\n | undefined;\n text = block?.text ?? text;\n }\n\n const generation: ChatGeneration = {\n text,\n message: new AIMessage({\n content: content ?? \"\",\n tool_calls: functionCalls?.map((fc) => ({\n type: \"tool_call\",\n id: fc.id,\n name: fc.functionCall.name,\n args: fc.functionCall.args,\n })),\n additional_kwargs: {\n ...generationInfo,\n [_FUNCTION_CALL_THOUGHT_SIGNATURES_MAP_KEY]: functionThoughtSignatures,\n },\n usage_metadata: extra?.usageMetadata,\n }),\n generationInfo,\n };\n\n return {\n generations: [generation],\n llmOutput: {\n tokenUsage: {\n promptTokens: extra?.usageMetadata?.input_tokens,\n completionTokens: extra?.usageMetadata?.output_tokens,\n totalTokens: extra?.usageMetadata?.total_tokens,\n },\n },\n };\n}\n\nexport function convertResponseContentToChatGenerationChunk(\n response: EnhancedGenerateContentResponse,\n extra: {\n usageMetadata?: UsageMetadata | undefined;\n index: number;\n }\n): ChatGenerationChunk | null {\n if (!response.candidates || response.candidates.length === 0) {\n return null;\n }\n const [candidate] = response.candidates;\n const { content: candidateContent, ...generationInfo } = candidate;\n const functionCalls = candidateContent.parts?.reduce((acc, p) => {\n if (\"functionCall\" in p && p.functionCall) {\n acc.push({\n ...p,\n id:\n \"id\" in p.functionCall && typeof p.functionCall.id === \"string\"\n ? p.functionCall.id\n : uuidv4(),\n });\n }\n return acc;\n }, [] as (FunctionCallPart & { id: string })[]);\n let content: MessageContent | undefined;\n // Checks if some parts do not have text. If false, it means that the content is a string.\n if (\n Array.isArray(candidateContent?.parts) &&\n candidateContent.parts.every((p) => \"text\" in p)\n ) {\n content = candidateContent.parts.map((p) => p.text).join(\"\");\n } else if (Array.isArray(candidateContent?.parts)) {\n content = candidateContent.parts.map((p) => {\n if (\"text\" in p) {\n return {\n type: \"text\",\n text: p.text,\n };\n } else if (\"inlineData\" in p) {\n return {\n type: \"inlineData\",\n inlineData: p.inlineData,\n };\n } else if (\"functionCall\" in p) {\n return {\n type: \"functionCall\",\n functionCall: p.functionCall,\n };\n } else if (\"functionResponse\" in p) {\n return {\n type: \"functionResponse\",\n functionResponse: p.functionResponse,\n };\n } else if (\"fileData\" in p) {\n return {\n type: \"fileData\",\n fileData: p.fileData,\n };\n } else if (\"executableCode\" in p) {\n return {\n type: \"executableCode\",\n executableCode: p.executableCode,\n };\n } else if (\"codeExecutionResult\" in p) {\n return {\n type: \"codeExecutionResult\",\n codeExecutionResult: p.codeExecutionResult,\n };\n }\n return p;\n });\n } else {\n // no content returned - likely due to abnormal stop reason, e.g. malformed function call\n content = [];\n }\n\n let text = \"\";\n if (content && typeof content === \"string\") {\n text = content;\n } else if (Array.isArray(content)) {\n const block = content.find((b) => \"text\" in b) as\n | { text: string }\n | undefined;\n text = block?.text ?? \"\";\n }\n\n const toolCallChunks: ToolCallChunk[] = [];\n if (functionCalls) {\n toolCallChunks.push(\n ...functionCalls.map((fc) => ({\n type: \"tool_call_chunk\" as const,\n id: fc.id,\n name: fc.functionCall.name,\n args: JSON.stringify(fc.functionCall.args),\n }))\n );\n }\n\n const functionThoughtSignatures = functionCalls?.reduce((acc, fc) => {\n if (\"thoughtSignature\" in fc && typeof fc.thoughtSignature === \"string\") {\n acc[fc.id] = fc.thoughtSignature;\n }\n return acc;\n }, {} as Record<string, string>);\n\n return new ChatGenerationChunk({\n text,\n message: new AIMessageChunk({\n content: content || \"\",\n name: !candidateContent ? undefined : candidateContent.role,\n tool_call_chunks: toolCallChunks,\n // Each chunk can have unique \"generationInfo\", and merging strategy is unclear,\n // so leave blank for now.\n additional_kwargs: {\n [_FUNCTION_CALL_THOUGHT_SIGNATURES_MAP_KEY]: functionThoughtSignatures,\n },\n response_metadata: {\n model_provider: \"google-genai\",\n },\n usage_metadata: extra.usageMetadata,\n }),\n generationInfo,\n });\n}\n\nexport function convertToGenerativeAITools(\n tools: GoogleGenerativeAIToolType[]\n): GoogleGenerativeAIFunctionDeclarationsTool[] {\n if (\n tools.every(\n (tool) =>\n \"functionDeclarations\" in tool &&\n Array.isArray(tool.functionDeclarations)\n )\n ) {\n return tools as GoogleGenerativeAIFunctionDeclarationsTool[];\n }\n return [\n {\n functionDeclarations: tools.map(\n (tool): GenerativeAIFunctionDeclaration => {\n if (isLangChainTool(tool)) {\n const jsonSchema = schemaToGenerativeAIParameters(tool.schema);\n if (\n jsonSchema.type === \"object\" &&\n \"properties\" in jsonSchema &&\n Object.keys(jsonSchema.properties).length === 0\n ) {\n return {\n name: tool.name,\n description: tool.description,\n };\n }\n return {\n name: tool.name,\n description: tool.description,\n parameters: jsonSchema,\n };\n }\n if (isOpenAITool(tool)) {\n return {\n name: tool.function.name,\n description:\n tool.function.description ?? `A function available to call.`,\n parameters: jsonSchemaToGeminiParameters(\n tool.function.parameters\n ),\n };\n }\n return tool as unknown as GenerativeAIFunctionDeclaration;\n }\n ),\n },\n ];\n}\n\nexport function convertUsageMetadata(\n usageMetadata: GenerateContentResponse[\"usageMetadata\"],\n model: string\n): UsageMetadata {\n const output: UsageMetadata = {\n input_tokens: usageMetadata?.promptTokenCount ?? 0,\n output_tokens: usageMetadata?.candidatesTokenCount ?? 0,\n total_tokens: usageMetadata?.totalTokenCount ?? 0,\n };\n if (usageMetadata?.cachedContentTokenCount) {\n output.input_token_details ??= {};\n output.input_token_details.cache_read =\n usageMetadata.cachedContentTokenCount;\n }\n // gemini-3-pro-preview has bracket based tracking of tokens per request\n // FIXME(hntrl): move this usageMetadata calculation elsewhere\n if (model === \"gemini-3-pro-preview\") {\n const over200k = Math.max(0, usageMetadata?.promptTokenCount ?? 0 - 200000);\n const cachedOver200k = Math.max(\n 0,\n usageMetadata?.cachedContentTokenCount ?? 0 - 200000\n );\n if (over200k) {\n output.input_token_details = {\n ...output.input_token_details,\n over_200k: over200k,\n } as InputTokenDetails;\n }\n if (cachedOver200k) {\n output.input_token_details = {\n ...output.input_token_details,\n cache_read_over_200k: cachedOver200k,\n } as InputTokenDetails;\n }\n }\n return output;\n}\n"],"mappings":";;;;;;;;AA+CA,MAAa,4CACX;AACF,MAAM,kBACJ;AAEF,MAAM,OAAO,CAACA,OAAqB,IAAI;AAEvC,SAAgB,iBAAiBC,SAAsB;AACrD,KAAI,YAAY,WAAW,QAAQ,CACjC,QAAO,QAAQ;AAEjB,QAAO,QAAQ;AAChB;;;;;;;AAQD,SAAgB,oBACdC,QACiC;AACjC,SAAQ,QAAR;EA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AO;GACV,sBAAsB;EACvB;CAEJ;AACD,QAAO;AACR"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@langchain/google-genai",
|
|
3
|
-
"version": "2.0.
|
|
3
|
+
"version": "2.0.5-dev-1765431816670",
|
|
4
4
|
"description": "Google Generative AI integration for LangChain.js",
|
|
5
5
|
"author": "LangChain",
|
|
6
6
|
"license": "MIT",
|
|
@@ -18,7 +18,7 @@
|
|
|
18
18
|
"uuid": "^11.1.0"
|
|
19
19
|
},
|
|
20
20
|
"peerDependencies": {
|
|
21
|
-
"@langchain/core": "1.1.
|
|
21
|
+
"@langchain/core": "1.1.5-dev-1765431816670"
|
|
22
22
|
},
|
|
23
23
|
"devDependencies": {
|
|
24
24
|
"@jest/globals": "^29.5.0",
|
|
@@ -36,9 +36,10 @@
|
|
|
36
36
|
"ts-jest": "^29.1.0",
|
|
37
37
|
"typescript": "~5.8.3",
|
|
38
38
|
"zod": "^3.25.76",
|
|
39
|
-
"@langchain/core": "1.1.
|
|
39
|
+
"@langchain/core": "1.1.5-dev-1765431816670",
|
|
40
|
+
"@langchain/standard-tests": "0.0.8-dev-1765431816670",
|
|
40
41
|
"@langchain/eslint": "0.1.1",
|
|
41
|
-
"@langchain/
|
|
42
|
+
"@langchain/tsconfig": "0.0.1"
|
|
42
43
|
},
|
|
43
44
|
"publishConfig": {
|
|
44
45
|
"access": "public"
|
|
@@ -81,8 +82,8 @@
|
|
|
81
82
|
"test:standard:unit": "NODE_OPTIONS=--experimental-vm-modules jest --testPathPattern=\\.standard\\.test.ts --testTimeout 100000 --maxWorkers=50%",
|
|
82
83
|
"test:standard:int": "NODE_OPTIONS=--experimental-vm-modules jest --testPathPattern=\\.standard\\.int\\.test.ts --testTimeout 100000 --maxWorkers=50%",
|
|
83
84
|
"test:standard": "pnpm test:standard:unit && pnpm test:standard:int",
|
|
84
|
-
"format": "prettier --
|
|
85
|
-
"format:check": "prettier --
|
|
85
|
+
"format": "prettier --write \"src\"",
|
|
86
|
+
"format:check": "prettier --check \"src\"",
|
|
86
87
|
"typegen": "pnpm run typegen:profiles",
|
|
87
88
|
"typegen:profiles": "pnpm --filter @langchain/model-profiles make --config profiles.toml"
|
|
88
89
|
}
|