-
Notifications
You must be signed in to change notification settings - Fork 0
/
example_test.go
349 lines (313 loc) · 7.89 KB
/
example_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
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
package openai_test
import (
"bufio"
"context"
"encoding/base64"
"errors"
"fmt"
"io"
"net/http"
"net/url"
"os"
"github.com/lysunagopher/go-openai"
)
func Example() {
client := openai.NewClient(os.Getenv("OPENAI_API_KEY"))
resp, err := client.CreateChatCompletion(
context.Background(),
openai.ChatCompletionRequest{
Model: openai.GPT3Dot5Turbo,
Messages: []openai.ChatCompletionMessage{
{
Role: openai.ChatMessageRoleUser,
Content: "Hello!",
},
},
},
)
if err != nil {
fmt.Printf("ChatCompletion error: %v\n", err)
return
}
fmt.Println(resp.Choices[0].Message.Content)
}
func ExampleClient_CreateChatCompletionStream() {
client := openai.NewClient(os.Getenv("OPENAI_API_KEY"))
stream, err := client.CreateChatCompletionStream(
context.Background(),
openai.ChatCompletionRequest{
Model: openai.GPT3Dot5Turbo,
MaxTokens: 20,
Messages: []openai.ChatCompletionMessage{
{
Role: openai.ChatMessageRoleUser,
Content: "Lorem ipsum",
},
},
Stream: true,
},
)
if err != nil {
fmt.Printf("ChatCompletionStream error: %v\n", err)
return
}
defer stream.Close()
fmt.Printf("Stream response: ")
for {
var response openai.ChatCompletionStreamResponse
response, err = stream.Recv()
if errors.Is(err, io.EOF) {
fmt.Println("\nStream finished")
return
}
if err != nil {
fmt.Printf("\nStream error: %v\n", err)
return
}
fmt.Printf(response.Choices[0].Delta.Content)
}
}
func ExampleClient_CreateCompletion() {
client := openai.NewClient(os.Getenv("OPENAI_API_KEY"))
resp, err := client.CreateCompletion(
context.Background(),
openai.CompletionRequest{
Model: openai.GPT3Ada,
MaxTokens: 5,
Prompt: "Lorem ipsum",
},
)
if err != nil {
fmt.Printf("Completion error: %v\n", err)
return
}
fmt.Println(resp.Choices[0].Text)
}
func ExampleClient_CreateCompletionStream() {
client := openai.NewClient(os.Getenv("OPENAI_API_KEY"))
stream, err := client.CreateCompletionStream(
context.Background(),
openai.CompletionRequest{
Model: openai.GPT3Ada,
MaxTokens: 5,
Prompt: "Lorem ipsum",
Stream: true,
},
)
if err != nil {
fmt.Printf("CompletionStream error: %v\n", err)
return
}
defer stream.Close()
for {
var response openai.CompletionResponse
response, err = stream.Recv()
if errors.Is(err, io.EOF) {
fmt.Println("Stream finished")
return
}
if err != nil {
fmt.Printf("Stream error: %v\n", err)
return
}
fmt.Printf("Stream response: %#v\n", response)
}
}
func ExampleClient_CreateTranscription() {
client := openai.NewClient(os.Getenv("OPENAI_API_KEY"))
resp, err := client.CreateTranscription(
context.Background(),
openai.AudioRequest{
Model: openai.Whisper1,
FilePath: "recording.mp3",
},
)
if err != nil {
fmt.Printf("Transcription error: %v\n", err)
return
}
fmt.Println(resp.Text)
}
func ExampleClient_CreateTranscription_captions() {
client := openai.NewClient(os.Getenv("OPENAI_API_KEY"))
resp, err := client.CreateTranscription(
context.Background(),
openai.AudioRequest{
Model: openai.Whisper1,
FilePath: os.Args[1],
Format: openai.AudioResponseFormatSRT,
},
)
if err != nil {
fmt.Printf("Transcription error: %v\n", err)
return
}
f, err := os.Create(os.Args[1] + ".srt")
if err != nil {
fmt.Printf("Could not open file: %v\n", err)
return
}
defer f.Close()
if _, err = f.WriteString(resp.Text); err != nil {
fmt.Printf("Error writing to file: %v\n", err)
return
}
}
func ExampleClient_CreateTranslation() {
client := openai.NewClient(os.Getenv("OPENAI_API_KEY"))
resp, err := client.CreateTranslation(
context.Background(),
openai.AudioRequest{
Model: openai.Whisper1,
FilePath: "recording.mp3",
},
)
if err != nil {
fmt.Printf("Translation error: %v\n", err)
return
}
fmt.Println(resp.Text)
}
func ExampleClient_CreateImage() {
client := openai.NewClient(os.Getenv("OPENAI_API_KEY"))
respURL, err := client.CreateImage(
context.Background(),
openai.ImageRequest{
Prompt: "Parrot on a skateboard performs a trick, cartoon style, natural light, high detail",
Size: openai.CreateImageSize256x256,
ResponseFormat: openai.CreateImageResponseFormatURL,
N: 1,
},
)
if err != nil {
fmt.Printf("Image creation error: %v\n", err)
return
}
fmt.Println(respURL.Data[0].URL)
}
func ExampleClient_CreateImage_base64() {
client := openai.NewClient(os.Getenv("OPENAI_API_KEY"))
resp, err := client.CreateImage(
context.Background(),
openai.ImageRequest{
Prompt: "Portrait of a humanoid parrot in a classic costume, high detail, realistic light, unreal engine",
Size: openai.CreateImageSize512x512,
ResponseFormat: openai.CreateImageResponseFormatB64JSON,
N: 1,
},
)
if err != nil {
fmt.Printf("Image creation error: %v\n", err)
return
}
b, err := base64.StdEncoding.DecodeString(resp.Data[0].B64JSON)
if err != nil {
fmt.Printf("Base64 decode error: %v\n", err)
return
}
f, err := os.Create("example.png")
if err != nil {
fmt.Printf("File creation error: %v\n", err)
return
}
defer f.Close()
_, err = f.Write(b)
if err != nil {
fmt.Printf("File write error: %v\n", err)
return
}
fmt.Println("The image was saved as example.png")
}
func ExampleClientConfig_clientWithProxy() {
config := openai.DefaultConfig(os.Getenv("OPENAI_API_KEY"))
port := os.Getenv("OPENAI_PROXY_PORT")
proxyURL, err := url.Parse(fmt.Sprintf("http://localhost:%s", port))
if err != nil {
panic(err)
}
transport := &http.Transport{
Proxy: http.ProxyURL(proxyURL),
}
config.HTTPClient = &http.Client{
Transport: transport,
}
client := openai.NewClientWithConfig(config)
client.CreateChatCompletion( //nolint:errcheck // outside of the scope of this example.
context.Background(),
openai.ChatCompletionRequest{
// etc...
},
)
}
func Example_chatbot() {
client := openai.NewClient(os.Getenv("OPENAI_API_KEY"))
req := openai.ChatCompletionRequest{
Model: openai.GPT3Dot5Turbo,
Messages: []openai.ChatCompletionMessage{
{
Role: openai.ChatMessageRoleSystem,
Content: "you are a helpful chatbot",
},
},
}
fmt.Println("Conversation")
fmt.Println("---------------------")
fmt.Print("> ")
s := bufio.NewScanner(os.Stdin)
for s.Scan() {
req.Messages = append(req.Messages, openai.ChatCompletionMessage{
Role: openai.ChatMessageRoleUser,
Content: s.Text(),
})
resp, err := client.CreateChatCompletion(context.Background(), req)
if err != nil {
fmt.Printf("ChatCompletion error: %v\n", err)
continue
}
fmt.Printf("%s\n\n", resp.Choices[0].Message.Content)
req.Messages = append(req.Messages, resp.Choices[0].Message)
fmt.Print("> ")
}
}
func ExampleDefaultAzureConfig() {
azureKey := os.Getenv("AZURE_OPENAI_API_KEY") // Your azure API key
azureEndpoint := os.Getenv("AZURE_OPENAI_ENDPOINT") // Your azure OpenAI endpoint
config := openai.DefaultAzureConfig(azureKey, azureEndpoint)
client := openai.NewClientWithConfig(config)
resp, err := client.CreateChatCompletion(
context.Background(),
openai.ChatCompletionRequest{
Model: openai.GPT3Dot5Turbo,
Messages: []openai.ChatCompletionMessage{
{
Role: openai.ChatMessageRoleUser,
Content: "Hello Azure OpenAI!",
},
},
},
)
if err != nil {
fmt.Printf("ChatCompletion error: %v\n", err)
return
}
fmt.Println(resp.Choices[0].Message.Content)
}
// Open-AI maintains clear documentation on how to handle API errors.
//
// see: https://platform.openai.com/docs/guides/error-codes/api-errors
func ExampleAPIError() {
var err error // Assume this is the error you are checking.
e := &openai.APIError{}
if errors.As(err, &e) {
switch e.HTTPStatusCode {
case 401:
// invalid auth or key (do not retry)
case 429:
// rate limiting or engine overload (wait and retry)
case 500:
// openai server error (retry)
default:
// unhandled
}
}
}