> ## Documentation Index
> Fetch the complete documentation index at: https://langchain-docs-zh.mintlify.site/llms.txt
> Use this file to discover all available pages before exploring further.

# BoxRetriever 集成

> 使用 LangChain Python 与 BoxRetriever 检索器集成。

这将帮助您从Box [retriever](https://langchain-docs-zh.mintlify.site/langchain/oss/deepagents/retrieval.md)入门。

# 概览

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

> [!NOTE]
>
> Box AI需要Enterprise Plus许可证

未提供文本表示的文件将被跳过。

### 集成细节

1: 自备数据（即索引和搜索自定义文档集合）：

| 检索器 | 自托管 | 云服务 | 包 |
| :- | :- | :-: | :-: |
| `BoxRetriever` | ❌ | ✅ | `langchain-box` |

## 设置

要使用 Box 包，您需要准备以下内容：

* Box账户：如果您不是 Box 当前客户或希望离线测试，可以使用 [免费开发者账户](https://account.box.com/signup/n/developer#ty9l3)。
* [Box应用](https://developer.box.com/guides/getting-started/first-application/)：此应用需在 [开发者控制台](https://account.box.com/developers/console) 中配置，并确保已启用 `Manage AI` 权限。此处您还将选择认证方式
* 应用必须由 [管理员启用](https://developer.box.com/guides/authorization/custom-app-approval/#manual-approval)。对于免费开发者账户，权限由注册账户的用户授予。

### 凭据

本示例使用 [令牌认证](https://developer.box.com/guides/authentication/tokens/developer-tokens)。该认证方式适用于任何 [认证方法](https://developer.box.com/guides/authentication/)。只需通过相应方法获取令牌。若需了解如何使用其他认证类型与 `langchain-box` 配合，请查阅 [Box 提供方](https://langchain-docs-zh.mintlify.site/langchain/oss/python/integrations/providers/box.md) 文档。

```python theme={null}
import getpass
import os

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

如需为单个查询启用自动化追踪，您也可以通过取消注释下方代码设置 [LangSmith](https://docs.langchain.com/langsmith/observability) API 密钥：

```python theme={null}
os.environ["LANGSMITH_API_KEY"] = getpass.getpass("Enter your LangSmith API key: ")
os.environ["LANGSMITH_TRACING"] = "true"
```

### 安装

此检索器位于 `langchain-box` 包中：

```python theme={null}
pip install -qU langchain-box
```

## 实例化

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

## 搜索

```python theme={null}
from langchain_box import BoxRetriever

retriever = BoxRetriever(box_developer_token=box_developer_token)
```

对于更精细的搜索，我们提供一系列选项来帮助您筛选结果。这使用了 `langchain_box.utilities.SearchOptions` 与 `langchain_box.utilities.SearchTypeFilter` 和 `langchain_box.utilities.DocumentFiles` 枚举值来对创建日期、文件搜索部分以及将搜索范围限制在特定文件夹等属性进行过滤。

```python theme={null}
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")
```

```text theme={null}
[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

```python theme={null}
from langchain_box import BoxRetriever

box_file_ids = ["1514555423624", "1514553902288"]

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

## 使用

```python theme={null}
query = "What was the most expensive item purchased"

retriever.invoke(query)
```

```text theme={null}
[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` 参数 `answer` 和 `citations` 实现这种灵活性。答案默认为 `True`，引用默认为 `False`，因此如果您只需要答案，可以省略两者。若需要两者，只需包含 `citations=True`；若仅需引用，则包含 `answer=False` 和 `citations=True`。

### 同时返回两者

```python theme={null}
retriever = BoxRetriever(
    box_developer_token=box_developer_token, box_file_ids=box_file_ids, citations=True
)

retriever.invoke(query)
```

```text theme={null}
[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')]
```

### 仅返回引用

```python theme={null}
retriever = BoxRetriever(
    box_developer_token=box_developer_token,
    box_file_ids=box_file_ids,
    answer=False,
    citations=True,
)

retriever.invoke(query)
```

```text theme={null}
[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')]
```

## 作为智能体工具

与 LangGraph 智能体中的其他检索器类似，BoxRetriever 也可以作为工具添加到 LangGraph 智能体中。

```python theme={null}
pip install -U langsmith
```

```python theme={null}
from langchain_classic import hub
from langchain_classic.agents import AgentExecutor, create_openai_tools_agent
from langchain_classic.tools.retriever import create_retriever_tool
from langchain_openai import ChatOpenAI
```

```python theme={null}
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]
```

```python theme={null}
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)
```

```text theme={null}
/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(
```

```python theme={null}
result = agent_executor.invoke(
    {
        "input": "list the items I purchased from AstroTech Solutions from most expensive to least expensive"
    }
)
```

```python theme={null}
print(f"result {result['output']}")
```

```text theme={null}
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"]`。

连接器会将此字段添加到集成所需的字段列表中，并将结果添加到 @\[`Document`] 或 `Blob` 返回的元数据中，例如 `"metadata" : { "source" : "source, "shared_link" : "shared_link" }`。如果该字段对于文件不可用，则会返回空字符串，例如 `"shared_link" : ""`。

***

## 帮助

如有疑问，请查阅我们的 [开发者文档](https://developer.box.com) 或加入我们的 [开发者社区](https://community.box.com)。

***

> 官方原文：[src/oss/python/integrations/retrievers/box.mdx](https://github.com/langchain-ai/docs/blob/main/src/oss/python/integrations/retrievers/box.mdx) · 非官方翻译，译文由 AI 生成，以英文原文为准。


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.