feat: replace Gemini with OpenRouter as fallback AI provider
Browse filesFiles changed (12)
- .env.example+2-2
- app/ai/__init__.py+2-2
- app/ai/orchestrator.py+4-4
- app/ai/providers.py+8-165
- app/config.py+2-2
- app/services/container.py+2-2
- app/services/conversation_service.py+1-1
- pyproject.toml-1
- requirements.txt-1
- tests/conftest.py+2-2
- tests/test_ai_orchestrator.py+5-5
- tests/test_group_message_service.py+2-2
15 unmodified lines1617181920192021222315 unmodified lines
GROQ_API_KEY=your-groq-api-keyGROQ_MODEL=your-groq-tool-calling-modelGEMINI_API_KEY=your-gemini-api-keyGEMINI_MODEL=gemini-2.0-flashOPENROUTER_API_KEY=your-openrouter-api-keyOPENROUTER_MODEL=openrouter/freeAI_TEMPERATURE=0.2AI_MAX_TOOL_ITERATIONS=3REQUEST_TIMEOUT_SECONDS=20122344from app.ai.orchestrator import AIOrchestratorfrom app.ai.providers import GeminiChatProvider, GroqChatProviderfrom app.ai.providers import GroqChatProvider, OpenRouterChatProvider
__all__ = ["AIOrchestrator", "GroqChatProvider", "GeminiChatProvider"]__all__ = ["AIOrchestrator", "GroqChatProvider", "OpenRouterChatProvider"]51 unmodified lines525354555556575758596028 unmodified lines899091929293949495969751 unmodified lines temperature=max(temperature - 0.2, 0.1), ) except RetryableProviderError: logger.warning("Primary retry failed; falling back to Gemini") logger.warning("Primary retry failed; falling back to OpenRouter") except RetryableProviderError: logger.warning("Primary provider failed; falling back to Gemini") logger.warning("Primary provider failed; falling back to OpenRouter")
return await self.fallback.chat( messages,28 unmodified lines temperature=max(self.temperature - 0.2, 0.1), ) except RetryableProviderError: logger.warning("Primary retry failed; falling back to Gemini") logger.warning("Primary retry failed; falling back to OpenRouter") except RetryableProviderError: logger.warning("Primary provider failed; falling back to Gemini") logger.warning("Primary provider failed; falling back to OpenRouter")
return await self._run_provider( self.fallback,112393 unmodified lines97989910110210310010110510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814910210310410510610710810911011123 unmodified lines135136137179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294138139140import jsonfrom typing import Any, Protocol
from app.config import Settings93 unmodified lines )
class GeminiChatProvider: name = "gemini"
class OpenRouterChatProvider(OpenAICompatibleChatProvider): def __init__(self, settings: Settings) -> None: self.api_key = settings.gemini_api_key self.model = settings.gemini_model self.timeout = settings.request_timeout_seconds self._client: Any | None = None
@property def client(self) -> Any: if self._client is None: from google import genai
self._client = genai.Client(api_key=self.api_key) return self._client
async def chat( self, messages: list[dict[str, Any]], *, tools: list[dict[str, Any]] | None = None, tool_choice: str | dict[str, Any] | None = "auto", temperature: float = 0.2, ) -> AIProviderResponse: from google.genai import types
try: contents = _convert_messages_to_gemini(messages) config_kwargs: dict[str, Any] = {"temperature": temperature} if tools: config_kwargs["tools"] = _convert_tools_to_gemini(tools) if tool_choice and tool_choice != "none": config_kwargs["tool_config"] = types.ToolConfig( function_calling_config=types.FunctionCallingConfig( mode=types.FunctionCallingConfig.Mode.AUTO if tool_choice == "auto" else types.FunctionCallingConfig.Mode.ANY, ) ) config = types.GenerateContentConfig(**config_kwargs) response = await self.client.aio.models.generate_content( model=self.model, contents=contents, config=config, ) return _parse_gemini_response(response) except Exception as exc: # noqa: BLE001 raise _provider_error_from_exception(exc, self.name) from exc super().__init__( api_key=settings.openrouter_api_key, base_url="https://openrouter.ai/api/v1", model=settings.openrouter_model, timeout=settings.request_timeout_seconds, name="openrouter", )
def _normalize_openai_message(message: Any) -> AIProviderResponse:23 unmodified lines )
def _convert_tools_to_gemini(tools: list[dict[str, Any]]) -> list[Any]: from google.genai import types
declarations = [] for tool in tools: func = tool.get("function", {}) params = func.get("parameters", {}) declarations.append( types.FunctionDeclaration( name=func.get("name", ""), description=func.get("description", ""), parameters=params if params else None, ) ) return [types.Tool(function_declarations=declarations)]
def _convert_messages_to_gemini(messages: list[dict[str, Any]]) -> list[Any]: from google.genai import types
contents = [] pending_tool_calls: dict[str, dict[str, Any]] = {}
for msg in messages: role = msg.get("role", "user")
if role == "tool": tool_call_id = msg.get("tool_call_id", "") if tool_call_id in pending_tool_calls: tc = pending_tool_calls.pop(tool_call_id) contents.append( types.Content( role="user", parts=[ types.Part.from_function_response( name=tc["name"], response=json.loads(msg.get("content", "{}")), ) ], ) ) continue
parts: list[Any] = [] content = msg.get("content") if content: parts.append(types.Part(text=content))
tool_calls = msg.get("tool_calls") or [] for tc in tool_calls: func = tc.get("function", {}) args = func.get("arguments", "{}") try: parsed_args = json.loads(args) except (json.JSONDecodeError, TypeError): parsed_args = {} parts.append( types.Part.from_function_call( name=func.get("name", ""), args=parsed_args, ) ) pending_tool_calls[tc.get("id", "")] = { "name": func.get("name", ""), }
if parts: gemini_role = "model" if role == "assistant" else "user" contents.append(types.Content(role=gemini_role, parts=parts))
return contents
def _parse_gemini_response(response: Any) -> AIProviderResponse: text_content = "" tool_calls: list[ToolCall] = [] raw_message: dict[str, Any] = {}
if not response.candidates: return AIProviderResponse( content=text_content, tool_calls=tool_calls, raw_message=raw_message )
candidate = response.candidates[0] parts = candidate.content.parts if candidate.content else []
for part in parts: if part.text: text_content += part.text elif part.function_call: fc = part.function_call args = dict(fc.args) if fc.args else {} tool_calls.append( ToolCall( id=fc.name, name=fc.name, arguments=json.dumps(args, ensure_ascii=False), ) )
raw_message["role"] = "assistant" if text_content: raw_message["content"] = text_content if tool_calls: raw_message["tool_calls"] = [ { "id": tc.id, "type": "function", "function": {"name": tc.name, "arguments": tc.arguments}, } for tc in tool_calls ]
return AIProviderResponse(content=text_content, tool_calls=tool_calls, raw_message=raw_message)
def _provider_error_from_exception(exc: Exception, provider_name: str) -> ProviderError: status_code = getattr(exc, "status_code", None) body = getattr(exc, "body", None)31 unmodified lines3233343536353637383931 unmodified lines
groq_api_key: str = Field(min_length=1) groq_model: str = Field(min_length=1) gemini_api_key: str = Field(min_length=1) gemini_model: str = Field(min_length=1) openrouter_api_key: str = Field(min_length=1) openrouter_model: str = Field(min_length=1) ai_temperature: float = 0.2 ai_max_tool_iterations: int = 3 request_timeout_seconds: float = 20.01234456722 unmodified lines3031323333343536from dataclasses import dataclass
from app.ai.orchestrator import AIOrchestratorfrom app.ai.providers import GeminiChatProvider, GroqChatProviderfrom app.ai.providers import GroqChatProvider, OpenRouterChatProviderfrom app.config import Settingsfrom app.database.supabase import SupabaseRepository, create_supabase_clientfrom app.services.admin_service import AdminService22 unmodified lines whatsapp = WhatsAppClient(settings) ai = AIOrchestrator( primary=GroqChatProvider(settings), fallback=GeminiChatProvider(settings), fallback=OpenRouterChatProvider(settings), temperature=settings.ai_temperature, max_tool_iterations=settings.ai_max_tool_iterations, )233 unmodified lines234235236237237238239240233 unmodified lines customer_id=str(customer["id"]), sender_type="assistant", message=reply, metadata={"provider_flow": "groq_primary_gemini_fallback", "user_mode": user_mode}, metadata={"provider_flow": "groq_primary_openrouter_fallback", "user_mode": user_mode}, )
if is_returning_driver:8 unmodified lines91011121213148 unmodified lines "pydantic-settings>=2.4.0", "supabase>=2.6.0", "openai>=1.40.0", "google-genai>=1.0.0", "httpx>=0.27.0", "python-dotenv>=1.0.1",]2 unmodified lines34566782 unmodified linespydantic-settings>=2.4.0supabase>=2.6.0openai>=1.40.0google-genai>=1.0.0httpx>=0.27.0python-dotenv>=1.0.1
19 unmodified lines2021222324232425262719 unmodified lines jina_api_key="jina-secret", groq_api_key="groq-secret", groq_model="groq-tool-model", gemini_api_key="gemini-secret", gemini_model="gemini-tool-model", openrouter_api_key="openrouter-secret", openrouter_model="openrouter-tool-model", whatsapp_verify_token="verify-token", whatsapp_app_secret="app-secret", whatsapp_access_token="wa-token",30 unmodified lines313233343435363718 unmodified lines565758595960616279 unmodified lines14214314414514514614714813 unmodified lines16216316416516516616716819 unmodified lines18818919019119119219319430 unmodified lines@pytest.mark.asyncioasync def test_ai_falls_back_when_primary_rate_limited(): primary = ScriptedProvider("groq", [RetryableProviderError("rate limited")]) fallback = ScriptedProvider("gemini", [AIProviderResponse(content="fallback reply")]) fallback = ScriptedProvider("openrouter", [AIProviderResponse(content="fallback reply")]) registry = ToolRegistry() orchestrator = AIOrchestrator( primary=primary,18 unmodified lines AIProviderResponse(content="primary retry reply"), ], ) fallback = ScriptedProvider("gemini", [AIProviderResponse(content="fallback")]) fallback = ScriptedProvider("openrouter", [AIProviderResponse(content="fallback")]) orchestrator = AIOrchestrator( primary=primary, fallback=fallback,79 unmodified lines@pytest.mark.asyncioasync def test_chat_falls_back_when_primary_rate_limited(): primary = ScriptedProvider("groq", [RetryableProviderError("rate limited")]) fallback = ScriptedProvider("gemini", [AIProviderResponse(content="fallback reply")]) fallback = ScriptedProvider("openrouter", [AIProviderResponse(content="fallback reply")]) orchestrator = AIOrchestrator( primary=primary, fallback=fallback,13 unmodified lines@pytest.mark.asyncioasync def test_chat_returns_primary_on_success(): primary = ScriptedProvider("groq", [AIProviderResponse(content="primary reply")]) fallback = ScriptedProvider("gemini", [AIProviderResponse(content="fallback")]) fallback = ScriptedProvider("openrouter", [AIProviderResponse(content="fallback")]) orchestrator = AIOrchestrator( primary=primary, fallback=fallback,19 unmodified lines AIProviderResponse(content="primary retry reply"), ], ) fallback = ScriptedProvider("gemini", [AIProviderResponse(content="fallback")]) fallback = ScriptedProvider("openrouter", [AIProviderResponse(content="fallback")]) orchestrator = AIOrchestrator( primary=primary, fallback=fallback,35 unmodified lines3637383940394041424335 unmodified lines jina_api_key="jina-secret", groq_api_key="groq-secret", groq_model="groq-tool-model", gemini_api_key="gemini-secret", gemini_model="gemini-tool-model", openrouter_api_key="openrouter-secret", openrouter_model="openrouter-tool-model", whatsapp_verify_token="verify-token", whatsapp_app_secret="app-secret", whatsapp_access_token="wa-token",.env.example+2-2
app/ai/__init__.py+2-2
app/ai/orchestrator.py+4-4
app/ai/providers.py+8-165
app/config.py+2-2
app/services/container.py+2-2
app/services/conversation_service.py+1-1
pyproject.toml-1
requirements.txt-1
tests/conftest.py+2-2
tests/test_ai_orchestrator.py+5-5
tests/test_group_message_service.py+2-2