批次處理

使用 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 系統

一起來練習吧!

使用 OpenAI API 開發 AI 系統

Preparing Video For Download...