OpenAI의 Chat Completions API는 대화형 LLM 상호작용의 표준 인터페이스입니다.
Copy
from openai import OpenAI# 클라이언트 초기화client = OpenAI() # OPENAI_API_KEY 환경 변수에서 자동 로드# 기본 호출response = client.chat.completions.create( model="gpt-4o-mini", messages=[ { "role": "system", "content": "당신은 친절한 한국어 AI 어시스턴트입니다." }, { "role": "user", "content": "자연어 처리가 무엇인지 한 문장으로 설명해 주세요." } ], temperature=0.7, # 생성 다양성 (0.0 ~ 2.0) max_tokens=200, # 최대 출력 토큰 수)# 응답 추출answer = response.choices[0].message.contentprint(answer)# 토큰 사용량 확인usage = response.usageprint(f"입력 토큰: {usage.prompt_tokens}")print(f"출력 토큰: {usage.completion_tokens}")print(f"총 토큰: {usage.total_tokens}")
주요 파라미터 정리:
파라미터
설명
기본값
권장 범위
model
사용할 모델 ID
-
gpt-4o-mini, gpt-4o
temperature
생성 다양성 제어
1.0
0.0 (결정적) ~ 1.5 (창의적)
max_tokens
최대 출력 토큰 수
모델별 상이
태스크에 맞게 설정
top_p
누적 확률 기반 샘플링
1.0
0.1 ~ 1.0
frequency_penalty
반복 토큰 패널티
0.0
0.0 ~ 1.0
presence_penalty
새 토픽 유도
0.0
0.0 ~ 1.0
temperature와 top_p는 동시에 조절하지 않는 것이 좋습니다. 둘 중 하나를 고정하고 나머지를 조절합니다.
2
멀티턴 대화 관리
Chat Completions API는 stateless입니다. 대화 히스토리를 직접 관리해야 합니다.
Copy
from openai import OpenAIclient = OpenAI()# 대화 히스토리 관리conversation = [ {"role": "system", "content": "당신은 NLP 전문가입니다. 간결하게 답변합니다."}]def chat(user_message: str) -> str: """사용자 메시지를 추가하고 응답을 받아 히스토리에 저장합니다.""" conversation.append({"role": "user", "content": user_message}) response = client.chat.completions.create( model="gpt-4o-mini", messages=conversation, temperature=0.7, ) assistant_message = response.choices[0].message.content conversation.append({"role": "assistant", "content": assistant_message}) return assistant_message# 대화 진행print(chat("Transformer의 핵심 메커니즘은 무엇인가요?"))print(chat("그것이 RNN보다 나은 점은 무엇인가요?")) # 이전 문맥을 기억합니다print(chat("구체적인 예시를 들어주세요."))
대화가 길어지면 토큰 수가 누적됩니다. 컨텍스트 윈도우 제한(예: GPT-4o-mini는 128K 토큰)에 유의하고, 필요하면 오래된 메시지를 정리하는 전략이 필요합니다.
3
Anthropic Claude API
Anthropic의 Claude API는 메시지 구조와 시스템 프롬프트 처리 방식이 OpenAI와 다릅니다.
Copy
import anthropic# 클라이언트 초기화client = anthropic.Anthropic() # ANTHROPIC_API_KEY 환경 변수에서 자동 로드# 기본 호출response = client.messages.create( model="claude-sonnet-4-20250514", max_tokens=1024, system="당신은 친절한 한국어 AI 어시스턴트입니다.", # system은 별도 파라미터 messages=[ { "role": "user", "content": "BERT와 GPT의 핵심 차이를 표로 정리해 주세요." } ],)# 응답 추출answer = response.content[0].textprint(answer)# 토큰 사용량 확인print(f"입력 토큰: {response.usage.input_tokens}")print(f"출력 토큰: {response.usage.output_tokens}")
OpenAI vs Anthropic API 비교:
항목
OpenAI
Anthropic
시스템 프롬프트
messages 배열 내 role: system
별도 system 파라미터
응답 구조
response.choices[0].message.content
response.content[0].text
토큰 카운트
prompt_tokens / completion_tokens
input_tokens / output_tokens
모델 명명
gpt-4o, gpt-4o-mini
claude-sonnet-4-20250514 등
최대 출력
max_tokens (선택)
max_tokens (필수)
4
HuggingFace Inference API
HuggingFace Inference API를 사용하면 오픈소스 모델을 서버 없이 호출할 수 있습니다.
Copy
from huggingface_hub import InferenceClient# 클라이언트 초기화client = InferenceClient(token=os.getenv("HF_TOKEN"))# 텍스트 생성 (오픈소스 모델 활용)response = client.text_generation( prompt="자연어 처리(NLP)란", model="meta-llama/Llama-3.1-8B-Instruct", max_new_tokens=200, temperature=0.7,)print(response)
Chat 형태로도 호출할 수 있습니다.
Copy
# Chat Completion 스타일 호출response = client.chat_completion( model="meta-llama/Llama-3.1-8B-Instruct", messages=[ {"role": "system", "content": "당신은 유용한 AI 어시스턴트입니다."}, {"role": "user", "content": "트랜스포머의 핵심 구성요소를 설명해 주세요."}, ], max_tokens=500,)print(response.choices[0].message.content)
HuggingFace의 무료 Inference API는 요청 속도 제한이 있습니다. 프로덕션 환경에서는 Inference Endpoints로 전용 인스턴스를 배포하는 것이 안정적입니다.
5
스트리밍 응답 처리
긴 응답을 생성할 때 스트리밍을 사용하면 사용자 경험이 크게 향상됩니다. 토큰이 생성되는 즉시 화면에 표시할 수 있습니다.OpenAI 스트리밍:
Copy
from openai import OpenAIclient = OpenAI()# 스트리밍 호출 (stream=True)stream = client.chat.completions.create( model="gpt-4o-mini", messages=[ {"role": "user", "content": "Transformer 아키텍처를 상세하게 설명해 주세요."} ], stream=True, # 스트리밍 활성화)# 토큰 단위로 출력full_response = ""for chunk in stream: if chunk.choices[0].delta.content is not None: token = chunk.choices[0].delta.content print(token, end="", flush=True) full_response += tokenprint() # 줄바꿈print(f"\n전체 응답 길이: {len(full_response)}자")
Anthropic 스트리밍:
Copy
import anthropicclient = anthropic.Anthropic()# 스트리밍 호출with client.messages.stream( model="claude-sonnet-4-20250514", max_tokens=1024, messages=[ {"role": "user", "content": "Self-Attention의 동작 과정을 단계별로 설명해 주세요."} ],) as stream: for text in stream.text_stream: print(text, end="", flush=True)print()# 최종 메시지에서 토큰 사용량 확인final_message = stream.get_final_message()print(f"입력 토큰: {final_message.usage.input_tokens}")print(f"출력 토큰: {final_message.usage.output_tokens}")