Langchain 介绍与入门
官方介绍
LangChain 是一个利用LLM开发应用程序的框架。它让应用程序具备:
- 上下文感知能力:将LLM连接到上下文源(提示说明、少量示例、用以形成其响应的内容等)
- 推理:依靠LLM进行推理(例如根据提供的上下文确定如何回答、采取什么措施等)
LangChain 框架包含以下几部分:
- LangChain 库:Python 和 JavaScript 库。包含用于大量的接口、组件, 可以将这些组件组合到链和agents运行。
- LangChain 模板:针对常见不同任务的案例架构模版。
- LangServe:部署 LangChain 链的库,对外提供rest服务
- LangSmith:一个开发人员平台,可用于调试、测试、评估和监视以任何 LLM 框架内置的链,并与 LangChain 无缝集成。
安装
最省事的做法是,直接pip安装:
pip install langchain
安装 LangChain CLI 和 LangServe, 安装langchain-cli会自动安装LangServe
pip install langchain-cli
LLM调用
基本调用
手上暂时没有ChatGPT的apikey,所以用之前获取的google gemini llm。
需要先安装:
pip install --upgrade langchain-google-genai
开始第一个demo,api_key 需要先去google申请。
from langchain_google_genai import GoogleGenerativeAI
api_key = ""
llm = GoogleGenerativeAI(model="models/text-bison-001", google_api_key=api_key)
print(
llm.invoke(
"What are some of the pros and cons of Python as a programming language?"
)
)
运行脚本,就能获得LLM的响应结果:
[root@dev T2Ranking]#python lang_chain_demo.py
**Pros of Python:**
* **Simplicity:** Python is a relatively easy-to-learn language, with a simple syntax that is easy to read and write. This makes it a good choice for beginners and experienced programmers alike.
* **Versatility:** Python can be used for a wide variety of applications, including web development, data science, machine learning, and artificial intelligence. This makes it a good choice for developers who want to work on a variety of projects.
* **Libraries:** Python has a large and active community of developers who have created a wide variety of libraries and frameworks that can be used to extend the functionality of the language. This makes it easy to add new features and functionality to Python applications.
* **Cross-platform:** Python is cross-platform, which means that it can be run on a variety of operating systems, including Windows, macOS, and Linux. This makes it a good choice for developers who want to develop applications that can be used on multiple platforms.
* **Open source:** Python is an open-source language, which means that it is free to use and modify. This makes it a good choice for developers who want to create custom applications or who want to contribute to the development of the language itself.
**Cons of Python:**
* **Speed:** Python is not as fast as some other programming languages, such as C or C++. This can be a disadvantage for applications that require high performance.
* **Memory usage:** Python can also be more memory-intensive than other programming languages. This can be a disadvantage for applications that need to run on devices with limited memory.
* **Lack of static typing:** Python is a dynamically typed language, which means that the type of a variable is not known until runtime. This can make it difficult to catch errors early on in the development process.
* **Lack of support for multithreading:** Python does not have built-in support for multithreading. This can make it difficult to develop applications that can take advantage of multiple processors.
* **Security:** Python is not as secure as some other programming languages. This can be a disadvantage for applications that need to handle sensitive data.
Streaming calls 流式调用LLM
通过stream接口,可以让LLM流式返回结果,类似yield。
import sys
from langchain_google_genai import GoogleGenerativeAI
api_key = ""
llm = GoogleGenerativeAI(model="gemini-pro", google_api_key=api_key)
for chunk in llm.stream("Tell me a short poem about snow"):
sys.stdout.write(chunk)
sys.stdout.flush()
Chains
Chain是LangChain的核心概念,先就1个简单的chain来做基本的理解。
第一个chain
调整上面的demo代码:
from langchain_google_genai import GoogleGenerativeAI
from langchain.prompts import PromptTemplate
api_key = ""
llm = GoogleGenerativeAI(model="gemini-pro", google_api_key=api_key)
# print(
# llm.invoke(
# "What are some of the pros and cons of Python as a programming language?"
# )
# )
template = """Question: {question}
Answer: Let's think step by step."""
prompt = PromptTemplate.from_template(template)
chain = prompt | llm
question = "How much is 2+2?"
print(chain.invoke({"question": question}))
template是prompt模版,可以通过{变量}语法定义变量,调用时可以通过dict传入数据。chain的定义,先prompt,接一个|,特殊而容易理解的语法
执行:
[root@dev T2Ranking]#python lang_chain_demo.py
2+2 is a basic arithmetic problem. The answer is 4.
Retrieval
为了更好的回答一些问题,我们需要向LLM提供更多的上下文信息,让其参考以便更好的回答问题,langchain对这块做了较好的封装,这块也是langchain的精华部分,我们来细看是如何设计的。
![[Pasted image 20240227101802.png]]
文档加载器
可预知,企业内有各种各样的文档,所以这里抽象一个Document loaders 文档加载器,或者文档解析器。LangChain 提供了 100 多种Document loaders ,另外与该领域的一些商用服务做了集成,例如 AirByte 和 Unstructured。LangChain 也支持了从各种位置(私有 S3 存储桶、网站)加载各种类型的文档(HTML、PDF、代码)。
Text Splitting 文本拆分
源于用户的问题,大部分只需要文档的一小部分就能回答,另外现在embedding模型支持的长度普遍也不长,所以在RAG系统里,通常需要对长文档进行拆分,拆成一个一个的chunk。
LangChain 提供了几种转换算法来执行此操作,以及针对特定文档类型(代码、markdown 等)优化的逻辑。
| Name | Splits On | Adds Metadata | Description |
|---|---|---|---|
| Recursive | A list of user defined characters | Recursively splits text. Splitting text recursively serves the purpose of trying to keep related pieces of text next to each other. This is the recommended way to start splitting text. | |
| HTML | HTML specific characters | Splits text based on HTML-specific characters. Notably, this adds in relevant information about where that chunk came from (based on the HTML) | |
| Markdown | Markdown specific characters | Splits text based on Markdown-specific characters. Notably, this adds in relevant information about where that chunk came from (based on the Markdown) | |
| Code | Code (Python, JS) specific characters | Splits text based on characters specific to coding languages. 15 different languages are available to choose from. | |
| Token | Tokens | Splits text on tokens. There exist a few different ways to measure tokens. | |
| Character | A user defined character | Splits text based on a user defined character. One of the simpler methods. | |
| [Experimental] Semantic Chunker | Sentences | First splits on sentences. Then combines ones next to each other if they are semantically similar enough. Taken from Greg Kamradt |
文本embedding模型
检索的另一个关键部分是为文档创建embedding。embedding可以捕获文本的语义含义,通过ANN查询快速找到相似的其他文本片段。LangChain 提供了与 25 种不同的embedding提供商和方法的集成,从开源到专有 API都有覆盖。LangChain提供标准的统一接口,可以根据实际需要切换不同的model。
向量存储 Vector stores
embedding是RAG的标配,因此用于向量存储和ANN检索的向量数据库如雨后春笋不停涌现,LangChain 提供了与 50 多种不同的向量数据库的集成,从开源的本地存储到云托管的专有存储,用户可以根据实际情况选择最适合的向量数据库。LangChain提供标准的统一接口,可以方便在不同stores之间切换。
检索器 Retrievers
embedding存入数据库后,需要通过检索才能发挥最大作用。LangChain 支持多种不同的检索算法,其中包括:
Parent Document Retriever父文档检索器:允许为每个父文档创建多个embedding,查询时查找较小的块,但会返回较大的上下文
Self Query Retriever:允许你从query中解析出语义部分和其他元数据,来对数据进行过滤,下面的图可以很好的示意。
![[Pasted image 20240227124617.png]]Ensemble Retriever集成检索器:如果需要从多个不同的源或使用多个不同的算法来检索文档,可以使用集成检索器
...
Agents 智能体
agent智能体的核心思想是使用LLM决策一系列的action并执行。在链中,执行的action是硬编码的,而在agents智能体中,语言模型自行推理决策采用哪些action,以及action的执行顺序。智能体最早是autogpt开始兴起的,红极一时。
在LangChain中,Agent可以根据用户的输入动态地调用chains,将问题拆分为几个步骤,每个步骤都可以根据提供的Agent来执行相关的操作。此外,LangChain提供了多种类型的代理(Agents)和工具(Tools),以支持不同的应用场景和需求。
具体到Agent的工作原理,它首先接收来自用户的输入,然后根据输入的内容决定调用哪些工具(Tools)来完成任务。这些工具可以是内置的,也可以是自定义的,关键在于如何以对Agent有利的方式描述这些工具。例如,如果用户询问“本周的天气”,Agent可能会调用一个天气查询工具来获取答案,或者调用一个计算器来计算年龄等。
LangChain Agent的设计还考虑了泛化能力和Prompt控制,利用大型LLMs的强大few-shot和zero-shot泛化能力,以及Prompt控制的核心基础。这种设计使得LangChain Agent能够在没有大量训练数据的情况下,通过少量的提示就能生成有意义的回答,从而提高了其实用性和效率。
Langchain 介绍与入门的更多相关文章
- .NET平台开源项目速览(6)FluentValidation验证组件介绍与入门(一)
在文章:这些.NET开源项目你知道吗?让.NET开源来得更加猛烈些吧!(第二辑)中,给大家初步介绍了一下FluentValidation验证组件.那里只是概述了一下,并没有对其使用和强大功能做深入研究 ...
- freemarker语法介绍及其入门教程实例
# freemarker语法介绍及其入门教程实例 # ## FreeMarker标签使用 #####一.FreeMarker模板文件主要有4个部分组成</br>#### 1.文本,直接输 ...
- (转)私有代码存放仓库 BitBucket介绍及入门操作
转自:http://blog.csdn.net/lhb_0531/article/details/8602139 私有代码存放仓库 BitBucket介绍及入门操作 分类: 研发管理2013-02-2 ...
- NET平台开源项目速览(6)FluentValidation验证组件介绍与入门(转载)
原文地址:http://www.cnblogs.com/asxinyu/p/dotnet_Opensource_project_FluentValidation_1.html 阅读目录 1.基本介绍 ...
- 读写Word的组件DocX介绍与入门
本文为转载内容: 文章原地址:http://www.cnblogs.com/asxinyu/archive/2013/02/22/2921861.html 开源Word读写组件DocX介绍与入门 阅读 ...
- [转帖]Druid介绍及入门
Druid介绍及入门 2018-09-19 19:38:36 拿着核武器的程序员 阅读数 22552更多 分类专栏: Druid 版权声明:本文为博主原创文章,遵循CC 4.0 BY-SA版权协议 ...
- Redis介绍及入门安装及使用
Redis介绍及入门安装及使用 什么是Redis Redis is an open source (BSD licensed), in-memory data structure store, use ...
- Mysql数据库的简单介绍与入门
Mysql数据库的简单介绍与入门 前言 一.下载与安装 1.下载 官网下载MYSQL5.7.21版本,链接地址https://www.mysql.com/downloads/.下载流程图如下: 找到M ...
- day01-Mybatis介绍与入门
Mybatis介绍与入门 1.官方文档 Mybatis中文手册:mybatis – MyBatis 3 或者 MyBatis中文网 Maven仓库:Maven Repository: org.myba ...
- Nodejs学习笔记(十四)— Mongoose介绍和入门
目录 简介 mongoose安装 连接字符串 Schema Model 常用数据库操作 插入 更新 删除 条件查询 数量查询 根据_id查询 模糊查询 分页查询 其它操作 写在之后... 简介 Mon ...
随机推荐
- redis 6源码解析之 事件
redis的事件分为:文件事件和时间事件.文件事件是基于I/O的事务处理,时间事件则是基于时间点的事务处理.redis事件支持的多路复用包含四个实现:ae_epoll.c,ae_evport.c,ae ...
- CDP技术系列(一):使用bitmap存储数十亿用户ID的标签或群体
一.背景介绍 CDP系统中目前存在大量由用户ID集合组成的标签和群体,截止当前已有几千+标签,群体2W+. 大量的标签都是亿级别数据量以上,例如性别.职业.学历等均,甚至有群体中的ID数量达到了数十亿 ...
- dump分析器winbdg
工具: winbdg WinDBG不是专门用于调试.Net程序的工具,它更偏向于底层,可用于内核和驱动调试.进行普通的.Net程序调试还是使用微软专为.Net开发的调试工具MDBG更方便一些.但是Wi ...
- tortoisesvn中看到的版本号和svn info不一致
tortoisesvn中看到的版本号和svn info不一致 在svn命令行中通过svn info命令获得的版本号与tortoisesvn中show log看到的不一样,原因是在小乌龟中可以只更新具体 ...
- vim 从嫌弃到依赖(17)——查找模式
最开始介绍vim的时候,提到vim有普通模式.插入模式.可视模式和命令行模式,并且已经对这几个模式做了详细的介绍了.除了这几个模式以外,vim还有一个非常强大的模式--查找模式,为什么最开始没有将其列 ...
- errgroup的常见误用
errgroup想必稍有经验的golang程序员都应该听说过,实际项目中用过的也应该不在少数.它和sync.WaitGroup类似,都可以发起执行并等待一组协程直到所有协程运行结束.除此之外errgr ...
- 【8】同步vscode配置和插件【导入导出】、再也不用担心换电脑重新安装插件了
相关文章: [1]VScode中文界面方法-------超简单教程 [2]VScode搭建python和tensorflow环境 [3]VSCode 主题设置推荐,自定义配色方案,修改注释高亮颜色 [ ...
- Dash 2.15版本新特性介绍
本文示例代码已上传至我的Github仓库https://github.com/CNFeffery/dash-master 大家好我是费老师,Dash不久前发布了其2.15.0版本,新增了一些实用的特性 ...
- Docker从认识到实践再到底层原理(二-3)|LXC容器
前言 那么这里博主先安利一些干货满满的专栏了! 首先是博主的高质量博客的汇总,这个专栏里面的博客,都是博主最最用心写的一部分,干货满满,希望对大家有帮助. 高质量博客汇总 然后就是博主最近最花时间的一 ...
- Apache和Nginx是什么?|Nginx和Reactor是什么?|网路IO的本质|阻塞队列|异步非阻塞IO
前言 那么这里博主先安利一些干货满满的专栏了! 首先是博主的高质量博客的汇总,这个专栏里面的博客,都是博主最最用心写的一部分,干货满满,希望对大家有帮助. 高质量干货博客汇总https://blog. ...