-
Notifications
You must be signed in to change notification settings - Fork 1.8k
Expand file tree
/
Copy pathGenerativeModelSession.swift
More file actions
755 lines (663 loc) · 29.5 KB
/
Copy pathGenerativeModelSession.swift
File metadata and controls
755 lines (663 loc) · 29.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
// 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.3)` when Xcode 26.2 is the minimum supported version.
#if compiler(>=6.2.3)
private import FirebaseCoreInternal
import Foundation
#if canImport(FoundationModels)
import FoundationModels
#endif // canImport(FoundationModels)
/// A session that handles multi-turn interactions with a generative model, similar to ``Chat``.
///
/// A `GenerativeModelSession` retains history between requests. For single-turn requests to a
/// model, use `generativeModelSession(model:tools:instructions:)` to start a new session.
/// `GenerativeModelSession` is particularly useful for generating structured data.
///
/// **Public Preview**: This API is a public preview and may be subject to change.
///
/// Example usage:
/// ```swift
/// @Generable
/// struct UserProfile {
/// @Guide(description: "A unique username for the user.")
/// var username: String
///
/// @Guide(description: "A short bio about the user, no more than 100 characters.")
/// var bio: String
///
/// @Guide(description: "A list of the user's favorite topics.", .count(3))
/// var favoriteTopics: [String]
/// }
///
/// let firebaseAI = // ... a `FirebaseAI` instance
/// let session = firebaseAI.generativeModelSession(model: "gemini-model-name")
/// let prompt = "Generate a user profile for a cat lover who enjoys hiking."
/// let response = try await session.respond(to: prompt, generating: UserProfile.self)
///
/// print("Username: \(response.content.username)")
/// print("Bio: \(response.content.bio)")
/// print("Favorite Topics: \(response.content.favoriteTopics.joined(separator: ", "))")
/// ```
public final class GenerativeModelSession: Sendable {
let sessionManager: SessionManager
let instructions: FirebaseAI.Instructions?
// The maximum number of automatic back-and-forth turns the session will perform to resolve
// function calls.
//
// This prevents infinite looping if the model consistently requests one or more function calls.
//
// TODO: Add ability to configure this setting.
static let maxAutoFunctionCallTurns = 10
/// Creates a new `GenerativeModelSession` with the given model.
///
/// **Public Preview**: This API is a public preview and may be subject to change.
///
/// - Parameters:
/// - model: The `GenerativeModel` to use for generating content.
/// - tools: A list of tools that extend the capabilities of the model. These are typically
/// native Gemini ``FirebaseAILogic/Tool``s, such as ``ToolRepresentable/googleSearch(_:)``,
/// or instances conforming to ``ToolRepresentable`` for automatic function calling.
/// - instructions: System instructions that direct the model's behavior.
init(model: any LanguageModel, tools: [any ToolRepresentable]? = nil,
instructions: FirebaseAI.Instructions? = nil) {
sessionManager = SessionManager(model: model, tools: tools)
self.instructions = instructions
}
/// Sends a new prompt to the model and returns a `Response` containing the generated content as
/// a `String`.
///
/// **Public Preview**: This API is a public preview and may be subject to change.
/// - Parameter prompt: The content to send to the model.
/// - Parameter options: An optional `GenerationConfig` to override the model's default
/// generation configuration.
/// - Returns: A `Response` containing the generated content as a `String`.
/// - Throws: A `GenerationError` if the model fails to generate a response.
@discardableResult
public nonisolated(nonsending)
func respond(to prompt: PartsRepresentable...,
options: any GenerationOptionsRepresentable
= ResponseGenerationOptions.default) async throws
-> GenerativeModelSession.Response<String> {
return try await respond(
to: prompt,
schema: nil as FirebaseAI.GenerationSchema?,
generating: String.self,
includeSchemaInPrompt: false,
options: options
)
}
#if canImport(FoundationModels)
/// Sends a new prompt to the model and returns a `Response` containing the generated content
/// as
/// `GeneratedContent`.
///
/// **Public Preview**: This API is a public preview and may be subject to change.
/// - Parameter prompt: The content to send to the model.
/// - Parameter schema: The `GenerationSchema` to use for generating the content.
/// - Parameter includeSchemaInPrompt: Whether to include the schema in the prompt to the
/// model.
/// - Parameter options: An optional `GenerationConfig` to override the model's default
/// generation configuration.
/// - Returns: A `Response` containing the generated content as `GeneratedContent`.
/// - Throws: A `GenerationError` if the model fails to generate a response.
@available(iOS 26.0, macOS 26.0, visionOS 26.0, *)
@available(tvOS, unavailable)
@available(watchOS, unavailable)
@discardableResult
nonisolated(nonsending)
func respond(to prompt: PartsRepresentable...,
schema: FoundationModels.GenerationSchema,
includeSchemaInPrompt: Bool = true,
options: any GenerationOptionsRepresentable =
ResponseGenerationOptions.default) async throws
-> GenerativeModelSession.Response<FirebaseAI.GeneratedContent> {
// TODO: Replace `FoundationModels.GenerationSchema` and make this method public when
// `FirebaseAI.GenerationSchema`'s public API is ready.
return try await respond(
to: prompt,
schema: FirebaseAI.GenerationSchema(schema),
generating: FirebaseAI.GeneratedContent.self,
includeSchemaInPrompt: includeSchemaInPrompt,
options: options
)
}
/// Sends a new prompt to the model and returns a `Response` containing the generated content
/// as
/// a `Generable` type.
///
/// **Public Preview**: This API is a public preview and may be subject to change.
/// - Parameter prompt: The content to send to the model.
/// - Parameter type: The `Generable` type to decode the response into.
/// - Parameter includeSchemaInPrompt: Whether to include the schema in the prompt to the
/// model.
/// - Parameter options: An optional `GenerationConfig` to override the model's default
/// generation configuration.
/// - Returns: A `Response` containing the generated content as the specified `Generable`
/// type.
/// - Throws: A `GenerationError` if the model fails to generate a response.
@available(iOS 26.0, macOS 26.0, visionOS 26.0, *)
@available(tvOS, unavailable)
@available(watchOS, unavailable)
@discardableResult
public nonisolated(nonsending)
func respond<Content>(to prompt: PartsRepresentable...,
generating type: Content.Type = Content.self,
includeSchemaInPrompt: Bool = true,
options: any GenerationOptionsRepresentable
= ResponseGenerationOptions.default) async throws
-> GenerativeModelSession.Response<Content> where Content: Generable {
return try await respond(
to: prompt,
schema: FirebaseAI.GenerationSchema(Content.generationSchema),
generating: type,
includeSchemaInPrompt: includeSchemaInPrompt,
options: options
)
}
/// Streams the model's response as `GeneratedContent`.
///
/// **Public Preview**: This API is a public preview and may be subject to change.
/// - Parameter prompt: The content to send to the model.
/// - Parameter schema: The `GenerationSchema` to use for generating the content.
/// - Parameter includeSchemaInPrompt: Whether to include the schema in the prompt to the
/// model.
/// - Parameter options: An optional `GenerationConfig` to override the model's default
/// generation configuration.
/// - Returns: A `ResponseStream` that yields snapshots of the generated content.
@available(iOS 26.0, macOS 26.0, visionOS 26.0, *)
@available(tvOS, unavailable)
@available(watchOS, unavailable)
func streamResponse(to prompt: PartsRepresentable...,
schema: FoundationModels.GenerationSchema,
includeSchemaInPrompt: Bool = true,
options: any GenerationOptionsRepresentable
= ResponseGenerationOptions.default)
-> sending GenerativeModelSession.ResponseStream<
FirebaseAI.GeneratedContent, FirebaseAI.GeneratedContent
> {
// TODO: Replace `FoundationModels.GenerationSchema` and make this method public when
// `FirebaseAI.GenerationSchema`'s public API is ready.
return streamResponse(
to: prompt,
schema: FirebaseAI.GenerationSchema(schema),
generating: FirebaseAI.GeneratedContent.self,
includeSchemaInPrompt: includeSchemaInPrompt,
options: options
)
}
/// Streams the model's response as a `Generable` type.
///
/// **Public Preview**: This API is a public preview and may be subject to change.
/// - Parameter prompt: The content to send to the model.
/// - Parameter type: The `Generable` type to decode the response into.
/// - Parameter includeSchemaInPrompt: Whether to include the schema in the prompt to the
/// model.
/// - Parameter options: An optional `GenerationConfig` to override the model's default
/// generation configuration.
/// - Returns: A `ResponseStream` that yields snapshots of the generated content.
@available(iOS 26.0, macOS 26.0, visionOS 26.0, *)
@available(tvOS, unavailable)
@available(watchOS, unavailable)
public func streamResponse<Content>(to prompt: PartsRepresentable...,
generating type: Content.Type = Content.self,
includeSchemaInPrompt: Bool = true,
options: any GenerationOptionsRepresentable =
ResponseGenerationOptions.default)
-> sending GenerativeModelSession.ResponseStream<
Content, Content.PartiallyGenerated
> where Content: Generable {
return streamResponse(
to: prompt,
schema: FirebaseAI.GenerationSchema(type.generationSchema),
generating: type,
includeSchemaInPrompt: includeSchemaInPrompt,
options: options
)
}
#endif // canImport(FoundationModels)
/// Streams the model's response as a `String`.
///
/// **Public Preview**: This API is a public preview and may be subject to change.
/// - Parameter prompt: The content to send to the model.
/// - Parameter options: An optional `GenerationConfig` to override the model's default
/// generation configuration.
/// - Returns: A `ResponseStream` that yields snapshots of the generated content.
@available(macOS 12.0, watchOS 8.0, *)
public func streamResponse(to prompt: PartsRepresentable...,
options: any GenerationOptionsRepresentable
= ResponseGenerationOptions.default)
-> sending GenerativeModelSession.ResponseStream<String, String> {
return streamResponse(
to: prompt,
schema: nil,
generating: String.self,
includeSchemaInPrompt: false,
options: options
)
}
// MARK: - Internal
private nonisolated(nonsending)
func respond<Content>(to prompt: [PartsRepresentable], schema: FirebaseAI.GenerationSchema?,
generating type: Content.Type, includeSchemaInPrompt: Bool,
options: any GenerationOptionsRepresentable) async throws
-> GenerativeModelSession.Response<Content> {
try sessionManager.startResponding()
defer {
self.sessionManager.finishResponding()
}
let session = try sessionManager.getOrStartSession(
instructions: instructions
)
let response = try await session._respond(
to: prompt.partsValue,
schema: schema,
includeSchemaInPrompt: includeSchemaInPrompt,
options: options
)
return try GenerativeModelSession.Response(
content: Self.resolveContent(from: response.rawContent),
rawContent: response.rawContent,
rawResponse: response.rawResponse
)
}
@available(macOS 12.0, watchOS 8.0, *)
private func streamResponse<Content, PartialContent>(to prompt: any PartsRepresentable,
schema: FirebaseAI.GenerationSchema?,
generating type: Content.Type,
includeSchemaInPrompt: Bool,
options: any GenerationOptionsRepresentable)
-> sending GenerativeModelSession.ResponseStream<Content, PartialContent> {
let parts = prompt.partsValue
return GenerativeModelSession.ResponseStream<Content, PartialContent> { context in
do {
try self.sessionManager.startResponding()
} catch {
await context.finish(throwing: error)
return
}
defer {
self.sessionManager.finishResponding()
}
do {
let session = try self.sessionManager.getOrStartSession(
instructions: self.instructions
)
let stream = session._streamResponse(
to: parts,
schema: schema,
includeSchemaInPrompt: includeSchemaInPrompt,
options: options
)
for try await response in stream {
let rawResult = GenerativeModelSession.ResponseStream<Content, PartialContent>
.RawResult(
rawContent: response.rawContent,
rawResponse: response.rawResponse
)
await context.yield(rawResult)
}
await context.finish()
return
} catch {
await context.finish(throwing: error)
}
}
}
static func makeRawContent(from text: String, generationID: FirebaseAI.GenerationID?,
hasSchema: Bool, isComplete: Bool) throws
-> FirebaseAI.GeneratedContent {
if hasSchema {
if text.isEmpty && !isComplete {
return FirebaseAI.GeneratedContent(
// TODO: Set `kind:` to `.array(...)`, `.bool()`, `.number()` based on schema type.
kind: .structure(properties: [:], orderedKeys: []),
id: generationID,
isComplete: isComplete
)
}
return try FirebaseAI.GeneratedContent(json: text, id: generationID, isComplete: isComplete)
}
#if canImport(FoundationModels) && IS_FOUNDATION_MODELS_SUPPORTED_PLATFORM
if #available(iOS 26.0, macOS 26.0, visionOS 26.0, *) {
return FirebaseAI
.GeneratedContent(
kind: FoundationModels.GeneratedContent.Kind.string(text),
id: generationID,
isComplete: isComplete
)
}
#endif // canImport(FoundationModels) && IS_FOUNDATION_MODELS_SUPPORTED_PLATFORM
return FirebaseAI.GeneratedContent(
kind: FirebaseAI.GeneratedContent.Kind.string(text),
id: generationID,
isComplete: isComplete
)
}
private static func resolveContent<T>(from rawContent: FirebaseAI.GeneratedContent) throws
-> T {
if let content = rawContent as? T {
return content
}
#if canImport(FoundationModels) && IS_FOUNDATION_MODELS_SUPPORTED_PLATFORM
if #available(iOS 26.0, macOS 26.0, visionOS 26.0, *), let contentMetatype = T
.self as? (any FoundationModels.ConvertibleFromGeneratedContent.Type),
let content = try contentMetatype.init(rawContent) as? T {
return content
}
#endif // canImport(FoundationModels) && IS_FOUNDATION_MODELS_SUPPORTED_PLATFORM
if let contentMetatype = T.self as? (any FirebaseAI.ConvertibleFromGeneratedContent.Type),
let content = try contentMetatype.init(rawContent) as? T {
return content
}
assertionFailure("Unsupported type: \(T.self).")
// In release builds we throw an error instead of crashing but this state should be
// unreachable based on the public API.
throw GenerativeModelSession.TypeConversionError(
from: type(of: rawContent), to: T.self
)
}
}
extension GenerativeModelSession {
final class SessionManager: @unchecked Sendable {
// TODO: Track when sessions have permanent failures.
// TODO: Track and propagate history status (`Transcript`) for `modelSessions`.
private let model: any LanguageModel
private let tools: [any ToolRepresentable]?
private let _isResponding = UnfairLock(false)
private(set) var _activeSession: (any _ModelSession)?
init(model: any LanguageModel, tools: [any ToolRepresentable]?) {
self.model = model
self.tools = tools
}
var isResponding: Bool {
_isResponding.value()
}
func startResponding() throws {
try _isResponding.withLock { isResponding in
guard !isResponding else {
throw GenerativeModelSession.GenerationError.concurrentRequests(
GenerativeModelSession.GenerationError.Context(debugDescription: """
Attempted to start a new generation request while one was already in progress. \
Create an additional session to perform concurrent requests.
""")
)
}
isResponding = true
}
}
func finishResponding() {
_isResponding.withLock { isResponding in
assert(isResponding, "`finishResponding` called but `isResponding` is false.")
isResponding = false
}
}
func getOrStartSession(instructions: FirebaseAI.Instructions?) throws -> any _ModelSession {
try _isResponding.withLock { isResponding in
if let currentSession = _activeSession {
return currentSession
} else {
let newSession = try model._startSession(tools: tools, instructions: instructions)
_activeSession = newSession
return newSession
}
}
}
}
}
// MARK: - Response Types
public extension GenerativeModelSession {
/// The response from a `respond` call.
struct Response<Content> {
/// The generated content, decoded into the requested `Generable` type.
public let content: Content
/// The raw, undecoded `GeneratedContent` from the model.
public let rawContent: FirebaseAI.GeneratedContent
/// The raw `GenerateContentResponse` from the model.
public let rawResponse: GenerateContentResponse
}
}
public extension GenerativeModelSession {
/// An asynchronous sequence of snapshots of the model's response.
struct ResponseStream<Content, PartialContent>: AsyncSequence {
public typealias Element = Snapshot
/// A snapshot of the model's response at a point in time.
public struct Snapshot {
/// The partially generated content, decoded into the requested `Generable`'s partial type.
public let content: PartialContent
/// The raw, undecoded `GeneratedContent` from the model.
public let rawContent: FirebaseAI.GeneratedContent
/// The raw `GenerateContentResponse` from the model.
public let rawResponse: GenerateContentResponse
}
private let rawStream: AsyncThrowingStream<RawResult, Error>
private let context: StreamContext
init(_ builder: @escaping @Sendable (StreamContext) async -> Void) {
var extractedContinuation: AsyncThrowingStream<RawResult, Error>.Continuation!
let stream = AsyncThrowingStream(RawResult.self) { continuation in
extractedContinuation = continuation
}
rawStream = stream
let context = StreamContext(continuation: extractedContinuation)
self.context = context
let task = Task {
await builder(context)
}
extractedContinuation.onTermination = { _ in
task.cancel()
}
}
/// An iterator that provides snapshots of the model's response.
public struct AsyncIterator: AsyncIteratorProtocol {
private var rawIterator: AsyncThrowingStream<RawResult, Error>.Iterator
init(rawIterator: AsyncThrowingStream<RawResult, Error>.Iterator) {
self.rawIterator = rawIterator
}
@available(iOS 18.0, macOS 15.0, macCatalyst 18.0, tvOS 18.0, watchOS 11.0, visionOS 2.0, *)
public mutating func next(isolation actor: isolated (any Actor)?) async throws
-> Snapshot? {
var lastDecodingError: Error? = nil
while let rawResult = try await rawIterator.next(isolation: actor) {
do {
// If it parses successfully, return the snapshot and discard any errors from previous
// loop iterations.
return try process(rawResult)
} catch {
// Intermediate failure (e.g., incomplete JSON that could not be parsed).
// Hold onto the error and let the loop fetch the next chunk.
lastDecodingError = error
}
}
// If the last chunk processed resulted in an error, throw it.
if let lastDecodingError {
throw lastDecodingError
}
return nil
}
public mutating func next() async throws -> Snapshot? {
var lastDecodingError: Error? = nil
while let rawResult = try await rawIterator.next() {
do {
// If it parses successfully, return the snapshot and discard any errors from previous
// loop iterations.
return try process(rawResult)
} catch {
// Intermediate failure (e.g., incomplete JSON that could not be parsed).
// Hold onto the error and let the loop fetch the next chunk.
lastDecodingError = error
}
}
// If the last chunk processed resulted in an error, throw it.
if let lastDecodingError {
throw lastDecodingError
}
return nil
}
private func process(_ rawResult: RawResult) throws -> Snapshot {
let partialContent: PartialContent = try GenerativeModelSession
.resolveContent(from: rawResult.rawContent)
return Snapshot(
content: partialContent,
rawContent: rawResult.rawContent,
rawResponse: rawResult.rawResponse
)
}
}
public func makeAsyncIterator() -> AsyncIterator {
return AsyncIterator(rawIterator: rawStream.makeAsyncIterator())
}
/// Collects the entire streamed response into a single `Response`.
/// - Returns: The final `Response` containing the fully generated content.
/// - Throws: A `GenerationError` if the model fails to generate a response.
public nonisolated(nonsending)
func collect() async throws -> sending GenerativeModelSession.Response<Content> {
let finalResult = try await context.value
let content: Content = try GenerativeModelSession
.resolveContent(from: finalResult.rawContent)
return GenerativeModelSession.Response(
content: content,
rawContent: finalResult.rawContent,
rawResponse: finalResult.rawResponse
)
}
}
}
extension GenerativeModelSession.ResponseStream {
struct RawResult: Sendable {
let rawContent: FirebaseAI.GeneratedContent
let rawResponse: GenerateContentResponse
}
actor StreamContext {
private let continuation: AsyncThrowingStream<RawResult, Error>.Continuation
private var finalResult: Result<RawResult, Error>?
private var waitingContinuations: [CheckedContinuation<RawResult, Error>] = []
private var latestRaw: RawResult?
// Returns `true` if the stream has yielded one or more values.
var hasYielded: Bool {
return latestRaw != nil
}
init(continuation: AsyncThrowingStream<RawResult, Error>.Continuation) {
self.continuation = continuation
}
func yield(_ rawResult: RawResult) {
// Prevent yielding new values if the stream has already been finalized
guard finalResult == nil else { return }
latestRaw = rawResult
continuation.yield(rawResult)
}
func finish() {
continuation.finish()
finalize(with: nil)
}
func finish(throwing error: Error) {
// TODO: Wrap `FoundationModels.GenerationError` errors into equivalent
// `GenerativeModelSession.GenerationError` values.
continuation.finish(throwing: error)
finalize(with: error)
}
var value: RawResult {
get async throws {
// 1. Return immediately if we already have the final result.
if let result = finalResult {
return try result.get()
}
// 2. Cancellation check: bail out early if the calling task was cancelled.
try Task.checkCancellation()
// 3. Suspend and wait.
return try await withTaskCancellationHandler {
try await withCheckedThrowingContinuation { continuation in
self.add(continuation)
}
} onCancel: {
// If the task calling `collect()` is cancelled, fail the stream immediately.
// This guarantees the continuation is resumed with a CancellationError.
Task {
await self.finish(throwing: CancellationError())
}
}
}
}
private func add(_ continuation: CheckedContinuation<RawResult, Error>) {
if let result = finalResult {
continuation.resume(with: result)
} else {
waitingContinuations.append(continuation)
}
}
private func finalize(with error: Error?) {
// Guards against resuming continuations multiple times, which would crash.
guard finalResult == nil else { return }
let result: Result<RawResult, Error>
if let error = error {
result = .failure(error)
} else if let last = latestRaw {
result = .success(last)
} else {
result = .failure(
GenerativeModelSession.GenerationError.decodingFailure(
GenerativeModelSession.GenerationError.Context(
debugDescription: "No content generated in stream."
)
)
)
}
finalResult = result
for continuation in waitingContinuations {
continuation.resume(with: result)
}
waitingContinuations.removeAll()
}
}
}
extension GenerativeModelSession {
enum ErrorCodes: Int {
// Generation Errors
case decodingFailure = 1000
// Internal Errors
case typeConversionFailed = 2000
}
static let errorDomain = "\(Constants.baseErrorDomain).\(GenerativeModelSession.self)"
/// An error that occurs during content generation.
@nonexhaustive
public enum GenerationError: Error, LocalizedError {
/// A context providing more information about the generation error.
public struct Context: Sendable {
/// A debug description of the error.
public let debugDescription: String
init(debugDescription: String) {
self.debugDescription = debugDescription
}
}
case assetsUnavailable(GenerativeModelSession.GenerationError.Context)
/// The model's response could not be decoded.
case decodingFailure(GenerativeModelSession.GenerationError.Context)
case concurrentRequests(GenerativeModelSession.GenerationError.Context)
/// The content provided as a prompt is not supported by the model.
case unsupportedPromptContent(GenerativeModelSession.GenerationError.Context)
case internalError(GenerativeModelSession.GenerationError.Context, underlyingError: any Error)
}
enum FunctionCallingError: Error, LocalizedError {
case invalidFunctionCall
case maxFunctionCallTurnsExceeded
}
struct TypeConversionError: CustomDebugStringConvertible, CustomNSError {
public static var errorDomain: String { GenerativeModelSession.errorDomain }
public var errorCode: Int { ErrorCodes.typeConversionFailed.rawValue }
public var errorUserInfo: [String: Any] { [NSLocalizedDescriptionKey: debugDescription] }
let debugDescription: String
init(from fromType: Any.Type, to toType: Any.Type) {
debugDescription = "Failed to convert from type '\(fromType)' to '\(toType)'."
}
}
}
#endif // compiler(>=6.2.3)