Coverage for src/local_deep_research/llm/providers/implementations/google.py: 100%
44 statements
« prev ^ index » next coverage.py v7.15.1, created at 2026-07-19 23:35 +0000
« prev ^ index » next coverage.py v7.15.1, created at 2026-07-19 23:35 +0000
1"""Google/Gemini LLM provider for Local Deep Research."""
3from ....security.secure_logging import logger
5from ....security.log_sanitizer import redact_secrets
6from ..base import Exposure
7from ..openai_base import OpenAICompatibleProvider
10class GoogleProvider(OpenAICompatibleProvider):
11 """Google Gemini provider using OpenAI-compatible endpoint.
13 This uses Google's OpenAI-compatible API endpoint to access Gemini models,
14 which automatically supports all current and future Gemini models without
15 needing to update the code.
16 """
18 provider_name = "Google Gemini"
19 api_key_setting = "llm.google.api_key"
20 default_base_url = "https://generativelanguage.googleapis.com/v1beta/openai"
21 default_model = "" # User must explicitly pick a model — no silent fallback
23 # Metadata for auto-discovery
24 provider_key = "GOOGLE"
25 company_name = "Google"
26 is_cloud = True
27 # Egress exposure (ADR-0007): cloud inference sink — data leaves the box.
28 egress_exposure = Exposure.EXPOSING
30 @classmethod
31 def requires_auth_for_models(cls):
32 """Google requires authentication for listing models.
34 Note: Google's OpenAI-compatible /models endpoint has a bug (returns 401).
35 The native Gemini API endpoint requires an API key.
36 """
37 return True
39 @classmethod
40 def list_models_for_api(cls, api_key=None, base_url=None):
41 """List available models using Google's native API.
43 Args:
44 api_key: Google API key
45 base_url: Not used - Google uses a fixed endpoint
47 Google's OpenAI-compatible /models endpoint returns 401 (bug),
48 so we use the native Gemini API endpoint instead.
49 """
50 if not api_key:
51 logger.debug("Google Gemini requires API key for listing models")
52 return []
54 try:
55 from ....security import safe_get
57 # Use the native Gemini API endpoint (not OpenAI-compatible).
58 # Pass the key via the x-goog-api-key header rather than a
59 # ?key=... query parameter so the secret never appears in the
60 # request URL — and therefore cannot leak into requests /
61 # urllib3 exception messages, which embed the URL but not
62 # headers. This is the prevention-by-construction control
63 # called for in issue #4184; the redact_secrets() wrap below
64 # remains as defense-in-depth.
65 url = "https://generativelanguage.googleapis.com/v1beta/models"
67 response = safe_get(
68 url,
69 headers={"x-goog-api-key": api_key},
70 timeout=10,
71 )
73 if response.status_code == 200:
74 data = response.json()
75 models = []
77 for model in data.get("models", []):
78 model_name = model.get("name", "")
79 # Extract just the model ID from "models/gemini-1.5-flash"
80 if model_name.startswith("models/"):
81 model_id = model_name[7:] # Remove "models/" prefix
82 else:
83 model_id = model_name
85 # Only include generative models (not embedding models)
86 supported_methods = model.get(
87 "supportedGenerationMethods", []
88 )
89 if "generateContent" in supported_methods and model_id:
90 models.append(
91 {
92 "value": model_id,
93 "label": model_id,
94 }
95 )
97 logger.info(
98 f"Found {len(models)} generative models from Google Gemini API"
99 )
100 return models
101 logger.warning(
102 f"Google Gemini API returned status {response.status_code}"
103 )
104 return []
106 except Exception as e:
107 # Defense-in-depth: the primary defense is now the
108 # x-goog-api-key header above (prevention by construction —
109 # the URL no longer carries the key, so requests/urllib3
110 # exception messages cannot embed it). This redact_secrets()
111 # wrap stays as a second layer in case a future code path
112 # reintroduces the key into a logged string, and we keep
113 # logger.warning rather than logger.exception so the
114 # exception chain (which carries the URL in earlier frames)
115 # is dropped. The redacted message is captured in a local
116 # before the logger call so the check-sensitive-logging
117 # pre-commit hook does not flag the exception variable as
118 # referenced inside the log call.
119 safe_msg = redact_secrets(str(e), api_key)
120 logger.warning(f"Error fetching Google Gemini models: {safe_msg}")
121 return []