Javascript版Langchain入门

发布时间 2023-09-11 23:33:21作者: China Soft

https://baijiahao.baidu.com/s?id=1769509377621631060&wfr=spider&for=pc

介绍

LangChain是一个开源Python库,用于构建由大型语言模型(LLM)支持的应用程序。它提供了一个框架,将LLM与其他数据源(如互联网或个人文件)连接起来,允许开发人员将多个命令链接在一起,以创建更复杂的应用程序。LangChain创建于2022年10月,是围绕LLMs(大语言模型)建立的一个框架,LLMs使用机器学习算法和海量数据来分析和理解自然语言。LangChain自身并不开发LLMs,它的核心理念是为各种LLMs实现通用的接口,把LLMs相关的组件“链接”在一起,简化LLMs应用的开发难度,方便开发者快速地开发复杂的LLMs应用。

支持的语言

LangChain目前有两个语言的实现:Python和Node.js。

组件

LangChain的组件包括:

  • • Models:模型,各种类型的模型和模型集成,比如GPT-4。

  • • Prompts:提示,包括提示管理、提示优化和提示序列化。

  • • Memory:记忆,用来保存和模型交互时的上下文状态。

  • • Indexes:索引,用来结构化文档,以便和模型交互。

  • • Chains:链,一系列对各种组件的调用。

  • • Agents:代理,决定模型采取哪些行动,执行并且观察流程,直到完成为止。

使用场景

LangChain的使用场景包括:构建聊天机器人、文本生成、文本分类、问答系统、语言翻译、语言模型微调等。

安装依赖库

npm install -S langchain

Hello World

首先,使用Langchain来调用OpenAI模型。

import { OpenAI } from "langchain/llms/openai";

const model = new OpenAI({
openAIApiKey: 'sk-xxxx',//你的OpenAI API Key
temperature: 0.9
});

const res = await model.call(
"写一首诗,限制20个字"
);
console.log(res);

输出



春风迎新年,喜气绕家园。
祝福短信语,友谊永绵长。

替换提示语中的参数

import { OpenAI } from "langchain/llms/openai";
import { PromptTemplate } from "langchain/prompts";
import { LLMChain } from "langchain/chains";

const model = new OpenAI({
openAIApiKey: 'sk-xxxx',//你的OpenAI API Key
temperature: 0.9
});
const template = "What is a good name for a company that makes {product}?";
const prompt = new PromptTemplate({
template: template,
inputVariables: ["product"],
});

const chain = new LLMChain({ llm: model, prompt: prompt });
const res = await chain.call({ product: "colorful socks" });
console.log(res);

开始见识Langchain的强大

截止上个实例,你还没见识到Langchain的强大。

接下来,你先注册一个SerpApi帐号,获取api key

点击这里注册

然后执行以下的代码,

import { OpenAI } from "langchain/llms/openai";
import { initializeAgentExecutorWithOptions } from "langchain/agents";
import { SerpAPI } from "langchain/tools";
import { Calculator } from "langchain/tools/calculator";

const model = new OpenAI({
streaming: true,
openAIApiKey: 'sk-xxxx',//你的OpenAI API Key
temperature: 0.9
});
const tools = [
new SerpAPI('你的SerpAPI的key', {
location: "Austin,Texas,United States",
hl: "en",
gl: "us",
}),
new Calculator(),
];

const executor = await initializeAgentExecutorWithOptions(tools, model, {
agentType: "zero-shot-react-description",
});
console.log("Loaded agent.");

const input =
"谁是周杰伦的老婆?" +
"她的年纪加上10是多少?"
console.log(`Executing with input "${input}"...`);

const result = await executor.call({ input });

console.log(`Got output ${result.output}`);

输出:

Loaded agent.
Executing with input "谁是周杰伦的老婆?她的年纪加上10是多少?"...
Got output Hannah Quinlivan is Zhou Jielun's wife and she is 39 years old.

执行结果做了两件事,

  1. 1. 使用SerpAPI工具获取周杰伦的老婆的名字:Quinlivan

  2. 2. 然后获取她的年龄:29岁

  3. 3. 最后使用Calculator工具加上10:最终得到39岁的结果

这里引进了Langchainagents概念:代理。

决定模型采取哪些行动,执行并且观察流程,直到完成为止。

代码中引进了两个工具:SerpAPICalculator