배치 처리

OpenAI API로 AI 시스템 개발하기

Francesca Donadoni

Curriculum Manager, DataCamp

요율 제한이란?

운전자가 경찰에게 정지된 모습

OpenAI API로 AI 시스템 개발하기

요율 제한이 발생하는 경우

 

  • 요청이 너무 많음

    여러 메시지를 나타내는 많은 말풍선

 

  • 요청 본문이 너무 김

    긴 메시지를 나타내는 큰 말풍선 아이콘
OpenAI API로 AI 시스템 개발하기

요율 제한 피하기

 

  • 재시도
    • 요청 간 짧은 대기

 

  • 배치 처리
    • 여러 메시지를 한 번에 처리

 

  • 토큰 줄이기
    • 토큰 수 측정 및 절감
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 시스템 개발하기

Vamos praticar!

OpenAI API로 AI 시스템 개발하기

Preparing Video For Download...