이 문서는 Box retriever 시작하기를 도와드립니다. 모든 BoxRetriever 기능과 구성에 대한 자세한 문서는 API reference를 참조하세요.

Overview

BoxRetriever 클래스는 Box의 비구조화된 콘텐츠를 LangChain의 Document 형식으로 가져오는 데 도움을 줍니다. 전체 텍스트 검색을 기반으로 파일을 검색하거나 Box AI를 사용하여 파일에 대한 AI 쿼리 결과를 포함하는 Document를 검색할 수 있습니다. 이를 위해서는 Box 파일 ID를 포함하는 List[str], 즉 ["12345","67890"]를 포함해야 합니다.
Box AI는 Enterprise Plus 라이선스가 필요합니다
텍스트 표현이 없는 파일은 건너뜁니다.

Integration details

1: Bring-your-own data (즉, 사용자 정의 문서 코퍼스를 인덱싱하고 검색):
RetrieverSelf-hostCloud offeringPackage
BoxRetrieverlangchain-box

Setup

Box 패키지를 사용하려면 다음 몇 가지가 필요합니다:
  • Box 계정 — 현재 Box 고객이 아니거나 프로덕션 Box 인스턴스 외부에서 테스트하려는 경우 무료 개발자 계정을 사용할 수 있습니다.
  • Box 앱개발자 콘솔에서 구성되며, Box AI의 경우 Manage AI 범위가 활성화되어 있어야 합니다. 여기에서 인증 방법도 선택합니다.
  • 앱은 관리자가 활성화해야 합니다. 무료 개발자 계정의 경우 계정에 가입한 사람이 관리자입니다.

Credentials

이 예제에서는 token authentication을 사용합니다. 이는 모든 인증 방법과 함께 사용할 수 있습니다. 어떤 방법을 사용하든 토큰을 가져오기만 하면 됩니다. langchain-box에서 다른 인증 유형을 사용하는 방법에 대해 자세히 알아보려면 Box provider 문서를 참조하세요.
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"

Installation

이 retriever는 langchain-box 패키지에 있습니다:
pip install -qU langchain-box
Note: you may need to restart the kernel to use updated packages.

Instantiation

이제 retriever를 인스턴스화할 수 있습니다:
from langchain_box import BoxRetriever

retriever = BoxRetriever(box_developer_token=box_developer_token)
더 세밀한 검색을 위해 결과를 필터링하는 데 도움이 되는 일련의 옵션을 제공합니다. 이는 langchain_box.utilities.SearchOptionslangchain_box.utilities.SearchTypeFilterlangchain_box.utilities.DocumentFiles enum과 함께 사용하여 생성 날짜, 검색할 파일의 부분, 심지어 특정 폴더로 검색 범위를 제한하는 등의 필터링을 수행합니다. 자세한 내용은 API reference를 확인하세요.
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
)

Usage

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**.')]

Citations

Box AI와 BoxRetriever를 사용하면 프롬프트에 대한 답변을 반환하거나, Box가 해당 답변을 얻는 데 사용한 인용을 반환하거나, 둘 다 반환할 수 있습니다. Box AI를 어떻게 사용하든 retriever는 List[Document] 객체를 반환합니다. 두 개의 bool 인수인 answercitations로 이러한 유연성을 제공합니다. Answer는 기본적으로 True이고 citations는 기본적으로 False이므로 답변만 원하는 경우 둘 다 생략할 수 있습니다. 둘 다 원하는 경우 citations=True만 포함하면 되고, 인용만 원하는 경우 answer=Falsecitations=True를 포함하면 됩니다.

Get both

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')]

Citations only

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')]

Use as an agent tool

다른 retriever와 마찬가지로 BoxRetriever도 LangGraph agent에 tool로 추가할 수 있습니다.
pip install -U langsmith
from langchain_classic 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

Extra fields

모든 Box connector는 Box FileFull 객체에서 추가 필드를 선택하여 사용자 정의 LangChain metadata로 반환하는 기능을 제공합니다. 각 객체는 extra_fields=["shared_link"]와 같이 반환 객체의 json 키를 포함하는 List[str] 타입의 선택적 extra_fields를 허용합니다. connector는 이 필드를 통합이 작동하는 데 필요한 필드 목록에 추가한 다음 "metadata" : { "source" : "source, "shared_link" : "shared_link" }와 같이 Document 또는 Blob에서 반환되는 metadata에 결과를 추가합니다. 해당 파일에 대해 필드를 사용할 수 없는 경우 "shared_link" : ""와 같이 빈 문자열로 반환됩니다.

API reference

모든 BoxRetriever 기능과 구성에 대한 자세한 문서는 API reference를 참조하세요.

Help

질문이 있으시면 개발자 문서를 확인하거나 개발자 커뮤니티에서 문의하실 수 있습니다.
Connect these docs programmatically to Claude, VSCode, and more via MCP for real-time answers.
I