-
Notifications
You must be signed in to change notification settings - Fork 1.7k
[AI] Add GenerativeModelSession class
#15872
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Draft
andrewheard
wants to merge
4
commits into
main
Choose a base branch
from
ah/ai-generative-model-session
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+364
−51
Draft
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
a883583
[AI] Add `GenerativeModelSession` class
andrewheard 5a3b629
Add `compiler(>=6.2)` check for `nonisolated(nonsending)` support
andrewheard 5b1e3b6
Merge branch 'main' into ah/ai-generative-model-session
andrewheard 3048948
Wrap integration tests in `#if compiler(>=6.2) && canImport(Foundatio…
andrewheard File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
34 changes: 34 additions & 0 deletions
34
FirebaseAI/Sources/Extensions/Internal/GenerationSchema+Gemini.swift
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,34 @@ | ||
| // Copyright 2026 Google LLC | ||
| // | ||
| // Licensed under the Apache License, Version 2.0 (the "License"); | ||
| // you may not use this file except in compliance with the License. | ||
| // You may obtain a copy of the License at | ||
| // | ||
| // http://www.apache.org/licenses/LICENSE-2.0 | ||
| // | ||
| // Unless required by applicable law or agreed to in writing, software | ||
| // distributed under the License is distributed on an "AS IS" BASIS, | ||
| // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| // See the License for the specific language governing permissions and | ||
| // limitations under the License. | ||
|
|
||
| #if canImport(FoundationModels) | ||
| import Foundation | ||
| import FoundationModels | ||
|
|
||
| @available(iOS 26.0, macOS 26.0, *) | ||
| @available(tvOS, unavailable) | ||
| @available(watchOS, unavailable) | ||
| extension GenerationSchema { | ||
| /// Returns a Gemini-compatible JSON Schema of this `GenerationSchema`. | ||
| func toGeminiJSONSchema() throws -> JSONObject { | ||
| let generationSchemaData = try JSONEncoder().encode(self) | ||
| var jsonSchema = try JSONDecoder().decode(JSONObject.self, from: generationSchemaData) | ||
| if let propertyOrdering = jsonSchema.removeValue(forKey: "x-order") { | ||
| jsonSchema["propertyOrdering"] = propertyOrdering | ||
| } | ||
|
|
||
| return jsonSchema | ||
| } | ||
| } | ||
| #endif // canImport(FoundationModels) |
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
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
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,122 @@ | ||
| // Copyright 2026 Google LLC | ||
| // | ||
| // Licensed under the Apache License, Version 2.0 (the "License"); | ||
| // you may not use this file except in compliance with the License. | ||
| // You may obtain a copy of the License at | ||
| // | ||
| // http://www.apache.org/licenses/LICENSE-2.0 | ||
| // | ||
| // Unless required by applicable law or agreed to in writing, software | ||
| // distributed under the License is distributed on an "AS IS" BASIS, | ||
| // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| // See the License for the specific language governing permissions and | ||
| // limitations under the License. | ||
|
|
||
| // TODO: Remove the `#if compiler(>=6.2)` when Xcode 26 is the minimum supported version. | ||
| #if compiler(>=6.2) && canImport(FoundationModels) | ||
| import Foundation | ||
| import FoundationModels | ||
|
|
||
| @available(iOS 26.0, macOS 26.0, *) | ||
| @available(tvOS, unavailable) | ||
| @available(watchOS, unavailable) | ||
| public final class GenerativeModelSession: Sendable { | ||
| let generativeModel: GenerativeModel | ||
|
|
||
| public init(model: GenerativeModel) { | ||
| generativeModel = model | ||
| } | ||
|
|
||
| @discardableResult | ||
| public final nonisolated(nonsending) | ||
| func respond(to prompt: PartsRepresentable..., options: GenerationConfig? = nil) async throws | ||
| -> GenerativeModelSession.Response<String> { | ||
| let parts = [ModelContent(parts: prompt)] | ||
|
|
||
| var config = GenerationConfig.merge( | ||
| generativeModel.generationConfig, with: options | ||
| ) ?? GenerationConfig() | ||
| config.responseModalities = nil // Override to the default (text only) | ||
| config.candidateCount = nil // Override to the default (one candidate) | ||
|
|
||
| let response = try await generativeModel.generateContent(parts, generationConfig: config) | ||
| guard let text = response.text else { | ||
| throw GenerationError.decodingFailure( | ||
| GenerationError.Context(debugDescription: "No text in response: \(response)") | ||
| ) | ||
| } | ||
| let generatedContent = GeneratedContent(kind: .string(text)) | ||
|
|
||
| return GenerativeModelSession.Response( | ||
| content: text, rawContent: generatedContent, rawResponse: response | ||
| ) | ||
| } | ||
|
|
||
| @discardableResult | ||
| public final nonisolated(nonsending) | ||
| func respond(to prompt: PartsRepresentable..., schema: GenerationSchema, | ||
| includeSchemaInPrompt: Bool = true, options: GenerationConfig? = nil) async throws | ||
| -> GenerativeModelSession.Response<GeneratedContent> { | ||
| let parts = [ModelContent(parts: prompt)] | ||
| var config = GenerationConfig.merge( | ||
| generativeModel.generationConfig, with: options | ||
| ) ?? GenerationConfig() | ||
| config.responseMIMEType = "application/json" | ||
| config.responseJSONSchema = includeSchemaInPrompt ? try schema.toGeminiJSONSchema() : nil | ||
| config.responseSchema = nil // `responseSchema` must not be set with `responseJSONSchema` | ||
| config.responseModalities = nil // Override to the default (text only) | ||
| config.candidateCount = nil // Override to the default (one candidate) | ||
|
|
||
| let response = try await generativeModel.generateContent(parts, generationConfig: config) | ||
| guard let text = response.text else { | ||
| throw GenerationError.decodingFailure( | ||
| GenerationError.Context(debugDescription: "No text in response: \(response)") | ||
| ) | ||
| } | ||
| let generatedContent = try GeneratedContent(json: text) | ||
|
|
||
| return GenerativeModelSession.Response( | ||
| content: generatedContent, rawContent: generatedContent, rawResponse: response | ||
| ) | ||
| } | ||
|
|
||
| @discardableResult | ||
| public final nonisolated(nonsending) | ||
| func respond<Content>(to prompt: PartsRepresentable..., | ||
| generating type: Content.Type = Content.self, | ||
| includeSchemaInPrompt: Bool = true, | ||
| options: GenerationConfig? = nil) async throws | ||
| -> GenerativeModelSession.Response<Content> where Content: Generable { | ||
| let response = try await respond( | ||
| to: prompt, | ||
| schema: type.generationSchema, | ||
| includeSchemaInPrompt: includeSchemaInPrompt, | ||
| options: options | ||
| ) | ||
|
|
||
| let content = try Content(response.rawContent) | ||
|
|
||
| return GenerativeModelSession.Response( | ||
| content: content, rawContent: response.rawContent, rawResponse: response.rawResponse | ||
| ) | ||
| } | ||
|
|
||
| public struct Response<Content> where Content: Generable { | ||
| public let content: Content | ||
| public let rawContent: GeneratedContent | ||
| public let rawResponse: GenerateContentResponse | ||
| } | ||
|
|
||
| public enum GenerationError: Error, LocalizedError { | ||
| public struct Context: Sendable { | ||
| public let debugDescription: String | ||
|
|
||
| init(debugDescription: String) { | ||
| self.debugDescription = debugDescription | ||
| } | ||
| } | ||
|
|
||
| case decodingFailure(GenerativeModelSession.GenerationError.Context) | ||
| } | ||
| } | ||
| #endif // compiler(>=6.2) && canImport(FoundationModels) |
Oops, something went wrong.
Oops, something went wrong.
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.
Uh oh!
There was an error while loading. Please reload this page.