Skip to main content
Open In ColabOpen on GitHub

BoxRetriever

这将帮助您开始使用Box retriever。有关BoxRetriever所有功能和配置的详细文档,请访问API参考

概述

BoxRetriever 类帮助您从 Box 中获取非结构化内容,并将其转换为 Langchain 的 Document 格式。您可以通过全文搜索文件或使用 Box AI 来检索包含对文件进行 AI 查询结果的 Document 来实现这一点。这需要包含一个包含 Box 文件 ID 的 List[str],例如 ["12345","67890"]

info

Box AI 需要企业增强版许可证

没有文本表示的文件将被跳过。

集成详情

1: 自带数据(即索引和搜索自定义文档集):

检索器自托管云服务
BoxRetrieverlangchain-box

设置

为了使用Box包,你需要准备一些东西:

  • 一个Box账户 — 如果您还不是Box的现有客户,或者想要在您的生产Box实例之外进行测试,您可以使用一个免费开发者账户
  • Box 应用 — 这是在开发者控制台中配置的,对于 Box AI,必须启用Manage AI范围。在这里,您还将选择您的认证方法
  • 应用程序必须由管理员启用。对于免费开发者账户,这是指注册账户的人。

凭证

对于这些示例,我们将使用令牌认证。这可以与任何认证方法一起使用。只需使用任何方法获取令牌。如果您想了解更多关于如何使用其他认证类型与langchain-box的信息,请访问Box 提供者文档。

import getpass
import os

box_developer_token = getpass.getpass("Enter your Box Developer Token: ")

如果你想从单个查询中获取自动追踪,你也可以通过取消注释以下内容来设置你的 LangSmith API 密钥:

# os.environ["LANGSMITH_API_KEY"] = getpass.getpass("Enter your LangSmith API key: ")
# os.environ["LANGSMITH_TRACING"] = "true"

安装

这个检索器位于 langchain-box 包中:

%pip install -qU langchain-box
Note: you may need to restart the kernel to use updated packages.

实例化

现在我们可以实例化我们的检索器:

from langchain_box import BoxRetriever

retriever = BoxRetriever(box_developer_token=box_developer_token)

为了更精细的搜索,我们提供了一系列选项来帮助您筛选结果。这使用了langchain_box.utilities.SearchOptionslangchain_box.utilities.SearchTypeFilterlangchain_box.utilities.DocumentFiles枚举结合,以根据创建日期、文件的哪一部分进行搜索,甚至将搜索范围限制在特定文件夹中。

欲了解更多信息,请查看API参考

from langchain_box.utilities import BoxSearchOptions, DocumentFiles, SearchTypeFilter

box_folder_id = "260931903795"

box_search_options = BoxSearchOptions(
ancestor_folder_ids=[box_folder_id],
search_type_filter=[SearchTypeFilter.FILE_CONTENT],
created_date_range=["2023-01-01T00:00:00-07:00", "2024-08-01T00:00:00-07:00,"],
k=200,
size_range=[1, 1000000],
updated_data_range=None,
)

retriever = BoxRetriever(
box_developer_token=box_developer_token, box_search_options=box_search_options
)

retriever.invoke("AstroTech Solutions")
[Document(metadata={'source': 'https://dl.boxcloud.com/api/2.0/internal_files/1514555423624/versions/1663171610024/representations/extracted_text/content/', 'title': 'Invoice-A5555_txt'}, page_content='Vendor: AstroTech Solutions\nInvoice Number: A5555\n\nLine Items:\n    - Gravitational Wave Detector Kit: $800\n    - Exoplanet Terrarium: $120\nTotal: $920')]

Box AI

from langchain_box import BoxRetriever

box_file_ids = ["1514555423624", "1514553902288"]

retriever = BoxRetriever(
box_developer_token=box_developer_token, box_file_ids=box_file_ids
)

用法

query = "What was the most expensive item purchased"

retriever.invoke(query)
[Document(metadata={'source': 'Box AI', 'title': 'Box AI What was the most expensive item purchased'}, page_content='The most expensive item purchased is the **Gravitational Wave Detector Kit** from AstroTech Solutions, which costs **$800**.')]

引用

使用 Box AI 和 BoxRetriever,您可以返回提示的答案,返回 Box 用于获取该答案的引用,或者两者都返回。无论您选择如何使用 Box AI,检索器都会返回一个 List[Document] 对象。我们通过两个 bool 参数 answercitations 提供这种灵活性。答案默认为 True,引用默认为 False,因此如果您只需要答案,可以省略两者。如果您需要两者,只需包含 citations=True,如果您只需要引用,则需要包含 answer=Falsecitations=True

获取两者

retriever = BoxRetriever(
box_developer_token=box_developer_token, box_file_ids=box_file_ids, citations=True
)

retriever.invoke(query)
[Document(metadata={'source': 'Box AI', 'title': 'Box AI What was the most expensive item purchased'}, page_content='The most expensive item purchased is the **Gravitational Wave Detector Kit** from AstroTech Solutions, which costs **$800**.'),
Document(metadata={'source': 'Box AI What was the most expensive item purchased', 'file_name': 'Invoice-A5555.txt', 'file_id': '1514555423624', 'file_type': 'file'}, page_content='Vendor: AstroTech Solutions\nInvoice Number: A5555\n\nLine Items:\n - Gravitational Wave Detector Kit: $800\n - Exoplanet Terrarium: $120\nTotal: $920')]

仅引用

retriever = BoxRetriever(
box_developer_token=box_developer_token,
box_file_ids=box_file_ids,
answer=False,
citations=True,
)

retriever.invoke(query)
[Document(metadata={'source': 'Box AI What was the most expensive item purchased', 'file_name': 'Invoice-A5555.txt', 'file_id': '1514555423624', 'file_type': 'file'}, page_content='Vendor: AstroTech Solutions\nInvoice Number: A5555\n\nLine Items:\n    - Gravitational Wave Detector Kit: $800\n    - Exoplanet Terrarium: $120\nTotal: $920')]

在链中使用

与其他检索器一样,BoxRetriever 可以通过 chains 集成到 LLM 应用程序中。

我们将需要一个LLM或聊天模型:

pip install -qU langchain-openai
import getpass
import os

if not os.environ.get("OPENAI_API_KEY"):
os.environ["OPENAI_API_KEY"] = getpass.getpass("Enter API key for OpenAI: ")

from langchain_openai import ChatOpenAI

llm = ChatOpenAI(model="gpt-4o-mini")
openai_key = getpass.getpass("Enter your OpenAI key: ")
Enter your OpenAI key:  ········
from langchain_core.output_parsers import StrOutputParser
from langchain_core.prompts import ChatPromptTemplate
from langchain_core.runnables import RunnablePassthrough

box_search_options = BoxSearchOptions(
ancestor_folder_ids=[box_folder_id],
search_type_filter=[SearchTypeFilter.FILE_CONTENT],
created_date_range=["2023-01-01T00:00:00-07:00", "2024-08-01T00:00:00-07:00,"],
k=200,
size_range=[1, 1000000],
updated_data_range=None,
)

retriever = BoxRetriever(
box_developer_token=box_developer_token, box_search_options=box_search_options
)

context = "You are a finance professional that handles invoices and purchase orders."
question = "Show me all the items purchased from AstroTech Solutions"

prompt = ChatPromptTemplate.from_template(
"""Answer the question based only on the context provided.

Context: {context}

Question: {question}"""
)


def format_docs(docs):
return "\n\n".join(doc.page_content for doc in docs)


chain = (
{"context": retriever | format_docs, "question": RunnablePassthrough()}
| prompt
| llm
| StrOutputParser()
)
chain.invoke(question)
'- Gravitational Wave Detector Kit: $800\n- Exoplanet Terrarium: $120'

作为代理工具使用

与其他检索器一样,BoxRetriever 也可以作为工具添加到 LangGraph 代理中。

pip install -U langsmith
from langchain import hub
from langchain.agents import AgentExecutor, create_openai_tools_agent
from langchain.tools.retriever import create_retriever_tool
box_search_options = BoxSearchOptions(
ancestor_folder_ids=[box_folder_id],
search_type_filter=[SearchTypeFilter.FILE_CONTENT],
created_date_range=["2023-01-01T00:00:00-07:00", "2024-08-01T00:00:00-07:00,"],
k=200,
size_range=[1, 1000000],
updated_data_range=None,
)

retriever = BoxRetriever(
box_developer_token=box_developer_token, box_search_options=box_search_options
)

box_search_tool = create_retriever_tool(
retriever,
"box_search_tool",
"This tool is used to search Box and retrieve documents that match the search criteria",
)
tools = [box_search_tool]
prompt = hub.pull("hwchase17/openai-tools-agent")
prompt.messages

llm = ChatOpenAI(temperature=0, openai_api_key=openai_key)

agent = create_openai_tools_agent(llm, tools, prompt)
agent_executor = AgentExecutor(agent=agent, tools=tools)
/Users/shurrey/local/langchain/.venv/lib/python3.11/site-packages/langsmith/client.py:312: LangSmithMissingAPIKeyWarning: API key must be provided when using hosted LangSmith API
warnings.warn(
result = agent_executor.invoke(
{
"input": "list the items I purchased from AstroTech Solutions from most expensive to least expensive"
}
)
print(f"result {result['output']}")
result The items you purchased from AstroTech Solutions from most expensive to least expensive are:

1. Gravitational Wave Detector Kit: $800
2. Exoplanet Terrarium: $120

Total: $920

额外字段

所有Box连接器都提供了从Box FileFull对象中选择额外字段作为自定义LangChain元数据返回的能力。每个对象接受一个可选的List[str]类型的extra_fields参数,该参数包含返回对象中的json键,例如extra_fields=["shared_link"]

连接器将将此字段添加到集成功能所需的字段列表中,然后将结果添加到DocumentBlob中返回的元数据中,例如"metadata" : { "source" : "source, "shared_link" : "shared_link" }。如果该文件不可用此字段,则将返回为空字符串,例如"shared_link" : ""

API参考

有关所有BoxRetriever功能和配置的详细文档,请访问API参考

帮助

如果您有任何问题,您可以查看我们的开发者文档或联系我们的开发者社区


这个页面有帮助吗?