トークン数の上限設定
あるEコマースプラットフォームが、OpenAI APIを使って構築したカスタマーサービスボットのパフォーマンス改善を依頼してきました。まずは、入力メッセージがレート制限の問題を起こさないよう、上限を100トークンに設定することから始めましょう。サンプルの入力メッセージを使って動作を確認します。
tiktoken ライブラリはあらかじめ読み込まれています。
この演習はコースの一部です
OpenAI API を使った AI システムの開発
演習の手順
tiktokenライブラリを使って、gpt-4o-miniモデル用のエンコーディングを作成しましょう。- 入力メッセージのトークン数が想定の範囲内かどうかを確認しましょう。
- 両方のチェックをパスした場合に、レスポンスを出力しましょう。
実践的なインタラクティブ演習
このサンプルコードを完成させて、この演習に挑戦してみましょう。
client = OpenAI(api_key="")
input_message = {"role": "user", "content": "I'd like to buy a shirt and a jacket. Can you suggest two color pairings for these items?"}
# Use tiktoken to create the encoding for your model
encoding = tiktoken.____(____)
# Check for the number of tokens
num_tokens = ____
# Run the chat completions function and print the response
if num_tokens <= ____:
response = client.chat.completions.create(model="gpt-4o-mini", messages=[input_message])
print(____)
else:
print("Message exceeds token limit")