ARTICLE DETAIL

资讯详情

深耕郑州网站建设与运营推广的一线实战洞察。

LangChain google-webauth 集成指南:以 API Key 与 Web 凭据访问 Google AI 服务

LangChain google-webauth 集成指南:以 API Key 与 Web 凭据访问 Google AI 服务 LangChain google-webauth 集成指南以 API Key 与 Web 凭据访问 Google AI 服务【免费下载链接】langchainjsThe agent engineering platform项目地址: https://gitcode.com/GitHub_Trending/la/langchainjs本文围绕 langchain-google-webauth 包展开讲解如何在无法使用文件系统凭据的环境中通过 API Key 或内嵌在环境变量中的 Service Account 凭据在 LangChain.js 中调用 Google AI/ML 模型如 Gemini 系列与其他 Google 服务。读完本文你将掌握该包的安装、完整的凭据解析优先级、ChatGoogle/GoogleLLM/GoogleEmbeddings的接入方法以及它与langchain/google-gauth的选型差异。包定位为无文件系统凭据的场景而生langchain/google-webauth是 LangChain.js 官方提供的一个 Google 服务集成包位于 libs/providers/langchain-google-webauth其作用是以 Web 方式完成 Google 服务的认证。与传统的google-auth-library文件凭据方式不同本包面向无法在本地文件系统存放 Service Account 凭据的运行环境——例如无服务器函数、浏览器端受限运行时、CDN Edge 环境等凭据以 API Key 或编码后的凭据字符串形式直接注入。从源码结构看该包是一个薄适配层核心的模型封装逻辑全部复用langchain/google-common本包仅负责认证层的差异。其入口 src/index.ts 统一导出chat_models、llms、embeddings三个模块认证核心位于 src/auth.ts提供了WebGoogleAuth客户端。package.json中声明其依赖为langchain/google-common与web-auth-library运行环境要求 Node.js 20。安装在 pnpm 工作区或普通 Node.js 项目中执行$ pnpm install langchain/google-webauth包以 ESM/CJS 双格式发布type: modulemain指向dist/index.cjsexports同时提供require与import入口并额外暴露了./types与./utils子路径对应 src/types.ts 与 src/utils.ts二者直接转发langchain/google-common的类型与工具函数。授权方式五级凭据解析优先级langchain/google-webauth的授权要么使用 API Key如果目标服务支持要么使用 Google Cloud Service Account。README 明确给出凭据解析的优先级顺序从上到下依次尝试命中即用通过构造函数apiKey属性传入的 API Key通过构造函数authInfo属性传入的凭据即authOptions中的credentials环境变量API_KEY中设置的 API Key直接保存在环境变量GOOGLE_WEB_CREDENTIALS中的 Service Account 凭据直接保存在环境变量GOOGLE_VERTEX_AI_WEB_CREDENTIALS中的 Service Account 凭据已弃用仅作兼容。README 中说明服务账号凭据的处理基于google-auth-library从当前仓库源码看实际实现引入了web-auth-library/google的getAccessToken、getCredentials与Credentials类型来完成令牌获取与解析见 src/auth.ts。源码级解读凭据是如何被解析的src/auth.ts 中WebGoogleAuth的构造函数完整实现了上述优先级关键逻辑如下const accessToken options?.accessToken; const credentials options?.credentials ?? getEnvironmentVariable(GOOGLE_WEB_CREDENTIALS) ?? getEnvironmentVariable(GOOGLE_VERTEX_AI_WEB_CREDENTIALS); if (credentials undefined) throw new Error( Credentials not found. Please set the GOOGLE_WEB_CREDENTIALS environment variable or pass credentials into authOptions.credentials. );几点值得注意的实现细节优先级实际顺序构造函数参数authOptions.credentials优先于GOOGLE_WEB_CREDENTIALS后者又优先于已弃用的GOOGLE_VERTEX_AI_WEB_CREDENTIALS。API Key 的解析由langchain/google-common的基类统一处理apiKey属性与环境变量API_KEY最终在WebGoogleAuth中聚合。作用域规范化ensureAuthOptionScopes会根据platformType自动补齐 OAuth scope。令牌获取request()方法中若未显式提供accessToken则调用getAccessToken(this.options)获取 Bearer Token再以Authorization: Bearer token请求头发送请求。项目 ID 解析getProjectId()从凭据对象中读取project_id字段供 Vertex AI 等需要项目信息的服务使用。WebGoogleAuthOptions的可选字段包括字段类型说明credentialsstring \| CredentialsService Account 凭据JSON 字符串或解析后的对象scopestring \| string[]OAuth 作用域可由platformType自动补全accessTokenstring预取好的访问令牌提供后跳过自动获取responseModalitystring响应模态配置快速上手三种模型封装本包通过继承langchain/google-common的基类提供了三个可直接实例化的模型类三者都通过buildAbstractedClient()返回WebGoogleAuth实例作为底层认证客户端。1. 对话模型 ChatGoogleimport { ChatGoogle } from langchain/google-webauth; // 方式一字符串模型名 字段 const model new ChatGoogle(gemini-1.5-flash-002, { apiKey: your-api-key, // 或设置环境变量 API_KEY }); // 方式二纯字段对象 const model2 new ChatGoogle({ modelName: gemini-2.0-flash-001, authOptions: { credentials: process.env.GOOGLE_WEB_CREDENTIALS, }, }); const res await model.invoke(What is 1 1?);ChatGoogle定义于 src/chat_models.ts同时支持invoke、stream、bindTools、withStructuredOutput等标准能力。2. 补全模型 GoogleLLMimport { GoogleLLM } from langchain/google-webauth; const llm new GoogleLLM({ model: gemini-1.5-pro-002, apiKey: your-api-key, }); const res await llm.invoke(Explain quantum computing in one sentence.);GoogleLLM定义于 src/llms.ts其lc_serializable true可参与 LangChain 的序列化/持久化流程。3. 嵌入模型 GoogleEmbeddingsimport { GoogleEmbeddings } from langchain/google-webauth; const embeddings new GoogleEmbeddings({ model: text-embedding-004, apiKey: your-api-key, }); const vectors await embeddings.embedDocuments([Hello world]);GoogleEmbeddings定义于 src/embeddings.ts同样标记为可序列化。平台类型与 API 版本GAI 与 GCP 双通道从集成测试 src/tests/chat_models.int.test.ts 可以看到ChatGoogle支持两种平台类型通过platformType与apiVersion控制请求端点platformTypeAPI 版本请求端点测试断言gaiGoogle AI Studio / Generative Language APIv1betahttps://generativelanguage.googleapis.comgcpGoogle Cloud Vertex AIv1https://region-aiplatform.googleapis.comimport { ChatGoogle } from langchain/google-webauth; // Google AI Studio 通道 const gai new ChatGoogle({ modelName: gemini-2.5-flash, platformType: gai, apiVersion: v1beta, apiKey: process.env.TEST_API_KEY, }); // Vertex AI 通道 const gcp new ChatGoogle({ modelName: gemini-2.5-flash, platformType: gcp, apiVersion: v1, });测试中还覆盖了gemini-1.5-pro-002、gemini-1.5-flash-002、gemini-2.0-flash-001、gemini-2.0-flash-lite-001、gemini-2.5-flash、gemini-2.5-pro、gemini-2.5-flash-lite-preview-06-17、gemma-3-27b-it、gemma-3n-e4b-it等模型见测试文件第 71-81 行与 447-506 行可作为模型名参考。媒体能力与实验性 BlobStore除文本外该包还通过 src/media.ts 提供两个实验性的媒体存储类BlobStoreGoogleCloudStorage基于 GCSgs://URI的媒体 Blob 存储继承自langchain/google-common/experimental/media中的BlobStoreGoogleCloudStorageBaseBlobStoreAIStudioFile对接 Google AI Studio 文件管理的存储实现。两者均以WebGoogleAuth作为认证客户端。集成测试验证了多模态输入能力image_url类型的 base64 图片消息可以被模型识别测试使用src/tests/data/blue-square.png并断言响应包含 blue 且usage_metadata.input_token_details.image大于 0视频输入rainbow.mp4与隐式缓存cache_readtoken也有对应用例参见 chat_models.int.test.ts。测试验证与可用性证据包的 package.json 提供了完整的测试脚本pnpm test运行单元/非集成测试pnpm test:int运行需要真实凭据的集成测试*.int.test.ts通过TEST_API_KEY等环境变量注入密钥test:single用于单测调试。集成测试覆盖的能力包括invoke/generate/predictMessages基础调用流式输出stream与streamUsage开关、构造参数streaming: true工具调用bindTools、强制工具选择tool_choice、工具多轮对话function conversationwithStructuredOutput结构化输出含 nullable 字段 schemausage_metadata中input_tokens/output_tokens/total_tokens及 token 明细的统计校验。与 google-gauth 的选型对比这是 README 特别强调的一点不要在同一个项目中同时使用langchain/google-gauth与本包二者互斥择一即可。如果你的应用运行在 Google Cloud Platform 上或者运行环境允许将 Service Account 凭据以文件形式保存在本地文件系统通过GOOGLE_APPLICATION_CREDENTIALS环境变量指定路径或者已通过gcloud auth application-default login登录那么应改用 langchain/google-gauth它支持默认凭据与应用默认凭据ADC链路无需显式管理凭据字符串如果你的环境无法提供文件系统凭据如无服务器、Edge、受限容器等则使用本包langchain/google-webauth将 API Key 或 Service Account 凭据直接写入环境变量。简言之google-gauth 面向凭据在文件/环境中可被发现的云原生场景google-webauth 面向凭据必须以字符串显式注入的受限场景。二者对外的模型类 API 保持一致切换成本极低。常见问题与注意事项凭据缺失时报错如果既未在authOptions.credentials传入凭据也未设置GOOGLE_WEB_CREDENTIALS或旧版GOOGLE_VERTEX_AI_WEB_CREDENTIALSWebGoogleAuth构造时会直接抛出Credentials not found异常错误信息会明确提示应设置的环境变量名见 src/auth.ts。API Key 与环境变量优先在构造函数传入apiKey否则读取API_KEY环境变量Service Account 场景请务必使用GOOGLE_WEB_CREDENTIALS而非已弃用的旧变量名。scope 自动补全platformType会影响 OAuth scope 的自动装配多服务混用时可通过authOptions.scope显式覆盖。Node 版本本包要求 Node.js 20见 package.json 的engines字段。通过以上配置你可以将 Google 的 Gemini、Gemma 系列模型与 Embedding 能力稳定接入 LangChain.js 应用同时让凭据管理完全适配无文件系统的 Web 化部署环境。【免费下载链接】langchainjsThe agent engineering platform项目地址: https://gitcode.com/GitHub_Trending/la/langchainjs创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考
返回列表