トークン上限の設定
あなたは 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")