跳到主要内容

BoxRetriever

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

概述

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

信息

Box AI 需要 Enterprise Plus 许可证

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

集成详情

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)
API 参考:BoxRetriever

为了进行更细粒度的搜索,我们提供了一系列选项来帮助您筛选结果。这会将 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
)
API 参考:BoxRetriever

用法

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 可以通过整合到 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

API 参考

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

帮助

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


此页面是否有帮助?