forked from intitni/CopilotForXcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMathChatPlugin.swift
More file actions
67 lines (56 loc) · 2.03 KB
/
MathChatPlugin.swift
File metadata and controls
67 lines (56 loc) · 2.03 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
import ChatPlugin
import Environment
import Foundation
import OpenAIService
/// Use Python to solve math problems.
public actor MathChatPlugin: ChatPlugin {
public static var command: String { "math" }
public nonisolated var name: String { "Math" }
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.memory.mutateHistory { history in
history.append(.init(role: .user, content: originalMessage))
}
do {
let result = try await solveMathProblem(content)
let formattedResult = "Answer: \(result)"
if !isCancelled {
await chatGPTService.memory.mutateHistory { history in
if history.last?.id == id {
history.removeLast()
}
reply.content = formattedResult
history.append(reply)
}
}
} catch {
if !isCancelled {
await chatGPTService.memory.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
}
}