
Anthropic Python SDK: 설치, base_url 설정, 스트리밍 및 오류 처리
이 anthropic 패키지는 Claude API용 Anthropic 공식 Python 클라이언트입니다. 인증, 재시도, 스트리밍 및 타입별 오류를 처리하며, Anthropic 호환 엔드포인트에서도 변경 없이 작동합니다. 다음을 설정하세요: base_url (또는 ANTHROPIC_BASE_URL). 나머지 코드는 그대로 유지됩니다.
설치
pip install anthropic1.x 릴리스는 다음 환경에서 실행됩니다: httpx2 그리고 Python 3.10 이상이 필요합니다. 자체 HTTP 클라이언트를 전달하는 경우 SDK의 다음 항목을 사용하세요: DefaultHttpxClient 그러면 기본 타임아웃과 연결 한도가 유지됩니다.
클라이언트 생성
import anthropic
client = anthropic.Anthropic(
api_key="your_key", # default: ANTHROPIC_API_KEY
base_url="https://aiprimetech.io", # default: ANTHROPIC_BASE_URL, else https://api.anthropic.com
)base_url 는 호스트 루트입니다. SDK가 다음 경로를 추가합니다: /v1/messages 자체적으로 추가하므로 https://aiprimetech.io/v1 를 사용하면 다음이 생성됩니다: /v1/v1/messages 및 404 page not found. 두 변수가 모두 환경에 설정되어 있으면 anthropic.Anthropic() 에는 인수가 전혀 필요하지 않습니다:
export ANTHROPIC_API_KEY=your_key
export ANTHROPIC_BASE_URL=https://aiprimetech.io메시지 보내기
message = client.messages.create(
model="claude-sonnet-5",
max_tokens=1024,
messages=[{"role": "user", "content": "Summarise TCP slow start in two sentences."}],
)
for block in message.content:
if block.type == "text":
print(block.text)
print(message.usage.input_tokens, message.usage.output_tokens)
print(message._request_id) # log this with any failure reportcontent 는 블록(텍스트, 사고, 도구 사용)의 목록이므로 다음을 확인하세요: block.type 다음을 읽는 대신 content[0].text 무작정 읽지 마세요.
응답 스트리밍
with client.messages.stream(
model="claude-sonnet-5",
max_tokens=16000,
messages=[{"role": "user", "content": "Write a short story about a lighthouse."}],
) as stream:
for text in stream.text_stream:
print(text, end="", flush=True)
final = stream.get_final_message()입력이 길거나 출력이 길거나 다음 값이 큰 경우에는 스트리밍을 사용하세요: max_tokens: 단일 비스트리밍 요청은 타임아웃 내에 완료되어야 하지만, 스트리밍은 그렇지 않습니다. messages.create(..., stream=True) 는 헬퍼가 필요하지 않을 때 원시 이벤트 이터레이터를 제공합니다.
비동기 클라이언트
import asyncio, anthropic
client = anthropic.AsyncAnthropic(base_url="https://aiprimetech.io")
limit = asyncio.Semaphore(3) # stay within your key's concurrency
async def ask(question: str) -> str:
async with limit:
msg = await client.messages.create(
model="claude-haiku-4-5",
max_tokens=512,
messages=[{"role": "user", "content": question}],
)
return next(b.text for b in msg.content if b.type == "text")
async def main():
answers = await asyncio.gather(*(ask(q) for q in ["What is DNS?", "What is BGP?"]))
print(answers)
asyncio.run(main())세마포어는 중요합니다. 다음을 사용해 수백 개의 요청을 한꺼번에 보내는 것은 asyncio.gather 다음 오류의 가장 흔한 원인입니다: Concurrency limit exceeded Python 클라이언트에서 관찰되는 오류입니다.
시간 제한 및 재시도
기본값: 요청당 10분의 타임아웃과 지수 백오프를 적용한 2회의 자동 재시도입니다. SDK는 연결 오류, 408, 409, 429 및 5xx 응답을 재시도합니다. 타임아웃도 재시도하므로 최악의 경우 실제 경과 시간은 타임아웃에 시도 횟수를 곱한 값입니다.
client = anthropic.Anthropic(base_url="https://aiprimetech.io", timeout=60.0, max_retries=4)
# override for one call only
client.with_options(timeout=300.0).messages.create(
model="claude-opus-5-5",
max_tokens=4000,
messages=[{"role": "user", "content": "Review this design doc..."}],
)오류 처리
| 상태 | 예외 | 재시도 여부 |
|---|---|---|
| 400 | anthropic.BadRequestError | 아니요: 요청을 수정하세요 |
| 401 | anthropic.AuthenticationError | 아니요: 키가 잘못되었거나 누락되었습니다 |
| 403 | anthropic.PermissionDeniedError | 아니요 |
| 404 | anthropic.NotFoundError | 아니요: 모델 ID 또는 URL을 확인하세요 |
| 429 | anthropic.RateLimitError | 예, 잠시 기다린 후 |
| 5xx, 529 과부하 포함 | anthropic.InternalServerError | 예 |
| 네트워크 장애 | anthropic.APIConnectionError | 예 |
| 타임아웃 | anthropic.APITimeoutError | 예, 또는 스트리밍 사용 |
try:
message = client.messages.create(model="claude-sonnet-5", max_tokens=1024,
messages=[{"role": "user", "content": "Hi"}])
except anthropic.NotFoundError as e:
print("Bad model ID or URL:", e.message)
except anthropic.RateLimitError as e:
print("Rate limited, retry after", e.response.headers.get("retry-after"))
except anthropic.APIStatusError as e:
print(e.status_code, e.type, e.message)
except anthropic.APIConnectionError:
print("Network problem")구체적인 예외 클래스부터 처리하고 APIStatusError 는 마지막에 처리하세요. 포괄적인 단일 except 는 재시도할 만한 오류와 코드 변경이 필요한 오류의 차이를 가립니다. e.type 는 API의 오류 유형 문자열을 제공합니다. 예를 들면 rate_limit_error 또는 overloaded_error.
모델 ID
| 모델 ID | 권장 용도 |
|---|---|
claude-sonnet-5 | 코딩과 에이전트 작업의 기본 선택: 빠르고 성능이 뛰어나며 가격은 중간 수준입니다. |
claude-opus-5-5 | 더 어려운 추론, 대규모 리팩터링, 장시간 에이전트 실행. |
claude-fable-5-1 | 성능이 가장 뛰어나고 가격도 가장 높습니다. 가장 어려운 작업에 사용하세요. |
claude-haiku-4-5 | 저렴하고 빠름: 제목, 요약, 분류, 간단한 단계. |
client.models.list() 는 엔드포인트가 제공하는 모델을 반환하므로 사용 전에 ID를 확인할 수 있습니다. ID는 표기된 그대로 사용하세요. 날짜 접미사는 붙이지 마세요.
게이트웨이 문제 해결
| 표시되는 내용 | 원인 | 해결 방법 |
|---|---|---|
NotFoundError 다음으로 바꾸세요: 404 page not found | /v1 에서 base_url | 호스트 루트 사용 |
AuthenticationError | 프로세스에 키가 설정되지 않았거나 공백이 포함된 채 붙여넣어짐 | 출력 len(os.environ["ANTHROPIC_API_KEY"]) |
RateLimitError: Concurrency limit exceeded for user | 동시에 처리 중인 요청이 너무 많음 | 다음 항목: asyncio.Semaphore 위와 같이 |
APITimeoutError 장시간 작업에서 | 비스트리밍 요청이 타임아웃을 초과함 | 스트리밍을 사용하거나 다음 값을 늘리세요: timeout |
InternalServerError: No available accounts | 일시적인 업스트림 용량 문제 | SDK가 재시도하도록 두세요. 다음 값을 늘리세요: max_retries |
Insufficient account balance | 잔액 없음 | 충전 |
모델 측 오류에 대한 자세한 내용: Claude API 오류 가이드.
자주 묻는 질문
Anthropic Python SDK는 어떻게 설치하나요?
Anthropic Python SDK에서 사용자 지정 기본 URL은 어떻게 설정하나요?
기본 타임아웃과 재시도 횟수는 어떻게 되나요?
Python SDK에서 스트리밍은 어떻게 사용하나요?
API 키를 발급받으세요 — Anthropic 계정이나 대기자 명단 등록이 필요하지 않습니다.
API 키 발급받기AI Prime Tech는 독립적인 API 게이트웨이입니다. Anthropic과 제휴 관계가 없으며, Anthropic의 보증을 받거나 Anthropic의 리셀러로 활동하지 않습니다. Claude 및 관련 모델 이름은 각 소유자의 상표입니다.