Claude API Python Eğitimi 2026 | APIMaster.ai
Python ile Claude API nasıl kullanılır? APIMaster.ai üzerinden Anthropic SDK ve OpenAI uyumlu istemci kullanarak sohbet, akış, görüntü işleme ve fonksiyon çağırma örnekleri.
Claude API Python Eğitimi
Bu kılavuz, Claude API'yi Python'da hem yerel Anthropic SDK hem de OpenAI uyumlu istemci ile kullanmayı kapsar. Tüm örnekler APIMaster.ai ile çalışır—kendi temel URL'nizi ve API anahtarınızı kullanın.
Kurulum
pip install anthropic # Native Anthropic SDK
pip install openai # OpenAI-compatible (optional)
Temel Kurulum
import anthropic
client = anthropic.Anthropic(
api_key="YOUR_APIMASTER_KEY",
base_url="https://apimaster.ai", # No /v1 for Anthropic SDK
)
Ya da OpenAI SDK ile (zaten OpenAI kullanıyorsanız daha kolay):
from openai import OpenAI
client = OpenAI(
api_key="YOUR_APIMASTER_KEY",
base_url="https://apimaster.ai/v1",
)
İlk Claude API Çağrınız
import anthropic
client = anthropic.Anthropic(
api_key="YOUR_APIMASTER_KEY",
base_url="https://apimaster.ai",
)
message = client.messages.create(
model="claude-sonnet-4-6",
max_tokens=1024,
messages=[
{"role": "user", "content": "Explain the difference between lists and tuples in Python."}
],
)
print(message.content[0].text)
Sistem İstemleri
response = client.messages.create(
model="claude-sonnet-4-6",
max_tokens=512,
system="You are a senior Python engineer. Be concise and use code examples.",
messages=[
{"role": "user", "content": "What's the fastest way to flatten a nested list?"}
],
)
print(response.content[0].text)
Çoklu Dönüşlü Sohbet
conversation = []
def chat(user_message):
conversation.append({"role": "user", "content": user_message})
response = client.messages.create(
model="claude-sonnet-4-6",
max_tokens=1024,
messages=conversation,
)
assistant_message = response.content[0].text
conversation.append({"role": "assistant", "content": assistant_message})
return assistant_message
print(chat("What is a decorator in Python?"))
print(chat("Can you show me a practical example?"))
Akış Yanıtları
Akış, token'lar üretildikçe döndürür—uzun çıktılar için daha iyi kullanıcı deneyimi:
with client.messages.stream(
model="claude-sonnet-4-6",
max_tokens=1024,
messages=[{"role": "user", "content": "Write a Python web scraper using requests and BeautifulSoup."}],
) as stream:
for text in stream.text_stream:
print(text, end="", flush=True)
print() # newline at end
Görüntü İşleme: Resimleri Analiz Etme
Claude Sonnet ve Opus, görüntü girdilerini destekler (base64 veya URL):
import base64
with open("chart.png", "rb") as f:
image_data = base64.standard_b64encode(f.read()).decode("utf-8")
response = client.messages.create(
model="claude-sonnet-4-6",
max_tokens=512,
messages=[
{
"role": "user",
"content": [
{
"type": "image",
"source": {
"type": "base64",
"media_type": "image/png",
"data": image_data,
},
},
{"type": "text", "text": "Summarize what this chart shows."},
],
}
],
)
print(response.content[0].text)
Araç Kullanımı (Fonksiyon Çağırma)
tools = [
{
"name": "get_weather",
"description": "Get current weather for a city",
"input_schema": {
"type": "object",
"properties": {
"city": {"type": "string", "description": "City name"},
},
"required": ["city"],
},
}
]
response = client.messages.create(
model="claude-sonnet-4-6",
max_tokens=256,
tools=tools,
messages=[{"role": "user", "content": "What's the weather in Tokyo?"}],
)
# Check if Claude wants to call a tool
if response.stop_reason == "tool_use":
tool_call = next(b for b in response.content if b.type == "tool_use")
print(f"Tool: {tool_call.name}, Input: {tool_call.input}")
Asenkron Kullanım
import asyncio
import anthropic
async def main():
client = anthropic.AsyncAnthropic(
api_key="YOUR_APIMASTER_KEY",
base_url="https://apimaster.ai",
)
response = await client.messages.create(
model="claude-sonnet-4-6",
max_tokens=256,
messages=[{"role": "user", "content": "Hello!"}],
)
print(response.content[0].text)
asyncio.run(main())
Hata Yönetimi
import anthropic
try:
response = client.messages.create(
model="claude-sonnet-4-6",
max_tokens=256,
messages=[{"role": "user", "content": "Hello"}],
)
except anthropic.AuthenticationError:
print("Invalid API key")
except anthropic.RateLimitError:
print("Rate limit—add retry logic")
except anthropic.APIStatusError as e:
print(f"API error {e.status_code}: {e.message}")
Python Projeleri İçin Doğru Claude Modelini Seçme
| Görev | Model | Neden |
|---|---|---|
| Sohbet robotları, Soru-Cevap | claude-haiku-4-5 | Hızlı + ucuz |
| Kod üretimi | claude-sonnet-4-6 | En iyi denge |
| Karmaşık akıl yürütme | claude-opus-4-8 | En yüksek doğruluk |
| Belge analizi | claude-sonnet-4-6 | 1M bağlam |
Claude API Erişimi Alın
Sıkça Sorulan Sorular
Claude API Python kütüphanesini nasıl kurarım?
Resmi SDK için pip install anthropic komutunu çalıştırın veya Claude modelleriyle APIMaster'ın OpenAI uyumlu uç noktasını kullanmak için pip install openai komutunu çalıştırın.
Claude API için hangi Python SDK'sını kullanmalıyım?
anthropic SDK resmi seçenektir ve tüm Claude'a özgü özellikleri (araç kullanımı, görüntü işleme, akış) destekler. openai SDK, APIMaster'ın uyumluluk katmanı üzerinden çalışır—zaten OpenAI kullanıyorsanız ve model değiştirmek istiyorsanız kullanışlıdır.
Python'da Claude API yanıtlarını nasıl akış halinde alırım?
openai kütüphanesiyle stream=True parametresini iletin veya anthropic SDK ile client.messages.stream() kullanın. Yukarıdaki akış örneğine bakın.
Claude API fonksiyon çağırmayı (araç kullanımı) destekliyor mu?
Evet—Claude, standart tools parametresini kullanarak hem yerel Anthropic SDK'da hem de APIMaster'ın OpenAI uyumlu uç noktası aracılığıyla araç kullanımını destekler.
Python'da Claude için maksimum bağlam penceresi nedir?
Claude Sonnet 4.6 ve Opus 4.8, her biri 1M token destekler. Çok uzun belgeleri doğrudan messages dizisine iletebilirsiniz.
APIMaster.ai'ye kaydolun ile birleşik bir uç nokta üzerinden Claude API erişimi elde edin, canlı fiyatlandırma ve parmak izi doğrulama verileriyle.
Ayrıca bakınız: Claude API Fiyatlandırması · Claude API Anahtarı Nasıl Alınır