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
50 lines (46 loc) · 1.47 KB
/
OpenAIChat.swift
File metadata and controls
50 lines (46 loc) · 1.47 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
import Foundation
import OpenAIService
public struct OpenAIChat: ChatModel {
public var temperature: Double
public var stream: Bool
public init(
temperature: Double = 0.7,
stream: Bool = false
) {
self.temperature = temperature
self.stream = stream
}
public func generate(
prompt: [ChatMessage],
stops: [String],
callbackManagers: [ChainCallbackManager]
) async throws -> String {
let service = ChatGPTService(temperature: temperature, stop: stops)
await service.mutateHistory { history in
for message in prompt {
let role: OpenAIService.ChatMessage.Role = {
switch message.role {
case .system:
return .system
case .user:
return .user
case .assistant:
return .assistant
}
}()
history.append(.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.onLLMNewToken(token: trunk) }
}
return message
} else {
return try await service.sendAndWait(content: "") ?? ""
}
}
}