【LangChain】数据连接(Data connection)

news2025/7/10 16:46:24

概要

许多LLM申请需要特定于用户的数据,这些数据不属于模型训练集的一部分。 LangChain 为您提供了通过以下方式加载、转换、存储和查询数据的构建块:

  • Document loaders : 从许多不同来源加载文档
  • Document transformers:拆分文档、将文档转换为问答格式、删除冗余文档等。
  • Text embedding models:获取非结构化文本并将其转换为浮点数列表
  • Vector stores:存储和搜索嵌入数据
  • Retrievers:Query your data

在这里插入图片描述

Document loaders(加载文档)

使用文档加载器从文档源加载数据。文档是一段文本和关联的元数据。例如,有一些文档加载器可以加载简单的 .txt 文件、加载任何网页的文本内容,甚至加载 YouTube 视频的脚本。

文档加载器提供了一个“加载”方法,用于从配置的源将数据加载为文档。它们还可以选择实现“延迟加载”,以便将数据延迟加载到内存中。

加载文件

最简单的加载程序将文件作为文本读入,并将其全部放入一个文档中。

from langchain.document_loaders import TextLoader

loader = TextLoader("./index.md")
loader.load()

结果:

[
    Document(page_content='---\nsidebar_position: 0\n---\n# Document loaders\n\nUse document loaders to load data from a source as `Document`\'s. A `Document` is a piece of text\nand associated metadata. For example, there are document loaders for loading a simple `.txt` file, for loading the text\ncontents of any web page, or even for loading a transcript of a YouTube video.\n\nEvery document loader exposes two methods:\n1. "Load": load documents from the configured source\n2. "Load and split": load documents from the configured source and split them using the passed in text splitter\n\nThey optionally implement:\n\n3. "Lazy load": load documents into memory lazily\n', metadata={'source': '../docs/docs_skeleton/docs/modules/data_connection/document_loaders/index.md'})
]

加载CSV文件

逗号分隔值 (CSV) 文件是使用逗号分隔值的分隔文本文件。文件的每一行都是一条数据记录。每条记录由一个或多个字段组成,以逗号分隔。

加载CSV 数据: 每行就是一个文档。

from langchain.document_loaders.csv_loader import CSVLoader

loader = CSVLoader(file_path='./example_data/mlb_teams_2012.csv')
data = loader.load()
print(data)

结果:

    [Document(page_content='Team: Nationals\n"Payroll (millions)": 81.34\n"Wins": 98', lookup_str='', metadata={'source': './example_data/mlb_teams_2012.csv', 'row': 0}, lookup_index=0), Document(page_content='Team: Reds\n"Payroll (millions)": 82.20\n"Wins": 97', lookup_str='', metadata={'source': './example_data/mlb_teams_2012.csv', 'row': 1}, lookup_index=0), Document(page_content='Team: Yankees\n"Payroll (millions)": 197.96\n"Wins": 95', lookup_str='', metadata={'source': './example_data/mlb_teams_2012.csv', 'row': 2}, lookup_index=0), Document(page_content='Team: Giants\n"Payroll (millions)": 117.62\n"Wins": 94', lookup_str='', metadata={'source': './example_data/mlb_teams_2012.csv', 'row': 3}, lookup_index=0)]

自定义 csv 解析和加载

有关支持哪些 csv 参数的更多信息,请参阅 csv 模块文档。

# 注意csv_args参数
loader = CSVLoader(file_path='./example_data/mlb_teams_2012.csv', csv_args={
    'delimiter': ',',
    'quotechar': '"',
    'fieldnames': ['MLB Team', 'Payroll in millions', 'Wins']
})

data = loader.load()
print(data)

结果:

[Document(page_content='Team: Nationals\n"Payroll (millions)": 81.34\n"Wins": 98', lookup_str='', metadata={'source': './example_data/mlb_teams_2012.csv', 'row': 0}, lookup_index=0), Document(page_content='Team: Reds\n"Payroll (millions)": 82.20\n"Wins": 97', lookup_str='', metadata={'source': './example_data/mlb_teams_2012.csv', 'row': 1}, lookup_index=0), Document(page_content='Team: Yankees\n"Payroll (millions)": 197.96\n"Wins": 95', lookup_str='', metadata={'source': './example_data/mlb_teams_2012.csv', 'row': 2}, lookup_index=0), Document(page_content='Team: Giants\n"Payroll (millions)": 117.62\n"Wins": 94', lookup_str='', metadata={'source': './example_data/mlb_teams_2012.csv', 'row': 3}, lookup_index=0)]

指定一列来标识文档来源(Specify a column to identify the document source)

使用 source_column 参数指定从每行创建文档的来源。否则,就取file_path 字段当做来源。

当使用从 CSV 文件加载的文档用于使用sources回答问题的链时,这非常有用。

loader = CSVLoader(file_path='./example_data/mlb_teams_2012.csv', source_column="Team")

data = loader.load()
print(data)

结果:

[Document(page_content='Team: Nationals\n"Payroll (millions)": 81.34\n"Wins": 98', lookup_str='', metadata={'source': 'Nationals', 'row': 0}, lookup_index=0), Document(page_content='Team: Reds\n"Payroll (millions)": 82.20\n"Wins": 97', lookup_str='', metadata={'source': 'Reds', 'row': 1}, lookup_index=0), Document(page_content='Team: Yankees\n"Payroll (millions)": 197.96\n"Wins": 95', lookup_str='', metadata={'source': 'Yankees', 'row': 2}, lookup_index=0), Document(page_content='Team: Giants\n"Payroll (millions)": 117.62\n"Wins": 94', lookup_str='', metadata={'source': 'Giants', 'row': 3}, lookup_index=0)]

文件目录(File Directory)

如何加载目录中的所有文档。默认情况下使用 UnstructedLoader。

from langchain.document_loaders import DirectoryLoader

我们可以使用 glob 参数来控制加载哪些文件。请注意,这里它不会加载 .rst 文件或 .html 文件。

loader = DirectoryLoader('../', glob="**/*.md")
docs = loader.load()
len(docs)

显示进度条(Show a progress bar)

默认情况下不会显示进度条。要显示进度条,请安装 tqdm 库(即:执行:pip install tqdm),并将 show_progress参数设置为 True

# 注意show_progress参数
loader = DirectoryLoader('../', glob="**/*.md", show_progress=True)
docs = loader.load()

结果:

    Requirement already satisfied: tqdm in /Users/jon/.pyenv/versions/3.9.16/envs/microbiome-app/lib/python3.9/site-packages (4.65.0)

# 进度条
    0it [00:00, ?it/s]

使用多线程(Use multithreading)

默认情况下,加载发生在一个线程中。为了利用多个线程,请将use_multithreading标志设置为 true

# 使用多线程进行加载:use_multithreading=True
loader = DirectoryLoader('../', glob="**/*.md", use_multithreading=True)
docs = loader.load()

更改加载器类(Change loader class)

默认情况下,是使用 UnstructedLoader类进行加载。但是,您可以很容易地更改加载程序的类型。

from langchain.document_loaders import TextLoader
# loader_cls指定加载器类
loader = DirectoryLoader('../', glob="**/*.md", loader_cls=TextLoader)
docs = loader.load()
len(docs)
# 结果
    1

如果需要加载Python源代码文件,请使用PythonLoader

from langchain.document_loaders import PythonLoader
# loader_cls指定python加载器类
loader = DirectoryLoader('../../../../../', glob="**/*.py", loader_cls=PythonLoader)
docs = loader.load()
len(docs)
# 结果
    691

使用 TextLoader 自动检测文件编码(Auto detect file encodings with TextLoader)

在此示例中,我们将看到一些策略,这些策略在使用 TextLoader 类从目录加载大量任意文件时非常有用。

path = '../../../../../tests/integration_tests/examples'
loader = DirectoryLoader(path, glob="**/*.txt", loader_cls=TextLoader)

A. 默认行为

loader.load()

结果:

<pre style="white-space:pre;overflow-x:auto;line-height:normal;font-family:Menlo,'DejaVu Sans Mono',consolas,'Courier New',monospace"><span style="color: #800000; text-decoration-color: #800000">╭─────────────────────────────── </span><span style="color: #800000; text-decoration-color: #800000; font-weight: bold">Traceback </span><span style="color: #bf7f7f; text-decoration-color: #bf7f7f; font-weight: bold">(most recent call last)</span><span style="color: #800000; text-decoration-color: #800000"> ────────────────────────────────╮</span>
<span style="color: #800000; text-decoration-color: #800000"></span> <span style="color: #bfbf7f; text-decoration-color: #bfbf7f">/data/source/langchain/langchain/document_loaders/</span><span style="color: #808000; text-decoration-color: #808000; font-weight: bold">text.py</span>:<span style="color: #0000ff; text-decoration-color: #0000ff">29</span> in <span style="color: #00ff00; text-decoration-color: #00ff00">load</span>                             <span style="color: #800000; text-decoration-color: #800000"></span>
<span style="color: #800000; text-decoration-color: #800000"></span>  
<span style="color: #ff0000; text-decoration-color: #ff0000; font-weight: bold">RuntimeError: </span>Error loading ..<span style="color: #800080; text-decoration-color: #800080">/../../../../tests/integration_tests/examples/</span><span style="color: #ff00ff; text-decoration-color: #ff00ff">example-non-utf8.txt</span>
</pre>

上面有所省略

文件 example-non-utf8.txt 使用不同的编码,load() 函数失败,并显示一条有用的消息,指示哪个文件解码失败。

TextLoader 的默认行为下,任何文档加载失败都会导致整个加载过程失败,并且不会加载任何文档。

B. 无声的失败(B. Silent fail)

我们可以将参数silent_errors传递给DirectoryLoader来跳过无法加载的文件并继续加载过程。

# 指定参数:silent_errors,跳过无法加载的文件
loader = DirectoryLoader(path, glob="**/*.txt", loader_cls=TextLoader, silent_errors=True)
docs = loader.load()

结果:

    Error loading ../../../../../tests/integration_tests/examples/example-non-utf8.txt

这样我们在加载多个文件时:

doc_sources = [doc.metadata['source']  for doc in docs]
doc_sources

其结果:

    ['../../../../../tests/integration_tests/examples/whatsapp_chat.txt',
     '../../../../../tests/integration_tests/examples/example-utf8.txt']

C. 自动检测编码(C. Auto detect encodings)

我们还可以通过将 autodetect_encoding 传递给加载器类,要求 TextLoader 在失败之前自动检测文件编码。

# 指定autodetect_encoding 参数,自动检测文件编码
text_loader_kwargs={'autodetect_encoding': True}
loader = DirectoryLoader(path, glob="**/*.txt", loader_cls=TextLoader, loader_kwargs=text_loader_kwargs)
docs = loader.load()

doc_sources = [doc.metadata['source']  for doc in docs]
doc_sources

结果:

    ['../../../../../tests/integration_tests/examples/example-non-utf8.txt',
     '../../../../../tests/integration_tests/examples/whatsapp_chat.txt',
     '../../../../../tests/integration_tests/examples/example-utf8.txt']

参考地址:

https://python.langchain.com/docs/modules/data_connection/document_loaders/how_to/file_directory

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

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

怎么把文档翻译成英文?这几款文档翻译工具都能实现

听说你正在寻找免费的文档翻译软件&#xff0c;我来给你一些建议吧&#xff01;翻译软件的确是个很有用的工具&#xff0c;能够帮助我们快速翻译各种语言的文档。而且现在有很多免费的选择&#xff0c;真是再好不过了&#xff01;但是随着市面上文档翻译软件数量的增多&#xf…

车载测试:车联网功能组件及安全测试策略

目录 一、车联网功能组件 车域网 IVI TBOX ECU TSP APP 通信及密码特殊指标 车端特殊指标 APP特殊指标 测试用例 一、车联网功能组件 车联网是以汽车智能化、网联化为基础&#xff0c;广泛应用新一代通信技术、人工智能技术构建起的新型基础设施。在整体架构上&…

单据小票打印模板自定义设计,手机收银软件APP搭配蓝牙便携打印机,移动便携打印零售单单据小票

单据小票打印模板自定义设计&#xff0c;手机收银软件APP搭配蓝牙便携打印机&#xff0c;移动便携打印零售单单据小票&#xff0c;轻松实现仓库条码管理&#xff0c;扫码入库出库盘点_哔哩哔哩_bilibili单据小票打印模板自定义设计&#xff0c;手机收银软件APP搭配蓝牙便携打印…

突破平凡:创造独特而吸引人的登陆页UI设计灵感

今天&#xff0c;我们从移动APP产品经理或者UI设计师的角度再来聊一聊APP登录设计方式和如何去设计这些有意思的APP登录模块。 1、熟悉目前常见的手机APP登陆方式 ① 账号登陆&#xff08;手机、邮箱&#xff09; ② 第三方登陆&#xff08;微信&#xff0c;QQ&#xff0c;微博…

Java编程-IDEA中Java的main方法、sout快捷键设置

目的 我打出psvm这四个字母时&#xff0c;可快速打出main方法 我打出syso,sout时&#xff0c;可快速打出System.out.println(); 步骤&#xff1a; 1、打开IDEA&#xff0c;点击文件&#xff0c;选择Editor中的 Live Templates选项&#xff0c;点击右侧边栏中的 号 2、选中…

quartus工具篇——Signal Tap

文章目录 quartus工具篇——Signal Tap1、Signal Tap简介2、操作步骤3、查看波形结果4、总结 quartus工具篇——Signal Tap 1、Signal Tap简介 Quartus中的Signal Tap是一种用于FPGA设计调试和分析的工具。它可以捕获和显示设计中的信号波形&#xff0c;帮助设计人员验证设计…

安卓:表示日期的控件

一、日期控件 &#xff08;一&#xff09;、DatePicker DatePicker是一种安卓平台上常用的控件&#xff0c;用于让用户选择日期。它通常以日历的形式显示&#xff0c;并允许用户通过滑动或点击来选择年、月和日。 常用属性&#xff1a; android:calendarViewShown&#xff1…

第一阶段-第十二章 Python基础的综合案例(数据可视化-动态柱状图)

目录 引、案例效果一、基础柱状图的构建  1.学习目标  2.通过Bar构建基础柱状图  3.反转x和y轴  4.数值标签在右侧  5.本节的演示  6.本小节的总结 二、基础时间线柱状图  1.学习目标  2.时间线  3. 自动播放  4.时间线的主题  5.本节的代码演示  6.本…

MSP432自主开发笔记3:串口__编写自定义printf发送函数、编写发送字节字符串函数编写

之前其实对于串口在收发字节、收发字符串方面的介绍已经挺完全了&#xff0c; 但今日无意间发现漏了些什么&#xff0c;之前有讲到过串口的printf()发送问题&#xff0c;但也仅仅教大家如何重定向printf&#xff08;&#xff09;&#xff1b;来决定向哪个串口发送数据. print…

代码随想录算法训练营第57天 | 动态规划 part17 ● 647 回文子串 ●516最长回文子序列 ●动归总结

#647 回文子串 自己不会做。 之前遇到的大部分题目是&#xff0c;我们求什么dp里面就放什么。但这道回文的题不是&#xff1a;" 本题如果我们定义&#xff0c;dp[i] 为 下标i结尾的字符串有 dp[i]个回文串的话&#xff0c;我们会发现很难找到递归关系。dp[i] 和 dp[i-1]…

自监督语义分割面模型——Masked Autoencoders Are Scalable Vision Learners(MAE)论文阅读

1、摘要 This paper shows that masked autoencoders (MAE) are scalable self-supervised learners for computer vision. Our MAE approach is simple: we mask random patches of the input image and reconstruct the missing pixels. It is based on two core designs. F…

实现二分搜索函数,设计脚手架程序进行自动测试。

1. 设计思路   二分搜索算法每次将数组中间值与目标值相比较&#xff0c;若相同&#xff0c;则该元素就是要寻找的元素&#xff0c;若不相同&#xff0c;二分搜索法通过一定的方法抛弃一半的待搜索区间&#xff0c;在剩余的区间中继续以相同方法搜索目标值. 2.源代码 #incl…

网络存储技术知识点整理

目录 前言1. 直接附加存储2. 网络附加存储3. 存储区域网络 前言 目前主流的存储技术只要有三种&#xff1a; 直接附加存储&#xff08;Direct Attached Storage&#xff0c;DAS&#xff09;网络附加存储&#xff08;Network Attached Storage&#xff0c;NAS&#xff09;存储…

flutter开发实战-Canvas绘图之Path路径动画

flutter开发实战-Canvas绘图之Path路径动画 flutter提供一块2D画布Canvas&#xff0c;Canvas内部封装了一些基本绘制的API&#xff0c;开发者可以通过Canvas绘制各种自定义图形。canvas上绘图&#xff0c;有多种不同的方式&#xff0c;常用的就是使用 Path。这里是flutter实现…

10分钟设置免费远程桌面

“你见过洛杉矶凌晨4点的样子吗&#xff1f;” 没有也没关系&#xff0c;你可以轻松配置一台位于洛杉矶的免费远程桌面。 利用Amazon全球可用区&#xff0c;甚至可以在世界各地搭建符合你配置需求的远程桌面。 本教程需要先拥有亚马逊云科技海外账户。目前注册亚马逊云科技账户…

32-ADC的寄存器

目录 stm32-adc通过比较获取电压原理 为什么会分注入组和规则组&#xff1f; “ECO"是指"Engineering Change Order”&#xff0c;即工程变更指令。 双ADC的不同模式以及为什么会有这个模式&#xff1a; 同步注入模式&#xff1a; 同步规则模式&#xff1a; 快…

应用系统的集成的方式

一、说明 应用系统的集成从技术上可以分为界面集成、数据集成、接口集成、流程集成和平台集成等多种方式。 二、详情 2.1界面集成 指的是系统与系统之间没有实质上的关联&#xff0c;只是汇聚到同样的应用接人点&#xff0c;采用类似的初始界面&#xff0c;或者统一的登录手…

IDEA修改新添加项目的Maven配置信息

改成自己的Maven环境即可 以后打开新项目都会自动哟用这个

【JDK环境配置】| 两种JDK环境能在同一台电脑共存吗?

目录 &#x1f981; 前言&#x1f981; 基础环境&#x1f981; 安装JDK1.8Ⅰ. 下载Ⅱ. 安装 &#x1f981; 在项目里更改JDK版本---------------------------------------------福利在下面--------------------------------------------------&#x1f981; 福利&#xff08;送…

一张表实现短视频“评论区“完整功能

前言 现如今&#xff0c;不管是哪种类型的应用&#xff0c;评论区都少不了。从工具类的到媒体信息流类的&#xff0c;评论留言都是最基本的互动环节。比如抖音短视频下&#xff0c;针对视频每个用户都可以发表自己的观点&#xff1b;而针对用户的评论&#xff0c;其他的用户又可…