-
Notifications
You must be signed in to change notification settings - Fork 119
/
cache.go
114 lines (94 loc) · 2.4 KB
/
cache.go
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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
package main
import (
"errors"
"fmt"
"io"
"os"
"path/filepath"
"sync"
openai "github.com/sashabaranov/go-openai"
)
const cacheExt = ".gob"
var errInvalidID = errors.New("invalid id")
type convoCache struct {
dir string
}
func newCache(dir string) *convoCache {
return &convoCache{dir}
}
func (c *convoCache) read(id string, messages *[]openai.ChatCompletionMessage) error {
if id == "" {
return fmt.Errorf("read: %w", errInvalidID)
}
file, err := os.Open(filepath.Join(c.dir, id+cacheExt))
if err != nil {
return fmt.Errorf("read: %w", err)
}
defer file.Close() //nolint:errcheck
if err := decode(file, messages); err != nil {
return fmt.Errorf("read: %w", err)
}
return nil
}
func (c *convoCache) write(id string, messages *[]openai.ChatCompletionMessage) error {
if id == "" {
return fmt.Errorf("write: %w", errInvalidID)
}
file, err := os.Create(filepath.Join(c.dir, id+cacheExt))
if err != nil {
return fmt.Errorf("write: %w", err)
}
defer file.Close() //nolint:errcheck
if err := encode(file, messages); err != nil {
return fmt.Errorf("write: %w", err)
}
return nil
}
func (c *convoCache) delete(id string) error {
if id == "" {
return fmt.Errorf("delete: %w", errInvalidID)
}
if err := os.Remove(filepath.Join(c.dir, id+cacheExt)); err != nil {
return fmt.Errorf("delete: %w", err)
}
return nil
}
var _ chatCompletionReceiver = &cachedCompletionStream{}
type cachedCompletionStream struct {
messages []openai.ChatCompletionMessage
read int
m sync.Mutex
}
func (c *cachedCompletionStream) Close() error { return nil }
func (c *cachedCompletionStream) Recv() (openai.ChatCompletionStreamResponse, error) {
c.m.Lock()
defer c.m.Unlock()
if c.read == len(c.messages) {
return openai.ChatCompletionStreamResponse{}, io.EOF
}
msg := c.messages[c.read]
prefix := ""
switch msg.Role {
case openai.ChatMessageRoleSystem:
prefix += "\n**System**: "
case openai.ChatMessageRoleUser:
prefix += "\n**Prompt**: "
case openai.ChatMessageRoleAssistant:
prefix += "\n**Assistant**: "
case openai.ChatMessageRoleFunction:
prefix += "\n**Function**: "
case openai.ChatMessageRoleTool:
prefix += "\n**Tool**: "
}
c.read++
return openai.ChatCompletionStreamResponse{
Choices: []openai.ChatCompletionStreamChoice{
{
Delta: openai.ChatCompletionStreamChoiceDelta{
Content: prefix + msg.Content + "\n",
Role: msg.Role,
},
},
},
}, nil
}