Commit ·
8c9a677
1
Parent(s): 7b97c87
Add StreamingResponse support to AI chat endpoint
Browse files419 unmodified lines4204214224234244256 unmodified lines43243343443543643743843944044144244344418 unmodified lines463464465466467468469470471472473474475476477419 unmodified linesexcept Exception as e:raise HTTPException(status_code=500, detail=f"حدث خطأ أثناء معالجة الملف: {str(e)}")# --- 🚀 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 repliesuser_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"]):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"}try:from groq import Groq18 unmodified linesmessages.append({"role": role, "content": h.content})messages.append({"role": "user", "content": chat_req.message})response = client.chat.completions.create(model="llama-3.3-70b-versatile",messages=messages,max_tokens=1024,)return {"reply": response.choices[0].message.content.strip()}except Exception as e:print(f"Groq Chat error: {e}")return {"reply": f"حدث خطأ أثناء الاتصال بالذكاء الاصطناعي: {str(e)}"}# --- 🔍 Web Search Endpoint ---@app.get("/api/v1/search", response_model=List[schemas.SearchResult])419 unmodified lines4204214224234244254264276 unmodified lines43443543643743843944044144244344444544644744844945045118 unmodified lines470471472473474475476477478479480481482483484485486487488489490491492493494495496497419 unmodified linesexcept 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 repliesuser_msg = chat_req.message.lower()if any(greeting in user_msg for greeting in ["مرحباً", "hello", "hi", "سلام", "هلا"]):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)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_chunkreturn StreamingResponse(fallback_generator(), media_type="text/plain; charset=utf-8")try:from groq import Groq18 unmodified linesmessages.append({"role": role, "content": h.content})messages.append({"role": "user", "content": chat_req.message})completion = client.chat.completions.create(model="llama-3.3-70b-versatile",messages=messages,max_tokens=1024,stream=True)def stream_generator():try:for chunk in completion:if chunk.choices and chunk.choices[0].delta.content:yield chunk.choices[0].delta.contentexcept 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}")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