|
| 1 | +// Copyright 2026 Google LLC |
| 2 | +// |
| 3 | +// Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +// you may not use this file except in compliance with the License. |
| 5 | +// You may obtain a copy of the License at |
| 6 | +// |
| 7 | +// http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +// |
| 9 | +// Unless required by applicable law or agreed to in writing, software |
| 10 | +// distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +// See the License for the specific language governing permissions and |
| 13 | +// limitations under the License. |
| 14 | + |
| 15 | +#if compiler(>=6.2.3) && canImport(FoundationModels) |
| 16 | + import Foundation |
| 17 | + import FoundationModels |
| 18 | + |
| 19 | + @available(iOS 26.0, macOS 26.0, visionOS 26.0, *) |
| 20 | + @available(tvOS, unavailable) |
| 21 | + @available(watchOS, unavailable) |
| 22 | + extension FoundationModels.LanguageModelSession: _ModelSession { |
| 23 | + /// Returns `true` if the session has history (i.e., it has already had one or more chat turns). |
| 24 | + /// |
| 25 | + /// > Important: This property is for **internal use only** and may change at any time. |
| 26 | + public var _hasHistory: Bool { |
| 27 | + return transcript.contains { entry in |
| 28 | + if case .instructions = entry { |
| 29 | + return false |
| 30 | + } |
| 31 | + |
| 32 | + return true |
| 33 | + } |
| 34 | + } |
| 35 | + |
| 36 | + /// Sends a prompt to the model and returns a ``_ModelSessionResponse``. |
| 37 | + /// |
| 38 | + /// > Important: This method is for **internal use only** and may change at any time. |
| 39 | + /// |
| 40 | + /// - Parameters: |
| 41 | + /// - prompt: The content to send to the model. |
| 42 | + /// - schema: An optional schema for structured outputs. |
| 43 | + /// - includeSchemaInPrompt: Whether to include the `schema` in the request to the model; if |
| 44 | + /// `false`, structured output (JSON) is requested but the schema is not strictly enforced. |
| 45 | + /// - options: A set of options, represented as a ``GenerationOptionsRepresentable`` type. |
| 46 | + public func _respond(to prompt: [any Part], schema: FirebaseAI.GenerationSchema?, |
| 47 | + includeSchemaInPrompt: Bool, |
| 48 | + options: any GenerationOptionsRepresentable) async throws |
| 49 | + -> _ModelSessionResponse { |
| 50 | + let prompt = try prompt.toFoundationModelsPrompt() |
| 51 | + |
| 52 | + let response: FoundationModels.LanguageModelSession |
| 53 | + .Response<FoundationModels.GeneratedContent> |
| 54 | + if let schema { |
| 55 | + response = try await respond( |
| 56 | + to: prompt, |
| 57 | + schema: schema.generationSchema, |
| 58 | + includeSchemaInPrompt: includeSchemaInPrompt, |
| 59 | + options: options.generationOptions |
| 60 | + ) |
| 61 | + } else { |
| 62 | + response = try await respond( |
| 63 | + to: prompt, |
| 64 | + schema: String.generationSchema, |
| 65 | + options: options.generationOptions |
| 66 | + ) |
| 67 | + } |
| 68 | + |
| 69 | + return makeResponse(from: response.rawContent, schema: schema) |
| 70 | + } |
| 71 | + |
| 72 | + /// Sends a prompt to the model and streams the model's response. |
| 73 | + /// |
| 74 | + /// - Parameters: |
| 75 | + /// - prompt: The content to send to the model. |
| 76 | + /// - schema: An optional schema for structured outputs. |
| 77 | + /// - includeSchemaInPrompt: Whether to include the `schema` in the request to the model; if |
| 78 | + /// `false`, structured output (JSON) is requested but the schema is not strictly enforced. |
| 79 | + /// - options: A set of options, represented as a ``GenerationOptionsRepresentable`` type. |
| 80 | + public func _streamResponse(to prompt: [any Part], schema: FirebaseAI.GenerationSchema?, |
| 81 | + includeSchemaInPrompt: Bool, |
| 82 | + options: any GenerationOptionsRepresentable) |
| 83 | + -> sending AsyncThrowingStream<_ModelSessionResponse, any Error> { |
| 84 | + return AsyncThrowingStream { continuation in |
| 85 | + let foundationModelsPrompt: Prompt |
| 86 | + do { |
| 87 | + foundationModelsPrompt = try prompt.toFoundationModelsPrompt() |
| 88 | + } catch { |
| 89 | + continuation.finish(throwing: error) |
| 90 | + return |
| 91 | + } |
| 92 | + |
| 93 | + let stream: FoundationModels.LanguageModelSession |
| 94 | + .ResponseStream<FoundationModels.GeneratedContent> |
| 95 | + if let schema { |
| 96 | + stream = streamResponse( |
| 97 | + to: foundationModelsPrompt, |
| 98 | + schema: schema.generationSchema, |
| 99 | + includeSchemaInPrompt: includeSchemaInPrompt, |
| 100 | + options: options.generationOptions |
| 101 | + ) |
| 102 | + } else { |
| 103 | + stream = streamResponse( |
| 104 | + to: foundationModelsPrompt, |
| 105 | + schema: String.generationSchema, |
| 106 | + options: options.generationOptions |
| 107 | + ) |
| 108 | + } |
| 109 | + |
| 110 | + let task = Task { |
| 111 | + do { |
| 112 | + for try await snapshot in stream { |
| 113 | + let response = makeResponse(from: snapshot.rawContent, schema: schema) |
| 114 | + |
| 115 | + continuation.yield(response) |
| 116 | + } |
| 117 | + continuation.finish() |
| 118 | + } catch { |
| 119 | + continuation.finish(throwing: error) |
| 120 | + return |
| 121 | + } |
| 122 | + } |
| 123 | + continuation.onTermination = { _ in task.cancel() } |
| 124 | + } |
| 125 | + } |
| 126 | + |
| 127 | + private func makeResponse(from content: FoundationModels.GeneratedContent, |
| 128 | + schema: FirebaseAI.GenerationSchema?) -> _ModelSessionResponse { |
| 129 | + let responseText: String |
| 130 | + if schema == nil, case let .string(text) = content.kind { |
| 131 | + responseText = text |
| 132 | + } else { |
| 133 | + responseText = content.jsonString |
| 134 | + } |
| 135 | + |
| 136 | + let generatedContent = content.firebaseGeneratedContent |
| 137 | + let modelContent = ModelContent( |
| 138 | + role: "model", |
| 139 | + parts: [TextPart(responseText, isThought: false, thoughtSignature: nil)] |
| 140 | + ) |
| 141 | + let candidate = Candidate( |
| 142 | + content: modelContent, |
| 143 | + safetyRatings: [], |
| 144 | + finishReason: nil, |
| 145 | + citationMetadata: nil |
| 146 | + ) |
| 147 | + let rawResponse = GenerateContentResponse( |
| 148 | + candidates: [candidate], |
| 149 | + modelVersion: FirebaseAI.SystemLanguageModel.modelName |
| 150 | + ) |
| 151 | + |
| 152 | + return _ModelSessionResponse(rawContent: generatedContent, rawResponse: rawResponse) |
| 153 | + } |
| 154 | + } |
| 155 | + |
| 156 | + @available(iOS 26.0, macOS 26.0, visionOS 26.0, *) |
| 157 | + @available(tvOS, unavailable) |
| 158 | + @available(watchOS, unavailable) |
| 159 | + private extension GenerationOptionsRepresentable { |
| 160 | + var generationOptions: FoundationModels.GenerationOptions { |
| 161 | + guard let options = responseGenerationOptions.foundationModelsGenerationOptions else { |
| 162 | + return FoundationModels.GenerationOptions() |
| 163 | + } |
| 164 | + |
| 165 | + return options.toFoundationModels() |
| 166 | + } |
| 167 | + } |
| 168 | +#endif // compiler(>=6.2.3) && canImport(FoundationModels) |
0 commit comments