Update app.py
Browse files5 unmodified lines67891011123 unmodified lines161718192021222312 unmodified lines363738394041424310 unmodified lines545556575859606162636465666768697071727374757677787980816 unmodified lines8889909192939495969798991002 unmodified lines1031041051061071081091101111121131141151161171181191201211221231241251261271281291301318 unmodified lines1401411421431441451465 unmodified linesfrom llama_cpp import Llamafrom huggingface_hub import hf_hub_downloadimport loggingfrom fastapi.responses import StreamingResponse # Yeni eklendi# --- LOG AYARLARI ---logging.basicConfig(level=logging.INFO)3 unmodified linesMODEL_REPO = "Qwen/Qwen2.5-3B-Instruct-GGUF"MODEL_FILE = "qwen2.5-3b-instruct-q4_k_m.gguf"RAG_URL_TEMPLATE = "https://deede.tr/rag_search.php?q={}"CONTEXT_MAX_LENGTH = 1500 # Yükü azalttıkSOURCE_SEPARATOR = "||SOURCE_URL||" # Kaynak URL'i ve cevabı ayırmak için# --- 1. ADIM: MODELİ İNDİR ---logger.info(f"{MODEL_FILE} modeli Hugging Face Hub'dan indiriliyor...")12 unmodified linestry:llm = Llama(model_path=model_path,n_ctx=4096, # Context'i biraz küçülttük, CPU'da hızlanabilirn_gpu_layers=0, # CPU kullandığımızdan emin olalımverbose=True)logger.info("Model başarıyla yüklendi.")10 unmodified linesclass ChatRequest(BaseModel):prompt: str# --- 4. ADIM: YENİ STREAM GENERATOR ---async def stream_generator(messages, source_url):"""Önce kaynak URL'i, sonra LLM'den gelen token'ları stream eder."""# 1. İlk parça: Kaynak URL'i ve ayıracı gönderyield f"{source_url}{SOURCE_SEPARATOR}"# 2. İkinci parça: LLM'den gelen token'ları stream ettry:stream = llm.create_chat_completion(messages=messages,max_tokens=1024,temperature=0.7,stream=True # BU ÇOK ÖNEMLİ!)for chunk in stream:content = chunk['choices'][0]['delta'].get('content', None)if content:yield content # Her kelimeyi/token'ı anında gönderexcept Exception as e:logger.error(f"LLM stream hatası: {e}")6 unmodified lines@app.post("/api/chat")async def chat_with_rag(request: ChatRequest):"""RAG yapar ve cevabı stream_generator aracılığıyla stream eder."""user_prompt = request.promptlogger.info(f"Gelen prompt: {user_prompt}")# --- RAG İŞLEMİ (Bu kısım hala bekletir) ---try:encoded_prompt = urllib.parse.quote(user_prompt)rag_url = RAG_URL_TEMPLATE.format(encoded_prompt)2 unmodified linesheaders = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36"}response = requests.get(rag_url, headers=headers, timeout=10) # 10 saniye timeoutresponse.raise_for_status()rag_data = response.json()if not rag_data.get("results") or len(rag_data["results"]) == 0:context = "İlgili bilgi bulunamadı."context_url = "Yok"else:context = rag_data["results"][0].get("full_content", "İçerik boş.")context_url = rag_data["results"][0].get("url", "No URL")context = context[:CONTEXT_MAX_LENGTH]logger.info(f"Context alındı ({context_url}), {len(context)} karakter.")except Exception as e:logger.error(f"RAG hatası (stream başlamadı): {e}")# RAG başarısız olursa, LLM'e en azından bir hata bilgisi stream etreturn StreamingResponse(stream_generator(messages=[{"role": "user", "content": user_prompt}],source_url=f"RAG_ERROR: {e}"), media_type="text/plain")# --- LLM PROMPT'U HAZIRLA ---messages = [{"role": "system",8 unmodified lines# --- STREAM'İ BAŞLAT ---return StreamingResponse(stream_generator(messages, context_url),media_type="text/plain" # JSON değil, düz metin stream ediyoruz)# --- 7. ADIM: UYGULAMAYI BAŞLAT ---5 unmodified lines67891011123 unmodified lines161718192021222312 unmodified lines363738394041424310 unmodified lines5455565758596061626364656667686970717273747576776 unmodified lines848586878889909192939495962 unmodified lines991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421438 unmodified lines1521531541551561571585 unmodified linesfrom llama_cpp import Llamafrom huggingface_hub import hf_hub_downloadimport loggingfrom fastapi.responses import StreamingResponse# --- LOG AYARLARI ---logging.basicConfig(level=logging.INFO)3 unmodified linesMODEL_REPO = "Qwen/Qwen2.5-3B-Instruct-GGUF"MODEL_FILE = "qwen2.5-3b-instruct-q4_k_m.gguf"RAG_URL_TEMPLATE = "https://deede.tr/rag_search.php?q={}"CONTEXT_MAX_LENGTH = 1500SOURCE_SEPARATOR = "||SOURCE_URL||"# --- 1. ADIM: MODELİ İNDİR ---logger.info(f"{MODEL_FILE} modeli Hugging Face Hub'dan indiriliyor...")12 unmodified linestry:llm = Llama(model_path=model_path,n_ctx=4096,n_gpu_layers=0,verbose=True)logger.info("Model başarıyla yüklendi.")10 unmodified linesclass ChatRequest(BaseModel):prompt: str# --- 4. ADIM: STREAM GENERATOR ---async def stream_generator(messages, source_url):try:# 1. İlk parça: Kaynak URL'i ve ayıracı gönderyield f"{source_url}{SOURCE_SEPARATOR}"# 2. İkinci parça: LLM'den gelen token'ları stream etstream = llm.create_chat_completion(messages=messages,max_tokens=1024,temperature=0.7,stream=True)for chunk in stream:content = chunk['choices'][0]['delta'].get('content', None)if content:yield contentexcept Exception as e:logger.error(f"LLM stream hatası: {e}")6 unmodified lines@app.post("/api/chat")async def chat_with_rag(request: ChatRequest):user_prompt = request.promptlogger.info(f"Gelen prompt: {user_prompt}")context = "İlgili bilgi bulunamadı." # Varsayılan contextcontext_url = "Yok" # Varsayılan URL# --- RAG İŞLEMİ ---try:encoded_prompt = urllib.parse.quote(user_prompt)rag_url = RAG_URL_TEMPLATE.format(encoded_prompt)2 unmodified linesheaders = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36"}response = requests.get(rag_url, headers=headers, timeout=10)response.raise_for_status() # 4xx veya 5xx HTTP hatalarını yakala# --- YENİ GÜVENLİ JSON İŞLEME ---raw_text = response.texttry:rag_data = response.json()# JSON başarılıysa, veriyi işleif rag_data.get("results") and len(rag_data["results"]) > 0:context = rag_data["results"][0].get("full_content", "İçerik boş.")context_url = rag_data["results"][0].get("url", "No URL")context = context[:CONTEXT_MAX_LENGTH]else:logger.warning("RAG 'results' bulamadı veya boş.")context = "İlgili bilgi bulunamadı (results boş)."context_url = "Yok"except requests.exceptions.JSONDecodeError:# JSON HATASI! Ham metni logla.logger.error(f"RAG hatası: JSON DEĞİL. deede.tr'den gelen ham yanıt: {raw_text[:500]}...")context = "İlgili bilgi bulunamadı (JSON hatası)."context_url = "Yok"logger.info(f"Context alındı ({context_url}), {len(context)} karakter.")except requests.exceptions.RequestException as e:# HTTP hatası (404, 500 vb.) veya timeoutlogger.error(f"RAG HTTP Hatası: {e}")context = f"RAG kaynağına ulaşılamadı: {e}"context_url = "Yok"except Exception as e:# Diğer beklenmedik hatalarlogger.error(f"Beklenmedik RAG Hatası: {e}")context = f"RAG sisteminde genel hata: {e}"context_url = "Yok"# --- LLM PROMPT'U HAZIRLA ---# RAG başarısız olsa bile, LLM'e context'i (hata mesajıyla birlikte) göndeririz.messages = [{"role": "system",8 unmodified lines# --- STREAM'İ BAŞLAT ---return StreamingResponse(stream_generator(messages, context_url),media_type="text/plain")# --- 7. ADIM: UYGULAMAYI BAŞLAT ---
app.py+48-36