> ## 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/text_genエンドポイントを使用して、Boxに保存されているファイルコンテンツに基づいてテキストを生成またはリファインします。

# Box AIを使用してテキストを生成する

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>;
};

<Note>
  Box AI APIは、Business以上をご利用のすべてのお客様が利用できます。
</Note>

Box AIを使用すると、提供されたコンテンツに基づいてテキストを生成できます。たとえば、Box Notesで参照または作成したコンテンツに基づいてテンプレートを生成するようBox AIに求めることができます。その後、生成されたテキストを直接ドキュメントに埋め込むことができます。

## 開始する前に

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

## リクエストの送信

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

<CodeGroup>
  ```sh cURL theme={null}
  curl -i -L POST "https://api.box.com/2.0/ai/text_gen" \
       -H "content-type: application/json" \
       -H "authorization: Bearer <ACCESS_TOKEN>" \
       -d '{
            "prompt": "Write a social media post about protein powder.",
            "items": [
           {
              "id": "12345678",
              "type": "file",
              "content": "More information about protein powders"
          },
          ],
            "dialogue_history": [
              {
                  "prompt": "Can you add some more information?",
                  "answer": "Public API schemas provide necessary information to integrate with APIs...",
                  "created_at": "2013-12-12T11:20:43-08:00"
              }
          ],
            "ai_agent": {
              "type": "ai_agent_text_gen",
              "basic_gen": {
                "model": "openai__gpt_5_mini"
              }
           }
       }'
  ```

  ```typescript Node/TypeScript v10 theme={null}
  await client.ai.createAiTextGen({
    prompt: 'Parapharse the document.s',
    items: [
      new AiTextGenItemsField({
        id: fileToAsk.id,
        type: 'file' as AiTextGenItemsTypeField,
        content:
          'The Earth goes around the sun. Sun rises in the East in the morning.',
      }),
    ],
    dialogueHistory: [
      {
        prompt: 'What does the earth go around?',
        answer: 'The sun',
        createdAt: dateTimeFromString('2021-01-01T00:00:00Z'),
      } satisfies AiDialogueHistory,
      {
        prompt: 'On Earth, where does the sun rise?',
        answer: 'East',
        createdAt: dateTimeFromString('2021-01-01T00:00:00Z'),
      } satisfies AiDialogueHistory,
    ],
    aiAgent: aiTextGenAgentConfig,
  } satisfies AiTextGen);
  ```

  ```python Python v10 theme={null}
  client.ai.create_ai_text_gen(
      "Parapharse the document.s",
      [
          CreateAiTextGenItems(
              id=file_to_ask.id,
              type=CreateAiTextGenItemsTypeField.FILE,
              content="The Earth goes around the sun. Sun rises in the East in the morning.",
          )
      ],
      dialogue_history=[
          AiDialogueHistory(
              prompt="What does the earth go around?",
              answer="The sun",
              created_at=date_time_from_string("2021-01-01T00:00:00Z"),
          ),
          AiDialogueHistory(
              prompt="On Earth, where does the sun rise?",
              answer="East",
              created_at=date_time_from_string("2021-01-01T00:00:00Z"),
          ),
      ],
      ai_agent=ai_text_gen_agent_config,
  )
  ```

  ```cs .NET v10 theme={null}
  await client.Ai.CreateAiTextGenAsync(requestBody: new AiTextGen(prompt: "Parapharse the document.s", items: Array.AsReadOnly(new [] {new AiTextGenItemsField(id: fileToAsk.Id, type: AiTextGenItemsTypeField.File) { Content = "The Earth goes around the sun. Sun rises in the East in the morning." }})) { DialogueHistory = Array.AsReadOnly(new [] {new AiDialogueHistory() { Prompt = "What does the earth go around?", Answer = "The sun", CreatedAt = Utils.DateTimeFromString(dateTime: "2021-01-01T00:00:00Z") },new AiDialogueHistory() { Prompt = "On Earth, where does the sun rise?", Answer = "East", CreatedAt = Utils.DateTimeFromString(dateTime: "2021-01-01T00:00:00Z") }}) });
  ```

  ```swift Swift v10 theme={null}
  try await client.ai.createAiTextGen(requestBody: AiTextGen(prompt: "Parapharse the document.s", items: [AiTextGenItemsField(id: fileToAsk.id, type: AiTextGenItemsTypeField.file, content: "The Earth goes around the sun. Sun rises in the East in the morning.")], dialogueHistory: [AiDialogueHistory(prompt: "What does the earth go around?", answer: "The sun", createdAt: try Utils.Dates.dateTimeFromString(dateTime: "2021-01-01T00:00:00Z")), AiDialogueHistory(prompt: "On Earth, where does the sun rise?", answer: "East", createdAt: try Utils.Dates.dateTimeFromString(dateTime: "2021-01-01T00:00:00Z"))]))
  ```

  ```java Java v10 theme={null}
  client.getAi().createAiTextGen(new AiTextGen.Builder("Parapharse the document.s", Arrays.asList(new AiTextGenItemsField.Builder(fileToAsk.getId()).type(AiTextGenItemsTypeField.FILE).content("The Earth goes around the sun. Sun rises in the East in the morning.").build())).dialogueHistory(Arrays.asList(new AiDialogueHistory.Builder().prompt("What does the earth go around?").answer("The sun").createdAt(dateTimeFromString("2021-01-01T00:00:00Z")).build(), new AiDialogueHistory.Builder().prompt("On Earth, where does the sun rise?").answer("East").createdAt(dateTimeFromString("2021-01-01T00:00:00Z")).build())).aiAgent(aiTextGenAgentConfig).build())
  ```

  ```java Java v5 theme={null}
  List<BoxAIDialogueEntry> dialogueHistory = new ArrayList<>();
  dialogueHistory.add(
          new BoxAIDialogueEntry(
              "Make my email about public APIs sound more professional",
              "Here is the first draft of your professional email about public APIs.",
              BoxDateFormat.parse("2013-05-16T15:26:57-07:00")
          )
      );
  BoxAIResponse response = BoxAI.sendAITextGenRequest(
      api,
      "Write an email to a client about the importance of public APIs.",
      Collections.singletonList(new BoxAIItem("123456", BoxAIItem.Type.FILE)),
      dialogueHistory
  );
  ```

  ```python Python v4 theme={null}
  items = [{
      "id": "1582915952443",
      "type": "file",
      "content": "More information about public APIs"
  }]
  dialogue_history = [{
          "prompt": "Make my email about public APIs sound more professional",
          "answer": "Here is the first draft of your professional email about public APIs",
          "created_at": "2013-12-12T10:53:43-08:00"
      },
      {
          "prompt": "Can you add some more information?",
          "answer": "Public API schemas provide necessary information to integrate with APIs...",
          "created_at": "2013-12-12T11:20:43-08:00"
  }]
  ai_agent = {
      'type': 'ai_agent_text_gen',
      'basic_gen': {
          'model': 'openai__gpt_3_5_turbo_16k'
      }
  }
  answer = client.send_ai_text_gen(
      dialogue_history=dialogue_history,
      items=items,
      prompt="Write an email to a client about the importance of public APIs.",
      ai_agent=ai_agent
  )
  print(answer)
  ```

  ```cs .NET v6 theme={null}
  BoxAIResponse response = await client.BoxAIManager.SendAITextGenRequestAsync(
      new BoxAITextGenRequest
      {
          Prompt = "What is the name of the file?",
          Items = new List<BoxAITextGenItem>() { new BoxAITextGenItem() { Id = "12345" } },
          DialogueHistory = new List<BoxAIDialogueHistory>()
          {
              new BoxAIDialogueHistory() { Prompt = "What is the name of the file?", Answer = "MyFile", CreatedAt = DateTimeOffset.Parse("2024-05-16T15:26:57-07:00") }
              new BoxAIDialogueHistory() { Prompt = "What is the size of the file?", Answer = "10kb", CreatedAt =  DateTimeOffset.Parse("2024-05-16T15:26:57-07:00") }
          }
      };
  );
  ```

  ```javascript Node v4 theme={null}
  client.ai.textGen(
      {
          prompt: 'What is the capital of France?',
          items: [
              {
                  type: 'file',
                  id: '12345'
              }
          ],
          dialogue_history: [
              {
                  prompt: 'What is the capital of France?',
                  answer: 'Paris',
                  created_at: '2021-10-01T00:00:00Z'
              },
              {
                  prompt: 'What is the capital of Germany?',
                  answer: 'Berlin',
                  created_at: '2021-10-01T00:00:00Z'
              }
          ]
      })
      .then(response => {
          /* response -> {
              "answer": "The capital of France is Paris.",
              "created_at": "2021-10-01T00:00:00Z",
              "completion_reason": "done"
          } */
      });
  ```
</CodeGroup>

### パラメータ

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

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

| パラメータ                         | 説明                                                                                                                                                                                                                                                                  | 例                                                               |
| ----------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------- |
| **`prompt`**                  | Box AIに対するテキストの生成またはリファインのリクエスト。最大10,000文字。                                                                                                                                                                                                                         | 週1回の営業会議のアジェンダを作成してください。                                        |
| **`items.id`**                | ドキュメントのBoxファイルID。                                                                                                                                                                                                                                                   | `1233039227512`                                                 |
| **`items.type`**              | 指定した入力データのタイプ。                                                                                                                                                                                                                                                      | `file`                                                          |
| `items.content`               | 項目のコンテンツ (多くの場合はテキストレプリゼンテーション)。                                                                                                                                                                                                                                    | `This article is about Box AI`.                                 |
| `dialogue_history.prompt`     | 以前にクライアントによって提供され、大規模言語モデル (LLM) が回答したプロンプト。                                                                                                                                                                                                                        | `Make my email about public APIs sound more professional`       |
| `dialogue_history.answer`     | 以前にLLMから提供された回答。                                                                                                                                                                                                                                                    | `Here is a draft of your professional email about public APIs.` |
| `dialogue_history.created_at` | プロンプトに対する前回の回答が作成された時点のISO日付形式のタイムスタンプ。                                                                                                                                                                                                                             | `2012-12-12T10:53:43-08:00`                                     |
| `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>を参照してください。 |                                                                 |

## ユースケース

指定されたファイルコンテンツとプロンプトに基づいてテキストを生成します。

```sh theme={null}
curl -i -L POST "https://api.box.com/2.0/ai/text_gen" \
     -H "content-type: application/json" \
     -H "authorization: Bearer <ACCESS_TOKEN>" \
     -d '{
    "items": [
        {
            "id": "12345678",
            "type": "file"
        }
    ],
    "prompt": "Create a short blog post that provides information on Box AI for Documents and focuses on best practices for asking questions. You can add emoticons, but not too many."
}'
```

結果は次のようになります。

```sh theme={null}
{
    "answer": "📝 **Box AI for Documents: Best Practices for Asking Questions** 🤔\n\n---\n\nWelcome to our blog post on Box AI for Documents! 🎉 Today, we're going to dive into some best practices when it comes to asking questions within this innovative platform.\n\n1. **Be Clear and Concise**: When formulating a question in Box Notes, make sure your query is clear and to the point. This helps Box AI understand exactly what you're looking for.\n\n2. **Provide Context**: Giving context around your question can significantly improve the accuracy of the response generated by Box AI. Include relevant details or background information.\n\n3. **Use Keywords**: Utilize keywords related to your query within the question itself. This can help Box AI better identify the main topic of your inquiry.\n\n4. **Avoid Ambiguity**: Try to avoid vague or ambiguous questions that could lead to misunderstandings. The more precise you are, the better Box AI can assist you.\n\n5. **Review Suggestions Carefully**: After receiving suggestions from Box AI, take the time to review them carefully before incorporating them into your document. Ensure they align with your intended message.\n\nBy following these best practices, you can maximize the effectiveness of Box AI for Documents and streamline your workflow like never before! 💼✨\n\nStay tuned for more tips and tricks on leveraging technology for enhanced productivity! 👩‍💻🚀",
    "created_at": "2024-11-04T02:46:23.459-08:00",
    "completion_reason": "done"
}
```

<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("Ask questions to Box AI"), href: "/guides/box-ai/ai-tutorials/ask-questions", badge: "GUIDE" },
{ label: translate("Extract metadata from file (freeform)"), href: "/guides/box-ai/ai-tutorials/extract-metadata", badge: "GUIDE" },
{ label: translate("Extract metadata from file (structured)"), href: "/guides/box-ai/ai-tutorials/extract-metadata-structured", badge: "GUIDE" }
]}
/>
