开始使用免费开始使用

设置 token 限制

一家电商平台刚刚聘请您来提升其基于 OpenAI API 构建的客服机器人性能。您决定先从输入消息入手,通过将上限设为 100 个 token,避免触发速率限制问题,并用一条示例输入消息进行测试。

tiktoken 库已预加载。

本练习是课程的一部分

使用 OpenAI API 构建 AI 系统

查看课程

练习说明

  • 使用 tiktoken 库为 gpt-4o-mini 模型创建编码。
  • 检查输入消息中的 token 数是否符合预期。
  • 如果消息通过两项检查,则打印响应。

交互式实操练习

通过完成这段示例代码来试试这个练习。

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")
编辑并运行代码