Spaces:
Running
Running
axeronis commited on
Commit Β·
db1017d
1
Parent(s): f754762
fix: Implement robust fallback for Gemini Caching (429 Quota) and switch to 1.5-flash
Browse filesFiles changed (3)
86 unmodified lines8788899091929394959697989986 unmodified lines# 5. Format conversation historychat_history = self._format_chat_history(conversation_history)# 6. Generate response utilizing CACHE# We pass 'dynamic_context' as system_instruction.# If cache covers the main persona, this instruction acts as the "Session Briefing".response = await self.llm.generate_response(prompt=user_message,system_instruction=dynamic_context,context=cache_name, # THE CACHE KEYchat_history=chat_history)86 unmodified lines8788899091929394959697989910010110210310410510610710810986 unmodified lines# 5. Format conversation historychat_history = self._format_chat_history(conversation_history)# 6. Generate response utilizing CACHE or FALLBACK# We pass 'dynamic_context' as system_instruction.# If cache covers the main persona, this instruction acts as the "Session Briefing".final_system_instruction = dynamic_contextif not cache_name:# FALLBACK: Memory Creation Failed (Quota/Auth) -> Inject Manually# This ensures the bot is not lobotomized if caching fails.print("β οΈ Memory Cache missing/failed. Injecting full context manually (Standard RAG).")full_static_context = await memory_manager.build_tenant_context(session, tenant)final_system_instruction = full_static_context + "\n\n" + dynamic_contextresponse = await self.llm.generate_response(prompt=user_message,system_instruction=final_system_instruction,context=cache_name, # THE CACHE KEY (or None)chat_history=chat_history)
73 unmodified lines747576777879808182838485868710 unmodified lines989910010110210373 unmodified linesawait self.invalidate_memory(session, tenant)# 2. BUILD CONTEXT ( The "Huge Prompt" )system_instruction = await self._build_huge_context(session, tenant)token_count = len(system_instruction) // 4 # Rough estimatelogger.info(f"π Compiled Context Size: ~{len(system_instruction)} chars (~{token_count} tokens)")# 3. UPLOAD TO GOOGLE CACHE# TTL: 1 hour (standard). We will refresh it on activity.cache = caching.CachedContent.create(model='models/gemini-2.5-flash',display_name=f"tenant_{tenant.id}_{int(datetime.now().timestamp())}",system_instruction=system_instruction,ttl=timedelta(minutes=60),10 unmodified linesexcept Exception as e:logger.error(f"β Failed to create AI Memory: {e}")import tracebacktraceback.print_exc()return None73 unmodified lines74757677787980818283848586878810 unmodified lines9910010110210310410510610773 unmodified linesawait self.invalidate_memory(session, tenant)# 2. BUILD CONTEXT ( The "Huge Prompt" )system_instruction = await self.build_tenant_context(session, tenant)token_count = len(system_instruction) // 4 # Rough estimatelogger.info(f"π Compiled Context Size: ~{len(system_instruction)} chars (~{token_count} tokens)")# 3. UPLOAD TO GOOGLE CACHE# TTL: 1 hour (standard). We will refresh it on activity.# Use 1.5-flash-001 for better free tier limitscache = caching.CachedContent.create(model='models/gemini-1.5-flash-001',display_name=f"tenant_{tenant.id}_{int(datetime.now().timestamp())}",system_instruction=system_instruction,ttl=timedelta(minutes=60),10 unmodified linesexcept Exception as e:logger.error(f"β Failed to create AI Memory: {e}")# If we fail (Quota exceeded, API error), return None.# The caller (AI Core) must handle this by falling back to standard prompt injection.return Noneimport tracebacktraceback.print_exc()return None
35 unmodified lines3637383940414235 unmodified linesgenai.configure(api_key=settings.GEMINI_API_KEY)# NOTE: gemini-2.5-flash currently has very low RPM (5) in preview/free tier.self.default_model_name = "gemini-2.5-flash"self.ai_queue = get_ai_queue() # Rate limiting queuelogger.info(f"β Gemini LLM client initialized (model: {self.default_model_name})")35 unmodified lines3637383940414235 unmodified linesgenai.configure(api_key=settings.GEMINI_API_KEY)# NOTE: gemini-2.5-flash currently has very low RPM (5) in preview/free tier.self.default_model_name = "gemini-1.5-flash-001"self.ai_queue = get_ai_queue() # Rate limiting queuelogger.info(f"β Gemini LLM client initialized (model: {self.default_model_name})")
backend/app/services/ai_core.py+13-3
backend/app/services/ai_memory_manager.py+6-2
backend/app/services/llm_client.py+1-1