forked from intitni/CopilotForXcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSearchChatPlugin.swift
More file actions
101 lines (82 loc) · 3.11 KB
/
SearchChatPlugin.swift
File metadata and controls
101 lines (82 loc) · 3.11 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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
import ChatPlugin
import Environment
import Foundation
import OpenAIService
public actor SearchChatPlugin: ChatPlugin {
public static var command: String { "search" }
public nonisolated var name: String { "Search" }
let chatGPTService: any ChatGPTServiceType
var isCancelled = false
weak var delegate: ChatPluginDelegate?
public init(inside chatGPTService: any ChatGPTServiceType, delegate: ChatPluginDelegate) {
self.chatGPTService = chatGPTService
self.delegate = delegate
}
public func send(content: String, originalMessage: String) async {
delegate?.pluginDidStart(self)
delegate?.pluginDidStartResponding(self)
let id = "\(Self.command)-\(UUID().uuidString)"
var reply = ChatMessage(id: id, role: .assistant, content: "")
await chatGPTService.mutateHistory { history in
history.append(.init(role: .user, content: originalMessage, summary: content))
}
do {
let (eventStream, cancelAgent) = try await search(content)
var actions = [String]()
var finishedActions = Set<String>()
var message = ""
for try await event in eventStream {
guard !isCancelled else {
await cancelAgent()
break
}
switch event {
case let .startAction(content):
actions.append(content)
case let .endAction(content):
finishedActions.insert(content)
case let .answerToken(token):
message.append(token)
case let .finishAnswer(answer, links):
message = """
\(answer)
\(links.map { "- [\($0.title)](\($0.link))" }.joined(separator: "\n"))
"""
}
await chatGPTService.mutateHistory { history in
if history.last?.id == id {
history.removeLast()
}
let actionString = actions.map {
"> \(finishedActions.contains($0) ? "✅" : "🔍") \($0)"
}.joined(separator: "\n>\n")
if message.isEmpty {
reply.content = actionString
} else {
reply.content = """
\(actionString)
\(message)
"""
}
history.append(reply)
}
}
} catch {
await chatGPTService.mutateHistory { history in
if history.last?.id == id {
history.removeLast()
}
reply.content = error.localizedDescription
history.append(reply)
}
}
delegate?.pluginDidEndResponding(self)
delegate?.pluginDidEnd(self)
}
public func cancel() async {
isCancelled = true
}
public func stopResponding() async {
isCancelled = true
}
}