@langchain/google-genai 2.1.25 → 2.1.26-dev-1773698445534
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.cjs +7 -8
- package/dist/chat_models.cjs.map +1 -1
- package/dist/chat_models.js +2 -3
- package/dist/chat_models.js.map +1 -1
- package/dist/embeddings.cjs +1 -2
- package/dist/embeddings.cjs.map +1 -1
- package/dist/embeddings.js +1 -2
- package/dist/embeddings.js.map +1 -1
- package/dist/index.cjs +4 -5
- package/dist/index.js +1 -2
- package/dist/output_parsers.cjs +1 -2
- package/dist/output_parsers.cjs.map +1 -1
- package/dist/output_parsers.js +1 -2
- package/dist/output_parsers.js.map +1 -1
- package/dist/profiles.cjs +1 -2
- package/dist/profiles.cjs.map +1 -1
- package/dist/profiles.js +1 -1
- package/dist/utils/common.cjs +42 -5
- package/dist/utils/common.cjs.map +1 -1
- package/dist/utils/common.js +40 -3
- package/dist/utils/common.js.map +1 -1
- package/dist/utils/tools.cjs +3 -4
- package/dist/utils/tools.cjs.map +1 -1
- package/dist/utils/tools.js +1 -2
- package/dist/utils/tools.js.map +1 -1
- package/dist/utils/validate_schema.cjs +1 -2
- package/dist/utils/validate_schema.cjs.map +1 -1
- package/dist/utils/validate_schema.js +1 -1
- package/dist/utils/validate_schema.js.map +1 -1
- package/dist/utils/zod_to_genai_parameters.cjs +1 -2
- package/dist/utils/zod_to_genai_parameters.cjs.map +1 -1
- package/dist/utils/zod_to_genai_parameters.js +1 -2
- package/dist/utils/zod_to_genai_parameters.js.map +1 -1
- package/package.json +10 -15
package/dist/utils/common.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"common.js","names":["uuidv4"],"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 {\n GoogleGenerativeAIPart,\n GoogleGenerativeAIToolType,\n} from \"../types.js\";\nimport { assertNoEmptyStringEnums } from \"./validate_schema.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 (content.type === \"tool_call\") {\n return {\n functionCall: {\n name: content.name,\n args: content.args,\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(\n (acc, p) => {\n if (\"functionCall\" in p && p.functionCall) {\n acc.push({\n ...p,\n id:\n \"id\" in p.functionCall && typeof p.functionCall.id === \"string\"\n ? p.functionCall.id\n : uuidv4(),\n });\n }\n return acc;\n },\n [] as (FunctionCallPart & { id: string })[]\n );\n let content: MessageContent | undefined;\n\n const parts = candidateContent?.parts as GoogleGenerativeAIPart[] | undefined;\n\n if (\n Array.isArray(parts) &&\n parts.length === 1 &&\n \"text\" in parts[0] &&\n parts[0].text &&\n !parts[0].thought\n ) {\n content = parts[0].text;\n } else if (Array.isArray(parts) && parts.length > 0) {\n content = parts.map((p) => {\n if (p.thought && \"text\" in p && p.text) {\n return {\n type: \"thinking\",\n thinking: p.text,\n ...(p.thoughtSignature ? { signature: p.thoughtSignature } : {}),\n };\n } else 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(\n (acc, fc) => {\n if (\"thoughtSignature\" in fc && typeof fc.thoughtSignature === \"string\") {\n acc[fc.id] = fc.thoughtSignature;\n }\n return acc;\n },\n {} as Record<string, string>\n );\n\n 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(\n (acc, p) => {\n if (\"functionCall\" in p && p.functionCall) {\n acc.push({\n ...p,\n id:\n \"id\" in p.functionCall && typeof p.functionCall.id === \"string\"\n ? p.functionCall.id\n : uuidv4(),\n });\n }\n return acc;\n },\n [] as (FunctionCallPart & { id: string })[]\n );\n let content: MessageContent | undefined;\n const streamParts = candidateContent?.parts as\n | GoogleGenerativeAIPart[]\n | undefined;\n\n // Checks if all parts are plain text (no thought flags). If so, join as string.\n if (\n Array.isArray(streamParts) &&\n streamParts.every((p) => \"text\" in p && !p.thought)\n ) {\n content = streamParts.map((p) => p.text).join(\"\");\n } else if (Array.isArray(streamParts)) {\n content = streamParts.map((p) => {\n if (p.thought && \"text\" in p && p.text) {\n return {\n type: \"thinking\",\n thinking: p.text,\n ...(p.thoughtSignature ? { signature: p.thoughtSignature } : {}),\n };\n } else 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(\n (acc, fc) => {\n if (\"thoughtSignature\" in fc && typeof fc.thoughtSignature === \"string\") {\n acc[fc.id] = fc.thoughtSignature;\n }\n return acc;\n },\n {} as Record<string, string>\n );\n\n 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 assertNoEmptyStringEnums(jsonSchema, tool.name);\n return {\n name: tool.name,\n description: tool.description,\n parameters: jsonSchema,\n };\n }\n if (isOpenAITool(tool)) {\n const params = jsonSchemaToGeminiParameters(\n tool.function.parameters\n );\n assertNoEmptyStringEnums(params, tool.function.name);\n return {\n name: tool.function.name,\n description:\n tool.function.description ?? `A function available to call.`,\n parameters: params,\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":";;;;;;;;;AAmDA,MAAa,4CACX;AACF,MAAM,kBACJ;AAEF,MAAM,QAAQ,OAAqB,IAAI;AAEvC,SAAgB,iBAAiB,SAAsB;AACrD,KAAI,YAAY,WAAW,QAAQ,CACjC,QAAO,QAAQ;AAEjB,QAAO,QAAQ;;;;;;;;AASjB,SAAgB,oBACd,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,iCAAiC,SAAS;;;AAIhE,SAAS,oBAAoB,SAAsC;AACjE,KAAI,cAAc,WAAW,UAAU,QACrC,QAAO,EACL,YAAY;EACV,UAAU,QAAQ;EAClB,MAAM,QAAQ;EACf,EACF;AAEH,KAAI,cAAc,WAAW,aAAa,QACxC,QAAO,EACL,UAAU;EACR,UAAU,QAAQ;EAClB,SAAS,QAAQ;EAClB,EACF;AAGH,OAAM,IAAI,MAAM,wBAAwB;;AAG1C,SAAS,kCACP,SACA,kBACoB;AACpB,QAAO,iBACJ,KAAK,QAAQ;AACZ,MAAI,YAAY,IAAI,CAClB,QAAO,IAAI,cAAc,EAAE;AAE7B,SAAO,EAAE;GACT,CACD,MAAM,CACN,MAAM,aAAa;AAClB,SAAO,SAAS,OAAO,QAAQ;GAC/B,EAAE;;AAGR,SAAS,kCAAkC,mBAA4B;AA4HrE,QAtHK;EACH,cAAc;EAEd,sBAAsB,OAAO;AAC3B,UAAO,EACL,MAAM,MAAM,MACb;;EAGH,uBAAuB,OAAsC;AAC3D,OAAI,CAAC,kBACH,OAAM,IAAI,MAAM,qCAAqC;AAEvD,OAAI,MAAM,gBAAgB,OAAO;IAC/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wB;EACtD,cAAc,eAAe,mBAAmB;EACjD;AACD,KAAI,eAAe,yBAAyB;AAC1C,SAAO,wBAAwB,EAAE;AACjC,SAAO,oBAAoB,aACzB,cAAc;;AAIlB,KAAI,UAAU,wBAAwB;EACpC,MAAM,WAAW,KAAK,IAAI,GAAG,eAAe,oBAAoB,KAAW;EAC3E,MAAM,iBAAiB,KAAK,IAC1B,GACA,eAAe,2BAA2B,KAC3C;AACD,MAAI,SACF,QAAO,sBAAsB;GAC3B,GAAG,OAAO;GACV,WAAW;GACZ;AAEH,MAAI,eACF,QAAO,sBAAsB;GAC3B,GAAG,OAAO;GACV,sBAAsB;GACvB;;AAGL,QAAO"}
|
|
1
|
+
{"version":3,"file":"common.js","names":["uuidv4"],"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 ContentBlock,\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 {\n GoogleGenerativeAIPart,\n GoogleGenerativeAIToolType,\n} from \"../types.js\";\nimport { assertNoEmptyStringEnums } from \"./validate_schema.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\n/**\n * Converts a ContentBlock.Multimodal block (image, video, audio, file)\n * to the appropriate Google Generative AI Part format.\n *\n * Handles three data record variants:\n * - DataRecordBase64: has `data` property → InlineDataPart\n * - DataRecordUrl: has `url` property → FileDataPart (or InlineDataPart for data: URLs)\n * - DataRecordFileId: has `fileId` property → not directly supported, throws\n */\nfunction _multimodalContentBlockToPart(\n block: ContentBlock.Multimodal.Data,\n defaultMimeType: string\n): InlineDataPart | FileDataPart {\n if (\"data\" in block && block.data !== undefined) {\n // DataRecordBase64: inline base64 data\n const data =\n // eslint-disable-next-line no-instanceof/no-instanceof\n block.data instanceof Uint8Array\n ? btoa(String.fromCharCode(...block.data))\n : block.data;\n return {\n inlineData: {\n mimeType: block.mimeType || defaultMimeType,\n data,\n },\n };\n }\n\n if (\"url\" in block && block.url !== undefined) {\n // DataRecordUrl: check if it's a data: URL first\n const parsed = parseBase64DataUrl({ dataUrl: block.url });\n if (parsed) {\n return {\n inlineData: {\n mimeType: parsed.mime_type,\n data: parsed.data,\n },\n };\n }\n // Regular URL → fileData\n return {\n fileData: {\n mimeType: block.mimeType || defaultMimeType,\n fileUri: block.url,\n },\n };\n }\n\n if (\"fileId\" in block && block.fileId !== undefined) {\n throw new Error(\n `ContentBlock.Multimodal fileId is not supported by Google Generative AI. ` +\n `Use a URL or base64 data instead.`\n );\n }\n\n throw new Error(\n `Invalid multimodal content block: must have \"data\", \"url\", or \"fileId\" property. ` +\n `Received: ${JSON.stringify(block)}`\n );\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 === \"image\") {\n return _multimodalContentBlockToPart(\n content as ContentBlock.Multimodal.Image,\n \"image/png\"\n );\n } else if (content.type === \"video\") {\n return _multimodalContentBlockToPart(\n content as ContentBlock.Multimodal.Video,\n \"video/mp4\"\n );\n } else if (content.type === \"audio\") {\n return _multimodalContentBlockToPart(\n content as ContentBlock.Multimodal.Audio,\n \"audio/mpeg\"\n );\n } else if (content.type === \"file\") {\n return _multimodalContentBlockToPart(\n content as ContentBlock.Multimodal.File,\n \"application/octet-stream\"\n );\n } else if (content.type === \"text-plain\") {\n // text-plain blocks can have an inline text property\n if (\n \"text\" in content &&\n typeof (content as ContentBlock.Multimodal.PlainText).text === \"string\"\n ) {\n return { text: (content as ContentBlock.Multimodal.PlainText).text! };\n }\n return _multimodalContentBlockToPart(\n content as ContentBlock.Multimodal.PlainText,\n \"text/plain\"\n );\n } else if (content.type === \"tool_use\") {\n return {\n functionCall: {\n name: content.name,\n args: content.input,\n },\n };\n } else if (content.type === \"tool_call\") {\n return {\n functionCall: {\n name: content.name,\n args: content.args,\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(\n (acc, p) => {\n if (\"functionCall\" in p && p.functionCall) {\n acc.push({\n ...p,\n id:\n \"id\" in p.functionCall && typeof p.functionCall.id === \"string\"\n ? p.functionCall.id\n : uuidv4(),\n });\n }\n return acc;\n },\n [] as (FunctionCallPart & { id: string })[]\n );\n let content: MessageContent | undefined;\n\n const parts = candidateContent?.parts as GoogleGenerativeAIPart[] | undefined;\n\n if (\n Array.isArray(parts) &&\n parts.length === 1 &&\n \"text\" in parts[0] &&\n parts[0].text &&\n !parts[0].thought\n ) {\n content = parts[0].text;\n } else if (Array.isArray(parts) && parts.length > 0) {\n content = parts.map((p) => {\n if (p.thought && \"text\" in p && p.text) {\n return {\n type: \"thinking\",\n thinking: p.text,\n ...(p.thoughtSignature ? { signature: p.thoughtSignature } : {}),\n };\n } else 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(\n (acc, fc) => {\n if (\"thoughtSignature\" in fc && typeof fc.thoughtSignature === \"string\") {\n acc[fc.id] = fc.thoughtSignature;\n }\n return acc;\n },\n {} as Record<string, string>\n );\n\n 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(\n (acc, p) => {\n if (\"functionCall\" in p && p.functionCall) {\n acc.push({\n ...p,\n id:\n \"id\" in p.functionCall && typeof p.functionCall.id === \"string\"\n ? p.functionCall.id\n : uuidv4(),\n });\n }\n return acc;\n },\n [] as (FunctionCallPart & { id: string })[]\n );\n let content: MessageContent | undefined;\n const streamParts = candidateContent?.parts as\n | GoogleGenerativeAIPart[]\n | undefined;\n\n // Checks if all parts are plain text (no thought flags). If so, join as string.\n if (\n Array.isArray(streamParts) &&\n streamParts.every((p) => \"text\" in p && !p.thought)\n ) {\n content = streamParts.map((p) => p.text).join(\"\");\n } else if (Array.isArray(streamParts)) {\n content = streamParts.map((p) => {\n if (p.thought && \"text\" in p && p.text) {\n return {\n type: \"thinking\",\n thinking: p.text,\n ...(p.thoughtSignature ? { signature: p.thoughtSignature } : {}),\n };\n } else 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(\n (acc, fc) => {\n if (\"thoughtSignature\" in fc && typeof fc.thoughtSignature === \"string\") {\n acc[fc.id] = fc.thoughtSignature;\n }\n return acc;\n },\n {} as Record<string, string>\n );\n\n 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 assertNoEmptyStringEnums(jsonSchema, tool.name);\n return {\n name: tool.name,\n description: tool.description,\n parameters: jsonSchema,\n };\n }\n if (isOpenAITool(tool)) {\n const params = jsonSchemaToGeminiParameters(\n tool.function.parameters\n );\n assertNoEmptyStringEnums(params, tool.function.name);\n return {\n name: tool.function.name,\n description:\n tool.function.description ?? `A function available to call.`,\n parameters: params,\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":";;;;;;;;AAoDA,MAAa,4CACX;AACF,MAAM,kBACJ;AAEF,MAAM,QAAQ,OAAqB,IAAI;AAEvC,SAAgB,iBAAiB,SAAsB;AACrD,KAAI,YAAY,WAAW,QAAQ,CACjC,QAAO,QAAQ;AAEjB,QAAO,QAAQ;;;;;;;;AASjB,SAAgB,oBACd,QACiC;AACjC,SAAQ,QAAR;EAKE,KAAK;EACL,KAAK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gB,KAAK,EAAE;GACzB,MAAM,aAAa,+BAA+B,KAAK,OAAO;AAC9D,OACE,WAAW,SAAS,YACpB,gBAAgB,cAChB,OAAO,KAAK,WAAW,WAAW,CAAC,WAAW,EAE9C,QAAO;IACL,MAAM,KAAK;IACX,aAAa,KAAK;IACnB;AAEH,4BAAyB,YAAY,KAAK,KAAK;AAC/C,UAAO;IACL,MAAM,KAAK;IACX,aAAa,KAAK;IAClB,YAAY;IACb;;AAEH,MAAI,aAAa,KAAK,EAAE;GACtB,MAAM,SAAS,6BACb,KAAK,SAAS,WACf;AACD,4BAAyB,QAAQ,KAAK,SAAS,KAAK;AACpD,UAAO;IACL,MAAM,KAAK,SAAS;IACpB,aACE,KAAK,SAAS,eAAe;IAC/B,YAAY;IACb;;AAEH,SAAO;GAEV,EACF,CACF;;AAGH,SAAgB,qBACd,eACA,OACe;CACf,MAAM,SAAwB;EAC5B,cAAc,eAAe,oBAAoB;EACjD,eAAe,eAAe,wBAAwB;EACtD,cAAc,eAAe,mBAAmB;EACjD;AACD,KAAI,eAAe,yBAAyB;AAC1C,SAAO,wBAAwB,EAAE;AACjC,SAAO,oBAAoB,aACzB,cAAc;;AAIlB,KAAI,UAAU,wBAAwB;EACpC,MAAM,WAAW,KAAK,IAAI,GAAG,eAAe,oBAAoB,KAAW;EAC3E,MAAM,iBAAiB,KAAK,IAC1B,GACA,eAAe,2BAA2B,KAC3C;AACD,MAAI,SACF,QAAO,sBAAsB;GAC3B,GAAG,OAAO;GACV,WAAW;GACZ;AAEH,MAAI,eACF,QAAO,sBAAsB;GAC3B,GAAG,OAAO;GACV,sBAAsB;GACvB;;AAGL,QAAO"}
|
package/dist/utils/tools.cjs
CHANGED
|
@@ -1,9 +1,8 @@
|
|
|
1
|
-
const require_zod_to_genai_parameters = require(
|
|
2
|
-
const require_common = require(
|
|
1
|
+
const require_zod_to_genai_parameters = require("./zod_to_genai_parameters.cjs");
|
|
2
|
+
const require_common = require("./common.cjs");
|
|
3
3
|
let _google_generative_ai = require("@google/generative-ai");
|
|
4
4
|
let _langchain_core_utils_function_calling = require("@langchain/core/utils/function_calling");
|
|
5
5
|
let _langchain_core_language_models_base = require("@langchain/core/language_models/base");
|
|
6
|
-
|
|
7
6
|
//#region src/utils/tools.ts
|
|
8
7
|
function convertToolsToGenAI(tools, extra) {
|
|
9
8
|
const genAITools = processTools(tools);
|
|
@@ -63,7 +62,7 @@ function createToolConfig(genAITools, extra) {
|
|
|
63
62
|
allowedFunctionNames: [...allowedFunctionNames ?? [], ...toolChoice && typeof toolChoice === "string" ? [toolChoice] : []]
|
|
64
63
|
} };
|
|
65
64
|
}
|
|
66
|
-
|
|
67
65
|
//#endregion
|
|
68
66
|
exports.convertToolsToGenAI = convertToolsToGenAI;
|
|
67
|
+
|
|
69
68
|
//# sourceMappingURL=tools.cjs.map
|
package/dist/utils/tools.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"tools.cjs","names":["convertToGenerativeAITools","removeAdditionalProperties","FunctionCallingMode"],"sources":["../../src/utils/tools.ts"],"sourcesContent":["import {\n Tool as GenerativeAITool,\n ToolConfig,\n FunctionCallingMode,\n FunctionDeclaration,\n FunctionDeclarationsTool,\n FunctionDeclarationSchema,\n} from \"@google/generative-ai\";\nimport { ToolChoice } from \"@langchain/core/language_models/chat_models\";\nimport { StructuredToolInterface } from \"@langchain/core/tools\";\nimport { isLangChainTool } from \"@langchain/core/utils/function_calling\";\nimport {\n isOpenAITool,\n ToolDefinition,\n} from \"@langchain/core/language_models/base\";\nimport { convertToGenerativeAITools } from \"./common.js\";\nimport { GoogleGenerativeAIToolType } from \"../types.js\";\nimport { removeAdditionalProperties } from \"./zod_to_genai_parameters.js\";\n\nexport function convertToolsToGenAI(\n tools: GoogleGenerativeAIToolType[],\n extra?: {\n toolChoice?: ToolChoice;\n allowedFunctionNames?: string[];\n }\n): {\n tools: GenerativeAITool[];\n toolConfig?: ToolConfig;\n} {\n // Extract function declaration processing to a separate function\n const genAITools = processTools(tools);\n\n // Simplify tool config creation\n const toolConfig = createToolConfig(genAITools, extra);\n\n return { tools: genAITools, toolConfig };\n}\n\nfunction processTools(tools: GoogleGenerativeAIToolType[]): GenerativeAITool[] {\n let functionDeclarationTools: FunctionDeclaration[] = [];\n const genAITools: GenerativeAITool[] = [];\n\n tools.forEach((tool) => {\n if (isLangChainTool(tool)) {\n const [convertedTool] = convertToGenerativeAITools([\n tool as StructuredToolInterface,\n ]);\n if (convertedTool.functionDeclarations) {\n functionDeclarationTools.push(...convertedTool.functionDeclarations);\n }\n } else if (isOpenAITool(tool)) {\n const { functionDeclarations } = convertOpenAIToolToGenAI(tool);\n if (functionDeclarations) {\n functionDeclarationTools.push(...functionDeclarations);\n } else {\n throw new Error(\n \"Failed to convert OpenAI structured tool to GenerativeAI tool\"\n );\n }\n } else {\n genAITools.push(tool as GenerativeAITool);\n }\n });\n\n const genAIFunctionDeclaration = genAITools.find(\n (t) => \"functionDeclarations\" in t\n );\n if (genAIFunctionDeclaration) {\n return genAITools.map((tool) => {\n if (\n functionDeclarationTools?.length > 0 &&\n \"functionDeclarations\" in tool\n ) {\n const newTool = {\n functionDeclarations: [\n ...(tool.functionDeclarations || []),\n ...functionDeclarationTools,\n ],\n };\n // Clear the functionDeclarationTools array so it is not passed again\n functionDeclarationTools = [];\n return newTool;\n }\n return tool;\n });\n }\n\n return [\n ...genAITools,\n ...(functionDeclarationTools.length > 0\n ? [\n {\n functionDeclarations: functionDeclarationTools,\n },\n ]\n : []),\n ];\n}\n\nfunction convertOpenAIToolToGenAI(\n tool: ToolDefinition\n): FunctionDeclarationsTool {\n return {\n functionDeclarations: [\n {\n name: tool.function.name,\n description: tool.function.description,\n parameters: removeAdditionalProperties(\n tool.function.parameters\n ) as FunctionDeclarationSchema,\n },\n ],\n };\n}\n\nfunction createToolConfig(\n genAITools: GenerativeAITool[],\n extra?: {\n toolChoice?: ToolChoice;\n allowedFunctionNames?: string[];\n }\n): ToolConfig | undefined {\n if (!genAITools.length || !extra) return undefined;\n\n const { toolChoice, allowedFunctionNames } = extra;\n\n const modeMap: Record<string, FunctionCallingMode> = {\n any: FunctionCallingMode.ANY,\n auto: FunctionCallingMode.AUTO,\n none: FunctionCallingMode.NONE,\n };\n\n if (toolChoice && [\"any\", \"auto\", \"none\"].includes(toolChoice as string)) {\n return {\n functionCallingConfig: {\n mode: modeMap[toolChoice as keyof typeof modeMap] ?? \"MODE_UNSPECIFIED\",\n allowedFunctionNames,\n },\n };\n }\n\n if (typeof toolChoice === \"string\" || allowedFunctionNames) {\n return {\n functionCallingConfig: {\n mode: FunctionCallingMode.ANY,\n allowedFunctionNames: [\n ...(allowedFunctionNames ?? []),\n ...(toolChoice && typeof toolChoice === \"string\" ? [toolChoice] : []),\n ],\n },\n };\n }\n\n return undefined;\n}\n"],"mappings":"
|
|
1
|
+
{"version":3,"file":"tools.cjs","names":["convertToGenerativeAITools","removeAdditionalProperties","FunctionCallingMode"],"sources":["../../src/utils/tools.ts"],"sourcesContent":["import {\n Tool as GenerativeAITool,\n ToolConfig,\n FunctionCallingMode,\n FunctionDeclaration,\n FunctionDeclarationsTool,\n FunctionDeclarationSchema,\n} from \"@google/generative-ai\";\nimport { ToolChoice } from \"@langchain/core/language_models/chat_models\";\nimport { StructuredToolInterface } from \"@langchain/core/tools\";\nimport { isLangChainTool } from \"@langchain/core/utils/function_calling\";\nimport {\n isOpenAITool,\n ToolDefinition,\n} from \"@langchain/core/language_models/base\";\nimport { convertToGenerativeAITools } from \"./common.js\";\nimport { GoogleGenerativeAIToolType } from \"../types.js\";\nimport { removeAdditionalProperties } from \"./zod_to_genai_parameters.js\";\n\nexport function convertToolsToGenAI(\n tools: GoogleGenerativeAIToolType[],\n extra?: {\n toolChoice?: ToolChoice;\n allowedFunctionNames?: string[];\n }\n): {\n tools: GenerativeAITool[];\n toolConfig?: ToolConfig;\n} {\n // Extract function declaration processing to a separate function\n const genAITools = processTools(tools);\n\n // Simplify tool config creation\n const toolConfig = createToolConfig(genAITools, extra);\n\n return { tools: genAITools, toolConfig };\n}\n\nfunction processTools(tools: GoogleGenerativeAIToolType[]): GenerativeAITool[] {\n let functionDeclarationTools: FunctionDeclaration[] = [];\n const genAITools: GenerativeAITool[] = [];\n\n tools.forEach((tool) => {\n if (isLangChainTool(tool)) {\n const [convertedTool] = convertToGenerativeAITools([\n tool as StructuredToolInterface,\n ]);\n if (convertedTool.functionDeclarations) {\n functionDeclarationTools.push(...convertedTool.functionDeclarations);\n }\n } else if (isOpenAITool(tool)) {\n const { functionDeclarations } = convertOpenAIToolToGenAI(tool);\n if (functionDeclarations) {\n functionDeclarationTools.push(...functionDeclarations);\n } else {\n throw new Error(\n \"Failed to convert OpenAI structured tool to GenerativeAI tool\"\n );\n }\n } else {\n genAITools.push(tool as GenerativeAITool);\n }\n });\n\n const genAIFunctionDeclaration = genAITools.find(\n (t) => \"functionDeclarations\" in t\n );\n if (genAIFunctionDeclaration) {\n return genAITools.map((tool) => {\n if (\n functionDeclarationTools?.length > 0 &&\n \"functionDeclarations\" in tool\n ) {\n const newTool = {\n functionDeclarations: [\n ...(tool.functionDeclarations || []),\n ...functionDeclarationTools,\n ],\n };\n // Clear the functionDeclarationTools array so it is not passed again\n functionDeclarationTools = [];\n return newTool;\n }\n return tool;\n });\n }\n\n return [\n ...genAITools,\n ...(functionDeclarationTools.length > 0\n ? [\n {\n functionDeclarations: functionDeclarationTools,\n },\n ]\n : []),\n ];\n}\n\nfunction convertOpenAIToolToGenAI(\n tool: ToolDefinition\n): FunctionDeclarationsTool {\n return {\n functionDeclarations: [\n {\n name: tool.function.name,\n description: tool.function.description,\n parameters: removeAdditionalProperties(\n tool.function.parameters\n ) as FunctionDeclarationSchema,\n },\n ],\n };\n}\n\nfunction createToolConfig(\n genAITools: GenerativeAITool[],\n extra?: {\n toolChoice?: ToolChoice;\n allowedFunctionNames?: string[];\n }\n): ToolConfig | undefined {\n if (!genAITools.length || !extra) return undefined;\n\n const { toolChoice, allowedFunctionNames } = extra;\n\n const modeMap: Record<string, FunctionCallingMode> = {\n any: FunctionCallingMode.ANY,\n auto: FunctionCallingMode.AUTO,\n none: FunctionCallingMode.NONE,\n };\n\n if (toolChoice && [\"any\", \"auto\", \"none\"].includes(toolChoice as string)) {\n return {\n functionCallingConfig: {\n mode: modeMap[toolChoice as keyof typeof modeMap] ?? \"MODE_UNSPECIFIED\",\n allowedFunctionNames,\n },\n };\n }\n\n if (typeof toolChoice === \"string\" || allowedFunctionNames) {\n return {\n functionCallingConfig: {\n mode: FunctionCallingMode.ANY,\n allowedFunctionNames: [\n ...(allowedFunctionNames ?? []),\n ...(toolChoice && typeof toolChoice === \"string\" ? [toolChoice] : []),\n ],\n },\n };\n }\n\n return undefined;\n}\n"],"mappings":";;;;;;AAmBA,SAAgB,oBACd,OACA,OAOA;CAEA,MAAM,aAAa,aAAa,MAAM;AAKtC,QAAO;EAAE,OAAO;EAAY,YAFT,iBAAiB,YAAY,MAAM;EAEd;;AAG1C,SAAS,aAAa,OAAyD;CAC7E,IAAI,2BAAkD,EAAE;CACxD,MAAM,aAAiC,EAAE;AAEzC,OAAM,SAAS,SAAS;AACtB,OAAA,GAAA,uCAAA,iBAAoB,KAAK,EAAE;GACzB,MAAM,CAAC,iBAAiBA,eAAAA,2BAA2B,CACjD,KACD,CAAC;AACF,OAAI,cAAc,qBAChB,0BAAyB,KAAK,GAAG,cAAc,qBAAqB;oEAEhD,KAAK,EAAE;GAC7B,MAAM,EAAE,yBAAyB,yBAAyB,KAAK;AAC/D,OAAI,qBACF,0BAAyB,KAAK,GAAG,qBAAqB;OAEtD,OAAM,IAAI,MACR,gEACD;QAGH,YAAW,KAAK,KAAyB;GAE3C;AAKF,KAHiC,WAAW,MACzC,MAAM,0BAA0B,EAClC,CAEC,QAAO,WAAW,KAAK,SAAS;AAC9B,MACE,0BAA0B,SAAS,KACnC,0BAA0B,MAC1B;GACA,MAAM,UAAU,EACd,sBAAsB,CACpB,GAAI,KAAK,wBAAwB,EAAE,EACnC,GAAG,yBACJ,EACF;AAED,8BAA2B,EAAE;AAC7B,UAAO;;AAET,SAAO;GACP;AAGJ,QAAO,CACL,GAAG,YACH,GAAI,yBAAyB,SAAS,IAClC,CACE,EACE,sBAAsB,0BACvB,CACF,GACD,EAAE,CACP;;AAGH,SAAS,yBACP,MAC0B;AAC1B,QAAO,EACL,sBAAsB,CACpB;EACE,MAAM,KAAK,SAAS;EACpB,aAAa,KAAK,SAAS;EAC3B,YAAYC,gCAAAA,2BACV,KAAK,SAAS,WACf;EACF,CACF,EACF;;AAGH,SAAS,iBACP,YACA,OAIwB;AACxB,KAAI,CAAC,WAAW,UAAU,CAAC,MAAO,QAAO,KAAA;CAEzC,MAAM,EAAE,YAAY,yBAAyB;CAE7C,MAAM,UAA+C;EACnD,KAAKC,sBAAAA,oBAAoB;EACzB,MAAMA,sBAAAA,oBAAoB;EAC1B,MAAMA,sBAAAA,oBAAoB;EAC3B;AAED,KAAI,cAAc;EAAC;EAAO;EAAQ;EAAO,CAAC,SAAS,WAAqB,CACtE,QAAO,EACL,uBAAuB;EACrB,MAAM,QAAQ,eAAuC;EACrD;EACD,EACF;AAGH,KAAI,OAAO,eAAe,YAAY,qBACpC,QAAO,EACL,uBAAuB;EACrB,MAAMA,sBAAAA,oBAAoB;EAC1B,sBAAsB,CACpB,GAAI,wBAAwB,EAAE,EAC9B,GAAI,cAAc,OAAO,eAAe,WAAW,CAAC,WAAW,GAAG,EAAE,CACrE;EACF,EACF"}
|
package/dist/utils/tools.js
CHANGED
|
@@ -3,7 +3,6 @@ import { convertToGenerativeAITools } from "./common.js";
|
|
|
3
3
|
import { FunctionCallingMode } from "@google/generative-ai";
|
|
4
4
|
import { isLangChainTool } from "@langchain/core/utils/function_calling";
|
|
5
5
|
import { isOpenAITool } from "@langchain/core/language_models/base";
|
|
6
|
-
|
|
7
6
|
//#region src/utils/tools.ts
|
|
8
7
|
function convertToolsToGenAI(tools, extra) {
|
|
9
8
|
const genAITools = processTools(tools);
|
|
@@ -63,7 +62,7 @@ function createToolConfig(genAITools, extra) {
|
|
|
63
62
|
allowedFunctionNames: [...allowedFunctionNames ?? [], ...toolChoice && typeof toolChoice === "string" ? [toolChoice] : []]
|
|
64
63
|
} };
|
|
65
64
|
}
|
|
66
|
-
|
|
67
65
|
//#endregion
|
|
68
66
|
export { convertToolsToGenAI };
|
|
67
|
+
|
|
69
68
|
//# sourceMappingURL=tools.js.map
|
package/dist/utils/tools.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"tools.js","names":[],"sources":["../../src/utils/tools.ts"],"sourcesContent":["import {\n Tool as GenerativeAITool,\n ToolConfig,\n FunctionCallingMode,\n FunctionDeclaration,\n FunctionDeclarationsTool,\n FunctionDeclarationSchema,\n} from \"@google/generative-ai\";\nimport { ToolChoice } from \"@langchain/core/language_models/chat_models\";\nimport { StructuredToolInterface } from \"@langchain/core/tools\";\nimport { isLangChainTool } from \"@langchain/core/utils/function_calling\";\nimport {\n isOpenAITool,\n ToolDefinition,\n} from \"@langchain/core/language_models/base\";\nimport { convertToGenerativeAITools } from \"./common.js\";\nimport { GoogleGenerativeAIToolType } from \"../types.js\";\nimport { removeAdditionalProperties } from \"./zod_to_genai_parameters.js\";\n\nexport function convertToolsToGenAI(\n tools: GoogleGenerativeAIToolType[],\n extra?: {\n toolChoice?: ToolChoice;\n allowedFunctionNames?: string[];\n }\n): {\n tools: GenerativeAITool[];\n toolConfig?: ToolConfig;\n} {\n // Extract function declaration processing to a separate function\n const genAITools = processTools(tools);\n\n // Simplify tool config creation\n const toolConfig = createToolConfig(genAITools, extra);\n\n return { tools: genAITools, toolConfig };\n}\n\nfunction processTools(tools: GoogleGenerativeAIToolType[]): GenerativeAITool[] {\n let functionDeclarationTools: FunctionDeclaration[] = [];\n const genAITools: GenerativeAITool[] = [];\n\n tools.forEach((tool) => {\n if (isLangChainTool(tool)) {\n const [convertedTool] = convertToGenerativeAITools([\n tool as StructuredToolInterface,\n ]);\n if (convertedTool.functionDeclarations) {\n functionDeclarationTools.push(...convertedTool.functionDeclarations);\n }\n } else if (isOpenAITool(tool)) {\n const { functionDeclarations } = convertOpenAIToolToGenAI(tool);\n if (functionDeclarations) {\n functionDeclarationTools.push(...functionDeclarations);\n } else {\n throw new Error(\n \"Failed to convert OpenAI structured tool to GenerativeAI tool\"\n );\n }\n } else {\n genAITools.push(tool as GenerativeAITool);\n }\n });\n\n const genAIFunctionDeclaration = genAITools.find(\n (t) => \"functionDeclarations\" in t\n );\n if (genAIFunctionDeclaration) {\n return genAITools.map((tool) => {\n if (\n functionDeclarationTools?.length > 0 &&\n \"functionDeclarations\" in tool\n ) {\n const newTool = {\n functionDeclarations: [\n ...(tool.functionDeclarations || []),\n ...functionDeclarationTools,\n ],\n };\n // Clear the functionDeclarationTools array so it is not passed again\n functionDeclarationTools = [];\n return newTool;\n }\n return tool;\n });\n }\n\n return [\n ...genAITools,\n ...(functionDeclarationTools.length > 0\n ? [\n {\n functionDeclarations: functionDeclarationTools,\n },\n ]\n : []),\n ];\n}\n\nfunction convertOpenAIToolToGenAI(\n tool: ToolDefinition\n): FunctionDeclarationsTool {\n return {\n functionDeclarations: [\n {\n name: tool.function.name,\n description: tool.function.description,\n parameters: removeAdditionalProperties(\n tool.function.parameters\n ) as FunctionDeclarationSchema,\n },\n ],\n };\n}\n\nfunction createToolConfig(\n genAITools: GenerativeAITool[],\n extra?: {\n toolChoice?: ToolChoice;\n allowedFunctionNames?: string[];\n }\n): ToolConfig | undefined {\n if (!genAITools.length || !extra) return undefined;\n\n const { toolChoice, allowedFunctionNames } = extra;\n\n const modeMap: Record<string, FunctionCallingMode> = {\n any: FunctionCallingMode.ANY,\n auto: FunctionCallingMode.AUTO,\n none: FunctionCallingMode.NONE,\n };\n\n if (toolChoice && [\"any\", \"auto\", \"none\"].includes(toolChoice as string)) {\n return {\n functionCallingConfig: {\n mode: modeMap[toolChoice as keyof typeof modeMap] ?? \"MODE_UNSPECIFIED\",\n allowedFunctionNames,\n },\n };\n }\n\n if (typeof toolChoice === \"string\" || allowedFunctionNames) {\n return {\n functionCallingConfig: {\n mode: FunctionCallingMode.ANY,\n allowedFunctionNames: [\n ...(allowedFunctionNames ?? []),\n ...(toolChoice && typeof toolChoice === \"string\" ? [toolChoice] : []),\n ],\n },\n };\n }\n\n return undefined;\n}\n"],"mappings":"
|
|
1
|
+
{"version":3,"file":"tools.js","names":[],"sources":["../../src/utils/tools.ts"],"sourcesContent":["import {\n Tool as GenerativeAITool,\n ToolConfig,\n FunctionCallingMode,\n FunctionDeclaration,\n FunctionDeclarationsTool,\n FunctionDeclarationSchema,\n} from \"@google/generative-ai\";\nimport { ToolChoice } from \"@langchain/core/language_models/chat_models\";\nimport { StructuredToolInterface } from \"@langchain/core/tools\";\nimport { isLangChainTool } from \"@langchain/core/utils/function_calling\";\nimport {\n isOpenAITool,\n ToolDefinition,\n} from \"@langchain/core/language_models/base\";\nimport { convertToGenerativeAITools } from \"./common.js\";\nimport { GoogleGenerativeAIToolType } from \"../types.js\";\nimport { removeAdditionalProperties } from \"./zod_to_genai_parameters.js\";\n\nexport function convertToolsToGenAI(\n tools: GoogleGenerativeAIToolType[],\n extra?: {\n toolChoice?: ToolChoice;\n allowedFunctionNames?: string[];\n }\n): {\n tools: GenerativeAITool[];\n toolConfig?: ToolConfig;\n} {\n // Extract function declaration processing to a separate function\n const genAITools = processTools(tools);\n\n // Simplify tool config creation\n const toolConfig = createToolConfig(genAITools, extra);\n\n return { tools: genAITools, toolConfig };\n}\n\nfunction processTools(tools: GoogleGenerativeAIToolType[]): GenerativeAITool[] {\n let functionDeclarationTools: FunctionDeclaration[] = [];\n const genAITools: GenerativeAITool[] = [];\n\n tools.forEach((tool) => {\n if (isLangChainTool(tool)) {\n const [convertedTool] = convertToGenerativeAITools([\n tool as StructuredToolInterface,\n ]);\n if (convertedTool.functionDeclarations) {\n functionDeclarationTools.push(...convertedTool.functionDeclarations);\n }\n } else if (isOpenAITool(tool)) {\n const { functionDeclarations } = convertOpenAIToolToGenAI(tool);\n if (functionDeclarations) {\n functionDeclarationTools.push(...functionDeclarations);\n } else {\n throw new Error(\n \"Failed to convert OpenAI structured tool to GenerativeAI tool\"\n );\n }\n } else {\n genAITools.push(tool as GenerativeAITool);\n }\n });\n\n const genAIFunctionDeclaration = genAITools.find(\n (t) => \"functionDeclarations\" in t\n );\n if (genAIFunctionDeclaration) {\n return genAITools.map((tool) => {\n if (\n functionDeclarationTools?.length > 0 &&\n \"functionDeclarations\" in tool\n ) {\n const newTool = {\n functionDeclarations: [\n ...(tool.functionDeclarations || []),\n ...functionDeclarationTools,\n ],\n };\n // Clear the functionDeclarationTools array so it is not passed again\n functionDeclarationTools = [];\n return newTool;\n }\n return tool;\n });\n }\n\n return [\n ...genAITools,\n ...(functionDeclarationTools.length > 0\n ? [\n {\n functionDeclarations: functionDeclarationTools,\n },\n ]\n : []),\n ];\n}\n\nfunction convertOpenAIToolToGenAI(\n tool: ToolDefinition\n): FunctionDeclarationsTool {\n return {\n functionDeclarations: [\n {\n name: tool.function.name,\n description: tool.function.description,\n parameters: removeAdditionalProperties(\n tool.function.parameters\n ) as FunctionDeclarationSchema,\n },\n ],\n };\n}\n\nfunction createToolConfig(\n genAITools: GenerativeAITool[],\n extra?: {\n toolChoice?: ToolChoice;\n allowedFunctionNames?: string[];\n }\n): ToolConfig | undefined {\n if (!genAITools.length || !extra) return undefined;\n\n const { toolChoice, allowedFunctionNames } = extra;\n\n const modeMap: Record<string, FunctionCallingMode> = {\n any: FunctionCallingMode.ANY,\n auto: FunctionCallingMode.AUTO,\n none: FunctionCallingMode.NONE,\n };\n\n if (toolChoice && [\"any\", \"auto\", \"none\"].includes(toolChoice as string)) {\n return {\n functionCallingConfig: {\n mode: modeMap[toolChoice as keyof typeof modeMap] ?? \"MODE_UNSPECIFIED\",\n allowedFunctionNames,\n },\n };\n }\n\n if (typeof toolChoice === \"string\" || allowedFunctionNames) {\n return {\n functionCallingConfig: {\n mode: FunctionCallingMode.ANY,\n allowedFunctionNames: [\n ...(allowedFunctionNames ?? []),\n ...(toolChoice && typeof toolChoice === \"string\" ? [toolChoice] : []),\n ],\n },\n };\n }\n\n return undefined;\n}\n"],"mappings":";;;;;;AAmBA,SAAgB,oBACd,OACA,OAOA;CAEA,MAAM,aAAa,aAAa,MAAM;AAKtC,QAAO;EAAE,OAAO;EAAY,YAFT,iBAAiB,YAAY,MAAM;EAEd;;AAG1C,SAAS,aAAa,OAAyD;CAC7E,IAAI,2BAAkD,EAAE;CACxD,MAAM,aAAiC,EAAE;AAEzC,OAAM,SAAS,SAAS;AACtB,MAAI,gBAAgB,KAAK,EAAE;GACzB,MAAM,CAAC,iBAAiB,2BAA2B,CACjD,KACD,CAAC;AACF,OAAI,cAAc,qBAChB,0BAAyB,KAAK,GAAG,cAAc,qBAAqB;aAE7D,aAAa,KAAK,EAAE;GAC7B,MAAM,EAAE,yBAAyB,yBAAyB,KAAK;AAC/D,OAAI,qBACF,0BAAyB,KAAK,GAAG,qBAAqB;OAEtD,OAAM,IAAI,MACR,gEACD;QAGH,YAAW,KAAK,KAAyB;GAE3C;AAKF,KAHiC,WAAW,MACzC,MAAM,0BAA0B,EAClC,CAEC,QAAO,WAAW,KAAK,SAAS;AAC9B,MACE,0BAA0B,SAAS,KACnC,0BAA0B,MAC1B;GACA,MAAM,UAAU,EACd,sBAAsB,CACpB,GAAI,KAAK,wBAAwB,EAAE,EACnC,GAAG,yBACJ,EACF;AAED,8BAA2B,EAAE;AAC7B,UAAO;;AAET,SAAO;GACP;AAGJ,QAAO,CACL,GAAG,YACH,GAAI,yBAAyB,SAAS,IAClC,CACE,EACE,sBAAsB,0BACvB,CACF,GACD,EAAE,CACP;;AAGH,SAAS,yBACP,MAC0B;AAC1B,QAAO,EACL,sBAAsB,CACpB;EACE,MAAM,KAAK,SAAS;EACpB,aAAa,KAAK,SAAS;EAC3B,YAAY,2BACV,KAAK,SAAS,WACf;EACF,CACF,EACF;;AAGH,SAAS,iBACP,YACA,OAIwB;AACxB,KAAI,CAAC,WAAW,UAAU,CAAC,MAAO,QAAO,KAAA;CAEzC,MAAM,EAAE,YAAY,yBAAyB;CAE7C,MAAM,UAA+C;EACnD,KAAK,oBAAoB;EACzB,MAAM,oBAAoB;EAC1B,MAAM,oBAAoB;EAC3B;AAED,KAAI,cAAc;EAAC;EAAO;EAAQ;EAAO,CAAC,SAAS,WAAqB,CACtE,QAAO,EACL,uBAAuB;EACrB,MAAM,QAAQ,eAAuC;EACrD;EACD,EACF;AAGH,KAAI,OAAO,eAAe,YAAY,qBACpC,QAAO,EACL,uBAAuB;EACrB,MAAM,oBAAoB;EAC1B,sBAAsB,CACpB,GAAI,wBAAwB,EAAE,EAC9B,GAAI,cAAc,OAAO,eAAe,WAAW,CAAC,WAAW,GAAG,EAAE,CACrE;EACF,EACF"}
|
|
@@ -1,4 +1,3 @@
|
|
|
1
|
-
|
|
2
1
|
//#region src/utils/validate_schema.ts
|
|
3
2
|
function assertNoEmptyStringEnums(schema, toolName, path = []) {
|
|
4
3
|
if (schema == null || typeof schema !== "object") return;
|
|
@@ -22,7 +21,7 @@ function assertNoEmptyStringEnums(schema, toolName, path = []) {
|
|
|
22
21
|
}
|
|
23
22
|
if (obj.additionalProperties && typeof obj.additionalProperties === "object") assertNoEmptyStringEnums(obj.additionalProperties, toolName, [...path, "additionalProperties"]);
|
|
24
23
|
}
|
|
25
|
-
|
|
26
24
|
//#endregion
|
|
27
25
|
exports.assertNoEmptyStringEnums = assertNoEmptyStringEnums;
|
|
26
|
+
|
|
28
27
|
//# sourceMappingURL=validate_schema.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"validate_schema.cjs","names":[],"sources":["../../src/utils/validate_schema.ts"],"sourcesContent":["export function assertNoEmptyStringEnums(\n schema: unknown,\n toolName?: string,\n path: string[] = []\n): void {\n if (schema == null || typeof schema !== \"object\") return;\n const obj = schema as Record<string, unknown>;\n\n if (Array.isArray(obj.enum)) {\n if (obj.enum.some((v) => v === \"\")) {\n const pathStr = path.length ? ` at path \"${path.join(\".\")}\"` : \"\";\n const toolStr = toolName ? ` in tool \"${toolName}\"` : \"\";\n throw new Error(\n `Invalid enum: empty string not allowed${toolStr}${pathStr}. ` +\n \"Gemini API rejects empty strings in enums.\"\n );\n }\n }\n\n // Descend into common JSON Schema nests\n if (\n obj.type === \"object\" &&\n obj.properties &&\n typeof obj.properties === \"object\"\n ) {\n for (const [prop, child] of Object.entries(\n obj.properties as Record<string, unknown>\n )) {\n assertNoEmptyStringEnums(child, toolName, [...path, prop]);\n }\n }\n\n if (obj.items) {\n assertNoEmptyStringEnums(obj.items, toolName, [...path, \"[]\"]);\n }\n\n for (const k of [\"anyOf\", \"oneOf\", \"allOf\"]) {\n const arr = obj[k];\n if (Array.isArray(arr)) {\n arr.forEach((child, i) =>\n assertNoEmptyStringEnums(child, toolName, [...path, `${k}[${i}]`])\n );\n }\n }\n\n if (\n obj.additionalProperties &&\n typeof obj.additionalProperties === \"object\"\n ) {\n assertNoEmptyStringEnums(obj.additionalProperties, toolName, [\n ...path,\n \"additionalProperties\",\n ]);\n }\n}\n"],"mappings":"
|
|
1
|
+
{"version":3,"file":"validate_schema.cjs","names":[],"sources":["../../src/utils/validate_schema.ts"],"sourcesContent":["export function assertNoEmptyStringEnums(\n schema: unknown,\n toolName?: string,\n path: string[] = []\n): void {\n if (schema == null || typeof schema !== \"object\") return;\n const obj = schema as Record<string, unknown>;\n\n if (Array.isArray(obj.enum)) {\n if (obj.enum.some((v) => v === \"\")) {\n const pathStr = path.length ? ` at path \"${path.join(\".\")}\"` : \"\";\n const toolStr = toolName ? ` in tool \"${toolName}\"` : \"\";\n throw new Error(\n `Invalid enum: empty string not allowed${toolStr}${pathStr}. ` +\n \"Gemini API rejects empty strings in enums.\"\n );\n }\n }\n\n // Descend into common JSON Schema nests\n if (\n obj.type === \"object\" &&\n obj.properties &&\n typeof obj.properties === \"object\"\n ) {\n for (const [prop, child] of Object.entries(\n obj.properties as Record<string, unknown>\n )) {\n assertNoEmptyStringEnums(child, toolName, [...path, prop]);\n }\n }\n\n if (obj.items) {\n assertNoEmptyStringEnums(obj.items, toolName, [...path, \"[]\"]);\n }\n\n for (const k of [\"anyOf\", \"oneOf\", \"allOf\"]) {\n const arr = obj[k];\n if (Array.isArray(arr)) {\n arr.forEach((child, i) =>\n assertNoEmptyStringEnums(child, toolName, [...path, `${k}[${i}]`])\n );\n }\n }\n\n if (\n obj.additionalProperties &&\n typeof obj.additionalProperties === \"object\"\n ) {\n assertNoEmptyStringEnums(obj.additionalProperties, toolName, [\n ...path,\n \"additionalProperties\",\n ]);\n }\n}\n"],"mappings":";AAAA,SAAgB,yBACd,QACA,UACA,OAAiB,EAAE,EACb;AACN,KAAI,UAAU,QAAQ,OAAO,WAAW,SAAU;CAClD,MAAM,MAAM;AAEZ,KAAI,MAAM,QAAQ,IAAI,KAAK;MACrB,IAAI,KAAK,MAAM,MAAM,MAAM,GAAG,EAAE;GAClC,MAAM,UAAU,KAAK,SAAS,aAAa,KAAK,KAAK,IAAI,CAAC,KAAK;GAC/D,MAAM,UAAU,WAAW,aAAa,SAAS,KAAK;AACtD,SAAM,IAAI,MACR,yCAAyC,UAAU,QAAQ,8CAE5D;;;AAKL,KACE,IAAI,SAAS,YACb,IAAI,cACJ,OAAO,IAAI,eAAe,SAE1B,MAAK,MAAM,CAAC,MAAM,UAAU,OAAO,QACjC,IAAI,WACL,CACC,0BAAyB,OAAO,UAAU,CAAC,GAAG,MAAM,KAAK,CAAC;AAI9D,KAAI,IAAI,MACN,0BAAyB,IAAI,OAAO,UAAU,CAAC,GAAG,MAAM,KAAK,CAAC;AAGhE,MAAK,MAAM,KAAK;EAAC;EAAS;EAAS;EAAQ,EAAE;EAC3C,MAAM,MAAM,IAAI;AAChB,MAAI,MAAM,QAAQ,IAAI,CACpB,KAAI,SAAS,OAAO,MAClB,yBAAyB,OAAO,UAAU,CAAC,GAAG,MAAM,GAAG,EAAE,GAAG,EAAE,GAAG,CAAC,CACnE;;AAIL,KACE,IAAI,wBACJ,OAAO,IAAI,yBAAyB,SAEpC,0BAAyB,IAAI,sBAAsB,UAAU,CAC3D,GAAG,MACH,uBACD,CAAC"}
|
|
@@ -21,7 +21,7 @@ function assertNoEmptyStringEnums(schema, toolName, path = []) {
|
|
|
21
21
|
}
|
|
22
22
|
if (obj.additionalProperties && typeof obj.additionalProperties === "object") assertNoEmptyStringEnums(obj.additionalProperties, toolName, [...path, "additionalProperties"]);
|
|
23
23
|
}
|
|
24
|
-
|
|
25
24
|
//#endregion
|
|
26
25
|
export { assertNoEmptyStringEnums };
|
|
26
|
+
|
|
27
27
|
//# sourceMappingURL=validate_schema.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"validate_schema.js","names":[],"sources":["../../src/utils/validate_schema.ts"],"sourcesContent":["export function assertNoEmptyStringEnums(\n schema: unknown,\n toolName?: string,\n path: string[] = []\n): void {\n if (schema == null || typeof schema !== \"object\") return;\n const obj = schema as Record<string, unknown>;\n\n if (Array.isArray(obj.enum)) {\n if (obj.enum.some((v) => v === \"\")) {\n const pathStr = path.length ? ` at path \"${path.join(\".\")}\"` : \"\";\n const toolStr = toolName ? ` in tool \"${toolName}\"` : \"\";\n throw new Error(\n `Invalid enum: empty string not allowed${toolStr}${pathStr}. ` +\n \"Gemini API rejects empty strings in enums.\"\n );\n }\n }\n\n // Descend into common JSON Schema nests\n if (\n obj.type === \"object\" &&\n obj.properties &&\n typeof obj.properties === \"object\"\n ) {\n for (const [prop, child] of Object.entries(\n obj.properties as Record<string, unknown>\n )) {\n assertNoEmptyStringEnums(child, toolName, [...path, prop]);\n }\n }\n\n if (obj.items) {\n assertNoEmptyStringEnums(obj.items, toolName, [...path, \"[]\"]);\n }\n\n for (const k of [\"anyOf\", \"oneOf\", \"allOf\"]) {\n const arr = obj[k];\n if (Array.isArray(arr)) {\n arr.forEach((child, i) =>\n assertNoEmptyStringEnums(child, toolName, [...path, `${k}[${i}]`])\n );\n }\n }\n\n if (\n obj.additionalProperties &&\n typeof obj.additionalProperties === \"object\"\n ) {\n assertNoEmptyStringEnums(obj.additionalProperties, toolName, [\n ...path,\n \"additionalProperties\",\n ]);\n }\n}\n"],"mappings":";AAAA,SAAgB,yBACd,QACA,UACA,OAAiB,EAAE,EACb;AACN,KAAI,UAAU,QAAQ,OAAO,WAAW,SAAU;CAClD,MAAM,MAAM;AAEZ,KAAI,MAAM,QAAQ,IAAI,KAAK
|
|
1
|
+
{"version":3,"file":"validate_schema.js","names":[],"sources":["../../src/utils/validate_schema.ts"],"sourcesContent":["export function assertNoEmptyStringEnums(\n schema: unknown,\n toolName?: string,\n path: string[] = []\n): void {\n if (schema == null || typeof schema !== \"object\") return;\n const obj = schema as Record<string, unknown>;\n\n if (Array.isArray(obj.enum)) {\n if (obj.enum.some((v) => v === \"\")) {\n const pathStr = path.length ? ` at path \"${path.join(\".\")}\"` : \"\";\n const toolStr = toolName ? ` in tool \"${toolName}\"` : \"\";\n throw new Error(\n `Invalid enum: empty string not allowed${toolStr}${pathStr}. ` +\n \"Gemini API rejects empty strings in enums.\"\n );\n }\n }\n\n // Descend into common JSON Schema nests\n if (\n obj.type === \"object\" &&\n obj.properties &&\n typeof obj.properties === \"object\"\n ) {\n for (const [prop, child] of Object.entries(\n obj.properties as Record<string, unknown>\n )) {\n assertNoEmptyStringEnums(child, toolName, [...path, prop]);\n }\n }\n\n if (obj.items) {\n assertNoEmptyStringEnums(obj.items, toolName, [...path, \"[]\"]);\n }\n\n for (const k of [\"anyOf\", \"oneOf\", \"allOf\"]) {\n const arr = obj[k];\n if (Array.isArray(arr)) {\n arr.forEach((child, i) =>\n assertNoEmptyStringEnums(child, toolName, [...path, `${k}[${i}]`])\n );\n }\n }\n\n if (\n obj.additionalProperties &&\n typeof obj.additionalProperties === \"object\"\n ) {\n assertNoEmptyStringEnums(obj.additionalProperties, toolName, [\n ...path,\n \"additionalProperties\",\n ]);\n }\n}\n"],"mappings":";AAAA,SAAgB,yBACd,QACA,UACA,OAAiB,EAAE,EACb;AACN,KAAI,UAAU,QAAQ,OAAO,WAAW,SAAU;CAClD,MAAM,MAAM;AAEZ,KAAI,MAAM,QAAQ,IAAI,KAAK;MACrB,IAAI,KAAK,MAAM,MAAM,MAAM,GAAG,EAAE;GAClC,MAAM,UAAU,KAAK,SAAS,aAAa,KAAK,KAAK,IAAI,CAAC,KAAK;GAC/D,MAAM,UAAU,WAAW,aAAa,SAAS,KAAK;AACtD,SAAM,IAAI,MACR,yCAAyC,UAAU,QAAQ,8CAE5D;;;AAKL,KACE,IAAI,SAAS,YACb,IAAI,cACJ,OAAO,IAAI,eAAe,SAE1B,MAAK,MAAM,CAAC,MAAM,UAAU,OAAO,QACjC,IAAI,WACL,CACC,0BAAyB,OAAO,UAAU,CAAC,GAAG,MAAM,KAAK,CAAC;AAI9D,KAAI,IAAI,MACN,0BAAyB,IAAI,OAAO,UAAU,CAAC,GAAG,MAAM,KAAK,CAAC;AAGhE,MAAK,MAAM,KAAK;EAAC;EAAS;EAAS;EAAQ,EAAE;EAC3C,MAAM,MAAM,IAAI;AAChB,MAAI,MAAM,QAAQ,IAAI,CACpB,KAAI,SAAS,OAAO,MAClB,yBAAyB,OAAO,UAAU,CAAC,GAAG,MAAM,GAAG,EAAE,GAAG,EAAE,GAAG,CAAC,CACnE;;AAIL,KACE,IAAI,wBACJ,OAAO,IAAI,yBAAyB,SAEpC,0BAAyB,IAAI,sBAAsB,UAAU,CAC3D,GAAG,MACH,uBACD,CAAC"}
|
|
@@ -1,7 +1,6 @@
|
|
|
1
1
|
let _langchain_core_utils_types = require("@langchain/core/utils/types");
|
|
2
2
|
let _langchain_core_utils_json_schema = require("@langchain/core/utils/json_schema");
|
|
3
3
|
let _langchain_core_utils_standard_schema = require("@langchain/core/utils/standard_schema");
|
|
4
|
-
|
|
5
4
|
//#region src/utils/zod_to_genai_parameters.ts
|
|
6
5
|
function removeAdditionalProperties(obj) {
|
|
7
6
|
if (typeof obj === "object" && obj !== null) {
|
|
@@ -25,9 +24,9 @@ function jsonSchemaToGeminiParameters(schema) {
|
|
|
25
24
|
const { $schema, ...rest } = removeAdditionalProperties(schema);
|
|
26
25
|
return rest;
|
|
27
26
|
}
|
|
28
|
-
|
|
29
27
|
//#endregion
|
|
30
28
|
exports.jsonSchemaToGeminiParameters = jsonSchemaToGeminiParameters;
|
|
31
29
|
exports.removeAdditionalProperties = removeAdditionalProperties;
|
|
32
30
|
exports.schemaToGenerativeAIParameters = schemaToGenerativeAIParameters;
|
|
31
|
+
|
|
33
32
|
//# sourceMappingURL=zod_to_genai_parameters.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"zod_to_genai_parameters.cjs","names":[],"sources":["../../src/utils/zod_to_genai_parameters.ts"],"sourcesContent":["import {\n type FunctionDeclarationSchema as GenerativeAIFunctionDeclarationSchema,\n type SchemaType as FunctionDeclarationSchemaType,\n} from \"@google/generative-ai\";\nimport {\n InteropZodType,\n isInteropZodSchema,\n} from \"@langchain/core/utils/types\";\nimport {\n type JsonSchema7Type,\n toJsonSchema,\n} from \"@langchain/core/utils/json_schema\";\nimport {\n isSerializableSchema,\n SerializableSchema,\n} from \"@langchain/core/utils/standard_schema\";\n\nexport interface GenerativeAIJsonSchema extends Record<string, unknown> {\n properties?: Record<string, GenerativeAIJsonSchema>;\n type: FunctionDeclarationSchemaType;\n}\n\nexport interface GenerativeAIJsonSchemaDirty extends GenerativeAIJsonSchema {\n properties?: Record<string, GenerativeAIJsonSchemaDirty>;\n additionalProperties?: boolean;\n}\n\nexport function removeAdditionalProperties(\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n obj: Record<string, any>\n): GenerativeAIJsonSchema {\n if (typeof obj === \"object\" && obj !== null) {\n const newObj = { ...obj };\n\n if (\"additionalProperties\" in newObj) {\n delete newObj.additionalProperties;\n }\n if (\"$schema\" in newObj) {\n delete newObj.$schema;\n }\n if (\"strict\" in newObj) {\n delete newObj.strict;\n }\n\n for (const key in newObj) {\n if (key in newObj) {\n if (Array.isArray(newObj[key])) {\n newObj[key] = newObj[key].map(removeAdditionalProperties);\n } else if (typeof newObj[key] === \"object\" && newObj[key] !== null) {\n newObj[key] = removeAdditionalProperties(newObj[key]);\n }\n }\n }\n\n return newObj as GenerativeAIJsonSchema;\n }\n\n return obj as GenerativeAIJsonSchema;\n}\n\nexport function schemaToGenerativeAIParameters<\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n RunOutput extends Record<string, any> = Record<string, any>,\n>(\n schema:\n | SerializableSchema<RunOutput>\n | InteropZodType<RunOutput>\n | JsonSchema7Type\n): GenerativeAIFunctionDeclarationSchema {\n // GenerativeAI doesn't accept either the $schema or additionalProperties\n // attributes, so we need to explicitly remove them.\n const jsonSchema = removeAdditionalProperties(\n isInteropZodSchema(schema) || isSerializableSchema(schema)\n ? toJsonSchema(schema)\n : schema\n );\n const { $schema, ...rest } = jsonSchema;\n return rest as GenerativeAIFunctionDeclarationSchema;\n}\n\nexport function jsonSchemaToGeminiParameters(\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n schema: Record<string, any>\n): GenerativeAIFunctionDeclarationSchema {\n // Gemini doesn't accept either the $schema or additionalProperties\n // attributes, so we need to explicitly remove them.\n const jsonSchema = removeAdditionalProperties(\n schema as GenerativeAIJsonSchemaDirty\n );\n const { $schema, ...rest } = jsonSchema;\n\n return rest as GenerativeAIFunctionDeclarationSchema;\n}\n"],"mappings":"
|
|
1
|
+
{"version":3,"file":"zod_to_genai_parameters.cjs","names":[],"sources":["../../src/utils/zod_to_genai_parameters.ts"],"sourcesContent":["import {\n type FunctionDeclarationSchema as GenerativeAIFunctionDeclarationSchema,\n type SchemaType as FunctionDeclarationSchemaType,\n} from \"@google/generative-ai\";\nimport {\n InteropZodType,\n isInteropZodSchema,\n} from \"@langchain/core/utils/types\";\nimport {\n type JsonSchema7Type,\n toJsonSchema,\n} from \"@langchain/core/utils/json_schema\";\nimport {\n isSerializableSchema,\n SerializableSchema,\n} from \"@langchain/core/utils/standard_schema\";\n\nexport interface GenerativeAIJsonSchema extends Record<string, unknown> {\n properties?: Record<string, GenerativeAIJsonSchema>;\n type: FunctionDeclarationSchemaType;\n}\n\nexport interface GenerativeAIJsonSchemaDirty extends GenerativeAIJsonSchema {\n properties?: Record<string, GenerativeAIJsonSchemaDirty>;\n additionalProperties?: boolean;\n}\n\nexport function removeAdditionalProperties(\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n obj: Record<string, any>\n): GenerativeAIJsonSchema {\n if (typeof obj === \"object\" && obj !== null) {\n const newObj = { ...obj };\n\n if (\"additionalProperties\" in newObj) {\n delete newObj.additionalProperties;\n }\n if (\"$schema\" in newObj) {\n delete newObj.$schema;\n }\n if (\"strict\" in newObj) {\n delete newObj.strict;\n }\n\n for (const key in newObj) {\n if (key in newObj) {\n if (Array.isArray(newObj[key])) {\n newObj[key] = newObj[key].map(removeAdditionalProperties);\n } else if (typeof newObj[key] === \"object\" && newObj[key] !== null) {\n newObj[key] = removeAdditionalProperties(newObj[key]);\n }\n }\n }\n\n return newObj as GenerativeAIJsonSchema;\n }\n\n return obj as GenerativeAIJsonSchema;\n}\n\nexport function schemaToGenerativeAIParameters<\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n RunOutput extends Record<string, any> = Record<string, any>,\n>(\n schema:\n | SerializableSchema<RunOutput>\n | InteropZodType<RunOutput>\n | JsonSchema7Type\n): GenerativeAIFunctionDeclarationSchema {\n // GenerativeAI doesn't accept either the $schema or additionalProperties\n // attributes, so we need to explicitly remove them.\n const jsonSchema = removeAdditionalProperties(\n isInteropZodSchema(schema) || isSerializableSchema(schema)\n ? toJsonSchema(schema)\n : schema\n );\n const { $schema, ...rest } = jsonSchema;\n return rest as GenerativeAIFunctionDeclarationSchema;\n}\n\nexport function jsonSchemaToGeminiParameters(\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n schema: Record<string, any>\n): GenerativeAIFunctionDeclarationSchema {\n // Gemini doesn't accept either the $schema or additionalProperties\n // attributes, so we need to explicitly remove them.\n const jsonSchema = removeAdditionalProperties(\n schema as GenerativeAIJsonSchemaDirty\n );\n const { $schema, ...rest } = jsonSchema;\n\n return rest as GenerativeAIFunctionDeclarationSchema;\n}\n"],"mappings":";;;;AA2BA,SAAgB,2BAEd,KACwB;AACxB,KAAI,OAAO,QAAQ,YAAY,QAAQ,MAAM;EAC3C,MAAM,SAAS,EAAE,GAAG,KAAK;AAEzB,MAAI,0BAA0B,OAC5B,QAAO,OAAO;AAEhB,MAAI,aAAa,OACf,QAAO,OAAO;AAEhB,MAAI,YAAY,OACd,QAAO,OAAO;AAGhB,OAAK,MAAM,OAAO,OAChB,KAAI,OAAO;OACL,MAAM,QAAQ,OAAO,KAAK,CAC5B,QAAO,OAAO,OAAO,KAAK,IAAI,2BAA2B;YAChD,OAAO,OAAO,SAAS,YAAY,OAAO,SAAS,KAC5D,QAAO,OAAO,2BAA2B,OAAO,KAAK;;AAK3D,SAAO;;AAGT,QAAO;;AAGT,SAAgB,+BAId,QAIuC;CAQvC,MAAM,EAAE,SAAS,GAAG,SALD,4BAAA,GAAA,4BAAA,oBACE,OAAO,KAAA,GAAA,sCAAA,sBAAyB,OAAO,IAAA,GAAA,kCAAA,cACzC,OAAO,GACpB,OACL;AAED,QAAO;;AAGT,SAAgB,6BAEd,QACuC;CAMvC,MAAM,EAAE,SAAS,GAAG,SAHD,2BACjB,OACD;AAGD,QAAO"}
|
|
@@ -1,7 +1,6 @@
|
|
|
1
1
|
import { isInteropZodSchema } from "@langchain/core/utils/types";
|
|
2
2
|
import { toJsonSchema } from "@langchain/core/utils/json_schema";
|
|
3
3
|
import { isSerializableSchema } from "@langchain/core/utils/standard_schema";
|
|
4
|
-
|
|
5
4
|
//#region src/utils/zod_to_genai_parameters.ts
|
|
6
5
|
function removeAdditionalProperties(obj) {
|
|
7
6
|
if (typeof obj === "object" && obj !== null) {
|
|
@@ -25,7 +24,7 @@ function jsonSchemaToGeminiParameters(schema) {
|
|
|
25
24
|
const { $schema, ...rest } = removeAdditionalProperties(schema);
|
|
26
25
|
return rest;
|
|
27
26
|
}
|
|
28
|
-
|
|
29
27
|
//#endregion
|
|
30
28
|
export { jsonSchemaToGeminiParameters, removeAdditionalProperties, schemaToGenerativeAIParameters };
|
|
29
|
+
|
|
31
30
|
//# sourceMappingURL=zod_to_genai_parameters.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"zod_to_genai_parameters.js","names":[],"sources":["../../src/utils/zod_to_genai_parameters.ts"],"sourcesContent":["import {\n type FunctionDeclarationSchema as GenerativeAIFunctionDeclarationSchema,\n type SchemaType as FunctionDeclarationSchemaType,\n} from \"@google/generative-ai\";\nimport {\n InteropZodType,\n isInteropZodSchema,\n} from \"@langchain/core/utils/types\";\nimport {\n type JsonSchema7Type,\n toJsonSchema,\n} from \"@langchain/core/utils/json_schema\";\nimport {\n isSerializableSchema,\n SerializableSchema,\n} from \"@langchain/core/utils/standard_schema\";\n\nexport interface GenerativeAIJsonSchema extends Record<string, unknown> {\n properties?: Record<string, GenerativeAIJsonSchema>;\n type: FunctionDeclarationSchemaType;\n}\n\nexport interface GenerativeAIJsonSchemaDirty extends GenerativeAIJsonSchema {\n properties?: Record<string, GenerativeAIJsonSchemaDirty>;\n additionalProperties?: boolean;\n}\n\nexport function removeAdditionalProperties(\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n obj: Record<string, any>\n): GenerativeAIJsonSchema {\n if (typeof obj === \"object\" && obj !== null) {\n const newObj = { ...obj };\n\n if (\"additionalProperties\" in newObj) {\n delete newObj.additionalProperties;\n }\n if (\"$schema\" in newObj) {\n delete newObj.$schema;\n }\n if (\"strict\" in newObj) {\n delete newObj.strict;\n }\n\n for (const key in newObj) {\n if (key in newObj) {\n if (Array.isArray(newObj[key])) {\n newObj[key] = newObj[key].map(removeAdditionalProperties);\n } else if (typeof newObj[key] === \"object\" && newObj[key] !== null) {\n newObj[key] = removeAdditionalProperties(newObj[key]);\n }\n }\n }\n\n return newObj as GenerativeAIJsonSchema;\n }\n\n return obj as GenerativeAIJsonSchema;\n}\n\nexport function schemaToGenerativeAIParameters<\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n RunOutput extends Record<string, any> = Record<string, any>,\n>(\n schema:\n | SerializableSchema<RunOutput>\n | InteropZodType<RunOutput>\n | JsonSchema7Type\n): GenerativeAIFunctionDeclarationSchema {\n // GenerativeAI doesn't accept either the $schema or additionalProperties\n // attributes, so we need to explicitly remove them.\n const jsonSchema = removeAdditionalProperties(\n isInteropZodSchema(schema) || isSerializableSchema(schema)\n ? toJsonSchema(schema)\n : schema\n );\n const { $schema, ...rest } = jsonSchema;\n return rest as GenerativeAIFunctionDeclarationSchema;\n}\n\nexport function jsonSchemaToGeminiParameters(\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n schema: Record<string, any>\n): GenerativeAIFunctionDeclarationSchema {\n // Gemini doesn't accept either the $schema or additionalProperties\n // attributes, so we need to explicitly remove them.\n const jsonSchema = removeAdditionalProperties(\n schema as GenerativeAIJsonSchemaDirty\n );\n const { $schema, ...rest } = jsonSchema;\n\n return rest as GenerativeAIFunctionDeclarationSchema;\n}\n"],"mappings":"
|
|
1
|
+
{"version":3,"file":"zod_to_genai_parameters.js","names":[],"sources":["../../src/utils/zod_to_genai_parameters.ts"],"sourcesContent":["import {\n type FunctionDeclarationSchema as GenerativeAIFunctionDeclarationSchema,\n type SchemaType as FunctionDeclarationSchemaType,\n} from \"@google/generative-ai\";\nimport {\n InteropZodType,\n isInteropZodSchema,\n} from \"@langchain/core/utils/types\";\nimport {\n type JsonSchema7Type,\n toJsonSchema,\n} from \"@langchain/core/utils/json_schema\";\nimport {\n isSerializableSchema,\n SerializableSchema,\n} from \"@langchain/core/utils/standard_schema\";\n\nexport interface GenerativeAIJsonSchema extends Record<string, unknown> {\n properties?: Record<string, GenerativeAIJsonSchema>;\n type: FunctionDeclarationSchemaType;\n}\n\nexport interface GenerativeAIJsonSchemaDirty extends GenerativeAIJsonSchema {\n properties?: Record<string, GenerativeAIJsonSchemaDirty>;\n additionalProperties?: boolean;\n}\n\nexport function removeAdditionalProperties(\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n obj: Record<string, any>\n): GenerativeAIJsonSchema {\n if (typeof obj === \"object\" && obj !== null) {\n const newObj = { ...obj };\n\n if (\"additionalProperties\" in newObj) {\n delete newObj.additionalProperties;\n }\n if (\"$schema\" in newObj) {\n delete newObj.$schema;\n }\n if (\"strict\" in newObj) {\n delete newObj.strict;\n }\n\n for (const key in newObj) {\n if (key in newObj) {\n if (Array.isArray(newObj[key])) {\n newObj[key] = newObj[key].map(removeAdditionalProperties);\n } else if (typeof newObj[key] === \"object\" && newObj[key] !== null) {\n newObj[key] = removeAdditionalProperties(newObj[key]);\n }\n }\n }\n\n return newObj as GenerativeAIJsonSchema;\n }\n\n return obj as GenerativeAIJsonSchema;\n}\n\nexport function schemaToGenerativeAIParameters<\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n RunOutput extends Record<string, any> = Record<string, any>,\n>(\n schema:\n | SerializableSchema<RunOutput>\n | InteropZodType<RunOutput>\n | JsonSchema7Type\n): GenerativeAIFunctionDeclarationSchema {\n // GenerativeAI doesn't accept either the $schema or additionalProperties\n // attributes, so we need to explicitly remove them.\n const jsonSchema = removeAdditionalProperties(\n isInteropZodSchema(schema) || isSerializableSchema(schema)\n ? toJsonSchema(schema)\n : schema\n );\n const { $schema, ...rest } = jsonSchema;\n return rest as GenerativeAIFunctionDeclarationSchema;\n}\n\nexport function jsonSchemaToGeminiParameters(\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n schema: Record<string, any>\n): GenerativeAIFunctionDeclarationSchema {\n // Gemini doesn't accept either the $schema or additionalProperties\n // attributes, so we need to explicitly remove them.\n const jsonSchema = removeAdditionalProperties(\n schema as GenerativeAIJsonSchemaDirty\n );\n const { $schema, ...rest } = jsonSchema;\n\n return rest as GenerativeAIFunctionDeclarationSchema;\n}\n"],"mappings":";;;;AA2BA,SAAgB,2BAEd,KACwB;AACxB,KAAI,OAAO,QAAQ,YAAY,QAAQ,MAAM;EAC3C,MAAM,SAAS,EAAE,GAAG,KAAK;AAEzB,MAAI,0BAA0B,OAC5B,QAAO,OAAO;AAEhB,MAAI,aAAa,OACf,QAAO,OAAO;AAEhB,MAAI,YAAY,OACd,QAAO,OAAO;AAGhB,OAAK,MAAM,OAAO,OAChB,KAAI,OAAO;OACL,MAAM,QAAQ,OAAO,KAAK,CAC5B,QAAO,OAAO,OAAO,KAAK,IAAI,2BAA2B;YAChD,OAAO,OAAO,SAAS,YAAY,OAAO,SAAS,KAC5D,QAAO,OAAO,2BAA2B,OAAO,KAAK;;AAK3D,SAAO;;AAGT,QAAO;;AAGT,SAAgB,+BAId,QAIuC;CAQvC,MAAM,EAAE,SAAS,GAAG,SALD,2BACjB,mBAAmB,OAAO,IAAI,qBAAqB,OAAO,GACtD,aAAa,OAAO,GACpB,OACL;AAED,QAAO;;AAGT,SAAgB,6BAEd,QACuC;CAMvC,MAAM,EAAE,SAAS,GAAG,SAHD,2BACjB,OACD;AAGD,QAAO"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@langchain/google-genai",
|
|
3
|
-
"version": "2.1.
|
|
3
|
+
"version": "2.1.26-dev-1773698445534",
|
|
4
4
|
"description": "Google Generative AI integration for LangChain.js",
|
|
5
5
|
"author": "LangChain",
|
|
6
6
|
"license": "MIT",
|
|
@@ -18,25 +18,20 @@
|
|
|
18
18
|
"uuid": "^11.1.0"
|
|
19
19
|
},
|
|
20
20
|
"peerDependencies": {
|
|
21
|
-
"@langchain/core": "^1.1.
|
|
21
|
+
"@langchain/core": "^1.1.33-dev-1773698445534"
|
|
22
22
|
},
|
|
23
23
|
"devDependencies": {
|
|
24
|
-
"@jest/globals": "^30.2.0",
|
|
25
|
-
"@swc/core": "^1.15.18",
|
|
26
|
-
"@swc/jest": "^0.2.29",
|
|
27
24
|
"@tsconfig/recommended": "^1.0.3",
|
|
28
25
|
"dotenv": "^16.3.1",
|
|
29
26
|
"dpdm": "^3.14.0",
|
|
30
27
|
"eslint": "^9.34.0",
|
|
31
28
|
"hnswlib-node": "^3.0.0",
|
|
32
|
-
"jest": "^30.2.0",
|
|
33
|
-
"jest-environment-node": "^30.2.0",
|
|
34
29
|
"prettier": "^3.5.0",
|
|
35
|
-
"ts-jest": "^29.4.6",
|
|
36
30
|
"typescript": "~5.8.3",
|
|
31
|
+
"vitest": "^3.2.4",
|
|
37
32
|
"zod": "^3.25.76",
|
|
38
|
-
"@langchain/core": "^1.1.32",
|
|
39
33
|
"@langchain/eslint": "0.1.1",
|
|
34
|
+
"@langchain/core": "^1.1.33-dev-1773698445534",
|
|
40
35
|
"@langchain/standard-tests": "0.0.23",
|
|
41
36
|
"@langchain/tsconfig": "0.0.1"
|
|
42
37
|
},
|
|
@@ -74,12 +69,12 @@
|
|
|
74
69
|
"lint": "pnpm lint:eslint && pnpm lint:dpdm",
|
|
75
70
|
"lint:fix": "pnpm lint:eslint --fix && pnpm lint:dpdm",
|
|
76
71
|
"clean": "rm -rf .turbo dist/",
|
|
77
|
-
"test": "
|
|
78
|
-
"test:watch": "
|
|
79
|
-
"test:single": "
|
|
80
|
-
"test:int": "
|
|
81
|
-
"test:standard:unit": "
|
|
82
|
-
"test:standard:int": "
|
|
72
|
+
"test": "vitest run",
|
|
73
|
+
"test:watch": "vitest",
|
|
74
|
+
"test:single": "vitest run",
|
|
75
|
+
"test:int": "vitest run --mode int",
|
|
76
|
+
"test:standard:unit": "vitest run --mode standard-unit",
|
|
77
|
+
"test:standard:int": "vitest run --mode standard-int",
|
|
83
78
|
"test:standard": "pnpm test:standard:unit && pnpm test:standard:int",
|
|
84
79
|
"format": "prettier --write \"src\"",
|
|
85
80
|
"format:check": "prettier --check \"src\"",
|