Module: Raif::Concerns::Llms::OpenAi::JsonSchemaValidation

Extended by:
ActiveSupport::Concern
Included in:
Llms::OpenAiBase, Llms::OpenRouter
Defined in:
app/models/raif/concerns/llms/open_ai/json_schema_validation.rb

Instance Method Summary collapse

Instance Method Details

#validate_json_schema!(schema) ⇒ Object



6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
# File 'app/models/raif/concerns/llms/open_ai/json_schema_validation.rb', line 6

def validate_json_schema!(schema)
  return if schema.blank?

  errors = []

  # Check if schema is present
  if schema.blank?
    errors << "JSON schema must include a 'schema' property"
  else
    # Check root object type
    if schema[:type] != "object" && !schema.key?(:properties)
      errors << "Root schema must be of type 'object' with 'properties'"
    end

    # Check all objects in the schema recursively
    validate_object_properties(schema, errors)

    # Check properties count (max 100 total)
    validate_properties_count(schema, errors)

    # Check nesting depth (max 5 levels)
    validate_nesting_depth(schema, errors)

    # Check for unsupported anyOf at root level
    if schema[:anyOf].present? && schema[:properties].blank?
      errors << "Root objects cannot be of type 'anyOf'"
    end
  end

  # Raise error if any validation issues found
  if errors.any?
    error_message = "Invalid JSON schema for OpenAI structured outputs: #{errors.join("; ")}\nSchema was: #{schema.inspect}"
    raise Raif::Errors::OpenAi::JsonSchemaError, error_message
  else
    true
  end
end