Skip to content

Commit 82d9324

Browse files
committed
Add batch API to integration tests and optimize batch API example
1 parent 4f72284 commit 82d9324

File tree

2 files changed

+87
-26
lines changed

2 files changed

+87
-26
lines changed

api_integration_test.go

Lines changed: 68 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ package openai_test
55
import (
66
"context"
77
"errors"
8+
"fmt"
89
"io"
910
"os"
1011
"testing"
@@ -144,6 +145,73 @@ func TestCompletionStream(t *testing.T) {
144145
}
145146
}
146147

148+
func TestBatchAPI(t *testing.T) {
149+
ctx := context.Background()
150+
apiToken := os.Getenv("OPENAI_TOKEN")
151+
if apiToken == "" {
152+
t.Skip("Skipping testing against production OpenAI API. Set OPENAI_TOKEN environment variable to enable it.")
153+
}
154+
var err error
155+
c := openai.NewClient(apiToken)
156+
157+
req := openai.CreateBatchWithUploadFileRequest{
158+
Endpoint: openai.BatchEndpointChatCompletions,
159+
CompletionWindow: "24h",
160+
}
161+
for i := 0; i < 5; i++ {
162+
req.AddChatCompletion(fmt.Sprintf("req-%d", i), openai.ChatCompletionRequest{
163+
Model: openai.GPT4oMini,
164+
Messages: []openai.ChatCompletionMessage{
165+
{
166+
Role: openai.ChatMessageRoleUser,
167+
Content: fmt.Sprintf("What is the square of %d?", i+1),
168+
},
169+
},
170+
})
171+
}
172+
_, err = c.CreateBatchWithUploadFile(ctx, req)
173+
checks.NoError(t, err, "CreateBatchWithUploadFile error")
174+
175+
var chatCompletions = make([]openai.BatchChatCompletion, 5)
176+
for i := 0; i < 5; i++ {
177+
chatCompletions[i] = openai.BatchChatCompletion{
178+
CustomID: fmt.Sprintf("req-%d", i),
179+
ChatCompletion: openai.ChatCompletionRequest{
180+
Model: openai.GPT4oMini,
181+
Messages: []openai.ChatCompletionMessage{
182+
{
183+
Role: openai.ChatMessageRoleUser,
184+
Content: fmt.Sprintf("What is the square of %d?", i+1),
185+
},
186+
},
187+
},
188+
}
189+
}
190+
_, err = c.CreateBatchWithChatCompletions(ctx, openai.CreateBatchWithChatCompletionsRequest{
191+
ChatCompletions: chatCompletions,
192+
})
193+
checks.NoError(t, err, "CreateBatchWithChatCompletions error")
194+
195+
var embeddings = make([]openai.BatchEmbedding, 3)
196+
for i := 0; i < 3; i++ {
197+
embeddings[i] = openai.BatchEmbedding{
198+
CustomID: fmt.Sprintf("req-%d", i),
199+
Embedding: openai.EmbeddingRequest{
200+
Input: "The food was delicious and the waiter...",
201+
Model: openai.AdaEmbeddingV2,
202+
EncodingFormat: openai.EmbeddingEncodingFormatFloat,
203+
},
204+
}
205+
}
206+
_, err = c.CreateBatchWithEmbeddings(ctx, openai.CreateBatchWithEmbeddingsRequest{
207+
Embeddings: embeddings,
208+
})
209+
checks.NoError(t, err, "CreateBatchWithEmbeddings error")
210+
211+
_, err = c.ListBatch(ctx, nil, nil)
212+
checks.NoError(t, err, "ListBatch error")
213+
}
214+
147215
func TestAPIError(t *testing.T) {
148216
apiToken := os.Getenv("OPENAI_TOKEN")
149217
if apiToken == "" {

examples/batch/main.go

Lines changed: 19 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@ func main() {
1414
ctx := context.Background()
1515

1616
// create batch
17-
response, err := createBatch(ctx, client)
17+
response, err := createBatchChatCompletion(ctx, client)
1818
if err != nil {
1919
log.Fatal(err)
2020
}
@@ -25,33 +25,26 @@ func main() {
2525
//retrieveBatch(ctx, client, batchID)
2626
}
2727

28-
func createBatch(ctx context.Context, client *openai.Client) (openai.BatchResponse, error) {
29-
req := openai.CreateBatchWithUploadFileRequest{
30-
Endpoint: openai.BatchEndpointChatCompletions,
31-
}
32-
comments := []string{
33-
"it's a good bike but if you have a problem after the sale they either do not respond to you or the parts are not available",
34-
"I ordered 2 Mars 2.0.A blue and an Orange.Blue came first and had shipping damage to the seat post.It came with a flip seat.The Orange came about 10 days later and didnt have a flip seat.I notified customer service about both issues.They shipped a new seat post but it will not fit the blue bike because it is for a non flip seat.I am still waiting for a fix both both of these problems.\nI do not like the fact that the throttle cannot be used without the peddle assist being on.At time I feel the peddle assist is dangerous.You better not try to make a turn with the peddle assist on.",
35-
"This was my first E-bike. Love it so far, it has plenty power and range. I use it for hunting on our land. Works well for me, I am very satisfied.",
36-
"I would definitely recommend this bike. Easy to use. Great battery life, quick delivery!",
37-
"Slight difficulty setting up bike but it’s perfect and love it’s speed and power",
38-
}
39-
prompt := "Please analyze the following product review and extract the mentioned dimensions and reasons.\n\nReview example:\n```\nThese headphones have excellent sound quality, perfect for music lovers. I wear them every day during my commute, and the noise cancellation is great. The customer service is also very good; they patiently solved my issues. The only downside is that wearing them for long periods makes my ears hurt.\n```\n\nExpected JSON output example:\n```json\n{\n \"dimensions\": [\n {\n \"dimension\": \"Usage Scenario\",\n \"value\": \"during commute\",\n \"reason\": \"user wears them every day during commute\"\n },\n {\n \"dimension\": \"Target Audience\",\n \"value\": \"music lovers\",\n \"reason\": \"user is a music lover\"\n },\n {\n \"dimension\": \"Positive Experience\",\n \"value\": \"excellent sound quality\",\n \"reason\": \"user thinks the headphones have excellent sound quality\"\n },\n {\n \"dimension\": \"Positive Experience\",\n \"value\": \"great noise cancellation\",\n \"reason\": \"user thinks the noise cancellation is great\"\n },\n {\n \"dimension\": \"Negative Experience\",\n \"value\": \"ears hurt after long periods\",\n \"reason\": \"user thinks wearing them for long periods makes ears hurt\"\n }\n ]\n}\n```\nPlease analyze accordingly and return the results in JSON format."
40-
41-
for i, comment := range comments {
42-
req.AddChatCompletion(fmt.Sprintf("req-%d", i), openai.ChatCompletionRequest{
43-
Model: openai.GPT4oMini20240718,
44-
ResponseFormat: &openai.ChatCompletionResponseFormat{
45-
Type: openai.ChatCompletionResponseFormatTypeJSONObject,
28+
func createBatchChatCompletion(ctx context.Context, client *openai.Client) (openai.BatchResponse, error) {
29+
var chatCompletions = make([]openai.BatchChatCompletion, 5)
30+
for i := 0; i < 5; i++ {
31+
chatCompletions[i] = openai.BatchChatCompletion{
32+
CustomID: fmt.Sprintf("req-%d", i),
33+
ChatCompletion: openai.ChatCompletionRequest{
34+
Model: openai.GPT4oMini,
35+
Messages: []openai.ChatCompletionMessage{
36+
{
37+
Role: openai.ChatMessageRoleUser,
38+
Content: fmt.Sprintf("What is the square of %d?", i+1),
39+
},
40+
},
4641
},
47-
Messages: []openai.ChatCompletionMessage{
48-
{Role: openai.ChatMessageRoleSystem, Content: prompt},
49-
{Role: openai.ChatMessageRoleUser, Content: comment},
50-
},
51-
MaxTokens: 2000,
52-
})
42+
}
5343
}
54-
return client.CreateBatchWithUploadFile(ctx, req)
44+
45+
return client.CreateBatchWithChatCompletions(ctx, openai.CreateBatchWithChatCompletionsRequest{
46+
ChatCompletions: chatCompletions,
47+
})
5548
}
5649

5750
func retrieveBatch(ctx context.Context, client *openai.Client, batchID string) {

0 commit comments

Comments
 (0)