【langchain】入门初探实战笔记(Chain, Retrieve, Memory, Agent)

1. 简介

1.1 大语言模型技术栈

大语言模型技术栈
大语言模型技术栈由四个主要部分组成:

  • 数据预处理流程(data preprocessing pipeline)
  • 嵌入端点(embeddings endpoint )+向量存储(vector store)
  • LLM 终端(LLM endpoints)
  • LLM 编程框架(LLM programming framework)

1.2 Langchain的简介和部署

LangChain 就是一个 LLM 编程框架,你想开发一个基于 LLM 应用,需要什么组件它都有,直接使用就行;甚至针对常规的应用流程,它利用链(LangChain中Chain的由来)这个概念已经内置标准化方案了。

安装langchain包

pip install langchain

调用openai接口

pip install openai

在代码里调用需要设置openai的api key,有两种方法,一种是在bashrc的文件中配置,另一种直接在调用的函数里设置openai的key值配置

openai的key可以通过https://platform.openai.com/api-keys 官网的连接获取

2. 大模型交互

openai接口代码调用示例

# openai_api_key = ""
# Importing modules
from langchain.llms import OpenAI
# Here we are using text-ada-001 but you can change it
from langchain.chat_models import ChatOpenAI
from langchain.prompts import ChatPromptTemplate
from langchain_core.output_parsers import StrOutputParser

output_parser = StrOutputParser()
prompt = ChatPromptTemplate.from_messages([
    ("system", "You are world class technical documentation writer."),
    ("user", "{input}")
])
llm = ChatOpenAI(openai_api_key = "")
# chain = prompt | llm
# print("prompt:", prompt)
# print("chain:", chain)
chain = prompt | llm | output_parser
res = chain.invoke("how can langsmith help with testing?")
print(res)

输出

content="Langsmith can help with testing in several ways:\n\n1. Test Automation: Langsmith can generate automated test scripts that cover various test scenarios and execute them repeatedly. This helps in reducing manual effort and time required for testing.\n\n2. Test Data Generation: Langsmith can generate test data that covers a wide range of input values and boundary conditions. This helps in testing the robustness and reliability of the system.\n\n3. Test Case Generation: Langsmith can generate test cases based on the specifications or requirements provided. These test cases can cover various combinations of inputs and expected outputs, ensuring comprehensive testing.\n\n4. Regression Testing: Langsmith can automate the execution of regression tests, which are performed to ensure that existing functionality is not impacted by any new changes or updates.\n\n5. Performance Testing: Langsmith can generate test scripts to simulate high loads and stress on the system, enabling performance testing and identifying potential bottlenecks or performance issues.\n\n6. Security Testing: Langsmith can help in identifying security vulnerabilities by generating test cases that simulate different attack scenarios, such as SQL injection or cross-site scripting.\n\nOverall, Langsmith's capabilities in generating automated test scripts, test data, test cases, and supporting various types of testing can significantly improve the efficiency and effectiveness of the testing process.

3. Chain

3.1 LLM Chain

最基本的链为 LLMChain,由 PromptTemplate、LLM 和 OutputParser 组成。LLM 的输出一般为文本,OutputParser 用于让 LLM 结构化输出并进行结果解析,方便后续的调用。

在这里插入图片描述

from langchain.chains import LLMChain
from langchain.prompts import PromptTemplate
from langchain.output_parsers import ResponseSchema, StructuredOutputParser
# from azure_chat_llm import llm
from langchain.chat_models import ChatOpenAI

#output parser
keyword_schema = ResponseSchema(name="keyword", description="评论的关键词列表")
emotion_schema = ResponseSchema(name="emotion", description="评论的情绪,正向为1,中性为0,负向为-1")
response_schemas = [keyword_schema, emotion_schema]
output_parser = StructuredOutputParser.from_response_schemas(response_schemas)
format_instructions = output_parser.get_format_instructions()

#prompt template
prompt_template_txt = '''
作为资深客服,请针对 >>> 和 <<< 中间的文本识别其中的关键词,以及包含的情绪是正向、负向还是中性。
>>> {text} <<<
RESPONSE:
{format_instructions}
'''

prompt = PromptTemplate(template=prompt_template_txt, input_variables=["text"],
                        partial_variables={"format_instructions": format_instructions})
llm = ChatOpenAI(openai_api_key = "")
#llmchain
llm_chain = LLMChain(prompt=prompt, llm=llm)
comment = "京东物流没的说,速度态度都是杠杠滴!这款路由器颜值贼高,怎么说呢,就是泰裤辣!这线条,这质感,这速度,嘎嘎快!以后妈妈再也不用担心家里的网速了!"
result = llm_chain.run(comment)
data = output_parser.parse(result)
print(f"type={type(data)}, keyword={data['keyword']}, emotion={data['emotion']}")

在这里插入图片描述

3.2 Sequential Chain

SequentialChains 是按预定义顺序执行的链。SimpleSequentialChain 为顺序链的最简单形式,其中每个步骤都有一个单一的输入 / 输出,一个步骤的输出是下一个步骤的输入。SequentialChain 为顺序链更通用的形式,允许多个输入 / 输出。

from langchain.chains import LLMChain
from langchain.prompts import PromptTemplate
from langchain.chains import SimpleSequentialChain
from langchain.chat_models import ChatOpenAI

llm = ChatOpenAI(openai_api_key = "")
first_prompt = PromptTemplate.from_template(
    "翻译下面的内容到中文:"
    "\n\n{content}"
)
# chain 1: 输入:Review 输出: 英文的 Review
chain_trans = LLMChain(llm=llm, prompt=first_prompt, output_key="content_zh")

second_prompt = PromptTemplate.from_template(
    "一句话总结下面的内容:"
    "\n\n{content_zh}"
)

chain_summary = LLMChain(llm=llm, prompt=second_prompt)
overall_simple_chain = SimpleSequentialChain(chains=[chain_trans, chain_summary],verbose=True)
content = '''In a blog post authored back in 2011, Marc Andreessen warned that, “Software is eating the world.” Over a decade later, we are witnessing the emergence of a new type of technology that’s consuming the world with even greater voracity: generative artificial intelligence (AI). This innovative AI includes a unique class of large language models (LLM), derived from a decade of groundbreaking research, that are capable of out-performing humans at certain tasks. And you don’t have to have a PhD in machine learning to build with LLMs—developers are already building software with LLMs with basic HTTP requests and natural language prompts.
In this article, we’ll tell the story of GitHub’s work with LLMs to help other developers learn how to best make use of this technology. This post consists of two main sections: the first will describe at a high level how LLMs function and how to build LLM-based applications. The second will dig into an important example of an LLM-based application: GitHub Copilot code completions.
Others have done an impressive job of cataloging our work from the outside. Now, we’re excited to share some of the thought processes that have led to the ongoing success of GitHub Copilot.
'''
result = overall_simple_chain.run(content)
print(f'result={result}')

在这里插入图片描述

3.3 RouterChain

在这里插入图片描述

4. 外部文档检索

索引和外部数据进行集成,用于从外部数据获取答案。

  • 通过 Document Loaders 加载各种不同类型的数据源,

LangChain 通过 Loader 加载外部的文档,转化为标准的 Document 类型。Document 类型主要包含两个属性:page_content 包含该文档的内容。meta_data 为文档相关的描述性数据,类似文档所在的路径等。

  • 通过 Text Splitters 进行文本语义分割

LLM 一般都会限制上下文窗口的大小,有 4k、16k、32k 等。针对大文本就需要进行文本分割,常用的文本分割器为 RecursiveCharacterTextSplitter,可以通过 separators 指定分隔符。其先通过第一个分隔符进行分割,不满足大小的情况下迭代分割。

著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

  • 通过 Vectorstore 进行非结构化数据的向量存储

通过 Text Embedding models,将文本转为向量,可以进行语义搜索,在向量空间中找到最相似的文本片段。目前支持常用的向量存储有 Faiss、Chroma 等。

  • 通过 Retriever 进行文档数据检索

Retriever 接口用于根据非结构化的查询获取文档,一般情况下是文档存储在向量数据库中。可以调用 get_relevant_documents 方法来检索与查询相关的文档。

在这里插入图片描述

from langchain import FAISS
from langchain.document_loaders import WebBaseLoader
from langchain.embeddings import HuggingFaceEmbeddings
from langchain.text_splitter import RecursiveCharacterTextSplitter

#通过 Document Loaders 加载各种不同类型的数据源
#LangChain 通过 Loader 加载外部的文档,转化为标准的 Document 类型。
# Document 类型主要包含两个属性:page_content 包含该文档的内容。meta_data 为文档相关的描述性数据,类似文档所在的路径等。
loader = WebBaseLoader("https://in.m.jd.com/help/app/register_info.html")
data = loader.load()

#针对大文本就需要进行文本分割,常用的文本分割器为 RecursiveCharacterTextSplitter,可以通过 separators 指定分隔符。
# 其先通过第一个分隔符进行分割,不满足大小的情况下迭代分割。
text_splitter = RecursiveCharacterTextSplitter.from_tiktoken_encoder(
    model_name="gpt-3.5-turbo",
    allowed_special="all",
    separators=["\n\n", "\n", "。", ","],
    chunk_size=800,
    chunk_overlap=0
)
docs = text_splitter.split_documents(data)
#通过cache_folder设置自己的本地模型路径
#embeddings = HuggingFaceEmbeddings(model_name="text2vec-base-chinese", cache_folder="models")

#通过 Text Embedding models,将文本转为向量,可以进行语义搜索,在向量空间中找到最相似的文本片段。
# 目前支持常用的向量存储有 Faiss、Chroma 等。
embeddings = HuggingFaceEmbeddings()

vectorstore = FAISS.from_documents(docs, embeddings)

#Retriever 接口用于根据非结构化的查询获取文档,一般情况下是文档存储在向量数据库中。
# 可以调用 get_relevant_documents 方法来检索与查询相关的文档。
result = vectorstore.as_retriever().get_relevant_documents("用户注册资格")
print(result)
print(len(result))

在这里插入图片描述

5. 外部文档交互

5.1 Stuff

StuffDocumentsChain 这种链最简单直接,是将所有获取到的文档作为 context 放入到 Prompt 中,传递到 LLM 获取答案

这种方式可以完整的保留上下文,调用 LLM 的次数也比较少,建议能使用 stuff 的就使用这种方式。其适合文档拆分的比较小,一次获取文档比较少的场景,不然容易超过 token 的限制。

在这里插入图片描述

5.2 Refine

RefineDocumentsChain 是通过迭代更新的方式获取答案。先处理第一个文档,作为 context 传递给 llm,获取中间结果 intermediate answer。然后将第一个文档的中间结果以及第二个文档发给 llm 进行处理,后续的文档类似处理。

Refine 这种方式能部分保留上下文,以及 token 的使用能控制在一定范围。

在这里插入图片描述

5.3 MapReduce

MapReduceDocumentsChain 先通过 LLM 对每个 document 进行处理,然后将所有文档的答案在通过 LLM 进行合并处理,得到最终的结果。

MapReduce 的方式将每个 document 单独处理,可以并发进行调用。但是每个文档之间缺少上下文。

在这里插入图片描述

5.4 MapRerank

MapRerankDocumentsChain 和 MapReduceDocumentsChain 类似,先通过 LLM 对每个 document 进行处理,每个答案都会返回一个 score,最后选择 score 最高的答案。

MapRerank 和 MapReduce 类似,会大批量的调用 LLM,每个 document 之间是独立处理

在这里插入图片描述

6. Memory

正常情况下 Chain 无状态的,每次交互都是独立的,无法知道之前历史交互的信息。LangChain 使用 Memory 组件保存和管理历史消息,这样可以跨多轮进行对话,在当前会话中保留历史会话的上下文。Memory 组件支持多种存储介质,可以与 Monogo、Redis、SQLite 等进行集成,以及简单直接形式就是 Buffer Memory。常用的 Buffer Memory 有:

  • ConversationSummaryMemory :以摘要的信息保存记录
  • ConversationBufferWindowMemory:以原始形式保存最新的 n 条记录
  • ConversationBufferMemory:以原始形式保存所有记录
from langchain.chains import ConversationChain
from langchain.memory import ConversationBufferMemory

from langchain.chat_models import ChatOpenAI

llm = ChatOpenAI(openai_api_key = "")

memory = ConversationBufferMemory()
conversation = ConversationChain(llm=llm, memory=memory, verbose=True)
print(conversation.prompt)
print(conversation.predict(input="我的姓名是tiger"))
print(conversation.predict(input="1+1=?"))
print(conversation.predict(input="我的姓名是什么"))

请添加图片描述

7. Agents

传统使用 LLM,需要给定 Prompt 一步一步的达成目标,通过 Agent 是给定目标,其会自动规划并达到目标。

目前这个领域特别活跃,诞生了类似 AutoGPT、BabyAGI、AgentGPT 等一堆优秀的项目。

目前的大模型一般都存在知识过时、逻辑计算能力低等问题,通过 Agent 访问工具,可以去解决这些问题。

  • Agent:代理,负责调用 LLM 以及决定下一步的 Action。其中 LLM 的 prompt 必须包含 agent_scratchpad 变量,记录执行的中间过程
  • Tools:工具,Agent 可以调用的方法。LangChain 已有很多内置的工具,也可以自定义工具。注意 Tools 的 description 属性,LLM 会通过描述决定是否使用该工具。
  • ToolKits:工具集,为特定目的的工具集合。类似 Office365、Gmail 工具集等
  • Agent Executor:Agent 执行器,负责进行实际的执行。
from langchain.agents import load_tools, initialize_agent, tool
from langchain.agents.agent_types import AgentType
from datetime import date
from langchain.chat_models import ChatOpenAI

llm = ChatOpenAI(openai_api_key = "")

#有多种方式可以自定义 Tool,最简单的方式是通过 @tool 装饰器,将一个函数转为 Tool。
# 注意函数必须得有 docString,其为 Tool 的描述。
@tool
def time(text: str) -> str:
    """
    返回今天的日期。
    """
    return str(date.today())

tools = load_tools(['llm-math'], llm=llm)
tools.append(time)
#一般通过 initialize_agent 函数进行 Agent 的初始化,除了 llm、tools 等参数,还需要指定 AgentType。
#该 Agent 为一个 zero-shot-react-description 类型的 Agent,其中 zero-shot 表明只考虑当前的操作,不会记录以及参考之前的操作。react 表明通过 ReAct 框架进行推理,description 表明通过工具的 description 进行是否使用的决策。
agent_math = initialize_agent(agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION,
                                   tools=tools,
                                   llm=llm,
                                   verbose=True)
print(agent_math("计算45 * 54"))
print(agent_math("今天是哪天?"))
#可以通过 agent.agent.llm_chain.prompt.template 方法,获取其推理决策所使用的模板。
print(agent_math.agent.llm_chain.prompt.template)

请添加图片描述

参考文献

知乎langchain到底该怎么使用,大家在项目中实践有成功的案例吗?https://www.zhihu.com/question/609483833/answer/3146379316?utm_psn=1725522909580394496

知乎小白入门大模型:LangChain https://zhuanlan.zhihu.com/p/656646499

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mfbz.cn/a/299747.html

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

看图识熊(三)

使用Windows Machine Learning加载ONNX模型并推理 环境要求 Windows Machine Learning支持在Windows应用程序中加载并使用训练好的机器学习模型。Windows 10从10.0.17763.0版本开始提供这套推理引擎&#xff0c;所以需要安装17763版本的Windows 10 SDK进行开发&#xff0c;并…

XML技术分析01

一、什么是XML eXtensible Markup Language ——可扩展标记语言 1、标记&#xff08; markup &#xff09;及标记语言&#xff1a; markup的含义是指插入到文档(document)中的标记 标记&#xff1a;是以标志的格式附加在文档中的。标志赋予文档的某一部分一个标记的标识…

HTML5+CSS3小实例:人物介绍卡片2.0

实例:人物介绍卡片2.0 技术栈:HTML+CSS 效果: 源码: 【HTML】 <!DOCTYPE html> <html lang="zh-CN"> <head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><…

PDF控件Spire.PDF for .NET【安全】演示:获取并验证 PDF 中的数字签名

在 PDF 中创建数字签名广泛用于保护 PDF 文件。因此&#xff0c;当您查看一些带有数字签名的PDF文件时&#xff0c;需要获取并验证数字签名。本文向您展示了一种通过使用Spire.PDF和 C# 代码来获取和验证 PDF 中的数字签名的解决方案。 Spire.PDF for .NET 是一款独立 PDF 控件…

搭建一个教育小程序的必要步骤

随着科技的飞速发展&#xff0c;小程序已经深入到我们生活的方方面面。对于教育行业来说&#xff0c;小程序的出现不仅为教育机构提供了新的宣传和互动平台&#xff0c;更为学生和家长带来了更为便捷的学习体验。那么&#xff0c;如何开发一款适合教育机构的小程序呢&#xff1…

基于springboot的sql防注入过滤器

目录 何为SQL注入基于springboot的sql防注入过滤器 回到顶部 何为SQL注入 SQL注入即是指web应用程序对用户输入数据的合法性没有判断或过滤不严&#xff0c;攻击者可以在web应用程序中事先定义好的查询语句的结尾上添加额外的SQL语句&#xff0c;在管理员不知情的情况下实现…

牛客网BC12-字符圣诞树

字符圣诞树 解题思路&#xff1a; 确定行数&#xff0c;一共5行&#xff0c;循环5次确定每行答应的内容&#xff0c;分成两部分&#xff0c;空格和字符 打印空格的个数依次递减打印字符的个数依次递增 找出打印空格和字符的个数与行数之间的关系 int main() {char ch 0;scanf(…

C# StringBuilder对比string的优点和15大案例

文章目录 StringBuilder和String 对比1. **循环内字符串连接**2. **构建大型日志消息**3. **格式化长字符串**4. **SQL 查询构造**5. **从文件读取并合并行**6. **拼接数组元素**7. **格式化电子邮件模板**8. **处理用户输入流**9. **JSON 或 XML 格式的序列化与构建**10. **动…

静态网页设计——天行九歌(HTML+CSS+JavaScript)(dw、sublime Text、webstorm、HBuilder X)

前言 声明&#xff1a;该文章只是做技术分享&#xff0c;若侵权请联系我删除。&#xff01;&#xff01; 感谢大佬的视频&#xff1a;https://www.bilibili.com/video/BV1de411m7y4/?vd_source5f425e0074a7f92921f53ab87712357b 源码&#xff1a;https://space.bilibili.com…

光明源@智慧环卫新标杆,智慧公厕系统全面升级

在城市的喧嚣之中&#xff0c;一个看似不太引人注目但却无法忽视的领域正在经历一场革命性的变革。作为城市基础设施的一部分&#xff0c;公厕一直以来被人们忽略&#xff0c;然而&#xff0c;随着科技的迅速发展&#xff0c;一项前所未有的升级正向我们走来——智慧公厕系统。…

2024.1.7周报

目录 摘要 ABSTRACT 一、文献阅读 1、题目 2、摘要 3、模型架构 4、文献解读 一、Introduction 二、创新点 三、实验过程 四、结论 二、深度学习知识 一、从Encoder-Decoder框架中理解为什么要有Attention机制 二、Attention思想 三、Seq2Seq Attention代码逐…

【C++】- 类和对象(!!C++类基本概念!this指针详解)

类和对象 引入类类的定义类的访问限定操作符类的作用域类的实例化类对象模型this指针 引入类 在 C中&#xff0c;引入了一个新的定义----------类。类是一种用户自定义的数据类型&#xff0c;用于封装数据和行为。类可以看作是一个模板或蓝图&#xff0c;描述了一组相关的数据和…

CCC数字钥匙设计【NFC】--NFC通信之APDU TLV

CCC3.0&#xff0c;包含NFC、BLE、UWB技术。当采用NFC通信时&#xff0c;车端与手机端是通过APDU来进行交互的。而在APDU中的data数据段&#xff0c;又可能会嵌入TLV协议的数据&#xff0c;以完成车端与手机端的通信交互。 本文先介绍APDU及TLV的一些基础知识&#xff0c;再通…

书生·浦语大模型第二课作业

作业一&#xff1a;小故事创作 作业要求&#xff1a;使用 InternLM-Chat-7B 模型生成 300 字的小故事&#xff08;需截图&#xff09; 完成情况&#xff1a; 作业二&#xff1a;熟悉 hugging face 下载功能 作业要求&#xff1a;熟悉 hugging face 下载功能&#xff0c;使用…

Anaconda 环境中安装OpenCV (cv2)

1、使用Anaconda 的对应环境&#xff0c;查看环境中的Python版本号 (1)使用Anaconda 查看存在的环境&#xff1a;conda info --env (2)激活环境&#xff1a;conda activate XXX 2、根据版本号&#xff0c;下载对应的 python-opencv 包 &#xff08;1&#xff09;选择国内源的…

[MySQL]视图索引以及连接查询案列

目录 1.视图 1.1视图是什么 1.2视图的作用 1.3操作 1.3.1创建视图 1.3.2视图的修改 1.3.3删除视图 1.3.4查看视图 2.索引 2.1什么是索引 2.2为什么要使用索引 2.3索引的优缺点 2.3.1优点 2.3.2缺点 2.4索引的分类 3.连接查询案列 4.思维导图 1.视图 1.1视图是什么 视图…

el-table魔改样式出现BUG,表格内容区域出现滚动条

问题&#xff1a;el-table表格内容区域在高度自适应的情况下冒出滚动条 解决办法&#xff1a; 代码排查后发现时我设置了fixed:“xxx” 属性就会导致滚动条出现的问题&#xff0c;不设置则无。 [{ type: index, label: 序号, fixed: left },{ prop: enterprisesName, label: …

【C++】带你学会使用C++线程库thread、原子库atomic、互斥量库mutex、条件变量库condition_variable

C线程相关知识讲解 前言正式开始C官方为啥要提供线程库thread构造函数代码演示this_threadget_id()yield()sleep_until和sleep_for mutex构造函数lock和unlock上锁全局锁局部锁lambda表达式 try_lock 其他锁时间锁递归版本专用锁recursive_mutex 锁的异常处理lock_guardunique_…

springboot整合缓存技术

缓存&#xff08;cache&#xff09; 为啥需要使用缓存 问题描述&#xff1a;企业级应用主要作用是信息处理&#xff0c;当需要读取数据时&#xff0c;由于受限于数据库的访问效率&#xff0c;导致整体系统性能偏低。&#xff08;就是说&#xff1a;应用程序直接与数据库打交道…

深入C++继承:面向对象编程的核心概念

C是一种功能强大的编程语言&#xff0c;支持面向对象编程&#xff08;OOP&#xff09;范式。在面向对象编程中&#xff0c;继承是一种重要的概念&#xff0c;它使得我们能够创建具有层次结构的类&#xff0c;并实现代码的重用和扩展。本文将深入探讨C中的继承机制&#xff0c;介…
最新文章