一文搞懂LangChain是什么(非常详细),零基础入门到精通,看这一篇就够了

📅 发布时间:2026/7/17 12:42:38
一文搞懂LangChain是什么(非常详细),零基础入门到精通,看这一篇就够了 前言介绍LangChain是一个专门为利用语言模型创建应用程序而设计的全面框架。它的主要目标是帮助开发人员轻松构建基于语言模型的应用。虽然LangChain与多种语言模型兼容但它特别与OpenAI ChatGPT无缝集成从中受益于其先进功能。本文学习知识点: 语言模型LLMs和LangChain。 提示工程。 语言模型的内存。 语言模型的链式结构。 LangChain索引。 工具和代理。LLMs和LangChainLLMs即大型语言模型是具有数十亿个参数的强大深度学习模型在各种自然语言处理任务中表现出色。它们可以执行诸如翻译、情感分析和聊天机器人对话等任务而无需进行特定训练。LLMs由多个神经网络层组成包括前馈、嵌入和注意力层共同处理输入文本并生成预测。 虽然LLMs有改变行业的潜力但应考虑它们的限制和伦理影响。开发人员应优化这些模型以最大程度地减少偏见并增强其实用性。LLMs可以处理的最大标记数取决于具体的实现。在LangChain中最大标记数由所使用的底层OpenAI模型确定。为了处理超过标记限制的输入文本可以将其拆分为较小的块并单独处理然后再将结果组合起来。简单使用from langchain.llms import OpenAI from langchain.callbacks import get_openai_callback llm OpenAI(model_nametext-davinci-003, n2, best_of2) with get_openai_callback() as cb: result llm(Tell me a joke) print(cb)输出Tokens Used: 48 Prompt Tokens: 4 Completion Tokens: 44 Successful Requests: 1 Total Cost (USD): $0.00096尽管LangChain与OpenAI LLMs协同工作非常顺畅但它也可以与其他LLMs一起使用。我们将看一下Hugging Face托管的一个名为’google/flan-t5-large’的LLM。from langchain import HuggingFaceHub, LLMChain # initialize Hub LLM hub_llm HuggingFaceHub( repo_idgoogle/flan-t5-large, model_kwargs{temperature:0} ) # create prompt template LLM chain llm_chain LLMChain( promptprompt, llmhub_llm ) print(llm_chain.run(question))输出paris基于OpenAI ChatGPT的gpt-3.5-turbo模型的示例。from langchain.chat_models import ChatOpenAI from langchain.chains import LLMChain from langchain.prompts import PromptTemplate llm ChatOpenAI(model_namegpt-3.5-turbo, temperature0) summarization_template Summarize the following text to one sentence: {text} summarization_prompt PromptTemplate(input_variables[text], templatesummarization_template) summarization_chain LLMChain(llmllm, promptsummarization_prompt) text LangChain provides many modules that can be used to build language model applications. Modules can be combined to create more complex applications, or be used individually for simple applications. The most basic building block of LangChain is calling an LLM on some input. Let’s walk through a simple example of how to do this. For this purpose, let’s pretend we are building a service that generates a company name based on what the company makes. summarized_text summarization_chain.predict(texttext) summarized_text输出LangChain offers various modules for building language model applications, allowing users to combine them for more complex applications or use them individually for simpler ones, with the basic building block being calling an LLM on input, as demonstrated in the example of creating a company name based on its product.提示工程Prompt Engineering提示工程Prompt Engineering是在使用大型语言模型时必须掌握的关键方面。通过精心设计适当的提示即使使用较弱或开源模型也可以达到可比较的准确性水平。角色提示Role prompting涉及指示LLM在执行任务时扮演特定的角色或身份。例如可以要求它扮演一个文案撰稿人的角色。这种方法通过提供上下文或观点来引导模型的回应。为了有效地利用角色提示可以按照以下迭代步骤进行操作1.在提示中明确指定所需的角色例如“作为一个文案撰稿人为AWS服务生成引人注目的口号。”2.利用提示从LLM生成输出。3.分析生成的回应并根据需要改进提示以提升结果的质量。from langchain import PromptTemplate, LLMChain from langchain.llms import OpenAI # Before executing the following code, make sure to have # your OpenAI key saved in the “OPENAI_API_KEY” environment variable. # Initialize LLM llm OpenAI(model_nametext-davinci-003, temperature0) template As a futuristic robot band conductor, I need you to help me come up with a song title. Whats a cool song title for a song about {theme} in the year {year}? # prompt template prompt PromptTemplate( input_variables[theme, year], templatetemplate, ) llm OpenAI(model_nametext-davinci-003, temperature0) input_data {theme: interstellar travel, year: 3030} chain LLMChain(llmllm, promptprompt) response chain.run(input_data) print(Theme: interstellar travel) print(Year: 3030) print(AI-generated song title:, response)输出Theme: interstellar travel Year: 3030 AI-generated song title: Journey to the Stars: 3030LLMs 内存在聊天机器人应用的动态领域中保留消息历史在提供上下文相关的回应以增强用户体验方面起着关键作用。LangChain的ConversationChain包括一种基本形式的内存它保留了过去的所有输入和输出并将它们融入当前的上下文中。这可以被视为一种短期记忆。LangChain提供了多种类型的内存链包括ConversationBufferMemory对话缓冲内存、ConversationBufferWindowMemory对话缓冲窗口内存、ConversationTokenBufferMemory对话标记缓冲内存和ConversationSummaryMemory对话摘要内存。通过使用这些内存链LangChain能够在对话过程中跟踪和保留消息的历史使得模型可以根据之前的对话内容和用户交互生成更具上下文相关的响应。这样的内存机制提高了对话的连贯性和个性化从而提升用户体验。llm ChatOpenAI(temperature0.0) memory ConversationBufferMemory() conversation ConversationChain( llmllm, memory memory, verboseTrue ) print(conversation.predict(inputHi, my name is Andrew)) print(conversation.predict(inputWhat is 11?)) print(conversation.predict(inputWhat is my name?))输出Hello Andrew! Its nice to meet you. How can I assist you today? 11 is equal to 2. Your name is Andrew.在上面的对话中LLM能够记住之前的对话并为第三次对话提供准确的回答。这得益于LangChain的内存机制特别是ConversationChain。ConversationChain保留了过去的输入和输出并将它们整合到当前的上下文中。这使得LLM能够根据之前的对话内容和用户交互生成更准确、更具上下文的回答。通过ConversationChain的内存功能LLM可以回顾之前的对话历史并将其作为参考来理解当前的问题并生成相关的回答。这样的记忆机制有助于提供连贯的对话体验并确保LLM在整个对话过程中能够保持准确性和一致性。print(memory.buffer)输出Human: Hi, my name is Andrew AI: Hello Andrew! Its nice to meet you. How can I assist you today? Human: What is 11? AI: 11 is equal to 2. Human: What is my name? AI: Your name is Andrew.LLMs的链式结构LangChain中的链式结构旨在建立一个全面的流程以利用语言模型。它们集成了模型、提示、内存、解析输出和调试功能提供了用户友好的界面。一个链式结构执行以下步骤1接收用户的查询作为输入2处理语言模型的响应3将输出返回给用户。链式结构的类型包括LLMChainLLMChain是使用单个语言模型的链式结构。它接收用户的查询将其发送给语言模型进行处理并将模型生成的响应返回给用户。Sequential ChainsSimpleSequentialChain和SequentialChain这些是顺序执行的链式结构可以按照特定的顺序连接多个处理组件。例如SimpleSequentialChain可能包括一个提示组件、一个语言模型组件和一个输出解析组件依次进行处理。Router Chain路由链是一种根据条件将查询路由到不同的子链的结构。它根据一些规则或条件决定将查询发送到哪个子链进行处理并返回子链处理的结果。通过这些链式结构LangChain能够组织和管理对语言模型的查询和响应流程提供更灵活、可扩展的应用开发方式并为用户提供更好的交互体验。这是一个用于SimpleSequentialChain的示例代码from langchain.chat_models import ChatOpenAI from langchain.prompts import ChatPromptTemplate from langchain.chains import SimpleSequentialChain llm ChatOpenAI(temperature0.9) # prompt template 1 first_prompt ChatPromptTemplate.from_template( What is the best name to describe \ a company that makes {product}? ) # Chain 1 chain_one LLMChain(llmllm, promptfirst_prompt) # prompt template 2 second_prompt ChatPromptTemplate.from_template( Write a 20 words description for the following \ company:{company_name} ) # chain 2 chain_two LLMChain(llmllm, promptsecond_prompt) overall_simple_chain SimpleSequentialChain(chains[chain_one, chain_two], verboseTrue ) overall_simple_chain.run(product)LangChain索引无论选择了哪种模型或使用了哪种提示表达方式语言模型本身都具有一些无法通过我们所学的技术来克服的局限性。这些模型有一个训练截断点这意味着它们无法获得实时新闻和最新的更新。因此这些模型提供的回应可能不总是事实准确的有可能包含虚构的信息。在LangChain中索引和检索器在组织和检索语言模型相关数据方面起着关键作用。索引是高效存储和组织文档的强大数据结构用于快速搜索而检索器利用这些索引在用户查询时定位和检索相关文档。在LangChain中主要的索引类型是基于向量数据库的其中基于嵌入向量的索引是最常见的方法。下面的图片展示了从向量数据库中读取索引的过程。图片来源deeplearning.ai面是一个读取词嵌入word embeddings的示例from langchain.chains import RetrievalQA from langchain.chat_models import ChatOpenAI from langchain.document_loaders import CSVLoader from langchain.vectorstores import DocArrayInMemorySearch from langchain.indexes import VectorstoreIndexCreator file csv_file.csv loader CSVLoader(file_pathfile) index VectorstoreIndexCreator( vectorstore_clsDocArrayInMemorySearch ).from_loaders([loader]) query Please list all your shirts with sun protection \ in a table in markdown and summarize each one. response index.query(query) loader CSVLoader(file_pathfile) docs loader.load() from langchain.embeddings import OpenAIEmbeddings embeddings OpenAIEmbeddings() embed embeddings.embed_query(Hi my name is Harrison) print(embed[:5])输出[-0.021913960576057434, 0.006774206645786762, -0.018190348520874977, -0.039148248732089996, -0.014089343138039112]下面是一个来自Data Lake Serverless Vector Database的示例from langchain.document_loaders import TextLoader # text to write to a local file # taken from https://www.theverge.com/2023/3/14/23639313/google-ai-language-model-palm-api-challenge-openai text Google opens up its AI language model PaLM to challenge OpenAI and GPT-3 Google is offering developers access to one of its most advanced AI language models: PaLM. The search giant is launching an API for PaLM alongside a number of AI enterprise tools it says will help businesses “generate text, images, code, videos, audio, and more from simple natural language prompts.” PaLM is a large language model, or LLM, similar to the GPT series created by OpenAI or Meta’s LLaMA family of models. Google first announced PaLM in April 2022. Like other LLMs, PaLM is a flexible system that can potentially carry out all sorts of text generation and editing tasks. You could train PaLM to be a conversational chatbot like ChatGPT, for example, or you could use it for tasks like summarizing text or even writing code. (It’s similar to features Google also announced today for its Workspace apps like Google Docs and Gmail.) # write text to local file with open(my_file.txt, w) as file: file.write(text) # use TextLoader to load text from local file loader TextLoader(my_file.txt) docs_from_file loader.load() from langchain.text_splitter import CharacterTextSplitter # create a text splitter text_splitter CharacterTextSplitter(chunk_size200, chunk_overlap20) # split documents into chunks docs text_splitter.split_documents(docs_from_file) from langchain.embeddings import OpenAIEmbeddings embeddings OpenAIEmbeddings(modeltext-embedding-ada-002) from langchain.vectorstores import DeepLake my_activeloop_org_id YOUR-ACTIVELOOP-ORG-ID my_activeloop_dataset_name langchain_course_indexers_retrievers dataset_path fhub://{my_activeloop_org_id}/{my_activeloop_dataset_name} db DeepLake(dataset_pathdataset_path, embedding_functionembeddings) # add documents to our Deep Lake dataset db.add_documents(docs) # create retriever from db retriever db.as_retriever() from langchain.chains import RetrievalQA from langchain.llms import OpenAI # create a retrieval chain qa_chain RetrievalQA.from_chain_type( llmOpenAI(modeltext-davinci-003), chain_typestuff, retrieverretriever ) query How Google plans to challenge OpenAI? response qa_chain.run(query) print(response)输出Google plans to challenge OpenAI by offering access to its AI language model PaLM, which is similar to OpenAIs GPT series and Metas LLaMA family of models. PaLM is a large language model that can be used for tasks like summarizing text or writing code.工具和代理LangChain提供了各种工具和代理用于帮助用户在应对挑战和生成有意义的回答时提高效率和便捷性。通过无缝集成这些工具用户可以访问各种功能和信息源以解决问题和提供不同类型的答案。LangChain中一些重要的工具示例包括Google搜索、Requests、Python REPL、Wikipedia和Wolfram Alpha。代理是根据自然语言指令行动的机器人可以利用工具来回答查询。它们确定要采取的操作顺序可能涉及使用工具或向用户提供回答。有效使用代理可以发挥强大的作用因为它们可以根据用户输入动态调用链条。在LangChain中创建代理时可以使用initialize_agent函数和load_tools函数来准备代理可用的工具。LangChain中的代理在根据用户输入进行决策和任务执行方面起着重要作用。它们评估情况并确定要使用的适当工具。LangChain提供了两类主要的代理执行单个动作的“Action Agents”适用于简单的任务以及制定包含多个动作并按顺序执行的“Plan-and-Execute Agents”适用于复杂或长时间运行的任务。以下示例中我们将使用Google搜索作为工具来查找Ashes系列赛事的最新摘要。在撰写这篇文章时我正在积极关注Ashes系列赛事)from langchain.llms import OpenAI from langchain.agents import AgentType from langchain.agents import load_tools from langchain.agents import initialize_agent from langchain.agents import Tool from langchain.utilities import GoogleSearchAPIWrapper llm OpenAI(modeltext-davinci-003, temperature0) os.environ[GOOGLE_API_KEY] GOOGLE_API_KEY os.environ[GOOGLE_CSE_ID] GOOGLE_CSE_ID search GoogleSearchAPIWrapper() tools [ Tool( name google-search, funcsearch.run, descriptionuseful for when you need to search google to answer questions about current events ) ] agent initialize_agent(tools, llm, agentAgentType.ZERO_SHOT_REACT_DESCRIPTION, verboseTrue, max_iterations6) response agent(latest status on ashes series) print(response[output])输出 Finished chain. The 2021–22 Ashes series, named the Vodafone Mens Ashes Series for sponsorship reasons, is scheduled to take place in England from 8 July to 7 September 2023. Australia last won an Ashes series in England in 2001 and the current series is scheduled to take place from 8 July to 7 September 2023. The ESPNcricinfo app has an all-new native experience on match score screens and an exciting new feature Fantasy Cheatsheet to help you win your fantasy games. The 2023 Ashes series is sure to be a highly anticipated event for cricket fans worldwide.进一步阅读随着ChatGPT和LangChain引起的激动这个领域出现了许多令人振奋的项目和发展。以下是一些链接可供探索这些令人兴奋的创新项目CAMEL : https://www.camel-ai.org/Deep Lake: https://python.langchain.com/docs/modules/data_connection/vectorstores/integrations/deeplakeAgentGPT : https://github.com/reworkd/AgentGPTAutoGPT : https://www.lesswrong.com/posts/566kBoPi76t8KAkoD/on-autogpthttps://github.com/yoheinakajima/babyagi/blob/main/docs/inspired-projects.md零基础入门AI大模型今天贴心为大家准备好了一系列AI大模型资源包括AI大模型入门学习思维导图、精品AI大模型学习书籍手册、视频教程、实战学习等录播视频免费分享出来。1.学习路线图第一阶段 从大模型系统设计入手讲解大模型的主要方法第二阶段 在通过大模型提示词工程从Prompts角度入手更好发挥模型的作用第三阶段 大模型平台应用开发借助阿里云PAI平台构建电商领域虚拟试衣系统第四阶段 大模型知识库应用开发以LangChain框架为例构建物流行业咨询智能问答系统第五阶段 大模型微调开发借助以大健康、新零售、新媒体领域构建适合当前领域大模型第六阶段 以SD多模态大模型为主搭建了文生图小程序案例第七阶段 以大模型平台应用与开发为主通过星火大模型文心大模型等成熟大模型构建大模型行业应用。2.视频教程网上虽然也有很多的学习资源但基本上都残缺不全的这是我自己整理的大模型视频教程上面路线图的每一个知识点我都有配套的视频讲解。都打包成一块的了不能一一展开总共300多集3.技术文档和电子书这里主要整理了大模型相关PDF书籍、行业报告、文档有几百本都是目前行业最新的。4.LLM面试题和面经合集这里主要整理了行业目前最新的大模型面试题和各种大厂offer面经合集。学会后的收获• 基于大模型全栈工程实现前端、后端、产品经理、设计、数据分析等通过这门课可获得不同能力• 能够利用大模型解决相关实际项目需求 大数据时代越来越多的企业和机构需要处理海量数据利用大模型技术可以更好地处理这些数据提高数据分析和决策的准确性。因此掌握大模型应用开发技能可以让程序员更好地应对实际项目需求• 基于大模型和企业数据AI应用开发实现大模型理论、掌握GPU算力、硬件、LangChain开发框架和项目实战技能 学会Fine-tuning垂直训练大模型数据准备、数据蒸馏、大模型部署一站式掌握• 能够完成时下热门大模型垂直领域模型训练能力提高程序员的编码能力 大模型应用开发需要掌握机器学习算法、深度学习框架等技术这些技术的掌握可以提高程序员的编码能力和分析能力让程序员更加熟练地编写高质量的代码。1.AI大模型学习路线图2.100套AI大模型商业化落地方案3.100集大模型视频教程4.200本大模型PDF书籍5.LLM面试题合集6.AI产品经理资源合集领取方式我会放在下面希望领取了的朋友不要忘了下方名片放心添加