@@ -32,18 +32,26 @@ public final class LiveSession: NSObject, URLSessionWebSocketDelegate, URLSessio
32
32
let generationConfig : LiveGenerationConfig ?
33
33
let webSocket : URLSessionWebSocketTask
34
34
35
+ // TODO: Refactor this property, potentially returning responses after `connect`.
36
+ public let responses : AsyncThrowingStream < BidiGenerateContentServerMessage , Error >
37
+
35
38
private var state : State = . notConnected
36
39
private var pendingMessages : [ ( String , CheckedContinuation < Void , Error > ) ] = [ ]
37
40
private let jsonEncoder = JSONEncoder ( )
38
41
private let jsonDecoder = JSONDecoder ( )
39
42
43
+ // TODO: Properly wrap callback code using `withCheckedContinuation` or similar.
44
+ private let responseContinuation : AsyncThrowingStream < BidiGenerateContentServerMessage , Error >
45
+ . Continuation
46
+
40
47
init ( modelResourceName: String ,
41
48
generationConfig: LiveGenerationConfig ? ,
42
49
url: URL ,
43
50
urlSession: URLSession ) {
44
51
self . modelResourceName = modelResourceName
45
52
self . generationConfig = generationConfig
46
53
webSocket = urlSession. webSocketTask ( with: url)
54
+ ( responses, responseContinuation) = AsyncThrowingStream . makeStream ( )
47
55
}
48
56
49
57
func open( ) async throws {
@@ -64,6 +72,7 @@ public final class LiveSession: NSObject, URLSessionWebSocketDelegate, URLSessio
64
72
continuation. resume ( throwing: error)
65
73
}
66
74
pendingMessages. removeAll ( )
75
+ responseContinuation. finish ( throwing: error)
67
76
}
68
77
69
78
private func processPendingMessages( ) {
@@ -144,6 +153,7 @@ public final class LiveSession: NSObject, URLSessionWebSocketDelegate, URLSessio
144
153
print ( " Web Socket closed. " )
145
154
state = . closed
146
155
failPendingMessages ( with: WebSocketError . connectionClosed)
156
+ responseContinuation. finish ( )
147
157
}
148
158
149
159
func setReceiveHandler( ) {
@@ -172,7 +182,6 @@ public final class LiveSession: NSObject, URLSessionWebSocketDelegate, URLSessio
172
182
self . state = . ready
173
183
self . processPendingMessages ( )
174
184
case . serverContent:
175
- // TODO: Return the serverContent to the developer
176
185
print ( " Server Content: \( responseJSON) " )
177
186
case . toolCall:
178
187
// TODO: Tool calls not yet implemented
@@ -188,6 +197,8 @@ public final class LiveSession: NSObject, URLSessionWebSocketDelegate, URLSessio
188
197
}
189
198
}
190
199
200
+ self . responseContinuation. yield ( response)
201
+
191
202
if self . state == . closed {
192
203
print ( " Web socket is closed, not listening for more messages. " )
193
204
} else {
@@ -201,6 +212,7 @@ public final class LiveSession: NSObject, URLSessionWebSocketDelegate, URLSessio
201
212
// handle the error
202
213
print ( error)
203
214
self . state = . closed
215
+ self . responseContinuation. finish ( throwing: error)
204
216
}
205
217
}
206
218
}
0 commit comments