diff --git a/python/packages/gemini/agent_framework_gemini/_chat_client.py b/python/packages/gemini/agent_framework_gemini/_chat_client.py index 0750e741f11..7c493137ec1 100644 --- a/python/packages/gemini/agent_framework_gemini/_chat_client.py +++ b/python/packages/gemini/agent_framework_gemini/_chat_client.py @@ -891,6 +891,19 @@ def _prepare_config( if key == "stop" and isinstance(value, str): # ChatOptions allows a single stop string; stop_sequences takes a list. value = [value] + if key == "candidate_count": + # Both the streaming and non-streaming parsers read candidates[0] only, + # so any count other than one is billed while every candidate but the + # first is silently dropped. The default should be to not pass the + # option at all; if passed, it needs to be 1 (including the stringified + # form some config paths produce, which is normalized here). + if value not in (1, "1"): + raise ChatClientInvalidRequestException( + "Gemini chat client supports a single candidate. Remove " + "candidate_count or set it to 1; candidate_count=" + f"{value!r} would silently drop every candidate but the first." + ) + value = 1 kwargs[_OPTION_TRANSLATIONS.get(key, key)] = value response_format = options.get("response_format") diff --git a/python/packages/gemini/tests/test_gemini_client.py b/python/packages/gemini/tests/test_gemini_client.py index 5d442bdf67e..1d49347d2ee 100644 --- a/python/packages/gemini/tests/test_gemini_client.py +++ b/python/packages/gemini/tests/test_gemini_client.py @@ -3233,3 +3233,34 @@ async def sdk_stream(): break assert closed + + +@pytest.mark.parametrize("bad_count", [0, "0", 2, "2", -1]) +def test_candidate_count_other_than_one_is_rejected(bad_count: Any) -> None: + """``candidate_count`` other than 1 (or absent) is rejected up front. + + Both the streaming and non-streaming parsers read ``candidates[0]`` only, so any + other count would be billed while all but the first candidate are silently dropped. + Zero is rejected along with counts above one (follow-up to the review on #9929). + """ + client, _ = _make_gemini_client() + + with pytest.raises(ChatClientInvalidRequestException, match="candidate_count"): + client._prepare_config({"candidate_count": bad_count}, None) + + +@pytest.mark.parametrize("good_count", [1, "1"]) +def test_candidate_count_one_passes_through_normalized(good_count: Any) -> None: + """A single candidate is accepted and normalized to an int for the config.""" + client, _ = _make_gemini_client() + + config = client._prepare_config({"candidate_count": good_count}, None) + assert config.candidate_count == 1 + + +def test_candidate_count_absent_leaves_config_unset() -> None: + """Without the option the config keeps Gemini's single-candidate default.""" + client, _ = _make_gemini_client() + + config = client._prepare_config({}, None) + assert config.candidate_count is None