@@ -4,6 +4,7 @@ package openai_test
4
4
5
5
import (
6
6
"context"
7
+ "encoding/json"
7
8
"errors"
8
9
"io"
9
10
"os"
@@ -178,3 +179,63 @@ func TestAPIError(t *testing.T) {
178
179
t .Fatal ("Empty error message occurred" )
179
180
}
180
181
}
182
+
183
+ func TestChatCompletionResponseFormat_JSONSchema (t * testing.T ) {
184
+ apiToken := os .Getenv ("OPENAI_TOKEN" )
185
+ if apiToken == "" {
186
+ t .Skip ("Skipping testing against production OpenAI API. Set OPENAI_TOKEN environment variable to enable it." )
187
+ }
188
+
189
+ var err error
190
+ c := openai .NewClient (apiToken )
191
+ ctx := context .Background ()
192
+
193
+ resp , err := c .CreateChatCompletion (
194
+ ctx ,
195
+ openai.ChatCompletionRequest {
196
+ Model : openai .GPT4oMini ,
197
+ Messages : []openai.ChatCompletionMessage {
198
+ {
199
+ Role : openai .ChatMessageRoleSystem ,
200
+ Content : "Please enter a string, and we will convert it into the following naming conventions:" +
201
+ "1. PascalCase: Each word starts with an uppercase letter, with no spaces or separators." +
202
+ "2. CamelCase: The first word starts with a lowercase letter, " +
203
+ "and subsequent words start with an uppercase letter, with no spaces or separators." +
204
+ "3. KebabCase: All letters are lowercase, with words separated by hyphens `-`." +
205
+ "4. SnakeCase: All letters are lowercase, with words separated by underscores `_`." ,
206
+ },
207
+ {
208
+ Role : openai .ChatMessageRoleUser ,
209
+ Content : "Hello World" ,
210
+ },
211
+ },
212
+ ResponseFormat : & openai.ChatCompletionResponseFormat {
213
+ Type : openai .ChatCompletionResponseFormatTypeJSONSchema ,
214
+ JSONSchema : openai.ChatCompletionResponseFormatJSONSchema {
215
+ Name : "cases" ,
216
+ Schema : jsonschema.Definition {
217
+ Type : jsonschema .Object ,
218
+ Properties : map [string ]jsonschema.Definition {
219
+ "PascalCase" : jsonschema.Definition {Type : jsonschema .String },
220
+ "CamelCase" : jsonschema.Definition {Type : jsonschema .String },
221
+ "KebabCase" : jsonschema.Definition {Type : jsonschema .String },
222
+ "SnakeCase" : jsonschema.Definition {Type : jsonschema .String },
223
+ },
224
+ Required : []string {"PascalCase" , "CamelCase" , "KebabCase" , "SnakeCase" },
225
+ AdditionalProperties : false ,
226
+ },
227
+ Strict : true ,
228
+ },
229
+ },
230
+ },
231
+ )
232
+ checks .NoError (t , err , "CreateChatCompletion (use json_schema response) returned error" )
233
+ var result = make (map [string ]string )
234
+ err = json .Unmarshal ([]byte (resp .Choices [0 ].Message .Content ), & result )
235
+ checks .NoError (t , err , "CreateChatCompletion (use json_schema response) unmarshal error" )
236
+ for _ , key := range []string {"PascalCase" , "CamelCase" , "KebabCase" , "SnakeCase" } {
237
+ if _ , ok := result [key ]; ! ok {
238
+ t .Errorf ("key:%s does not exist." , key )
239
+ }
240
+ }
241
+ }
0 commit comments