Python으로 Claude API 사용 방법
Source: Dev.to
위의 링크에 있는 글의 내용을 제공해 주시면, 해당 부분을 한국어로 번역해 드리겠습니다.
파이썬 스크립트가 있습니다. 생각하게 만들고 싶습니다.
그게 전체 전제입니다. 이 튜토리얼에서는 코드를 Claude — Anthropic의 AI 모델 — 에 연결하는 방법을 보여줍니다. 이를 통해 코드가 읽고, 추론하고, 여러분의 프로젝트 안에서 응답할 수 있게 됩니다.
제가 직접 오후 내내 고민해서 만든 내용입니다. 사전 AI 경험은 필요하지 않습니다. 파이썬 함수만이라도 작성해 본 적이 있다면 따라 할 수 있습니다.
시작하기 전에
두 가지를 미리 알아두세요.
-
API는 비용이 듭니다.
많이는 아니지만 — $5면 몇 주간 일반 사용이 가능합니다 — 하지만 Claude.ai 채팅 인터페이스처럼 무료는 아닙니다. 크레딧을 추가하려면 at 에 가야 합니다. -
Python 3.9 이상이 필요합니다.
버전을 확인하세요:python --version3.9보다 낮으면 at 에서 업데이트하세요.
Windows에서는 설치 중 “Add Python to PATH” 를 반드시 체크하세요; 이를 건너뛰면 모든 것이 깨집니다.
설정
폴더를 만들고, 가상 환경을 설정한 뒤 SDK를 설치합니다.
mkdir claude-project
cd claude-project
python -m venv venv
환경을 활성화합니다:
# macOS / Linux
source venv/bin/activate
# Windows
venv\Scripts\activate
터미널 프롬프트가 이제 (venv) 로 시작해야 합니다. 이것이 활성화된 것을 확인하는 방법입니다. venv가 활성화되지 않은 상태에서 패키지를 설치하면 잘못된 위치에 설치됩니다.
pip install anthropic python-dotenv
Your API Key
-
Go to , create an account, and generate a key under API Keys.
-
프로젝트 폴더에
.env파일을 만들어 저장합니다:ANTHROPIC_API_KEY=your-key-here -
해당 파일을 버전 관리에서 제외합니다:
echo .env > .gitignore
Why? 공개된 API 키는 금방 발견되어 사용되고, 몇 시간 안에 여러분에게 비용이 청구됩니다.
Source: …
첫 번째 호출
파이썬에서 Claude와 대화하는 모습은 다음과 같습니다:
from dotenv import load_dotenv
from anthropic import Anthropic
load_dotenv()
client = Anthropic()
message = client.messages.create(
model="claude-sonnet-4-6",
max_tokens=1024,
messages=[
{
"role": "user",
"content": "What is a REST API?"
}
]
)
print(message.content[0].text)
스크립트를 실행하면 Claude가 터미널에 답변을 출력합니다.
이 호출에 대해 이해해야 할 세 가지
| 매개변수 | 의미 |
|---|---|
model | 사용 중인 Claude 버전. claude-sonnet-4-6은 대부분의 사용 사례에 기본값 – 빠르고 능력 있음. |
max_tokens | Claude 응답의 최대 길이. 너무 낮게 설정하면 답변이 문장 중간에 잘립니다. 1024는 안전한 시작점. |
messages | 대화의 턴 목록. 각 턴은 role을 가짐 (user는 사용자의 메시지, assistant는 Claude). |
What Comes Back
The response object holds more than just text:
print(message.content[0].text) # Claude's response
print(message.stop_reason) # Why it stopped — usually "end_turn"
print(message.usage.input_tokens) # Tokens in your message
print(message.usage.output_tokens) # Tokens in Claude's reply
Tokens are roughly equivalent to words. Watching them matters because that’s what you’re paying for.
Claude에게 역할 부여하기
기본적으로 Claude는 일반적인 어시스턴트입니다. 시스템 프롬프트가 이를 변경합니다. 대화가 시작되기 전에 제공하는 브리핑이라고 생각하면 됩니다:
message = client.messages.create(
model="claude-sonnet-4-6",
max_tokens=1024,
system="You are a Python code reviewer. Be direct. Point out issues first, then explain why.",
messages=[
{
"role": "user",
"content": "Review this: for i in range(len(my_list)): print(my_list[i])"
}
]
)
print(message.content[0].text)
같은 모델이지만 완전히 다른 동작을 보입니다. 시스템 프롬프트가 실제 제어가 대부분 이루어지는 곳입니다.
Conversations
The API has no memory. Every call starts fresh unless you pass the history yourself.
from dotenv import load_dotenv
from anthropic import Anthropic
load_dotenv()
client = Anthropic()
history = []
def chat(message: str) -> str:
# Add the user message to the history
history.append({"role": "user", "content": message})
response = client.messages.create(
model="claude-sonnet-4-6",
max_tokens=1024,
system="You are a helpful programming assistant.",
messages=history
)
# Extract Claude's reply and add it to the history
reply = response.content[0].text
history.append({"role": "assistant", "content": reply})
return reply
print(chat("What is a decorator in Python?"))
print(chat("Show me a real example."))
print(chat("How would that work in Flask?"))
Each call passes the full history. Claude reads it, understands the context, and continues the thread.
Common mistake: 사용자의 메시지는 추가했지만 Claude의 답변을 추가하는 것을 잊는 경우. 이렇게 하면 다음 요청이 컨텍스트 없이 도착하고, Claude는 대화가 전혀 없었던 것처럼 답변합니다.
스트리밍
전체 응답을 기다렸다가 출력하는 방식은 스크립트에서는 괜찮지만, 사용자와 직접 상호작용하는 경우에는 스트리밍이 훨씬 좋습니다.
from dotenv import load_dotenv
from anthropic import Anthropic
load_dotenv()
client = Anthropic()
with client.messages.stream(
model="claude-sonnet-4-6",
max_tokens=1024,
messages=[
{"role": "user", "content": "Explain recursion simply."}
]
) as stream:
for text in stream.text_stream:
print(text, end="", flush=True)
텍스트가 토큰 단위로 나타나며, 실시간 대화처럼 느껴집니다.
실시간 스트리밍
대기하지 않고 Claude가 생성하는 대로 단어가 나타납니다 — Claude.ai 인터페이스에서 경험하는 것과 동일합니다.
실제 사용 사례
보관할 가치가 있는 함수입니다. 전달하는 모든 텍스트를 요약합니다:
from dotenv import load_dotenv
from anthropic import Anthropic
load_dotenv()
client = Anthropic()
def summarize(text: str, sentences: int = 3) -> str:
response = client.messages.create(
model="claude-sonnet-4-6",
max_tokens=512,
system=f"Summarize the following text in {sentences} sentences. Return only the summary.",
messages=[{"role": "user", "content": text}]
)
return response.content[0].text
article = """
The James Webb Space Telescope has captured the deepest infrared image
of the universe ever taken. The image covers a patch of sky approximately
the size of a grain of sand held at arm's length. It contains thousands
of galaxies, some of which formed less than a billion years after the
Big Bang. Scientists believe this data will reshape our understanding
of how the earliest galaxies formed and evolved.
"""
print(summarize(article, sentences=2))
시스템 프롬프트를 바꾸면 번역기, 분류기, 데이터 추출기로 변신합니다. 패턴은 언제나 동일합니다.
오류 처리
네트워크는 실패할 수 있습니다. 속도 제한이 발생합니다. 호출을 감싸세요:
from dotenv import load_dotenv
from anthropic import Anthropic, APIError, RateLimitError, APIConnectionError
load_dotenv()
client = Anthropic()
def ask(question: str) -> str:
try:
response = client.messages.create(
model="claude-sonnet-4-6",
max_tokens=1024,
messages=[{"role": "user", "content": question}]
)
return response.content[0].text
except RateLimitError:
return "Rate limit reached. Wait a moment and try again."
except APIConnectionError:
return "Connection failed. Check your internet."
except APIError as e:
return f"API error {e.status_code}."
모델 선택
| Model | 사용 상황 |
|---|---|
claude-sonnet-4-6 | 대부분의 경우. 빠르고, 능력 있으며, 비용‑효율적 |
claude-opus-4-6 | 깊은 추론이 필요한 어려운 문제 |
claude-haiku-4-5-20251001 | 대량, 간단한 작업, 가장 낮은 비용 |
먼저 Sonnet을 사용하세요. 이유가 있다면 전환하세요.
주의할 점
- API는 비용이 듭니다. Claude.ai의 웹 UI는 무료입니다. 시작하기 전에 크레딧을 충전하세요.
load_dotenv()는 스스로 호출되지 않습니다. 키가 로드되지 않는다면 이것이 원인일 가능성이 높습니다.max_tokens값이 너무 낮으면 응답이 중간에 끊깁니다. 답변이 불완전하게 느껴지면 값을 높이세요.- 대화 기록에는 양쪽 모두 필요합니다: 사용자 메시지 와 Claude의 답변. 하나라도 빠지면 컨텍스트가 깨집니다.
- macOS/Linux에서는
python이 Python 2를 가리킬 수 있습니다. 예상대로 동작하지 않으면python3를 사용하세요.
What’s Next
The foundation is here. Where it goes depends on what you’re building.
- Tool use lets Claude call your own Python functions — useful when you want it to interact with real data or external services.
- Vision lets you send images alongside text, so Claude can read screenshots, diagrams, or documents.
- Async support via
AsyncAnthropicis worth exploring if you’re handling multiple requests at once.
The full documentation is at .
열 줄 안에 전체 코드
from dotenv import load_dotenv
from anthropic import Anthropic
load_dotenv()
client = Anthropic()
response = client.messages.create(
model="claude-sonnet-4-6",
max_tokens=1024,
messages=[{"role": "user", "content": "Your message here."}]
)
print(response.content[0].text)