Spaces:
Sleeping
Sleeping
Commit ·
7211eef
1
Parent(s): 3cb9fd0
Enable real-time token streaming with Groq StreamingResponse
Browse files439 unmodified lines44044144244344444544619 unmodified lines466467468469470471472473474475476477478479480481439 unmodified lineselse:reply_text = "أهلاً بك! لم يتم ضبط مفتاح Groq API Key في ملف `.env` بعد. يمكنك الحصول عليه مجاناً من https://console.groq.com"return {"reply": reply_text}try:from groq import Groq19 unmodified linesmessages.append({"role": role, "content": h.content.strip()})messages.append({"role": "user", "content": chat_req.message.strip()})response = client.chat.completions.create(model="llama-3.3-70b-versatile",messages=messages,max_tokens=1024,)reply_text = response.choices[0].message.content.strip()return {"reply": reply_text}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])439 unmodified lines44044144244344444544644744844919 unmodified lines469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499439 unmodified lineselse:reply_text = "أهلاً بك! لم يتم ضبط مفتاح Groq API Key في ملف `.env` بعد. يمكنك الحصول عليه مجاناً من https://console.groq.com"def fallback_stream():for word in reply_text.split(' '):yield f"{word} "return StreamingResponse(fallback_stream(), media_type="text/plain; charset=utf-8")try:from groq import Groq19 unmodified linesmessages.append({"role": role, "content": h.content.strip()})messages.append({"role": "user", "content": chat_req.message.strip()})completion = client.chat.completions.create(model="llama-3.3-70b-versatile",messages=messages,max_tokens=1024,stream=True # Real-time token streaming!)def stream_generator():try:for chunk in completion:if chunk.choices and len(chunk.choices) > 0:delta = chunk.choices[0].deltaif delta and delta.content:yield 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_stream():yield f"حدث خطأ أثناء الاتصال بالذكاء الاصطناعي: {str(e)}"return StreamingResponse(error_stream(), media_type="text/plain; charset=utf-8")# --- 🔍 Web Search Endpoint ---@app.get("/api/v1/search", response_model=List[schemas.SearchResult])
app/main.py+23-5