> ## 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.

> POST /ai/extractエンドポイントを使用し、自然言語のプロンプトを利用してドキュメントからメタデータを抽出します。

# ファイルからメタデータを抽出する (自由形式)

export const MultiRelatedLinks = ({sections = []}) => {
  if (!sections || sections.length === 0) {
    return null;
  }
  return <div className="space-y-8">
      {sections.map((section, index) => <RelatedLinks key={index} title={section.title} items={section.items} />)}
    </div>;
};

export const RelatedLinks = ({title, items = []}) => {
  const getBadgeClass = badge => {
    if (!badge) return "badge-default";
    const badgeType = badge.toLowerCase().replace(/\s+/g, "-");
    return `badge-${badge === "ガイド" ? "guide" : badgeType}`;
  };
  if (!items || items.length === 0) {
    return null;
  }
  return <div className="my-8">
      {}
      <h3 className="text-sm font-bold uppercase tracking-wider mb-4">{title}</h3>

      {}
      <div className="flex flex-col gap-3">
        {items.map((item, index) => <a key={index} href={item.href} className="py-2 px-3 rounded related_link hover:bg-[#f2f2f2] dark:hover:bg-[#111827] flex items-center gap-3 group no-underline hover:no-underline border-b-0">
            {}
            <span className={`px-2 py-1 rounded-full text-xs font-semibold uppercase tracking-wide flex-shrink-0 ${getBadgeClass(item.badge)}`}>
              {item.badge}
            </span>

            {}
            <span className="text-base">{item.label}</span>
          </a>)}
      </div>
    </div>;
};

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

Box AI APIを使用すると、ドキュメントを照会し、指定したプロンプトに基づいてメタデータを抽出できます。**自由形式**とは、JSONやXMLなどの形式の文字列化バージョン、またはプレーンテキストをプロンプトに含めることができるという意味です。

<Note>
  **メタデータを抽出 (自由形式)** エンドポイントはOCRをサポートしていません。英語以外の言語の画像ファイル (TIFF、PNG、JPEG) またはドキュメントからメタデータを抽出するには、<Link href="/guides/box-ai/ai-tutorials/extract-metadata-structured">メタデータを抽出 (構造化)</Link> エンドポイントを使用してください。
</Note>

## 開始する前に

Platformアプリを作成して認証するには、<Link href="/guides/box-ai/ai-tutorials/prerequisites">Box AIの使い方</Link>に記載されている手順に従っていることを確認してください。

## リクエストの送信

リクエストを送信するには、`POST /2.0/ai/extract`エンドポイントを使用します。

<CodeGroup>
  ```sh cURL theme={null}
  curl -i -L 'https://api.box.com/2.0/ai/extract' \
       -H 'content-type: application/json' \
       -H 'authorization: Bearer <ACCESS_TOKEN>' \
       -d '{
          "prompt": "Extract data related to contract conditions",
          "items": [
                {
                    "type": "file",
                    "id": "1497741268097"
                }
          ],
          "ai_agent": {
            "type": "ai_agent_extract",
            "long_text": {
              "model": "openai__gpt_5_mini",
              "prompt_template": "It is `{current_date}`, and I have $8000 and want to spend a week in the Azores. What should I see?",
            },
            "basic_text": {
              "model": "openai__gpt_5_mini",
            }
          }
        }'
  ```

  ```typescript Node/TypeScript v10 theme={null}
  await client.ai.createAiExtract({
    prompt: 'firstName, lastName, location, yearOfBirth, company',
    items: [new AiItemBase({ id: file.id })],
    aiAgent: agentIgnoringOverridingEmbeddingsModel,
  } satisfies AiExtract);
  ```

  ```python Python v10 theme={null}
  client.ai.create_ai_extract(
      "firstName, lastName, location, yearOfBirth, company",
      [AiItemBase(id=file.id)],
      ai_agent=agent_ignoring_overriding_embeddings_model,
  )
  ```

  ```cs .NET v10 theme={null}
  await client.Ai.CreateAiExtractAsync(requestBody: new AiExtract(prompt: "firstName, lastName, location, yearOfBirth, company", items: Array.AsReadOnly(new [] {new AiItemBase(id: file.Id)})));
  ```

  ```swift Swift v10 theme={null}
  try await client.ai.createAiExtract(requestBody: AiExtract(prompt: "firstName, lastName, location, yearOfBirth, company", items: [AiItemBase(id: file.id)]))
  ```

  ```java Java v10 theme={null}
  client.getAi().createAiExtract(new AiExtract.Builder("firstName, lastName, location, yearOfBirth, company", Arrays.asList(new AiItemBase(file.getId()))).aiAgent(agentIgnoringOverridingEmbeddingsModel).build())
  ```

  ```java Java v5 theme={null}
  BoxAIResponse response = BoxAI.extractMetadataFreeform(
      api,
      "firstName, lastName, location, yearOfBirth, company",
      Collections.singletonList(new BoxAIItem("123456", BoxAIItem.Type.FILE))
  );
  ```
</CodeGroup>

### パラメータ

コールを実行するには、以下のパラメータを渡す必要があります。必須のパラメータは**太字**で示されています。

`items`配列には要素が1つだけ含まれている必要があります。プロンプトとファイルの制限については、<Link href="/guides/box-ai/index#input-limits">入力制限</Link>を参照してください。

| パラメータ            | 説明                                                                                                                                                                                                                                                                  | 例                               |
| ---------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------- |
| **`prompt`**     | Box AIに対するメタデータの抽出リクエスト。最大10,000文字。                                                                                                                                                                                                                                 | 週1回の営業会議のアジェンダを作成してください。        |
| **`items.id`**   | ドキュメントのBoxファイルID。IDは、拡張子が付いている実際のファイルを参照する必要があります。                                                                                                                                                                                                                  | `1233039227512`                 |
| **`items.type`** | 指定した入力データのタイプ。                                                                                                                                                                                                                                                      | `file`                          |
| `items.content`  | 項目のコンテンツ (多くの場合はテキストレプリゼンテーション)。                                                                                                                                                                                                                                    | `This article is about Box AI`. |
| `ai_agent`       | デフォルトのモデル構成を上書きします。これにより、モデル、プロンプトテンプレート、システムメッセージ、またはLLMパラメータを変更できます。仕組みについては<Link href="/guides/box-ai/index#the-ai_agent-override-system">上書きシステム</Link>を参照してください。また、使用例については<Link href="/guides/box-ai/ai-agents/ai-agent-overrides">AIモデルの上書き</Link>を参照してください。 |                                 |

## ユースケース

この例では、サンプル請求書からメタデータを抽出する方法を示します。

### リクエストの作成

Box AIから応答を取得するには、以下のパラメータを使用して、`POST /2.0/ai/extract`エンドポイントを呼び出します。

* クエリか、抽出するフィールドの構造化リストまたは非構造化リストを指定できる`prompt`。
* データの抽出元となるファイルの`type`および`id`。

### プロンプトの作成

ユースケースや詳細度に応じて、さまざまなプロンプトを作成できます。

#### プレーンテキストを使用する

このエンドポイントでは自由形式のプロンプトが許可されているため、プレーンテキストを使用して情報を取得できます。

```bash theme={null}
curl --location 'https://api.box.com/2.0/ai/extract' \
--header 'Content-Type: application/json' \
--header 'Authorization: Bearer <ACCESS_TOKEN>' \
--data '{
    "prompt": "find the document type (invoice or po), vendor, total, and po number",
    "items": [
        {
            "type": "file",
            "id": "1443721424754"
        }
    ]
}'
```

その場合、レスポンスは、テキストに含まれているキーワードに基づいて作成されます。

```bash theme={null}
{
    "answer": "{\"Document Type\": \"Invoice\", \"Vendor\": \"Quasar Innovations\", \"Total\": \"$1,050\", \"PO Number\": \"003\"}",
    "created_at": "2024-05-31T10:30:51.223-07:00",
    "completion_reason": "done"
}
```

#### 特定の用語を使用する

文全体を書かなくても、請求書に含まれることが予想される用語でプロンプトを構成できます。

```bash theme={null}
curl --location 'https://api.box.com/2.0/ai/extract' \
--header 'Content-Type: application/json' \
--header 'Authorization: <ACCESS_TOKEN>' \
--data '{
    "prompt": "{\"vendor\",\"total\",\"doctype\",\"date\",\"PO\"}",
    "items": [
        {
            "type": "file",
            "id": "1443721424754"
        }
    ]
}'
```

このアプローチを使用すると、以下のように、リクエストで指定した用語のリストとその値が返されます。

```bash theme={null}
{
    "answer": "{\"vendor\": \"Quasar Innovations\", \"total\": \"$1,050\", \"doctype\": \"Invoice\", \"PO\": \"003\"}",
    "created_at": "2024-05-31T10:28:51.906-07:00",
    "completion_reason": "done"
}
```

#### キー/値ペアを使用する

プロンプトには、Box AIがメタデータの構造を認識するのに役立つキー/値ペアのリストを指定することができます。このアプローチでは、`fields`配列内にキー/値ペアを列挙する必要があります。

```bash theme={null}
curl --location 'https://api.box.com/2.0/ai/extract' \
--header 'Content-Type: application/json' \
--header 'Authorization: Bearer <ACCESS_TOKEN>' \
--data '{
          "prompt": "{\"fields\":   [{\"key\":\"vendor\",\"displayName\":\"Vendor\",\"type\":\"string\",\"description\":\ "Vendorname\"},{\"key\":\"documentType\",\"displayName\":\"Type\",\"type\":\"string\",\"description\":\"\"}]}",
    "items": [
        {
            "type": "file",
            "id": "1443721424754"
        }
    ]
}'
```

レスポンスには、以下のように、ファイル内に存在する`fields`とその値が含まれます。

```bash theme={null}
{
    "answer": "{\"vendor\": \"Quasar Innovations\", \"documentType\": \"Invoice\"}",
    "created_at": "2024-05-31T10:15:38.17-07:00",
    "completion_reason": "done"
}
```

<RelatedLinks
  title="関連するAPI"
  items={[
{ label: translate("Extract metadata (freeform)"), href: "/reference/post-ai-extract", badge: "POST" }
]}
/>

<RelatedLinks
  title="関連するガイド"
  items={[
{ label: translate("Get started with Box AI"), href: "/guides/box-ai/ai-tutorials/prerequisites", badge: "GUIDE" },
{ label: translate("Override AI model configuration"), href: "/guides/box-ai/ai-tutorials/default-agent-overrides", badge: "GUIDE" },
{ label: translate("Generate text with Box AI"), href: "/guides/box-ai/ai-tutorials/generate-text", badge: "GUIDE" },
{ label: translate("Ask questions to Box AI"), href: "/guides/box-ai/ai-tutorials/ask-questions", badge: "GUIDE" },
{ label: translate("Extract metadata from file (structured)"), href: "/guides/box-ai/ai-tutorials/extract-metadata-structured", badge: "GUIDE" }
]}
/>
