Enable OpenAI JSON mode
mainTo ensure OpenAI returns valid JSON (predecessor to Structured Outputs), set the responseFormat to .jsonObject.
Important: When using JSON mode, you must also explicitly instruct the model in the system or user prompt to return JSON only.
import AIProxy
// ... setup openAIService ...
do {
let requestBody = OpenAIChatCompletionRequestBody(
model: "gpt-4o",
messages: [
.system(content: .text("Return valid JSON only")),
.user(content: .text("Return alice and bob in a list of names"))
],
responseFormat: .jsonObject
)
let response = try await openAIService.chatCompletionRequest(body: requestBody)
print(response.choices.first?.message.content ?? "")
} catch {
// ... handle error ...
}