CLAWIST.
📖 가이드8분 읽기••작성자: Lin

Claude API 파이썬 튜토리얼: Anthropic's API로 AI 앱 만들기

Claude API 파이썬 튜토리얼: Anthropic's API로 AI 앱 만들기

Claude API를 사용하면 Anthropic's의 가장 강력한 AI 모델에 직접 접근할 수 있습니다. ChatGPT의 브라우저 인터페이스와 달리, API를 통해 맞춤형 애플리케이션을 만들고, 워크플로를 자동화하며, 기존 시스템에 AI를 통합할 수 있습니다.

이 튜토리얼에서는 인증, 기본 메시지 전송, 스트리밍 응답, 도구 사용, 그리고 안정적인 AI 애플리케이션 구축을 위한 모범 사례까지 처음부터 프로덕션까지 필요한 모든 내용을 다룹니다.

튜토리얼을 마치면 일반적인 사용 사례에 대한 동작하는 파이썬 코드를 갖게 되고, 필요에 맞게 확장하는 방법도 이해하게 될 것입니다.

Claude API 시작하기

API 연동을 위한 Python 코드 Claude API 개발을 위한 파이썬 환경 설정

먼저 API 키를 발급받고 환경을 설정하세요.

API 키 발급받기:

  1. 계정 만들기: console.anthropic.com
  2. API Keys로 이동
  3. 새 키를 생성하고 안전하게 보관하세요

공식 SDK 설치 (PyPI 패키지):

pip install anthropic

API 키 설정:

export ANTHROPIC_API_KEY="sk-ant-..."

import os
os.environ["ANTHROPIC_API_KEY"] = "sk-ant-..."

첫 번째 API 호출:

from anthropic import Anthropic

client = Anthropic()

message = client.messages.create(
    model="claude-sonnet-4-20250514",
    max_tokens=1024,
    messages=[
        {"role": "user", "content": "Hello, Claude!"}
    ]
)

print(message.content[0].text)

이게 전부입니다. 이제 파이썬에서 Claude를 직접 호출하고 있습니다.

Messages API 이해하기

API 연동 패턴 Messages API는 Claude와 상호작용하는 핵심 인터페이스입니다

Messages API는 Claude와의 모든 대화를 처리합니다. 구조는 다음과 같습니다:

기본 메시지 구조:

response = client.messages.create(
    model="claude-sonnet-4-20250514",  # Model selection
    max_tokens=1024,                    # Maximum response length
    system="You are a helpful coding assistant.",  # System prompt
    messages=[
        {"role": "user", "content": "Explain Python decorators"},
        {"role": "assistant", "content": "Decorators are..."},
        {"role": "user", "content": "Show me an example"}
    ]
)

사용 가능한 모델 (최신 정보는 Anthropic 문서 를 참조하세요):

  • claude-opus-4-20250514 - 가장 뛰어난 성능, 복잡한 작업에 적합
  • claude-sonnet-4-20250514 - 성능과 비용의 균형
  • claude-haiku-3-20250514 - 가장 빠르고 저렴함

주요 매개변수:

  • model - 사용할 Claude 버전
  • max_tokens - 최대 응답 토큰 수 (필수)
  • system - 동작 설정을 위한 시스템 프롬프트
  • messages - 대화 기록
  • temperature - 무작위성 (0-1, 기본값은 모델에 따라 다름)
  • stop_sequences - 생성을 중단시키는 문자열

응답 처리하기:

response = client.messages.create(...)

text = response.content[0].text

print(f"Input tokens: {response.usage.input_tokens}")
print(f"Output tokens: {response.usage.output_tokens}")

print(f"Stop reason: {response.stop_reason}")

스트리밍 응답

AI 자동화 대시보드 실시간 애플리케이션에서 더 나은 UX를 위한 응답 스트리밍

긴 응답의 경우, 스트리밍을 사용하면 텍스트가 생성되는 대로 보여주어 더 나은 사용자 경험을 제공합니다.

기본 스트리밍:

with client.messages.stream(
    model="claude-sonnet-4-20250514",
    max_tokens=1024,
    messages=[{"role": "user", "content": "Write a short story"}]
) as stream:
    for text in stream.text_stream:
        print(text, end="", flush=True)

이벤트 기반 스트리밍:

with client.messages.stream(
    model="claude-sonnet-4-20250514",
    max_tokens=1024,
    messages=[{"role": "user", "content": "Explain machine learning"}]
) as stream:
    for event in stream:
        if event.type == "content_block_delta":
            print(event.delta.text, end="")
        elif event.type == "message_stop":
            print("\n[Complete]")

비동기 스트리밍 (웹 앱용):

import asyncio
from anthropic import AsyncAnthropic

async_client = AsyncAnthropic()

async def stream_response(prompt: str):
    async with async_client.messages.stream(
        model="claude-sonnet-4-20250514",
        max_tokens=1024,
        messages=[{"role": "user", "content": prompt}]
    ) as stream:
        async for text in stream.text_stream:
            yield text

async def main():
    async for chunk in stream_response("Tell me a joke"):
        print(chunk, end="")

asyncio.run(main())

도구 사용 (함수 호출)

도구를 위한 API 아키텍처 Claude가 여러분의 함수를 호출할 수 있도록 하기

도구 사용을 통해 Claude는 Python 함수를 호출하여 외부 데이터에 접근하거나 작업을 수행할 수 있습니다.

도구 정의하기:

tools = [
    {
        "name": "get_weather",
        "description": "Get current weather for a location",
        "input_schema": {
            "type": "object",
            "properties": {
                "location": {
                    "type": "string",
                    "description": "City and country, e.g. London, UK"
                },
                "unit": {
                    "type": "string",
                    "enum": ["celsius", "fahrenheit"],
                    "description": "Temperature unit"
                }
            },
            "required": ["location"]
        }
    }
]

도구 호출 처리하기:

def get_weather(location: str, unit: str = "celsius") -> dict:
    # Your actual weather API call here
    return {"temp": 22, "condition": "sunny", "location": location}

response = client.messages.create(
    model="claude-sonnet-4-20250514",
    max_tokens=1024,
    tools=tools,
    messages=[{"role": "user", "content": "What's the weather in Tokyo?"}]
)

if response.stop_reason == "tool_use":
    tool_use = response.content[1]  # Tool call is second content block
    tool_name = tool_use.name
    tool_input = tool_use.input
    
    # Execute the function
    if tool_name == "get_weather":
        result = get_weather(**tool_input)
    
    # Send result back to Claude
    final_response = client.messages.create(
        model="claude-sonnet-4-20250514",
        max_tokens=1024,
        tools=tools,
        messages=[
            {"role": "user", "content": "What's the weather in Tokyo?"},
            {"role": "assistant", "content": response.content},
            {
                "role": "user",
                "content": [
                    {
                        "type": "tool_result",
                        "tool_use_id": tool_use.id,
                        "content": str(result)
                    }
                ]
            }
        ]
    )
    
    print(final_response.content[0].text)

재사용 가능한 클라이언트 만들기

API 클라이언트를 위한 Python 클래스 구조 프로덕션 환경에서 사용할 유지보수가 쉬운 API 래퍼 만들기

프로덕션 애플리케이션에서는 API를 재사용 가능한 클래스로 감싸는 것이 좋습니다:

from anthropic import Anthropic
from typing import Generator, Optional
import json

class ClaudeClient:
    def __init__(
        self, 
        model: str = "claude-sonnet-4-20250514",
        system_prompt: Optional[str] = None
    ):
        self.client = Anthropic()
        self.model = model
        self.system_prompt = system_prompt
        self.conversation: list = []
    
    def chat(self, message: str, max_tokens: int = 1024) -> str:
        """Send a message and get a response."""
        self.conversation.append({"role": "user", "content": message})
        
        response = self.client.messages.create(
            model=self.model,
            max_tokens=max_tokens,
            system=self.system_prompt or "",
            messages=self.conversation
        )
        
        assistant_message = response.content[0].text
        self.conversation.append({
            "role": "assistant", 
            "content": assistant_message
        })
        
        return assistant_message
    
    def stream_chat(self, message: str) -> Generator[str, None, None]:
        """Stream a response for real-time display."""
        self.conversation.append({"role": "user", "content": message})
        
        full_response = ""
        with self.client.messages.stream(
            model=self.model,
            max_tokens=1024,
            system=self.system_prompt or "",
            messages=self.conversation
        ) as stream:
            for text in stream.text_stream:
                full_response += text
                yield text
        
        self.conversation.append({
            "role": "assistant",
            "content": full_response
        })
    
    def clear_history(self):
        """Reset conversation history."""
        self.conversation = []

claude = ClaudeClient(system_prompt="You are a Python expert.")
print(claude.chat("What's the best way to handle exceptions?"))
print(claude.chat("Show me an example"))  # Has context from previous message

오류 처리 및 요청 제한

오류 처리 코드 패턴 프로덕션 환경에서 API 오류를 안정적으로 처리하기

프로덕션 애플리케이션에는 견고한 오류 처리가 필요합니다:

from anthropic import (
    Anthropic,
    APIError,
    RateLimitError,
    APIConnectionError
)
import time

def call_with_retry(
    client: Anthropic,
    messages: list,
    max_retries: int = 3
) -> str:
    for attempt in range(max_retries):
        try:
            response = client.messages.create(
                model="claude-sonnet-4-20250514",
                max_tokens=1024,
                messages=messages
            )
            return response.content[0].text
            
        except RateLimitError as e:
            wait_time = 2 ** attempt  # Exponential backoff
            print(f"Rate limited. Waiting {wait_time}s...")
            time.sleep(wait_time)
            
        except APIConnectionError as e:
            print(f"Connection error: {e}")
            time.sleep(1)
            
        except APIError as e:
            print(f"API error: {e}")
            raise
    
    raise Exception("Max retries exceeded")

요청 제한 가이드라인:

  • 지수 백오프를 구현하세요
  • 가능하면 응답을 캐시하세요
  • 대량 작업에는 배치 처리를 사용하세요
  • Anthropic 콘솔에서 사용량을 모니터링하세요

결론

Claude API 개발 완료 프로덕션 AI 애플리케이션을 구축할 준비가 되었습니다

Claude API는 채팅 인터페이스에서 제공되는 것 이상의 가능성을 열어줍니다. 이제 맞춤형 AI 애플리케이션을 구축하고, 워크플로를 자동화하며, Claude를 기존 시스템에 통합할 수 있습니다.

핵심 요약:

  • 모든 상호작용에 Messages API를 사용하세요
  • 더 나은 UX를 위해 응답을 스트리밍하세요
  • 외부 기능을 위해 도구를 구현하세요
  • 재시도 로직으로 오류를 처리하세요
  • 프로덕션을 위해 재사용 가능한 클라이언트를 구축하세요

계속 학습하기:

간단한 사용 사례로 시작하여 반복적으로 개선하세요. API는 여러분이 구축하는 어떤 것이든 지원할 수 있을 만큼 유연합니다.

자주 묻는 질문

Claude API 자주 묻는 질문 Claude API에 대해 자주 묻는 질문

Claude API 비용은 얼마인가요?

요금은 토큰 단위로 부과됩니다. Claude Sonnet: 입력 100만 토큰당 $3, 출력 100만 토큰당 $15. Claude Haiku: 입력 100만 토큰당 $0.25, 출력 100만 토큰당 $1.25. 확인하세요: anthropic.com/pricing 에서 최신 요금을 확인하세요.

Claude API와 OpenClaw의 차이점은 무엇인가요?

Claude API는 Anthropic의 원시 인터페이스입니다. OpenClaw는 Claude(또는 다른 모델) 위에 지속성, 메시징 플랫폼 통합, 도구, 메모리를 추가합니다. 맞춤형 앱에는 API를, 개인 비서 사용 사례에는 OpenClaw를 사용하세요.

Claude API를 상업적 프로젝트에 사용할 수 있나요?

네, API는 상업적 사용을 위해 설계되었습니다. 구체적인 지침은 Anthropic의 사용 정책을 확인하세요.

최대 컨텍스트 길이는 얼마인가요?

Claude는 200K 토큰의 컨텍스트를 지원합니다. 대부분의 애플리케이션에는 충분하고도 남습니다. 비용 효율성을 위해 컨텍스트를 신중하게 관리하세요.

API 비용을 줄이려면 어떻게 해야 하나요?

간단한 작업에는 Haiku를 사용하고, 응답을 캐시하고, 긴 대화에는 대화 요약을 구현하고, 유사한 요청을 함께 배치 처리하세요.