批处理

使用 OpenAI API 构建 AI 系统

Francesca Donadoni

Curriculum Manager, DataCamp

什么是速率限制

一名开车的人被警察拦下

使用 OpenAI API 构建 AI 系统

速率限制的成因

 

  • 请求过多

    一组对话气泡,表示多条消息

 

  • 请求文本过长

    白色背景上的大型对话气泡图标,表示长消息
使用 OpenAI API 构建 AI 系统

避免速率限制

 

  • 重试
    • 请求间短暂等待

 

  • 批处理
    • 在一次请求中处理多条消息

 

  • 减少 tokens
    • 统计并减少 token 数量
使用 OpenAI API 构建 AI 系统

重试

 

from tenacity import (
    retry,
    stop_after_attempt,
    wait_random_exponential
)

@retry(wait=wait_random_exponential(min=1, max=60), stop=stop_after_attempt(6))
使用 OpenAI API 构建 AI 系统

重试

 

@retry(wait=wait_random_exponential(min=1, max=60), stop=stop_after_attempt(6))

def get_response(model, message): response = client.chat.completions.create( model=model, messages=[message], response_format={"type": "json_object"} ) return response.choices[0].message.content
使用 OpenAI API 构建 AI 系统

批处理

countries = ["United States", "Ireland", "India"]

message=[
    {
    "role": "system",
    "content": """You are given a series of countries and are asked to return the 
    country and capital city. Provide each of the questions with an answer in the 
    response as separate content.""",
    }]


[message.append({"role": "user", "content": i }) for i in countries]
使用 OpenAI API 构建 AI 系统

批处理

response = client.chat.completions.create(
      model="gpt-4o-mini",
      messages=message
    )

print(response.choices[0].message.content)
United States: Washington D.C.
Ireland: Dublin
India: New Delhi
使用 OpenAI API 构建 AI 系统

减少 tokens

 

import tiktoken


encoding = tiktoken.encoding_for_model("gpt-4o-mini")
prompt = "Tokens can be full words, or groups of characters commonly grouped together: tokenization."
num_tokens = len(encoding.encode(prompt))
print("Number of tokens in prompt:", num_tokens)
Number of tokens in prompt: 17
使用 OpenAI API 构建 AI 系统

Passons à la pratique !

使用 OpenAI API 构建 AI 系统

Preparing Video For Download...