> ## Documentation Index
> Fetch the complete documentation index at: https://developer.box.com/llms.txt
> Use this file to discover all available pages before exploring further.

> Box AI抽出エージェント (強化) とBox Python SDKを使用して、大規模で複雑なドキュメントから自動的にデータを抽出する方法についてご紹介します。

# Box AI抽出エージェント (強化) による抽出 (構造化) (Python)

export const SignupCTA = ({children}) => {
  return <div className="flex flex-wrap items-center gap-4 p-5 rounded-lg border border-gray-200 dark:border-gray-700 my-6" style={{
    background: "linear-gradient(135deg, rgba(0, 97, 213, 0.06), rgba(0, 97, 213, 0.02))"
  }}>
      <div className="flex-1 text-sm leading-relaxed text-gray-700 dark:text-gray-300" style={{
    minWidth: "280px"
  }}>
        {children}
      </div>
      <div className="flex flex-col items-center gap-2">
        <a href="https://account.box.com/signup/developer#ty9l3" className="signup-cta-button inline-flex items-center whitespace-nowrap px-5 py-2 text-sm font-semibold text-white no-underline">
          {translate("Get started for free")}
        </a>
        <a href="https://account.box.com/developers/console" className="signup-cta-login text-xs text-gray-500 dark:text-gray-400 no-underline whitespace-nowrap">
          {translate("Already have an account? Log in")}
        </a>
      </div>
    </div>;
};

export const Link = ({href, children, className, ...props}) => {
  const localizedHref = localizeLink(href);
  return <a href={localizedHref} className={className} {...props}>
      {children}
    </a>;
};

<Link href="/ai">Box AI</Link>が公開するインテリジェントな抽出機能により、開発者は、1回のAPIコールでドキュメントから自動的にキー/値ペアを抽出できます。抽出エージェント (強化) は、高度な推論モデルを使用して、複雑な非構造化ドキュメントのコンテンツを、手動によるデータ入力なしで実用的なメタデータに変換するため、請求書、フォーム、契約書などのビジネスドキュメントのドキュメント処理ワークフローが効率化されます。

このクイックスタートでは、Box Python SDKを構成し、Box AIを使用して、Boxに保存されている株式購入契約書からデータを抽出する方法を紹介します。

<SignupCTA>
  無料のDeveloperアカウントを作成すると、Box AI APIにアクセスできます。APIを使用して、ドキュメントの要約、質問への回答、メタデータ抽出を試してみましょう。
</SignupCTA>

<Steps>
  <Step title="Boxアプリケーションを作成して構成する">
    任意のBox Platform統合では、最初のステップとして、Boxアプリケーションを作成して構成します。

    1. <Link href="https://app.box.com/developers/console">Box開発者コンソール</Link>に移動します。
    2. このクイックスタートでは、アプリケーションの種類として`Client Credentials Grant`を使用してアプリを作成します。
    3. アプリが作成されたら、以下のスコープを有効にします。
       * Boxに格納されているすべてのファイルとフォルダの読み取り
       * Boxに格納されているすべてのファイルとフォルダへの書き込み
       * AIを管理する

    Boxアプリケーションの新規作成の詳細については、<Link href="/guides/getting-started/first-application#create-your-first-application">最初のアプリケーションの作成</Link>を参照してください。
  </Step>

  <Step title="テストファイルをアップロードする">
    テンプレートを準備したら、テストするファイルを選択します。このクイックスタートでは、こちらの<Link href="/static/quickstarts/extract/files/enhanced-extract-file.pdf">株式購入契約書のサンプル</Link>を使用してください。

    1. テスト用ドキュメントをダウンロードして、Boxアカウントにドラッグアンドドロップします。
    2. ファイルIDを確認するには、Boxでファイルを開いてURLを調べます。パスの最後の部分がファイルIDです。たとえば、次のようなURLがあるとします: `https://app.box.com/file/2064123286902`

       この場合、ファイルIDは`2064123286902`です。
  </Step>

  <Step title="環境を設定する">
    抽出を実行するために、開発環境を設定します。このクイックスタートでは、PythonとBox Python SDKバージョン10を使用します。お使いのマシンにPython 3.11以上がインストールされていることを確認してください。

    1. プロジェクト用に新しいディレクトリを作成し、そのディレクトリに移動します。
    2. 仮想環境を作成します。
       ```bash theme={null}
       python3 -m venv .venv
       source .venv/bin/activate
       ```
    3. Box Python SDKをインストールします。
       ```bash theme={null}
       pip install "boxsdk~=10"
       ```
    4. `.env`ファイルから環境変数を読み込むために`python-dotenv`パッケージをインストールします。
       ```bash theme={null}
       pip install python-dotenv
       ```
    5. プロジェクトディレクトリのルートに`.env`ファイルを作成し、以下の環境変数を追加します。その際、プレースホルダの値を実際のBoxアプリの資格情報と前の手順で確認したIDに置き換えます。
       ```bash theme={null}
        BOX_DEVELOPER_TOKEN=your_box_developer_token

        BOX_METADATA_TEMPLATE_KEY=your_metadata_template_key
        BOX_FILE_ID=your_box_file_id
       ```

    開発者トークンを取得するには、Box開発者コンソールに移動します。アプリを開き、\[**構成**] タブに移動します。

    6. \[**開発者トークンを生成**] をクリックして新しいトークンを作成します。

    <Tip>
      簡略化するために、このクイックスタートでは、有効期間の短い開発者トークンを使用します。実稼働環境では、開発者トークンではなく、お使いのアプリに設定された方法 (クライアント資格情報許可など) で認証する必要があります。
    </Tip>
  </Step>

  <Step title="enhanced-extract.pyファイルを作成する">
    開発環境の準備ができました。Box AIを使用してドキュメントからデータを抽出するPythonスクリプトを作成できます。

    1. プロジェクトディレクトリのルートに`enhanced-extract.py`という名前の新しいファイルを作成し、以下のコードを追加します。

       ```python theme={null}
       import os

       from dotenv import load_dotenv

       from box_sdk_gen import (
           AiAgentReference,
           AiAgentReferenceTypeField,
           AiItemBase,
           BoxClient,
           BoxDeveloperTokenAuth,
           CreateAiExtractStructuredFields,
           CreateAiExtractStructuredFieldsOptionsField
       )

       load_dotenv()

       developer_token = os.getenv("BOX_DEVELOPER_TOKEN")
       file_id = os.getenv("BOX_FILE_ID")

       def get_box_client(token: str) -> BoxClient:
           
           if not developer_token:
               raise ValueError("BOX_DEVELOPER_TOKEN is not set in environment variables.")
           
           auth = BoxDeveloperTokenAuth(token=token)
           client = BoxClient(auth=auth)

           return client

       def main():
           client = get_box_client(token=developer_token)

           me = client.users.get_user_me()
           print(f"My user ID is {me.id}")

       if __name__ == "__main__":
           main()
       ```

       このコードは、環境変数を`.env`ファイルから読み込み、Box SDKクライアントを初期化し、現在のユーザーのIDを出力して、クライアントが正しく動作していることを確認します。

    2. ターミナルで次のコマンドを使用してスクリプトを実行します。

       ```bash theme={null}
       python enhanced-extract.py
       ```

       Box SDKクライアントが正しく設定されると、コンソールにはユーザーIDが表示されます。次に例を示します。

       ```bash theme={null}
       My user ID is 123456789
       ```
  </Step>

  <Step title="データを抽出する">
    Box SDKクライアントが動作を開始したら、Box AIを使用してドキュメントからデータを抽出するためのコードを追加できます。

    1. `get_box_client`関数と`main`関数の間に次の関数を追加します。

       ```python theme={null}
       def extract_metadata(client: BoxClient, file_id: str) -> dict:

           enhanced_extract_config = AiAgentReference(
               id="enhanced_extract_agent",
               type=AiAgentReferenceTypeField.AI_AGENT_ID
           )

           fields=[
               CreateAiExtractStructuredFields(
                   key="parties",
                   display_name="Parties",
                   description="The named parties involved",
                   prompt="A comma separated list of the named parties involved",
                   type="string",
               ),
               CreateAiExtractStructuredFields(
                   key="effectiveDate",
                   display_name="Effective date",
                   description="The effective date of the contract",
                   prompt="The effective date of the contract",
                   type="date",
               ),
               CreateAiExtractStructuredFields(
                   key="purchasePrice",
                   display_name="Purchase price",
                   description="The purchase price stated in the contract",
                   prompt="The purchase price stated in the contract",
                   type="float",
               ),
               CreateAiExtractStructuredFields(
                   key="summary",
                   display_name="Summary",
                   description="A summary of the contract in 50 words or less",
                   prompt="A summary of the contract in 50 words or less including key obligations",
                   type="string",
               ),
               CreateAiExtractStructuredFields(
                   key="recommendation",
                   display_name="Recommendation",
                   description="Should we make this purchase?",
                   prompt="Given the financial details, would you recommend proceeding with the purchase? Answer Yes or No.",
                   type="enum",
                   options=[
                       CreateAiExtractStructuredFieldsOptionsField(key="Yes"),
                       CreateAiExtractStructuredFieldsOptionsField(key="No"),
                   ],
               ),
           ]

           metadata = client.ai.create_ai_extract_structured(
               [ AiItemBase(id=file_id) ],
               fields=fields,
               ai_agent=enhanced_extract_config,
           )
           
           return metadata.to_dict()['answer']

       ```

       この関数では、Box AIの`create_ai_extract_structured`メソッドを使用して、指定したファイルからメタデータを抽出します。BoxClientとファイルIDは関数に送信され、この関数により、抽出されたメタデータがディクショナリとして返されます。

           <Tip>
             `fields`パラメータは、ドキュメントから抽出する特定のデータポイントを定義します。また、代わりにメタデータテンプレートキーを参照して、Boxメタデータテンプレートで定義されたフィールドを抽出することもできます。
           </Tip>

    2. `main`関数でメタデータを抽出する関数呼び出しを追加します。新しい`main`関数に次のロジックが含まれていることを確認します。

       ```python theme={null}
       def main():
           client = get_box_client(token=developer_token)

           me = client.users.get_user_me()
           print(f"My user ID is {me.id}")

           metadata = extract_metadata(client=client, file_id=file_id)

           print(f"\n\nExtracted Metadata: {metadata}")
       ```

       SDKはBox AIへのAPIコールを処理し、抽出されたメタデータを<Link href="/reference/resources/ai-extract-structured-response">`AiExtractStructuredResponse`</Link>オブジェクトとして返します。このクイックスタートでは、このコードによって、このオブジェクトがディクショナリに変換され、抽出されたキー/値ペアを含む`answer`フィールドが返されます。

    3. ターミナルで次のコマンドを実行して、抽出されたメタデータをコンソールに出力し、抽出が成功したかどうかを確認します。

       ```bash theme={null}
       python enhanced-extract.py
       ```

       抽出が成功した場合、コンソールでは、ユーザーIDの後に、株式購入契約書から抽出されたメタデータが表示されます。

       ```bash theme={null}
       My user ID is 123456789

       Extracted Metadata: {'parties': 'Argyle LLP, Suregood Family Trust', 'effectiveDate': '2023-03-31', 'purchasePrice': 231000000, 'summary': 'Argyle LLP agrees to purchase 51% of Erebor Life, Inc. from Suregood Family Trust for $231,000,000. The Seller must operate the business normally until closing, and the Buyer must pay the purchase price. The agreement is effective March 31, 2023.', 'recommendation': 'Yes'}
       ```
  </Step>
</Steps>

## リソース

* <Link href="https://github.com/box-community/box-quickstarts/tree/main/box-ai-enhanced-extract-quickstart">最終的なコード</Link>
* <Link href="/reference/post-ai-extract-structured">構造化メタデータの抽出のAPIリファレンス</Link>
* <Link href="https://github.com/box/box-python-sdk/tree/main">Box Python SDK</Link>
