LLM Integration
LLM Entegrasyonu: AI Model API Rehberi
GPT-4 Turbo, Claude 3.5 Sonnet, Gemini Pro API entegrasyonu. Function calling, embeddings, RAG, streaming ve cost optimization.
🧠LLM Karşılaştırması 2026
Large Language Models (LLM), doğal dil işleme, kod üretme, analiz ve karar verme yetenekleriyle iş süreçlerini dönüştürüyor.
GPT-4 Turbo
• Context: 128K tokens
• Fiyat: $10/1M input, $30/1M output
• Hız: Orta
• Güç: Genel amaçlı, çok yönlü
Claude 3.5 Sonnet
• Context: 200K tokens
• Fiyat: $3/1M input, $15/1M output
• Hız: Hızlı
• Güç: Kod, analiz, uzun dokümana
Gemini Pro 1.5
• Context: 2M tokens (!)
• Fiyat: $1.25/1M input, $5/1M output
• Hız: Orta-Yavaş
• Güç: Çok uzun doküman, video
GPT-4 API Kullanımı
# OpenAI GPT-4 Turbo API
from openai import OpenAI
import json
client = OpenAI(api_key="your-api-key")
# Basit completion
response = client.chat.completions.create(
model="gpt-4-turbo-preview",
messages=[
{
"role": "system",
"content": "Sen bir e-ticaret asistanısın. Müşterilere yardımcı olursun."
},
{
"role": "user",
"content": "Siparişim nerede?"
}
],
temperature=0.7,
max_tokens=500
)
print(response.choices[0].message.content)
# Streaming (gerçek zamanlı yanıt)
stream = client.chat.completions.create(
model="gpt-4-turbo-preview",
messages=[{"role": "user", "content": "Uzun bir makale yaz"}],
stream=True
)
for chunk in stream:
if chunk.choices[0].delta.content is not None:
print(chunk.choices[0].delta.content, end="")
# JSON mode (yapılandırılmış çıktı)
response = client.chat.completions.create(
model="gpt-4-turbo-preview",
messages=[
{
"role": "system",
"content": "Müşteri bilgilerini JSON formatında çıkar"
},
{
"role": "user",
"content": "Adım Ahmet Yılmaz, 05551234567 numaralı telefon, İstanbul'da yaşıyorum"
}
],
response_format={"type": "json_object"}
)
customer_data = json.loads(response.choices[0].message.content)
print(customer_data)
# {"name": "Ahmet Yılmaz", "phone": "05551234567", "city": "İstanbul"}Function Calling
# GPT-4 Function Calling ile araç entegrasyonu
import openai
import requests
# Fonksiyon tanımları
functions = [
{
"name": "get_order_status",
"description": "Sipariş durumunu sorgula",
"parameters": {
"type": "object",
"properties": {
"order_id": {
"type": "string",
"description": "Sipariş numarası (ORD-12345)"
}
},
"required": ["order_id"]
}
},
{
"name": "get_weather",
"description": "Hava durumu bilgisi al",
"parameters": {
"type": "object",
"properties": {
"city": {
"type": "string",
"description": "Şehir adı"
}
},
"required": ["city"]
}
}
]
# Gerçek fonksiyon implementasyonları
def get_order_status(order_id):
# Veritabanından sipariş durumu çek
return {"order_id": order_id, "status": "Kargoda", "tracking": "YK123456"}
def get_weather(city):
# API'den hava durumu al
return {"city": city, "temp": 15, "condition": "Güneşli"}
# GPT-4'e kullanıcı sorusu
messages = [
{"role": "user", "content": "ORD-12345 numaralı siparişim nerede?"}
]
response = client.chat.completions.create(
model="gpt-4-turbo-preview",
messages=messages,
functions=functions,
function_call="auto"
)
# GPT-4 fonksiyon çağırmak istedi mi?
response_message = response.choices[0].message
if response_message.function_call:
function_name = response_message.function_call.name
function_args = json.loads(response_message.function_call.arguments)
# Fonksiyonu çalıştır
if function_name == "get_order_status":
function_response = get_order_status(**function_args)
elif function_name == "get_weather":
function_response = get_weather(**function_args)
# Fonksiyon sonucunu GPT-4'e geri gönder
messages.append(response_message)
messages.append({
"role": "function",
"name": function_name,
"content": json.dumps(function_response)
})
# Final yanıt
second_response = client.chat.completions.create(
model="gpt-4-turbo-preview",
messages=messages
)
print(second_response.choices[0].message.content)
# "ORD-12345 numaralı siparişiniz kargoda. Takip numarası: YK123456"Claude 3.5 Sonnet API
# Anthropic Claude API
import anthropic
client = anthropic.Anthropic(api_key="your-api-key")
# Basit completion
message = client.messages.create(
model="claude-3-5-sonnet-20241022",
max_tokens=1024,
messages=[
{
"role": "user",
"content": "Python'da binary search algoritması yaz"
}
]
)
print(message.content[0].text)
# Streaming
with client.messages.stream(
model="claude-3-5-sonnet-20241022",
max_tokens=1024,
messages=[{"role": "user", "content": "Uzun bir hikaye anlat"}]
) as stream:
for text in stream.text_stream:
print(text, end="", flush=True)
# Tool use (Claude'un function calling'i)
tools = [
{
"name": "get_stock_price",
"description": "Hisse senedi fiyatı sorgula",
"input_schema": {
"type": "object",
"properties": {
"ticker": {
"type": "string",
"description": "Hisse kodu (AAPL, GOOGL, vb.)"
}
},
"required": ["ticker"]
}
}
]
response = client.messages.create(
model="claude-3-5-sonnet-20241022",
max_tokens=1024,
tools=tools,
messages=[{"role": "user", "content": "AAPL hissesinin fiyatı nedir?"}]
)
# Tool kullandı mı?
if response.stop_reason == "tool_use":
tool_use = next(block for block in response.content if block.type == "tool_use")
tool_name = tool_use.name
tool_input = tool_use.input
# Tool'u çalıştır
if tool_name == "get_stock_price":
price = get_stock_price(tool_input["ticker"]) # API'den çek
# Sonucu Claude'a gönder
final_response = client.messages.create(
model="claude-3-5-sonnet-20241022",
max_tokens=1024,
tools=tools,
messages=[
{"role": "user", "content": "AAPL hissesinin fiyatı nedir?"},
{"role": "assistant", "content": response.content},
{
"role": "user",
"content": [
{
"type": "tool_result",
"tool_use_id": tool_use.id,
"content": str(price)
}
]
}
]
)
print(final_response.content[0].text)Embeddings ve RAG
# RAG (Retrieval Augmented Generation) sistemi
from openai import OpenAI
import chromadb
from chromadb.utils import embedding_functions
client = OpenAI()
# 1. Dokümanları embedding'e çevir ve vektör DB'ye kaydet
chroma_client = chromadb.PersistentClient(path="./chroma_db")
openai_ef = embedding_functions.OpenAIEmbeddingFunction(
api_key="your-api-key",
model_name="text-embedding-3-small" # $0.02/1M tokens
)
collection = chroma_client.get_or_create_collection(
name="documents",
embedding_function=openai_ef
)
# Dokümanları ekle
documents = [
"Ürün iade süresi 14 gündür.",
"Kargo bedava, 150 TL üzeri siparişlerde.",
"Müşteri hizmetleri 7/24 hizmet vermektedir.",
"İade için fatura ve ürün kutusunun tam olması gerekir."
]
collection.add(
documents=documents,
ids=[f"doc_{i}" for i in range(len(documents))]
)
# 2. Kullanıcı sorusu geldiğinde, ilgili dokümanları bul
def answer_with_rag(user_question):
# Benzer dokümanları bul (semantic search)
results = collection.query(
query_texts=[user_question],
n_results=3
)
relevant_docs = results['documents'][0]
context = "\n".join(relevant_docs)
# GPT-4'e context ile soru sor
response = client.chat.completions.create(
model="gpt-4-turbo-preview",
messages=[
{
"role": "system",
"content": f"""Sen bir müşteri hizmetleri asistanısın.
Sadece aşağıdaki bilgileri kullanarak yanıt ver:
{context}
Eğer bilgi yoksa, "Bu konuda bilgim yok" de."""
},
{
"role": "user",
"content": user_question
}
],
temperature=0.3 # Düşük temp = daha tutarlı
)
return response.choices[0].message.content
# Kullanım
print(answer_with_rag("Ürünü iade edebilir miyim?"))
# "Evet, ürünleri 14 gün içinde iade edebilirsiniz. İade için fatura ve ürün kutusunun tam olması gerekir."
print(answer_with_rag("Kargo ücreti var mı?"))
# "150 TL üzeri siparişlerde kargo bedavadır."RAG Avantajları:
• Güncel bilgi: Model eğitim tarihinden sonraki bilgileri kullanabilir
• Doğruluk: Halüsinasyon (uydurma) riskini azaltır
• Kaynak: Yanıtın hangi doküman/paragraftan geldiğini gösterir
• Özelleştirme: Kendi verilerinizle çalışır (ürün kataloğu, FAQ, vb.)
Maliyet Optimizasyonu
| Model | Input | Output | Best For |
|---|---|---|---|
| GPT-4 Turbo | $10/1M | $30/1M | Karmaşık görevler, akıl yürütme |
| GPT-3.5 Turbo | $0.50/1M | $1.50/1M | Basit chatbot, sınıflandırma |
| Claude 3.5 Sonnet | $3/1M | $15/1M | Kod, uzun doküman analizi |
| Claude 3 Haiku | $0.25/1M | $1.25/1M | Hızlı, ucuz, basit görevler |
| Gemini Pro 1.5 | $1.25/1M | $5/1M | Çok uzun context, video |
Maliyet Düşürme Taktikleri:
• Model seçimi: GPT-3.5 basit görevler için yeterli (%95 senaryoda)
• Caching: Aynı promptları cache'leyin (Anthropic: %90 indirim)
• Prompt optimization: Kısa, net promptlar kullanın
• Batch API: Gerçek zamanlı değilse %50 indirimli batch API
• Temperature: Düşük temp (0.2-0.5) → daha kısa yanıt → daha ucuz
LLM Entegrasyonunuzu Kuralım
GPT-4, Claude, Gemini ile function calling, RAG, embeddings entegrasyonu. AI yeteneklerini uygulamanıza entegre edin.
Demo İste→