forked from picatz/openai
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclient.go
4256 lines (3514 loc) · 128 KB
/
client.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
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package openai
import (
"bufio"
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"math/rand"
"mime/multipart"
"net/http"
"os"
"strconv"
"time"
)
// Client is a client for the OpenAI API.
//
// https://platform.openai.com/docs/api-reference
type Client struct {
// APIKey is the API key to use for requests.
APIKey string
// HTTPClient is the HTTP client to use for requests.
HTTPClient *http.Client
// Organization is the organization to use for requests.
Organization string
}
// ClientOption is a function that configures a Client.
type ClientOption func(*Client)
// WithHTTPClient is a ClientOption that sets the HTTP client to use for requests.
//
// If the client is nil, then http.DefaultClient is used
func WithHTTPClient(c *http.Client) ClientOption {
return func(client *Client) {
if c == nil {
c = http.DefaultClient
}
client.HTTPClient = c
}
}
// WithOrganization is a ClientOption that sets the organization to use for requests.
//
// https://platform.openai.com/docs/api-reference/authentication
func WithOrganization(org string) ClientOption {
return func(client *Client) {
client.Organization = org
}
}
// NewClient returns a new Client with the given API key.
//
// # Example
//
// c := openai.NewClient(os.Getenv("OPENAI_API_KEY"))
func NewClient(apiKey string, opts ...ClientOption) *Client {
c := &Client{
APIKey: apiKey,
HTTPClient: http.DefaultClient,
}
for _, opt := range opts {
opt(c)
}
return c
}
// Role is the role of the user for a chat message.
type Role = string
const (
// RoleSystem is a special used to ground the model within the context of the conversation.
//
// For example, it may be used to provide a name for the assistant, or to provide other global information
// or instructions that the model should know about.
RoleSystem Role = "system"
// RoleUser is the role of the user for a chat message.
RoleUser Role = "user"
// RoleAssistant is the role of the assistant for a chat message.
RoleAssistant Role = "assistant"
// RoleFunction is a special role used to represent a function call.
RoleFunction Role = "function"
)
// CreateCompletionRequest contains information for a "completion" request
// to the OpenAI API. This is the fundamental request type for the API.
//
// https://platform.openai.com/docs/api-reference/completions/create
type CreateCompletionRequest struct {
// ID of the model to use. You can use the List models API to see all of your available models, or see our Model overview for descriptions of them.
//
// https://platform.openai.com/docs/api-reference/completions/create#completions/create-model
Model string `json:"model"`
// The prompt(s) to generate completions for, encoded as a string, array of strings, array of tokens, or array of token arrays.
//
// Note that <|endoftext|> is the document separator that the model sees during training, so if a prompt is not specified the model
// will generate as if from the beginning of a new document.
//
// https://platform.openai.com/docs/api-reference/completions/create#completions/create-prompt
Prompt []string `json:"prompt"`
// https://platform.openai.com/docs/api-reference/completions/create#completions/create-suffix
Suffix string `json:"suffix,omitempty"`
// The maximum number of tokens to generate in the completion.
//
// The token count of your prompt plus max_tokens cannot exceed the model's context length. Most models have a context
// length of 2048 tokens (except for the newest models, which support 4096).
//
// Defaults to 16 if not specified.
//
// https://platform.openai.com/docs/api-reference/completions/create#completions/create-max_tokens
MaxTokens int `json:"max_tokens,omitempty"`
// https://platform.openai.com/docs/api-reference/completions/create#completions/create-temperature
//
// Defaults to 1 if not specified.
Temperature float64 `json:"temperature,omitempty"`
// https://platform.openai.com/docs/api-reference/completions/create#completions/create-top_p
//
// Defaults to 1 if not specified.
TopP float64 `json:"top_p,omitempty"`
// https://platform.openai.com/docs/api-reference/completions/create#completions/create-n
//
// Defaults to 1 if not specified.
N int `json:"n,omitempty"`
// https://platform.openai.com/docs/api-reference/completions/create#completions/create-stream
//
// Defaults to false if not specified.
Stream bool `json:"stream,omitempty"`
// https://platform.openai.com/docs/api-reference/completions/create#completions/create-logprobs
//
// Defaults to nil.
LogProbs *int `json:"logprobs,omitempty"`
// https://platform.openai.com/docs/api-reference/completions/create#completions/create-echo
//
// Defaults to false if not specified.
Echo bool `json:"echo,omitempty"`
// https://platform.openai.com/docs/api-reference/completions/create#completions/create-stop
Stop []string `json:"stop,omitempty"`
// https://platform.openai.com/docs/api-reference/completions/create#completions/create-presence_penalty
//
// Defaults to 0 if not specified.
PresencePenalty int `json:"presence_penalty,omitempty"`
// https://platform.openai.com/docs/api-reference/completions/create#completions/create-frequency_penalty
//
// Defaults to 0 if not specified.
FrequencyPenalty int `json:"frequency_penalty,omitempty"`
// https://platform.openai.com/docs/api-reference/completions/create#completions/create-best_of
//
// Defaults to 1 if not specified.
//
// WARNING: Because this parameter generates many completions, it can quickly consume your token quota.
// Use carefully and ensure that you have reasonable settings for max_tokens and stop.
BestOf int `json:"best_of,omitempty"`
// https://platform.openai.com/docs/api-reference/completions/create#completions/create-logit_bias
//
// Defaults to nil.
LogitBias map[string]float64 `json:"logit_bias,omitempty"`
// https://platform.openai.com/docs/api-reference/completions/create#completions/create-user
//
// Defaults to nil.
User string `json:"user,omitempty"`
}
// CreateCompletionResponse is the response from a "completion" request to the OpenAI API.
//
// https://platform.openai.com/docs/api-reference/completions/create
type CreateCompletionResponse struct {
ID string `json:"id"`
Object string `json:"object"`
Created int `json:"created"`
Model string `json:"model"`
Choices []struct {
Text string `json:"text"`
Index int `json:"index"`
Logprobs interface{} `json:"logprobs"`
FinishReason string `json:"finish_reason"`
} `json:"choices"`
Usage struct {
PromptTokens int `json:"prompt_tokens"`
CompletionTokens int `json:"completion_tokens"`
TotalTokens int `json:"total_tokens"`
} `json:"usage"`
}
// CreateCompletion performs a "completion" request using the OpenAI API.
//
// # Warning
//
// The completions API endpoint received its final update in July 2023 and
// has a different interface than the new [chat completions] endpoint. Instead
// of the input being a list of messages, the input is a freeform text string
// called a prompt.
//
// # Example
//
// resp, _ := client.CreateCompletion(ctx, &openai.CreateCompletionRequest{
// Model: openai.ModelDavinci,
// Prompt: []string{"Once upon a time"},
// MaxTokens: 16,
// })
//
// Deprecated: [github.com/picatz/openai.Client.CreateCompletion] is [deprecated] (legacy). Use [github.com/picatz/openai.Client.CreateChat] instead.
//
// https://platform.openai.com/docs/api-reference/completions/create
//
// [deprecated]: https://platform.openai.com/docs/guides/gpt/completions-api
// [chat completions]: https://platform.openai.com/docs/api-reference/chat/create
func (c *Client) CreateCompletion(ctx context.Context, req *CreateCompletionRequest) (*CreateCompletionResponse, error) {
b, err := json.Marshal(req)
if err != nil {
return nil, err
}
r, err := http.NewRequestWithContext(ctx, http.MethodPost, "https://api.openai.com/v1/completions", bytes.NewReader(b))
if err != nil {
return nil, err
}
r.Header.Set("Authorization", "Bearer "+c.APIKey)
r.Header.Set("Content-Type", "application/json")
if c.Organization != "" {
r.Header.Set("OpenAI-Organization", c.Organization)
}
resp, err := c.HTTPClient.Do(r)
if err != nil {
return nil, err
}
if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("unexpected status code: %d: %s", resp.StatusCode, http.StatusText(resp.StatusCode))
}
cResp := &CreateCompletionResponse{}
err = json.NewDecoder(resp.Body).Decode(cResp)
if err != nil {
return nil, err
}
return cResp, nil
}
// https://platform.openai.com/docs/api-reference/models/list
type Models struct {
Object string `json:"object"`
Data []struct {
ID string `json:"id"`
Object string `json:"object"`
Created int `json:"created"`
OwnedBy string `json:"owned_by"`
Permission []struct {
ID string `json:"id"`
Object string `json:"object"`
Created int `json:"created"`
AllowCreateEngine bool `json:"allow_create_engine"`
AllowSampling bool `json:"allow_sampling"`
AllowLogprobs bool `json:"allow_logprobs"`
AllowSearchIndices bool `json:"allow_search_indices"`
AllowView bool `json:"allow_view"`
AllowFineTuning bool `json:"allow_fine_tuning"`
Organization string `json:"organization"`
Group interface{} `json:"group"`
IsBlocking bool `json:"is_blocking"`
} `json:"permission"`
Root string `json:"root"`
Parent interface{} `json:"parent"`
} `json:"data"`
}
// ListModels list model identifiers that can be used with the OpenAI API.
//
// # Example
//
// resp, _ := client.ListModels(ctx)
//
// for _, model := range resp.Data {
// fmt.Println(model.ID)
// }
//
// https://platform.openai.com/docs/api-reference/models/list
func (c *Client) ListModels(ctx context.Context) (*Models, error) {
r, err := http.NewRequestWithContext(ctx, http.MethodPost, "https://api.openai.com/v1/models", nil)
if err != nil {
return nil, err
}
r.Header.Set("Authorization", "Bearer "+c.APIKey)
r.Header.Set("Content-Type", "application/json")
if c.Organization != "" {
r.Header.Set("OpenAI-Organization", c.Organization)
}
resp, err := c.HTTPClient.Do(r)
if err != nil {
return nil, err
}
if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("unexpected status code: %d: %s", resp.StatusCode, http.StatusText(resp.StatusCode))
}
cResp := &Models{}
err = json.NewDecoder(resp.Body).Decode(cResp)
if err != nil {
return nil, err
}
return cResp, nil
}
// CreateEditRequest is the request for a "edit" request to the OpenAI API.
//
// https://platform.openai.com/docs/api-reference/edits/create
type CreateEditRequest struct {
// https://platform.openai.com/docs/api-reference/edits/create#edits/create-model
//
// Required.
Model string `json:"model"`
// https://platform.openai.com/docs/api-reference/edits/create#edits/create-instruction
//
// Required.
Instruction string `json:"instruction"`
// https://platform.openai.com/docs/api-reference/edits/create#edits/create-input
Input string `json:"input"`
// https://platform.openai.com/docs/api-reference/edits/create#edits/create-n
N int `json:"n,omitempty"`
// https://platform.openai.com/docs/api-reference/edits/create#edits/create-temperature
Temperature float64 `json:"temperature,omitempty"`
// https://platform.openai.com/docs/api-reference/edits/create#edits/create-top-p
TopP float64 `json:"top_p,omitempty"`
}
// https://platform.openai.com/docs/api-reference/edits/create
type CreateEditResponse struct {
Object string `json:"object"`
Created int `json:"created"`
Choices []struct {
Text string `json:"text"`
Index int `json:"index"`
} `json:"choices"`
Usage struct {
PromptTokens int `json:"prompt_tokens"`
CompletionTokens int `json:"completion_tokens"`
TotalTokens int `json:"total_tokens"`
} `json:"usage"`
}
// CreateEdit performs a "edit" request using the OpenAI API.
//
// # Warning
//
// Users of the Edits API and its associated models (e.g., text-davinci-edit-001 or code-davinci-edit-001)
// will need to migrate to GPT-3.5 Turbo by January 4, 2024.
//
// # Example
//
// resp, _ := client.CreateEdit(ctx, &CreateEditRequest{
// Model: openai.ModelTextDavinciEdit001,
// Instruction: "Change the word 'test' to 'example'",
// Input: "This is a test",
// })
//
// Deprecated: [github.com/picatz/openai.Client.CreateEdit] is [deprecated] (legacy). Use [github.com/picatz/openai.Client.CreateChat] instead.
//
// https://platform.openai.com/docs/api-reference/edits/create
//
// [deprecated]: https://openai.com/blog/gpt-4-api-general-availability
func (c *Client) CreateEdit(ctx context.Context, req *CreateEditRequest) (*CreateEditResponse, error) {
b, err := json.Marshal(req)
if err != nil {
return nil, err
}
r, err := http.NewRequestWithContext(ctx, http.MethodPost, "https://api.openai.com/v1/edits", bytes.NewReader(b))
if err != nil {
return nil, err
}
r.Header.Set("Authorization", "Bearer "+c.APIKey)
r.Header.Set("Content-Type", "application/json")
r.Header.Set("Content-Length", fmt.Sprintf("%d", len(b)))
if c.Organization != "" {
r.Header.Set("OpenAI-Organization", c.Organization)
}
resp, err := c.HTTPClient.Do(r)
if err != nil {
return nil, err
}
if resp.StatusCode != http.StatusOK {
body, _ := io.ReadAll(resp.Body)
return nil, fmt.Errorf("unexpected status code: %d: %s: %s", resp.StatusCode, http.StatusText(resp.StatusCode), body)
}
cResp := &CreateEditResponse{}
err = json.NewDecoder(resp.Body).Decode(cResp)
if err != nil {
return nil, err
}
return cResp, nil
}
// https://platform.openai.com/docs/api-reference/images/create
type CreateImageRequest struct {
// https://platform.openai.com/docs/api-reference/images/create#images/create-prompt
//
// Required. Max of 1,000 characters.
Prompt string `json:"prompt"`
// https://platform.openai.com/docs/api-reference/images/create#images-create-model
//
// Optional. Defaults to "dall-e-2".
Model string `json:"model,omitempty"`
// https://platform.openai.com/docs/api-reference/completions/create#completions/create-n
//
// Number of images to generate. Defaults to 1 if not specified. Most be between 1 and 10.
N int `json:"n,omitempty"`
// https://platform.openai.com/docs/api-reference/images/create#images/create-size
//
// Size of the image to generate. Must be one of 256x256, 512x512, or 1024x1024.
Size string `json:"size,omitempty"`
// https://platform.openai.com/docs/api-reference/images/create#images/create-response_format
//
// Defaults to "url". The format in which the generated images are returned. Must be one of "url" or "b64_json".
ResponseFormat string `json:"response_format,omitempty"`
// https://platform.openai.com/docs/api-reference/images/create#images/create-user
User string `json:"user,omitempty"`
// https://platform.openai.com/docs/api-reference/images/create#images-create-quality
//
// Optional. Either "standard" or "hd", defaults to "standard".
Quality string `json:"quality,omitempty"`
// https://platform.openai.com/docs/api-reference/images/create#images-create-style
//
// Optional. Either "vivid" or "natural", defaults to "vivid". Only valid for "dall-e-3" model.
Style string `json:"style,omitempty"`
}
// CreateImageResponse ...
type CreateImageResponse struct {
Created int `json:"created"`
Data []struct {
// One of the following: "url" or "b64_json"
URL *string `json:"url"`
B64JSON *string `json:"b64_json"`
// If there were any prompt revisions made by the API.
// Use this to refine further.
RevisedPrompt *string `json:"revised_prompt"`
} `json:"data"`
}
// CreateImage performs a "image" request using the OpenAI API.
//
// # Example
//
// resp, _ := c.CreateImage(ctx, &openai.CreateImageRequest{
// Prompt: "Golang-style gopher mascot wearing an OpenAI t-shirt",
// N: 1,
// Size: "256x256",
// ResponseFormat: "url",
// })
//
// https://platform.openai.com/docs/api-reference/images/create
func (c *Client) CreateImage(ctx context.Context, req *CreateImageRequest) (*CreateImageResponse, error) {
b, err := json.Marshal(req)
if err != nil {
return nil, err
}
r, err := http.NewRequestWithContext(ctx, http.MethodPost, "https://api.openai.com/v1/images/generations", bytes.NewReader(b))
if err != nil {
return nil, err
}
r.Header.Set("Authorization", "Bearer "+c.APIKey)
r.Header.Set("Content-Type", "application/json")
r.Header.Set("Content-Length", fmt.Sprintf("%d", len(b)))
if c.Organization != "" {
r.Header.Set("OpenAI-Organization", c.Organization)
}
resp, err := c.HTTPClient.Do(r)
if err != nil {
return nil, err
}
if resp.StatusCode != http.StatusOK {
body, _ := io.ReadAll(resp.Body)
return nil, fmt.Errorf("unexpected status code: %d: %s: %s", resp.StatusCode, http.StatusText(resp.StatusCode), body)
}
cResp := &CreateImageResponse{}
err = json.NewDecoder(resp.Body).Decode(cResp)
if err != nil {
return nil, err
}
return cResp, nil
}
// https://platform.openai.com/docs/api-reference/embeddings
type CreateEmbeddingRequest struct {
// https://platform.openai.com/docs/api-reference/embeddings/create#embeddings/create-model
//
// Required. The text to embed.
Model string `json:"model"`
// https://platform.openai.com/docs/api-reference/embeddings/create#embeddings/create-input
//
// Required. The text to embed.
Input string `json:"input"`
// https://platform.openai.com/docs/api-reference/embeddings/create#embeddings/create-user
User string `json:"user,omitempty"`
}
// CreateEmbeddingResponse ...
//
// https://platform.openai.com/docs/guides/embeddings/what-are-embeddings
type CreateEmbeddingResponse struct {
Object string `json:"object"`
Data []struct {
Object string `json:"object"`
Embedding []float64 `json:"embedding"`
Index int `json:"index"`
} `json:"data"`
Model string `json:"model"`
Usage struct {
PromptTokens int `json:"prompt_tokens"`
TotalTokens int `json:"total_tokens"`
} `json:"usage"`
}
// CreateEmbedding performs a "embedding" request using the OpenAI API.
//
// # Example
//
// resp, _ := c.CreateEmbedding(ctx, &openai.CreateEmbeddingRequest{
// Model: openai.ModelTextEmbeddingAda002,
// Input: "The food was delicious and the waiter...",
// })
//
// https://platform.openai.com/docs/api-reference/embeddings
func (c *Client) CreateEmbedding(ctx context.Context, req *CreateEmbeddingRequest) (*CreateEmbeddingResponse, error) {
b, err := json.Marshal(req)
if err != nil {
return nil, err
}
r, err := http.NewRequestWithContext(ctx, http.MethodPost, "https://api.openai.com/v1/embeddings", bytes.NewReader(b))
if err != nil {
return nil, err
}
r.Header.Set("Authorization", "Bearer "+c.APIKey)
r.Header.Set("Content-Type", "application/json")
r.Header.Set("Content-Length", fmt.Sprintf("%d", len(b)))
if c.Organization != "" {
r.Header.Set("OpenAI-Organization", c.Organization)
}
resp, err := c.HTTPClient.Do(r)
if err != nil {
return nil, err
}
if resp.StatusCode != http.StatusOK {
body, _ := io.ReadAll(resp.Body)
return nil, fmt.Errorf("unexpected status code: %d: %s: %s", resp.StatusCode, http.StatusText(resp.StatusCode), body)
}
cResp := &CreateEmbeddingResponse{}
err = json.NewDecoder(resp.Body).Decode(cResp)
if err != nil {
return nil, err
}
return cResp, nil
}
// https://platform.openai.com/docs/api-reference/moderations/create
type CreateModerationRequest struct {
// https://platform.openai.com/docs/api-reference/moderations/create#moderations/create-model
//
// Optional. The model to use for moderation. Defaults to "text-moderation-latest".
Model string `json:"model"`
// https://platform.openai.com/docs/api-reference/moderations/create#moderations/create-input
//
// Required. The text to moderate.
Input string `json:"input"`
}
// CreateModerationResponse ...
//
// https://platform.openai.com/docs/guides/moderations/what-are-moderations
type CreateModerationResponse struct {
ID string `json:"id"`
Model string `json:"model"`
Results []struct {
Categories struct {
Hate bool `json:"hate"`
HateThreatening bool `json:"hate/threatening"`
SelfHarm bool `json:"self-harm"`
Sexual bool `json:"sexual"`
SexualMinors bool `json:"sexual/minors"`
Violence bool `json:"violence"`
ViolenceGraphic bool `json:"violence/graphic"`
} `json:"categories"`
CategoryScores struct {
Hate float64 `json:"hate"`
HateThreatening float64 `json:"hate/threatening"`
SelfHarm float64 `json:"self-harm"`
Sexual float64 `json:"sexual"`
SexualMinors float64 `json:"sexual/minors"`
Violence float64 `json:"violence"`
ViolenceGraphic float64 `json:"violence/graphic"`
} `json:"category_scores"`
Flagged bool `json:"flagged"`
} `json:"results"`
}
// CreateModeration performs a "moderation" request using the OpenAI API.
//
// # Example
//
// resp, _ := c.CreateModeration(ctx, &openai.CreateModerationRequest{
// Input: "I want to kill them.",
// })
//
// https://platform.openai.com/docs/api-reference/moderations
func (c *Client) CreateModeration(ctx context.Context, req *CreateModerationRequest) (*CreateModerationResponse, error) {
b, err := json.Marshal(req)
if err != nil {
return nil, err
}
r, err := http.NewRequestWithContext(ctx, http.MethodPost, "https://api.openai.com/v1/moderations", bytes.NewReader(b))
if err != nil {
return nil, err
}
r.Header.Set("Authorization", "Bearer "+c.APIKey)
r.Header.Set("Content-Type", "application/json")
r.Header.Set("Content-Length", fmt.Sprintf("%d", len(b)))
if c.Organization != "" {
r.Header.Set("OpenAI-Organization", c.Organization)
}
resp, err := c.HTTPClient.Do(r)
if err != nil {
return nil, err
}
if resp.StatusCode != http.StatusOK {
body, _ := io.ReadAll(resp.Body)
return nil, fmt.Errorf("unexpected status code: %d: %s: %s", resp.StatusCode, http.StatusText(resp.StatusCode), body)
}
cResp := &CreateModerationResponse{}
err = json.NewDecoder(resp.Body).Decode(cResp)
if err != nil {
return nil, err
}
return cResp, nil
}
// https://platform.openai.com/docs/api-reference/files/list
type ListFilesRequest struct {
// https://platform.openai.com/docs/api-reference/files/list#files-list-purpose
//
// Optional. Filter to only list files with the specified purpose (assistants, fine-tune, etc).
Purpose string `json:"purpose,omitempty"`
}
// https://platform.openai.com/docs/api-reference/files/list
type ListFilesResponse struct {
Data []struct {
ID string `json:"id"`
Object string `json:"object"`
Bytes int `json:"bytes"`
CreatedAt int `json:"created_at"`
Filename string `json:"filename"`
Purpose string `json:"purpose"`
} `json:"data"`
Object string `json:"object"`
}
// ListFiles performs a "list files" request using the OpenAI API.
//
// # Example
//
// resp, _ := c.ListFiles(ctx, &openai.ListFilesRequest{})
//
// https://platform.openai.com/docs/api-reference/files
func (c *Client) ListFiles(ctx context.Context, req *ListFilesRequest) (*ListFilesResponse, error) {
r, err := http.NewRequestWithContext(ctx, http.MethodGet, "https://api.openai.com/v1/files", nil)
if err != nil {
return nil, err
}
r.Header.Set("Authorization", "Bearer "+c.APIKey)
if c.Organization != "" {
r.Header.Set("OpenAI-Organization", c.Organization)
}
resp, err := c.HTTPClient.Do(r)
if err != nil {
return nil, err
}
if resp.StatusCode != http.StatusOK {
body, _ := io.ReadAll(resp.Body)
return nil, fmt.Errorf("unexpected status code: %d: %s: %s", resp.StatusCode, http.StatusText(resp.StatusCode), body)
}
cResp := &ListFilesResponse{}
err = json.NewDecoder(resp.Body).Decode(cResp)
if err != nil {
return nil, err
}
return cResp, nil
}
// https://platform.openai.com/docs/api-reference/files/upload
type UploadFileRequest struct {
// Name of the JSON Lines file to be uploaded.
//
// If the purpose is set to "fine-tune", each line is a JSON
// record with "prompt" and "completion" fields representing
// your training examples.
//
// Required.
Name string `json:"name"`
// Purpose of the uploaded documents.
//
// Use "fine-tune" for Fine-tuning. This allows us to validate t
// the format of the uploaded file.
//
// Required.
Purpose string `json:"purpose"`
// Body of the file to upload.
//
// Required.
Body io.Reader `json:"file"` // TODO: how to handle this?
}
// UploadFileResponse ...
//
// https://platform.openai.com/docs/api-reference/files/upload
type UploadFileResponse struct {
ID string `json:"id"`
Object string `json:"object"`
Bytes int `json:"bytes"`
CreatedAt int `json:"created_at"`
Filename string `json:"filename"`
Purpose string `json:"purpose"`
}
// UploadFile performs a "upload file" request using the OpenAI API.
//
// # Example
//
// resp, _ := c.UploadFile(ctx, &openai.UploadFileRequest{
// Name: "fine-tune.jsonl",
// Purpose: "fine-tune",
// })
//
// https://platform.openai.com/docs/api-reference/files
func (c *Client) UploadFile(ctx context.Context, req *UploadFileRequest) (*UploadFileResponse, error) {
r, err := http.NewRequestWithContext(ctx, http.MethodPost, "https://api.openai.com/v1/files", nil)
if err != nil {
return nil, err
}
r.Header.Set("Authorization", "Bearer "+c.APIKey)
if c.Organization != "" {
r.Header.Set("OpenAI-Organization", c.Organization)
}
r.Header.Set("Content-Type", "multipart/form-data")
var b bytes.Buffer
w := multipart.NewWriter(&b)
fw, err := w.CreateFormFile("file", req.Name)
if err != nil {
return nil, err
}
_, err = io.Copy(fw, req.Body)
if err != nil {
return nil, err
}
err = w.WriteField("purpose", req.Purpose)
if err != nil {
return nil, err
}
err = w.Close()
if err != nil {
return nil, err
}
r.Body = io.NopCloser(&b)
r.ContentLength = int64(b.Len())
r.Header.Set("Content-Type", w.FormDataContentType())
resp, err := c.HTTPClient.Do(r)
if err != nil {
return nil, err
}
if resp.StatusCode != http.StatusOK {
body, _ := io.ReadAll(resp.Body)
return nil, fmt.Errorf("unexpected status code: %d: %s: %s", resp.StatusCode, http.StatusText(resp.StatusCode), body)
}
cResp := &UploadFileResponse{}
err = json.NewDecoder(resp.Body).Decode(cResp)
if err != nil {
return nil, err
}
return cResp, nil
}
// https://platform.openai.com/docs/api-reference/files/delete
type DeleteFileRequest struct {
// ID of the file to delete.
//
// Required.
ID string `json:"id"`
}
// DeleteFileResponse ...
//
// https://platform.openai.com/docs/api-reference/files/delete
type DeleteFileResponse struct {
ID string `json:"id"`
Object string `json:"object"`
Deleted bool `json:"deleted"`
}
// DeleteFile performs a "delete file" request using the OpenAI API.
//
// # Example
//
// resp, _ := c.DeleteFile(ctx, &openai.DeleteFileRequest{
// ID: "file-123",
// })
//
// https://platform.openai.com/docs/api-reference/files/delete
func (c *Client) DeleteFile(ctx context.Context, req *DeleteFileRequest) (*DeleteFileResponse, error) {
r, err := http.NewRequestWithContext(ctx, http.MethodDelete, "https://api.openai.com/v1/files/"+req.ID, nil)
if err != nil {
return nil, err
}
r.Header.Set("Authorization", "Bearer "+c.APIKey)
if c.Organization != "" {
r.Header.Set("OpenAI-Organization", c.Organization)
}
resp, err := c.HTTPClient.Do(r)
if err != nil {
return nil, err
}
if resp.StatusCode != http.StatusOK {
body, _ := io.ReadAll(resp.Body)
return nil, fmt.Errorf("unexpected status code: %d: %s: %s", resp.StatusCode, http.StatusText(resp.StatusCode), body)
}
cResp := &DeleteFileResponse{}
err = json.NewDecoder(resp.Body).Decode(cResp)
if err != nil {
return nil, err
}
return cResp, nil
}
// https://platform.openai.com/docs/api-reference/files/retrieve
type GetFileInfoRequest struct {
// ID of the file to retrieve.
//
// Required.
ID string `json:"id"`
}
// GetFileInfoResponse ...
//
// https://platform.openai.com/docs/api-reference/files/retrieve
type GetFileInfoResponse struct {
ID string `json:"id"`
Object string `json:"object"`
Bytes int `json:"bytes"`
CreatedAt int `json:"created_at"`
Filename string `json:"filename"`
Purpose string `json:"purpose"`
}
// GetFileInfo performs a "get file info (retrieve)" request using the OpenAI API.
//
// # Example
//
// resp, _ := c.GetFileInfo(ctx, &openai.GetFileRequest{
// ID: "file-123",
// })
//
// https://platform.openai.com/docs/api-reference/files/retrieve
func (c *Client) GetFileInfo(ctx context.Context, req *GetFileInfoRequest) (*GetFileInfoResponse, error) {
r, err := http.NewRequestWithContext(ctx, http.MethodGet, "https://api.openai.com/v1/files/"+req.ID, nil)
if err != nil {
return nil, err
}
r.Header.Add("Authorization", "Bearer "+c.APIKey)
if c.Organization != "" {
r.Header.Set("OpenAI-Organization", c.Organization)
}
resp, err := c.HTTPClient.Do(r)
if err != nil {
return nil, err
}
if resp.StatusCode != http.StatusOK {
body, _ := io.ReadAll(resp.Body)
return nil, fmt.Errorf("unexpected status code: %d: %s: %s", resp.StatusCode, http.StatusText(resp.StatusCode), body)
}
cResp := &GetFileInfoResponse{}
err = json.NewDecoder(resp.Body).Decode(cResp)
if err != nil {
return nil, err
}
return cResp, nil
}
// https://platform.openai.com/docs/api-reference/files/retrieve-content
type GetFileContentRequest struct {
// ID of the file to retrieve.
//
// Required.
ID string `json:"id"`