@@ -20,7 +20,7 @@ public class LegacyChatGPTService: LegacyChatGPTServiceType {
2020 public var configuration : ChatGPTConfiguration
2121 public var functionProvider : ChatGPTFunctionProvider
2222
23- var runningTask : Task < Void , Never > ?
23+ var runningTask : Task < AsyncThrowingStream < String , any Error > , Never > ?
2424
2525 public init (
2626 memory: ChatGPTMemory = AutoManagedChatGPTMemory (
@@ -45,32 +45,36 @@ public class LegacyChatGPTService: LegacyChatGPTServiceType {
4545 content: String ,
4646 summary: String ? = nil
4747 ) async throws -> AsyncThrowingStream < String , Error > {
48- if !content. isEmpty || summary != nil {
49- let newMessage = ChatMessage (
50- id: uuid ( ) . uuidString,
51- role: . user,
52- content: content,
53- name: nil ,
54- toolCalls: nil ,
55- summary: summary,
56- references: [ ]
48+ let task = Task {
49+ if !content. isEmpty || summary != nil {
50+ let newMessage = ChatMessage (
51+ id: uuid ( ) . uuidString,
52+ role: . user,
53+ content: content,
54+ name: nil ,
55+ toolCalls: nil ,
56+ summary: summary,
57+ references: [ ]
58+ )
59+ await memory. appendMessage ( newMessage)
60+ }
61+
62+ let service = ChatGPTService (
63+ configuration: configuration,
64+ functionProvider: functionProvider
5765 )
58- await memory. appendMessage ( newMessage)
66+
67+ let responses = service. send ( memory)
68+
69+ return responses. compactMap { response in
70+ switch response {
71+ case let . partialText( token) : return token
72+ default : return nil
73+ }
74+ } . eraseToThrowingStream ( )
5975 }
60-
61- let service = ChatGPTService (
62- configuration: configuration,
63- functionProvider: functionProvider
64- )
65-
66- let responses = service. send ( memory)
67-
68- return responses. compactMap { response in
69- switch response {
70- case let . partialText( token) : return token
71- default : return nil
72- }
73- } . eraseToThrowingStream ( )
76+ runningTask = task
77+ return await task. value
7478 }
7579
7680 /// Send a message and get the reply in return.
@@ -96,6 +100,8 @@ public class LegacyChatGPTService: LegacyChatGPTServiceType {
96100 return try await service. send ( memory) . asText ( )
97101 }
98102
99- public func stopReceivingMessage( ) { }
103+ public func stopReceivingMessage( ) {
104+ runningTask? . cancel ( )
105+ }
100106}
101107
0 commit comments