forked from intitni/CopilotForXcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathChatService.swift
More file actions
76 lines (66 loc) · 2.43 KB
/
ChatService.swift
File metadata and controls
76 lines (66 loc) · 2.43 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
import ChatPlugins
import Foundation
import OpenAIService
public final class ChatService: ObservableObject {
let chatGPTService: ChatGPTServiceType
let plugins = registerPlugins(
TerminalChatPlugin.self
)
var runningPlugin: ChatPlugin?
public init(chatGPTService: ChatGPTServiceType) {
self.chatGPTService = chatGPTService
}
public func send(content: String) async throws {
// look for the prefix of content, see if there is something like /command.
// If there is, then we need to find the plugin that can handle this command.
// If there is no such plugin, then we just send the message to the GPT service.
let regex = try NSRegularExpression(pattern: #"^\/([a-zA-Z0-9]+)"#)
let matches = regex.matches(in: content, range: NSRange(content.startIndex..., in: content))
if let match = matches.first {
let command = String(content[Range(match.range(at: 1), in: content)!])
if let pluginType = plugins[command] {
let plugin = pluginType.init(inside: chatGPTService, delegate: self)
await plugin.send(content: String(content.dropFirst(command.count + 1)))
}
} else {
_ = try await chatGPTService.send(content: content, summary: nil)
}
}
public func stopReceivingMessage() async {
if let runningPlugin {
await runningPlugin.cancel()
}
await chatGPTService.stopReceivingMessage()
}
public func clearHistory() async {
if let runningPlugin {
await runningPlugin.cancel()
}
await chatGPTService.clearHistory()
}
}
extension ChatService: ChatPluginDelegate {
public func pluginDidStartResponding(_ plugin: ChatPlugins.ChatPlugin) {
Task {
await chatGPTService.markReceivingMessage(true)
}
}
public func pluginDidEndResponding(_ plugin: ChatPlugins.ChatPlugin) {
Task {
await chatGPTService.markReceivingMessage(false)
}
}
public func pluginDidStart(_ plugin: ChatPlugin) {
runningPlugin = plugin
}
public func pluginDidEnd(_ plugin: ChatPlugin) {
runningPlugin = nil
}
}
func registerPlugins(_ plugins: ChatPlugin.Type...) -> [String: ChatPlugin.Type] {
var all = [String: ChatPlugin.Type]()
for plugin in plugins {
all[plugin.command] = plugin
}
return all
}