Skip to content
The Chat Archive
o1-mini-2024-09-12· OpenAI WildChat-4.8M (AI2)

smsprocessor.py import subprocess import re import requests import logging import…

  1. User

    sms_processor.py

    import subprocess import re import requests import logging import sqlite3 import sys import json from urllib.parse import quote

    Logging yapılandırması

    logging.basicConfig( level=logging.DEBUG, # Daha fazla detay için DEBUG seviyesine çektik format='%(asctime)s [%(levelname)s] %(message)s', handlers=[ logging.FileHandler("sms_processor.log"), logging.StreamHandler() ] )

    DB_FILE = "smsai.db" PROCESSED_SMS_FILE = "processed_sms.json"

    Model listesi

    MODEL_LIST = [ { "name": "openai", "type": "chat", "censored": True, "description": "OpenAI GPT-4o", "baseModel": True }, { "name": "mistral", "type": "chat", "censored": False, "description": "mistral sansürsüz model", "baseModel": True }, { "name": "karma", "type": "completion", "censored": True, "description": "Karma modeli haberlere ulaşabilir, internetten arama yapabilir.", "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 save_processed_sms(processed_sms): """Processed SMS ID'lerini JSON dosyasına kaydeder.""" try: with open(PROCESSED_SMS_FILE, 'w') as f: json.dump(list(processed_sms), f) logging.debug(f"Processed SMS IDs saved: {processed_sms}") except Exception as e: logging.error(f"Error saving processed SMS IDs: {e}")

    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 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
    }
    
    headers = {
        "Content-Type": "application/json"
        # No Authorization header needed since no API key is required
    }
    
    try:
        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()
        # 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ı."
        
        # 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}"
    

    def extract_sms_id(log_line): """Log satırından SMS ID'sini çıkartır.""" match = re.search(r'uri:\s+content://sms/(\d+)', log_line) if match: sms_id = match.group(1).strip() logging.debug(f"Extracted SMS ID: {sms_id}") return sms_id return None

    def parse_sms_content(sms_id): """SMS içeriğini sorgular ve adres ile body'yi döndürür.""" try: cmd = [ 'adb', 'shell', 'content', 'query', '--uri', f'content://sms/{sms_id}', '--projection', 'address,body,type' ] logging.debug(f"Running command: {' '.join(cmd)}") result = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)

        if result.stderr:
            logging.error(f"SMS query hatası: {result.stderr}")
            return None, None
        
        # Tam çıktıyı loglama
        logging.debug(f"SMS query output: {result.stdout}")
        
        address = None
        body = None
        sms_type = None
    
        # 'address', 'body' ve 'type' alanlarını regex ile çıkarma
        address_search = re.search(r'address=([^,]+)', result.stdout)
        if address_search:
            address = address_search.group(1).strip()
            logging.debug(f"Address: {address}")
        else:
            logging.debug("Address bulunamadı.")
    
        body_search = re.search(r'body=(.*)', result.stdout)
        if body_search:
            body_full = body_search.group(1).strip()
            # Remove ', type=1' or similar suffix
            body = re.sub(r',\s*type=\d+', '', body_full).strip()
            logging.debug(f"Body (cleaned): {body}")
        else:
            logging.debug("Body bulunamadı.")
    
        type_search = re.search(r'type=(\d+)', result.stdout)
        if type_search:
            sms_type = int(type_search.group(1))
            logging.debug(f"SMS Type: {sms_type}")
        else:
            logging.debug("Type bulunamadı.")
        
        # Sadece gelen SMS'leri işle
        if sms_type != 1:
            logging.debug("SMS tipi alındı ancak gelen SMS değil, işlenmiyor.")
            return None, None
    
        logging.debug(f"Parsed SMS - Address: {address}, Body: {body}, Type: {sms_type}")
        return address, body
    except Exception as e:
        logging.error(f"SMS parse hatası: {e}")
        return None, None
    

    def escape_message(message): """SMS mesajındaki boşluk ve özel karakterleri kaçırır.""" message = sanitize_message(message) escape_chars = { ' ': '\ ', '-': '\-', '!': '\!', '"': '\"', "'": "\'", '\': '\\', '(': '\(', # Açık parantez ')': '\)', # Kapalı parantez '&': '\&', # Ampersand ';': '\;', # Noktalı virgül '|': '\|', # Boru '<': '\<', # Küçük eşit '>': '\>', # Büyük eşit '′:′': '\\', # Dolar işareti '': '\\', # Backtick '': '\', # Yıldız '?': '\?', # Soru işareti } escaped = ''.join([escape_chars.get(c, c) for c in message]) return escaped

    def send_sms(number, message): """Yanıt mesajını ShellMS aracılığıyla gönderir.""" try: escaped_message = escape_message(message) cmd = [ 'adb', 'shell', 'am', 'startservice', '--user', '0', '-n', 'com.android.shellms/.sendSMS', '--es', 'contact', number, '--es', 'msg', escaped_message # Mesajı kaçırılmış şekilde gönder ] # Komutun loglanması için, 'shell' altındaki tüm argümanları loglamalıyız. logging.debug(f"Executing ShellMS command: adb {' '.join(cmd[1:])}") subprocess.run(cmd, check=True) logging.info(f"Yanıt SMS olarak gönderildi: {number} -> {message}") except subprocess.CalledProcessError as e: logging.error(f"SMS gönderim hatası: {e}") except Exception as e: logging.error(f"SMS gönderim hatası: {e}")

    def handle_commands(number, body, received_message_id): """Kullanıcının gönderdiği komutları işler.""" body_lower = body.lower().strip()

    # /yardım komutunu işleme
    if re.fullmatch(r'/?(yardım)', body_lower, re.IGNORECASE):
        help_message = (
            "Yardım Komutları: "
            "/yardım - Bu mesajı gösterir. "
            "/model [model_adı] - Modelinizi değiştirir. "
            "Mevcut Modeller: "
        )
        for model in MODEL_LIST:
            help_message += f"- {model['name']}: {model['description']} "
        help_message += "Modelinizi değiştirmek için /model [model_adı] yazabilirsiniz."
        help_message = sanitize_message(help_message)  # Yeni satır karakterlerini temizle
        send_sms(number, help_message)
        log_message(number, 'sent', help_message, receivedno=received_message_id)
        return True
    
    # /model komutunu işleme
    match = re.match(r'/?model\s+([\w\-]+)', body, re.IGNORECASE)
    if match:
        selected_model_input = match.group(1).lower()
        # Model ismi varyasyonlarını normalize et
        selected_model_key = selected_model_input.replace('-', '')
        # Bulunan modeli kontrol et
        valid_models = {model['name'].lower().replace('-', ''): model for model in MODEL_LIST}
        if selected_model_key in valid_models:
            actual_model_name = valid_models[selected_model_key]['name']
            # Güncelle
            conn = sqlite3.connect(DB_FILE)
            cursor = conn.cursor()
            cursor.execute("UPDATE numbers SET model = ? WHERE number = ?", (actual_model_name, number))
            conn.commit()
            conn.close()
            user = get_number(number)
            remaining_coins = user[1] if user else 0
            confirmation_message = f"Modeliniz güncellendi: {valid_models[selected_model_key]['description']} modeli aktif. C:{remaining_coins} M:{actual_model_name}"
            confirmation_message = sanitize_message(confirmation_message)  # Yeni satır karakterlerini temizle
            send_sms(number, confirmation_message)
            log_message(number, 'sent', confirmation_message, receivedno=received_message_id)
            return True
        else:
            error_message = "Geçersiz model adı. /yardım yazarak mevcut modelleri görebilirsiniz."
            error_message = sanitize_message(error_message)  # Yeni satır karakterlerini temizle
            send_sms(number, error_message)
            log_message(number, 'sent', error_message, receivedno=received_message_id)
            return True
    
    # /yardım veya /model komutu değilse False döner
    return False
    

    def main(): """Ana döngü.""" init_db() logging.info("SMS dinleniyor...")

    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()

    burada şöyle bir sıkıntımız var her şey güzel çalışıyor ama karma modeli chat desteklemiyor. sadece kullanıcının son mesajını oraya atsın normalde son 7 mesajla beraber chat şeklinde atıyordu ama o şekilde çalışmıyor bu model. eğer karma modeli aktif ise chat yerine sadece kullanıcının attığı son mesajı apiye iletsin.

  2. Assistant

    Anladığım kadarıyla, karma modeli Chat API'sini desteklemiyor ve sadece son kullanıcı mesajını işleyebiliyor. Diğer modeller ise (örneğin openai ve mistral) sohbet geçmişini kullanarak yanıt oluşturabiliyor. Bu durumu yönetmek için kodunuzda bazı değişiklikler yapmamız gerekecek.

    Aşağıda, bu durumu yönetmek için yapmanız gereken adımları ve ilgili kod değişikliklerini detaylandırıyorum:

    1. Model Bilgisine Erişim Sağlamak:

      send_to_ai fonksiyonunda, kullanıcının seçtiği modelin type bilgisini elde etmemiz gerekiyor. Bu bilgiye göre, modelin sohbet geçmişini kullanıp kullanmayacağını belirleyebiliriz.

    2. Sohbet Geçmişi ile API'ye İstek Gönderme:

      Modelin type bilgisine göre, chat türündeki modeller için sohbet geçmişi ile birlikte mesajı, completion türündeki modeller için ise sadece son mesajı API'ye göndermemiz gerekecek.

    3. Fonksiyonları Güncellemek:

      send_to_ai fonksiyonunu, model tipine göre farklı payload yapıları oluşturacak şekilde güncelleyeceğiz.

    Aşağıda, gerekli değişiklikleri içeren güncellenmiş kod kısmını bulabilirsiniz:

    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": 150  # 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}"
    

    Açıklamalar ve Değişiklikler:

    1. Model Tipinin Belirlenmesi:

      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'
      

      Burada, kullanıcının seçtiği modelin detaylarını MODEL_LIST içerisinden alıyoruz ve model tipini belirliyoruz (chat veya completion).

    2. Payload Yapısının Model Tipine Göre Oluşturulması:

      • Chat Tipi Modeller (chat):

        Sohbet geçmişi ile birlikte OpenAI Chat API formatında payload oluşturuluyor.

      • Completion Tipi Modeller (completion):

        Sadece son kullanıcı mesajını içeren basit bir prompt şeklinde payload oluşturuluyor.

    3. AI Yanıtının İşlenmesi:

      Model tipine göre, yanıtın hangi alandan alınacağını belirledik:

      • Chat: choices[0].message.content
      • Completion: choices[0].text
    4. Hata Yönetimi:

      Bilinmeyen model tipleri veya API hatalarında uygun hata mesajları döndürülüyor.

    Diğer Potansiyel İyileştirmeler:

    1. MODEL_LIST İçindeki Modellerin Tiplerini Kullanarak Kolay Erişim Sağlamak:

      Eğer başka modeller eklerken bu tür farklılıkları yönetmek isterseniz, MODEL_LIST'i daha esnek hale getirebilirsiniz veya model tiplerine göre daha kapsamlı seçenekler ekleyebilirsiniz.

    2. Komut İşleme Fonksiyonu:

      handle_commands fonksiyonunda, eğer model değiştirme gibi işlemler yaptıktan sonra kullanıcıya geri bildirim verirken model tipine bağlı olarak farklı mesajlar göndermek isteyebilirsiniz.

    3. Dinamik API Endpoint Kullanımı:

      Eğer farklı modeller farklı API uç noktalarını kullanıyorsa, MODEL_LIST'e api_endpoint gibi bir alan ekleyip, her modelin kendi uç noktasını dinamik olarak belirleyebilirsiniz.

    Tamamlanmış send_to_ai Fonksiyonu

    Aşağıda, yukarıda yapılan değişikliklerle birlikte tam olarak güncellenmiş send_to_ai fonksiyonunu bulabilirsiniz:

    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": 150  # 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 Değişikliklerin İşleyişi:

    1. Model Tipine Göre Payload Oluşturma:

      • Chat Tipi (chat): Sohbet geçmişi ile birlikte messages listesi gönderilir.
      • Completion Tipi (completion): Sadece prompt alanı ile istek yapılır.
    2. AI Yanıtını Doğru Şekilde Alma:

      • Chat Tipi: choices[0].message.content
      • Completion Tipi: choices[0].text
    3. Hata Durumlarını Yönetme:

      Bilinmeyen model tipleri veya API yanıt hatalarında uygun mesajlar döndürülür.

    Sonuç

    Bu değişikliklerle birlikte, karma modeli gibi sohbet geçmişi desteklemeyen modeller için sadece son kullanıcı mesajını AI API'sine gönderirken, sohbet geçmişi destekleyen modeller için son 7 mesajı içeren bir sohbet geçmişi ile birlikte mesajı göndereceksiniz. Bu sayede her iki model tipi için uygun şekilde yanıtlar alabilirsiniz.

    Kodunuzda bu değişiklikleri uyguladıktan sonra, sistemi test etmeyi unutmayın. Her modelin beklenen şekilde çalıştığından emin olmak için hem chat hem de completion tipi modellerle testler yapmanız faydalı olacaktır.

    Eğer başka sorularınız veya eklememizi istediğiniz başka özellikler varsa, lütfen belirtin!