Commit ·
8c9a677
1
Parent(s): 7b97c87
Add StreamingResponse support to AI chat endpoint
Browse files419 unmodified lines4204214224234244254264276 unmodified lines43443543643543643743743843943944044144044144244344444544644744844945045118 unmodified lines470471472466473474475476477478471479480481482483484485486487488489490491474492493494495496497419 unmodified lines except Exception as e: raise HTTPException(status_code=500, detail=f"حدث خطأ أثناء معالجة الملف: {str(e)}")
from fastapi.responses import StreamingResponse
# --- 🚀 Upgraded Chatbot (RAG) Endpoint ---@app.post("/api/v1/ai/articles/{article_id}/chat")def chat_with_article(article_id: int, chat_req: schemas.ChatRequest, db: Session = Depends(get_db)):6 unmodified lines # Fallback offline replies user_msg = chat_req.message.lower() if any(greeting in user_msg for greeting in ["مرحباً", "hello", "hi", "سلام", "هلا"]): return {"reply": "أهلاً بك! أنا مساعدك الذكي لقراءة وتلخيص هذا المقال. كيف يمكنني مساعدتك اليوم؟"} if any(kw in user_msg for kw in ["لخص", "ملخص", "summary", "summarize"]): reply_text = "أهلاً بك! أنا مساعدك الذكي لقراءة وتلخيص هذا المقال. كيف يمكنني مساعدتك اليوم؟" elif any(kw in user_msg for kw in ["لخص", "ملخص", "summary", "summarize"]): summary_text = article.summary if article.summary else generate_ai_summary(article.content) return {"reply": f"إليك ملخص سريع للمقال:\n{summary_text}"} return {"reply": f"أهلاً بك! لم يتم ضبط مفتاح Groq API Key في ملف `.env` بعد. يمكنك الحصول عليه مجاناً من https://console.groq.com"} reply_text = f"إليك ملخص سريع للمقال:\n{summary_text}" else: reply_text = "أهلاً بك! لم يتم ضبط مفتاح Groq API Key في ملف `.env` بعد. يمكنك الحصول عليه مجاناً من https://console.groq.com" def fallback_generator(): for char_chunk in [reply_text[i:i+5] for i in range(0, len(reply_text), 5)]: yield char_chunk
return StreamingResponse(fallback_generator(), media_type="text/plain; charset=utf-8") try: from groq import Groq18 unmodified lines messages.append({"role": role, "content": h.content}) messages.append({"role": "user", "content": chat_req.message}) response = client.chat.completions.create( completion = client.chat.completions.create( model="llama-3.3-70b-versatile", messages=messages, max_tokens=1024, stream=True ) return {"reply": response.choices[0].message.content.strip()}
def stream_generator(): try: for chunk in completion: if chunk.choices and chunk.choices[0].delta.content: yield chunk.choices[0].delta.content except Exception as e: print(f"Streaming error: {e}") yield f"\n[حدث خطأ أثناء البث: {str(e)}]"
return StreamingResponse(stream_generator(), media_type="text/plain; charset=utf-8") except Exception as e: print(f"Groq Chat error: {e}") return {"reply": f"حدث خطأ أثناء الاتصال بالذكاء الاصطناعي: {str(e)}"} def error_generator(): yield f"حدث خطأ أثناء الاتصال بالذكاء الاصطناعي: {str(e)}" return StreamingResponse(error_generator(), media_type="text/plain; charset=utf-8")
# --- 🔍 Web Search Endpoint ---@app.get("/api/v1/search", response_model=List[schemas.SearchResult])app/main.py+29-9