Source code for langchain_community.docstore.arbitrary_fn

from typing import Callable, Union

from langchain_core.documents import Document

from langchain_community.docstore.base import Docstore


[docs]class DocstoreFn(Docstore): """通过任意查找函数进行文档存储。 当以下情况时,这将非常有用: * 构建InMemoryDocstore/dict的成本很高 * 从远程源检索文档 * 想要重用现有对象"""
[docs] def __init__( self, lookup_fn: Callable[[str], Union[Document, str]], ): self._lookup_fn = lookup_fn
[docs] def search(self, search: str) -> Document: """搜索文档。 参数: search: 搜索字符串 返回: 如果找到文档,则返回文档,否则返回错误消息。 """ r = self._lookup_fn(search) if isinstance(r, str): # NOTE: assume the search string is the source ID return Document(page_content=r, metadata={"source": search}) elif isinstance(r, Document): return r raise ValueError(f"Unexpected type of document {type(r)}")