-
Notifications
You must be signed in to change notification settings - Fork 65
/
gpt3.go
491 lines (427 loc) · 14.3 KB
/
gpt3.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
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
package gpt3
import (
"bufio"
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"net/http"
"time"
)
// Engine Types
const (
TextAda001Engine = "text-ada-001"
TextBabbage001Engine = "text-babbage-001"
TextCurie001Engine = "text-curie-001"
TextDavinci001Engine = "text-davinci-001"
TextDavinci002Engine = "text-davinci-002"
TextDavinci003Engine = "text-davinci-003"
AdaEngine = "ada"
BabbageEngine = "babbage"
CurieEngine = "curie"
DavinciEngine = "davinci"
DefaultEngine = DavinciEngine
)
type EmbeddingEngine string
const (
GPT3Dot5Turbo = "gpt-3.5-turbo"
GPT3Dot5Turbo0301 = "gpt-3.5-turbo-0301"
GPT3Dot5Turbo0613 = "gpt-3.5-turbo-0613"
TextSimilarityAda001 = "text-similarity-ada-001"
TextSimilarityBabbage001 = "text-similarity-babbage-001"
TextSimilarityCurie001 = "text-similarity-curie-001"
TextSimilarityDavinci001 = "text-similarity-davinci-001"
TextSearchAdaDoc001 = "text-search-ada-doc-001"
TextSearchAdaQuery001 = "text-search-ada-query-001"
TextSearchBabbageDoc001 = "text-search-babbage-doc-001"
TextSearchBabbageQuery001 = "text-search-babbage-query-001"
TextSearchCurieDoc001 = "text-search-curie-doc-001"
TextSearchCurieQuery001 = "text-search-curie-query-001"
TextSearchDavinciDoc001 = "text-search-davinci-doc-001"
TextSearchDavinciQuery001 = "text-search-davinci-query-001"
CodeSearchAdaCode001 = "code-search-ada-code-001"
CodeSearchAdaText001 = "code-search-ada-text-001"
CodeSearchBabbageCode001 = "code-search-babbage-code-001"
CodeSearchBabbageText001 = "code-search-babbage-text-001"
TextEmbeddingAda002 = "text-embedding-ada-002"
)
const (
TextModerationLatest = "text-moderation-latest"
TextModerationStable = "text-moderation-stable"
)
const (
defaultBaseURL = "https://api.openai.com/v1"
defaultUserAgent = "go-gpt3"
defaultTimeoutSeconds = 30
)
func getEngineURL(engine string) string {
return fmt.Sprintf("%s/engines/%s/completions", defaultBaseURL, engine)
}
// A Client is an API client to communicate with the OpenAI gpt-3 APIs
type Client interface {
// Engines lists the currently available engines, and provides basic information about each
// option such as the owner and availability.
Engines(ctx context.Context) (*EnginesResponse, error)
// Engine retrieves an engine instance, providing basic information about the engine such
// as the owner and availability.
Engine(ctx context.Context, engine string) (*EngineObject, error)
// ChatCompletion creates a completion with the Chat completion endpoint which
// is what powers the ChatGPT experience.
ChatCompletion(ctx context.Context, request ChatCompletionRequest) (*ChatCompletionResponse, error)
// ChatCompletion creates a completion with the Chat completion endpoint which
// is what powers the ChatGPT experience.
ChatCompletionStream(ctx context.Context, request ChatCompletionRequest, onData func(*ChatCompletionStreamResponse) error) error
// Completion creates a completion with the default engine. This is the main endpoint of the API
// which auto-completes based on the given prompt.
Completion(ctx context.Context, request CompletionRequest) (*CompletionResponse, error)
// CompletionStream creates a completion with the default engine and streams the results through
// multiple calls to onData.
CompletionStream(ctx context.Context, request CompletionRequest, onData func(*CompletionResponse)) error
// CompletionWithEngine is the same as Completion except allows overriding the default engine on the client
CompletionWithEngine(ctx context.Context, engine string, request CompletionRequest) (*CompletionResponse, error)
// CompletionStreamWithEngine is the same as CompletionStream except allows overriding the default engine on the client
CompletionStreamWithEngine(ctx context.Context, engine string, request CompletionRequest, onData func(*CompletionResponse)) error
// Given a prompt and an instruction, the model will return an edited version of the prompt.
Edits(ctx context.Context, request EditsRequest) (*EditsResponse, error)
// Search performs a semantic search over a list of documents with the default engine.
Search(ctx context.Context, request SearchRequest) (*SearchResponse, error)
// SearchWithEngine performs a semantic search over a list of documents with the specified engine.
SearchWithEngine(ctx context.Context, engine string, request SearchRequest) (*SearchResponse, error)
// Returns an embedding using the provided request.
Embeddings(ctx context.Context, request EmbeddingsRequest) (*EmbeddingsResponse, error)
// Moderation performs a moderation check on the given text against an OpenAI classifier to determine whether the
// provided content complies with OpenAI's usage policies.
Moderation(ctx context.Context, request ModerationRequest) (*ModerationResponse, error)
}
type client struct {
baseURL string
apiKey string
userAgent string
httpClient *http.Client
defaultEngine string
idOrg string
}
// NewClient returns a new OpenAI GPT-3 API client. An apiKey is required to use the client
func NewClient(apiKey string, options ...ClientOption) Client {
httpClient := &http.Client{
Timeout: time.Duration(defaultTimeoutSeconds * time.Second),
}
c := &client{
userAgent: defaultUserAgent,
apiKey: apiKey,
baseURL: defaultBaseURL,
httpClient: httpClient,
defaultEngine: DefaultEngine,
idOrg: "",
}
for _, o := range options {
o(c)
}
return c
}
func (c *client) Engines(ctx context.Context) (*EnginesResponse, error) {
req, err := c.newRequest(ctx, "GET", "/engines", nil)
if err != nil {
return nil, err
}
resp, err := c.performRequest(req)
if err != nil {
return nil, err
}
output := new(EnginesResponse)
if err := getResponseObject(resp, output); err != nil {
return nil, err
}
return output, nil
}
func (c *client) Engine(ctx context.Context, engine string) (*EngineObject, error) {
req, err := c.newRequest(ctx, "GET", fmt.Sprintf("/engines/%s", engine), nil)
if err != nil {
return nil, err
}
resp, err := c.performRequest(req)
if err != nil {
return nil, err
}
output := new(EngineObject)
if err := getResponseObject(resp, output); err != nil {
return nil, err
}
return output, nil
}
func (c *client) ChatCompletion(ctx context.Context, request ChatCompletionRequest) (*ChatCompletionResponse, error) {
if request.Model == "" {
if request.Functions == nil {
request.Model = GPT3Dot5Turbo
} else {
request.Model = GPT3Dot5Turbo0613
}
}
request.Stream = false
req, err := c.newRequest(ctx, "POST", "/chat/completions", request)
if err != nil {
return nil, err
}
resp, err := c.performRequest(req)
if err != nil {
return nil, err
}
output := new(ChatCompletionResponse)
if err := getResponseObject(resp, output); err != nil {
return nil, err
}
output.RateLimitHeaders = NewRateLimitHeadersFromResponse(resp)
return output, nil
}
func (c *client) ChatCompletionStream(
ctx context.Context,
request ChatCompletionRequest,
onData func(*ChatCompletionStreamResponse) error) error {
if request.Model == "" {
request.Model = GPT3Dot5Turbo
}
request.Stream = true
req, err := c.newRequest(ctx, "POST", "/chat/completions", request)
if err != nil {
return err
}
resp, err := c.performRequest(req)
if err != nil {
return err
}
reader := bufio.NewReader(resp.Body)
defer resp.Body.Close()
for {
line, err := reader.ReadBytes('\n')
if err != nil {
return err
}
// make sure there isn't any extra whitespace before or after
line = bytes.TrimSpace(line)
// the completion API only returns data events
if !bytes.HasPrefix(line, dataPrefix) {
continue
}
line = bytes.TrimPrefix(line, dataPrefix)
// the stream is completed when terminated by [DONE]
if bytes.HasPrefix(line, doneSequence) {
break
}
output := new(ChatCompletionStreamResponse)
if err := json.Unmarshal(line, output); err != nil {
return fmt.Errorf("invalid json stream data: %v", err)
}
if err := onData(output); err != nil {
return fmt.Errorf("callback returned an error: %v", err)
}
}
return nil
}
func (c *client) Completion(ctx context.Context, request CompletionRequest) (*CompletionResponse, error) {
return c.CompletionWithEngine(ctx, c.defaultEngine, request)
}
func (c *client) CompletionWithEngine(ctx context.Context, engine string, request CompletionRequest) (*CompletionResponse, error) {
request.Stream = false
req, err := c.newRequest(ctx, "POST", fmt.Sprintf("/engines/%s/completions", engine), request)
if err != nil {
return nil, err
}
resp, err := c.performRequest(req)
if err != nil {
return nil, err
}
output := new(CompletionResponse)
if err := getResponseObject(resp, output); err != nil {
return nil, err
}
output.RateLimitHeaders = NewRateLimitHeadersFromResponse(resp)
return output, nil
}
func (c *client) CompletionStream(ctx context.Context, request CompletionRequest, onData func(*CompletionResponse)) error {
return c.CompletionStreamWithEngine(ctx, c.defaultEngine, request, onData)
}
var (
dataPrefix = []byte("data: ")
doneSequence = []byte("[DONE]")
)
func (c *client) CompletionStreamWithEngine(
ctx context.Context,
engine string,
request CompletionRequest,
onData func(*CompletionResponse),
) error {
request.Stream = true
req, err := c.newRequest(ctx, "POST", fmt.Sprintf("/engines/%s/completions", engine), request)
if err != nil {
return err
}
resp, err := c.performRequest(req)
if err != nil {
return err
}
reader := bufio.NewReader(resp.Body)
defer resp.Body.Close()
for {
line, err := reader.ReadBytes('\n')
if err != nil {
return err
}
// make sure there isn't any extra whitespace before or after
line = bytes.TrimSpace(line)
// the completion API only returns data events
if !bytes.HasPrefix(line, dataPrefix) {
continue
}
line = bytes.TrimPrefix(line, dataPrefix)
// the stream is completed when terminated by [DONE]
if bytes.HasPrefix(line, doneSequence) {
break
}
output := new(CompletionResponse)
if err := json.Unmarshal(line, output); err != nil {
return fmt.Errorf("invalid json stream data: %v", err)
}
onData(output)
}
return nil
}
func (c *client) Edits(ctx context.Context, request EditsRequest) (*EditsResponse, error) {
req, err := c.newRequest(ctx, "POST", "/edits", request)
if err != nil {
return nil, err
}
resp, err := c.performRequest(req)
if err != nil {
return nil, err
}
output := new(EditsResponse)
if err := getResponseObject(resp, output); err != nil {
return nil, err
}
return output, nil
}
func (c *client) Search(ctx context.Context, request SearchRequest) (*SearchResponse, error) {
return c.SearchWithEngine(ctx, c.defaultEngine, request)
}
func (c *client) SearchWithEngine(ctx context.Context, engine string, request SearchRequest) (*SearchResponse, error) {
req, err := c.newRequest(ctx, "POST", fmt.Sprintf("/engines/%s/search", engine), request)
if err != nil {
return nil, err
}
resp, err := c.performRequest(req)
if err != nil {
return nil, err
}
output := new(SearchResponse)
if err := getResponseObject(resp, output); err != nil {
return nil, err
}
return output, nil
}
// Embeddings creates text embeddings for a supplied slice of inputs with a provided model.
//
// See: https://beta.openai.com/docs/api-reference/embeddings
func (c *client) Embeddings(ctx context.Context, request EmbeddingsRequest) (*EmbeddingsResponse, error) {
req, err := c.newRequest(ctx, "POST", "/embeddings", request)
if err != nil {
return nil, err
}
resp, err := c.performRequest(req)
if err != nil {
return nil, err
}
output := EmbeddingsResponse{}
if err := getResponseObject(resp, &output); err != nil {
return nil, err
}
return &output, nil
}
// Moderation performs a moderation check on the given text against an OpenAI classifier.
//
// See: https://platform.openai.com/docs/api-reference/moderations/create
func (c *client) Moderation(ctx context.Context, request ModerationRequest) (*ModerationResponse, error) {
req, err := c.newRequest(ctx, "POST", "/moderations", request)
if err != nil {
return nil, err
}
resp, err := c.performRequest(req)
if err != nil {
return nil, err
}
output := ModerationResponse{}
if err := getResponseObject(resp, &output); err != nil {
return nil, err
}
return &output, nil
}
func (c *client) performRequest(req *http.Request) (*http.Response, error) {
resp, err := c.httpClient.Do(req)
if err != nil {
return nil, err
}
if err := checkForSuccess(resp); err != nil {
return nil, err
}
return resp, nil
}
// returns an error if this response includes an error.
func checkForSuccess(resp *http.Response) error {
if resp.StatusCode >= 200 && resp.StatusCode < 300 {
return nil
}
defer resp.Body.Close()
data, err := ioutil.ReadAll(resp.Body)
if err != nil {
return fmt.Errorf("failed to read from body: %w", err)
}
var result APIErrorResponse
if err := json.Unmarshal(data, &result); err != nil {
// if we can't decode the json error then create an unexpected error
apiError := APIError{
StatusCode: resp.StatusCode,
Type: "Unexpected",
Message: string(data),
}
apiError.RateLimitHeaders = NewRateLimitHeadersFromResponse(resp)
return apiError
}
result.Error.StatusCode = resp.StatusCode
result.Error.RateLimitHeaders = NewRateLimitHeadersFromResponse(resp)
return result.Error
}
func getResponseObject(rsp *http.Response, v interface{}) error {
defer rsp.Body.Close()
if err := json.NewDecoder(rsp.Body).Decode(v); err != nil {
return fmt.Errorf("invalid json response: %w", err)
}
return nil
}
func jsonBodyReader(body interface{}) (io.Reader, error) {
if body == nil {
return bytes.NewBuffer(nil), nil
}
raw, err := json.Marshal(body)
if err != nil {
return nil, fmt.Errorf("failed encoding json: %w", err)
}
return bytes.NewBuffer(raw), nil
}
func (c *client) newRequest(ctx context.Context, method, path string, payload interface{}) (*http.Request, error) {
bodyReader, err := jsonBodyReader(payload)
if err != nil {
return nil, err
}
url := c.baseURL + path
req, err := http.NewRequestWithContext(ctx, method, url, bodyReader)
if err != nil {
return nil, err
}
if len(c.idOrg) > 0 {
req.Header.Set("OpenAI-Organization", c.idOrg)
}
req.Header.Set("Content-type", "application/json")
req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", c.apiKey))
return req, nil
}