Skip to content

feat(ai): add GeminiLanguageModel - #16601

Merged
andrewheard merged 16 commits into
mainfrom
ah/ai-add-gemini-language-model
Sep 4, 2026
Merged

andrewheard merged 16 commits into
mainfrom
ah/ai-add-gemini-language-model

Conversation

@andrewheard

@andrewheard andrewheard commented Sep 3, 2026 •

Copy link
Copy Markdown
Contributor

Implemented GeminiLanguageModel, providing an adapter for Google's Gemini models conforming to Apple's FoundationModels.LanguageModel protocol. This PR includes text to text generation capabilities; other modalities and Gemini features will be handled in follow-up PRs.

Note: The GeminiLanguageModel implementation is guarded by the environment variable GEMINI_LANGUAGE_MODEL. By default none of the GeminiLanguageModel implementation is included.

Key additions:

  • GeminiLanguageModel: Implements LanguageModel protocol with reasoning capabilities, configuring execution via ModelResource and EndpointConfiguration.
  • GeminiLanguageModelExecutor: Converts prompt instructions and history into Gemini streaming requests, yielding responses as LanguageModelSession.ResponseStream.
  • GeminiTranscriptTranslator: Translates Apple Transcript entries and segments into Gemini Content structures while preserving thought signatures and validating supported transcript features.
  • GeminiLanguageModel.Error and GeminiErrorMapper: Translates Gemini API, HTTP, and network errors into standard LanguageModelError cases (rateLimited, timeout, guardrailViolation, refusal, and unsupportedLanguageOrLocale) or GeminiLanguageModel.Error cases (serviceUnavailable, networkFailure, modelNotFound, apiError). The APIError payload is designed for seamless forward compatibility with both GenerateContent and the upcoming Interactions API.
  • Testing infrastructure: Adds ConditionTrait.requireFoundationModels to conditionally run Foundation Models tests only on supported platforms (macOS 27+, iOS 27+, watchOS 27+, visionOS 27+), along with shared test constants, mock fixtures, and comprehensive unit and integration test suites.

#no-changelog

Initialize the Swift package structure for GeminiForFoundationModels
with Swift 6 language mode and platform deployment targets.

- Set swift-tools-version to 6.1 and enable Swift 6 language mode.
- Rename target and test directories to PascalCase naming.
- Define supported Apple platforms (iOS 15+, macOS 10.15+, tvOS 15+,
  watchOS 7+).
- Add Apache 2.0 license headers to package manifest, source, and
  test files.
Added a lightweight HTTP client backed by `URLSession` that supports
asynchronous text line streaming to prepare for handling Server-Sent
Event (SSE) streaming.

- Introduce `HTTPStreamingClient` with a `lines(for:)` streaming API.
- Provide `HTTPAsyncLineSequence` mirroring standard
  `URLSession.AsyncBytes.lines` (`AsyncLineSequence`) ergonomics.
- Implement incremental UTF-8 line decoding supporting CRLF, LF, CR,
  and split multi-byte unicode characters across chunk boundaries.
- Adopt Swift 6 strict concurrency with compiler-checked `Sendable`
  types and properly synchronized task delegate management.
- Add comprehensive unit test suite in `HTTPStreamingClientTests`.
Added the `GenerateContentDataModels` and `SharedDataModels` targets to
provide strongly-typed data models for Gemini Developer API and Gemini
Enterprise Agent Platform `GenerateContent` requests and responses.

- Added `SharedDataModels` target with `GoogleCloudAPIError` and
  `JSONValue` primitives for API error parsing and dynamic JSON.
- Added `GenerateContentDataModels` target containing over 110 wire
  models covering prompts, candidates, modalities, safety settings,
  grounding, tool calls, citations, and audio/image/video formats.
- Updated `Package.swift` with upcoming feature `ExistentialAny` and
  extracted these Swift settings into a `defaultSwiftSettings` constant
  to more easily maintain consistency.
- Enforced strict internal import access levels and explicit existential
  annotations (`any Decoder`, `any Encoder`) across all models.
Added `GeminiAPIClient` to communicate with Google Gemini API endpoints,
supporting Server-Sent Events (SSE) streaming, token counting,
configurable base URLs, dynamic header injection, and Firebase AI Logic
support. `GeminiAPIClient` will be used internally by the public
`GeminiLanguageModel` in a follow-up PR.

- Added `GeminiAPIClient` target and product to Package.swift.
- Implemented `GeminiAPIClient` for streaming content generation via
  `HTTPStreamingClient` and performing token counting.
- Added `GeminiAPIError` error handling with `GoogleCloudAPIError`
  decoding, `RetryInfo` delay calculation, and custom `NSError`
  properties.
- Added `AppCheckDebugClient` actor in `SharedTestUtilities` to exchange
  and cache Firebase App Check debug tokens for tests.
- Added test condition traits (`.requireAPIKey`, `.requireNoAPIKey`,
  `.requireFirebaseAILogic`) in `SharedTestUtilities`.
- Add unit tests and integration tests for both the Gemini Developer API
  and Firebase AI Logic Developer API endpoints.
Reduced the number of targets to simplify integration in the
`firebase-ios-sdk` monorepo `Package.swift` but tried to keep reasonable
file groupings in the targets that remain.

- Merged `HTTPStreamingClient` into `GeminiAPIClient`.
- Merged `GenerateContentDataModels` and `SharedDataModels` into
  `GeminiDataModels`.
- Disabled the upcoming `InternalImportsByDefault` feature for
  `GeminiDataModels` since it is difficult to determine import access
  levels during generation.
- Introduce `ModelResource` to encapsulate model IDs and resource name
  routing.
- Introduce `EndpointConfiguration` to configure network endpoint
  scheme, host, port, and API version.
- Introduce `HeaderProvider` to wrap async dynamic HTTP header closures
  with hashable identity.
- Update `GeminiAPIClient` to use `ModelResource`,
  `EndpointConfiguration`, and `HeaderProvider`, and add
  `makeRequestURL(action:queryItems:)`.
- Add `httpBodyData` test helper to `MockHTTPURLProtocol` for
  stream-drain support in URLProtocol-intercepted requests.
- Add unit tests for `ModelResource`, `EndpointConfiguration`, and
  `HeaderProvider`.
Implemented `GeminiLanguageModel`, providing an adapter for Google's
Gemini models conforming to Apple's `FoundationModels.LanguageModel`
protocol. This PR includes text to text generation capabilities; other
modalities and Gemini features will be handled in follow-up PRs.

Key additions:
- `GeminiLanguageModel`: Implements `LanguageModel` protocol with
  reasoning capabilities, configuring execution via `ModelResource` and
  `EndpointConfiguration`.
- `GeminiLanguageModelExecutor`: Converts prompt instructions and
  history into Gemini streaming requests, yielding responses as
  `LanguageModelSession.ResponseStream`.
- `GeminiTranscriptTranslator`: Translates Apple `Transcript` entries
  and segments into Gemini `Content` structures while preserving
  thought signatures and validating supported transcript features.
- `GeminiLanguageModel.Error` and `GeminiErrorMapper`: Translates Gemini
  API, HTTP, and network errors into standard `LanguageModelError`
  cases (`rateLimited`, `timeout`, `guardrailViolation`, `refusal`, and
  `unsupportedLanguageOrLocale`) or `GeminiLanguageModel.Error` cases
  (`serviceUnavailable`, `networkFailure`, `modelNotFound`, `apiError`).
  The `APIError` payload is designed for seamless forward compatibility
  with both GenerateContent and the upcoming Interactions API.
- Testing infrastructure: Adds `ConditionTrait.requireFoundationModels`
  to conditionally run Foundation Models tests only on supported
  platforms (macOS 27+, iOS 27+, watchOS 27+, visionOS 27+), along with
  shared test constants, mock fixtures, and comprehensive unit and
  integration test suites. See Error Mapping Details below for a table
  of mapping decisions.
…7a4abfbfffb'

git-subtree-dir: GeminiLanguageModel
git-subtree-mainline: a748db3
git-subtree-split: 13ff043
@gemini-code-assist

Copy link
Copy Markdown
Contributor
Using Gemini Code Assist

The full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips.

Invoking Gemini

You can request assistance from Gemini at any point by creating a comment using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands on the current page.

Feature Command Description
Code Review /gemini review Performs a code review for the current pull request in its current state.
Pull Request Summary /gemini summary Provides a summary of the current pull request in its current state.
Comment @gemini-code-assist Responds in comments when explicitly tagged, both in pull request comments and review comments.
Help /gemini help Displays a list of available commands.

Customization

To customize the Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a .gemini/ folder in the base of the repository. Detailed instructions can be found here.

Limitations & Feedback

Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counterproductive. You can react with 👍 and 👎 on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for GitHub and other Google products, sign up here.

@danger-firebase-ios

danger-firebase-ios Bot commented Sep 3, 2026 •

Copy link
Copy Markdown
2 Warnings
⚠️ Did you forget to add a changelog entry? (Add #no-changelog to the PR description to silence this warning.)
⚠️ New public headers were added, did you remember to add them to the umbrella header?

Generated by 🚫 Danger

@andrewheard
andrewheard marked this pull request as ready for review September 4, 2026 20:09
@andrewheard
andrewheard requested a review from paulb777 September 4, 2026 20:10
Comment thread GeminiLanguageModel/.gitignore Resolved
Comment thread scripts/style.sh Resolved
@andrewheard
andrewheard merged commit 3796a55 into main Sep 4, 2026
184 checks passed
@andrewheard
andrewheard deleted the ah/ai-add-gemini-language-model branch September 4, 2026 22:05
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

3 participants