ChatGPT API 완벽 가이드
OpenAI ChatGPT API를 활용한 애플리케이션 개발
ChatGPT API 완벽 가이드
OpenAI API를 사용하여 자신만의 ChatGPT 기반 애플리케이션을 구축하는 방법을 알아봅니다.
API 시작하기
1. API 키 발급
- platform.openai.com 접속
- 계정 생성 또는 로그인
- API Keys 메뉴에서 새 키 생성
- 키를 안전하게 저장
2. 설치
# Python
pip install openai
# Node.js
npm install openai
기본 사용법
Python 예시
from openai import OpenAI
client = OpenAI(api_key="your-api-key")
response = client.chat.completions.create(
model="gpt-4o",
messages=[
{"role": "system", "content": "당신은 친절한 AI 어시스턴트입니다."},
{"role": "user", "content": "안녕하세요!"}
],
temperature=0.7,
max_tokens=1000
)
print(response.choices[0].message.content)
Node.js/TypeScript 예시
import OpenAI from 'openai';
const openai = new OpenAI({
apiKey: process.env.OPENAI_API_KEY,
});
async function chat(userMessage: string) {
const completion = await openai.chat.completions.create({
model: "gpt-4o",
messages: [
{ role: "system", content: "당신은 친절한 AI 어시스턴트입니다." },
{ role: "user", content: userMessage }
],
});
return completion.choices[0].message.content;
}
핵심 파라미터
| 파라미터 | 설명 | 기본값 | 범위 |
|---|---|---|---|
| model | 사용할 모델 | - | gpt-4o, gpt-4, gpt-3.5-turbo |
| temperature | 응답의 창의성 | 1 | 0-2 |
| max_tokens | 최대 출력 토큰 | 모델별 상이 | 1-128000 |
| top_p | nucleus sampling | 1 | 0-1 |
| frequency_penalty | 반복 억제 | 0 | -2 to 2 |
| presence_penalty | 새 주제 유도 | 0 | -2 to 2 |
스트리밍 응답
긴 응답을 실시간으로 받아 사용자 경험을 향상시킬 수 있습니다.
stream = client.chat.completions.create(
model="gpt-4o",
messages=[{"role": "user", "content": "긴 이야기를 해주세요"}],
stream=True
)
for chunk in stream:
if chunk.choices[0].delta.content:
print(chunk.choices[0].delta.content, end="")
Function Calling
AI가 외부 함수를 호출하도록 할 수 있습니다.
tools = [{
"type": "function",
"function": {
"name": "get_weather",
"description": "지정된 위치의 현재 날씨를 가져옵니다",
"parameters": {
"type": "object",
"properties": {
"location": {
"type": "string",
"description": "도시명, 예: 서울"
}
},
"required": ["location"]
}
}
}]
response = client.chat.completions.create(
model="gpt-4o",
messages=[{"role": "user", "content": "서울 날씨 어때?"}],
tools=tools,
tool_choice="auto"
)
# 함수 호출 결과 처리
tool_calls = response.choices[0].message.tool_calls
if tool_calls:
function_name = tool_calls[0].function.name
arguments = json.loads(tool_calls[0].function.arguments)
# 실제 함수 실행 후 결과 전달
에러 처리
from openai import APIError, RateLimitError, APIConnectionError
try:
response = client.chat.completions.create(...)
except RateLimitError:
print("요청 한도 초과. 잠시 후 재시도...")
time.sleep(60)
except APIConnectionError:
print("API 연결 실패")
except APIError as e:
print(f"API 오류: {e}")
비용 최적화 팁
- 가능하면
gpt-3.5-turbo사용 (비용 1/10) max_tokens를 적절히 제한- 시스템 프롬프트 길이 최적화
- 불필요한 대화 히스토리 정리
- 캐싱 전략 활용