Skip to content

Valid OpenAI API Schema is not possible with JSONSchemaDefine because JSONSchemaType doesn't allow union types #141

Open
@TheLexoPlexx

Description

@TheLexoPlexx

Describe the bug

So, this is valid OpenAI-Schema, taken from the docs:

{
  "name": "get_weather",
  "description": "Fetches the weather in the given location",
  "strict": true,
  "parameters": {
      "type": "object",
      "properties": {
          "location": {
              "type": "string",
              "description": "The location to get the weather for"
          },
          "unit": {
              "type": ["string", "null"],
              "description": "The unit to return the temperature in",
              "enum": ["F", "C"]
          }
      },
      "additionalProperties": false,
      "required": [
          "location", "unit"
      ]
  }
}

Source: https://platform.openai.com/docs/guides/structured-outputs/supported-schemas#supported-schemas

Although all fields must be required (and the model will return a value for each parameter), it is possible to emulate an optional parameter by using a union type with null.

But it is disallowed by: JSONSchemaType

Is this intentional? If not, I can create a PR if you like, but it would be a tiny fix afaik.

To Reproduce

  1. Run:
use std::process::exit;

use openai_api_rs::v1::types::Function;

fn main() {
    let sample = r#"
{
    "name": "get_weather",
    "description": "Fetches the weather in the given location",
    "strict": true,
    "parameters": {
        "type": "object",
        "properties": {
            "location": {
                "type": "string",
                "description": "The location to get the weather for"
            },
            "unit": {
                "type": ["string", "null"],
                "description": "The unit to return the temperature in",
                "enum": ["F", "C"]
            }
        },
        "additionalProperties": false,
        "required": [
            "location", "unit"
        ]
    }
}
    "#;

    let parser: Function = serde_json::from_str(&sample).expect("Error");

    dbg!(parser);
}

(I don't know if there's a rust playground that allows crates to be used).

Code snippets

No response

OS

Windows 11 Pro 32H2 22631.4391

Rust version

rustc 1.83.0 (90b35a623 2024-11-26)

Library version

5.2.4

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't working

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions