Struct Schema

Source
pub struct Schema {
    pub name: Option<String>,
    pub schema: Option<JsonItem>,
    /* private fields */
}
Expand description

Complete JSON schema definition with name and structure.

This is the top-level structure for defining JSON schemas that can be used with OpenAI’s structured output features. It combines a schema name with the actual schema definition to create a complete, reusable schema.

§Fields

  • name - A unique identifier for this schema
  • schema - The actual schema definition describing the structure

§Usage with OpenAI API

This structure can be directly serialized and used with OpenAI’s chat completion API to ensure structured responses that conform to the defined schema.

§Example

use openai_tools::structured_output::Schema;

// Create a schema for extracting contact information
let mut contact_schema = Schema::chat_json_schema("contact_info".to_string());

contact_schema.add_property(
    "name".to_string(),
    "string".to_string(),
    Some("Full name of the person".to_string())
);
contact_schema.add_property(
    "email".to_string(),
    "string".to_string(),
    Some("Email address".to_string())
);
contact_schema.add_property(
    "phone".to_string(),
    "string".to_string(),
    Some("Phone number".to_string())
);

// Serialize for API use
let json_string = serde_json::to_string(&contact_schema).unwrap();

Fields§

§name: Option<String>§schema: Option<JsonItem>

Implementations§

Source§

impl Schema

Source

pub fn responses_text_schema() -> Self

Creates a new JsonSchema with the specified name.

This creates an empty object schema that can be populated with properties using the various add_* methods.

§Arguments
  • name - A unique identifier for this schema
§Returns

A new JsonSchema instance with an empty object schema.

§Example
use openai_tools::structured_output::Schema;

let schema = Schema::chat_json_schema("user_profile".to_string());
// Schema is now ready for property addition
Source

pub fn responses_json_schema(name: String) -> Self

Creates a new JsonSchema with the specified name (alternative constructor).

This method is functionally identical to new() but provides an alternative naming convention for schema creation.

§Arguments
  • name - A unique identifier for this schema
§Returns

A new JsonSchema instance with an empty object schema.

Source

pub fn chat_json_schema(name: String) -> Self

Creates a new JsonSchema for chat completions with the specified name.

This method creates a schema specifically designed for use with OpenAI’s chat completion API. Unlike responses_json_schema(), this method doesn’t set a type name, making it suitable for chat-based structured outputs.

§Arguments
  • name - A unique identifier for this schema
§Returns

A new JsonSchema instance with an empty object schema optimized for chat completions.

§Example
use openai_tools::structured_output::Schema;

let mut chat_schema = Schema::chat_json_schema("chat_response".to_string());
chat_schema.add_property(
    "response".to_string(),
    "string".to_string(),
    Some("The AI's response message".to_string())
);
Source

pub fn add_property( &mut self, prop_name: String, type_name: String, description: Option<String>, )

Adds a simple property to the schema.

This method adds a property with a basic type (string, number, boolean, etc.) to the schema. The property is automatically marked as required.

§Arguments
  • prop_name - The name of the property
  • type_name - The JSON type (e.g., “string”, “number”, “boolean”)
  • description - Optional description explaining the property’s purpose
§Example
use openai_tools::structured_output::Schema;

let mut schema = Schema::chat_json_schema("person".to_string());

// Add string property with description
schema.add_property(
    "name".to_string(),
    "string".to_string(),
    Some("The person's full name".to_string())
);

// Add number property without description
schema.add_property(
    "age".to_string(),
    "number".to_string(),
    None
);

// Add boolean property
schema.add_property(
    "is_active".to_string(),
    "boolean".to_string(),
    Some("Whether the person is currently active".to_string())
);
Source

pub fn add_array(&mut self, prop_name: String, items: Vec<(String, String)>)

Adds an array property with string elements to the schema.

This method creates an array property where each element is an object with string properties. All specified properties in the array elements are marked as required.

§Arguments
  • prop_name - The name of the array property
  • items - Vector of (property_name, description) tuples for array elements
§Example
use openai_tools::structured_output::Schema;

let mut schema = Schema::chat_json_schema("user_profile".to_string());

// Add an array of address objects
schema.add_array(
    "addresses".to_string(),
    vec![
        ("street".to_string(), "Street address".to_string()),
        ("city".to_string(), "City name".to_string()),
        ("state".to_string(), "State or province".to_string()),
        ("zip_code".to_string(), "Postal code".to_string()),
    ]
);

// This creates an array where each element must have all four properties
§Note

Currently, this method only supports arrays of objects with string properties. For more complex array structures, you may need to manually construct the schema using JsonItem and ItemType.

Source

pub fn clone(&self) -> Self

Creates a deep clone of this JsonSchema instance.

This method performs a deep copy of the entire schema structure, including all nested properties and their definitions.

§Returns

A new JsonSchema instance that is an exact copy of this one.

§Example
use openai_tools::structured_output::Schema;

let mut original = Schema::chat_json_schema("template".to_string());
original.add_property("id".to_string(), "number".to_string(), None);

let mut copy = original.clone();
copy.add_property("name".to_string(), "string".to_string(), None);

// original still only has "id", copy has both "id" and "name"

Trait Implementations§

Source§

impl Clone for Schema

Source§

fn clone(&self) -> Schema

Returns a duplicate of the value. Read more
1.0.0 · Source§

const fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for Schema

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Default for Schema

Source§

fn default() -> Schema

Returns the “default value” for a type. Read more
Source§

impl<'de> Deserialize<'de> for Schema

Source§

fn deserialize<__D>(__deserializer: __D) -> Result<Self, __D::Error>
where __D: Deserializer<'de>,

Deserialize this value from the given Serde deserializer. Read more
Source§

impl Serialize for Schema

Source§

fn serialize<__S>(&self, __serializer: __S) -> Result<__S::Ok, __S::Error>
where __S: Serializer,

Serialize this value into the given Serde serializer. Read more

Auto Trait Implementations§

§

impl Freeze for Schema

§

impl RefUnwindSafe for Schema

§

impl Send for Schema

§

impl Sync for Schema

§

impl Unpin for Schema

§

impl UnwindSafe for Schema

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self>

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

impl<T> Pointable for T

Source§

const ALIGN: usize

The alignment of pointer.
Source§

type Init = T

The type for initializers.
Source§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
Source§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
Source§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
Source§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
Source§

impl<T> PolicyExt for T
where T: ?Sized,

Source§

fn and<P, B, E>(self, other: P) -> And<T, P>
where T: Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow only if self and other return Action::Follow. Read more
Source§

fn or<P, B, E>(self, other: P) -> Or<T, P>
where T: Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow if either self or other returns Action::Follow. Read more
Source§

impl<R, P> ReadPrimitive<R> for P
where R: Read + ReadEndian<P>, P: Default,

Source§

fn read_from_little_endian(read: &mut R) -> Result<Self, Error>

Read this value from the supplied reader. Same as ReadEndian::read_from_little_endian().
Source§

fn read_from_big_endian(read: &mut R) -> Result<Self, Error>

Read this value from the supplied reader. Same as ReadEndian::read_from_big_endian().
Source§

fn read_from_native_endian(read: &mut R) -> Result<Self, Error>

Read this value from the supplied reader. Same as ReadEndian::read_from_native_endian().
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

impl<T> DeserializeOwned for T
where T: for<'de> Deserialize<'de>,

Source§

impl<T> ErasedDestructor for T
where T: 'static,