我用亚马逊云的Lambda函数,通过langChain调用OpenAI API。我把OPENAI_API_KEY存在了Lambda函数的环境变量里了。神奇的是,在创建new ChatOpenAI()实例的时候没有传入OPENAI_API_KEY,还是可以获取到正确的返回值。这是为什么?
import { ChatOpenAI } from "langchain/chat_models/openai";
import { HumanChatMessage, SystemChatMessage } from "langchain/schema";
export const handler = async (event) => {
const chat = new ChatOpenAI({ temperature: 0 });
const response = await chat.call([
new HumanChatMessage(
"把大象装冰箱一共分几步?"
),
new HumanChatMessage(
"为什么?"
),
]);
return response;
};
已解决。经过验证langChain会自动读取环境变量。文档也有说明,没仔细看。
Here we create a chat model using the API key stored in the environment variable OPENAI_API_KEY or AZURE_OPENAI_API_KEY in case you are using Azure OpenAI. We'll be calling this chat model throughout this section.