forked from intitni/CopilotForXcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathOpenAIChat.swift
More file actions
55 lines (50 loc) · 1.63 KB
/
Copy pathOpenAIChat.swift
File metadata and controls
55 lines (50 loc) · 1.63 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
import Foundation
import OpenAIService
public struct OpenAIChat: ChatModel {
public var configuration: ChatGPTConfiguration
public var stream: Bool
public init(
configuration: ChatGPTConfiguration,
stream: Bool
) {
self.configuration = configuration
self.stream = stream
}
public func generate(
prompt: [ChatMessage],
stops: [String],
callbackManagers: [CallbackManager]
) async throws -> String {
let memory = AutoManagedChatGPTMemory(
systemPrompt: "",
configuration: configuration,
functionProvider: NoChatGPTFunctionProvider()
)
let service = ChatGPTService(memory: memory, configuration: configuration)
for message in prompt {
let role: OpenAIService.ChatMessage.Role = {
switch message.role {
case .system:
return .system
case .user:
return .user
case .assistant:
return .assistant
}
}()
await memory.appendMessage(.init(role: role, content: message.content))
}
if stream {
let stream = try await service.send(content: "")
var message = ""
for try await trunk in stream {
message.append(trunk)
callbackManagers
.forEach { $0.send(CallbackEvents.LLMDidProduceNewToken(info: trunk)) }
}
return message
} else {
return try await service.sendAndWait(content: "") ?? ""
}
}
}