01 | 引言
上一节我们聊到的是数据的加载
数据加载可以实现如下的能力: 加载最新的数据,用于模型总结归纳或者信息提取; 加载文档,比如PDF等文档,实现总结归纳等能力; 加载数据库,实现业务自身能力;
果冻布丁兔,公众号:陆队长GPT入门(七)LangChain外部数据加载
加载之后不就是会访问呢?那这里的访问又是什么意思呢?
02 | 数据加载和数据数据的区别
我们再看下两个类的注释区别:
我们先看数据加载的逻辑,也就是上节课提到的Loader组件。
class BaseLoader(ABC):
"""Interface for loading documents.
Implementations should implement the lazy-loading method using generators
to avoid loading all documents into memory at once.
The `load` method will remain as is for backwards compatibility, but its
implementation should be just `list(self.lazy_load())`.
"""
将注释内容翻译一下就是:
我们在实现数据加载时,需要使用生成器实现延迟加载的方法,以避免一次性将所有的文档加载到内存中。
同时,为了向后兼容,load方法将保持原样,其实现应该只是list(self.lazy_load())
我们再看下数据访问的逻辑。
class Docstore(ABC):
"""Interface to access to place that stores documents."""
@abstractmethod
def search(self, search: str) -> Union[str, Document]:
"""Search for document.
If page exists, return the page summary, and a Document object.
If page does not exist, return similar entries.
"""
类似上面,我们将其中的注释进行简单翻译:
首先,基类声明,它是一个访问文件存储位置的接口。
它的查找方法search的功能是查找一份文件,如果文件存在,则返回页面摘要和Document对象。若页面不存在,则返回类似的条目。
也就是说,数据访问接口store组件主要关注的是文件存储的位置,也就是访问的是存储了Documens的接口,任何的数据库、网络、内存等等都可以看成是一个store,只要实现了search接口,就能够进行检索。
LangChain已经给出的store实现只有四个,其中我们直接看下wiki的store吧,毕竟这个对我们来说比较熟悉。
class Wikipedia(Docstore):
"""Wrapper around wikipedia API."""
def search(self, search: str) -> Union[str, Document]:
"""Try to search for wiki page.
If page exists, return the page summary, and a PageWithLookups object.
If page does not exist, return similar entries.
"""
import wikipedia
try:
page_content = wikipedia.page(search).content
url = wikipedia.page(search).url
result: Union[str, Document] = Document(
page_content=page_content, metadata={"page": url}
)
except wikipedia.PageError:
result = f"Could not find [{search}]. Similar: {wikipedia.search(search)}"
except wikipedia.DisambiguationError:
result = f"Could not find [{search}]. Similar: {wikipedia.search(search)}"
return result
这里的逻辑也非常简单,如果页面存在则返回页面的总结。
03 | 小结
LangChain不仅具备直接查询文件的能力,还可以查询一定存储路径的数据,我们需要按照不同的业务场景选择不同的组件实现相应能力。
网友评论