@@ -128,9 +128,28 @@ typealias ChatCompletionsStreamAPIBuilder = (
128128) -> any ChatCompletionsStreamAPI
129129
130130protocol ChatCompletionsStreamAPI {
131- associatedtype CompletionSequence : AsyncSequence
132- where CompletionSequence. Element == ChatCompletionsStreamDataChunk
133- func callAsFunction( ) async throws -> CompletionSequence
131+ func callAsFunction( ) async throws -> AsyncThrowingStream < ChatCompletionsStreamDataChunk , Error >
132+ }
133+
134+ extension AsyncSequence {
135+ func toStream( ) -> AsyncThrowingStream < Element , Error > {
136+ AsyncThrowingStream { continuation in
137+ let task = Task {
138+ do {
139+ for try await element in self {
140+ continuation. yield ( element)
141+ }
142+ continuation. finish ( )
143+ } catch {
144+ continuation. finish ( throwing: error)
145+ }
146+ }
147+
148+ continuation. onTermination = { _ in
149+ task. cancel ( )
150+ }
151+ }
152+ }
134153}
135154
136155struct ChatCompletionsStreamDataChunk : Codable {
@@ -159,7 +178,13 @@ struct ChatCompletionsStreamDataChunk: Codable {
159178
160179// MARK: - Non Stream API
161180
162- typealias ChatCompletionsAPIBuilder = ( String , ChatModel , URL , ChatCompletionsRequestBody , ChatGPTPrompt )
181+ typealias ChatCompletionsAPIBuilder = (
182+ String ,
183+ ChatModel ,
184+ URL ,
185+ ChatCompletionsRequestBody ,
186+ ChatGPTPrompt
187+ )
163188 -> any ChatCompletionsAPI
164189
165190protocol ChatCompletionsAPI {
0 commit comments