Pythonワークショップ: Box AI API

Yuko Taniguchi
Box Developer Japan Blog
16 min readApr 9, 2024
Image By vecstock

データが豊富な今日の環境において、非構造化ドキュメントから有意義なインサイトを抽出することは非常に重要です。Box AI APIを使用すると、チームがコンテンツの価値を引き出し、要約を出力して、対話型AIを利用するのに役立つ強力なツールキットを入手できます。

このワークショップでは、Box AI APIの機能について詳しく説明し、そのAPIによりアプリケーションがテキストコンテンツを迅速に分析して理解できるようになる仕組みを確認します。作成するものがチャットボット、ナレッジマネジメントシステム、コンテンツ駆動型アプリケーションのいずれであっても、Box AI APIで非構造化データを実用的なインテリジェンスに変換する方法を確認できます。

Box AI APIはプライベートベータ版のみ利用可能であり、機能は変更される可能性があることにご注意ください。

このワークショップは、こちらのGitHubリポジトリにあるコードサンプル一式を使用して進めることができます。ここでは、Box Platformの次世代のPython SDKを使用します。

それでは、始めましょう。

概念

Box AI APIには、主に以下の3つの概念があります。

  • 質問: アプリがあるコンテンツに関して質問できるようにする
  • テキスト生成: それまでの質問と回答に基づいて、アプリがBox AIと会話できるようにする
  • コンテキスト: Box AIが質問に回答する際に使用する情報 (1つのドキュメント、複数のドキュメント、または断片的なテキストの場合があります)

コンテンツに関する質問

ここで、Box AIに質問するメソッドを作成します。

def ask(
client: Client, question: str, file_id: str, content: str = None
) -> IntelligenceResponse:
"""Ask a question to the AI"""

if file_id is None:
raise ValueError("file_id must be provided")
mode = IntelligenceMode.SINGLE_ITEM_QA
items = [{"id": file_id, "type": "file"}]
# add content if provided
if content is not None:
items[0]["content"] = content
try:
response = client.intelligence.intelligence_ask(
mode=mode,
prompt=question,
items=items,
)
except BoxAPIError as e:
print(f"Error: {e}")
return response

次に、mainメソッドに入力プロンプトサイクルを作成し、ユーザーがBox AIと対話できるようにします。

def main():
...

# Summarize the file
response = ask(
client,
"Summarize document.",
DEMO_FILE,
)
print(f"\nResponse: {response.answer}")
while True:
question = input("\nAsk a question (type 'exit' to quit): ")
if question == "exit":
break
response = ask(
client,
question,
DEMO_FILE,
)
print(f"\nResponse: {response.answer}")

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

Response: The document outlines the requirements and responsibilities for
participating in scuba diving activities. It states that participants must
be able to swim, be in good physical condition, and release the dive center
from any liabilities. Certified divers are required to follow specific
guidelines such as diving with a buddy, planning their dive responsibly,
carrying necessary equipment, and ending the dive if feeling uncomfortable
or unsafe. The document also emphasizes safety measures in case of distress
while diving. Finally, it includes a section for individuals to agree to
these terms by signing their full name.

Ask a question (type 'exit' to quit): do I need to know how to swim

Response: Yes, you must be able to swim to participate in any in water
activities.

Ask a question (type 'exit' to quit): what are the emergency procedures

Response: Emergency procedures outlined in the document include immediately
ending a dive if feeling uncomfortable with planning abilities or
diving conditions, dropping weight belt and inflating BC for flotation
while signaling for assistance if distressed on the surface, and not
holding breath while scuba diving.

Ask a question (type 'exit' to quit):

参考訳:

回答: このドキュメントでは、スキューバダイビングアクティビティに参加するための要件と責任の概要を説明しています。
参加者は泳げること、体調が良いこと、ダイビングセンターの法的責任を免除することが条件として明記されています。

認定ダイバーは、仲間と一緒に潜る、責任を持ってダイビングを計画する、必要な道具を装備する、不安を感じた場合はダイビングを終了するなど、特定のガイドラインに従う必要があります。

また、ドキュメントでは、ダイビング中に遭難した場合の安全対策についても強調しています。
最後に、個人がフルネームを署名してこれらの利用規約に同意するためのセクションが用意されています。

質問してください (終了するには「exit」と入力してください ): 泳ぎ方を知っておく必要はありますか

回答: はい。ウォーターアクティビティに参加するには、泳げる必要があります。

質問してください (終了するには「exit」と入力してください): 緊急時の対応について教えてください

回答: このドキュメントで説明されている緊急時の対応には、企画力やダイビングの状況に不安を感じた場合はすぐにダイビングを終了すること、水面で苦しくなった場合はウェイトベルトをはずし、浮力調整装置を膨らませて浮力を確保しながら合図を送って助けを求めること、スキューバダイビング中に息を止めないことが含まれます。

質問してください (終了するには「exit」と入力してください):

ご覧のとおり、ユーザーはコンテンツに関する質問を続けることができます。上記の例で使用したのは1つのファイルだけですが、複数のファイルについて質問することも、コンテキストを表す断片的なテキストについて質問することもできます。

テキスト生成

テキスト生成モードでは、それまでの質問と回答に基づいてBox AIと会話することができます。

ここで、プロンプトに基づいてテキストを生成するメソッドを作成します。

def text_gen(
client: Client,
prompt: str,
file_id: str,
content: str = None,
dialogue_history: IntelligenceDialogueHistory = None,
) -> IntelligenceResponse:
"""Ask a question to the AI"""

if file_id is None:
raise ValueError("file_id must be provided")
items = [{"id": file_id, "type": "file"}]
# add content if provided
if content is not None:
items[0]["content"] = content
try:
response = client.intelligence.intelligence_text_gen(
prompt=prompt,
items=items,
dialogue_history=dialogue_history,
)
except BoxAPIError as e:
print(f"Error: {e}")
return response

最後に、mainメソッドに入力プロンプトサイクルを作成し、ユーザーがBox AIと対話できるようにします。Box AIが会話のコンテキストを保持できるように、会話の履歴が送り返されていることに注意してください。

def main():
...

# Text gen dialog
dialog_history = []
while True:
question = input(
"\nWhat would you like to talk about? (type 'exit' to quit): "
)
if question == "exit":
break
response = text_gen(
client,
question,
DEMO_FILE,
dialogue_history=dialog_history,
)
print(f"\nResponse: {response.answer}")
dialog_history.append(
IntelligenceDialogueHistory(
prompt=question,
answer=response.answer,
created_at=response.created_at,
)
)

会話の例を以下に示します。

What would you like to talk about? (type 'exit' to quit): 
how to learn how to fly

Response: To learn how to fly, you can follow these steps:

1. Research flight schools in your area or online courses for pilot training.
2. Enroll in a reputable flight school or sign up for an online course with
good reviews.
3. Obtain the necessary medical certificate from an aviation medical
examiner.
4. Start ground school to learn about aircraft systems, navigation, weather
patterns, and regulations.
5. Begin flight training with a certified flight instructor to gain
hands-on experience in the cockpit.
6. Study for and pass the written knowledge test and practical flying exam
administered by the Federal Aviation Administration (FAA) or relevant
aviation authority.

Remember that learning to fly requires dedication, time commitment, and
financial investment but can be incredibly rewarding!

What would you like to talk about? (type 'exit' to quit): tell me about
navigation

Response: Navigation is the process of determining and controlling a
craft's position and direction. It involves using various tools, techniques,
and systems to ensure that the craft reaches its intended destination safely.

There are several methods of navigation:

1. **Pilotage**: This method involves visually identifying landmarks or
using maps to navigate.
2. **Dead Reckoning**: Dead reckoning involves calculating current position
based on previously determined positions, taking into account speed, time,
and course changes.
3. **Radio Navigation**: Using radio signals from ground-based navigational
aids such as VOR (VHF Omnidirectional Range) or NDB (Non-Directional Beacon)
4. **Inertial Navigation Systems (INS)**: These use gyroscopes and
accelerometers to continuously calculate position based on initial starting
point.
5. **Global Positioning System (GPS)**: GPS uses satellites to determine
precise location anywhere on Earth.

Modern aircraft often use a combination of these methods for redundancy
and accuracy in navigation.

It's important for pilots to be proficient in all aspects of navigation to
ensure safe travels from takeoff to landing!

What would you like to talk about? (type 'exit' to quit):

参考訳:

何について話したいですか? (終了するには「exit」と入力してください): 飛行機の操縦方法を習得する方法

回答: 飛行機の操縦方法を習得するには、以下のステップに従ってください。

1. お住まいの地域の航空学校やパイロット養成のオンラインコースを調べます。
2. 評判の良い航空学校に入学するか、良い評価が付いているオンラインコースに申し込みます。
3. 航空身体検査医から必要な診断書を入手します。
4. 地上訓練を開始して、航空機システム、航法、気象パターン、規制について学習します。
5. 認定フライトインストラクターよる飛行訓練を開始して、コックピットでの実践的な経験を積みます。
6. 連邦航空局 (FAA) または関係のある航空当局が実施する筆記試験と操縦の実技試験に向けて勉強し、合格します。

操縦を習得するには、専念する姿勢、時間の確保、金銭的な投資が必要ですが、信じられないほどやりがいがあることを忘れないでください。

何について話したいですか? (終了するには「exit」と入力してください): 航法について教えてください

回答: 航法とは、航空機の位置と方向を決定および制御するプロセスのことです。
航空機が意図した目的地に安全に到着するように、さまざまなツール、手法、システムの使用を伴います。

航法にはいくつかの方法があります。

1. **地文航法**: この方法では、ランドマークを視覚的に識別したり、地図を使用して誘導したりします。
2. **推測航法**: 推測航法では、速度、時間、コース変更を考慮した状態で、あらかじめ決められた位置に基づいて現在の位置を計算します。
3. **無線航法**: VOR (超短波全方向式無線標識) やNDB (無指向性無線標識) などの地上航行援助施設からの電波信号を使用します。
4. **慣性航法装置 (INS)**: ジャイロスコープと加速度計を使用して、最初の起点に基づいて位置を連続的に計算します。
5. **全地球測位システム (GPS)**: GPSでは、衛星を使用して、地球上のどこにいても正確な位置を測定します。

現代の航空機では、航行の冗長性と精度を求めて上記の方法を組み合わせて使用することがよくあります。

パイロットは、離陸から着陸まで安全な旅を約束するために航法のすべての側面に習熟していることが重要です。

何について話したいですか? (終了するには「exit」と入力してください):

今回は、ドキュメントについて具体的な質問はしませんでしたが、それでもBox AIは回答できました。

その後、Box AIは前の質問をフォローアップし、航法について詳細な回答を返しました。

まとめ

Box AI APIには、開発者がアプリケーションで自然言語処理の能力を利用するための堅牢なツールキットが用意されています。質問への回答とテキスト生成の機能により、開発者は、非構造化ドキュメントからインサイトを抽出し、ユーザーが有意義な会話を行える新しい方法を実現できます。

ドキュメントの要約、特定の質問への回答、プロンプトに基づいたテキストの生成のいずれを行う場合も、Box AI APIは、チャットボットの作成からナレッジマネジメントシステムの構築まで、幅広いユースケースに対応する汎用性のあるソリューションを提供します。

アイデア、コメント、フィードバックがある場合は、コミュニティフォーラム (英語のみ) にコメントをお送りください。

--

--