MODEL_LIST = [
{
"name": "openai",
"type": "chat",
"censored": True,
"description": "OpenAI GPT-4o modeli",
"baseModel": True
},
{
"name": "karma",
"type": "completion",
"censored": True,
"description": "Bu modelin internet erişimi mevcuttur. Son dakika haberlerini veya namaz saatlerini güncel olarak alabilirsiniz.",
"baseModel": False
}
]
def sanitize_message(message):
"""Mesaj içindeki yeni satır karakterlerini kaldırır veya boşlukla değiştirir."""
return message.replace('\n', ' ')
def init_db():
"""Veritabanını başlatır ve gerekli tabloları oluşturur."""
conn = sqlite3.connect(DB_FILE)
cursor = conn.cursor()
# numbers tablosu
cursor.execute('''
CREATE TABLE IF NOT EXISTS numbers (
number TEXT PRIMARY KEY,
coin INTEGER DEFAULT 20,
name TEXT,
mail TEXT,
model TEXT DEFAULT 'openai'
)
''')
# numbers tablosunda 'model' sütunu olup olmadığını kontrol et
cursor.execute("PRAGMA table_info(numbers)")
columns = [info[1] for info in cursor.fetchall()]
if 'model' not in columns:
logging.info("numbers tablosuna 'model' sütunu ekleniyor.")
cursor.execute("ALTER TABLE numbers ADD COLUMN model TEXT DEFAULT 'openai'")
# Mevcut kullanıcılar için varsayılan model ataması
cursor.execute("UPDATE numbers SET model = 'openai' WHERE model IS NULL")
conn.commit()
# messages tablosu
cursor.execute('''
CREATE TABLE IF NOT EXISTS messages (
id INTEGER PRIMARY KEY AUTOINCREMENT,
number TEXT,
direction TEXT,
content TEXT,
ai_response_id INTEGER,
receivedno INTEGER,
FOREIGN KEY(number) REFERENCES numbers(number)
)
''')
# messages_history tablosu (konuşma geçmişi için)
cursor.execute('''
CREATE TABLE IF NOT EXISTS messages_history (
id INTEGER PRIMARY KEY AUTOINCREMENT,
number TEXT,
role TEXT,
content TEXT,
FOREIGN KEY(number) REFERENCES numbers(number)
)
''')
conn.commit()
conn.close()
def load_processed_sms():
"""Processed SMS ID'lerini JSON dosyasından yükler."""
try:
with open(PROCESSED_SMS_FILE, 'r') as f:
processed = json.load(f)
processed_set = set(str(id_) for id_ in processed)
logging.debug(f"Processed SMS IDs loaded: {processed_set}")
return processed_set
except FileNotFoundError:
logging.debug("Processed SMS file not found. Creating a new one.")
return set()
except json.JSONDecodeError as e:
logging.error(f"Processed SMS JSON decode error: {e}")
return set()
def get_number(number):
"""Veritabanında numarayı kontrol eder."""
conn = sqlite3.connect(DB_FILE)
cursor = conn.cursor()
cursor.execute("SELECT * FROM numbers WHERE number = ?", (number,))
result = cursor.fetchone()
conn.close()
return result
def add_number(number, name="", mail="", coin=20, model='openai'):
"""Yeni bir numara ekler."""
conn = sqlite3.connect(DB_FILE)
cursor = conn.cursor()
cursor.execute("INSERT OR IGNORE INTO numbers (number, coin, name, mail, model) VALUES (?, ?, ?, ?, ?)",
(number, coin, name, mail, model))
conn.commit()
conn.close()
def update_coins(number, amount):
"""Kullanıcının coin bakiyesini günceller."""
conn = sqlite3.connect(DB_FILE)
cursor = conn.cursor()
cursor.execute("UPDATE numbers SET coin = coin + ? WHERE number = ?", (amount, number))
conn.commit()
cursor.execute("SELECT coin FROM numbers WHERE number = ?", (number,))
coin = cursor.fetchone()[0]
conn.close()
return coin
def deduct_coin(number, amount=1):
"""Kullanıcının coin bakiyesinden belirtilen miktarı düşer."""
conn = sqlite3.connect(DB_FILE)
cursor = conn.cursor()
cursor.execute("UPDATE numbers SET coin = coin - ? WHERE number = ?", (amount, number))
conn.commit()
cursor.execute("SELECT coin FROM numbers WHERE number = ?", (number,))
result = cursor.fetchone()
if result:
coin = result[0]
else:
coin = 0
conn.close()
return coin
def log_message(number, direction, content, ai_response_id=None, receivedno=None):
"""Mesajı veritabanına kaydeder."""
conn = sqlite3.connect(DB_FILE)
cursor = conn.cursor()
cursor.execute('''
INSERT INTO messages (number, direction, content, ai_response_id, receivedno)
VALUES (?, ?, ?, ?, ?)
''', (number, direction, content, ai_response_id, receivedno))
message_id = cursor.lastrowid
conn.commit()
# Eğer mesaj kullanıcıdan ise, konuşma geçmişine ekle
if direction == 'received':
cursor.execute('''
INSERT INTO messages_history (number, role, content)
VALUES (?, ?, ?)
''', (number, 'user', content))
conn.commit()
# Eğer mesaj AI'dan ise, konuşma geçmişine ekle
if direction == 'sent':
cursor.execute('''
INSERT INTO messages_history (number, role, content)
VALUES (?, ?, ?)
''', (number, 'assistant', content))
conn.commit()
conn.close()
return message_id
def get_conversation_history(number, limit=7):
"""Kullanıcının konuşma geçmişini alır, son 'limit' mesajla sınırlar."""
conn = sqlite3.connect(DB_FILE)
cursor = conn.cursor()
cursor.execute('''
SELECT role, content FROM messages_history
WHERE number = ?
ORDER BY id DESC
LIMIT ?
''', (number, limit))
history = cursor.fetchall()
conn.close()
# Reverse the history to have chronological order
history = history[::-1]
messages = [{"role": role, "content": content} for role, content in history]
return messages
def normalize_text(text):
"""Türkçe karakterleri uygun şekilde dönüştürür."""
replacements = {
'ç': 'c', 'Ç': 'C',
'ğ': 'g', 'Ğ': 'G',
'ı': 'i', 'İ': 'I',
'ö': 'o', 'Ö': 'O',
'ş': 's', 'Ş': 'S',
'ü': 'u', 'Ü': 'U',
}
return ''.join(replacements.get(c, c) for c in text)
def send_to_ai(number, prompt):
"""Sends the SMS message to the AI service and returns the response."""
# Normalize and prepare the prompt
normalized_prompt = normalize_text(prompt)
# Define the API endpoint
url = "https://text.pollinations.ai/openai"
# Get the user's selected model
user = get_number(number)
if not user:
logging.error(f"Kullanıcı {number} veritabanında bulunamadı.")
return "Kullanıcı veritabanında bulunamadı."
selected_model = user[4] # model column
# Get model details from MODEL_LIST
model_details = next((model for model in MODEL_LIST if model['name'].lower() == selected_model.lower()), None)
if not model_details:
logging.error(f"Seçilen model {selected_model} bulunamadı.")
return "Seçilen model bulunamadı."
model_type = model_details['type'] # 'chat' veya 'completion'
try:
if model_type == 'chat':
# Get conversation history
# To include system prompt as first message, limit to last 6 messages
conversation_history = get_conversation_history(number, limit=6) # 6
# 6 + 1 system message = 7 total
# Define the system prompt
system_prompt = {"role": "system", "content": "You are an AI that answers questions received via SMS."}
# Construct the payload following OpenAI's ChatGPT API format
payload = {
"model": selected_model,
"messages": [system_prompt] + conversation_history + [{"role": "user", "content": normalized_prompt}],
"stream": False # Disable streaming
}
elif model_type == 'completion':
# For completion models, send only the prompt
payload = {
"model": selected_model,
"prompt": normalized_prompt,
"max_tokens": 500 # Ayarları ihtiyaçlarınıza göre düzenleyin
}
else:
logging.error(f"Bilinmeyen model tipi: {model_type}")
return "Bilinmeyen model tipi kullanılıyor."
headers = {
"Content-Type": "application/json"
# No Authorization header needed since no API key is required
}
logging.debug(f"Sending request to AI endpoint: {url} with payload: {payload}")
# Make a POST request without streaming
response = requests.post(url, headers=headers, data=json.dumps(payload))
if response.status_code != 200:
logging.warning(f"AI service returned status code {response.status_code}")
return "AI servisine bağlanılamadı."
ai_response_json = response.json()
if model_type == 'chat':
# AI yanıtının beklendiği yapıyı kontrol et
if "choices" in ai_response_json and len(ai_response_json["choices"]) > 0:
ai_response = ai_response_json["choices"][0].get("message", {}).get("content", "").strip()
else:
ai_response = "AI'dan geçersiz yanıt alındı."
elif model_type == 'completion':
# Completion modeli için yanıt farklı bir yapıda olabilir
if "choices" in ai_response_json and len(ai_response_json["choices"]) > 0:
ai_response = ai_response_json["choices"][0].get("text", "").strip()
else:
ai_response = "AI'dan geçersiz yanıt alındı."
else:
ai_response = "AI model türü desteklenmiyor."
# Mesaj içinde yeni satır karakterlerini temizle
ai_response = sanitize_message(ai_response)
logging.info("AI yanıtı alındı.")
return ai_response
except Exception as e:
logging.error(f"AI servisi hatası: {e}")
return f"AI servisi hatası: {e}"
processed_sms = load_processed_sms()
try:
# adb logcat komutunu çalıştır
process = subprocess.Popen(
['adb', 'logcat', '-v', 'time'],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
text=True,
universal_newlines=True
)
except Exception as e:
logging.error(f"Logcat başlatma hatası: {e}")
sys.exit(1)
# Logcat satırlarını oku
try:
for line in process.stdout:
line = line.strip()
if 'ReceiveSmsMessageHelper: Received SMS message' in line:
logging.debug(f"Detected SMS log line: {line}")
sms_id = extract_sms_id(line)
if sms_id and sms_id not in processed_sms:
logging.debug(f"Processing SMS ID: {sms_id}")
# Parse SMS content
address, body = parse_sms_content(sms_id)
if address and body:
logging.debug(f"Parsed SMS - Address: {address}, Body: {body}")
# Log the received message in the database
received_message_id = log_message(address, 'received', body)
# Add Sms ID to processed list
processed_sms.add(sms_id)
save_processed_sms(processed_sms)
# Check if the number is registered
user = get_number(address)
if user:
coins = user[1]
selected_model = user[4]
logging.debug(f"Kullanıcı {address} bulundu. Coin: {coins}, Model: {selected_model}")
# Komutları kontrol et
if handle_commands(address, body, received_message_id):
continue # Komut işlendi, devam et
if coins >= 1:
prompt = body.strip()
if prompt.startswith('#'):
prompt = prompt.lstrip('#').strip()
logging.info(f"Gelen SMS: {address} - {prompt}")
ai_response = send_to_ai(address, prompt)
if ai_response:
# Deduct coins
remaining_coins = deduct_coin(address, 1)
logging.debug(f"{address} numaralı kullanıcının kalan coin sayısı: {remaining_coins}")
# Prepare AI message with coin and model info
model_info = f"M:{selected_model}"
ai_message = f"{ai_response} C:{remaining_coins} {model_info}"
# Gönderilecek mesajın yeni satır karakterlerini temizle
ai_message = sanitize_message(ai_message)
# Send AI response
send_sms(address, ai_message)
# Log the sent message with reference to received message
sent_message_id = log_message(address, 'sent', ai_message, receivedno=received_message_id)
# Update AI response ID in received message
conn = sqlite3.connect(DB_FILE)
cursor = conn.cursor()
cursor.execute("UPDATE messages SET ai_response_id = ? WHERE id = ?", (sent_message_id, received_message_id))
conn.commit()
conn.close()
# Save changes
logging.info(f"Yanıt SMS olarak gönderildi: {address} -> {ai_message}")
else:
logging.warning(f"AI yanıtı boş geldi: {address}")
else:
# Coin yeterli değil, gönderim yapma
zero_coin_message = "Coininiz bulunmamaktadır, coin yüklemesi yapmak için https://example.com sitesinden yükleme yapabilirsiniz."
zero_coin_message = sanitize_message(zero_coin_message) # Yeni satır karakterlerini temizle
send_sms(address, zero_coin_message)
logging.info(f"Coin eksik, mesaj gönderilmedi: {address}")
# Log the sent zero coin message
sent_zero_coin_id = log_message(address, 'sent', zero_coin_message, receivedno=received_message_id)
else:
# Kullanıcı kayıtlı değil, ekle ve abonelik mesajı gönder
add_number(address, coin=30) # Yeni kullanıcıya 30 kredi tanımla
welcome_message = "Hoş geldiniz! SMSGPT servisine hoş geldiniz. Hesabınıza 30 kredi tanımlandı. Modeliniz 'openai GPT-4o' olarak ayarlandı. /yardım yazarak komutları görebilirsiniz."
welcome_message = sanitize_message(welcome_message) # Yeni satır karakterlerini temizle
send_sms(address, welcome_message)
logging.info(f"Hoş geldin mesajı gönderildi ve {address} numarası veritabanına eklendi.")
# Log the sent welcome message
sent_welcome_id = log_message(address, 'sent', welcome_message, receivedno=received_message_id)
except KeyboardInterrupt:
logging.info("Program sonlandırıldı.")
except Exception as e:
logging.error(f"Logcat dinleme hatası: {e}")
finally:
process.terminate()
if name == "main":
main() bu kodda karma modeliyle böyle oldu:
2024-10-06 13:08:55,619 [DEBUG] Sending request to AI endpoint: https://text.pollinations.ai/openai with payload: {'model': 'karma', 'prompt': 'Bursa ikindi namazi vakti', 'max_tokens': 150}
2024-10-06 13:08:55,623 [DEBUG] Starting new HTTPS connection (1): text.pollinations.ai:443
2024-10-06 13:08:57,202 [DEBUG] https://text.pollinations.ai:443 "POST /openai HTTP/1.1" 400 22
2024-10-06 13:08:57,203 [WARNING] AI service returned status code 400 400 kodu
kullanacağın karma postlarını bu formatta kullanırsan sorun çözülür:
curl -X POST https://text.pollinations.ai/openai
-H "Content-Type: application/json"
-d '{
"model": "karma",
"messages": [
{"role": "user", "content": "Bursa ikindi namazi vakti"}
],
"max_tokens": 500
}'
bu curl kodunu bizim kodumuzda kullandığımız koddan farkı ne bilmiyorum ama düzelt bunu işte. bu son attığım curl kodu gayet güzel çalışıyor ancak loglardaki gönderilen https://text.pollinations.ai/openai with payload: {'model': 'karma', 'prompt': 'Bursa ikindi namazi vakti', 'max_tokens': 150} promptu hatalı döndü.
Anladığım kadarıyla, karma modeliniz için API'ye gönderilen istekte bir uyumsuzluk var. karma modeli, chat tipi olarak kullanılmalı çünkü API'nin beklediği messages formatını kullanıyorsunuz ancak kodunuz bunu completion tipi olarak tanımlamış. Bu nedenle, 400 Bad Request hatası alıyorsunuz.
Aşağıda bu sorunu çözmek için yapmanız gereken değişiklikleri adım adım açıklayacağım:
1. MODEL_LIST İçindeki karma Modelinin Typini chat Olarak Güncelleyin
MODEL_LIST'te karma modelini completion yerine chat tipi olarak tanımlamalısınız. Böylece, send_to_ai fonksiyonu doğru payload formatını kullanır.
# Model listesi
MODEL_LIST = [
{
"name": "openai",
"type": "chat",
"censored": True,
"description": "OpenAI GPT-4o modeli",
"baseModel": True
},
{
"name": "karma",
"type": "chat", # Değişiklik burada: "completion" yerine "chat"
"censored": True,
"description": "Bu modelin internet erişimi mevcuttur. Son dakika haberlerini veya namaz saatlerini güncel olarak alabilirsiniz.",
"baseModel": False
}
]
2. send_to_ai Fonksiyonunda max_tokens Ayarını Model Bazında Yapılandırın
karma modeli için max_tokens değerini 500 olarak ayarladıysanız, send_to_ai fonksiyonunda bu değeri doğru şekilde uygulamanız gerekir. Bunun için MODEL_LIST'te her model için bireysel ayarlar tanımlayabilirsiniz veya mevcut yapı içerisinde sadece karma modeli için özel bir durum ekleyebilirsiniz.
Ancak, daha temiz ve sürdürülebilir bir çözüm için her modelin kendi ayarlarını taşımasını sağlayabiliriz. Örneğin:
MODEL_LIST = [
{
"name": "openai",
"type": "chat",
"censored": True,
"description": "OpenAI GPT-4o modeli",
"baseModel": True,
"max_tokens": 500 # Yeni eklenen özellik
},
{
"name": "karma",
"type": "chat",
"censored": True,
"description": "Bu modelin internet erişimi mevcuttur. Son dakika haberlerini veya namaz saatlerini güncel olarak alabilirsiniz.",
"baseModel": False,
"max_tokens": 500 # Yeni eklenen özellik
}
]
3. send_to_ai Fonksiyonunda Payload Yapısını Doğru Şekilde Oluşturun
Artık MODEL_LIST'te her model için type doğru olarak chat olarak ayarlandığına göre, send_to_ai fonksiyonunuzun chat tipi modelleri doğru şekilde işlemesi gerekir.
Aşağıda send_to_ai fonksiyonunun güncellenmiş hali bulunmaktadır:
def send_to_ai(number, prompt):
"""Sends the SMS message to the AI service and returns the response."""
# Normalize and prepare the prompt
normalized_prompt = normalize_text(prompt)
# Define the API endpoint
url = "https://text.pollinations.ai/openai"
# Get the user's selected model
user = get_number(number)
if not user:
logging.error(f"Kullanıcı {number} veritabanında bulunamadı.")
return "Kullanıcı veritabanında bulunamadı."
selected_model = user[4] # model column
# Get model details from MODEL_LIST
model_details = next((model for model in MODEL_LIST if model['name'].lower() == selected_model.lower()), None)
if not model_details:
logging.error(f"Seçilen model {selected_model} bulunamadı.")
return "Seçilen model bulunamadı."
model_type = model_details['type'] # 'chat' veya 'completion'
max_tokens = model_details.get('max_tokens', 150) # Default olarak 150
try:
if model_type == 'chat':
# Get conversation history
# To include system prompt as first message, limit to last 6 messages
conversation_history = get_conversation_history(number, limit=6) # 6
# 6 + 1 system message = 7 total
# Define the system prompt
system_prompt = {"role": "system", "content": "You are an AI that answers questions received via SMS."}
# Construct the payload following OpenAI's ChatGPT API format
payload = {
"model": selected_model,
"messages": [system_prompt] + conversation_history + [{"role": "user", "content": normalized_prompt}],
"max_tokens": max_tokens,
"stream": False # Disable streaming
}
elif model_type == 'completion':
# For completion models, send only the prompt
payload = {
"model": selected_model,
"prompt": normalized_prompt,
"max_tokens": max_tokens # Ayarları ihtiyaçlarınıza göre düzenleyin
}
else:
logging.error(f"Bilinmeyen model tipi: {model_type}")
return "Bilinmeyen model tipi kullanılıyor."
headers = {
"Content-Type": "application/json"
# No Authorization header needed since no API key is required
}
logging.debug(f"Sending request to AI endpoint: {url} with payload: {payload}")
# Make a POST request without streaming
response = requests.post(url, headers=headers, data=json.dumps(payload))
if response.status_code != 200:
logging.warning(f"AI service returned status code {response.status_code}")
return "AI servisine bağlanılamadı."
ai_response_json = response.json()
if model_type == 'chat':
# AI yanıtının beklendiği yapıyı kontrol et
if "choices" in ai_response_json and len(ai_response_json["choices"]) > 0:
ai_response = ai_response_json["choices"][0].get("message", {}).get("content", "").strip()
else:
ai_response = "AI'dan geçersiz yanıt alındı."
elif model_type == 'completion':
# Completion modeli için yanıt farklı bir yapıda olabilir
if "choices" in ai_response_json and len(ai_response_json["choices"]) > 0:
ai_response = ai_response_json["choices"][0].get("text", "").strip()
else:
ai_response = "AI'dan geçersiz yanıt alındı."
else:
ai_response = "AI model türü desteklenmiyor."
# Mesaj içinde yeni satır karakterlerini temizle
ai_response = sanitize_message(ai_response)
logging.info("AI yanıtı alındı.")
return ai_response
except Exception as e:
logging.error(f"AI servisi hatası: {e}")
return f"AI servisi hatası: {e}"
Bu güncellemelerle birlikte:
karma modeli artık chat tipi olarak tanımlandığı için, send_to_ai fonksiyonunda messages formatını kullanacak ve doğru payload yapısı oluşturulacak.
max_tokens değeri de MODEL_LIST'te tanımlanan değere göre ayarlanarak, API'nin beklediği değer gönderilecek.
Artık karma modeli ile ilgili 400 Bad Request hatası almayacaksınız çünkü API'nin beklediği format doğru şekilde sağlanacak.
4. Ek Tavsiyeler
Hata Yönetimi: send_to_ai fonksiyonunda daha ayrıntılı hata yönetimi ekleyebilirsiniz. Örneğin, API'den gelen hata mesajlarını log'lara ekleyerek sorunun kaynağını daha kolay tespit edebilirsiniz.
Dinamik max_tokens: Eğer gelecekte farklı modeller için max_tokens değerlerini değiştirmek isterseniz, bu değeri MODEL_LIST içinde tutmak ve dinamik olarak kullanmak iyi bir uygulamadır. Bu sayede, tek bir yerden tüm modellerin ayarlarını yönetebilirsiniz.
API Endpoint Yapısı: API endpoint'inin tüm modeller için aynı olup olmadığını kontrol edin. Eğer farklı modeller farklı endpoint'ler gerektiriyorsa, MODEL_LIST'e endpoint gibi bir alan ekleyip, send_to_ai fonksiyonunda bu endpoint'i dinamik olarak kullanabilirsiniz.
5. Güncellenmiş Kod
Aşağıda yapılan tüm değişiklikleri içeren güncellenmiş MODEL_LIST ve send_to_ai fonksiyonu yer almaktadır:
# Model listesi
MODEL_LIST = [
{
"name": "openai",
"type": "chat",
"censored": True,
"description": "OpenAI GPT-4o modeli",
"baseModel": True,
"max_tokens": 500 # Yeni eklenen özellik
},
{
"name": "karma",
"type": "chat", # Değişiklik burada: "completion" yerine "chat"
"censored": True,
"description": "Bu modelin internet erişimi mevcuttur. Son dakika haberlerini veya namaz saatlerini güncel olarak alabilirsiniz.",
"baseModel": False,
"max_tokens": 500 # Yeni eklenen özellik
}
]
def send_to_ai(number, prompt):
"""Sends the SMS message to the AI service and returns the response."""
# Normalize and prepare the prompt
normalized_prompt = normalize_text(prompt)
# Define the API endpoint
url = "https://text.pollinations.ai/openai"
# Get the user's selected model
user = get_number(number)
if not user:
logging.error(f"Kullanıcı {number} veritabanında bulunamadı.")
return "Kullanıcı veritabanında bulunamadı."
selected_model = user[4] # model column
# Get model details from MODEL_LIST
model_details = next((model for model in MODEL_LIST if model['name'].lower() == selected_model.lower()), None)
if not model_details:
logging.error(f"Seçilen model {selected_model} bulunamadı.")
return "Seçilen model bulunamadı."
model_type = model_details['type'] # 'chat' veya 'completion'
max_tokens = model_details.get('max_tokens', 150) # Default olarak 150
try:
if model_type == 'chat':
# Get conversation history
# To include system prompt as first message, limit to last 6 messages
conversation_history = get_conversation_history(number, limit=6) # 6
# 6 + 1 system message = 7 total
# Define the system prompt
system_prompt = {"role": "system", "content": "You are an AI that answers questions received via SMS."}
# Construct the payload following OpenAI's ChatGPT API format
payload = {
"model": selected_model,
"messages": [system_prompt] + conversation_history + [{"role": "user", "content": normalized_prompt}],
"max_tokens": max_tokens,
"stream": False # Disable streaming
}
elif model_type == 'completion':
# For completion models, send only the prompt
payload = {
"model": selected_model,
"prompt": normalized_prompt,
"max_tokens": max_tokens # Ayarları ihtiyaçlarınıza göre düzenleyin
}
else:
logging.error(f"Bilinmeyen model tipi: {model_type}")
return "Bilinmeyen model tipi kullanılıyor."
headers = {
"Content-Type": "application/json"
# No Authorization header needed since no API key is required
}
logging.debug(f"Sending request to AI endpoint: {url} with payload: {payload}")
# Make a POST request without streaming
response = requests.post(url, headers=headers, data=json.dumps(payload))
if response.status_code != 200:
logging.warning(f"AI service returned status code {response.status_code}")
return "AI servisine bağlanılamadı."
ai_response_json = response.json()
if model_type == 'chat':
# AI yanıtının beklendiği yapıyı kontrol et
if "choices" in ai_response_json and len(ai_response_json["choices"]) > 0:
ai_response = ai_response_json["choices"][0].get("message", {}).get("content", "").strip()
else:
ai_response = "AI'dan geçersiz yanıt alındı."
elif model_type == 'completion':
# Completion modeli için yanıt farklı bir yapıda olabilir
if "choices" in ai_response_json and len(ai_response_json["choices"]) > 0:
ai_response = ai_response_json["choices"][0].get("text", "").strip()
else:
ai_response = "AI'dan geçersiz yanıt alındı."
else:
ai_response = "AI model türü desteklenmiyor."
# Mesaj içinde yeni satır karakterlerini temizle
ai_response = sanitize_message(ai_response)
logging.info("AI yanıtı alındı.")
return ai_response
except Exception as e:
logging.error(f"AI servisi hatası: {e}")
return f"AI servisi hatası: {e}"
6. Test Etme
Yukarıdaki değişiklikleri yaptıktan sonra, karma modeli ile tekrar test edin. 400 Bad Request hatası alıp almadığınızı kontrol edin. Eğer her şey doğru yapılandırıldıysa, API'den başarılı yanıt almanız gerekir.
7. Sonuç
Bu değişikliklerle birlikte, karma modelinizin doğru yapılandırılmış chat tipi olarak tanımlanması ve doğru payload formatıyla API'ye gönderilmesi sağlanmıştır. Böylece, 400 Bad Request hatasını ortadan kaldırmalı ve karma modeli ile sorunsuz bir şekilde iletişim kurabilmelisiniz.
Bir başka önemli nokta da, gelecekte ekleyeceğiniz modellerin doğru tip ve payload yapısına sahip olduğundan emin olmaktır. Bu, API ile uyumlu kalmanızı ve sorunsuz bir entegrasyon sağlanmasını kolaylaştıracaktır.
Herhangi bir başka sorunla karşılaşırsanız veya ek yardım isterseniz, lütfen bana bildirin!