You can define schemas by implementing the JSONSchemaConvertible protocol on your Swift types (similar to Pydantic or Zod).
Requirements:
- The type must conform to
JSONSchemaConvertible and provide a static let example: Self property. - All enum types within the provided type must conform to
JSONSchemaEnumConvertible and implement var caseNames: [String] { get } to return an array of all case names.
struct MovieInfo: JSONSchemaConvertible {
let title: String
let director: String
let release: Date
let genres: [MovieGenre]
let cast: [String]
static let example: Self = {
.init(
title: "Earth",
director: "Alexander Dovzhenko",
release: Calendar.current.date(from: DateComponents(year: 1930, month: 4, day: 1))!,
genres: [.drama],
cast: ["Stepan Shkurat", "Semyon Svashenko", "Yuliya Solntseva"]
)
}()
}
enum MovieGenre: String, Codable, JSONSchemaEnumConvertible {
case action, drama, comedy, scifi
var caseNames: [String] { Self.allCases.map { $0.rawValue } }
}
let query = ChatQuery(
messages: [
.system(
.init(content: .textContent("Best Picture winner at the 2011 Oscars"))
)
],
model: .gpt4_o,
responseFormat: .jsonSchema(
.init(
name: "movie-info",
description: nil,
schema: .derivedJsonSchema(MovieInfo.self),
strict: true
)
)
)
let result = try await openAI.chats(query: query)