뒤로
임세진
·
OpenAI API 사용법 간략한 소개
OpenAI API 속 기능들
일반적인 사용법
from openai import OpenAI client = OpenAI( # defaults to os.environ.get("OPENAI_API_KEY") api_key="My API Key", ) chat_completion = client.chat.completions.create( messages=[ { "role": "user", "content": "Say this is a test", } ], model="gpt-3.5-turbo", )
Async 방식으로 요청 시
import asyncio
from openai import AsyncOpenAI
client = AsyncOpenAI(
# defaults to os.environ.get("OPENAI_API_KEY")
api_key="My API Key",
)
async def main() -> None:
chat_completion = await client.chat.completions.create(
messages=[
{
"role": "user",
"content": "Say this is a test",
}
],
model="gpt-3.5-turbo",
)
asyncio.run(main())실시간 Stream 방식으로 요청 시
Sync
from openai import OpenAI client = OpenAI() stream = client.chat.completions.create( model="gpt-4", messages=[{"role": "user", "content": "Say this is a test"}], stream=True, ) for chunk in stream: if chunk.choices[0].delta.content is not None: print(chunk.choices[0].delta.content)Async
하단 URL에서 보실 수 있어요~
이 외에도 다양한 기능들이 있어요~
Nested params와 같이 출력 양식을 정해주는 것도 있구요.
from openai import OpenAI
client = OpenAI(api_key="API-KEY")
completion = client.chat.completions.create(
messages=[
{
"role": "user",
"content": "Can you generate an example json object describing a fruit?",
}
],
model="gpt-3.5-turbo-1106",
response_format={"type": "json_object"},
)
completion.choices[0].message.contenttimeout, max_tries 등과 같이 API에 response 관련된 요청 사항을 넘겨줄 수도 있어요.
from openai import OpenAI
# Configure the default for all requests:
client = OpenAI()
# Or, configure per-request:
client.with_options(max_retries=5, timeout=60).chat.completions.create(
messages=[
{
"role": "user",
"content": "How can I get the name of the current day in Node.js?",
}
],
model="gpt-3.5-turbo",
)위의 요청 내용은 매 try 마다 timeout 60초의 제한 시간을 부여하고, 60초 안에 답변 생성이 되지 않으면 max_retries인 최대 5회까지만 생성 시도를 하라는 뜻이에요. (기본 max_retries 값은 2라고 하네요.)
이 두 조합을 적절하게 잘 배합해서 사용하면 원하는 시간 내로 API 요청에 대한 답변을 받아볼 수 있어요. (응답이 오기까지 무기한 기다리지 않아도 된다는 말이죠.)
프롬프트에 따라 적절한 timeout과 max_retries 값은 달라질 것 같으니, 각자 서비스에 맞는 파라미터 값들을 찾아내는 것이 필요할 것 같아 보여요.
10X AI Club
그룹의 글
휴튼
나도 몰랐던 나를 알아가는 질문들
13
댓글
로그인 후 댓글을 남길 수 있습니다.
아직 댓글이 없습니다.