Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
kardolus
GitHub Repository: kardolus/chatgpt-cli
Path: blob/main/history/manager.go
2649 views
1
package history
2
3
import (
4
"errors"
5
"fmt"
6
"github.com/kardolus/chatgpt-cli/api"
7
"os"
8
"strings"
9
)
10
11
const (
12
assistantRole = "assistant"
13
systemRole = "system"
14
userRole = "user"
15
functionRole = "function"
16
)
17
18
type Manager struct {
19
store Store
20
}
21
22
func NewHistory(store Store) *Manager {
23
return &Manager{store: store}
24
}
25
26
func (h *Manager) ParseUserHistory(thread string) ([]string, error) {
27
var result []string
28
29
historyEntries, err := h.store.ReadThread(thread)
30
if err != nil {
31
// Gracefully handle missing file
32
if errors.Is(err, os.ErrNotExist) {
33
return []string{}, nil
34
}
35
// Return any other error
36
return nil, err
37
}
38
39
for _, entry := range historyEntries {
40
if entry.Role == userRole {
41
if s, ok := entry.Content.(string); ok {
42
result = append(result, s)
43
}
44
}
45
}
46
47
return result, nil
48
}
49
50
func (h *Manager) Print(thread string) (string, error) {
51
var result string
52
53
historyEntries, err := h.store.ReadThread(thread)
54
if err != nil {
55
return "", err
56
}
57
58
var (
59
lastRole string
60
concatenatedMessage string
61
)
62
63
for _, entry := range historyEntries {
64
if entry.Role == userRole && lastRole == userRole {
65
concatenatedMessage += entry.Content.(string)
66
} else {
67
if lastRole == userRole && concatenatedMessage != "" {
68
result += formatHistory(History{
69
Message: api.Message{Role: userRole, Content: concatenatedMessage},
70
Timestamp: entry.Timestamp,
71
})
72
concatenatedMessage = ""
73
}
74
75
if entry.Role == userRole {
76
concatenatedMessage = entry.Content.(string)
77
} else {
78
result += formatHistory(History{
79
Message: entry.Message,
80
Timestamp: entry.Timestamp,
81
})
82
}
83
}
84
85
lastRole = entry.Role
86
}
87
88
// Handle the case where the last entry is a user entry and was concatenated
89
if lastRole == userRole && concatenatedMessage != "" {
90
result += formatHistory(History{
91
Message: api.Message{Role: userRole, Content: concatenatedMessage},
92
})
93
}
94
95
return result, nil
96
}
97
98
func formatHistory(entry History) string {
99
var (
100
emoji string
101
prefix string
102
timestamp string
103
)
104
105
switch entry.Role {
106
case systemRole:
107
emoji = "💻"
108
prefix = "\n"
109
case userRole:
110
emoji = "👤"
111
prefix = "---\n"
112
if !entry.Timestamp.IsZero() {
113
timestamp = fmt.Sprintf(" [%s]", entry.Timestamp.Format("2006-01-02 15:04:05"))
114
}
115
case functionRole:
116
emoji = "🔌"
117
prefix = "---\n"
118
case assistantRole:
119
emoji = "🤖"
120
prefix = "\n"
121
}
122
123
return fmt.Sprintf("%s**%s** %s%s:\n%s\n", prefix, strings.ToUpper(entry.Role), emoji, timestamp, entry.Content)
124
}
125
126