-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathConversation.swift
77 lines (64 loc) · 2.47 KB
/
Conversation.swift
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
//
// Conversation.swift
// basicchatgpt
//
// Created by Yasuhito Nagatomo on 2023/04/01.
//
import Foundation
// Conversation between person and AI
struct Conversation: Identifiable, Codable {
enum State: Int, Codable {
case idle // doing nothing
case asking // communicating with OpenAI server
}
private(set) var id = UUID() // ID
var state = State.idle // state
var title: String // conversation title
var chats = [Chat]() // conversation messages (chats) by person and AI
private(set) var lastUpdated = Date() // last updated date
var settings: ChatSettings // chat settings for this conversation
#if DEBUG
static let sample: Conversation = { // sample data for debug
var conv = Conversation(title: "Greeting", settings: ChatSettings(chatModel: .gpt35turbo))
conv.append(chat: Chat(role: "user", content: "Say hello.", usage: nil))
conv.append(chat: Chat(role: "assistant", content: "Hello.", usage: nil))
return conv
}()
#endif
// The first User's message (chat) or ""
var firstUserContent: String {
if let chat = chats.first(where: { $0.role == "user" }) {
return chat.content // the first User's message
}
return "" // none
}
// Tokens - max of (prompt tokens + completion tokens)
var allTokens: Int {
(chats.map { ($0.usage?[0] ?? 0) + ($0.usage?[1] ?? 0) }).max() ?? 0
}
// Add a chat (message) of alternating user or assistant (AI)
mutating func addChat() {
let chat: Chat
if let lastChat = chats.last {
// Alternating user's or assistant's
if lastChat.isUser {
chat = Chat(role: OpenAIChatRole.assistant.rawValue,
content: "")
} else {
chat = Chat(role: OpenAIChatRole.user.rawValue,
content: "")
}
} else {
// The first chat (message) is user's.
chat = Chat(role: OpenAIChatRole.user.rawValue,
content: "")
}
chats.append(chat) // add the chat (message) to this conversation
lastUpdated = Date() // update the date
}
// Add the chat (message) to this conversation
mutating func append(chat: Chat) {
chats.append(chat) // add the chat (message) to this conversation
lastUpdated = Date() // update the date
}
}