官方介绍

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 介绍与入门的更多相关文章

  1. .NET平台开源项目速览(6)FluentValidation验证组件介绍与入门(一)

    在文章:这些.NET开源项目你知道吗?让.NET开源来得更加猛烈些吧!(第二辑)中,给大家初步介绍了一下FluentValidation验证组件.那里只是概述了一下,并没有对其使用和强大功能做深入研究 ...

  2. freemarker语法介绍及其入门教程实例

    # freemarker语法介绍及其入门教程实例 # ## FreeMarker标签使用 #####一.FreeMarker模板文件主要有4个部分组成</br>####  1.文本,直接输 ...

  3. (转)私有代码存放仓库 BitBucket介绍及入门操作

    转自:http://blog.csdn.net/lhb_0531/article/details/8602139 私有代码存放仓库 BitBucket介绍及入门操作 分类: 研发管理2013-02-2 ...

  4. NET平台开源项目速览(6)FluentValidation验证组件介绍与入门(转载)

    原文地址:http://www.cnblogs.com/asxinyu/p/dotnet_Opensource_project_FluentValidation_1.html 阅读目录 1.基本介绍 ...

  5. 读写Word的组件DocX介绍与入门

    本文为转载内容: 文章原地址:http://www.cnblogs.com/asxinyu/archive/2013/02/22/2921861.html 开源Word读写组件DocX介绍与入门 阅读 ...

  6. [转帖]Druid介绍及入门

    Druid介绍及入门 2018-09-19 19:38:36 拿着核武器的程序员 阅读数 22552更多 分类专栏: Druid   版权声明:本文为博主原创文章,遵循CC 4.0 BY-SA版权协议 ...

  7. Redis介绍及入门安装及使用

    Redis介绍及入门安装及使用 什么是Redis Redis is an open source (BSD licensed), in-memory data structure store, use ...

  8. Mysql数据库的简单介绍与入门

    Mysql数据库的简单介绍与入门 前言 一.下载与安装 1.下载 官网下载MYSQL5.7.21版本,链接地址https://www.mysql.com/downloads/.下载流程图如下: 找到M ...

  9. day01-Mybatis介绍与入门

    Mybatis介绍与入门 1.官方文档 Mybatis中文手册:mybatis – MyBatis 3 或者 MyBatis中文网 Maven仓库:Maven Repository: org.myba ...

  10. Nodejs学习笔记(十四)— Mongoose介绍和入门

    目录 简介 mongoose安装 连接字符串 Schema Model 常用数据库操作 插入 更新 删除 条件查询 数量查询 根据_id查询 模糊查询 分页查询 其它操作 写在之后... 简介 Mon ...

随机推荐

  1. 使用Configmap 配置 springboot的application.yaml文件的方式部署环境的方法

    Configmap部署k8s下Springboot服务的办法 前提 日常工作中需要使用k8s部署微服务环境, 但是内部的数据库连接和redis等连接非常麻烦,使用helm chart 进行变量替换时非 ...

  2. 一种轻量分表方案-MyBatis拦截器分表实践

    背景 部门内有一些亿级别核心业务表增速非常快,增量日均100W,但线上业务只依赖近一周的数据.随着数据量的迅速增长,慢SQL频发,数据库性能下降,系统稳定性受到严重影响.本篇文章,将分享如何使用MyB ...

  3. 【网络流,dp】Gym102220A Apple Business

    Problem Link 有一棵 \(n\) 个点的完全二叉树(点 \(i\) 的父亲是 \(\lfloor i/2\rfloor\)),第 \(i\) 个点有 \(a_i\) 个苹果.现在有 \(m ...

  4. element-ui表格排序

    <el-table :data="TableAwitDoArr" style="width: 100%"> <el-table-column ...

  5. 7.6 Windows驱动开发:内核监控FileObject文件回调

    本篇文章与上一篇文章<内核注册并监控对象回调>所使用的方式是一样的都是使用ObRegisterCallbacks注册回调事件,只不过上一篇博文中LyShark将回调结构体OB_OPERAT ...

  6. MySQL 索引与性能调优

    索引用于快速找出在某个列中有一特定值的行,如果不使用索引MySQL必须从第l条记录开始读完整个表,直到找出相关的行.表越大,查询数据所花费的时间越多,如果表中查询的列有一个索引,MySQL能快速到达某 ...

  7. Windows上部署Python flask项目

    最近使用Python flask做了一个项目要部署,网上一大堆教程没有一个完整,最后看了多个教程才配置完成,下面根据自己的环境整理一下做个备忘录 环境: Windows 10 apache httpd ...

  8. Apache和Nginx是什么?|Nginx和Reactor是什么?|网路IO的本质|阻塞队列|异步非阻塞IO

    前言 那么这里博主先安利一些干货满满的专栏了! 首先是博主的高质量博客的汇总,这个专栏里面的博客,都是博主最最用心写的一部分,干货满满,希望对大家有帮助. 高质量干货博客汇总https://blog. ...

  9. TPopupMenu 替换 自身自动的 热键

    有时候自动生成的热键 并不是 很理想 这个时候 需要 用自己认为好的 方法如下图,加个(&热键)

  10. C++——数据类型笔记

    在C++编程中,了解各类数据类型也是至关重要的.下面我会总结一下C++中的数据类型,包括基本类型,符合类型和自定义类型.方便自己整理和理解. 1,基本类型 C++中的基本类型是构建其他数据类型的基础, ...