fix: migrar main.py a google-genai SDK
Browse files1233 unmodified lines789101112138 unmodified lines2223242526272828 unmodified lines57585960616263646566676869707117 unmodified lines899091929394955 unmodified lines10110210310410510610710810911011111211311411511611711811912078 unmodified lines1992002012022032042052067 unmodified lines21421521621721821922022122222322422522622722822923023123223323437 unmodified lines27227327427527627727821 unmodified lines3003013023033043053063073083093103113123133143153163173183 unmodified lines3223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773784 unmodified lines3833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744751 unmodified line4774784794804814824834844854864874884894 unmodified lines49449549649749849950050150250350450550650750850951051151230 unmodified lines54354454554654754854955055155255355455516 unmodified lines5725735745755765775785795805815826 unmodified lines5895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926934 unmodified lines6986997007017027037041 unmodified line706707708709import base64import jsonimport logging3 unmodified linesfrom typing import Any, Optionalimport firebase_adminimport google.generativeai as genaiimport pytzfrom anthropic import (APIConnectionError,8 unmodified linesfrom fastapi.middleware.cors import CORSMiddlewarefrom fastapi.responses import JSONResponse, StreamingResponsefrom firebase_admin import auth, credentials, firestorefrom google.api_core import exceptions as google_exceptionsfrom pydantic import BaseModel, Field, field_validator# --- Logging con request_id ---28 unmodified linesALLOWED_GEMINI_MODELS = {"gemini-2.5-flash","gemini-2.5-pro","gemini-1.5-flash",}AI_DAILY_LIMITS = {"free": 5, "basic": 50, "premium": 50, "enterprise": 200}DEFAULT_AI_PLAN = "free"# --- Estado global tolerante a fallos en boot ---# IMPORTANTE: no lanzar excepciones al import-time o el Space queda en "Starting"# indefinidamente. Cualquier fallo se reporta en GET / y en los logs.db: Optional[firestore.Client] = Nonefirebase_error: Optional[str] = None17 unmodified lineselse:db = firestore.client()# --- Clientes externos como singletons ---CLAUDE_API_KEY = os.environ.get("CLAUDE_API_KEY")GEMINI_API_KEY = os.environ.get("GEMINI_API_KEY")5 unmodified linesclaude_client: Optional[AsyncAnthropic] = Noneif CLAUDE_API_KEY:try:claude_client = AsyncAnthropic(api_key=CLAUDE_API_KEY, timeout=HTTP_TIMEOUT_SECONDS)except Exception as exc:logger.exception("No se pudo crear cliente Anthropic: %s", exc)if GEMINI_API_KEY:try:genai.configure(api_key=GEMINI_API_KEY)except Exception as exc:logger.exception("No se pudo configurar Gemini: %s", exc)# --- App ---app = FastAPI(title="Surco AI Proxy", version="2.1.0")app.add_middleware(CORSMiddleware,78 unmodified lineslimit = AI_DAILY_LIMITS.get(plan, 5)today = datetime.now(BOGOTA_TZ).strftime("%Y-%m-%d")if db is None:# Firebase no disponible — concedemos sin contar para no bloquear UX,# pero el endpoint igual va a fallar más abajo si Firebase es requerido.return {"allowed": True, "remaining": limit, "plan": plan}ref = (db.collection("users")7 unmodified linessnap = ref.get(transaction=transaction)current = (snap.to_dict() or {}).get("count", 0) if snap.exists else 0if current >= limit:return {"allowed": False,"limit": limit,"plan": plan,"used": current,}new_count = current + 1transaction.set(ref,{"count": new_count,"limit": limit,"plan": plan,"date": today,},merge=True,)return {"allowed": True, "remaining": limit - new_count, "plan": plan}37 unmodified lines)# --- Endpoints ---@app.post("/claude")async def claude_proxy(request: Request,21 unmodified linesuser_content: list[dict[str, Any]] = []if payload.imageBase64:user_content.append({"type": "image","source": {"type": "base64","media_type": "image/jpeg","data": payload.imageBase64,},})user_content.append({"type": "text", "text": payload.userText or "Analiza esta imagen"})messages.append({"role": "user", "content": user_content})res = await claude_client.messages.create(3 unmodified linesmessages=messages,)text_blocks = [b.text for b in res.content if getattr(b, "type", None) == "text"]if not text_blocks:_decrement_quota(uid)logger.error("Claude respondió sin bloques de texto", extra=extra)raise HTTPException(status_code=502, detail="Respuesta vacía del modelo")logger.info("Claude OK model=%s remaining=%s", model, quota["remaining"], extra=extra)return {"text": "\n".join(text_blocks),"remaining": quota["remaining"],"model": model,}except RateLimitError:_decrement_quota(uid)logger.warning("Claude upstream rate limit", extra=extra)return JSONResponse(status_code=429,content={"error": "upstream_rate_limit","message": "El proveedor está saturado, intenta en un minuto",},)except BadRequestError as exc:_decrement_quota(uid)logger.warning("Claude bad request: %s", exc, extra=extra)raise HTTPException(status_code=400, detail=f"Solicitud inválida: {exc.message}") from excexcept AuthenticationError as exc:_decrement_quota(uid)logger.error("Claude auth error — revisa CLAUDE_API_KEY", extra=extra)raise HTTPException(status_code=502, detail="Error de autenticación con el proveedor") from excexcept (APITimeoutError, APIConnectionError) as exc:_decrement_quota(uid)logger.warning("Claude conexión: %s", exc, extra=extra)raise HTTPException(status_code=504, detail="Tiempo de espera agotado") from excexcept APIStatusError as exc:_decrement_quota(uid)logger.error("Claude API error %s: %s", exc.status_code, exc, extra=extra)raise HTTPException(status_code=502, detail="Error del proveedor") from excexcept HTTPException:raiseexcept Exception as exc:_decrement_quota(uid)logger.exception("Claude error inesperado", extra=extra)raise HTTPException(status_code=500, detail=f"Error interno: {type(exc).__name__}") from exc@app.post("/gemini")async def gemini_proxy(request: Request,4 unmodified linesextra = {"request_id": rid}uid = user["uid"]if not GEMINI_API_KEY:raise HTTPException(status_code=503, detail="Gemini no disponible")quota = _check_and_increment_quota(uid)if not quota["allowed"]:return _quota_response(quota)model_name = _resolve_model(payload.model, ALLOWED_GEMINI_MODELS, DEFAULT_GEMINI_MODEL)try:model = genai.GenerativeModel(model_name=model_name,system_instruction=payload.systemPrompt or "",)history: list[dict[str, Any]] = []for msg in payload.history[-MAX_HISTORY:]:role = "user" if msg.role == "user" else "model"history.append({"role": role, "parts": [msg.text or "[imagen]"]})chat = model.start_chat(history=history)content: list[Any] = []if payload.imageBase64:try:img_bytes = base64.b64decode(payload.imageBase64, validate=True)except Exception as exc:_decrement_quota(uid)raise HTTPException(status_code=400, detail=f"imageBase64 inv��lido: {exc}") from exccontent.append({"mime_type": "image/jpeg", "data": img_bytes})content.append(payload.userText or "Analiza esta imagen")res = await chat.send_message_async(content,request_options={"timeout": HTTP_TIMEOUT_SECONDS},)text = getattr(res, "text", None)if not text:_decrement_quota(uid)logger.error("Gemini respondió sin texto", extra=extra)raise HTTPException(status_code=502, detail="Respuesta vacía del modelo")logger.info("Gemini OK model=%s remaining=%s", model_name, quota["remaining"], extra=extra)return {"text": text, "remaining": quota["remaining"], "model": model_name}except google_exceptions.ResourceExhausted:_decrement_quota(uid)logger.warning("Gemini upstream rate limit", extra=extra)return JSONResponse(status_code=429,content={"error": "upstream_rate_limit","message": "El proveedor está saturado, intenta en un minuto",},)except google_exceptions.InvalidArgument as exc:_decrement_quota(uid)logger.warning("Gemini bad request: %s", exc, extra=extra)raise HTTPException(status_code=400, detail=f"Solicitud inválida: {exc}") from excexcept google_exceptions.PermissionDenied as exc:_decrement_quota(uid)logger.error("Gemini permission denied — revisa GEMINI_API_KEY", extra=extra)raise HTTPException(status_code=502, detail="Error de autenticación con el proveedor") from excexcept google_exceptions.DeadlineExceeded as exc:_decrement_quota(uid)logger.warning("Gemini timeout", extra=extra)raise HTTPException(status_code=504, detail="Tiempo de espera agotado") from excexcept google_exceptions.GoogleAPICallError as exc:_decrement_quota(uid)logger.error("Gemini API error: %s", exc, extra=extra)raise HTTPException(status_code=502, detail="Error del proveedor") from excexcept HTTPException:raiseexcept Exception as exc:_decrement_quota(uid)logger.exception("Gemini error inesperado", extra=extra)raise HTTPException(status_code=500, detail=f"Error interno: {type(exc).__name__}") from exc# --- Endpoints streaming (SSE) ---SSE_HEADERS = {"Cache-Control": "no-cache, no-transform","X-Accel-Buffering": "no",1 unmodified line"Content-Type": "text/event-stream; charset=utf-8",}def _sse(event: dict) -> str:return f"data: {json.dumps(event, ensure_ascii=False)}\n\n"def _build_claude_messages(payload: AIRequest) -> list[dict[str, Any]]:"""Construye messages con alternancia user/assistant estricta + turno actual."""messages: list[dict[str, Any]] = []for msg in payload.history[-MAX_HISTORY:]:role = "user" if msg.role == "user" else "assistant"4 unmodified linesuser_content: list[dict[str, Any]] = []if payload.imageBase64:user_content.append({"type": "image","source": {"type": "base64","media_type": "image/jpeg","data": payload.imageBase64,},})user_content.append({"type": "text", "text": payload.userText or "Analiza esta imagen"})messages.append({"role": "user", "content": user_content})return messages30 unmodified linesasync for text in stream.text_stream:yielded = Trueyield _sse({"delta": text})yield _sse({"done": True,"remaining": quota["remaining"],"model": model,})logger.info("Claude stream OK model=%s", model, extra=extra)except RateLimitError:if not yielded:16 unmodified lineslogger.exception("Claude stream error inesperado", extra=extra)yield _sse({"error": "internal", "message": type(exc).__name__})return StreamingResponse(event_stream(),media_type="text/event-stream",headers=SSE_HEADERS,)@app.post("/gemini/stream")6 unmodified linesextra = {"request_id": rid}uid = user["uid"]if not GEMINI_API_KEY:raise HTTPException(status_code=503, detail="Gemini no disponible")quota = _check_and_increment_quota(uid)if not quota["allowed"]:return _quota_response(quota)model_name = _resolve_model(payload.model, ALLOWED_GEMINI_MODELS, DEFAULT_GEMINI_MODEL)# Decode image upfront so we fail before opening the streamimg_bytes: Optional[bytes] = Noneif payload.imageBase64:try:img_bytes = base64.b64decode(payload.imageBase64, validate=True)except Exception as exc:_decrement_quota(uid)raise HTTPException(status_code=400, detail=f"imageBase64 inválido: {exc}") from excsafety = [{"category": "HARM_CATEGORY_HARASSMENT", "threshold": "BLOCK_NONE"},{"category": "HARM_CATEGORY_HATE_SPEECH", "threshold": "BLOCK_NONE"},{"category": "HARM_CATEGORY_SEXUALLY_EXPLICIT", "threshold": "BLOCK_NONE"},{"category": "HARM_CATEGORY_DANGEROUS_CONTENT", "threshold": "BLOCK_NONE"},]async def event_stream():yielded = Falsetry:model = genai.GenerativeModel(model_name=model_name,system_instruction=payload.systemPrompt or "",safety_settings=safety,)history: list[dict[str, Any]] = []for msg in payload.history[-MAX_HISTORY:]:role = "user" if msg.role == "user" else "model"if not history or history[-1]["role"] != role:history.append({"role": role, "parts": [msg.text or "[imagen]"]})chat = model.start_chat(history=history)content: list[Any] = []if img_bytes is not None:content.append({"mime_type": "image/jpeg", "data": img_bytes})content.append(payload.userText or "Analiza esta imagen")response = await chat.send_message_async(content,stream=True,request_options={"timeout": HTTP_TIMEOUT_SECONDS},)async for chunk in response:text = getattr(chunk, "text", None)if text:yielded = Trueyield _sse({"delta": text})yield _sse({"done": True,"remaining": quota["remaining"],"model": model_name,})logger.info("Gemini stream OK model=%s", model_name, extra=extra)except google_exceptions.ResourceExhausted:if not yielded:_decrement_quota(uid)logger.warning("Gemini stream rate limit", extra=extra)yield _sse({"error": "upstream_rate_limit", "retryable": True})except google_exceptions.DeadlineExceeded:if not yielded:_decrement_quota(uid)logger.warning("Gemini stream timeout", extra=extra)yield _sse({"error": "timeout", "retryable": True})except (google_exceptions.InvalidArgument,google_exceptions.PermissionDenied,google_exceptions.GoogleAPICallError,) as exc:if not yielded:_decrement_quota(uid)logger.error("Gemini stream upstream error: %s", exc, extra=extra)yield _sse({"error": "upstream_error", "message": str(exc)})except Exception as exc:if not yielded:_decrement_quota(uid)logger.exception("Gemini stream error inesperado", extra=extra)yield _sse({"error": "internal", "message": type(exc).__name__})return StreamingResponse(event_stream(),media_type="text/event-stream",headers=SSE_HEADERS,)@app.get("/")4 unmodified lines"firebase": db is not None,"firebase_error": firebase_error,"claude": claude_client is not None,"gemini": GEMINI_API_KEY is not None,"streaming": True,"time": datetime.now(BOGOTA_TZ).isoformat(),}1 unmodified line@app.get("/healthz")def healthz():return {"ok": True}12343 unmodified lines89101112138 unmodified lines22232425262728293028 unmodified lines59606162636465666768697017 unmodified lines888990919293945 unmodified lines10010110210310410510610710810911011111211311411511611711811978 unmodified lines1981992002012022037 unmodified lines21121221321421521621721821922022137 unmodified lines25926026126226326426526626726826927027127227327421 unmodified lines2962972982993003013023033043053063 unmodified lines3103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473484 unmodified lines3533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344351 unmodified line4374384394404414424434444454464474484494504514 unmodified lines45645745845946046146246346446546630 unmodified lines49749849950050150250316 unmodified lines5205215225235245255266 unmodified lines5335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286294 unmodified lines6346356366376386396401 unmodified line642643644645import asyncioimport base64import jsonimport logging3 unmodified linesfrom typing import Any, Optionalimport firebase_adminimport pytzfrom anthropic import (APIConnectionError,8 unmodified linesfrom fastapi.middleware.cors import CORSMiddlewarefrom fastapi.responses import JSONResponse, StreamingResponsefrom firebase_admin import auth, credentials, firestorefrom google import genai as google_genaifrom google.genai import errors as genai_errorsfrom google.genai import types as genai_typesfrom pydantic import BaseModel, Field, field_validator# --- Logging con request_id ---28 unmodified linesALLOWED_GEMINI_MODELS = {"gemini-2.5-flash","gemini-2.5-pro",}AI_DAILY_LIMITS = {"free": 5, "pro": 50, "proTecnico": 200}DEFAULT_AI_PLAN = "free"# --- Estado global tolerante a fallos en boot ---db: Optional[firestore.Client] = Nonefirebase_error: Optional[str] = None17 unmodified lineselse:db = firestore.client()# --- Clientes externos ---CLAUDE_API_KEY = os.environ.get("CLAUDE_API_KEY")GEMINI_API_KEY = os.environ.get("GEMINI_API_KEY")5 unmodified linesclaude_client: Optional[AsyncAnthropic] = Noneif CLAUDE_API_KEY:try:claude_client = AsyncAnthropic(api_key=CLAUDE_API_KEY, timeout=HTTP_TIMEOUT_SECONDS)except Exception as exc:logger.exception("No se pudo crear cliente Anthropic: %s", exc)gemini_client: Optional[google_genai.Client] = Noneif GEMINI_API_KEY:try:gemini_client = google_genai.Client(api_key=GEMINI_API_KEY)logger.info("Cliente Gemini (google-genai) inicializado, model=%s", DEFAULT_GEMINI_MODEL)except Exception as exc:logger.exception("No se pudo crear cliente Gemini: %s", exc)# --- App ---app = FastAPI(title="Surco AI Proxy", version="2.2.0")app.add_middleware(CORSMiddleware,78 unmodified lineslimit = AI_DAILY_LIMITS.get(plan, 5)today = datetime.now(BOGOTA_TZ).strftime("%Y-%m-%d")if db is None:return {"allowed": True, "remaining": limit, "plan": plan}ref = (db.collection("users")7 unmodified linessnap = ref.get(transaction=transaction)current = (snap.to_dict() or {}).get("count", 0) if snap.exists else 0if current >= limit:return {"allowed": False, "limit": limit, "plan": plan, "used": current}new_count = current + 1transaction.set(ref,{"count": new_count, "limit": limit, "plan": plan, "date": today},merge=True,)return {"allowed": True, "remaining": limit - new_count, "plan": plan}37 unmodified lines)def _gemini_safety() -> list[genai_types.SafetySetting]:return [genai_types.SafetySetting(category="HARM_CATEGORY_HARASSMENT", threshold="BLOCK_NONE"),genai_types.SafetySetting(category="HARM_CATEGORY_HATE_SPEECH", threshold="BLOCK_NONE"),genai_types.SafetySetting(category="HARM_CATEGORY_SEXUALLY_EXPLICIT", threshold="BLOCK_NONE"),genai_types.SafetySetting(category="HARM_CATEGORY_DANGEROUS_CONTENT", threshold="BLOCK_NONE"),]# --- Endpoints Claude ---@app.post("/claude")async def claude_proxy(request: Request,21 unmodified linesuser_content: list[dict[str, Any]] = []if payload.imageBase64:user_content.append({"type": "image","source": {"type": "base64", "media_type": "image/jpeg", "data": payload.imageBase64},})user_content.append({"type": "text", "text": payload.userText or "Analiza esta imagen"})messages.append({"role": "user", "content": user_content})res = await claude_client.messages.create(3 unmodified linesmessages=messages,)text_blocks = [b.text for b in res.content if getattr(b, "type", None) == "text"]if not text_blocks:_decrement_quota(uid)raise HTTPException(status_code=502, detail="Respuesta vacía del modelo")logger.info("Claude OK model=%s remaining=%s", model, quota["remaining"], extra=extra)return {"text": "\n".join(text_blocks), "remaining": quota["remaining"], "model": model}except RateLimitError:_decrement_quota(uid)logger.warning("Claude upstream rate limit", extra=extra)return JSONResponse(status_code=429, content={"error": "upstream_rate_limit", "message": "El proveedor está saturado"})except BadRequestError as exc:_decrement_quota(uid)raise HTTPException(status_code=400, detail=f"Solicitud inválida: {exc.message}") from excexcept AuthenticationError as exc:_decrement_quota(uid)raise HTTPException(status_code=502, detail="Error de autenticación con el proveedor") from excexcept (APITimeoutError, APIConnectionError) as exc:_decrement_quota(uid)raise HTTPException(status_code=504, detail="Tiempo de espera agotado") from excexcept APIStatusError as exc:_decrement_quota(uid)raise HTTPException(status_code=502, detail="Error del proveedor") from excexcept HTTPException:raiseexcept Exception as exc:_decrement_quota(uid)logger.exception("Claude error inesperado", extra=extra)raise HTTPException(status_code=500, detail=f"Error interno: {type(exc).__name__}") from exc# --- Endpoints Gemini ---@app.post("/gemini")async def gemini_proxy(request: Request,4 unmodified linesextra = {"request_id": rid}uid = user["uid"]if not gemini_client:raise HTTPException(status_code=503, detail="Gemini no disponible")quota = _check_and_increment_quota(uid)if not quota["allowed"]:return _quota_response(quota)model_name = DEFAULT_GEMINI_MODELlogger.info("Gemini model=%s uid=%s", model_name, uid, extra=extra)try:contents: list[dict[str, Any]] = []for msg in payload.history[-MAX_HISTORY:]:role = "user" if msg.role == "user" else "model"contents.append({"role": role, "parts": [{"text": msg.text or "[imagen]"}]})current_parts: list[Any] = []if payload.imageBase64:try:img_bytes = base64.b64decode(payload.imageBase64, validate=True)except Exception as exc:_decrement_quota(uid)raise HTTPException(status_code=400, detail=f"imageBase64 inválido: {exc}") from exccurrent_parts.append({"inline_data": {"mime_type": "image/jpeg", "data": img_bytes}})current_parts.append({"text": payload.userText or "Analiza esta imagen"})contents.append({"role": "user", "parts": current_parts})config = genai_types.GenerateContentConfig(system_instruction=payload.systemPrompt or None,safety_settings=_gemini_safety(),)text: Optional[str] = Nonelast_rate_exc: Optional[Exception] = Nonefor attempt in range(3):if attempt > 0:await asyncio.sleep(2 ** (attempt - 1))try:response = await gemini_client.aio.models.generate_content(model=model_name, contents=contents, config=config,)text = response.textlast_rate_exc = Nonebreakexcept genai_errors.APIError as exc:if exc.status_code == 429:last_rate_exc = exclogger.warning("Gemini rate limit attempt %d/3", attempt + 1, extra=extra)else:raiseif last_rate_exc is not None:_decrement_quota(uid)return JSONResponse(status_code=429, content={"error": "upstream_rate_limit", "message": "El proveedor está saturado"})if not text:_decrement_quota(uid)raise HTTPException(status_code=502, detail="Respuesta vacía del modelo")logger.info("Gemini OK model=%s remaining=%s", model_name, quota["remaining"], extra=extra)return {"text": text, "remaining": quota["remaining"], "model": model_name}except genai_errors.APIError as exc:_decrement_quota(uid)if exc.status_code in (401, 403):raise HTTPException(status_code=502, detail="Error de autenticación con el proveedor") from exclogger.error("Gemini API error %s: %s", exc.status_code, exc, extra=extra)raise HTTPException(status_code=502, detail="Error del proveedor") from excexcept HTTPException:raiseexcept Exception as exc:_decrement_quota(uid)logger.exception("Gemini error inesperado", extra=extra)raise HTTPException(status_code=500, detail=f"Error interno: {type(exc).__name__}") from exc# --- SSE helpers ---SSE_HEADERS = {"Cache-Control": "no-cache, no-transform","X-Accel-Buffering": "no",1 unmodified line"Content-Type": "text/event-stream; charset=utf-8",}# 2KB padding para vencer el buffering de proxies/edge._SSE_PADDING = ": " + ("surco" * 400) + "\n\n"def _sse(event: dict) -> str:return f"data: {json.dumps(event, ensure_ascii=False)}\n\n"def _build_claude_messages(payload: AIRequest) -> list[dict[str, Any]]:messages: list[dict[str, Any]] = []for msg in payload.history[-MAX_HISTORY:]:role = "user" if msg.role == "user" else "assistant"4 unmodified linesuser_content: list[dict[str, Any]] = []if payload.imageBase64:user_content.append({"type": "image","source": {"type": "base64", "media_type": "image/jpeg", "data": payload.imageBase64},})user_content.append({"type": "text", "text": payload.userText or "Analiza esta imagen"})messages.append({"role": "user", "content": user_content})return messages30 unmodified linesasync for text in stream.text_stream:yielded = Trueyield _sse({"delta": text})yield _sse({"done": True, "remaining": quota["remaining"], "model": model})logger.info("Claude stream OK model=%s", model, extra=extra)except RateLimitError:if not yielded:16 unmodified lineslogger.exception("Claude stream error inesperado", extra=extra)yield _sse({"error": "internal", "message": type(exc).__name__})return StreamingResponse(event_stream(), media_type="text/event-stream", headers=SSE_HEADERS)@app.post("/gemini/stream")6 unmodified linesextra = {"request_id": rid}uid = user["uid"]if not gemini_client:raise HTTPException(status_code=503, detail="Gemini no disponible")quota = _check_and_increment_quota(uid)if not quota["allowed"]:return _quota_response(quota)model_name = DEFAULT_GEMINI_MODELlogger.info("Gemini stream model=%s uid=%s", model_name, uid, extra=extra)img_bytes: Optional[bytes] = Noneif payload.imageBase64:try:img_bytes = base64.b64decode(payload.imageBase64, validate=True)except Exception as exc:_decrement_quota(uid)raise HTTPException(status_code=400, detail=f"imageBase64 inválido: {exc}") from exccontents: list[dict[str, Any]] = []for msg in payload.history[-MAX_HISTORY:]:role = "user" if msg.role == "user" else "model"if not contents or contents[-1]["role"] != role:contents.append({"role": role, "parts": [{"text": msg.text or "[imagen]"}]})current_parts: list[Any] = []if img_bytes is not None:current_parts.append({"inline_data": {"mime_type": "image/jpeg", "data": img_bytes}})current_parts.append({"text": payload.userText or "Analiza esta imagen"})contents.append({"role": "user", "parts": current_parts})config = genai_types.GenerateContentConfig(system_instruction=payload.systemPrompt or None,safety_settings=_gemini_safety(),)async def event_stream():yield _SSE_PADDINGyield _sse({"start": True, "model": model_name})await asyncio.sleep(0)yielded = Falselast_rate_exc: Optional[Exception] = Nonefor attempt in range(3):if attempt > 0:await asyncio.sleep(2 ** (attempt - 1))last_rate_exc = Nonetry:async for chunk in gemini_client.aio.models.generate_content_stream(model=model_name, contents=contents, config=config,):if chunk.text:yielded = Trueyield _sse({"delta": chunk.text})await asyncio.sleep(0)yield _sse({"done": True, "remaining": quota["remaining"], "model": model_name})logger.info("Gemini stream OK model=%s", model_name, extra=extra)returnexcept genai_errors.APIError as exc:if exc.status_code == 429:last_rate_exc = excif yielded:breaklogger.warning("Gemini stream rate limit attempt %d/3", attempt + 1, extra=extra)else:if not yielded:_decrement_quota(uid)logger.error("Gemini stream API error %s: %s", exc.status_code, exc, extra=extra)yield _sse({"error": "upstream_error", "message": str(exc)})returnexcept asyncio.TimeoutError:if not yielded:_decrement_quota(uid)logger.warning("Gemini stream timeout", extra=extra)yield _sse({"error": "timeout", "retryable": True})returnexcept Exception as exc:if not yielded:_decrement_quota(uid)logger.exception("Gemini stream error inesperado", extra=extra)yield _sse({"error": "internal", "message": type(exc).__name__})returnif not yielded:_decrement_quota(uid)logger.warning("Gemini stream rate limit exhausted", extra=extra)yield _sse({"error": "upstream_rate_limit", "retryable": True})return StreamingResponse(event_stream(), media_type="text/event-stream", headers=SSE_HEADERS)@app.get("/")4 unmodified lines"firebase": db is not None,"firebase_error": firebase_error,"claude": claude_client is not None,"gemini": gemini_client is not None,"streaming": True,"time": datetime.now(BOGOTA_TZ).isoformat(),}1 unmodified line@app.get("/healthz")def healthz():return {"ok": True}
main.py+162-226