|
| 1 | +import ChatPlugin |
| 2 | +import Environment |
| 3 | +import Foundation |
| 4 | +import OpenAIService |
| 5 | + |
| 6 | +/// Use Python to solve math problems. |
| 7 | +public actor MathChatPlugin: ChatPlugin { |
| 8 | + public static var command: String { "math" } |
| 9 | + public nonisolated var name: String { "Math" } |
| 10 | + |
| 11 | + let chatGPTService: any ChatGPTServiceType |
| 12 | + var isCancelled = false |
| 13 | + weak var delegate: ChatPluginDelegate? |
| 14 | + |
| 15 | + public init(inside chatGPTService: any ChatGPTServiceType, delegate: ChatPluginDelegate) { |
| 16 | + self.chatGPTService = chatGPTService |
| 17 | + self.delegate = delegate |
| 18 | + } |
| 19 | + |
| 20 | + public func send(content: String, originalMessage: String) async { |
| 21 | + delegate?.pluginDidStart(self) |
| 22 | + delegate?.pluginDidStartResponding(self) |
| 23 | + |
| 24 | + let id = "\(Self.command)-\(UUID().uuidString)" |
| 25 | + var reply = ChatMessage(id: id, role: .assistant, content: "Calculating...") |
| 26 | + |
| 27 | + await chatGPTService.mutateHistory { history in |
| 28 | + history.append(.init(role: .user, content: originalMessage, summary: content)) |
| 29 | + history.append(reply) |
| 30 | + } |
| 31 | + |
| 32 | + do { |
| 33 | + let result = try await solveMathProblem(content) |
| 34 | + await chatGPTService.mutateHistory { history in |
| 35 | + if history.last?.id == id { |
| 36 | + history.removeLast() |
| 37 | + } |
| 38 | + reply.content = result |
| 39 | + history.append(reply) |
| 40 | + } |
| 41 | + } catch { |
| 42 | + await chatGPTService.mutateHistory { history in |
| 43 | + if history.last?.id == id { |
| 44 | + history.removeLast() |
| 45 | + } |
| 46 | + reply.content = error.localizedDescription |
| 47 | + history.append(reply) |
| 48 | + } |
| 49 | + } |
| 50 | + |
| 51 | + delegate?.pluginDidEndResponding(self) |
| 52 | + delegate?.pluginDidEnd(self) |
| 53 | + } |
| 54 | + |
| 55 | + public func cancel() async { |
| 56 | + isCancelled = true |
| 57 | + } |
| 58 | + |
| 59 | + public func stopResponding() async { |
| 60 | + isCancelled = true |
| 61 | + } |
| 62 | +} |
| 63 | + |
0 commit comments