문서/Claude/Claude API 완벽 가이드

Claude API 완벽 가이드

Anthropic Claude API를 활용한 애플리케이션 개발

Claude API 완벽 가이드

Anthropic의 Claude API를 사용하여 강력한 AI 애플리케이션을 구축하는 방법을 알아봅니다.

API 시작하기

1. API 키 발급

  1. console.anthropic.com 접속
  2. 계정 생성 또는 로그인
  3. API Keys에서 새 키 생성
  4. 안전하게 보관

2. SDK 설치

# Python
pip install anthropic

# Node.js
npm install @anthropic-ai/sdk

기본 사용법

Python

from anthropic import Anthropic

client = Anthropic()

message = client.messages.create(
    model="claude-3-5-sonnet-20241022",
    max_tokens=1024,
    system="당신은 친절한 AI 어시스턴트입니다.",
    messages=[
        {"role": "user", "content": "안녕하세요!"}
    ]
)

print(message.content[0].text)

TypeScript

import Anthropic from '@anthropic-ai/sdk';

const anthropic = new Anthropic();

async function chat(userMessage: string) {
  const message = await anthropic.messages.create({
    model: "claude-3-5-sonnet-20241022",
    max_tokens: 1024,
    messages: [
      { role: "user", content: userMessage }
    ],
  });

  return message.content[0].text;
}

모델 선택 가이드

모델특징가격권장 사용
claude-3-5-sonnet속도와 성능 균형중간일반 작업
claude-3-opus최고 성능높음복잡한 분석
claude-3-haiku초고속낮음대량 처리

스트리밍

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)

Tool Use (Function Calling)

tools = [{
    "name": "get_weather",
    "description": "지정된 위치의 현재 날씨를 가져옵니다",
    "input_schema": {
        "type": "object",
        "properties": {
            "location": {
                "type": "string",
                "description": "도시명"
            }
        },
        "required": ["location"]
    }
}]

response = client.messages.create(
    model="claude-3-5-sonnet-20241022",
    max_tokens=1024,
    tools=tools,
    messages=[{"role": "user", "content": "서울 날씨 알려줘"}]
)

# tool_use 처리
for block in response.content:
    if block.type == "tool_use":
        tool_name = block.name
        tool_input = block.input
        # 실제 함수 실행 후 결과 전달

Vision (이미지 분석)

import base64

# 이미지를 base64로 인코딩
with open("image.png", "rb") as f:
    image_data = base64.standard_b64encode(f.read()).decode("utf-8")

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/png",
                    "data": image_data,
                }
            },
            {
                "type": "text",
                "text": "이 이미지를 설명해주세요"
            }
        ]
    }]
)

Extended Thinking (심층 추론)

# Claude 3.5 Sonnet v2+에서 지원
response = client.messages.create(
    model="claude-3-5-sonnet-20241022",
    max_tokens=16000,
    thinking={
        "type": "enabled",
        "budget_tokens": 10000
    },
    messages=[{"role": "user", "content": "복잡한 수학 문제..."}]
)

# thinking 블록과 답변 블록 분리
for block in response.content:
    if block.type == "thinking":
        print("추론 과정:", block.thinking)
    elif block.type == "text":
        print("답변:", block.text)

에러 처리

from anthropic import APIError, RateLimitError

try:
    response = client.messages.create(...)
except RateLimitError:
    print("요청 한도 초과")
    time.sleep(60)
except APIError as e:
    print(f"API 오류: {e.status_code} - {e.message}")
Claude API 완벽 가이드 - 문서 - SpacebarCorp AI Academy | SpacebarCorp