클로드 API 시작 전 준비
클로드 API를 사용하려면 먼저 몇 가지 준비가 필요해요. API Key 발급, 개발 환경 설정, 필요한 라이브러리 설치 등이 그것입니다. 이 준비 단계를 제대로 거치면, 실제 개발이 훨씬 수월해져요.
처음 API를 다루는 사람이라도, 이 가이드를 차근차근 따라가면 충분히 할 수 있습니다. 각 단계마다 구체적인 예제 코드를 제공하므로, 복사해서 바로 사용할 수 있어요.
API Key 발급 및 설정
Anthropic 계정 생성
먼저 console.anthropic.com에 접속하세요. 새 계정을 만들거나 기존 계정으로 로그인하세요. 회원가입 시 이메일 인증을 거쳐야 하므로, 사용 중인 이메일 주소를 입력하세요.
계정 생성 후에는 결제 정보를 등록해야 해요. API는 사용량에 따라 청구되므로, 신용카드 정보를 입력해야 합니다. 정보는 안전하게 암호화되어 관리돼요.
API Key 생성
콘솔에 로그인한 후, 좌측 메뉴에서 ‘API Keys’ 항목을 찾으세요. ‘새 키 생성’ 버튼을 클릭하면, 새로운 API Key가 생성돼요. 이 Key 값을 반드시 복사해서 안전한 곳에 저장하세요.
Key를 잃어버렸다면, 새로운 Key를 생성하면 돼요. 이전 Key는 자동으로 삭제되지 않으므로, 보안 관리를 위해 불필요한 Key는 수동으로 삭제해야 합니다.
환경 변수 설정
API Key를 코드에 직접 입력하면 보안상 위험해요. 대신 환경 변수로 설정하세요.
Mac/Linux:
“`bash
export ANTHROPIC_API_KEY=”sk-…”
“`
Windows (PowerShell):
“`powershell
$env:ANTHROPIC_API_KEY=”sk-…”
“`
또는 .env 파일을 만들고, 다음을 입력하세요:
“`
ANTHROPIC_API_KEY=sk-…
“`
개발 환경 설정
Python 설치
Python을 아직 설치하지 않았다면, python.org에서 최신 버전을 다운로드해서 설치하세요. 설치 후 터미널에서 다음 명령으로 확인하세요:
“`bash
python –version
“`
가상 환경 생성
프로젝트별로 독립된 환경을 만드는 것이 좋은 관행이에요:
“`bash
python -m venv myproject_env
source myproject_env/bin/activate # Mac/Linux
myproject_env\Scripts\activate # Windows
“`
필요한 라이브러리 설치
“`bash
pip install anthropic python-dotenv
“`
설치 확인:
“`bash
pip list | grep anthropic
“`
첫 번째 API 호출
간단한 예제
test.py 파일을 만들고 다음을 입력하세요:
“`python
import os
from anthropic import Anthropic
from dotenv import load_dotenv
# .env 파일 로드
load_dotenv()
# 클라이언트 초기화
client = Anthropic(
api_key=os.environ.get(“ANTHROPIC_API_KEY”)
)
# API 호출
message = client.messages.create(
model=”claude-3-5-sonnet-20241022″,
max_tokens=1024,
messages=[
{“role”: “user”, “content”: “안녕하세요! 당신은 누구인가요?”}
]
)
# 응답 출력
print(message.content[0].text)
“`
실행하세요:
“`bash
python test.py
“`
응답 분석
응답에는 여러 정보가 포함돼요:
- content: 실제 응답 텍스트
- usage: 사용한 토큰 수
- stop_reason: 응답 종료 이유
“`python
response = client.messages.create(…)
print(f”응답: {response.content[0].text}”)
print(f”입력 토큰: {response.usage.input_tokens}”)
print(f”출력 토큰: {response.usage.output_tokens}”)
“`
대화형 애플리케이션
멀티턴 대화
“`python
messages = []
while True:
user_input = input(“당신: “)
if user_input.lower() == “exit”:
break
messages.append({“role”: “user”, “content”: user_input})
response = client.messages.create(
model=”claude-3-5-sonnet-20241022″,
max_tokens=1024,
messages=messages
)
assistant_message = response.content[0].text
messages.append({“role”: “assistant”, “content”: assistant_message})
print(f”클로드: {assistant_message}”)
“`
시스템 프롬프트 활용
“`python
system_prompt = “당신은 친절한 한국어 교사입니다. 사용자의 질문에 정중하게 답변하세요.”
message = client.messages.create(
model=”claude-3-5-sonnet-20241022″,
max_tokens=1024,
system=system_prompt,
messages=[
{“role”: “user”, “content”: “한국어를 배우고 싶어요”}
]
)
print(message.content[0].text)
“`
고급 기능
이미지 처리
“`python
import base64
def encode_image(image_path):
with open(image_path, “rb”) as image_file:
return base64.standard_b64encode(image_file.read()).decode(“utf-8”)
image_data = encode_image(“photo.jpg”)
message = client.messages.create(
model=”claude-3-5-sonnet-20241022″,
max_tokens=1024,
messages=[
{
“role”: “user”,
“content”: [
{
“type”: “image”,
“source”: {
“type”: “base64”,
“media_type”: “image/jpeg”,
“data”: image_data,
},
},
{
“type”: “text”,
“text”: “이 사진의 내용을 설명해주세요”
}
],
}\br/> ],
)
print(message.content[0].text)
“`
스트리밍 응답
“`python
with client.messages.stream(
model=”claude-3-5-sonnet-20241022″,
max_tokens=1024,
messages=[{“role”: “user”, “content”: “긴 이야기를 써주세요”}]
) as stream:
for text in stream.text_stream:
print(text, end=””, flush=True)
print() # 줄바꿈
“`
에러 처리
기본 예외 처리
“`python
from anthropic import APIError
try:
message = client.messages.create(
model=”claude-3-5-sonnet-20241022″,
max_tokens=1024,
messages=[{“role”: “user”, “content”: “Hello”}]
)
print(message.content[0].text)
except APIError as e:
print(f”API 에러: {e}”)
“`
재시도 로직
“`python
from time import sleep
def call_api_with_retry(max_retries=3):
for attempt in range(max_retries):
try:
return client.messages.create(
model=”claude-3-5-sonnet-20241022″,
max_tokens=1024,
messages=[{“role”: “user”, “content”: “Hello”}]
)
except APIError as e:
if attempt < max_retries - 1:
sleep(2 ** attempt)
else:
raise
“`
실전 예제
텍스트 분석 애플리케이션
“`python
def analyze_text(text):
message = client.messages.create(
model=”claude-3-5-sonnet-20241022″,
max_tokens=1024,
system=”당신은 텍스트 분석 전문가입니다. 주어진 텍스트의 감정, 주제, 키워드를 분석해주세요.”,
messages=[
{“role”: “user”, “content”: text}
]
)
return message.content[0].text
result = analyze_text(“이 제품은 정말 좋아요! 매우 만족합니다.”)
print(result)
“`
결론
클로드 API 사용은 생각보다 간단해요. API Key 발급, 라이브러리 설치, 간단한 호출만으로 시작할 수 있습니다. 이 가이드의 예제들을 참고해서 자신의 프로젝트를 만들어보세요.
더 복잡한 기능이 필요하다면, Anthropic의 공식 문서를 참고하거나 지원팀에 문의할 수 있어요. 즐거운 개발이 되길 바랍니다!