Module: DSPy::TypeSystem::SorbetJsonSchema

Extended by:
T::Helpers, T::Sig
Defined in:
lib/dspy/type_system/sorbet_json_schema.rb

Overview

Unified module for converting Sorbet types to JSON Schema Extracted from Signature class to ensure consistency across Tools, Toolsets, and Signatures

Class Method Summary collapse

Class Method Details

.generate_struct_schema(struct_class) ⇒ Object



209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
# File 'lib/dspy/type_system/sorbet_json_schema.rb', line 209

def self.generate_struct_schema(struct_class)
  return { type: "string", description: "Struct (schema introspection not available)" } unless struct_class.respond_to?(:props)

  properties = {}
  required = []

  # Check if struct already has a _type field
  if struct_class.props.key?(:_type)
    raise DSPy::ValidationError, "_type field conflict: #{struct_class.name} already has a _type field defined. " \
                                 "DSPy uses _type for automatic type detection in union types."
  end

  # Add automatic _type field for type detection
  properties[:_type] = {
    type: "string",
    const: struct_class.name.split('::').last  # Use the simple class name
  }
  required << "_type"

  struct_class.props.each do |prop_name, prop_info|
    prop_type = prop_info[:type_object] || prop_info[:type]
    properties[prop_name] = self.type_to_json_schema(prop_type)
    
    # A field is required if it's not fully optional
    # fully_optional is true for nilable prop fields
    # immutable const fields are required unless nilable
    unless prop_info[:fully_optional]
      required << prop_name.to_s
    end
  end

  {
    type: "object",
    properties: properties,
    required: required,
    description: "#{struct_class.name} struct"
  }
end

.type_to_json_schema(type) ⇒ Object



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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
# File 'lib/dspy/type_system/sorbet_json_schema.rb', line 16

def self.type_to_json_schema(type)
  # Handle T::Boolean type alias first
  if type == T::Boolean
    return { type: "boolean" }
  end

  # Handle type aliases by resolving to their underlying type
  if type.is_a?(T::Private::Types::TypeAlias)
    return self.type_to_json_schema(type.aliased_type)
  end

  # Handle raw class types first
  if type.is_a?(Class)
    if type < T::Enum
      # Get all enum values
      values = type.values.map(&:serialize)
      { type: "string", enum: values }
    elsif type == String
      { type: "string" }
    elsif type == Integer
      { type: "integer" }
    elsif type == Float
      { type: "number" }
    elsif type == Numeric
      { type: "number" }
    elsif [TrueClass, FalseClass].include?(type)
      { type: "boolean" }
    elsif type < T::Struct
      # Handle custom T::Struct classes by generating nested object schema
      self.generate_struct_schema(type)
    else
      { type: "string" }  # Default fallback
    end
  elsif type.is_a?(T::Types::Simple)
    case type.raw_type.to_s
    when "String"
      { type: "string" }
    when "Integer"
      { type: "integer" }
    when "Float"
      { type: "number" }
    when "Numeric"
      { type: "number" }
    when "TrueClass", "FalseClass"
      { type: "boolean" }
    when "T::Boolean"
      { type: "boolean" }
    else
      # Check if it's an enum
      if type.raw_type < T::Enum
        # Get all enum values
        values = type.raw_type.values.map(&:serialize)
        { type: "string", enum: values }
      elsif type.raw_type < T::Struct
        # Handle custom T::Struct classes
        generate_struct_schema(type.raw_type)
      else
        { type: "string" }  # Default fallback
      end
    end
  elsif type.is_a?(T::Types::TypedArray)
    # Handle arrays properly with nested item type
    {
      type: "array",
      items: self.type_to_json_schema(type.type)
    }
  elsif type.is_a?(T::Types::TypedHash)
    # Handle hashes as objects with additionalProperties
    # TypedHash has keys and values methods to access its key and value types
    key_schema = self.type_to_json_schema(type.keys)
    value_schema = self.type_to_json_schema(type.values)
    
    # Create a more descriptive schema for nested structures
    {
      type: "object",
      propertyNames: key_schema,  # Describe key constraints
      additionalProperties: value_schema,
      # Add a more explicit description of the expected structure
      description: "A mapping where keys are #{key_schema[:type]}s and values are #{value_schema[:description] || value_schema[:type]}s"
    }
  elsif type.is_a?(T::Types::FixedHash)
    # Handle fixed hashes (from type aliases like { "key" => Type })
    properties = {}
    required = []
    
    type.types.each do |key, value_type|
      properties[key] = self.type_to_json_schema(value_type)
      required << key
    end
    
    {
      type: "object",
      properties: properties,
      required: required,
      additionalProperties: false
    }
  elsif type.class.name == "T::Private::Types::SimplePairUnion"
    # Handle T.nilable types (T::Private::Types::SimplePairUnion)
    # This is the actual implementation of T.nilable(SomeType)
    has_nil = type.respond_to?(:types) && type.types.any? do |t| 
      (t.respond_to?(:raw_type) && t.raw_type == NilClass) ||
      (t.respond_to?(:name) && t.name == "NilClass")
    end
    
    if has_nil
      # Find the non-nil type
      non_nil_type = type.types.find do |t|
        !(t.respond_to?(:raw_type) && t.raw_type == NilClass) &&
        !(t.respond_to?(:name) && t.name == "NilClass")
      end
      
      if non_nil_type
        base_schema = self.type_to_json_schema(non_nil_type)
        if base_schema[:type].is_a?(String)
          # Convert single type to array with null
          { type: [base_schema[:type], "null"] }.merge(base_schema.except(:type))
        else
          # For complex schemas, use anyOf to allow null
          { anyOf: [base_schema, { type: "null" }] }
        end
      else
        { type: "string" } # Fallback
      end
    else
      # Not nilable SimplePairUnion - this is a regular T.any() union
      # Generate oneOf schema for all types
      if type.respond_to?(:types) && type.types.length > 1
        {
          oneOf: type.types.map { |t| self.type_to_json_schema(t) },
          description: "Union of multiple types"
        }
      else
        # Single type or fallback
        first_type = type.respond_to?(:types) ? type.types.first : type
        self.type_to_json_schema(first_type)
      end
    end
  elsif type.is_a?(T::Types::Union)
    # Check if this is a nilable type (contains NilClass)
    is_nilable = type.types.any? { |t| t == T::Utils.coerce(NilClass) }
    non_nil_types = type.types.reject { |t| t == T::Utils.coerce(NilClass) }
    
    # Special case: check if we have TrueClass + FalseClass (T.nilable(T::Boolean))
    if non_nil_types.size == 2 && is_nilable
      true_class_type = non_nil_types.find { |t| t.respond_to?(:raw_type) && t.raw_type == TrueClass }
      false_class_type = non_nil_types.find { |t| t.respond_to?(:raw_type) && t.raw_type == FalseClass }
      
      if true_class_type && false_class_type
        # This is T.nilable(T::Boolean) - treat as nilable boolean
        return { type: ["boolean", "null"] }
      end
    end
    
    if non_nil_types.size == 1 && is_nilable
      # This is T.nilable(SomeType) - generate proper schema with null allowed
      base_schema = self.type_to_json_schema(non_nil_types.first)
      if base_schema[:type].is_a?(String)
        # Convert single type to array with null
        { type: [base_schema[:type], "null"] }.merge(base_schema.except(:type))
      else
        # For complex schemas, use anyOf to allow null
        { anyOf: [base_schema, { type: "null" }] }
      end
    elsif non_nil_types.size == 1
      # Non-nilable single type union (shouldn't happen in practice)
      self.type_to_json_schema(non_nil_types.first)
    elsif non_nil_types.size > 1
      # Handle complex unions with oneOf for better JSON schema compliance
      base_schema = {
        oneOf: non_nil_types.map { |t| self.type_to_json_schema(t) },
        description: "Union of multiple types"
      }
      if is_nilable
        # Add null as an option for complex nilable unions
        base_schema[:oneOf] << { type: "null" }
      end
      base_schema
    else
      { type: "string" }  # Fallback for complex unions
    end
  elsif type.is_a?(T::Types::ClassOf)
    # Handle T.class_of() types
    {
      type: "string",
      description: "Class name (T.class_of type)"
    }
  else
    { type: "string" }  # Default fallback
  end
end