-
Notifications
You must be signed in to change notification settings - Fork 1
/
inference_test.go
310 lines (285 loc) · 7 KB
/
inference_test.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
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
package groq
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"log"
"net/http"
"os"
"path/filepath"
"testing"
"github.com/conneroisu/groq-go/pkg/builders"
"github.com/conneroisu/groq-go/pkg/test"
"github.com/conneroisu/groq-go/pkg/tools"
"github.com/stretchr/testify/assert"
)
func TestChat(t *testing.T) {
ctx := context.Background()
a := assert.New(t)
ts := test.NewTestServer()
returnObj := ChatCompletionResponse{
ID: "chatcmpl-123",
Object: "chat.completion.chunk",
Created: 1693721698,
Model: "llama3-groq-70b-8192-tool-use-preview",
Choices: []ChatCompletionChoice{
{
Index: 0,
Message: ChatCompletionMessage{
Role: RoleAssistant,
Content: "Hello!",
},
},
},
}
ts.RegisterHandler("/v1/chat/completions", func(w http.ResponseWriter, _ *http.Request) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
jsval, err := json.Marshal(returnObj)
a.NoError(err)
_, err = w.Write(jsval)
if err != nil {
t.Fatal(err)
}
})
testS := ts.GroqTestServer()
testS.Start()
client, err := NewClient(
test.GetTestToken(),
WithBaseURL(testS.URL+"/v1"),
)
a.NoError(err)
resp, err := client.ChatCompletion(ctx, ChatCompletionRequest{
Model: ModelLlama3Groq70B8192ToolUsePreview,
Messages: []ChatCompletionMessage{
{
Role: RoleUser,
Content: "Hello!",
},
},
MaxTokens: 2000,
Tools: []tools.Tool{},
})
a.NoError(err)
a.NotEmpty(resp.Choices[0].Message.Content)
}
func TestAudioWithFailingFormBuilder(t *testing.T) {
a := assert.New(t)
dir, cleanup := test.CreateTestDirectory(t)
defer cleanup()
path := filepath.Join(dir, "fake.mp3")
test.CreateTestFile(t, path)
req := AudioRequest{
FilePath: path,
Prompt: "test",
Temperature: 0.5,
Language: "en",
Format: FormatSRT,
}
mockFailedErr := fmt.Errorf("mock form builder fail")
mockBuilder := &mockFormBuilder{}
mockBuilder.mockCreateFormFile = func(string, *os.File) error {
return mockFailedErr
}
err := audioMultipartForm(req, mockBuilder)
a.ErrorIs(
err,
mockFailedErr,
"audioMultipartForm should return error if form builder fails",
)
mockBuilder.mockCreateFormFile = func(string, *os.File) error {
return nil
}
var failForField string
mockBuilder.mockWriteField = func(fieldname, _ string) error {
if fieldname == failForField {
return mockFailedErr
}
return nil
}
failOn := []string{
"model",
"prompt",
"temperature",
"language",
"response_format",
}
for _, failingField := range failOn {
failForField = failingField
mockFailedErr = fmt.Errorf(
"mock form builder fail on field %s",
failingField,
)
err = audioMultipartForm(req, mockBuilder)
a.Error(
err,
mockFailedErr,
"audioMultipartForm should return error if form builder fails",
)
}
}
func TestModeration(t *testing.T) {
a := assert.New(t)
ctx := context.Background()
client, server, teardown := setupGroqTestServer()
defer teardown()
server.RegisterHandler("/v1/chat/completions", handleModerationEndpoint)
mod, err := client.Moderate(ctx,
[]ChatCompletionMessage{
{
Role: RoleUser,
Content: "I want to kill them.",
},
},
ModelLlamaGuard38B,
)
a.NoError(err)
a.NotEmpty(mod)
}
func setupGroqTestServer() (
client *Client,
server *test.ServerTest,
teardown func(),
) {
server = test.NewTestServer()
ts := server.GroqTestServer()
ts.Start()
teardown = ts.Close
client, err := NewClient(
test.GetTestToken(),
WithBaseURL(ts.URL+"/v1"),
)
if err != nil {
log.Fatal(err)
}
return
}
// handleModerationEndpoint handles the moderation endpoint.
func handleModerationEndpoint(w http.ResponseWriter, _ *http.Request) {
response := ChatCompletionResponse{
ID: "chatcmpl-123",
Object: "chat.completion",
Created: 1693721698,
Model: ChatModel(ModelLlamaGuard38B),
Choices: []ChatCompletionChoice{
{
Message: ChatCompletionMessage{
Role: RoleAssistant,
Content: "unsafe\nS1,S2",
},
FinishReason: "stop",
},
},
}
buf := new(bytes.Buffer)
err := json.NewEncoder(buf).Encode(response)
if err != nil {
http.Error(
w,
"could not encode response",
http.StatusInternalServerError,
)
return
}
_, err = w.Write(buf.Bytes())
if err != nil {
http.Error(
w,
"could not write response",
http.StatusInternalServerError,
)
return
}
}
func TestCreateFileField(t *testing.T) {
a := assert.New(t)
t.Run("createFileField failing file", func(t *testing.T) {
t.Parallel()
dir, cleanup := test.CreateTestDirectory(t)
defer cleanup()
path := filepath.Join(dir, "fake.mp3")
test.CreateTestFile(t, path)
req := AudioRequest{
FilePath: path,
}
mockFailedErr := fmt.Errorf("mock form builder fail")
mockBuilder := &mockFormBuilder{
mockCreateFormFile: func(string, *os.File) error {
return mockFailedErr
},
}
err := audioMultipartForm(req, mockBuilder)
a.ErrorIs(
err,
mockFailedErr,
"createFileField using a file should return error if form builder fails",
)
})
t.Run("createFileField failing reader", func(t *testing.T) {
t.Parallel()
req := AudioRequest{
FilePath: "test.wav",
Reader: bytes.NewBuffer([]byte(`wav test contents`)),
}
mockFailedErr := fmt.Errorf("mock form builder fail")
mockBuilder := &mockFormBuilder{
mockCreateFormFileReader: func(string, io.Reader, string) error {
return mockFailedErr
},
}
err := audioMultipartForm(req, mockBuilder)
a.ErrorIs(
err,
mockFailedErr,
"createFileField using a reader should return error if form builder fails",
)
})
t.Run("createFileField failing open", func(t *testing.T) {
t.Parallel()
req := AudioRequest{
FilePath: "non_existing_file.wav",
}
mockBuilder := builders.NewFormBuilder(&test.FailingErrorBuffer{})
err := audioMultipartForm(req, mockBuilder)
a.Error(
err,
"createFileField using file should return error when open file fails",
)
})
}
// mockFormBuilder is a mock form builder.
type mockFormBuilder struct {
mockCreateFormFile func(string, *os.File) error
mockCreateFormFileReader func(string, io.Reader, string) error
mockWriteField func(string, string) error
mockClose func() error
}
// CreateFormFile is a mock form builder create form file method.
func (fb *mockFormBuilder) CreateFormFile(
fieldname string,
file *os.File,
) error {
return fb.mockCreateFormFile(fieldname, file)
}
// CreateFormFileReader is a mock form builder create form file reader method
func (fb *mockFormBuilder) CreateFormFileReader(
fieldname string,
r io.Reader,
filename string,
) error {
return fb.mockCreateFormFileReader(fieldname, r, filename)
}
// WriteField is a mock form builder write field method.
func (fb *mockFormBuilder) WriteField(fieldname, value string) error {
return fb.mockWriteField(fieldname, value)
}
// Close is a mock form builder close method.
func (fb *mockFormBuilder) Close() error {
return fb.mockClose()
}
// FormDataContentType is a mock form builder.
func (fb *mockFormBuilder) FormDataContentType() string {
return ""
}