Skip to content

Commit 20016a9

Browse files
committed
Allow recursive schemas
1 parent 73901e6 commit 20016a9

File tree

3 files changed

+26
-2
lines changed

3 files changed

+26
-2
lines changed

README.md

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -262,7 +262,7 @@ end
262262

263263
### Schema Definitions and References
264264

265-
You can define sub-schemas and reference them in other schemas.
265+
You can define sub-schemas and reference them in other schemas, or reference the root schema to generate recursive schemas.
266266

267267
```ruby
268268
class MySchema < RubyLLM::Schema
@@ -281,6 +281,13 @@ class MySchema < RubyLLM::Schema
281281
object :user do
282282
reference :location
283283
end
284+
285+
# Using a reference to the root schema
286+
object :ui_schema do
287+
string :element, enum: ["input", "button"]
288+
string :label
289+
object :sub_schema, reference: :root
290+
end
284291
end
285292
```
286293

lib/ruby_llm/schema/dsl.rb

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -87,7 +87,11 @@ def define(name, &)
8787
end
8888

8989
def reference(schema_name)
90-
{"$ref" => "#/$defs/#{schema_name}"}
90+
if schema_name == :root
91+
{"$ref" => "#"}
92+
else
93+
{"$ref" => "#/$defs/#{schema_name}"}
94+
end
9195
end
9296

9397
# Schema building methods

spec/ruby_llm/schema_spec.rb

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -274,6 +274,19 @@
274274
additionalProperties: false
275275
})
276276
end
277+
278+
it "supports reference to the root schema" do
279+
schema_class.define :ui_element do
280+
string :element_type, enum: ["input", "button"]
281+
string :label
282+
object :sub_schema, reference: :root
283+
end
284+
285+
instance = schema_class.new
286+
json_output = instance.to_json_schema
287+
288+
expect(json_output[:schema][:properties][:ui_schema][:properties][:sub_schema]).to eq({"$ref" => "#"})
289+
end
277290
end
278291

279292
# ===========================================

0 commit comments

Comments
 (0)