前言
该系列教程的代码: https://github.com/shar-pen/Langchain-MiniTutorial
我主要参考 langchain 官方教程, 有选择性的记录了一下学习内容
这是教程清单
- 1.初试langchain
- 2.prompt
- 3.OutputParser/输出解析
- 4.model/vllm模型部署和langchain调用
- 5.DocumentLoader/多种文档加载器
- 6.TextSplitter/文档切分
- 7.Embedding/文本向量化
- 8.VectorStore/向量数据库存储和检索
- 9.Retriever/检索器
- 10.Reranker/文档重排序
- 11.RAG管道/多轮对话RAG
- 12.Agent/工具定义/Agent调用工具/Agentic RAG
Document
用于存储一段文本及其相关元数据的类。
page_content
(必需):以字符串形式存储一段文本。metadata
(可选):以字典形式存储与page_content
相关的元数据。
from langchain_core.documents import Document
document = Document(page_content="Hello, welcome to LangChain Open Tutorial!")
document
Document(metadata={}, page_content='Hello, welcome to LangChain Open Tutorial!')
文档加载器(Document Loader)
文档加载器是一个用于从各种来源加载 Document
的类。
以下是一些常见的文档加载器示例:
PyPDFLoader
:加载 PDF 文件CSVLoader
:加载 CSV 文件UnstructuredHTMLLoader
:加载 HTML 文件JSONLoader
:加载 JSON 文件TextLoader
:加载纯文本文件DirectoryLoader
:从目录中批量加载文档
from langchain_community.document_loaders import PyPDFLoader
# Set up the loader
FILE_PATH = "./data/01-document-loader-sample.pdf"
loader = PyPDFLoader(FILE_PATH)
load()
- 加载文档,并以
list[Document]
的形式返回。
docs = loader.load()
print(len(docs))
print('-'*3)
docs[0:2]
48
---
[Document(metadata={'source': './data/01-document-loader-sample.pdf', 'page': 0}, page_content=' \n \n \nOctober 2016 \n \n \n \n \n \n \n \n \n \nTHE NATIONAL \nARTIFICIAL INTELLIGENCE \nRESEARCH AND DEVELOPMENT \nSTRATEGIC PLAN \nNational Science and Technology Council \n \nNetworking and Information Technology \nResearch and Development Subcommittee \n '),
Document(metadata={'source': './data/01-document-loader-sample.pdf', 'page': 1}, page_content=' ii \n \n ')]
aload()
- 异步加载文档,并以
list[Document]
的形式返回。
# Load Documents asynchronously
docs = await loader.aload()
lazy_load()
- 顺序加载文档,并以
Iterator[Document]
的形式返回。
docs = loader.lazy_load()
for doc in docs:
print(doc.metadata)
break # Used to limit the output length
alazy_load()
- 异步顺序加载文档,并以
AsyncIterator[Document]
的形式返回。
可以观察到,这种方法作为一个 async_generator
工作。它是一种特殊类型的异步迭代器,能够按需生成值,而不需要一次性将所有值存储在内存中。
loader.alazy_load()
docs = loader.alazy_load()
async for doc in docs:
print(doc.metadata)
break # Used to limit the output length
load_and_split()
- 加载文档,并使用
TextSplitter
自动拆分为多个文本块,最终以list[Document]
的形式返回。
from langchain_text_splitters import RecursiveCharacterTextSplitter
# Set up the TextSplitter
text_splitter = RecursiveCharacterTextSplitter(chunk_size=128, chunk_overlap=0)
# Split Documents into chunks
docs = loader.load_and_split(text_splitter=text_splitter)
<