【LLM大模型】Langchain 介绍与入门

官方介绍

LangChain 是一个利用LLM开发应用程序的框架。它让应用程序具备:

  • 上下文感知能力:将LLM连接到上下文源(提示说明、少量示例、用以形成其响应的内容等)
  • 推理:依靠LLM进行推理(例如根据提供的上下文确定如何回答、采取什么措施等)

LangChain 框架包含以下几部分:

  • LangChain 库:Python 和 JavaScript 库。包含用于大量的接口、组件, 可以将这些组件组合到链和agents运行。
  • LangChain 模板:针对常见不同任务的案例架构模版。
  • LangServe:部署 LangChain 链的库,对外提供rest服务
  • LangSmith:一个开发人员平台,可用于调试、测试、评估和监视以任何 LLM 框架内置的链,并与 LangChain 无缝集成。

安装

最省事的做法是,直接pip安装:

Copy
pip install langchain

安装 LangChain CLI 和 LangServe, 安装langchain-cli会自动安装LangServe

Copy
pip install langchain-cli

LLM调用

基本调用

手上暂时没有ChatGPT的apikey,所以用之前获取的google gemini llm。

需要先安装:

Copy
pip install --upgrade  langchain-google-genai

开始第一个demo,api_key 需要先去google申请。

Copy
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的响应结果:

Copy
[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

Copy
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代码:

Copy
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,接一个 |,特殊而容易理解的语法

执行:

Copy
[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 等)优化的逻辑。

NameSplits OnAdds MetadataDescription
RecursiveA list of user defined charactersRecursively 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.
HTMLHTML specific charactersSplits text based on HTML-specific characters. Notably, this adds in relevant information about where that chunk came from (based on the HTML)
MarkdownMarkdown specific charactersSplits text based on Markdown-specific characters. Notably, this adds in relevant information about where that chunk came from (based on the Markdown)
CodeCode (Python, JS) specific charactersSplits text based on characters specific to coding languages. 15 different languages are available to choose from.
TokenTokensSplits text on tokens. There exist a few different ways to measure tokens.
CharacterA user defined characterSplits text based on a user defined character. One of the simpler methods.
[Experimental] Semantic ChunkerSentencesFirst 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能够在没有大量训练数据的情况下,通过少量的提示就能生成有意义的回答,从而提高了其实用性和效率。

如何系统的去学习大模型LLM ?

作为一名热心肠的互联网老兵,我意识到有很多经验和知识值得分享给大家,也可以通过我们的能力和经验解答大家在人工智能学习中的很多困惑,所以在工作繁忙的情况下还是坚持各种整理和分享。

但苦于知识传播途径有限,很多互联网行业朋友无法获得正确的资料得到学习提升,故此将并将重要的 AI大模型资料 包括AI大模型入门学习思维导图、精品AI大模型学习书籍手册、视频教程、实战学习等录播视频免费分享出来

所有资料 ⚡️ ,朋友们如果有需要全套 《LLM大模型入门+进阶学习资源包》,扫码获取~

👉CSDN大礼包🎁:全网最全《LLM大模型入门+进阶学习资源包》免费分享(安全链接,放心点击)👈

一、全套AGI大模型学习路线

AI大模型时代的学习之旅:从基础到前沿,掌握人工智能的核心技能!

img

二、640套AI大模型报告合集

这套包含640份报告的合集,涵盖了AI大模型的理论研究、技术实现、行业应用等多个方面。无论您是科研人员、工程师,还是对AI大模型感兴趣的爱好者,这套报告合集都将为您提供宝贵的信息和启示。

img

三、AI大模型经典PDF籍

随着人工智能技术的飞速发展,AI大模型已经成为了当今科技领域的一大热点。这些大型预训练模型,如GPT-3、BERT、XLNet等,以其强大的语言理解和生成能力,正在改变我们对人工智能的认识。 那以下这些PDF籍就是非常不错的学习资源。

img

在这里插入图片描述

四、AI大模型商业化落地方案

img

阶段1:AI大模型时代的基础理解

  • 目标:了解AI大模型的基本概念、发展历程和核心原理。
  • 内容
    • L1.1 人工智能简述与大模型起源
    • L1.2 大模型与通用人工智能
    • L1.3 GPT模型的发展历程
    • L1.4 模型工程
      - L1.4.1 知识大模型
      - L1.4.2 生产大模型
      - L1.4.3 模型工程方法论
      - L1.4.4 模型工程实践
    • L1.5 GPT应用案例

阶段2:AI大模型API应用开发工程

  • 目标:掌握AI大模型API的使用和开发,以及相关的编程技能。
  • 内容
    • L2.1 API接口
      - L2.1.1 OpenAI API接口
      - L2.1.2 Python接口接入
      - L2.1.3 BOT工具类框架
      - L2.1.4 代码示例
    • L2.2 Prompt框架
      - L2.2.1 什么是Prompt
      - L2.2.2 Prompt框架应用现状
      - L2.2.3 基于GPTAS的Prompt框架
      - L2.2.4 Prompt框架与Thought
      - L2.2.5 Prompt框架与提示词
    • L2.3 流水线工程
      - L2.3.1 流水线工程的概念
      - L2.3.2 流水线工程的优点
      - L2.3.3 流水线工程的应用
    • L2.4 总结与展望

阶段3:AI大模型应用架构实践

  • 目标:深入理解AI大模型的应用架构,并能够进行私有化部署。
  • 内容
    • L3.1 Agent模型框架
      - L3.1.1 Agent模型框架的设计理念
      - L3.1.2 Agent模型框架的核心组件
      - L3.1.3 Agent模型框架的实现细节
    • L3.2 MetaGPT
      - L3.2.1 MetaGPT的基本概念
      - L3.2.2 MetaGPT的工作原理
      - L3.2.3 MetaGPT的应用场景
    • L3.3 ChatGLM
      - L3.3.1 ChatGLM的特点
      - L3.3.2 ChatGLM的开发环境
      - L3.3.3 ChatGLM的使用示例
    • L3.4 LLAMA
      - L3.4.1 LLAMA的特点
      - L3.4.2 LLAMA的开发环境
      - L3.4.3 LLAMA的使用示例
    • L3.5 其他大模型介绍

阶段4:AI大模型私有化部署

  • 目标:掌握多种AI大模型的私有化部署,包括多模态和特定领域模型。
  • 内容
    • L4.1 模型私有化部署概述
    • L4.2 模型私有化部署的关键技术
    • L4.3 模型私有化部署的实施步骤
    • L4.4 模型私有化部署的应用场景

学习计划:

  • 阶段1:1-2个月,建立AI大模型的基础知识体系。
  • 阶段2:2-3个月,专注于API应用开发能力的提升。
  • 阶段3:3-4个月,深入实践AI大模型的应用架构和私有化部署。
  • 阶段4:4-5个月,专注于高级模型的应用和部署。
这份完整版的所有 ⚡️ 大模型 LLM 学习资料已经上传CSDN,朋友们如果需要可以微信扫描下方CSDN官方认证二维码免费领取【保证100%免费

全套 《LLM大模型入门+进阶学习资源包↓↓↓ 获取~

👉CSDN大礼包🎁:全网最全《LLM大模型入门+进阶学习资源包》免费分享(安全链接,放心点击)👈

  • 6
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值