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 lines161718192021222315 unmodified linesGROQ_API_KEY=your-groq-api-keyGROQ_MODEL=your-groq-tool-calling-modelGEMINI_API_KEY=your-gemini-api-keyGEMINI_MODEL=gemini-2.0-flashAI_TEMPERATURE=0.2AI_MAX_TOOL_ITERATIONS=3REQUEST_TIMEOUT_SECONDS=2015 unmodified lines161718192021222315 unmodified linesGROQ_API_KEY=your-groq-api-keyGROQ_MODEL=your-groq-tool-calling-modelOPENROUTER_API_KEY=your-openrouter-api-keyOPENROUTER_MODEL=openrouter/freeAI_TEMPERATURE=0.2AI_MAX_TOOL_ITERATIONS=3REQUEST_TIMEOUT_SECONDS=20
1234from app.ai.orchestrator import AIOrchestratorfrom app.ai.providers import GeminiChatProvider, GroqChatProvider__all__ = ["AIOrchestrator", "GroqChatProvider", "GeminiChatProvider"]1234from app.ai.orchestrator import AIOrchestratorfrom app.ai.providers import GroqChatProvider, OpenRouterChatProvider__all__ = ["AIOrchestrator", "GroqChatProvider", "OpenRouterChatProvider"]
51 unmodified lines52535455565758596028 unmodified lines89909192939495969751 unmodified linestemperature=max(temperature - 0.2, 0.1),)except RetryableProviderError:logger.warning("Primary retry failed; falling back to Gemini")except RetryableProviderError:logger.warning("Primary provider failed; falling back to Gemini")return await self.fallback.chat(messages,28 unmodified linestemperature=max(self.temperature - 0.2, 0.1),)except RetryableProviderError:logger.warning("Primary retry failed; falling back to Gemini")except RetryableProviderError:logger.warning("Primary provider failed; falling back to Gemini")return await self._run_provider(self.fallback,51 unmodified lines52535455565758596028 unmodified lines89909192939495969751 unmodified linestemperature=max(temperature - 0.2, 0.1),)except RetryableProviderError:logger.warning("Primary retry failed; falling back to OpenRouter")except RetryableProviderError:logger.warning("Primary provider failed; falling back to OpenRouter")return await self.fallback.chat(messages,28 unmodified linestemperature=max(self.temperature - 0.2, 0.1),)except RetryableProviderError:logger.warning("Primary retry failed; falling back to OpenRouter")except RetryableProviderError:logger.warning("Primary provider failed; falling back to OpenRouter")return await self._run_provider(self.fallback,
123493 unmodified lines989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115223 unmodified lines176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297import jsonfrom typing import Any, Protocolfrom app.config import Settings93 unmodified lines)class GeminiChatProvider:name = "gemini"def __init__(self, settings: Settings) -> None:self.api_key = settings.gemini_api_keyself.model = settings.gemini_modelself.timeout = settings.request_timeout_secondsself._client: Any | None = None@propertydef client(self) -> Any:if self._client is None:from google import genaiself._client = genai.Client(api_key=self.api_key)return self._clientasync 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 typestry: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.AUTOif 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: BLE001raise _provider_error_from_exception(exc, self.name) from excdef _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 typesdeclarations = []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 typescontents = []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", "{}")),)],))continueparts: 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 contentsdef _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.textelif part.function_call:fc = part.function_callargs = 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_contentif 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)12393 unmodified lines97989910010110210310410510610710810911011123 unmodified lines135136137138139140from typing import Any, Protocolfrom app.config import Settings93 unmodified lines)class OpenRouterChatProvider(OpenAICompatibleChatProvider):def __init__(self, settings: Settings) -> None: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 _provider_error_from_exception(exc: Exception, provider_name: str) -> ProviderError:status_code = getattr(exc, "status_code", None)body = getattr(exc, "body", None)
31 unmodified lines323334353637383931 unmodified linesgroq_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)ai_temperature: float = 0.2ai_max_tool_iterations: int = 3request_timeout_seconds: float = 20.031 unmodified lines323334353637383931 unmodified linesgroq_api_key: str = Field(min_length=1)groq_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.2ai_max_tool_iterations: int = 3request_timeout_seconds: float = 20.0
123456722 unmodified lines30313233343536from dataclasses import dataclassfrom app.ai.orchestrator import AIOrchestratorfrom app.ai.providers import GeminiChatProvider, GroqChatProviderfrom app.config import Settingsfrom app.database.supabase import SupabaseRepository, create_supabase_clientfrom app.services.admin_service import AdminService22 unmodified lineswhatsapp = WhatsAppClient(settings)ai = AIOrchestrator(primary=GroqChatProvider(settings),fallback=GeminiChatProvider(settings),temperature=settings.ai_temperature,max_tool_iterations=settings.ai_max_tool_iterations,)123456722 unmodified lines30313233343536from dataclasses import dataclassfrom app.ai.orchestrator import AIOrchestratorfrom 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 lineswhatsapp = WhatsAppClient(settings)ai = AIOrchestrator(primary=GroqChatProvider(settings),fallback=OpenRouterChatProvider(settings),temperature=settings.ai_temperature,max_tool_iterations=settings.ai_max_tool_iterations,)
233 unmodified lines234235236237238239240233 unmodified linescustomer_id=str(customer["id"]),sender_type="assistant",message=reply,metadata={"provider_flow": "groq_primary_gemini_fallback", "user_mode": user_mode},)if is_returning_driver:233 unmodified lines234235236237238239240233 unmodified linescustomer_id=str(customer["id"]),sender_type="assistant",message=reply,metadata={"provider_flow": "groq_primary_openrouter_fallback", "user_mode": user_mode},)if is_returning_driver:
8 unmodified lines91011121314158 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",]8 unmodified lines910111213148 unmodified lines"pydantic-settings>=2.4.0","supabase>=2.6.0","openai>=1.40.0","httpx>=0.27.0","python-dotenv>=1.0.1",]
2 unmodified lines34567892 unmodified linespydantic-settings>=2.4.0supabase>=2.6.0openai>=1.40.0google-genai>=1.0.0httpx>=0.27.0python-dotenv>=1.0.12 unmodified lines3456782 unmodified linespydantic-settings>=2.4.0supabase>=2.6.0openai>=1.40.0httpx>=0.27.0python-dotenv>=1.0.1
19 unmodified lines202122232425262719 unmodified linesjina_api_key="jina-secret",groq_api_key="groq-secret",groq_model="groq-tool-model",gemini_api_key="gemini-secret",gemini_model="gemini-tool-model",whatsapp_verify_token="verify-token",whatsapp_app_secret="app-secret",whatsapp_access_token="wa-token",19 unmodified lines202122232425262719 unmodified linesjina_api_key="jina-secret",groq_api_key="groq-secret",groq_model="groq-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 lines3132333435363718 unmodified lines5657585960616279 unmodified lines14214314414514614714813 unmodified lines16216316416516616716819 unmodified lines18818919019119219319430 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")])registry = ToolRegistry()orchestrator = AIOrchestrator(primary=primary,18 unmodified linesAIProviderResponse(content="primary retry reply"),],)fallback = ScriptedProvider("gemini", [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")])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")])orchestrator = AIOrchestrator(primary=primary,fallback=fallback,19 unmodified linesAIProviderResponse(content="primary retry reply"),],)fallback = ScriptedProvider("gemini", [AIProviderResponse(content="fallback")])orchestrator = AIOrchestrator(primary=primary,fallback=fallback,30 unmodified lines3132333435363718 unmodified lines5657585960616279 unmodified lines14214314414514614714813 unmodified lines16216316416516616716819 unmodified lines18818919019119219319430 unmodified lines@pytest.mark.asyncioasync def test_ai_falls_back_when_primary_rate_limited():primary = ScriptedProvider("groq", [RetryableProviderError("rate limited")])fallback = ScriptedProvider("openrouter", [AIProviderResponse(content="fallback reply")])registry = ToolRegistry()orchestrator = AIOrchestrator(primary=primary,18 unmodified linesAIProviderResponse(content="primary retry reply"),],)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("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("openrouter", [AIProviderResponse(content="fallback")])orchestrator = AIOrchestrator(primary=primary,fallback=fallback,19 unmodified linesAIProviderResponse(content="primary retry reply"),],)fallback = ScriptedProvider("openrouter", [AIProviderResponse(content="fallback")])orchestrator = AIOrchestrator(primary=primary,fallback=fallback,
35 unmodified lines363738394041424335 unmodified linesjina_api_key="jina-secret",groq_api_key="groq-secret",groq_model="groq-tool-model",gemini_api_key="gemini-secret",gemini_model="gemini-tool-model",whatsapp_verify_token="verify-token",whatsapp_app_secret="app-secret",whatsapp_access_token="wa-token",35 unmodified lines363738394041424335 unmodified linesjina_api_key="jina-secret",groq_api_key="groq-secret",groq_model="groq-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