LangChain google-common:Google 模型接入的认证无关公共基础设施解析
2026/9/13 20:13:31 网站建设 项目流程

LangChain google-common:Google 模型接入的认证无关公共基础设施解析

【免费下载链接】langchainjsThe agent engineering platform项目地址: https://gitcode.com/GitHub_Trending/la/langchainjs

@langchain/google-common 是 LangChain.js 生态中面向 Google AI/ML 模型与 Google 服务的认证无关(auth-independent)公共基础包。它统一了 Google AI Studio(Generative AI)与 Google Cloud Vertex AI 两条模型服务链路,让同一套 LLM / Chat / Embeddings 接口可以无差别地切换底层平台。读完本文,你将理解该包的定位与安装方式、其"零 Google 官方依赖、纯 REST 调用"的设计取舍、Gemini 模型(含函数/工具调用)的双平台支持机制,以及使用 Zod 定义工具 Schema 时必须规避的三类限制与替代写法。

包定位:不是独立包,而是公共底座

这个包不是一个可独立安装使用的包,因为 README.md 明确说明它"不包含任何做授权(authorization)的代码"。它的职责是提供访问 Google AI/ML 模型及其他 Google 服务时与认证方式无关的公共资源,而具体怎么拿凭证、怎么签名请求,交给上层认证包负责。

实际的安装路径是二选一:

  • @langchain/google-gauth:面向服务端,基于 Google Cloud 服务账号 / ADC(Application Default Credentials)的认证;
  • @langchain/google-webauth:面向浏览器 / Web 场景,基于 OAuth 的认证。

安装示例如下(以 gauth 为例):

npm install @langchain/google-gauth # 或 pnpm add @langchain/google-gauth # 或 yarn add @langchain/google-gauth

两个包的认证细节请分别参阅各自文档;google-common 会在运行时被它们作为依赖引入,无需手动安装。

从源码视角看,认证与业务被刻意解耦:GoogleAbstractedClient接口只暴露request()getProjectId()clientType三个能力(见 src/auth.ts),上层模型类完全面向该接口编程,不关心底层是 API Key 直连还是 OAuth 令牌。接口之下还提供了一个基于原生fetch的参考实现GoogleAbstractedFetchClient,并内置了ApiKeyGoogleAuth这一现成的 API Key 客户端——它会自动在请求头注入X-Goog-Api-KeyclientType属性对平台判定至关重要:ChatGoogleBase.buildClient()的逻辑是"优先使用apiKey/GOOGLE_API_KEY环境变量构造 API Key 客户端,否则回退到抽象的buildAbstractedClient()走认证包"(见 src/chat_models.ts)。

设计核心:不依赖任何 Google 官方库,纯 REST 调用

README 强调了一个关键设计决策:本包不依赖任何 Google 官方库(如@google/generative-ai或 Google Cloud 客户端库),而是直接向 Google 端点发起 REST 调用。原因有二:

  1. 减少(有时相互冲突的)依赖——不同 Google 库之间存在传递依赖版本冲突,抽掉它们能让依赖树更干净;
  2. 可在无文件系统的平台上运行——Google 官方 SDK 往往依赖本地文件缓存/凭证文件读取,纯 REST 实现规避了这些环境假设。

这一点在package.json中可验证:依赖列表里只有@langchain/core作为 peer dependency,以及 TypeScript、Vitest、Zod 等开发依赖(见 package.json),没有任何google-*运行时依赖。engines字段要求node >= 20(package.json),因为实现依赖全局fetch

请求层实现

所有 REST 请求都经过GoogleConnection家族(src/connection.ts),其核心职责是:

  • 组装 URL、HTTP 方法与请求头;
  • 通过AsyncCaller(来自@langchain/core/utils/async_caller)执行调用,自动获得重试、并发限制等能力;
  • 根据streaming标志决定responseTypestream还是json

URL 的构建逻辑揭示了双平台的本质差异(src/connection.ts):

  • AI Studio(gai 平台)https://generativelanguage.googleapis.com/{apiVersion}/models/{model}:{method}
  • Vertex AI(gcp 平台)https://{endpoint}/{apiVersion}/projects/{projectId}/locations/{location}/publishers/{publisher}/models/{model}:{method},其中端点根据location自动推导,例如us-central1对应us-central1-aiplatform.googleapis.com(src/connection.ts);
  • API 版本也按平台区分:AI Studio 默认v1beta,Vertex 默认v1(src/connection.ts)。

平台与认证方式之间存在一个自动推断规则(src/connection.ts):若当前客户端是 API Key 类型则推断为gai,否则推断为gcp。因此,只配置GOOGLE_API_KEY时会自动走 AI Studio,只有配置了完整 Google Cloud 凭证时才走 Vertex。若你的环境特殊(例如 GCP 上也想用 API Key 直连),可以通过platformTypevertexai: true/false显式指定平台——platformType优先级更高(见 src/types.ts)。

调用方还可以通过自定义事件观测请求/响应全流程:GoogleRequestCallbackHandler及其现成实现GoogleRequestLoggerGoogleRequestRecorder会订阅google-request-*/google-response-*/google-chunk-*事件,便于调试与流量录制(src/connection.ts)。

已支持的 Google 服务

README 列出的已支持能力目前聚焦于:

  • Gemini 模型,通过 LLM 类和 Chat 类访问,同时覆盖 Google AI Studio 与 Google Cloud Vertex AI 两个平台
  • 其中 Chat 类支持Function/Tool(函数/工具调用)

从包根入口 src/index.ts 可以看到对应的导出面:chat_modelsllmsembeddingsoutput_parsersauthconnectiontypes以及一组utils(stream、common、safety、zod_to_gemini_parameters 等)。

双平台统一接口的实现方式

"同一接口、两个平台"并非简单的文档承诺,而是代码层面的工程结果。以聊天模型为例,ChatGoogleBase(src/chat_models.ts)在构造时通过buildClient()选择客户端,然后在buildConnection()中同时创建两个连接实例connection(非流式)与streamedConnection(流式)(src/chat_models.ts)。当streaming: true时,_generate会把_streamResponseChunks的输出逐个 chunk 合并成最终结果(src/chat_models.ts),从而让"流式"和"非流式"对调用方表现一致。

嵌入模型同理:EmbeddingsConnection根据平台选择不同的端点方法——AI Studio 走embedContent,Vertex 走predict,并各自格式化请求体(src/embeddings.ts)。

值得注意的细节:ChatGoogleBase对 system 指令的使用做了精细的模型兼容判断(src/chat_models.ts),例如gemini-1.0-pro-001gemini-pro-vision*、Gemma 系列等模型不支持 system instruction,会退化为把 system 消息转成 human 内容;也可以通过convertSystemMessageToHumanContent手动控制。

工具/函数调用支持

ChatGoogleBase重写了bindTools(),将工具列表经convertToGeminiTools()转换后以tools配置注入调用选项(src/chat_models.ts)。工具 Schema 的转换核心在 src/utils/zod_to_gemini_parameters.ts:Zod / JSON Schema 会被翻译成 Gemini 的FunctionDeclaration格式,这正与下面要讲的 Schema 限制直接相关。

已知限制:工具/函数 Schema 的 Zod 兼容性

这是 README 中最需要开发者注意的部分。使用 Gemini 模型的工具/函数时,以下 Zod Schema 特性不受支持

Zod 特性限制说明推荐替代方案
z.discriminatedUnion()(判别联合)不支持,转换时直接抛错改用带可选字段的扁平对象
z.union()(普通联合类型)不支持,转换时直接抛错拆成多个可选字段
z.number().positive()(正数约束)不直接支持,会被自动改写为z.number().min(0.01)接受自动转换,或显式写min

底层原理:Schema 转换器如何处置这些特性

在 src/utils/zod_to_gemini_parameters.ts 中,schemaToGeminiParameters()会先做一系列归一化:

  1. 删除$schemaadditionalProperties:Gemini API 不接受这两个属性;
  2. 展平可空联合:对T \| null这种双元素联合(如z.string().nullable()),会提取非 null 类型并把nullable置为true
  3. 拒绝真正的联合:对非简单可空形式的anyOf/oneOf(即z.union()z.discriminatedUnion()的产物),直接抛出错误"Gemini cannot handle union types (discriminatedUnion, anyOf, oneOf). Consider using a flat object structure with optional fields instead."
  4. 改写正数约束:将exclusiveMinimum: 0(来自.positive())转换为minimum: 0.01,其他exclusiveMinimum则换算为minimum = exclusiveMinimum + 0.00001
  5. 清理 type 数组:把 Zod 因.nullish()产生的type数组规整为字符串。

上述行为全部有测试用例背书,见 src/tests/zod_to_gemini_parameters.test.ts 与 src/tests/utils.test.ts:

  • discriminatedUnion会抛错,错误信息提示改用扁平对象(zod_to_gemini_parameters.test.ts#L156-L167);
  • z.union([z.string(), z.number()])抛同样的 union 错误(utils.test.ts#L401-L409);
  • .positive()被转换为minimum: 0.01且不含exclusiveMinimum(zod_to_gemini_parameters.test.ts#L32-L49);
  • 可空(nullable)、可选(optional)、可空可选(nullish)的标量与对象字段则能正确转换为nullable: true或从required中剔除(zod_to_gemini_parameters.test.ts#L73-L154)。

实战写法:反面示例与正确姿势

反面示例(会抛错)——使用判别联合定义工具参数:

import { z } from "zod"; import { schemaToGeminiParameters } from "@langchain/google-common/utils/zod_to_gemini_parameters"; const badSchema = z.object({ expiration: z.discriminatedUnion("type", [ z.object({ type: z.literal("relative"), relativeSeconds: z.number().positive().describe("从现在到过期的秒数"), }), z.object({ type: z.literal("exact"), exactDate: z.string().describe("ISO 8601 格式的精确过期时间"), }), ]), }); // 运行时抛出:Gemini cannot handle union types ... schemaToGeminiParameters(badSchema);

正确姿势——使用带可选字段的扁平对象:

import { z } from "zod"; import { schemaToGeminiParameters } from "@langchain/google-common/utils/zod_to_gemini_parameters"; const goodSchema = z.object({ type: z.enum(["relative", "exact"]).describe("过期方式"), relativeSeconds: z .number() .min(0.01) .optional() .describe("相对过期秒数(type 为 relative 时使用)"), exactDate: z .string() .optional() .describe("ISO 8601 精确过期时间(type 为 exact 时使用)"), }); // 正常转换,可直接作为 Gemini 工具 Schema 使用 const geminiParams = schemaToGeminiParameters(goodSchema);
// 正数约束的自动改写示例: // z.number().positive() 在转换后等价于: // { type: "number", minimum: 0.01 } const priceSchema = z.object({ price: z.number().positive().describe("商品价格"), }); // 转换结果中 price 为 { type: "number", minimum: 0.01 }

更完整的示例与 Workaround 说明,请参阅 @langchain/google-vertexai 或 @langchain/google-genai 包文档中的 "Tool Schema Limitations" 一节。

计划中的功能(Planned Features)

README 同时披露了未来可能实现的任务与服务清单,可作为选型与路线图参考:

  • Gemini embeddings(Gemini 嵌入模型支持)
  • Multimodal embeddings(多模态嵌入)
  • Vertex AI Search(检索服务)
  • Vertex AI Model Garden
    • 在线预测端点(Online prediction endpoints):Gemma
    • Google 托管模型(Google managed models):Claude
  • AI Studio Tuned Models(微调模型支持)
  • Google Cloud Vector Store(向量存储)

需要说明的是,以上属于"未来计划",当前仓库源码中尚未实现,不应在业务中依赖。其中 Gemini embeddings 目前仓库已有部分嵌入基础能力(EmbeddingsConnection已按 AI Studio / Vertex 双平台实现端点分发),但 README 将其列为规划项,说明完整的 Gemini 嵌入模型接入仍待落地。

进一步阅读

  • 包总览:README.md
  • 包元数据与导出面:package.json、src/index.ts
  • 认证抽象与 API Key 客户端:src/auth.ts
  • 连接与 URL 构建(双平台路由核心):src/connection.ts
  • 聊天模型基类(含工具绑定、流式合并、system 指令兼容):src/chat_models.ts
  • 嵌入模型双平台实现:src/embeddings.ts
  • Zod Schema 转换与限制实现:src/utils/zod_to_gemini_parameters.ts
  • 限制行为测试用例:src/tests/zod_to_gemini_parameters.test.ts、src/tests/utils.test.ts
  • 上层认证包:langchain-google-gauth、langchain-google-webauth

总结

@langchain/google-common 是理解 LangChain.js Google 集成体系的一把钥匙:它通过"认证无关的接口抽象 + 零 Google 官方依赖的纯 REST 调用 + 平台自动推断"三件事,把 AI Studio 与 Vertex AI 的差异收敛到了极小的范围。对开发者而言,最需要记住的三点是:不要直接安装它(应装 gauth 或 webauth)、API Key 与 Cloud 凭证会决定默认平台(必要时显式设置platformType)、以及为 Gemini 写工具 Schema 时避开判别联合/联合类型,正数约束交给自动改写

【免费下载链接】langchainjsThe agent engineering platform项目地址: https://gitcode.com/GitHub_Trending/la/langchainjs

创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考

需要专业的网站建设服务?

联系我们获取免费的网站建设咨询和方案报价,让我们帮助您实现业务目标

立即咨询