Skip to content

Add a native Google Gemini provider - #69

Merged
alexey-milovidov merged 4 commits into
mainfrom
google-gemini-provider
Nov 27, 2026
Merged

alexey-milovidov merged 4 commits into
mainfrom
google-gemini-provider

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Nov 27, 2026 •

Copy link
Copy Markdown
Member

Adds ai::google, a provider for the native Gemini API (generateContent and streamGenerateContent?alt=sse under /v1beta, authenticated with x-goog-api-key). It does not go through the OpenAI-compatibility endpoint. With the native API we get thought signatures, functionCallingConfig, responseJsonSchema, promptFeedback, and the full usageMetadata.

It follows the Anthropic provider layout: an ai::google component target with AI_SDK_HAS_GOOGLE, a client, a factory, a request builder, a response parser, and an HttpSseStream subclass. The public header is include/ai/google.h. It has ai::google::models::k* constants (Gemini 4 Carbon/Neon/Hydrogen/Argon, Gemini 3.8/3.6 Flash, 3.5/3.1 Flash-Lite, taken from the current models page) and kDefaultModel = gemini-4-hydrogen, which Google recommends as the general-purpose model. The usual create_client overloads and try_create_client are there too. The key is read from GOOGLE_API_KEY or GEMINI_API_KEY; when both are set, GOOGLE_API_KEY wins, as in Google's SDKs. There is no static model list: supports_model accepts any non-empty name.

How requests and responses are mapped:

  • system and system messages go to systemInstruction. Messages go to contents with roles user/model, and consecutive messages with the same role share one entry.
  • Tool calls become functionCall parts and tool results become functionResponse parts. functionResponse.name is required, but ToolResultContentPart only carries the call ID, so the name is looked up from the call the result answers. Non-object results are wrapped as {"output": ...}, failed ones as {"error": ...}.
  • Tools go to functionDeclarations with parametersJsonSchema, which takes plain JSON Schema (parameters only accepts a subset of OpenAPI 3.0).
  • tool_choice maps to functionCallingConfig.mode: AUTO, ANY, NONE, or ANY plus allowedFunctionNames for a specific tool.
  • max_tokens, temperature, top_p, seed, and the penalties go to generationConfig. temperature and top_p are left out for Gemini 4 and Gemini 3.6+: the docs say those models ignore them, return deprecation warnings, and will reject them with 400 in a future release.
  • A response_format with a JSON schema maps to responseMimeType: application/json plus responseJsonSchema. json_object and text are accepted, and any other format is an error.
  • finishReason maps to the finish reason. STOP and MAX_TOKENS with function calls become tool_calls. SAFETY, RECITATION, and similar become content_filter. MALFORMED_FUNCTION_CALL, OTHER, and unknown reasons are errors that include finishMessage. promptFeedback.blockReason is a content-filter error.
  • In usageMetadata, thinking tokens count as completion tokens.

Thought signatures. Gemini 4 and Gemini 3 return 400 when a function call in the current turn is sent back without its thoughtSignature. The parser keeps the signatures, and thought or signature-only parts, as ai::ProviderContentParts in response_messages, the same mechanism the OpenAI Responses client from #67 uses. The multi-step coordinator then replays the model turn exactly as received. Function calls that carry no signature (streamed calls, hand-built conversations, or turns from another provider) get the skip_thought_signature_validator value that the docs specify for that case. Gemini 2.5 calls come without an id, so the client makes one up (gemini-call-N) to pair each call with its result, and does not send it to the API.

Streaming. If the request cannot be built, the stream yields an error event. Every SSE event is a complete GenerateContentResponse chunk, and the stream finishes on the chunk that has finishReason. Thought parts (thought: true) are emitted as StreamEvent::reasoning(...). Streamed requests that think also ask for thought summaries with includeThoughts.

Shared code. BaseProviderClient gets a completions_path hook, because Gemini puts the model in the URL. The standard error parser now also reads Google's error.status.

Thinking. Thinking tokens count against max_tokens. Like the OpenAI builders' lowest reasoning effort, each request asks for the least thinking the model accepts, per the thinking guide:

  • thinkingLevel: low on Gemini 4 (which requires thinkingLevel), Gemini 3.8 Flash, and the Gemini 3 Pro previews;
  • thinkingLevel: minimal on Gemini 3.6 Flash, the Flash-Lite models, and Gemini 3 Flash Preview;
  • thinkingBudget 0 (Flash, Flash-Lite) or 128 (Pro) on Gemini 2.5.

Other models get no thinkingConfig.

Not included: embeddings (embedContent is a different API, so the client returns an error) and resuming long decode via continuationToken. A list_models override for Gemini (GET /v1beta/models, strip the models/ prefix, page with nextPageToken) is a follow-up once #68 is merged.

Tests. New unit tests cover request building, response parsing, a multi-step replay through MultiStepCoordinator, and stream parsing. Integration tests in tests/integration/google_integration_test.cpp and the google instance of the parameterized tool-calling test run when GEMINI_API_KEY is set. CI now passes GEMINI_API_KEY: ${{ secrets.GEMINI_API_KEY }}. A maintainer needs to add that repository secret; until then the Gemini integration tests are skipped. Locally, without a key, all unit tests pass. InvalidApiKey also passes: it reaches the real API (generateContent and streamGenerateContent both answer API_KEY_INVALID).

Also adds examples/google_gemini.cpp, examples/components/google, and a README section.

🤖 Generated with Claude Code


Note

Medium Risk
Large new provider surface (HTTP, streaming, multi-step tools, thought signatures) touches shared base client and coordinator replay paths, but no changes to auth or secrets handling beyond a new CI env var.

Overview
Adds a native Google Gemini provider (ai::google / ai-sdk-cpp-google) wired into the umbrella ai::sdk, CMake package components, include/ai/google.h, and AI_SDK_HAS_GOOGLE.

The client targets Gemini’s /v1beta generateContent and streamGenerateContent?alt=sse endpoints (model in the URL, x-goog-api-key auth), with factory helpers reading GOOGLE_API_KEY or GEMINI_API_KEY. It maps the shared GenerateOptions surface to Gemini JSON: systemInstruction, alternating contents, tools/toolConfig, structured output via responseJsonSchema, model-specific thinking defaults, and omission of sampling params on Gemini 4 / 3.6+.

Gemini-specific behavior includes preserving and replaying thought signatures on tool turns via ProviderContentPart in response_messages, synthetic call IDs for id-less function calls, streaming thought summaries as reasoning events, and explicit “embeddings not supported.” BaseProviderClient gains a completions_path override; shared error parsing also reads Google’s error.status.

CI passes GEMINI_API_KEY for integration tests; README, examples/google_gemini.cpp, and component demos are updated. Broad unit/integration coverage exercises request building, parsing, streaming, multi-step tool replay, and parameterized tool-calling for google.

Reviewed by Cursor Bugbot for commit e2f5b78. Bugbot is set up for automated code reviews on this repo. Configure here.

`ai::google` talks to the native Gemini API (`generateContent` and
`streamGenerateContent?alt=sse` under `/v1beta`, `x-goog-api-key` auth)
instead of the OpenAI-compatibility endpoint.

- Messages map to `contents` (`user`/`model`), system prompts to
  `systemInstruction`, tool calls to `functionCall` parts, tool results to
  `functionResponse` parts (the function name is taken from the call they
  answer), tools to `functionDeclarations` with `parametersJsonSchema`, and
  `tool_choice` to `functionCallingConfig` modes.
- Thought signatures, which Gemini 4 and Gemini 3 require to be sent back
  with function calls, are kept in `response_messages` as
  `ProviderContentPart`s and replayed by the multi-step loop. Function calls
  without a signature (streamed or hand-built) get the documented
  `skip_thought_signature_validator` signature.
- `response_format` maps to `responseMimeType` + `responseJsonSchema`;
  `finishReason`, `promptFeedback.blockReason` and `usageMetadata` map to
  the finish reason, errors and usage (thinking tokens count as completion
  tokens).
- `temperature`/`top_p` are not sent to Gemini 4 and Gemini 3.6+ models,
  which ignore them.
- `BaseProviderClient` gets a `completions_path` hook for providers that
  address the model in the URL; the standard error parser also reads
  Google's `error.status`.

Unit tests cover request building, response parsing, the multi-step replay,
and stream parsing; integration tests (and the `google` instance of the
parameterized tool-calling test) run when `GEMINI_API_KEY` is set, which CI
now passes from the secret of the same name.

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

@cursor cursor Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Stale Bugbot comment from a previous run.

Comment thread src/providers/google/google_client.cpp Resolved
alexey-milovidov and others added 2 commits November 27, 2026 20:28
- `GoogleClient::stream_text` no longer lets exceptions from building the
  request (an unsupported `response_format`, a tool result without its
  call) escape; the stream yields an error event and an error finish event,
  as `generate_text` returns an error result.
- Consecutive messages with the same role (two user messages, or tool
  results followed by a user message) now join one `contents` entry, since
  Gemini expects alternating `user` and `model` turns.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Thinking tokens count against `maxOutputTokens`, and the default levels
(`high` on Gemini 4 Neon and Hydrogen) can use up a small `max_tokens`
before any text is produced. Like the lowest reasoning effort of the OpenAI
builders, the request now carries the lowest `thinkingConfig` each model
accepts according to the thinking guide: `thinkingLevel` `low` on Gemini 4
(which requires `thinkingLevel`), Gemini 3.8 Flash and the Gemini 3 Pro
previews, `minimal` on Gemini 3.6 Flash, the Flash-Lite models and Gemini 3
Flash Preview, and `thinkingBudget` 0 (Flash, Flash-Lite) or 128 (Pro) on
Gemini 2.5. Other models get no `thinkingConfig`.

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

@cursor cursor Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Cursor Bugbot has reviewed your changes using high effort and found 1 potential issue.

Fix All in Cursor

❌ Bugbot Autofix is OFF. To automatically fix reported issues with cloud agents, have a team admin enable autofix in the Cursor dashboard.

Reviewed by Cursor Bugbot for commit 4808abf. Configure here.

Conflicts (both sides kept): the component list in
`cmake/ai-sdk-cpp-config.cmake.in` (`google` plus the optional `bedrock`),
the component example subdirectories and messages in
`examples/CMakeLists.txt`, and the provider lists in `README.md`.

With #65 on main, `StreamEvent::reasoning` carries text, so the Gemini
stream now emits thought parts (`thought: true`) as reasoning events, and
streamed requests that think ask for them with `includeThoughts`.
`GoogleStreamImpl` only uses `push_event` and `mark_complete`, which work
unchanged with the new `HttpSseStream` queue.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@alexey-milovidov
alexey-milovidov merged commit 72979dc into main Nov 27, 2026
3 checks passed
alexey-milovidov added a commit that referenced this pull request Nov 27, 2026
The Gemini provider, merged in #69, answers `list_models` from its own
models endpoint: it follows `nextPageToken` (failing if a token
repeats), and reports the IDs without the `models/` prefix, the way
requests take them. The request and error handling of the OpenAI and
Anthropic listing moves to `BaseProviderClient::get_json`, shared by
both implementations.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
alexey-milovidov added a commit that referenced this pull request Nov 27, 2026
* List models from the provider instead of a static catalog

`supported_models` and `supports_model` answered from a hand-maintained
list that went stale with every model release, returned false for valid
models, and could not know what an API key or a custom `base_url`
(OpenRouter, gateways) serves. Requests never consulted it: model names
are forwarded to the API as is.

- Add `Client::list_models`, which asks the provider's models endpoint
  (`GET /v1/models`) and follows Anthropic's `has_more`/`last_id`
  pagination; errors are parsed like completion errors. It uses the
  same retry policy as other requests (new `HttpRequestHandler::get`).
- `supports_model` is now true for every non-empty model name.
- `supported_models` stays as the list of well-known names (the
  `models::k*` constants) and is documented as such.

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

* Bedrock: list models from `ListFoundationModels`, accept any model name

Align the Bedrock client, merged in #38, with the rest of this change:
`list_models` returns the foundation model IDs of the Region through
`ModelDiscovery`, and `supports_model` is true for every non-empty
model ID (inference profiles and ARNs are forwarded to Converse as is).

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

* Bedrock: tests for client construction, `supports_model`, `list_models`

- Unit tests (no network): a client is created with a region, accepts any
  non-empty model ID in `supports_model` and rejects "", lists the current
  Claude models in `supported_models`, and requires a region.
- Integration test (skipped without `AI_SDK_IT_BEDROCK`): `list_models`
  returns the foundation models of the Region.

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

* Fail `list_models` when the pagination cursor repeats

A server or gateway that ignores `after_id` and keeps answering
`has_more` with the same `last_id` made `list_models` page forever.
Report an error when a cursor comes back a second time.

Reported by Cursor Bugbot in #68

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

* Gemini: list models from `GET /v1beta/models`

The Gemini provider, merged in #69, answers `list_models` from its own
models endpoint: it follows `nextPageToken` (failing if a token
repeats), and reports the IDs without the `models/` prefix, the way
requests take them. The request and error handling of the OpenAI and
Anthropic listing moves to `BaseProviderClient::get_json`, shared by
both implementations.

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant