forked from sashabaranov/go-openai
-
Notifications
You must be signed in to change notification settings - Fork 1
/
api_test.go
264 lines (227 loc) · 6.85 KB
/
api_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
package openai_test
import (
"context"
"encoding/json"
"errors"
"io"
"net/http"
"net/http/httptest"
"os"
"testing"
. "github.com/sashabaranov/go-openai"
"github.com/sashabaranov/go-openai/internal/test/checks"
)
func TestAPI(t *testing.T) {
apiToken := os.Getenv("OPENAI_TOKEN")
if apiToken == "" {
t.Skip("Skipping testing against production OpenAI API. Set OPENAI_TOKEN environment variable to enable it.")
}
var err error
c := NewClient(apiToken)
ctx := context.Background()
_, err = c.ListEngines(ctx)
checks.NoError(t, err, "ListEngines error")
_, err = c.GetEngine(ctx, "davinci")
checks.NoError(t, err, "GetEngine error")
fileRes, err := c.ListFiles(ctx)
checks.NoError(t, err, "ListFiles error")
if len(fileRes.Files) > 0 {
_, err = c.GetFile(ctx, fileRes.Files[0].ID)
checks.NoError(t, err, "GetFile error")
} // else skip
embeddingReq := EmbeddingRequest{
Input: []string{
"The food was delicious and the waiter",
"Other examples of embedding request",
},
Model: AdaSearchQuery,
}
_, err = c.CreateEmbeddings(ctx, embeddingReq)
checks.NoError(t, err, "Embedding error")
_, err = c.CreateChatCompletion(
ctx,
ChatCompletionRequest{
Model: GPT3Dot5Turbo,
Messages: []ChatCompletionMessage{
{
Role: ChatMessageRoleUser,
Content: "Hello!",
},
},
},
)
checks.NoError(t, err, "CreateChatCompletion (without name) returned error")
_, err = c.CreateChatCompletion(
ctx,
ChatCompletionRequest{
Model: GPT3Dot5Turbo,
Messages: []ChatCompletionMessage{
{
Role: ChatMessageRoleUser,
Name: "John_Doe",
Content: "Hello!",
},
},
},
)
checks.NoError(t, err, "CreateChatCompletion (with name) returned error")
stream, err := c.CreateCompletionStream(ctx, CompletionRequest{
Prompt: "Ex falso quodlibet",
Model: GPT3Ada,
MaxTokens: 5,
Stream: true,
})
checks.NoError(t, err, "CreateCompletionStream returned error")
defer stream.Close()
counter := 0
for {
_, err = stream.Recv()
if err != nil {
if errors.Is(err, io.EOF) {
break
}
t.Errorf("Stream error: %v", err)
} else {
counter++
}
}
if counter == 0 {
t.Error("Stream did not return any responses")
}
}
func TestAPIError(t *testing.T) {
apiToken := os.Getenv("OPENAI_TOKEN")
if apiToken == "" {
t.Skip("Skipping testing against production OpenAI API. Set OPENAI_TOKEN environment variable to enable it.")
}
var err error
c := NewClient(apiToken + "_invalid")
ctx := context.Background()
_, err = c.ListEngines(ctx)
checks.HasError(t, err, "ListEngines should fail with an invalid key")
var apiErr *APIError
if !errors.As(err, &apiErr) {
t.Fatalf("Error is not an APIError: %+v", err)
}
if apiErr.HTTPStatusCode != 401 {
t.Fatalf("Unexpected API error status code: %d", apiErr.HTTPStatusCode)
}
switch v := apiErr.Code.(type) {
case string:
if v != "invalid_api_key" {
t.Fatalf("Unexpected API error code: %s", v)
}
default:
t.Fatalf("Unexpected API error code type: %T", v)
}
if apiErr.Error() == "" {
t.Fatal("Empty error message occurred")
}
}
func TestAPIErrorUnmarshalJSONInteger(t *testing.T) {
var apiErr APIError
response := `{"code":418,"message":"I'm a teapot","param":"prompt","type":"teapot_error"}`
err := json.Unmarshal([]byte(response), &apiErr)
checks.NoError(t, err, "Unexpected Unmarshal API response error")
switch v := apiErr.Code.(type) {
case int:
if v != 418 {
t.Fatalf("Unexpected API code integer: %d; expected 418", v)
}
default:
t.Fatalf("Unexpected API error code type: %T", v)
}
}
func TestAPIErrorUnmarshalJSONString(t *testing.T) {
var apiErr APIError
response := `{"code":"teapot","message":"I'm a teapot","param":"prompt","type":"teapot_error"}`
err := json.Unmarshal([]byte(response), &apiErr)
checks.NoError(t, err, "Unexpected Unmarshal API response error")
switch v := apiErr.Code.(type) {
case string:
if v != "teapot" {
t.Fatalf("Unexpected API code string: %s; expected `teapot`", v)
}
default:
t.Fatalf("Unexpected API error code type: %T", v)
}
}
func TestAPIErrorUnmarshalJSONNoCode(t *testing.T) {
// test integer code
response := `{"message":"I'm a teapot","param":"prompt","type":"teapot_error"}`
var apiErr APIError
err := json.Unmarshal([]byte(response), &apiErr)
checks.NoError(t, err, "Unexpected Unmarshal API response error")
switch v := apiErr.Code.(type) {
case nil:
default:
t.Fatalf("Unexpected API error code type: %T", v)
}
}
func TestAPIErrorUnmarshalInvalidData(t *testing.T) {
apiErr := APIError{}
data := []byte(`--- {"code":418,"message":"I'm a teapot","param":"prompt","type":"teapot_error"}`)
err := apiErr.UnmarshalJSON(data)
checks.HasError(t, err, "Expected error when unmarshaling invalid data")
if apiErr.Code != nil {
t.Fatalf("Expected nil code, got %q", apiErr.Code)
}
if apiErr.Message != "" {
t.Fatalf("Expected empty message, got %q", apiErr.Message)
}
if apiErr.Param != nil {
t.Fatalf("Expected nil param, got %q", *apiErr.Param)
}
if apiErr.Type != "" {
t.Fatalf("Expected empty type, got %q", apiErr.Type)
}
}
func TestAPIErrorUnmarshalJSONInvalidParam(t *testing.T) {
var apiErr APIError
response := `{"code":418,"message":"I'm a teapot","param":true,"type":"teapot_error"}`
err := json.Unmarshal([]byte(response), &apiErr)
checks.HasError(t, err, "Param should be a string")
}
func TestAPIErrorUnmarshalJSONInvalidType(t *testing.T) {
var apiErr APIError
response := `{"code":418,"message":"I'm a teapot","param":"prompt","type":true}`
err := json.Unmarshal([]byte(response), &apiErr)
checks.HasError(t, err, "Type should be a string")
}
func TestAPIErrorUnmarshalJSONInvalidMessage(t *testing.T) {
var apiErr APIError
response := `{"code":418,"message":false,"param":"prompt","type":"teapot_error"}`
err := json.Unmarshal([]byte(response), &apiErr)
checks.HasError(t, err, "Message should be a string")
}
func TestRequestError(t *testing.T) {
var err error
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusTeapot)
}))
defer ts.Close()
config := DefaultConfig("dummy")
config.BaseURL = ts.URL
c := NewClientWithConfig(config)
ctx := context.Background()
_, err = c.ListEngines(ctx)
checks.HasError(t, err, "ListEngines did not fail")
var reqErr *RequestError
if !errors.As(err, &reqErr) {
t.Fatalf("Error is not a RequestError: %+v", err)
}
if reqErr.HTTPStatusCode != 418 {
t.Fatalf("Unexpected request error status code: %d", reqErr.HTTPStatusCode)
}
if reqErr.Unwrap() == nil {
t.Fatalf("Empty request error occurred")
}
}
// numTokens Returns the number of GPT-3 encoded tokens in the given text.
// This function approximates based on the rule of thumb stated by OpenAI:
// https://beta.openai.com/tokenizer
//
// TODO: implement an actual tokenizer for GPT-3 and Codex (once available)
func numTokens(s string) int {
return int(float32(len(s)) / 4)
}