OpenAI API, ChatGPT, GPT-4, DALL-E ve Whisper gibi güçlü AI modellerine programatik erişim sağlar. Bu kapsamlı rehberde, API entegrasyonunun tüm yönlerini ele alacağız.
API Erişimi ve Kurulum
API Key Alma
- platform.openai.com adresine gidin
- Hesap oluşturun veya giriş yapın
- API Keys bölümünden yeni key oluşturun
- Key'i güvenli bir yerde saklayın (tekrar gösterilmez)
Kurulum (Python)
pip install openai # .env dosyası OPENAI_API_KEY=sk-... # Python kodu from openai import OpenAI client = OpenAI() # Otomatik olarak env variable kullanır
Chat Completions API
response = client.chat.completions.create(
model="gpt-4-turbo-preview",
messages=[
{"role": "system", "content": "Sen yardımcı bir asistansın."},
{"role": "user", "content": "Python ile web scraping nasıl yapılır?"}
],
temperature=0.7,
max_tokens=1000
)
print(response.choices[0].message.content)
Önemli Parametreler
- model: gpt-4-turbo-preview, gpt-4, gpt-3.5-turbo
- temperature: 0-2 arası, yaratıcılık seviyesi
- max_tokens: Maksimum çıktı uzunluğu
- top_p: Nucleus sampling
- frequency_penalty: Tekrar önleme
- presence_penalty: Yeni konu teşviki
Streaming Responses
stream = client.chat.completions.create(
model="gpt-4-turbo-preview",
messages=[{"role": "user", "content": "Bir hikaye anlat"}],
stream=True
)
for chunk in stream:
if chunk.choices[0].delta.content:
print(chunk.choices[0].delta.content, end="")
Function Calling
tools = [
{
"type": "function",
"function": {
"name": "get_weather",
"description": "Belirtilen şehrin hava durumunu getirir",
"parameters": {
"type": "object",
"properties": {
"city": {"type": "string", "description": "Şehir adı"}
},
"required": ["city"]
}
}
}
]
response = client.chat.completions.create(
model="gpt-4-turbo-preview",
messages=[{"role": "user", "content": "İstanbul hava durumu nasıl?"}],
tools=tools,
tool_choice="auto"
)
Vision API (GPT-4V)
response = client.chat.completions.create(
model="gpt-4-vision-preview",
messages=[
{
"role": "user",
"content": [
{"type": "text", "text": "Bu resimde ne var?"},
{"type": "image_url", "image_url": {"url": "https://..."}}
]
}
]
)
DALL-E 3 Image Generation
response = client.images.generate(
model="dall-e-3",
prompt="A futuristic city at sunset, cyberpunk style",
size="1024x1024",
quality="hd",
n=1
)
image_url = response.data[0].url
Whisper (Speech-to-Text)
audio_file = open("speech.mp3", "rb")
transcript = client.audio.transcriptions.create(
model="whisper-1",
file=audio_file,
language="tr"
)
print(transcript.text)
Embeddings
response = client.embeddings.create(
model="text-embedding-3-small",
input="OpenAI embeddings örneği"
)
embedding = response.data[0].embedding # 1536 boyutlu vektör
Rate Limiting ve Best Practices
- Exponential backoff ile retry mekanizması
- Request rate limitlerini takip edin (RPM, TPM)
- Batch processing kullanın
- Response caching uygulayın
- Prompt'ları optimize edin (token tasarrufu)
Maliyet Optimizasyonu
- Basit görevler için gpt-3.5-turbo kullanın
- max_tokens'ı sınırlayın
- Gereksiz context'i temizleyin
- Caching stratejileri uygulayın
OpenAI API, AI yeteneklerini uygulamalarınıza entegre etmenin en hızlı yoludur. Doğru kullanımla güçlü ve maliyet-etkin çözümler oluşturabilirsiniz.