简单之美LangChain框架介绍及入门指南

LangChain是一个用来开发大型语言模型(LLM)应用的框架,为了简化构建基于LLM的应用,它能够为开发LLM应用带来如下能力:

LangChain是什么

LangChainLibraries是一个Python和JavaScript库,是LangChain中最核心的部分,在图中对应于下方的深色块。LangChainLibraries被分为3个核心的部分,也是代码组织方式的表现:LangChain、LangChain-Community、LangChain-Core,简要介绍如下:

包含LangChain的基本抽象和LCEL(LangChainExpressionLanguage)。

提供了一组用于简化部署的参考架构,方便构建基于LLM应用的中的各种任务。

提供了用来将LangChain部署为RESTAPI服务的工具,以供应用的其他模块调用。LangChain使用了FastAPI来实现这种服务能力。

LangSmith是LangChain提供的开发平台,方便开发人员进行调试、测试、评估、监控等。

LangChain模块(Modules)概览

LangChain提供了一个标准的可扩展的接口,可以方便地与外部其他组件进行交互以满足面向特定领域LLM应用的需求,它也能够与外部其它组件/中间件连接和交互。这些模块根据功能及行为方式,分为6个类别,如下表所示:

通过上面表格,我们基本了解了LangChain提供的一些方便构建LLM应用的模块及其对应的功能,下面,针对每个模块进行更详细的说明。

LangChain模块:ModelI/O

使用Ollama在本地就可以启动一个模型服务,然后我们就可以使用LangChain创建对应的LLM和ChatModel,示例代码如下:

使用LangChain与LLM进行对话,示例代码如下:

fromlangchain.schemaimportHumanMessagetext="Whatwouldbeagoodcompanynameforacompanythatmakescolorfulsocks"messages=[HumanMessage(content=text)]llm.invoke(text)#>>FeetfulofFunchat_model.invoke(messages)#>>AIMessage(content="SocksO'Color")PromptTemplate包含了我们要查询LLM的请求内容,以及我们所基于的上下文,这样就限制了预训练的LLM能够基于我们提供的上下文来给出更准确的回答。示例代码如下:

LangChain提供了不同类型的OutputParser,能够将LLM输出的消息进行格式化,方便下游应用任务使用。比如,下面示例中使用CommaSeparatedListOutputParser,将消息按照逗号分割,并返回一个列表:

fromlangchain.output_parsersimportCommaSeparatedListOutputParseroutput_parser=CommaSeparatedListOutputParser()output_parser.parse("hi,bye")#>>['hi','bye']使用LCEL将上面的PromptTemplate、ChatModel、OutputParser组合到一起,并实现了与LLM的交互,示例代码如下:

template="Generatealistof5{text}.\n\n{format_instructions}"chat_prompt=ChatPromptTemplate.from_template(template)chat_prompt=chat_prompt.partial(format_instructions=output_parser.get_format_instructions())chain=chat_prompt|chat_model|output_parserchain.invoke({"text":"colors"})#>>['red','blue','green','yellow','orange']LangChain模块:Retrieval

VectorStore也叫VectorDB,用来存储我们自己数据的向量表示内容(Embedding),以支持Retrieval模块的检索匹配。

Retriever称为检索器,从我们构建好的VectorStore中进行检索。LangChain提供了各种支持检索的算法,比如:ParentDocumentRetriever、SelfQueryRetriever、EnsembleRetriever、MultiVectorRetriever,等等。下面以SelfQueryRetriever为例说明使用方法,示例代码如下所示:

LangChain模块:Agents

Agent通过LLM来推理,能够自然地、持续多轮地与LLM交互,这也是智能体所具备与支持的基本能力。为了说明Agent框架的使用方法,使用Tavily和Retriever两个工具来构建Agent,其中Tavily是一个支持Online搜索的工具。

agent_executor.invoke({"input":"hi!"})这样的交互不会记忆上下文,是无状态的。所以,如果考虑上下文,需要把以往的记录加入到Memory,示例代码如下:

fromlangchain_core.messagesimportAIMessage,HumanMessageagent_executor.invoke({"chat_history":[HumanMessage(content="hi!mynameisbob"),AIMessage(content="HelloBob!HowcanIassistyoutoday"),],"input":"what'smyname",})也可以直接使用LangChain提供的ChatMessageHistory、RunnableWithMessageHistory来实现自动跟踪历史消息的功能,可以参考LangChain文档。

LangChain模块:Chains

Chains是一个调用/处理/计算任务序列的抽象,可以根据我们自己的需求来构建不同的调用链、处理链,等等。Chains是通过LangChain提供的LCEL来构建的。下面是LainChain提供的一些LCELConstructor,可以方便构建一个Chain,如下所示:

通过名称,就可以大致了解每个LCELConstructor实现的Chain的功能。

LangChain模块:Memory

fromlangchain_openaiimportOpenAIfromlangchain.promptsimportPromptTemplatefromlangchain.chainsimportLLMChainfromlangchain.memoryimportConversationBufferMemoryllm=OpenAI(temperature=0)prompt=PromptTemplate.from_template(template)memory=ConversationBufferMemory(memory_key="chat_history")#needtoalignthe`memory_key`conversation=LLMChain(llm=llm,prompt=prompt,verbose=True,memory=memory)当然也可以直接使用ChatModel来实现整个对话过程,具体例子可以参考LangChain官网文档。Memory模块提供了多个不同的实现,具体也可以根据自己实际应用需求来实现,如下所示是LangChain提供的一些实现:

具体功能和使用方法,可以点击对应链接查看官网文档的详细说明。

LangChain模块:Callbacks

LangChain支持使用Callbacks,通过Hook到基于LLM的应用的任何位置,来实现类似日志记录、监控、Streaming处理以及其它任务等等。要想实现自定义的Callback能力,可以直接实现CallbackHandler接口,开发满足自己应用需求的CallbackHandler。LangChain实现的StdOutCallbackHandler是一个非常基础的Callback,使用示例如下:

fromlangchain.callbacksimportStdOutCallbackHandlerfromlangchain.chainsimportLLMChainfromlangchain_openaiimportOpenAIfromlangchain.promptsimportPromptTemplatehandler=StdOutCallbackHandler()llm=OpenAI()prompt=PromptTemplate.from_template("1+{number}=")chain=LLMChain(llm=llm,prompt=prompt,callbacks=[handler])#Constructorcallbackchain.invoke({"number":2})chain=LLMChain(llm=llm,prompt=prompt,verbose=True)#Useverboseflagtoachievecallbackschain.invoke({"number":2})chain=LLMChain(llm=llm,prompt=prompt)#Requestcallbackschain.invoke({"number":2},{"callbacks":[handler]})LCEL(LangChainExpressionLanguage)

下面通过一个实现prompt+model+outputparser的例子,用来说明使用LCEL带来的直观性和便利性,示例代码如下:

LangServe工具介绍

LangServe提供了将LangChain的runnables和chains部署为RESTAPI的能力,它是使用FastAPI来实现的。使用LangServe部署基于LLM的应用,会包含两个部分:Server(提供LLMChatModel服务)、Client(调用模型服务)。下面通过一个例子来说明如何构建。

Server包括OpenAIChatModel和AnthropicChatModel,它们可以提供对话服务能力,示例代码如下:

#!/usr/bin/envpythonfromfastapiimportFastAPIfromlangchain.promptsimportChatPromptTemplatefromlangchain.chat_modelsimportChatAnthropic,ChatOpenAIfromlangserveimportadd_routesimportuvicornapp=FastAPI(title="LangChainServer",version="1.0",description="AsimpleapiserverusingLangchain'sRunnableinterfaces",)add_routes(app,ChatOpenAI(),path="/openai",)add_routes(app,ChatAnthropic(),path="/anthropic",)model=ChatAnthropic()prompt=ChatPromptTemplate.from_template("tellmeajokeabout{topic}")add_routes(app,prompt|model,path="/joke",)if__name__=="__main__":uvicorn.run(app,host="localhost",port=8000)如果没有报错,打开浏览器浏览localhost:8080/docs可以看到对应的页面,说明Server端部署成功。

Client端用来与Server端进行交互:调用Server端提供的RESTAPI就可以实现。Client端示例的Python代码如下:

LangSmith工具介绍

LangGraph介绍

LangGraph是一个用来构建有状态的、多Actor的LLM应用的库,它是在LangChain框架的基础之上构建实现的。LangGraph的灵感来自Pregel和ApacheBeam,支持基于LCEL的能力构建一个带有循环的(Cyclic)的应用模式,从而实现协调多个Chain跨多个计算步骤(ComputationSteps)的能力。可见,LangGraph是支持带环的计算图模式的,并不是简单的DAG(有向无环图)。下面以官网的入门例子为例,说明如何使用LangGraph,如下所示:

fromlangchain_community.tools.tavily_searchimportTavilySearchResultstools=[TavilySearchResults(max_results=1)]fromlanggraph.prebuiltimportToolExecutortool_executor=ToolExecutor(tools)#wrapTavilytoolusingLangGraphToolExecutorfromlangchain_openaiimportChatOpenAI#Wewillsetstreaming=Truesothatwecanstreamtokensmodel=ChatOpenAI(temperature=0,streaming=True)fromlangchain.tools.renderimportformat_tool_to_openai_functionfunctions=[format_tool_to_openai_function(t)fortintools]model=model.bind_functions(functions)#Bindtoolstothemodellanggraph提供的图主要是指StatefulGraph,它可以被一个状态对象参数化(Parameterized)。状态对象在图中的每个节点之间传递,每一个节点会返回更新状态对象的操作,从而实现状态的更新。这里的状态会跟踪对话过程中产生的消息的列表,构建的图中的每个节点需要把消息添加到列表中,所以使用TypedDict来实现Agent状态,如下所示:

fromtypingimportTypedDict,Annotated,Sequenceimportoperatorfromlangchain_core.messagesimportBaseMessageclassAgentState(TypedDict):messages:Annotated[Sequence[BaseMessage],operator.add]在langgraph中,图节点是一个function对象或runnable对象;然后通过边来连接各个节点,在langgraph中有两种类型的边:ConditionalEdge和NormalEdge,可以通过定义函数来实现,确定从一个节点到另一个节点的路径。示例代码如下:

fromlanggraph.graphimportStateGraph,ENDworkflow=StateGraph(AgentState)#Definethetwonodeswewillcyclebetweenworkflow.add_node("agent",call_model)workflow.add_node("action",call_tool)workflow.set_entry_point("agent")#Settheentrypointas`agent`#Addaconditionaledgeworkflow.add_conditional_edges("agent",#First,wedefinethestartnode.Weuse`agent`.should_continue,#Next,thefunctionwilldeterminewhichnodeiscallednext.#Finallywepassinamapping,andbasedonwhichoneitmatches,thatnodewillthenbecalled.{"continue":"action",#If`tools`,thenwecallthetoolnode."end":END#Otherwisewefinish.})#Addanormaledgefrom`tools`to`agent`:after`tools`iscalled,`agent`nodeiscallednext.workflow.add_edge('action','agent')app=workflow.compile()##CompilesitintoaLangChainRunnable,fromlangchain_core.messagesimportHumanMessageinputs={"messages":[HumanMessage(content="whatistheweatherinsf")]}app.invoke(inputs)通过上面1~6步骤,就可以构建并执行一个基于LangGraph的简单LLM应用。

THE END
1.LibrariesDefinition&MeaningMerriamHow to Use Em Dashes (—), En Dashes (–) , and Hyphens (-) Plural and Possessive Names: A Guide The Difference Between 'i.e.' and 'e.g.' Why is '-ed' sometimes pronounced at the end of a word? What's the difference between 'fascism' and 'socialism'? https://www.merriam-webster.com/dictionary/libraries
2.AdobeCreativeCloudLibraries您可以使用 Creative Cloud 网站、Creative Cloud 桌面应用程序或您的任意 Creative Cloud 桌面应用程序与团队共享资料库。要使用 Creative Cloud Libraries,团队成员需要获得免费或付费的 Creative Cloud 会员资格。在进行共享时,您也可以向其提供查看或编辑权限。有关共享的详细信息,请参阅协作使用资料库。 https://learn.adobe.com/cn/creative-cloud/help/libraries.html
3.《RAGFlow》本地部署创建知识库RAGFlow 是什么? RAGFlow 是一款基于深度文档理解构建的开源 RAG(Retrieval-Augmented Generation)引擎。RAGFlow 可以为各种规模的企业及个人提供一套精简的 RAG 工作流程,结合大语言模型(LLM)针对用户各类不同的复杂格式数据提供可靠的问答以及有理有据的引用。 https://blog.csdn.net/2401_85592132/article/details/144399721
4.3.NetUI库:MaterialSkin开源项目研究文章MaterialSkin 是一个开源的 WinForms 第三方库,提供了许多仿谷歌设计风格的组件,使得 WinForms 窗体程序更加美观。以下是 MaterialSkin 的一些关键特点和使用方法: 主要特点: 仿谷歌设计风格:MaterialSkin 提供了大量符合 Material Design 风格的控件,使得应用程序界面更加现代和美观。 https://blog.51cto.com/lzhdim/12778102
5.10月28日CLEVNET图书馆网络换新搜索引擎,咋访问阿斯彭借书俄亥俄州克利夫兰——图书馆联盟 CLEVNET 最近宣布,能为读者在查找图书、有声读物、DVD、杂志等时提供更友好的浏览体验。 CLEVNET 在一份新闻稿中称,新的搜索功能“Aspen Discovery”将于 10 月 28 日(星期一)推出。CLEVNET 是该地区 47 个图书馆系统的联盟。 https://www.163.com/dy/article/JJ16596S05568E2X.html
6.GitHubNote that this is not a standard feature for all JWTs - only JWEs - and is not likely to be supported by other JWT libraries for non-JWE tokens. JJWT supports compression for both JWSs and JWEs, however. Please see the main Compression section to see how to compress and decompress http://www.jsonwebtoken.io/
7.人工智能计算领域的领导者NVIDIANVIDIA 发明了 GPU,并推动了 AI、HPC、游戏、创意设计、自动驾驶汽车和机器人开发领域的进步。http://nvidia.com/
8.PodcastIn this episode of FYI: The Public Libraries Podcast, we share inspiring stories of Library Joy. Ten stories in under twenty minutes! Inspired by Mychal Threets’ focus on celebrating joy in libraries, this episode highlights moments from library workers across the country that capture the magichttps://publiclibrariesonline.org/category/media/podcast/
9.Mpu6500(I2cDevice)建構函式(Iot.Device.Imu)MicrosoftLearnMicrosoft Learn Challenge Nov 23, 2024 – Jan 10, 2025 立即註冊 解除警示 Learn 探索 產品文件 開發語言 主題 登入 版本 .NET IoT Libraries 2.2.0 Iot.Device.Imu AccelerometerBandwidth AccelerometerLowPowerFrequency AccelerometerRange DisableModes https://docs.microsoft.com/zh-hk/dotnet/api/iot.device.imu.mpu6500.-ctor
10.GiftstolibrariesALA"Virtual Bookplates: Enhancing Donor Recognition and Library Development." College and Research Libraries News, September 2010, p. 419-423. Cooper, Tom. "Getting the Most from Donations". Public Libraries, March/April 2010, p. 31-36. NOTE: Article freely available at PublicLibrariesOnline.org https://www.ala.org/tools/atoz/gifts-libraries
11.Reviewonnaturalproductsdatabases:wheretofinddatainNatural products online resources: availability and characteristics For now, there is no globally accepted community resource for NPs, where their structures and annotations can be submitted, edited and queried by a large public, like there is UniProt [19] for proteins or NCBI Taxonomy [20] for http://dx.doi.org/10.1186/s13321-020-00424-9
12.2023年12月高等学校英语应用能力考试B级真题及解析SectionCHi,I’mBrianSmith.NowI’llsharesomeideaswithyouforusingakindofnewsoftware.Thesoftwareisdesignedandmadebyourcompany.Itcanhelpyoutofindouttheaveragesalaryforyourjobtype.Thesoftwarecanbefoundonline.Whetheryouarelookingforanewjob,ormovingtoanotherarea,itcanbeausefultooltogetthenecessaryinformation.Ihopehttps://www.renrendoc.com/paper/269387355.html
13.AskTheHeadhunter?WTF is going on with employment in America? Why have I written and published 500 weekly editions of the Ask The Headhunter Newsletter? Because America’s employment system still doesn’t work. The emperor still has no clothes, and that’s why over 25 million Americans are unemployed or underhttps://www.asktheheadhunter.com/6827/employment-in-america-wtf-is-going-on
14.continuingeducation&unbonlineStay informed Winter credit courses Explore our diverse range of credit courses available, including online and in-person options to suit your learning style and schedule. Enrol now to advance your knowledge and skills in a supportive and dynamic educational environment. https://www.unb.ca/cel/
15.英语四级作文(精选46篇)In conclusion, online libraries are one of the greatest inventions in this modern world. We can not only enhance the efficiency of acquiring information and knowledge but also enjoy the technological innovation. 在线图书馆越来越受欢迎。越来越多的人通过手机和电脑阅读书籍和查阅所需内容,以供研究。 https://www.ruiwen.com/zuowen/qitaleiyingyuzuowen/6421925.html
16.专家介绍The Impact of Hygiene Factors on Online Hotel Consumption,in China during the COVID-19 ,Pandemic,Sustainability,2023,15(4):1-16. SCI&SSCI; Research on Knowledge Organization of Intangible,Cultural Heritage Based on ;Metadata,Information Technology and Libraries,2022, (6):1-11.SCI&SSCI; 基于DPShttp://db.hbskw.com/pcms/index.php?m=content&c=index&a=show&catid=6&id=11300
17.IMSLNumericalLibraries中国区金牌代理商购买销售电话:021以上是IMSL Numerical Libraries软件的最新版产品介绍简介,有关于IMSL Numerical Libraries软件的购买,使用教程,免费下载,服务技术支持,帮助测试,功能更新升级,试用版支持及销售报价价格表等请致电金牌代理商购买销售电话。 买软件网为IMSL Numerical Libraries软件的正版软件销售公司,金牌代理商,经销代理商及合作伙伴。 http://www.buysoftware.cn/onlinebuy/detail.asp?p_id=4013
18.StackOverflowDeveloperSurvey2023Which other frameworks and libraries have you done extensive development work in over the past year, and which do you want to work in over the next year? (If you both worked with the framework and want to continue to do so, please check both boxes in that row.) Other tools This yehttps://survey.stackoverflow.co/2023
19.我们的图书馆大学英语作文(精选27篇)Directions: For this part, you are allowed 30 minutes to write an essay on online libraries. You can start your essay with the sentence "Online libraries are becoming increasingly popular." You should write at least 120 words but no more than 180 words. https://www.yjbys.com/edu/daxue/456234.html