-
Notifications
You must be signed in to change notification settings - Fork 4
/
model.go
228 lines (185 loc) · 5.06 KB
/
model.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
package typechat
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"os"
"time"
)
type response struct {
Id string `json:"id"`
Object string `json:"object"`
Created int `json:"created"`
Choices []*choice `json:"choices"`
Usage *usage `json:"usage"`
}
type message struct {
Role string `json:"role"`
Content string `json:"content"`
}
type choice struct {
Index int `json:"index"`
Message *message `json:"message"`
FinishReason string `json:"finish_reason"`
}
type usage struct {
PromptTokens int `json:"prompt_tokens"`
CompletionTokens int `json:"completion_tokens"`
TotalTokens int `json:"total_tokens"`
}
type LanguageModel interface {
complete(prompt string) (string, error)
}
func NewLanguageModel() (LanguageModel, error) {
if os.Getenv("OPENAI_API_KEY") != "" {
apiKey := os.Getenv("OPENAI_API_KEY")
model := os.Getenv("OPENAI_MODEL")
if model == "" {
return nil, missingEnvironmentVariable("OPENAI_MODEL")
}
endPoint := os.Getenv("OPENAI_ENDPOINT")
if endPoint == "" {
endPoint = "https://api.openai.com/v1/chat/completions"
}
return NewOpenAILanguageModel(apiKey, model, endPoint, os.Getenv("OPENAI_ORGANIZATION")), nil
}
if os.Getenv("AZURE_OPENAI_API_KEY") != "" {
apiKey := os.Getenv("AZURE_OPENAI_API_KEY")
endPoint := os.Getenv("AZURE_OPENAI_ENDPOINT")
if endPoint == "" {
return nil, missingEnvironmentVariable("AZURE_OPENAI_ENDPOINT")
}
return NewAzureOpenAILanguageModel(apiKey, endPoint), nil
}
return nil, missingEnvironmentVariable("OPENAI_API_KEY or AZURE_OPENAI_API_KEY")
}
type Option func(*baseLanguageModel)
func WithHeaders(headers map[string]string) func(*baseLanguageModel) {
return func(m *baseLanguageModel) {
m.headers = headers
}
}
func WithDefaultParams(defaultParams map[string]any) func(*baseLanguageModel) {
return func(m *baseLanguageModel) {
m.defaultParams = defaultParams
}
}
type baseLanguageModel struct {
url string
retryMaxAttempts int
retryPauseDuration time.Duration
headers map[string]string
defaultParams map[string]any
}
func newBaseLanguageModel(url string, options ...Option) LanguageModel {
m := &baseLanguageModel{
url: url,
retryMaxAttempts: 3,
retryPauseDuration: 1000 * time.Millisecond,
headers: make(map[string]string),
}
for _, option := range options {
option(m)
}
return m
}
func (m *baseLanguageModel) complete(prompt string) (string, error) {
retryCount := 0
for {
paramMap := map[string]any{
"messages": []map[string]any{
{
"role": "user",
"content": prompt,
},
},
"temperature": 0,
"n": 1,
}
if m.defaultParams != nil {
for k, v := range m.defaultParams {
paramMap[k] = v
}
}
params, err := json.Marshal(paramMap)
if err != nil {
return "", err
}
req, err := http.NewRequest(http.MethodPost, m.url, bytes.NewBuffer(params))
if err != nil {
return "", err
}
req.Header.Add("Content-Type", "application/json;charset=utf-8")
if m.headers != nil {
for k, v := range m.headers {
req.Header.Add(k, v)
}
}
client := http.Client{}
resp, err := client.Do(req)
if err != nil {
return "", err
}
bodyBytes, err := m.readBody(resp)
if err != nil {
return "", err
}
if resp.StatusCode == http.StatusOK {
var r response
err = json.Unmarshal(bodyBytes, &r)
if err != nil {
return "", err
}
if len(r.Choices) == 0 || r.Choices[0].Message == nil {
return "", nil
}
return r.Choices[0].Message.Content, nil
}
if !m.isTransientHttpError(resp.StatusCode) || retryCount >= m.retryMaxAttempts {
return "", errors.New(fmt.Sprintf("REST API error %d: %s", resp.StatusCode, resp.Status))
}
time.Sleep(m.retryPauseDuration)
retryCount++
}
}
func (m *baseLanguageModel) readBody(resp *http.Response) ([]byte, error) {
defer resp.Body.Close()
respBytes, err := io.ReadAll(resp.Body)
if err != nil {
return nil, err
}
return respBytes, nil
}
// 429: TooManyRequests
// 500: InternalServerError
// 502: BadGateway
// 503: ServiceUnavailable
// 504: GatewayTimeout
func (m *baseLanguageModel) isTransientHttpError(code int) bool {
return code == 429 || code == 500 || code == 502 || code == 503 || code == 504
}
// NewAzureOpenAILanguageModel Creates a language model encapsulation of an Azure OpenAI REST API endpoint.
func NewAzureOpenAILanguageModel(apiKey, endPoint string) LanguageModel {
return newBaseLanguageModel(endPoint, WithHeaders(map[string]string{
"api-key": apiKey,
}))
}
// NewOpenAILanguageModel Creates a language model encapsulation of an OpenAI REST API endpoint.
func NewOpenAILanguageModel(apiKey, model, endPoint, org string) LanguageModel {
return newBaseLanguageModel(
endPoint,
WithHeaders(map[string]string{
"Authorization": fmt.Sprintf("Bearer %s", apiKey),
"OpenAI-Organization": org,
}),
WithDefaultParams(map[string]any{
"model": model,
}),
)
}
func missingEnvironmentVariable(name string) error {
return fmt.Errorf("Missing environment variable: %s", name)
}