Repository navigation
Add a native Google Gemini provider - #69
Merged
Merged
Conversation
`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>
- `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>
There was a problem hiding this comment.
Cursor Bugbot has reviewed your changes using high effort and found 1 potential issue.
❌ 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
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>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.

Adds
ai::google, a provider for the native Gemini API (generateContentandstreamGenerateContent?alt=sseunder/v1beta, authenticated withx-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 fullusageMetadata.It follows the Anthropic provider layout: an
ai::googlecomponent target withAI_SDK_HAS_GOOGLE, a client, a factory, a request builder, a response parser, and anHttpSseStreamsubclass. The public header isinclude/ai/google.h. It hasai::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) andkDefaultModel = gemini-4-hydrogen, which Google recommends as the general-purpose model. The usualcreate_clientoverloads andtry_create_clientare there too. The key is read fromGOOGLE_API_KEYorGEMINI_API_KEY; when both are set,GOOGLE_API_KEYwins, as in Google's SDKs. There is no static model list:supports_modelaccepts any non-empty name.How requests and responses are mapped:
systemand system messages go tosystemInstruction. Messages go tocontentswith rolesuser/model, and consecutive messages with the same role share one entry.functionCallparts and tool results becomefunctionResponseparts.functionResponse.nameis required, butToolResultContentPartonly 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": ...}.functionDeclarationswithparametersJsonSchema, which takes plain JSON Schema (parametersonly accepts a subset of OpenAPI 3.0).tool_choicemaps tofunctionCallingConfig.mode:AUTO,ANY,NONE, orANYplusallowedFunctionNamesfor a specific tool.max_tokens,temperature,top_p,seed, and the penalties go togenerationConfig.temperatureandtop_pare 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.response_formatwith a JSON schema maps toresponseMimeType: application/jsonplusresponseJsonSchema.json_objectandtextare accepted, and any other format is an error.finishReasonmaps to the finish reason.STOPandMAX_TOKENSwith function calls becometool_calls.SAFETY,RECITATION, and similar becomecontent_filter.MALFORMED_FUNCTION_CALL,OTHER, and unknown reasons are errors that includefinishMessage.promptFeedback.blockReasonis a content-filter error.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, asai::ProviderContentParts inresponse_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 theskip_thought_signature_validatorvalue that the docs specify for that case. Gemini 2.5 calls come without anid, 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
GenerateContentResponsechunk, and the stream finishes on the chunk that hasfinishReason. Thought parts (thought: true) are emitted asStreamEvent::reasoning(...). Streamed requests that think also ask for thought summaries withincludeThoughts.Shared code.
BaseProviderClientgets acompletions_pathhook, because Gemini puts the model in the URL. The standard error parser now also reads Google'serror.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: lowon Gemini 4 (which requiresthinkingLevel), Gemini 3.8 Flash, and the Gemini 3 Pro previews;thinkingLevel: minimalon Gemini 3.6 Flash, the Flash-Lite models, and Gemini 3 Flash Preview;thinkingBudget0 (Flash, Flash-Lite) or 128 (Pro) on Gemini 2.5.Other models get no
thinkingConfig.Not included: embeddings (
embedContentis a different API, so the client returns an error) and resuming long decode viacontinuationToken. Alist_modelsoverride for Gemini (GET /v1beta/models, strip themodels/prefix, page withnextPageToken) 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 intests/integration/google_integration_test.cppand thegoogleinstance of the parameterized tool-calling test run whenGEMINI_API_KEYis set. CI now passesGEMINI_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.InvalidApiKeyalso passes: it reaches the real API (generateContentandstreamGenerateContentboth answerAPI_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 umbrellaai::sdk, CMake package components,include/ai/google.h, andAI_SDK_HAS_GOOGLE.The client targets Gemini’s
/v1betagenerateContentandstreamGenerateContent?alt=sseendpoints (model in the URL,x-goog-api-keyauth), with factory helpers readingGOOGLE_API_KEYorGEMINI_API_KEY. It maps the sharedGenerateOptionssurface to Gemini JSON:systemInstruction, alternatingcontents, tools/toolConfig, structured output viaresponseJsonSchema, 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
ProviderContentPartinresponse_messages, synthetic call IDs for id-less function calls, streaming thought summaries as reasoning events, and explicit “embeddings not supported.”BaseProviderClientgains acompletions_pathoverride; shared error parsing also reads Google’serror.status.CI passes
GEMINI_API_KEYfor 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 forgoogle.Reviewed by Cursor Bugbot for commit e2f5b78. Bugbot is set up for automated code reviews on this repo. Configure here.