Claude를 채팅 도구로만 쓰는 건 솔직히 절반도 활용 못 하는 거예요.
API를 연동하면 내 서비스에 Claude를 직접 붙일 수 있고, 커스텀 시스템 프롬프트로 완전히 다른 성격의 AI를 만들 수도 있어요.
이번 포스팅에서는 Anthropic API를 이용해 실제로 쓸 수 있는 AI 앱을 만드는 과정을 단계별로 알아볼게요.
API 키 발급 및 환경 설정
시작 전에 Anthropic Console에서 API 키를 발급받아야 해요. 키는 절대 코드에 하드코딩하지 말고 환경변수로 관리하세요.
# Python 환경 설정
pip install anthropic python-dotenv
# .env 파일 (절대 git에 올리지 마세요!)
ANTHROPIC_API_KEY=sk-ant-api03-...
# Python 코드
import os
from anthropic import Anthropic
from dotenv import load_dotenv
load_dotenv()
client = Anthropic(api_key=os.environ.get("ANTHROPIC_API_KEY"))
# Node.js 환경
npm install @anthropic-ai/sdk dotenv
프로젝트 1: 코드 리뷰 봇
GitHub PR이나 코드 파일을 넣으면 자동으로 리뷰해주는 봇을 만들어볼게요. 시스템 프롬프트로 리뷰 기준을 세밀하게 제어할 수 있어요.
import anthropic
client = anthropic.Anthropic()
def review_code(code: str, language: str = "Python") -> str:
"""코드를 받아서 리뷰 결과를 반환하는 함수"""
message = client.messages.create(
model="claude-sonnet-4-6",
max_tokens=2048,
system="""당신은 시니어 소프트웨어 엔지니어입니다.
코드 리뷰 시 다음 관점으로 검토하세요:
1. 버그 및 잠재적 오류
2. 성능 문제 (시간/공간 복잡도)
3. 보안 취약점
4. 코드 가독성 및 유지보수성
각 이슈는 [심각도: HIGH/MEDIUM/LOW] 형식으로 분류하고,
개선 코드 예시를 반드시 포함하세요.""",
messages=[
{
"role": "user",
"content": f"다음 {language} 코드를 리뷰해주세요:
'''{language.lower()}
{code}
'''"
}
]
)
return message.content[0].text
# 사용 예시
code_to_review = """
def get_user(user_id):
query = "SELECT * FROM users WHERE id = " + str(user_id)
return db.execute(query)
"""
result = review_code(code_to_review, "Python")
print(result)
프로젝트 2: 멀티턴 대화 구현
단순 일회성 질문이 아니라 이전 대화를 기억하는 연속 대화를 구현해볼게요.
class ConversationBot:
def __init__(self, system_prompt: str):
self.client = anthropic.Anthropic()
self.system = system_prompt
self.history = [] # 대화 기록 저장
def chat(self, user_message: str) -> str:
# 대화 기록에 사용자 메시지 추가
self.history.append({
"role": "user",
"content": user_message
})
response = self.client.messages.create(
model="claude-sonnet-4-6",
max_tokens=1024,
system=self.system,
messages=self.history # 전체 대화 기록 전달
)
assistant_message = response.content[0].text
# 대화 기록에 AI 응답 추가
self.history.append({
"role": "assistant",
"content": assistant_message
})
return assistant_message
def clear(self):
self.history = []
# 사용 예시: 기술 면접 연습 봇
bot = ConversationBot(
system_prompt="당신은 네이버 기술 면접관입니다. Java 백엔드 포지션 면접을 진행하세요."
)
print(bot.chat("안녕하세요, 면접 시작할게요."))
print(bot.chat("Spring의 DI와 IoC를 설명해주세요."))
print(bot.chat("방금 답변에 대해 더 구체적인 질문이 있으신가요?"))
스트리밍 응답으로 UX 개선
답변이 길면 전부 생성될 때까지 기다려야 해요. 스트리밍을 쓰면 ChatGPT처럼 글자가 하나씩 나타나는 효과를 구현할 수 있어요.
import anthropic
client = anthropic.Anthropic()
# 스트리밍 응답
with client.messages.stream(
model="claude-sonnet-4-6",
max_tokens=1024,
messages=[{"role": "user", "content": "Python 비동기 처리를 상세히 설명해줘"}]
) as stream:
for text in stream.text_stream:
print(text, end="", flush=True) # 실시간 출력
# FastAPI + 스트리밍 응답 (웹 서버)
from fastapi import FastAPI
from fastapi.responses import StreamingResponse
import anthropic
app = FastAPI()
client = anthropic.Anthropic()
@app.post("/chat/stream")
async def chat_stream(message: str):
def generate():
with client.messages.stream(
model="claude-sonnet-4-6",
max_tokens=1024,
messages=[{"role": "user", "content": message}]
) as stream:
for text in stream.text_stream:
yield f"data: {text}
"
return StreamingResponse(generate(), media_type="text/event-stream")
Tip💡 API 비용을 절약하려면 캐싱 전략을 활용하세요. Anthropic은 Prompt Caching 기능을 지원해서 동일한 시스템 프롬프트를 반복 사용할 때 비용을 최대 90%까지 줄일 수 있어요.
'AI' 카테고리의 다른 글
| [Claude]Claude를 200% 활용하는 프롬프트 엔지니어링 실전 가이드 (0) | 2026.04.09 |
|---|---|
| [Claude] 어느순간 내 buddy가 바꼈다..!! (0) | 2026.04.06 |
| [Claude]요즘 다 쓴다는 Claude, 뭐가 그렇게 다른 걸까? (0) | 2026.04.05 |
| [Claude] Claude Code 'Plan Mode': 생각은 깊게, 코딩은 가볍게 (0) | 2026.04.04 |
| [Claude] MCP(Model Context Protocol)란? 개념부터 활용 방안까지 정리 (0) | 2026.04.03 |