バッチ処理

OpenAI API で開発する AI システム

Francesca Donadoni

Curriculum Manager, DataCamp

レート制限とは

警察官に停止を求められたドライバー

OpenAI API で開発する AI システム

レート制限が発生する原因

 

  • リクエスト過多

    複数のメッセージを表す吹き出しが集まった画像

 

  • リクエストのテキスト過多

    長いメッセージを表す大きな吹き出しアイコン
OpenAI API で開発する AI システム

レート制限の回避

 

  • リトライ
    • リクエスト間に短い待機時間を設ける

 

  • バッチ処理
    • 複数のメッセージを1リクエストで処理

 

  • トークン数の削減
    • トークン数の計測と削減
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 システム

トークン数の削減

 

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...