一、简述1 什么是LangChainLangChain由 Harrison Chase 创建于2022年10月,它是围绕LLMs(大语言模型)建立的一个框架,它的核心理念是为各种LLMs实现通用的接口,把LLMs相关的组件“链接”在一起,简化LLMs应用的开发难度,方便开发者快速地开发复杂的LLMs应用。LangChain 最初是于 2022 年 10 月开源的一个项目,在 GitHub 上获得大量关注之后迅速转变为一家初创公司。2017 年 Harrison Chase 还在哈佛上大学,如今已是硅谷的一家热门初创公司的 CEO,这对他来说是一次重大而迅速的跃迁。Insider 独家报道,人工智能初创公司 LangChain 在种子轮一周后,再次获得红杉领投的 2000 万至 2500 万美元融资,估值达到 2 亿美元。LangChain官网:https://python.langchain.com/docs/introduction/LangChain官网中文版:https://www.langchain.com.cn/LangChain 简化了 LLM 应用程序生命周期的每个阶段:开发:使用 LangChain 的开源组件和第三方集成构建应用程序。使用 LangGraph 构建具有一流流式和人机交互支持的状态智能体。生产化:使用 LangSmith 检查、监控和评估应用程序,方便持续优化和部署。部署:使用 LangGraph平台 将应用程序转变为可用于生产的 API 和助手。2 主要组件Models:模型,各种类型的模型和模型集成,比如GPT-4Prompts:提示,包括提示管理、提示优化和提示序列化Chains:链,一系列对各种组件的调用Memory:记忆,用来保存和模型交互时的上下文状态Indexes:索引,用来结构化文档,以便和模型交互Agents:代理,决定模型采取哪些行动,执行并且观察流程,直到完成为止3 LangChain核心包langchain-core:聊天模型和其他组件的基础抽象。集成包(例如 langchain-openai、langchain-anthropic 等):重要的集成被拆分为轻量级的独立包,由 LangChain 团队和集成方共同维护。langchain:包含链(chains)、智能体(agents)和检索策略,这些构成了应用的认知架构。langchain-community:由社区维护的第三方集成。langgraph:一个编排框架,用于将 LangChain 组件组合成可用于生产的应用,支持持久化、流式处理及其他关键特性。4 环境准备本课程以LangChain+Qwen进行学习,需要提前安装pip install openaipip install langchainpip install modelscope借助阿里云-百炼平台(需要申请API Key 以及Secret Key):https://bailian.console.aliyun.com/#/home二、Models现在市面上的模型多如牛毛,各种各样的模型不断出现,LangChain模型组件提供了与各种模型的集成,并为所有模型提供一个精简的统一接口。LangChain目前支持三种类型的模型:LLMs、Chat Models(聊天模型)、Embeddings Models(嵌入模型)。LLMs:大语言模型接收文本字符作为输入,返回的也是文本字符。聊天模型:基于LLMs, 不同的是它接收聊天消息(一种特定格式的数据)作为输入,返回的也是聊天消息。文本嵌入模型:文本嵌入模型接收文本作为输入, 返回的是浮点数列表。LangChain支持的三类模型,它们的使用场景不同,输入和输出不同,开发者需要根据项目需要选择相应的模型。1 LLMsLLMs(大语言模型)使用场景最多,常用大模型的下载库:https://huggingface.co/modelshttps://modelscope.cn/models下面Qwen为例进行讲解。模型调用有2种方式:通过ChatOpenAI进行调用fromlangchain_openaiimportChatOpenAIimportos# 实例化模型model=ChatOpenAI(base_url=os.environ.get('base_url','https://dashscope.aliyuncs.com/compatible-mode/v1'),model='qwen-plus',openai_api_key=os.environ.get('api_key','sk-XXXXXX'),max_tokens=1000,temperature=0)# 获取问答结果result=model.invoke("帮我讲个笑话吧")print(result.content)通过Ollama进行调用 Ollama支持模型# from langchain_community.llms import Ollama # Langchain 0.x版本使用fromlangchain_ollamaimportOllamaLLM# 实例化模型# model = Ollama(model="qwen2.5:7b") # Langchain 0.x版本使用model=OllamaLLM(model="qwen2.5:7b")# 获取问答结果result=model.invoke("请给我讲个笑话吧")print(result)2 Chat Models聊天模型,聊天消息包含下面几种类型,使用时需要按照约定传入合适的值:AIMessage: 就是 AI 输出的消息,可以是针对问题的回答.HumanMessage: 人类消息就是用户信息,由人给出的信息发送给LLMs的提示信息,比如“实现一个快速排序方法”.SystemMessage: 可以用于指定模型具体所处的环境和背景,如角色扮演等。你可以在这里给出具体的指示,比如“作为一个代码专家”,或者“返回json格式”.ChatMessage: Chat 消息可以接受任意角色的参数,但是在大多数时间,我们应该使用上面的三种类型.LangChain支持大量的chat 模型,可以通过官网查询:https://python.langchain.com/docs/integrations/chat/也可以通过langchain源码查看SystemMessage+HumanMessage+AIMessagefromlangchain_core.messagesimportHumanMessage,SystemMessage,AIMessage# from langchain_community.chat_models import ChatOllama # Langchain 0.x版本使用fromlangchain_ollamaimportChatOllama# 实例化模型model=ChatOllama(model="qwen2.5:7b")# 定义提示词messages=[SystemMessage(content="现在你是一个著名的诗人"),HumanMessage(content="给我写一首唐诗")]# 获取问答结果result=model.invoke(messages)# print(result)print(result.content)3 Embeddings ModelsEmbeddings Models(嵌入模型)特点:将字符串作为输入,返回一个浮动数的列表。在NLP中,Embedding的作用就是将数据进行文本向量化。https://python.langchain.com/docs/integrations/text_embedding/不同的Embedding模型对多语言支持和文本类型有不同的特点:多语言支持:text-embedding-ada-002:支持多种语言,但对中文等亚洲语言的支持相对较弱bge-large-zh:对中文有很好的支持multilingual-e5-large:对多语言都有较好的支持mxbai-embed-large:文本类型适用性:代码文本:建议使用专门的代码Embedding模型,如CodeBERT通用文本:可以使用text-embedding-ada-002或bge-large-zh专业领域文本:建议使用该领域的专门模型可以参考MTEB(大规模文本嵌入基准)排行榜以获取最新模型效果:https://huggingface.co/spaces/mteb/leaderboard接下来以一个文本嵌入模型的例子进行说明:# from langchain_community.embeddings import OllamaEmbeddings # Langchain 0.x版本使用fromlangchain_ollamaimportOllamaEmbeddings# 初始化Ollama嵌入模型,使用mxbai-embed-large模型,温度设置为0model=OllamaEmbeddings(model="mxbai-embed-large",temperature=0)# 对单个查询文本进行嵌入编码res1=model.embed_query('这是第一个测试文档')print(f'result1-{res1}')print(f'result1的长度-{len(res1)}')# 对多个文档进行批量嵌入编码res2=model.embed_documents(['这是第一个测试文档','这是第二个测试文档'])print(res2)运行结果:三、Prompts1 通用promptPrompt是指当用户输入信息给模型时加入的提示,这个提示的形式可以是zero-shot或者few-shot等方式,目的是让模型理解更为复杂的业务场景以便更好的解决问题。提示模板:如果你有了一个起作用的提示,你可能想把它作为一个模板用于解决其他问题,LangChain就提供了PromptTemplates组件,它可以帮助你更方便的构建提示。zero-shot提示方式# from langchain import PromptTemplate # Langchain 0.x版本使用fromlangchain_core.promptsimportPromptTemplate# from langchain_community.llms import Ollama # Langchain 0.x版本使用fromlangchain_ollamaimportOllamaLLM# model = Ollama(model="qwen2.5:7b") # Langchain 0.x版本使用model=OllamaLLM(model="qwen2.5:7b")# 定义模板template="我的邻居姓{lastname},他生了个儿子,给他儿子起个名字"prompt=PromptTemplate(input_variables=["lastname"],template=template)prompt_text=prompt.format(lastname="王")print(prompt_text)# result: 我的邻居姓王,他生了个儿子,给他儿子起个名字result=model.invoke(prompt_text)print(result)运行结果:few-shot提示方式# from langchain import PromptTemplate, FewShotPromptTemplate # Langchain 0.x版本使用fromlangchain_core.promptsimportPromptTemplate,FewShotPromptTemplatefromlangchain_ollamaimportOllamaLLM model=OllamaLLM(model="qwen2.5:7b")examples=[{"word":"开心","antonym":"难过"},{"word":"高","antonym":"矮"}]example_template=""" 单词: {word} 反义词: {antonym}\\n """example_prompt=PromptTemplate(input_variables=["word","antonym"],template=example_template,)few_shot_prompt=FewShotPromptTemplate(examples=examples,example_prompt=example_prompt,prefix="给出每个单词的反义词",suffix="单词: {input}\\n反义词:",input_variables=["input"],example_separator="\\n",)prompt_text=few_shot_prompt.format(input="粗")print(model.invoke(prompt_text))# 细2 ChatPrompts适合交互式对话应用,如聊天机器人、智能客服等,这些应用需要处理用户和LLM之间的多轮对话。ChatPromptTemplateSystemMessagePromptTemplateHumanMessagePromptTemplatehistory=[(“system”,“…”),(‘human’,“…”),(“ai”,“…”)]直接提问提示模板就是把一些常见的提示整理成模板,用户只需要修改模板中特定的词语,就能快速准确地告诉模型自己的需求。我们看个例子:fromlangchain_core.promptsimportChatPromptTemplatefromlangchain_ollamaimportOllamaLLM# 实例化模型model=OllamaLLM(model="qwen2.5:7b")# 定义提示词模版template_str="帮我讲个关于{name}笑话吧"prompt_template=ChatPromptTemplate.from_template(template_str)prompt=prompt_template.format_messages(name="气球")print(f'prompt--{prompt}')# 调用模型result=model.invoke(prompt)print(f'result--{result}')zero-shot提示方式fromlangchain_core.promptsimportChatPromptTemplate,HumanMessagePromptTemplatefromlangchain_core.messagesimportSystemMessagefromlangchain_ollamaimportOllamaLLM# 实例化模型model=OllamaLLM(model="qwen2.5:7b")# 系统信息system_prompt=SystemMessage("你是取名专家。")# 用户信息模版human_str="我的邻居姓{lastname},他生了个儿子,给他儿子起个名字。"human_template