Langchain部署至Firebase Function报错问题求助
LangChain部署Firebase Functions报错排查及解决
问题概述
将基于LangChain的函数部署到Firebase Functions时持续出现编译错误:
- 使用TypeScript 4.9.0时,出现3个错误:找不到名称'this'、ChatOpenAI类型无法匹配RunnableLike参数
- 升级至TypeScript 5后,出现IterableReadableStreamInterface接口冲突的新错误
当前使用LangChain ^0.1.18,相关配置及代码如下。
一、TypeScript 4.9.0时的错误信息
node_modules/@langchain/openai/node_modules/@langchain/core/dist/language_models/chat_models.d.ts:64:129 - error TS2304: Cannot find name 'this'. 64 _generateCached({ messages, cache, llmStringKey, parsedOptions, handledOptions, }: ChatModelGenerateCachedParameters<typeof this>): Promise<LLMResult & { ~~~~ node_modules/@langchain/openai/node_modules/@langchain/core/dist/language_models/llms.d.ts:66:122 - error TS2304: Cannot find name 'this'. 66 _generateCached({ prompts, cache, llmStringKey, parsedOptions, handledOptions, }: LLMGenerateCachedParameters<typeof this>): Promise<LLMResult & { ~~~~ src/index.ts:36:31 - error TS2345: Argument of type 'ChatOpenAI<ChatOpenAICallOptions>' is not assignable to parameter of type 'RunnableLike<ChatPromptValueInterface, BaseMessageChunk>'. Type 'ChatOpenAI<ChatOpenAICallOptions>' is missing the following properties from type 'RunnableMapLike<ChatPromptValueInterface, BaseMessageChunk>': concat, text, content, additional_kwargs, and 3 more. 36 const chain = prompt.pipe(chatModel).pipe(outputParser); ~~~~~~~~~ Found 3 errors in 3 files. Errors Files 1 node_modules/@langchain/openai/node_modules/@langchain/core/dist/language_models/chat_models.d.ts:64 1 node_modules/@langchain/openai/node_modules/@langchain/core/dist/language_models/llms.d.ts:66 1 src/index.ts:36 Error: functions predeploy error: Command terminated with non-zero exit code 2
相关配置及代码
tsconfig.json
{ "compilerOptions": { "module": "NodeNext", "noImplicitReturns": true, "noUnusedLocals": true, "outDir": "lib", "sourceMap": true, "strict": true, "target": "ES2020", "esModuleInterop": true, "moduleResolution": "node" }, "compileOnSave": true, "include": ["src"] }
package.json
{ "name": "functions", "scripts": { "build": "tsc", "build:watch": "tsc --watch", "serve": "npm run build && firebase emulators:start --only functions", "shell": "npm run build && firebase functions:shell", "start": "npm run shell", "deploy": "firebase deploy --only functions", "logs": "firebase functions:log" }, "engines": { "node": "20" }, "main": "lib/index.js", "dependencies": { "@langchain/openai": "^0.0.14", "firebase-admin": "^11.8.0", "firebase-functions": "^4.3.1", "langchain": "^0.1.18", "stream-chat": "^8.16.0" }, "overrides": { "@langchain/core": "0.1.5" }, "devDependencies": { "firebase-functions-test": "^3.1.0", "typescript": "^4.9.0" }, "private": true }
函数代码
import { onRequest } from "firebase-functions/v2/https"; import * as logger from "firebase-functions/logger"; import { StreamChat } from "stream-chat"; import { ChatOpenAI } from "@langchain/openai"; import { ChatPromptTemplate } from "@langchain/core/prompts"; import { StringOutputParser } from "@langchain/core/output_parsers"; export const myFunction = onRequest( { timeoutSeconds: 60, region: ["europe-west2"] }, (request, response) => { const client = StreamChat.getInstance( "api_key", "api_secret" ); const signature = request.headers["x-signature"] as string; const valid = client.verifyWebhook(request.rawBody, signature); if (!valid) response.status(204).end(); const chatModel = new ChatOpenAI({ openAIApiKey: "openai_key", }); const outputParser = new StringOutputParser(); const prompt = ChatPromptTemplate.fromMessages([ [ "system", "You are a helpful assistant", ], ["user", "{input}"], ]); const chain = prompt.pipe(chatModel).pipe(outputParser); if (request.body.user.id !== "system_user") { chain.invoke({ input: request.body.message.text }).then((aiRes) => { const channel = client.channel( "messaging", "channel_id" ); return channel.sendMessage({ user_id: "my-app", text: aiRes, }); }); } response.status(200).end(); } );
二、升级TypeScript 5后的新错误
node_modules/@langchain/core/dist/utils/stream.d.ts:1:18 - error TS2320: Interface 'IterableReadableStreamInterface<T>' cannot simultaneously extend types 'ReadableStream<T>' and 'AsyncIterable<T>'. Named property '[Symbol.asyncIterator]' of types 'ReadableStream<T>' and 'AsyncIterable<T>' are not identical. 1 export interface IterableReadableStreamInterface<T> extends ReadableStream<T>, AsyncIterable<T> { ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ node_modules/@langchain/core/dist/utils/stream.d.ts:9:5 - error TS2425: Class 'ReadableStream<T>' defines instance member property '[Symbol.asyncIterator]', but extended class 'IterableReadableStream<T>' defines it as instance member function. 9 [Symbol.asyncIterator](): this; ~~~~~~~~~~~~~~~~~~~~~~ Found 2 errors in the same file, starting at: node_modules/@langchain/core/dist/utils/stream.d.ts:1 Error: functions predeploy error: Command terminated with non-zero exit code 2
三、解决方案
1. 修复LangChain依赖版本冲突
核心问题是@langchain/openai ^0.0.14与langchain ^0.1.18版本不兼容,且手动指定的@langchain/core 0.1.5存在类型定义缺陷。修改package.json如下:
- 移除
overrides字段,让npm自动处理兼容依赖 - 升级
@langchain/openai到^0.1.6(与langchain 0.1.18匹配的版本) - 升级TypeScript到
^5.3.3(兼容Node.js 20及LangChain最新类型)
修改后的package.json:
{ "name": "functions", "scripts": { "build": "tsc", "build:watch": "tsc --watch", "serve": "npm run build && firebase emulators:start --only functions", "shell": "npm run build && firebase functions:shell", "start": "npm run shell", "deploy": "firebase deploy --only functions", "logs": "firebase functions:log" }, "engines": { "node": "20" }, "main": "lib/index.js", "dependencies": { "@langchain/openai": "^0.1.6", "firebase-admin": "^11.8.0", "firebase-functions": "^4.3.1", "langchain": "^0.1.18", "stream-chat": "^8.16.0" }, "devDependencies": { "firebase-functions-test": "^3.1.0", "typescript": "^5.3.3" }, "private": true }
2. 调整TypeScript配置
修改tsconfig.json以适配Node.js 20和LangChain的类型要求:
- 将
target设为ES2022(Node.js 20原生支持) - 保持
module和moduleResolution为NodeNext以支持ES模块 - 添加
skipLibCheck: true跳过第三方库类型检查,避免类型冲突
修改后的tsconfig.json:
{ "compilerOptions": { "module": "NodeNext", "noImplicitReturns": true, "noUnusedLocals": true, "outDir": "lib", "sourceMap": true, "strict": true, "target": "ES2022", "esModuleInterop": true, "moduleResolution": "NodeNext", "skipLibCheck": true }, "compileOnSave": true, "include": ["src"] }
3. 修复函数代码中的异步问题
原代码存在异步操作未等待、未处理错误的问题,修改为:
import { onRequest } from "firebase-functions/v2/https"; import * as logger from "firebase-functions/logger"; import { StreamChat } from "stream-chat"; import { ChatOpenAI } from "@langchain/openai"; import { ChatPromptTemplate } from "@langchain/core/prompts"; import { StringOutputParser } from "@langchain/core/output_parsers"; export const myFunction = onRequest( { timeoutSeconds: 60, region: ["europe-west2"] }, async (request, response) => { const client = StreamChat.getInstance( "api_key", "api_secret" ); const signature = request.headers["x-signature"] as string; const valid = client.verifyWebhook(request.rawBody, signature); if (!valid) { response.status(204).end(); return; // 终止后续执行 } const chatModel = new ChatOpenAI({ openAIApiKey: "openai_key", }); const outputParser = new StringOutputParser(); const prompt = ChatPromptTemplate.fromMessages([ ["system", "You are a helpful assistant"], ["user", "{input}"], ]); const chain = prompt.pipe(chatModel).pipe(outputParser); if (request.body.user.id !== "system_user") { try { const aiRes = await chain.invoke({ input: request.body.message.text }); const channel = client.channel("messaging", "channel_id"); await channel.sendMessage({ user_id: "my-app", text: aiRes, }); } catch (err) { logger.error("消息处理失败:", err); } } response.status(200).end(); } );
4. 重新安装依赖并部署
执行以下命令:
rm -rf node_modules package-lock.json npm install npm run deploy
内容的提问来源于stack exchange,提问作者Victor
相关产品推荐
相关产品推荐

