kind_openai_schema

Trait OpenAISchema

Source
pub trait OpenAISchema: for<'de> Deserialize<'de> {
    // Required method
    fn openai_schema() -> GeneratedOpenAISchema;
}
Expand description

Any type that can be used as a structured chat completion.

Docstrings on the top level of a type will automatically be consumed and provided to the schema, as well as any docstrings on fields of said struct.

Additionally, serde(skip) and serde(rename) on fields works perfectly fine.

For example:

#[derive(Deserialize, OpenAISchema)]
/// Hello friends
struct SuperComplexSchema {
   // The first one.
   optional_string: Option<String>,
   #[serde(rename = "not_so_regular_string")]
   regular_string: String,
   #[serde(skip)]
   regular_string_2: String,
   int: i32,
   basic_enum: BasicEnum,
}

#[derive(Deserialize, OpenAISchema)]
/// A basic enum.
enum BasicEnum {
   #[serde(rename = "variant1")]
   Variant1,
   #[serde(skip)]
   Variant4,
   Variant2,
}

Will produce the following schema:

{
  "name": "SuperComplexSchema",
  "description": "Hello friends",
  "strict": true,
  "schema": {
    "type": "object",
    "additionalProperties": false,
    "properties": {
      "optional_string": {
        "description": "The first one.",
        "type": ["string", "null"]
      },
      "not_so_regular_string": { "type": "string" },
      "int": { "type": "integer" },
      "basic_enum": { "enum": ["variant1", "Variant2"], "type": "string" }
    },
    "required": ["optional_string", "not_so_regular_string", "int", "basic_enum"]
  }
}

OpenAI’s JSON schema implements a stricter and more limited subset of the JSON schema spec to make it easier for the model to interpret. In addition to that, the proc macro implementation is not 100% complete so there are still some things that are supported that we need to implement, too.

As such, there are some rules which must be followed (most of which are caught by compiler errors. If they aren’t, please file an issue!):

  • The derive can be used on both structs and enums, but only structs can be provided to a structured completion; enums must be used as a field in a containing struct.
  • Enums must be unit variants. Enums with int descriminants (for example enum MyEnum { Variant1 = 1, Variant2 = 2 }) are also allowed, but they must be annotated with repr(i32) or similar, and derive Deserialize_repr from serde_repr.
  • Struct fields are allowed to be any of the following types:
    • String
    • All int types, (i32, i64, u32, u64, isize, usize, etc.)
    • f32 and f64
    • bool
    • Any unit enum type which also derives OpenAISchema
    • Vec<T> where T is any of the above types
    • Option<T> where T is any of the above types

Required Methods§

Dyn Compatibility§

This trait is not dyn compatible.

In older versions of Rust, dyn compatibility was called "object safety", so this trait is not object safe.

Implementors§