JoeTach Claude Opus 4.7 commited on
Commit
0f51210
·
1 Parent(s): 78896de

Gemini: switch to gemini-2.0-flash; move key to header; redact errors

Browse files

Three issues surfaced in the live chat box on the HF Space, all from
the same Gemini call:

LLM provider 'gemini' is unavailable: Gemini call failed:
Client error '404 Not Found' for url
'https://generativelanguage.googleapis.com/v1beta/models/
gemini-1.5-flash:generateContent?key=AQ.Ab8RN6Ic8-CB7kqKS1-...

(1) Google retired the gemini-1.5 family in mid-2025; the endpoint
now returns 404 with a misleading 'model not found' wording.
Switching the DEFAULT_MODELS['gemini'] entry to the current
free-tier successor 'gemini-2.0-flash' (1M context, same JSON
structured-output behaviour) restores parsing.

(2) The provider was passing the key in the URL query string, so
httpx's HTTPStatusError quoted the FULL request URL including
?key=... into the exception message --- which surfaced verbatim
in the chat box and the build log. The key is now sent via the
'x-goog-api-key' HTTP header instead, so even when the next 4xx
fires the URL no longer carries the secret.

(3) Defence in depth: a small _redact_secrets() helper scrubs
'?key=' / '&key=' / 'Bearer ...' patterns out of any error string
before it is wrapped in LLMUnavailableError. The simulation
builder runs the same scrub a second time before appending notes
to the chat reply, so a future provider that forgets to redact
at the raise site still can't leak the key into the UI.

(4) A 404 from the Gemini endpoint now produces an actionable
message naming the three current free-tier models (2.0-flash,
2.0-flash-lite, 2.5-flash) and reminding the user to delete any
GEMINI_MODEL override pinned to a retired 1.5 model.

Also refreshed:
* .env.example --- documents the new default and the retirement
* docs/llm-providers.md --- new 'Model choice' subsection covering
the 1.5 retirement and the header-vs-URL key placement

Smoke-tested:
* cdpr.llm.config.DEFAULT_MODELS['gemini'] == 'gemini-2.0-flash'
* build_provider('echo') still wires up
* _redact_secrets and _redact both strip
'key=AQ.Ab8RN6Ic...FAKE' to 'key=<redacted>' on a string shaped
like the leaked URL

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>

.env.example CHANGED
@@ -64,8 +64,11 @@ SUPABASE_SERVICE_ROLE_KEY=
64
  # Gemini (recommended default --- free tier).
65
  # Get a key at https://aistudio.google.com/app/apikey
66
  GEMINI_API_KEY=
67
- # Optional model override; default gemini-1.5-flash.
68
- # GEMINI_MODEL=gemini-1.5-flash
 
 
 
69
 
70
  # OpenRouter (covers DeepSeek-R1 math reasoning and DeepSeek-V3 code).
71
  # Get a key at https://openrouter.ai/keys
 
64
  # Gemini (recommended default --- free tier).
65
  # Get a key at https://aistudio.google.com/app/apikey
66
  GEMINI_API_KEY=
67
+ # Optional model override; default is gemini-2.0-flash.
68
+ # Google retired the gemini-1.5 family in mid-2025 (returns 404). The
69
+ # current free-tier choices are gemini-2.0-flash (general purpose),
70
+ # gemini-2.0-flash-lite (faster, smaller), or gemini-2.5-flash (newer).
71
+ # GEMINI_MODEL=gemini-2.0-flash
72
 
73
  # OpenRouter (covers DeepSeek-R1 math reasoning and DeepSeek-V3 code).
74
  # Get a key at https://openrouter.ai/keys
docs/llm-providers.md CHANGED
@@ -31,10 +31,12 @@ explaining simulation outputs.
31
  2. Open Google AI Studio: <https://aistudio.google.com/>
32
  3. Accept Google's AI terms of service.
33
  4. Click **Get API key** → **Create API key in new project**.
34
- 5. **Copy the key** (starts with `AI…`) and keep it private.
 
 
35
  6. In the project root, copy `.env.example` to `.env` and add:
36
  ```
37
- GEMINI_API_KEY=AI...your_key...
38
  ```
39
  7. Verify with the smoke script:
40
  ```powershell
@@ -42,6 +44,21 @@ explaining simulation outputs.
42
  python scripts\test_llm.py --provider gemini
43
  ```
44
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
45
  ### OpenRouter (DeepSeek-R1 + DeepSeek-V3)
46
 
47
  > The agent CANNOT do these steps for you.
 
31
  2. Open Google AI Studio: <https://aistudio.google.com/>
32
  3. Accept Google's AI terms of service.
33
  4. Click **Get API key** → **Create API key in new project**.
34
+ 5. **Copy the key** and keep it private. Modern keys start with
35
+ `AIzaSy…` (classic format) or `AQ.Ab…` (the v2 format introduced
36
+ in 2025). Both authenticate the same way.
37
  6. In the project root, copy `.env.example` to `.env` and add:
38
  ```
39
+ GEMINI_API_KEY=<paste your key>
40
  ```
41
  7. Verify with the smoke script:
42
  ```powershell
 
44
  python scripts\test_llm.py --provider gemini
45
  ```
46
 
47
+ **Model choice.** The default is `gemini-2.0-flash`. Google retired
48
+ the `gemini-1.5-flash` and `gemini-1.5-pro` models in mid-2025; calls
49
+ to those endpoints now return HTTP 404 with a misleading "model not
50
+ found" message. If you see a 404 from this provider, your
51
+ `GEMINI_MODEL` env var is probably still pinned to the retired name
52
+ --- delete the override (or update to one of):
53
+
54
+ * `gemini-2.0-flash` --- general purpose, 1 M context, free tier (default)
55
+ * `gemini-2.0-flash-lite` --- faster, smaller, free tier
56
+ * `gemini-2.5-flash` --- newer, free tier where available
57
+
58
+ The key is sent via the `x-goog-api-key` HTTP header rather than the
59
+ URL query string, so a 404 / 401 message that quotes the request URL
60
+ will *not* leak your key into the chat box or the build log.
61
+
62
  ### OpenRouter (DeepSeek-R1 + DeepSeek-V3)
63
 
64
  > The agent CANNOT do these steps for you.
src/cdpr/llm/config.py CHANGED
@@ -40,9 +40,14 @@ OLLAMA_URL_ENV: Final = "OLLAMA_URL"
40
  LMSTUDIO_URL_ENV: Final = "LMSTUDIO_URL"
41
 
42
  # Default model identifiers per provider. Users can override via the
43
- # matching env var (e.g. ``GEMINI_MODEL=gemini-1.5-pro``).
 
 
 
 
 
44
  DEFAULT_MODELS: Final[dict[str, str]] = {
45
- "gemini": "gemini-1.5-flash",
46
  "openrouter": "deepseek/deepseek-r1", # math reasoning default
47
  "ollama": "llama3",
48
  "lmstudio": "local-model",
 
40
  LMSTUDIO_URL_ENV: Final = "LMSTUDIO_URL"
41
 
42
  # Default model identifiers per provider. Users can override via the
43
+ # matching env var (e.g. ``GEMINI_MODEL=gemini-2.5-flash``).
44
+ #
45
+ # Google retired the gemini-1.5 family in mid-2025; the endpoint now
46
+ # returns 404. ``gemini-2.0-flash`` is the current free-tier successor
47
+ # (1M token context, same JSON-structured-output behaviour) and is the
48
+ # new default. ``gemini-2.5-flash`` works too if you've enabled it.
49
  DEFAULT_MODELS: Final[dict[str, str]] = {
50
+ "gemini": "gemini-2.0-flash",
51
  "openrouter": "deepseek/deepseek-r1", # math reasoning default
52
  "ollama": "llama3",
53
  "lmstudio": "local-model",
src/cdpr/llm/providers/gemini.py CHANGED
@@ -1,12 +1,25 @@
1
- """Google Gemini provider — the directive's default assistant.
2
 
3
  Uses Gemini's REST endpoint directly so we don't take a hard
4
- ``google-generativeai`` SDK dependency. The free tier covers the
5
- ``gemini-1.5-flash`` model used here.
 
 
 
 
 
 
 
 
 
 
 
 
6
  """
7
 
8
  from __future__ import annotations
9
 
 
10
  from typing import Iterator
11
 
12
  from cdpr.llm.base import LLMMessage, LLMResponse, LLMUnavailableError
@@ -14,6 +27,20 @@ from cdpr.llm.config import LLMConfig
14
  from cdpr.llm.providers._http import post_json
15
 
16
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
17
  class GeminiProvider:
18
  name = "gemini"
19
 
@@ -36,10 +63,13 @@ class GeminiProvider:
36
  model: str | None = None,
37
  ) -> LLMResponse:
38
  model_id = model or self.model
 
 
39
  url = (
40
  f"https://generativelanguage.googleapis.com/v1beta/"
41
- f"models/{model_id}:generateContent?key={self._cfg.api_key}"
42
  )
 
43
  # Gemini expects a single ``contents`` list with ``role`` ∈ {"user",
44
  # "model"}. System prompts are concatenated into the first user turn.
45
  gem_messages: list[dict] = []
@@ -65,15 +95,30 @@ class GeminiProvider:
65
  },
66
  }
67
  try:
68
- data = post_json(url, payload, timeout=self._cfg.timeout_s)
 
 
69
  except Exception as exc: # network / 4xx / 5xx
70
- raise LLMUnavailableError(f"Gemini call failed: {exc}") from exc
 
 
 
 
 
 
 
 
 
 
 
 
 
71
  try:
72
  text = data["candidates"][0]["content"]["parts"][0]["text"]
73
  finish = data["candidates"][0].get("finishReason", "")
74
  except (KeyError, IndexError) as exc:
75
  raise LLMUnavailableError(
76
- f"Gemini response missing expected fields: {data!r}"
77
  ) from exc
78
  return LLMResponse(
79
  text=text, model=model_id, provider=self.name,
 
1
+ r"""Google Gemini provider --- the directive's default assistant.
2
 
3
  Uses Gemini's REST endpoint directly so we don't take a hard
4
+ ``google-generativeai`` SDK dependency. The free tier covers
5
+ ``gemini-2.0-flash`` (the current default; the 1.5 family was retired
6
+ in mid-2025 and the endpoint now returns 404).
7
+
8
+ Two error-handling rules from the directive's secrets-hygiene line:
9
+
10
+ 1. Never let the API key appear in an exception that surfaces to the
11
+ UI. We pass the key in the ``x-goog-api-key`` request header rather
12
+ than the URL query string, so a 404 / 401 message that quotes the
13
+ request URL does NOT leak the key into the chat box.
14
+ 2. When ``httpx.HTTPStatusError`` carries the URL in its message, we
15
+ still scrub it through :func:`_redact_secrets` before raising
16
+ :class:`LLMUnavailableError`, because httpx in some versions prints
17
+ the full URL including the query string.
18
  """
19
 
20
  from __future__ import annotations
21
 
22
+ import re
23
  from typing import Iterator
24
 
25
  from cdpr.llm.base import LLMMessage, LLMResponse, LLMUnavailableError
 
27
  from cdpr.llm.providers._http import post_json
28
 
29
 
30
+ # Patterns we redact from any error string that might surface to the
31
+ # user. Both Google-style key query parameters and bearer tokens are
32
+ # covered. The replacement is a fixed string so downstream string-
33
+ # comparison code (tests, logs) stays stable.
34
+ _KEY_QUERY_RE = re.compile(r"([?&])key=[^&\s'\"]+", flags=re.IGNORECASE)
35
+ _BEARER_RE = re.compile(r"(Bearer\s+)[A-Za-z0-9._\-]+", flags=re.IGNORECASE)
36
+
37
+
38
+ def _redact_secrets(text: str) -> str:
39
+ text = _KEY_QUERY_RE.sub(r"\1key=<redacted>", text)
40
+ text = _BEARER_RE.sub(r"\1<redacted>", text)
41
+ return text
42
+
43
+
44
  class GeminiProvider:
45
  name = "gemini"
46
 
 
63
  model: str | None = None,
64
  ) -> LLMResponse:
65
  model_id = model or self.model
66
+ # Key goes in a header, NOT the URL, so 4xx error messages
67
+ # (which often quote the request URL) don't leak it.
68
  url = (
69
  f"https://generativelanguage.googleapis.com/v1beta/"
70
+ f"models/{model_id}:generateContent"
71
  )
72
+ key_header = {"x-goog-api-key": self._cfg.api_key}
73
  # Gemini expects a single ``contents`` list with ``role`` ∈ {"user",
74
  # "model"}. System prompts are concatenated into the first user turn.
75
  gem_messages: list[dict] = []
 
95
  },
96
  }
97
  try:
98
+ data = post_json(
99
+ url, payload, headers=key_header, timeout=self._cfg.timeout_s,
100
+ )
101
  except Exception as exc: # network / 4xx / 5xx
102
+ msg = _redact_secrets(str(exc))
103
+ # Translate the common 404 case into actionable language so
104
+ # the user doesn't waste time on the wrong fix.
105
+ if "404" in msg or "Not Found" in msg:
106
+ msg += (
107
+ " --- model "
108
+ f"{model_id!r} returned 404. Google retired the "
109
+ "gemini-1.5 family in mid-2025; the current free-tier "
110
+ "models are 'gemini-2.0-flash' (default), "
111
+ "'gemini-2.0-flash-lite', and 'gemini-2.5-flash'. "
112
+ "Set GEMINI_MODEL=gemini-2.0-flash (or leave unset to "
113
+ "use the new default) and retry."
114
+ )
115
+ raise LLMUnavailableError(f"Gemini call failed: {msg}") from exc
116
  try:
117
  text = data["candidates"][0]["content"]["parts"][0]["text"]
118
  finish = data["candidates"][0].get("finishReason", "")
119
  except (KeyError, IndexError) as exc:
120
  raise LLMUnavailableError(
121
+ f"Gemini response missing expected fields: {_redact_secrets(str(data))!r}"
122
  ) from exc
123
  return LLMResponse(
124
  text=text, model=model_id, provider=self.name,
src/cdpr/llm/simulation_builder.py CHANGED
@@ -40,6 +40,23 @@ from cdpr.interface.specs import SimulationRequest, TrajectorySpec
40
  from cdpr.llm import LLMMessage, LLMUnavailableError, build_provider
41
 
42
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
43
  _SYSTEM_PROMPT = """\
44
  You are a parser for the CDPR Simulator. Convert the user's free-text
45
  description of a Cable-Driven Parallel Robot experiment into a JSON
@@ -115,12 +132,12 @@ def describe_to_request(
115
  parsed = _extract_json(raw_text)
116
  except LLMUnavailableError as exc:
117
  notes.append(
118
- f"LLM provider {llm.name!r} is unavailable: {exc}. "
119
  "Returning a conservative default request."
120
  )
121
  except (ValueError, KeyError) as exc:
122
  notes.append(
123
- f"LLM response was not valid JSON: {exc}. "
124
  "Returning a conservative default request."
125
  )
126
 
 
40
  from cdpr.llm import LLMMessage, LLMUnavailableError, build_provider
41
 
42
 
43
+ # Secret-scrub pattern applied to any error string that surfaces in
44
+ # ``BuilderResult.notes`` --- belt-and-braces, on top of the same
45
+ # redaction the providers do at the raise site. If a future provider
46
+ # misses the redaction, the chat box still won't leak the key.
47
+ _SECRET_PATTERNS = (
48
+ re.compile(r"([?&])key=[^&\s'\"]+", flags=re.IGNORECASE),
49
+ re.compile(r"(Bearer\s+)[A-Za-z0-9._\-]+", flags=re.IGNORECASE),
50
+ )
51
+
52
+
53
+ def _redact(text: str) -> str:
54
+ out = text
55
+ for pat in _SECRET_PATTERNS:
56
+ out = pat.sub(lambda m: f"{m.group(1)}<redacted>", out)
57
+ return out
58
+
59
+
60
  _SYSTEM_PROMPT = """\
61
  You are a parser for the CDPR Simulator. Convert the user's free-text
62
  description of a Cable-Driven Parallel Robot experiment into a JSON
 
132
  parsed = _extract_json(raw_text)
133
  except LLMUnavailableError as exc:
134
  notes.append(
135
+ f"LLM provider {llm.name!r} is unavailable: {_redact(str(exc))}. "
136
  "Returning a conservative default request."
137
  )
138
  except (ValueError, KeyError) as exc:
139
  notes.append(
140
+ f"LLM response was not valid JSON: {_redact(str(exc))}. "
141
  "Returning a conservative default request."
142
  )
143