LangChainJS 快速入门指南:构建智能应用的基础教程
langchainjs 项目地址: https://gitcode.com/gh_mirrors/lan/langchainjs
LangChainJS 是一个强大的 JavaScript/TypeScript 库,专门用于构建基于大型语言模型(LLM)的应用程序。本文将带你快速了解如何使用 LangChainJS 构建不同类型的智能应用。
环境准备
首先需要安装 LangChainJS 核心库:
npm install langchain
基础组件介绍
LangChainJS 提供了几个核心组件,它们是构建应用的基础:
- 提示模板(Prompt Templates):用于结构化用户输入
- 模型接口(Models):与各种LLM交互的接口
- 输出解析器(Output Parsers):处理模型输出
构建第一个LLM链
让我们从最简单的LLM链开始,它直接将用户输入传递给模型:
import { ChatOpenAI } from "@langchain/openai";
import { ChatPromptTemplate } from "@langchain/core/prompts";
import { StringOutputParser } from "@langchain/core/output_parsers";
// 初始化聊天模型
const chatModel = new ChatOpenAI({});
// 创建提示模板
const prompt = ChatPromptTemplate.fromMessages([
["system", "你是一位世界级的技术文档作者"],
["user", "{input}"]
]);
// 构建完整链
const chain = prompt.pipe(chatModel).pipe(new StringOutputParser());
// 调用链
const result = await chain.invoke({
input: "什么是LangSmith?"
});
这个简单的链展示了 LangChainJS 的基本工作流程:输入→提示模板→模型→输出解析。
增强应用:检索链
当需要回答基于特定知识库的问题时,简单的LLM链可能会产生幻觉(编造答案)。这时可以使用检索链:
import { CheerioWebBaseLoader } from "langchain/document_loaders/web/cheerio";
import { RecursiveCharacterTextSplitter } from "langchain/text_splitter";
import { MemoryVectorStore } from "langchain/vectorstores/memory";
import { OpenAIEmbeddings } from "@langchain/openai";
// 1. 加载文档
const loader = new CheerioWebBaseLoader("https://docs.smith.langchain.com/user_guide");
const docs = await loader.load();
// 2. 分割文档
const splitter = new RecursiveCharacterTextSplitter();
const splitDocs = await splitter.splitDocuments(docs);
// 3. 创建向量存储
const vectorstore = await MemoryVectorStore.fromDocuments(
splitDocs,
new OpenAIEmbeddings()
);
// 4. 构建检索链
const retriever = vectorstore.asRetriever();
const retrievalChain = await createRetrievalChain({
combineDocsChain: documentChain,
retriever,
});
// 使用检索链
const result = await retrievalChain.invoke({
input: "LangSmith的主要功能是什么?"
});
检索链会自动从向量库中查找相关文档片段,提供给LLM作为上下文,从而得到更准确的答案。
进阶:对话检索链
要使应用能够处理对话上下文,需要创建对话感知的检索链:
import { createHistoryAwareRetriever } from "langchain/chains/history_aware_retriever";
import { MessagesPlaceholder } from "@langchain/core/prompts";
// 创建历史感知的检索器
const historyAwareRetrieverChain = await createHistoryAwareRetriever({
llm: chatModel,
retriever,
rephrasePrompt: ChatPromptTemplate.fromMessages([
new MessagesPlaceholder("chat_history"),
["user", "{input}"],
["user", "根据以上对话生成搜索查询"]
])
});
// 使用示例
const chatHistory = [
new HumanMessage("LangSmith能帮助测试LLM应用吗?"),
new AIMessage("是的!")
];
const relevantDocs = await historyAwareRetrieverChain.invoke({
chat_history: chatHistory,
input: "告诉我具体怎么做!"
});
这种链能够理解对话上下文,生成更相关的搜索查询。
模型选择与配置
LangChainJS 支持多种模型后端:
- OpenAI:商业API,性能稳定
- Anthropic:Claude系列模型
- 本地模型(Ollama):开源模型,可本地运行
// OpenAI配置示例
import { ChatOpenAI } from "@langchain/openai";
const openAIModel = new ChatOpenAI({
modelName: "gpt-4",
temperature: 0.7
});
// 本地Ollama配置示例
import { ChatOllama } from "@langchain/community/chat_models/ollama";
const localModel = new ChatOllama({
model: "mistral"
});
最佳实践
- 合理设置temperature参数:控制生成文本的创造性
- 使用适当的文本分割策略:根据文档类型选择分割方式
- 监控应用性能:考虑使用LangSmith进行跟踪
- 处理超长上下文:注意模型的最大token限制
总结
通过本教程,你已经学会了:
- 如何设置基本的LLM链
- 如何增强应用使用检索功能
- 如何构建对话式应用
- 如何配置不同的模型后端
LangChainJS 提供了丰富的工具和抽象,使得构建复杂的LLM应用变得更加简单。随着对这些基础概念的掌握,你可以进一步探索更高级的功能,如代理(Agents)、工具(Tools)等。
langchainjs 项目地址: https://gitcode.com/gh_mirrors/lan/langchainjs
创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考