-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathopenai.go
249 lines (209 loc) · 5.14 KB
/
openai.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
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
package main
import (
"context"
"fmt"
"io"
"os"
"github.com/charmbracelet/huh"
"github.com/philippgille/chromem-go"
goopenai "github.com/sashabaranov/go-openai"
bolt "go.etcd.io/bbolt"
)
type openaiProvider struct {
APIKey string `json:"apiKey"`
}
type openai struct {
apiKey string
model string
temperature float64
client *goopenai.Client
}
func (o openai) chat(ctx context.Context, chats []chat) llmResponse {
systemChat, cs := extractSystemChat(chats)
msgs := make([]goopenai.ChatCompletionMessage, 0, len(cs)+1)
if systemChat != "" {
msgs = append(msgs, goopenai.ChatCompletionMessage{
Role: goopenai.ChatMessageRoleSystem,
Content: systemChat,
})
}
for _, chat := range cs {
msgs = append(msgs, goopenai.ChatCompletionMessage{
Role: chat.Role,
Content: chat.Content,
})
}
resp, err := o.client.CreateChatCompletion(
ctx,
goopenai.ChatCompletionRequest{
Model: o.model,
Messages: msgs,
Temperature: float32(o.temperature),
},
)
if err != nil {
return llmResponse{
err: fmt.Errorf("error creating chat completion: %w", err),
}
}
if len(resp.Choices) == 0 {
return llmResponse{
err: fmt.Errorf("no choices in response"),
}
}
return llmResponse{
content: resp.Choices[0].Message.Content,
}
}
func (o openai) chatStream(ctx context.Context, chats []chat) <-chan llmResponse {
responseChan := make(chan llmResponse)
go func() {
defer close(responseChan)
systemChat, cs := extractSystemChat(chats)
msgs := make([]goopenai.ChatCompletionMessage, 0, len(cs)+1)
if systemChat != "" {
msgs = append(msgs, goopenai.ChatCompletionMessage{
Role: goopenai.ChatMessageRoleSystem,
Content: systemChat,
})
}
for _, chat := range cs {
msgs = append(msgs, goopenai.ChatCompletionMessage{
Role: chat.Role,
Content: chat.Content,
})
}
stream, err := o.client.CreateChatCompletionStream(
ctx,
goopenai.ChatCompletionRequest{
Model: o.model,
Messages: msgs,
Temperature: float32(o.temperature),
Stream: true,
},
)
if err != nil {
responseChan <- llmResponse{
err: fmt.Errorf("error creating chat completion stream: %w", err),
}
return
}
defer stream.Close()
for {
response, err := stream.Recv()
if err != nil {
if err == io.EOF {
return
}
if err == context.Canceled {
return
}
responseChan <- llmResponse{
err: fmt.Errorf("error receiving from stream: %w", err),
}
return
}
if len(response.Choices) > 0 && response.Choices[0].Delta.Content != "" {
responseChan <- llmResponse{
content: response.Choices[0].Delta.Content,
}
}
}
}()
return responseChan
}
func (o openai) embeddingFunc() chromem.EmbeddingFunc {
return chromem.NewEmbeddingFuncOpenAI(o.apiKey, chromem.EmbeddingModelOpenAI(o.model))
}
func (o openaiProvider) Title() string {
if o.isConfigured() {
return fmt.Sprintf("%s (configured)", providerOpenAI)
}
return fmt.Sprintf("%s (not configured)", providerOpenAI)
}
func (o openaiProvider) Description() string {
return "Configure OpenAI connection"
}
func (o openaiProvider) FilterValue() string {
return providerOpenAI
}
func (o openaiProvider) name() string {
return providerOpenAI
}
func (o openaiProvider) availableModels() []string {
client := goopenai.NewClient(o.APIKey)
mList, err := client.ListModels(context.Background())
if err != nil {
return []string{}
}
res := make([]string, len(mList.Models))
for i, m := range mList.Models {
res[i] = m.ID
}
return res
}
func (o openaiProvider) isConfigured() bool {
return o.APIKey != ""
}
func (o openaiProvider) form(width, height int, keymap *huh.KeyMap) *huh.Form {
apiKey := o.APIKey
if apiKey == "" {
apiKey = os.Getenv("OPENAI_API_KEY")
}
return huh.NewForm(
huh.NewGroup(
huh.NewInput().
Key("openaiAPIKey").
Title("API Key").
Description("Enter the API key for OpenAI.").
Placeholder("API Key").
Value(&apiKey),
huh.NewConfirm().
Key("openaiConfirm").
Title("Confirm").
Description("Save this OpenAI settings?").
Affirmative("Yes").
Negative("Back"),
),
).
WithWidth(width).
WithHeight(height).
WithTheme(huh.ThemeCatppuccin()).
WithKeyMap(keymap).
WithShowErrors(true).
WithShowHelp(true)
}
func (o openaiProvider) saveForm(db *bolt.DB, form *huh.Form) (llmProvider, bool, error) {
if !form.GetBool("openaiConfirm") {
return o, false, nil
}
apiKey := form.GetString("openaiAPIKey")
if apiKey == "" {
return o, false, nil
}
o.APIKey = apiKey
if err := saveOpenAISettings(db, o); err != nil {
return o, false, fmt.Errorf("error saving openai settings: %w", err)
}
return o, true, nil
}
func (o openaiProvider) new(setting llmSetting) llm {
client := goopenai.NewClient(o.APIKey)
return openai{
apiKey: o.APIKey,
model: setting.Model,
temperature: setting.Temperature,
client: client,
}
}
func (o openaiProvider) supportEmbedding() bool {
return true
}
func (o openaiProvider) newEmbedder(setting llmSetting) embedder {
client := goopenai.NewClient(o.APIKey)
return &openai{
apiKey: o.APIKey,
model: setting.Model,
client: client,
}
}