@@ -3,6 +3,7 @@ import ChatPlugin
33import Combine
44import Foundation
55import OpenAIService
6+ import Preferences
67
78public final class ChatService : ObservableObject {
89 public let memory : AutoManagedChatGPTMemory
@@ -89,10 +90,10 @@ public final class ChatService: ObservableObject {
8990 await pluginController. stopResponding ( )
9091 await chatGPTService. stopReceivingMessage ( )
9192 isReceivingMessage = false
92-
93+
9394 // if it's stopped before the function finishes, remove the function call.
9495 await memory. mutateHistory { history in
95- if history. last? . role == . assistant && history. last? . functionCall != nil {
96+ if history. last? . role == . assistant, history. last? . functionCall != nil {
9697 history. removeLast ( )
9798 }
9899 }
@@ -149,5 +150,62 @@ public final class ChatService: ObservableObject {
149150 public func mutateHistory( _ mutator: @escaping ( inout [ ChatMessage ] ) -> Void ) async {
150151 await memory. mutateHistory ( mutator)
151152 }
153+
154+ public func handleCustomCommand( _ command: CustomCommand ) async throws {
155+ struct CustomCommandInfo {
156+ var specifiedSystemPrompt : String ?
157+ var extraSystemPrompt : String ?
158+ var sendingMessageImmediately : String ?
159+ var name : String ?
160+ }
161+
162+ let info : CustomCommandInfo ? = {
163+ switch command. feature {
164+ case let . chatWithSelection( extraSystemPrompt, prompt, useExtraSystemPrompt) :
165+ let updatePrompt = useExtraSystemPrompt ?? true
166+ return . init(
167+ extraSystemPrompt: updatePrompt ? extraSystemPrompt : nil ,
168+ sendingMessageImmediately: prompt,
169+ name: command. name
170+ )
171+ case let . customChat( systemPrompt, prompt) :
172+ return . init(
173+ specifiedSystemPrompt: systemPrompt,
174+ extraSystemPrompt: " " ,
175+ sendingMessageImmediately: prompt,
176+ name: command. name
177+ )
178+ case . promptToCode:
179+ return nil
180+ }
181+ } ( )
182+
183+ guard let info else { return }
184+
185+ let templateProcessor = CustomCommandTemplateProcessor ( )
186+ mutateSystemPrompt ( info. specifiedSystemPrompt. map ( templateProcessor. process) )
187+ mutateExtraSystemPrompt ( info. extraSystemPrompt. map ( templateProcessor. process) ?? " " )
188+
189+ let customCommandPrefix = {
190+ if let name = info. name { return " [ \( name) ] " }
191+ return " "
192+ } ( )
193+
194+ if info. specifiedSystemPrompt != nil || info. extraSystemPrompt != nil {
195+ await mutateHistory { history in
196+ history. append ( . init(
197+ role: . assistant,
198+ content: " " ,
199+ summary: " \( customCommandPrefix) System prompt is updated. "
200+ ) )
201+ }
202+ }
203+
204+ if let sendingMessageImmediately = info. sendingMessageImmediately,
205+ !sendingMessageImmediately. isEmpty
206+ {
207+ try await send ( content: templateProcessor. process ( sendingMessageImmediately) )
208+ }
209+ }
152210}
153211
0 commit comments