部署在AWS Amplify的Next.js应用出现Langchain意外Azure依赖问题
问题描述
- 基于Next.js + LangChain开发的聊天应用,本地运行完全正常,但部署到AWS Amplify后出现故障
- 应用使用OpenAIEmbeddings生成向量、PineconeStore存储向量,已确认本地与Amplify控制台的环境变量配置一致
- 报错信息显示LangChain误判为Azure环境,要求提供
azureOpenAIApiInstanceName变量,但实际未使用Azure服务
代码片段
import type { NextApiRequest, NextApiResponse } from 'next'; import { OpenAIEmbeddings } from 'langchain/embeddings/openai'; import { PineconeStore } from 'langchain/vectorstores/pinecone'; import { makeChain } from '@/utils/makechain'; import { pinecone } from '@/utils/pinecone-client'; import { PINECONE_INDEX_NAME, PINECONE_NAME_SPACE } from '@/config/pinecone'; export default async function handler( req: NextApiRequest, res: NextApiResponse, ) { const { question, history } = req.body; if (req.method !== 'POST') { res.status(405).json({ error: 'Method not allowed' }); return; } if (!question) { return res.status(400).json({ message: 'No question in the request' }); } const sanitizedQuestion = question.trim().replaceAll('\n', ' '); try { const index = pinecone.Index(PINECONE_INDEX_NAME); const vectorStore = await PineconeStore.fromExistingIndex( new OpenAIEmbeddings(), { pineconeIndex: index, textKey: 'text', namespace: PINECONE_NAME_SPACE, }, ); const chain = makeChain(vectorStore); const response = await chain.call({ question: sanitizedQuestion, chat_history: history || [], }); res.status(200).json(response); } catch (error: any) { console.log('chat.ts file error: ', error); res.status(500).json({ error: error.message || 'Something went wrong' }); } }
解决方案
1. 清理Azure相关环境变量
LangChain的OpenAIEmbeddings会自动检测环境变量,若存在AZURE_OPENAI_API_KEY等Azure前缀的变量(即使是空值),会自动切换到Azure模式。
- 操作:登录AWS Amplify控制台,进入应用的环境变量设置,删除所有带
AZURE_前缀的变量,仅保留OPENAI_API_KEY等OpenAI相关变量。
2. 锁定依赖版本并清除构建缓存
本地与Amplify部署的LangChain版本不一致,可能导致环境变量检测逻辑差异。
- 操作:
- 在
package.json中指定langchain、@langchain/openai(若使用新版)的具体版本号,避免自动升级 - 修改Amplify构建命令为
npm ci,确保依赖版本与本地完全一致;同时在控制台触发重新构建时清除缓存
- 在
3. 显式指定OpenAI配置
初始化OpenAIEmbeddings时,强制指定使用OpenAI官方API,跳过自动环境检测:
new OpenAIEmbeddings({ configuration: { basePath: "https://api.openai.com/v1", apiKey: process.env.OPENAI_API_KEY, }, })
若使用新版@langchain/openai包,调整为:
new OpenAIEmbeddings({ openAIApiKey: process.env.OPENAI_API_KEY, configuration: { basePath: "https://api.openai.com/v1" } })
4. 确认Amplify环境变量注入
检查Amplify环境变量的作用范围,确保勾选「Build time」和「Runtime」;同时在next.config.js中添加环境变量暴露配置:
module.exports = { env: { OPENAI_API_KEY: process.env.OPENAI_API_KEY, PINECONE_API_KEY: process.env.PINECONE_API_KEY, PINECONE_INDEX_NAME: process.env.PINECONE_INDEX_NAME, PINECONE_NAME_SPACE: process.env.PINECONE_NAME_SPACE } }
内容的提问来源于stack exchange,提问作者Lloukas
相关产品推荐
相关产品推荐

