forked from huggingface/AnyLanguageModel
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLanguageModelSession.swift
More file actions
936 lines (831 loc) · 31.7 KB
/
LanguageModelSession.swift
File metadata and controls
936 lines (831 loc) · 31.7 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
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
import Foundation
import Observation
@Observable
public final class LanguageModelSession: @unchecked Sendable {
public var isResponding: Bool {
access(keyPath: \.isResponding)
return state.withLock { $0.isResponding }
}
public var transcript: Transcript {
access(keyPath: \.transcript)
return state.withLock { $0.transcript }
}
@ObservationIgnored private let state: Locked<State>
private let model: any LanguageModel
public let tools: [any Tool]
public let instructions: Instructions?
/// A delegate that observes and controls tool execution.
///
/// Set this property to intercept tool calls, provide custom output,
/// or stop after tool calls are generated.
///
/// - Note: This property is exclusive to AnyLanguageModel
/// and using it means your code is no longer drop-in compatible
/// with the Foundation Models framework.
@ObservationIgnored public var toolExecutionDelegate: (any ToolExecutionDelegate)?
public convenience init(
model: any LanguageModel,
tools: [any Tool] = [],
@InstructionsBuilder instructions: () throws -> Instructions
) rethrows {
try self.init(model: model, tools: tools, instructions: instructions())
}
public convenience init(
model: any LanguageModel,
tools: [any Tool] = [],
instructions: String
) {
self.init(model: model, tools: tools, instructions: Instructions(instructions), transcript: Transcript())
}
public convenience init(
model: any LanguageModel,
tools: [any Tool] = [],
instructions: Instructions? = nil
) {
self.init(model: model, tools: tools, instructions: instructions, transcript: Transcript())
}
public convenience init(
model: any LanguageModel,
tools: [any Tool] = [],
transcript: Transcript
) {
self.init(model: model, tools: tools, instructions: nil, transcript: transcript)
}
private init(
model: any LanguageModel,
tools: [any Tool],
instructions: Instructions?,
transcript: Transcript
) {
self.model = model
self.tools = tools
self.instructions = instructions
// Build transcript with instructions if provided and not already in transcript
var finalTranscript = transcript
if let instructions = instructions {
// Only add instructions if transcript doesn't already start with instructions
let hasInstructions =
finalTranscript.first.map { entry in
if case .instructions = entry { return true } else { return false }
} ?? false
if !hasInstructions {
let instructionsEntry = Transcript.Entry.instructions(
Transcript.Instructions(
segments: [.text(.init(content: instructions.description))],
toolDefinitions:
tools
.filter(\.includesSchemaInInstructions)
.map { Transcript.ToolDefinition(tool: $0) }
)
)
finalTranscript.append(instructionsEntry)
}
}
self.state = .init(.init(finalTranscript))
}
public func prewarm(promptPrefix: Prompt? = nil) {
model.prewarm(for: self, promptPrefix: promptPrefix, tools: tools.isEmpty ? nil : tools)
}
nonisolated private func beginResponding() {
withMutation(keyPath: \.isResponding) {
state.withLock { $0.beginResponding() }
}
}
nonisolated private func endResponding() {
withMutation(keyPath: \.isResponding) {
state.withLock { $0.endResponding() }
}
}
nonisolated private func wrapRespond<T>(_ operation: () async throws -> T) async throws -> T {
beginResponding()
do {
let result = try await operation()
endResponding()
return result
} catch {
endResponding()
throw error
}
}
nonisolated private func wrapStream<Content>(
_ upstream: sending ResponseStream<Content>,
promptEntry: Transcript.Entry
) -> ResponseStream<Content> where Content: Generable, Content.PartiallyGenerated: Sendable {
let session = self
let relay = AsyncThrowingStream<ResponseStream<Content>.Snapshot, any Error> { continuation in
let stream = upstream
Task {
session.beginResponding()
var lastSnapshot: ResponseStream<Content>.Snapshot?
do {
for try await snapshot in stream {
lastSnapshot = snapshot
continuation.yield(snapshot)
}
continuation.finish()
// Add response to transcript after stream completes
if let lastSnapshot {
// Extract text content from the generated content
let textContent: String
if case .string(let str) = lastSnapshot.rawContent.kind {
textContent = str
} else {
textContent = lastSnapshot.rawContent.jsonString
}
let responseEntry = Transcript.Entry.response(
Transcript.Response(
assetIDs: [],
segments: [.text(.init(content: textContent))]
)
)
session.withMutation(keyPath: \.transcript) {
session.state.withLock { $0.transcript.append(responseEntry) }
}
}
} catch {
continuation.finish(throwing: error)
}
session.endResponding()
}
}
return ResponseStream(stream: relay)
}
public struct Response<Content>: Sendable where Content: Generable, Content: Sendable {
public let content: Content
public let rawContent: GeneratedContent
public let transcriptEntries: ArraySlice<Transcript.Entry>
/// Creates a response value from generated content and transcript entries.
/// - Parameters:
/// - content: The decoded response content.
/// - rawContent: The raw content produced by the model.
/// - transcriptEntries: Transcript entries associated with the response.
public init(
content: Content,
rawContent: GeneratedContent,
transcriptEntries: ArraySlice<Transcript.Entry>
) {
self.content = content
self.rawContent = rawContent
self.transcriptEntries = transcriptEntries
}
}
@discardableResult
nonisolated public func respond<Content>(
to prompt: Prompt,
generating type: Content.Type = Content.self,
includeSchemaInPrompt: Bool = true,
options: GenerationOptions = GenerationOptions()
) async throws -> Response<Content> where Content: Generable {
try await wrapRespond {
// Add prompt to transcript
let promptEntry = Transcript.Entry.prompt(
Transcript.Prompt(
segments: [.text(.init(content: prompt.description))],
options: options,
responseFormat: nil
)
)
withMutation(keyPath: \.transcript) {
state.withLock { $0.transcript.append(promptEntry) }
}
let response = try await model.respond(
within: self,
to: prompt,
generating: type,
includeSchemaInPrompt: includeSchemaInPrompt,
options: options
)
// Add response entry to transcript
let textContent: String
if case .string(let str) = response.rawContent.kind {
textContent = str
} else {
textContent = response.rawContent.jsonString
}
let responseEntry = Transcript.Entry.response(
Transcript.Response(
assetIDs: [],
segments: [.text(.init(content: textContent))]
)
)
// Add tool entries and response to transcript
withMutation(keyPath: \.transcript) {
state.withLock { lockedState in
lockedState.transcript.append(contentsOf: response.transcriptEntries)
lockedState.transcript.append(responseEntry)
}
}
return response
}
}
nonisolated public func streamResponse<Content>(
to prompt: Prompt,
generating type: Content.Type = Content.self,
includeSchemaInPrompt: Bool = true,
options: GenerationOptions = GenerationOptions()
) -> sending ResponseStream<Content> where Content: Generable {
// Add prompt to transcript
let promptEntry = Transcript.Entry.prompt(
Transcript.Prompt(
segments: [.text(.init(content: prompt.description))],
options: options,
responseFormat: nil
)
)
withMutation(keyPath: \.transcript) {
state.withLock { $0.transcript.append(promptEntry) }
}
return wrapStream(
model.streamResponse(
within: self,
to: prompt,
generating: type,
includeSchemaInPrompt: includeSchemaInPrompt,
options: options
),
promptEntry: promptEntry
)
}
}
// MARK: - String Response Convenience Methods
extension LanguageModelSession {
@discardableResult
nonisolated public func respond(
to prompt: Prompt,
options: GenerationOptions = GenerationOptions()
) async throws -> Response<String> {
try await respond(
to: prompt,
generating: String.self,
includeSchemaInPrompt: true,
options: options
)
}
@discardableResult
nonisolated public func respond(
to prompt: String,
options: GenerationOptions = GenerationOptions()
) async throws -> Response<String> {
try await respond(to: Prompt(prompt), options: options)
}
@discardableResult
nonisolated public func respond(
options: GenerationOptions = GenerationOptions(),
@PromptBuilder prompt: () throws -> Prompt
) async throws -> Response<String> {
try await respond(to: try prompt(), options: options)
}
public func streamResponse(
to prompt: Prompt,
options: GenerationOptions = GenerationOptions()
) -> sending ResponseStream<String> {
streamResponse(
to: prompt,
generating: String.self,
includeSchemaInPrompt: true,
options: options
)
}
public func streamResponse(
to prompt: String,
options: GenerationOptions = GenerationOptions()
) -> sending ResponseStream<String> {
streamResponse(to: Prompt(prompt), options: options)
}
public func streamResponse(
options: GenerationOptions = GenerationOptions(),
@PromptBuilder prompt: () throws -> Prompt
) rethrows -> sending ResponseStream<String> {
streamResponse(to: try prompt(), options: options)
}
}
// MARK: - GeneratedContent with Schema Convenience Methods
extension LanguageModelSession {
@discardableResult
nonisolated public func respond(
to prompt: Prompt,
schema: GenerationSchema,
includeSchemaInPrompt: Bool = true,
options: GenerationOptions = GenerationOptions()
) async throws -> Response<GeneratedContent> {
try await respond(
to: prompt,
generating: GeneratedContent.self,
includeSchemaInPrompt: includeSchemaInPrompt,
options: options
)
}
@discardableResult
nonisolated public func respond(
to prompt: String,
schema: GenerationSchema,
includeSchemaInPrompt: Bool = true,
options: GenerationOptions = GenerationOptions()
) async throws -> Response<GeneratedContent> {
try await respond(
to: Prompt(prompt),
schema: schema,
includeSchemaInPrompt: includeSchemaInPrompt,
options: options
)
}
@discardableResult
nonisolated public func respond(
schema: GenerationSchema,
includeSchemaInPrompt: Bool = true,
options: GenerationOptions = GenerationOptions(),
@PromptBuilder prompt: () throws -> Prompt
) async throws -> Response<GeneratedContent> {
try await respond(
to: try prompt(),
schema: schema,
includeSchemaInPrompt: includeSchemaInPrompt,
options: options
)
}
nonisolated public func streamResponse(
to prompt: Prompt,
schema: GenerationSchema,
includeSchemaInPrompt: Bool = true,
options: GenerationOptions = GenerationOptions()
) -> sending ResponseStream<GeneratedContent> {
streamResponse(
to: prompt,
generating: GeneratedContent.self,
includeSchemaInPrompt: includeSchemaInPrompt,
options: options
)
}
nonisolated public func streamResponse(
to prompt: String,
schema: GenerationSchema,
includeSchemaInPrompt: Bool = true,
options: GenerationOptions = GenerationOptions()
) -> sending ResponseStream<GeneratedContent> {
streamResponse(
to: Prompt(prompt),
schema: schema,
includeSchemaInPrompt: includeSchemaInPrompt,
options: options
)
}
nonisolated public func streamResponse(
schema: GenerationSchema,
includeSchemaInPrompt: Bool = true,
options: GenerationOptions = GenerationOptions(),
@PromptBuilder prompt: () throws -> Prompt
) rethrows -> sending ResponseStream<GeneratedContent> {
streamResponse(to: try prompt(), schema: schema, includeSchemaInPrompt: includeSchemaInPrompt, options: options)
}
}
// MARK: - Generic Content Convenience Methods
extension LanguageModelSession {
@discardableResult
nonisolated public func respond<Content>(
to prompt: String,
generating type: Content.Type = Content.self,
includeSchemaInPrompt: Bool = true,
options: GenerationOptions = GenerationOptions()
) async throws -> Response<Content> where Content: Generable {
try await respond(
to: Prompt(prompt),
generating: type,
includeSchemaInPrompt: includeSchemaInPrompt,
options: options
)
}
@discardableResult
nonisolated public func respond<Content>(
generating type: Content.Type = Content.self,
includeSchemaInPrompt: Bool = true,
options: GenerationOptions = GenerationOptions(),
@PromptBuilder prompt: () throws -> Prompt
) async throws -> Response<Content> where Content: Generable {
try await respond(
to: try prompt(),
generating: type,
includeSchemaInPrompt: includeSchemaInPrompt,
options: options
)
}
nonisolated public func streamResponse<Content>(
to prompt: String,
generating type: Content.Type = Content.self,
includeSchemaInPrompt: Bool = true,
options: GenerationOptions = GenerationOptions()
) -> sending ResponseStream<Content> where Content: Generable {
streamResponse(
to: Prompt(prompt),
generating: type,
includeSchemaInPrompt: includeSchemaInPrompt,
options: options
)
}
public func streamResponse<Content>(
generating type: Content.Type = Content.self,
includeSchemaInPrompt: Bool = true,
options: GenerationOptions = GenerationOptions(),
@PromptBuilder prompt: () throws -> Prompt
) rethrows -> sending ResponseStream<Content> where Content: Generable {
streamResponse(
to: try prompt(),
generating: type,
includeSchemaInPrompt: includeSchemaInPrompt,
options: options
)
}
}
// MARK: - Image Convenience Methods
extension LanguageModelSession {
@discardableResult
nonisolated public func respond(
to prompt: String,
image: Transcript.ImageSegment,
options: GenerationOptions = GenerationOptions()
) async throws -> Response<String> {
try await respond(
to: prompt,
images: [image],
options: options
)
}
@discardableResult
nonisolated public func respond(
to prompt: String,
images: [Transcript.ImageSegment],
options: GenerationOptions = GenerationOptions()
) async throws -> Response<String> {
try await respond(
to: prompt,
images: images,
generating: String.self,
includeSchemaInPrompt: true,
options: options
)
}
@discardableResult
nonisolated public func respond<Content>(
to prompt: String,
image: Transcript.ImageSegment,
generating type: Content.Type = Content.self,
includeSchemaInPrompt: Bool = true,
options: GenerationOptions = GenerationOptions()
) async throws -> Response<Content> where Content: Generable {
try await respond(
to: prompt,
images: [image],
generating: type,
includeSchemaInPrompt: includeSchemaInPrompt,
options: options
)
}
@discardableResult
nonisolated public func respond<Content>(
to prompt: String,
images: [Transcript.ImageSegment],
generating type: Content.Type = Content.self,
includeSchemaInPrompt: Bool = true,
options: GenerationOptions = GenerationOptions()
) async throws -> Response<Content> where Content: Generable {
try await wrapRespond {
// Build segments from text and images
var segments: [Transcript.Segment] = []
if !prompt.isEmpty {
segments.append(.text(.init(content: prompt)))
}
segments.append(contentsOf: images.map { .image($0) })
// Add prompt to transcript
let promptEntry = Transcript.Entry.prompt(
Transcript.Prompt(
segments: segments,
options: options,
responseFormat: nil
)
)
withMutation(keyPath: \.transcript) {
state.withLock { $0.transcript.append(promptEntry) }
}
// Extract text content for the Prompt parameter
let textPrompt = Prompt(prompt)
let response = try await model.respond(
within: self,
to: textPrompt,
generating: type,
includeSchemaInPrompt: includeSchemaInPrompt,
options: options
)
// Add response entry to transcript
let textContent: String
if case .string(let str) = response.rawContent.kind {
textContent = str
} else {
textContent = response.rawContent.jsonString
}
let responseEntry = Transcript.Entry.response(
Transcript.Response(
assetIDs: [],
segments: [.text(.init(content: textContent))]
)
)
// Add tool entries and response to transcript
withMutation(keyPath: \.transcript) {
state.withLock { lockedState in
lockedState.transcript.append(contentsOf: response.transcriptEntries)
lockedState.transcript.append(responseEntry)
}
}
return response
}
}
public func streamResponse(
to prompt: String,
image: Transcript.ImageSegment,
options: GenerationOptions = GenerationOptions()
) -> sending ResponseStream<String> {
streamResponse(
to: prompt,
images: [image],
options: options
)
}
public func streamResponse(
to prompt: String,
images: [Transcript.ImageSegment],
options: GenerationOptions = GenerationOptions()
) -> sending ResponseStream<String> {
streamResponse(
to: prompt,
images: images,
generating: String.self,
includeSchemaInPrompt: true,
options: options
)
}
nonisolated public func streamResponse<Content>(
to prompt: String,
image: Transcript.ImageSegment,
generating type: Content.Type = Content.self,
includeSchemaInPrompt: Bool = true,
options: GenerationOptions = GenerationOptions()
) -> sending ResponseStream<Content> where Content: Generable {
streamResponse(
to: prompt,
images: [image],
generating: type,
includeSchemaInPrompt: includeSchemaInPrompt,
options: options
)
}
nonisolated public func streamResponse<Content>(
to prompt: String,
images: [Transcript.ImageSegment],
generating type: Content.Type = Content.self,
includeSchemaInPrompt: Bool = true,
options: GenerationOptions = GenerationOptions()
) -> sending ResponseStream<Content> where Content: Generable {
// Build segments from text and images
var segments: [Transcript.Segment] = []
if !prompt.isEmpty {
segments.append(.text(.init(content: prompt)))
}
segments.append(contentsOf: images.map { .image($0) })
// Create prompt entry that will be added when stream starts
let promptEntry = Transcript.Entry.prompt(
Transcript.Prompt(
segments: segments,
options: options,
responseFormat: nil
)
)
withMutation(keyPath: \.transcript) {
state.withLock { $0.transcript.append(promptEntry) }
}
// Extract text content for the Prompt parameter
let textPrompt = Prompt(prompt)
return wrapStream(
model.streamResponse(
within: self,
to: textPrompt,
generating: type,
includeSchemaInPrompt: includeSchemaInPrompt,
options: options
),
promptEntry: promptEntry
)
}
}
// MARK: -
extension LanguageModelSession {
@discardableResult
public func logFeedbackAttachment(
sentiment: LanguageModelFeedback.Sentiment?,
issues: [LanguageModelFeedback.Issue] = [],
desiredOutput: Transcript.Entry? = nil
) -> Data {
model.logFeedbackAttachment(
within: self,
sentiment: sentiment,
issues: issues,
desiredOutput: desiredOutput
)
}
}
// MARK: -
extension LanguageModelSession {
public enum GenerationError: Error, LocalizedError {
public struct Context: Sendable {
public let debugDescription: String
public init(debugDescription: String) {
self.debugDescription = debugDescription
}
}
public struct Refusal: Sendable {
public let transcriptEntries: [Transcript.Entry]
public init(transcriptEntries: [Transcript.Entry]) {
self.transcriptEntries = transcriptEntries
}
public var explanation: Response<String> {
get async throws {
// Extract explanation from transcript entries
let explanationText = transcriptEntries.compactMap { entry in
if case .response(let response) = entry {
return response.segments.compactMap { segment in
if case .text(let textSegment) = segment {
return textSegment.content
}
return nil
}.joined(separator: " ")
}
return nil
}.joined(separator: "\n")
return Response(
content: explanationText.isEmpty ? "No explanation available" : explanationText,
rawContent: GeneratedContent(
explanationText.isEmpty ? "No explanation available" : explanationText
),
transcriptEntries: ArraySlice(transcriptEntries)
)
}
}
public var explanationStream: ResponseStream<String> {
// Create a simple stream that yields the explanation text
let explanationText = transcriptEntries.compactMap { entry in
if case .response(let response) = entry {
return response.segments.compactMap { segment in
if case .text(let textSegment) = segment {
return textSegment.content
}
return nil
}.joined(separator: " ")
}
return nil
}.joined(separator: "\n")
let finalText = explanationText.isEmpty ? "No explanation available" : explanationText
return ResponseStream(content: finalText, rawContent: GeneratedContent(finalText))
}
}
case exceededContextWindowSize(Context)
case assetsUnavailable(Context)
case guardrailViolation(Context)
case unsupportedGuide(Context)
case unsupportedLanguageOrLocale(Context)
case decodingFailure(Context)
case rateLimited(Context)
case concurrentRequests(Context)
case refusal(Refusal, Context)
public var errorDescription: String? { nil }
public var recoverySuggestion: String? { nil }
public var failureReason: String? { nil }
}
public struct ToolCallError: Error, LocalizedError {
public var tool: any Tool
public var underlyingError: any Error
public init(tool: any Tool, underlyingError: any Error) {
self.tool = tool
self.underlyingError = underlyingError
}
public var errorDescription: String? { nil }
}
}
extension LanguageModelSession {
public struct ResponseStream<Content>: Sendable where Content: Generable, Content.PartiallyGenerated: Sendable {
private let fallbackSnapshot: Snapshot?
private let streaming: AsyncThrowingStream<Snapshot, any Error>?
/// Creates a response stream that yields a single snapshot.
/// - Parameters:
/// - content: The complete response content.
/// - rawContent: The raw content produced by the model.
public init(content: Content, rawContent: GeneratedContent) {
self.fallbackSnapshot = Snapshot(content: content.asPartiallyGenerated(), rawContent: rawContent)
self.streaming = nil
}
/// Creates a response stream that yields snapshots from an async stream.
/// - Parameter stream: The snapshot stream to relay.
public init(stream: AsyncThrowingStream<Snapshot, any Error>) {
// When streaming, snapshots arrive from the upstream sequence, so no fallback is required.
self.fallbackSnapshot = nil
self.streaming = stream
}
public struct Snapshot: Sendable where Content.PartiallyGenerated: Sendable {
public var content: Content.PartiallyGenerated
public var rawContent: GeneratedContent
/// Creates a snapshot from partially generated content and raw content.
/// - Parameters:
/// - content: The partially generated content.
/// - rawContent: The raw content produced by the model.
public init(content: Content.PartiallyGenerated, rawContent: GeneratedContent) {
self.content = content
self.rawContent = rawContent
}
}
}
}
extension LanguageModelSession.ResponseStream: AsyncSequence {
public typealias Element = Snapshot
public struct AsyncIterator: AsyncIteratorProtocol {
private var hasYielded = false
private let fallbackSnapshot: Snapshot?
private var streamIterator: AsyncThrowingStream<Snapshot, any Error>.AsyncIterator?
private let useStream: Bool
init(fallbackSnapshot: Snapshot?, stream: AsyncThrowingStream<Snapshot, any Error>?) {
self.fallbackSnapshot = fallbackSnapshot
self.streamIterator = stream?.makeAsyncIterator()
self.useStream = stream != nil
}
public mutating func next() async throws -> Snapshot? {
if useStream {
if var iterator = streamIterator {
if let value = try await iterator.next() {
// store back the advanced iterator
streamIterator = iterator
return value
}
streamIterator = iterator
}
return nil
} else {
guard !hasYielded, let fallbackSnapshot else { return nil }
hasYielded = true
return fallbackSnapshot
}
}
public typealias Element = Snapshot
}
public func makeAsyncIterator() -> AsyncIterator {
return AsyncIterator(fallbackSnapshot: fallbackSnapshot, stream: streaming)
}
nonisolated public func collect() async throws -> sending LanguageModelSession.Response<Content> {
if let streaming {
var last: Snapshot?
for try await snapshot in streaming {
last = snapshot
}
if let last {
// Attempt to materialize a concrete Content from the last snapshot
let finalContent: Content
if let concrete = last.content as? Content {
finalContent = concrete
} else {
finalContent = try Content(last.rawContent)
}
return LanguageModelSession.Response(
content: finalContent,
rawContent: last.rawContent,
transcriptEntries: []
)
}
}
if let fallbackSnapshot {
let finalContent: Content
if let concrete = fallbackSnapshot.content as? Content {
finalContent = concrete
} else {
finalContent = try Content(fallbackSnapshot.rawContent)
}
return LanguageModelSession.Response(
content: finalContent,
rawContent: fallbackSnapshot.rawContent,
transcriptEntries: []
)
}
throw ResponseStreamError.noSnapshots
}
}
private enum ResponseStreamError: Error {
case noSnapshots
}
// MARK: -
private struct State: Equatable, Sendable {
var transcript: Transcript
var isResponding: Bool { count > 0 }
private var count = 0
init(_ transcript: Transcript) {
self.transcript = transcript
}
mutating func beginResponding() {
count += 1
}
mutating func endResponding() {
count = max(0, count - 1)
}
}