Source: https://aiprimetech.io/ko/learn/anthropic-python-sdk/ [홈](/ko/) / [학습](/ko/learn/) / Anthropic Python SDK: 설치, base_url 설정, 스트리밍 및 오류 처리 # Anthropic Python SDK: 설치, base_url 설정, 스트리밍 및 오류 처리 이 anthropic 패키지는 Claude API용 Anthropic 공식 Python 클라이언트입니다. 인증, 재시도, 스트리밍 및 타입별 오류를 처리하며, Anthropic 호환 엔드포인트에서도 변경 없이 작동합니다. 다음을 설정하세요: base_url (또는 ANTHROPIC_BASE_URL). 나머지 코드는 그대로 유지됩니다. ## 설치 터미널복사 ``` pip install anthropic ``` 1.x 릴리스는 다음 환경에서 실행됩니다: httpx2 그리고 Python 3.10 이상이 필요합니다. 자체 HTTP 클라이언트를 전달하는 경우 SDK의 다음 항목을 사용하세요: DefaultHttpxClient 그러면 기본 타임아웃과 연결 한도가 유지됩니다. ## 클라이언트 생성 app.py복사 ``` 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 ``` ## 메시지 보내기 app.py복사 ``` 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 report ``` content 는 블록(텍스트, 사고, 도구 사용)의 목록이므로 다음을 확인하세요: block.type 다음을 읽는 대신 content[0].text 무작정 읽지 마세요. ## 응답 스트리밍 stream.py복사 ``` 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) 는 헬퍼가 필요하지 않을 때 원시 이벤트 이터레이터를 제공합니다. ## 비동기 클라이언트 async_app.py복사 ``` 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 응답을 재시도합니다. 타임아웃도 재시도하므로 최악의 경우 실제 경과 시간은 타임아웃에 시도 횟수를 곱한 값입니다. app.py복사 ``` 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 | 예, 또는 스트리밍 사용 errors.py복사 ``` 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 | 잔액 없음 | [충전](/ko/topup/) 모델 측 오류에 대한 자세한 내용: [Claude API 오류 가이드](/ko/learn/claude-api-errors-troubleshooting/). ## 자주 묻는 질문 Anthropic Python SDK는 어떻게 설치하나요? pip install anthropic을 실행하세요. 1.x 버전은 Python 3.10 이상이 필요합니다. Anthropic Python SDK에서 사용자 지정 기본 URL은 어떻게 설정하나요? anthropic.Anthropic()에 base_url을 전달하거나 ANTHROPIC_BASE_URL을 설정하세요. 호스트 루트를 사용하세요. SDK가 /v1/messages를 추가합니다. 기본 타임아웃과 재시도 횟수는 어떻게 되나요? 요청당 10분이며, 연결 오류, 408, 409, 429 및 5xx에 대해 지수 백오프를 적용하여 2회 재시도합니다. Python SDK에서 스트리밍은 어떻게 사용하나요? with client.messages.stream(...) as stream:을 사용하고 stream.text_stream을 순회하세요. stream.get_final_message()는 전체 메시지를 반환합니다. 몇 분 만에 Claude 사용 시작하기 API 키를 발급받으세요 — Anthropic 계정이나 대기자 명단 등록이 필요하지 않습니다.[API 키 발급받기](/register) AI Prime Tech는 독립적인 API 게이트웨이입니다. Anthropic과 제휴 관계가 없으며, Anthropic의 보증을 받거나 Anthropic의 리셀러로 활동하지 않습니다. Claude 및 관련 모델 이름은 각 소유자의 상표입니다. ## 더 많은 Claude API 가이드 [Claude API 키 발급 방법](/ko/learn/how-to-get-a-claude-api-key/)[Claude API 요금 해설](/ko/learn/claude-api-pricing-explained/)[Claude API를 가장 저렴하게 사용하는 방법](/ko/learn/cheapest-way-to-use-claude-api/)[Claude API로 Cursor 무제한 사용](/learn/use-claude-api-with-cursor/)[Claude Code 무제한 이용](/ko/learn/use-claude-api-with-claude-code/)[Claude API 게이트웨이와 Anthropic 직접 이용 비교](/ko/learn/claude-api-vs-anthropic-direct/)[OpenAI 호환 API를 통해 Claude 사용하기](/ko/learn/openai-compatible-claude-api/)[Claude 모델 해설: Claude Opus, Sonnet, Haiku, Fable 비교 — 모든 Claude API 모델, Anthropic 모델 이름 및 가격 (2026)](/ko/learn/claude-api-models-compared/)[암호화폐로 Claude API 요금 결제하기](/ko/learn/claude-api-with-crypto-payment/)[대기 명단 없이 Claude API 이용하기](/ko/learn/claude-api-without-waitlist/)[Claude 토큰 사용량을 줄이는 방법](/ko/learn/how-to-reduce-claude-token-usage/)[Claude API로 Cline 무제한 사용](/ko/learn/use-claude-api-with-cline/)[Claude API로 Roo Code 무제한 사용](/ko/learn/use-claude-api-with-roo-code/)[JetBrains IDE에서 Claude 무제한 사용](/ko/learn/use-claude-api-with-jetbrains/)[Claude API로 Aider 무제한 사용하기](/ko/learn/use-claude-api-with-aider/)[VS Code에서 Claude 무제한 사용](/ko/learn/use-claude-api-with-vscode/)[Claude용 OpenCode 구성: opencode.json 설정, 모델 및 일반적인 오류](/ko/learn/use-claude-api-with-opencode/)[Claude에서 Hermes 에이전트 무제한 실행하기](/ko/learn/run-hermes-agent-with-claude-api/)[Claude에서 OpenClaw 무제한 실행하기](/ko/learn/run-openclaw-with-claude-api/)[Anthropic 호환 API의 의미](/ko/learn/anthropic-compatible-api/)[Claude Code API 키 — ANTHROPIC_API_KEY: 발급 및 설정 방법과 대신 claude setup-token을 사용해야 하는 경우](/ko/learn/claude-code-api-key-setup/)[Claude Code API 비용 — 요금과 절감 방법](/ko/learn/claude-code-api-costs/)[Claude API 오류 설명: 서버 오류 500, 과부하 529, 사용량 제한 429, 잘못된 요청 400 — 각 오류의 해결 방법](/ko/learn/claude-api-errors-troubleshooting/)[Claude API 크레딧 구매 방법 — 그리고 Claude 크레딧이 어떤 "Claude 계정 구매" 상품보다 나은 이유](/ko/learn/buy-claude-api-credits/)[Claude 무료 API: 무료 Claude API 키가 있나요? 2026년에 실제로 무료인 것은 무엇인가요?](/ko/learn/claude-api-free-trial/)[Claude API와 Claude Pro/Max 구독 — 어떤 것을 선택할까요](/ko/learn/claude-api-vs-subscription/)[Claude에서 Codex CLI 실행하기](/ko/learn/use-claude-api-with-codex/)[Claude를 n8n에 연결하기](/ko/learn/use-claude-api-with-n8n/)[LiteLLM을 Claude로 라우팅하기](/ko/learn/use-claude-api-with-litellm/)[Kilo Code에서 Claude 사용하기](/ko/learn/use-claude-api-with-kilo-code/)[GitHub Copilot에 Claude 연결하기](/ko/learn/use-claude-api-with-github-copilot/)[게이트웨이를 통해 Zed를 Claude에 연결하기](/ko/learn/use-claude-api-with-zed/)[Cherry Studio를 Claude에 연결하기](/ko/learn/use-claude-api-with-cherry-studio/)[LangChain의 ChatAnthropic: 가져오기, base_url, 스트리밍, 도구 및 오류](/ko/learn/use-claude-api-with-langchain/)[Vercel AI SDK로 Claude 사용하기: createAnthropic baseURL, 스트리밍 및 문제 해결](/ko/learn/use-claude-api-with-vercel-ai-sdk/)[Claude로 Factory Droid 실행하기](/ko/learn/use-claude-api-with-factory-droid/)[Claude Code API 이해하기](/ko/learn/claude-code-api/)[애플리케이션에 Claude API 통합하기](/ko/learn/claude-api-integration/)[Claude를 무제한으로 사용하는 방법 — 그리고 "Claude Code 크랙 버전"이 없는 이유](/ko/learn/get-unlimited-claude-usage/)