ruby-on-dspy 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (118) hide show
  1. checksums.yaml +7 -0
  2. data/CHANGELOG.md +112 -0
  3. data/LICENSE +21 -0
  4. data/README.md +442 -0
  5. data/exe/ruby-on-dspy +7 -0
  6. data/lib/dspy_rb/cli.rb +83 -0
  7. data/lib/dspy_rb/clients/dummy_lm.rb +81 -0
  8. data/lib/dspy_rb/clients/lm.rb +44 -0
  9. data/lib/dspy_rb/datasets/data_loader.rb +74 -0
  10. data/lib/dspy_rb/datasets/dataset.rb +37 -0
  11. data/lib/dspy_rb/datasets/python_random.rb +38 -0
  12. data/lib/dspy_rb/errors.rb +135 -0
  13. data/lib/dspy_rb/evaluate/evaluate.rb +53 -0
  14. data/lib/dspy_rb/evaluate/metric.rb +61 -0
  15. data/lib/dspy_rb/execution/around.rb +63 -0
  16. data/lib/dspy_rb/execution/collector.rb +61 -0
  17. data/lib/dspy_rb/execution/context.rb +160 -0
  18. data/lib/dspy_rb/execution/evaluation.rb +90 -0
  19. data/lib/dspy_rb/execution/optimization.rb +71 -0
  20. data/lib/dspy_rb/execution/program.rb +126 -0
  21. data/lib/dspy_rb/execution/rows.rb +41 -0
  22. data/lib/dspy_rb/execution/scorer.rb +68 -0
  23. data/lib/dspy_rb/execution/step.rb +116 -0
  24. data/lib/dspy_rb/execution/toolbox.rb +28 -0
  25. data/lib/dspy_rb/predict/chain_of_thought.rb +22 -0
  26. data/lib/dspy_rb/predict/predict.rb +101 -0
  27. data/lib/dspy_rb/predict/react.rb +80 -0
  28. data/lib/dspy_rb/primitives/module.rb +105 -0
  29. data/lib/dspy_rb/primitives/parts.rb +121 -0
  30. data/lib/dspy_rb/runtime/channel/callback.rb +105 -0
  31. data/lib/dspy_rb/runtime/channel/ending.rb +35 -0
  32. data/lib/dspy_rb/runtime/channel/exchange.rb +176 -0
  33. data/lib/dspy_rb/runtime/channel/gate.rb +74 -0
  34. data/lib/dspy_rb/runtime/channel/listener.rb +125 -0
  35. data/lib/dspy_rb/runtime/channel/meter.rb +46 -0
  36. data/lib/dspy_rb/runtime/channel/reporter.rb +68 -0
  37. data/lib/dspy_rb/runtime/channel/settler.rb +69 -0
  38. data/lib/dspy_rb/runtime/channel/traffic.rb +121 -0
  39. data/lib/dspy_rb/runtime/channel/watchdog.rb +36 -0
  40. data/lib/dspy_rb/runtime/channel/writer.rb +77 -0
  41. data/lib/dspy_rb/runtime/channel.rb +145 -0
  42. data/lib/dspy_rb/runtime/child.rb +48 -0
  43. data/lib/dspy_rb/runtime/python.rb +43 -0
  44. data/lib/dspy_rb/runtime/registry.rb +48 -0
  45. data/lib/dspy_rb/runtime/startup.rb +53 -0
  46. data/lib/dspy_rb/secrets.rb +25 -0
  47. data/lib/dspy_rb/setup/environment.rb +120 -0
  48. data/lib/dspy_rb/setup/stale.rb +102 -0
  49. data/lib/dspy_rb/setup/uv.rb +122 -0
  50. data/lib/dspy_rb/signatures/signature.rb +100 -0
  51. data/lib/dspy_rb/signatures/types.rb +44 -0
  52. data/lib/dspy_rb/source.rb +64 -0
  53. data/lib/dspy_rb/teleprompt/bootstrap_few_shot.rb +9 -0
  54. data/lib/dspy_rb/teleprompt/bootstrap_few_shot_with_optuna.rb +9 -0
  55. data/lib/dspy_rb/teleprompt/bootstrap_few_shot_with_random_search.rb +9 -0
  56. data/lib/dspy_rb/teleprompt/gepa.rb +9 -0
  57. data/lib/dspy_rb/teleprompt/labeled_few_shot.rb +14 -0
  58. data/lib/dspy_rb/teleprompt/mipro_v2.rb +16 -0
  59. data/lib/dspy_rb/teleprompt/optimizer.rb +127 -0
  60. data/lib/dspy_rb/teleprompt/simba.rb +16 -0
  61. data/lib/dspy_rb/tool.rb +108 -0
  62. data/lib/dspy_rb/values/check.rb +14 -0
  63. data/lib/dspy_rb/values/context.rb +46 -0
  64. data/lib/dspy_rb/values/dataset.rb +55 -0
  65. data/lib/dspy_rb/values/dict.rb +17 -0
  66. data/lib/dspy_rb/values/env.rb +23 -0
  67. data/lib/dspy_rb/values/evaluation_result.rb +31 -0
  68. data/lib/dspy_rb/values/example.rb +134 -0
  69. data/lib/dspy_rb/values/fault.rb +15 -0
  70. data/lib/dspy_rb/values/history.rb +13 -0
  71. data/lib/dspy_rb/values/list.rb +16 -0
  72. data/lib/dspy_rb/values/literal.rb +27 -0
  73. data/lib/dspy_rb/values/loss.rb +12 -0
  74. data/lib/dspy_rb/values/optional.rb +16 -0
  75. data/lib/dspy_rb/values/prediction.rb +58 -0
  76. data/lib/dspy_rb/values/reasoning.rb +13 -0
  77. data/lib/dspy_rb/values/spend.rb +27 -0
  78. data/lib/dspy_rb/values/types.rb +164 -0
  79. data/lib/dspy_rb/version.rb +11 -0
  80. data/lib/dspy_rb/wire/departure.rb +100 -0
  81. data/lib/dspy_rb/wire/descriptions.rb +220 -0
  82. data/lib/dspy_rb/wire/facts.rb +79 -0
  83. data/lib/dspy_rb/wire/in_flight.rb +128 -0
  84. data/lib/dspy_rb/wire/json.rb +76 -0
  85. data/lib/dspy_rb/wire/optimizers.rb +240 -0
  86. data/lib/dspy_rb/wire/records.rb +44 -0
  87. data/lib/dspy_rb/wire/replies.rb +188 -0
  88. data/lib/dspy_rb/wire/requests.rb +214 -0
  89. data/lib/dspy_rb/wire/shape.rb +25 -0
  90. data/lib/dspy_rb/wire/types.rb +23 -0
  91. data/lib/dspy_rb/wire.rb +34 -0
  92. data/lib/dspy_rb.rb +191 -0
  93. data/lib/ruby-on-dspy.rb +4 -0
  94. data/python/dspy_rb/__init__.py +1 -0
  95. data/python/dspy_rb/__main__.py +76 -0
  96. data/python/dspy_rb/server/__init__.py +1 -0
  97. data/python/dspy_rb/server/build.py +281 -0
  98. data/python/dspy_rb/server/calls.py +215 -0
  99. data/python/dspy_rb/server/conversion.py +180 -0
  100. data/python/dspy_rb/server/data.py +169 -0
  101. data/python/dspy_rb/server/evaluation.py +107 -0
  102. data/python/dspy_rb/server/facts.py +357 -0
  103. data/python/dspy_rb/server/optimization.py +98 -0
  104. data/python/dspy_rb/server/pulse.py +68 -0
  105. data/python/dspy_rb/server/ruby.py +206 -0
  106. data/python/dspy_rb/server/serve.py +369 -0
  107. data/python/dspy_rb/server/standins.py +364 -0
  108. data/python/dspy_rb/server/state.py +104 -0
  109. data/python/dspy_rb/server/traffic.py +93 -0
  110. data/python/dspy_rb/values.py +51 -0
  111. data/python/dspy_rb/wire/__init__.py +1 -0
  112. data/python/dspy_rb/wire/channel.py +107 -0
  113. data/python/dspy_rb/wire/lines.py +269 -0
  114. data/python/dspy_rb/wire/shapes.py +1220 -0
  115. data/python/dspy_rb/wire/wire.json +4592 -0
  116. data/python/pyproject.toml +86 -0
  117. data/python/uv.lock +1576 -0
  118. metadata +230 -0
@@ -0,0 +1,58 @@
1
+ # frozen_string_literal: true
2
+
3
+ module DSPyRb
4
+ module Values
5
+ # A predictor's or a program's outputs as readers, with what its model calls spent.
6
+ class Prediction < Dry::Struct
7
+ schema schema.strict
8
+
9
+ attribute(:values, Wire::Types::Strict::Hash.constructor { |values| outputs(values) })
10
+ attribute :spend, Spend
11
+
12
+ # DSPy's Prediction(**values), as Prediction[answer: "Paris"].
13
+ def self.[](**values)
14
+ of(values)
15
+ end
16
+
17
+ # Outputs by name, with what was spent for them.
18
+ def self.of(values, spend = Spend.new)
19
+ new(values:, spend:)
20
+ end
21
+
22
+ # Its outputs by name, none hidden by its readers, what it owns frozen and any other object kept as given.
23
+ def self.outputs(values)
24
+ Types.frozen(Types.shown(Wire::Json.keyed(values), Prediction, "an output"))
25
+ end
26
+
27
+ private_class_method :outputs
28
+
29
+ def with_spend(spend)
30
+ raise Error, "a Prediction's spend is a DSPyRb::Spend, not #{Error.class_of(spend)}" unless spend.is_a?(Spend)
31
+
32
+ new(spend:)
33
+ end
34
+
35
+ # DSPy's pred["answer"].
36
+ def [](name)
37
+ values.fetch(name.to_sym)
38
+ end
39
+
40
+ def to_h
41
+ values
42
+ end
43
+
44
+ # Dry::Struct's own to_hash reads the struct's attributes through [].
45
+ alias to_hash to_h
46
+
47
+ def respond_to_missing?(name, include_private = false)
48
+ values.key?(name) || super
49
+ end
50
+
51
+ def method_missing(name, *arguments)
52
+ return values[name] if arguments.empty? && values.key?(name)
53
+
54
+ super
55
+ end
56
+ end
57
+ end
58
+ end
@@ -0,0 +1,13 @@
1
+ # frozen_string_literal: true
2
+
3
+ module DSPyRb
4
+ module Values
5
+ # A ChainOfThought's reasoning as text, which goes back to DSPy as its Reasoning (predict/chain_of_thought.py:46).
6
+ class Reasoning < ::String
7
+ # YAML writes it plain, as JSON does, so YAML.safe_load reads it back.
8
+ def encode_with(coder)
9
+ coder.represent_object(nil, to_s)
10
+ end
11
+ end
12
+ end
13
+ end
@@ -0,0 +1,27 @@
1
+ # frozen_string_literal: true
2
+
3
+ module DSPyRb
4
+ module Values
5
+ # What model calls were spent: those that arrived, those Python could not record, and those running at the reply.
6
+ class Spend < Dry::Struct
7
+ schema schema.strict
8
+
9
+ # Its type checks its default with it, so it comes first.
10
+ def self.frozen(calls)
11
+ Ractor.make_shareable(calls.map(&Wire::Call))
12
+ end
13
+
14
+ # Frozen, so a prediction's or an error's spend stays as it was.
15
+ attribute :calls, Wire::Types::Strict::Array.constructor { |calls| Spend.frozen(calls) }.default([].freeze)
16
+ attribute :unrecorded, Wire::UNRECORDED
17
+ attribute :running, Wire::RUNNING
18
+
19
+ # Two spends as one, as a program's sums its predictors'.
20
+ def +(other)
21
+ unrecorded = self.unrecorded + other.unrecorded
22
+
23
+ Spend.new(calls: calls + other.calls, unrecorded:, running: running + other.running)
24
+ end
25
+ end
26
+ end
27
+ end
@@ -0,0 +1,164 @@
1
+ # frozen_string_literal: true
2
+
3
+ module DSPyRb
4
+ module Values
5
+ # The types that name the gem's values, for each place that takes one, each check made whatever builds the value.
6
+ module Types
7
+ # Examples, as demos and a devset are given.
8
+ Examples = Wire::Types::Strict::Array.constructor { |items| Types.examples(items) }
9
+
10
+ # One of DSPy's metrics or its description, a Ruby one (anything that takes `call`), or none.
11
+ Metric = Wire::Types::Any.constructor { |given| Types.metric(given) }
12
+
13
+ # The inputs DSPy takes from a call as its own options (dspy/predict/predict.py:154-160).
14
+ RESERVED = %w[config demos lm signature new_signature].freeze
15
+
16
+ # ReAct's two more (dspy/predict/react.py:140-141); a Predict's history is an input like any other.
17
+ REACT_RESERVED = [*RESERVED, "max_iters", "history"].freeze
18
+
19
+ # DSPy's own types a value crosses as, by name, each held in Ruby as a class of its own.
20
+ DSPY_TYPES = { "Reasoning" => Reasoning, "History" => History }.freeze
21
+
22
+ # DSPy's custom-type markers (dspy/adapters/types/base_type.py:15-16), which DSPy reserves for its own types.
23
+ MARKERS = %w[<<CUSTOM-TYPE-START-IDENTIFIER>> <<CUSTOM-TYPE-END-IDENTIFIER>>].freeze
24
+
25
+ class << self
26
+ # Raised by name and kind alone, never quoting what was given.
27
+ def examples(items)
28
+ unless items.is_a?(::Array)
29
+ raise Error, "examples come as an Array of DSPyRb::Example, not #{Error.class_of(items)}"
30
+ end
31
+
32
+ stray = items.index { !_1.is_a?(Example) }
33
+
34
+ return items unless stray
35
+
36
+ raise Error, "examples come as an Array of DSPyRb::Example: item #{stray} is #{Error.class_of(items[stray])}"
37
+ end
38
+
39
+ # Any other object refused by its class alone.
40
+ def metric(given)
41
+ return given if given.nil? || given.is_a?(Wire::Metric) || given.respond_to?(:call)
42
+
43
+ raise Error, "a metric takes call: #{Error.class_of(given)} does not"
44
+ end
45
+
46
+ # Each field refused, by name alone, when a reader of `owner` would hide it; the caller gives the remedy.
47
+ def shown(fields, owner, noun, remedy: "name it otherwise")
48
+ fields.each_key do |name|
49
+ next unless owner.public_method_defined?(name)
50
+
51
+ reader = "DSPyRb::#{owner.name.split("::").last}##{name}"
52
+
53
+ raise Error, "#{noun} named #{name} would be hidden by #{reader}: #{remedy}"
54
+ end
55
+ end
56
+
57
+ # The first of `inputs` a predictor of `kind` has DSPy take as its own, refused at `place` before it is sent.
58
+ def refuse_reserved(inputs, place, kind = nil)
59
+ refuse_marked(inputs, "#{place}'s input")
60
+ refuse_predicted(inputs, place)
61
+
62
+ name = inputs.keys.map(&:to_s).find { (kind == "react" ? REACT_RESERVED : RESERVED).include?(_1) }
63
+
64
+ return unless name
65
+
66
+ settings = " for a call's LM settings; for one call, give them to a copy of the LM: " \
67
+ "DSPyRb.context(lm: DSPyRb.lm.copy(temperature: 1.0)) { ... }"
68
+
69
+ raise Error, "#{place} takes no input named #{name}: DSPy reserves that name#{settings if name == "config"}"
70
+ end
71
+
72
+ # Hashes, arrays and strings copied and frozen through; any other object kept by reference, as it was given.
73
+ def frozen(value)
74
+ case value
75
+ when History then History[frozen(value.to_h)].freeze
76
+ when ::Hash then value.to_h { |key, item| [frozen(key), frozen(item)] }.freeze
77
+ when ::Array then value.map { frozen(_1) }.freeze
78
+ when ::String then value.frozen? ? value : value.dup.freeze
79
+ else value
80
+ end
81
+ end
82
+
83
+ # A value as it goes back to DSPy: a Prediction as its outputs, naming where they hold DSPy's types.
84
+ def returned(value, place)
85
+ refuse_marked(value, place)
86
+ value.is_a?(Prediction) ? { prediction: value.to_h, typed: typed(value.to_h) }.compact : { value: }
87
+ end
88
+
89
+ # `value`, refused at `place` alone when its text holds DSPy's markers, which the refusal never quotes.
90
+ def refuse_marked(value, place)
91
+ return value unless marked?(value)
92
+
93
+ raise Error, marked(place)
94
+ end
95
+
96
+ def marked(place)
97
+ "#{place} holds DSPy's custom-type markers, which DSPy reserves for its own types: " \
98
+ "remove the markers from the text"
99
+ end
100
+
101
+ # Text in an encoding ASCII can't be found in is left to Wire::Json, which refuses it.
102
+ def marked?(value)
103
+ case value
104
+ when ::String, ::Symbol then value.encoding.ascii_compatible? && MARKERS.any? { value.to_s.include?(_1) }
105
+ when ::Hash, ::Array then value.to_a.any? { marked?(_1) }
106
+ when Dry::Struct then marked?(value.to_h)
107
+ else false
108
+ end
109
+ end
110
+
111
+ # Where `value` holds one of DSPy's own types, each by its path of keys and indexes as JSON carries them.
112
+ def typed(value)
113
+ found = paths(value)
114
+
115
+ found unless found.empty?
116
+ end
117
+
118
+ # `value` with what each of `types` names held as that type again, every Hash and Array on its path copied.
119
+ def retyped(value, types)
120
+ types.to_a.reduce(value) { |held, each| holding(held, each.path, DSPY_TYPES.fetch(each.type)) }
121
+ end
122
+
123
+ private
124
+
125
+ def paths(value, path = [])
126
+ type = DSPY_TYPES.key(value.class)
127
+
128
+ return [Wire::Typed.new(path:, type:)] if type
129
+
130
+ case value
131
+ when ::Hash then value.flat_map { |key, item| paths(item, [*path, key.to_s]) }
132
+ when ::Array then value.each_with_index.flat_map { |item, index| paths(item, [*path, index]) }
133
+ else []
134
+ end
135
+ end
136
+
137
+ # Both types' own replace takes the item's text or pairs, keeping its encoding.
138
+ def holding(value, path, type)
139
+ return type.new.replace(value) if path.empty?
140
+
141
+ key, *rest = path
142
+
143
+ case value
144
+ when ::Hash then value.to_h { |name, item| [name, name.to_s == key ? holding(item, rest, type) : item] }
145
+ else value.each_with_index.map { |item, index| index == key ? holding(item, rest, type) : item }
146
+ end
147
+ end
148
+
149
+ def refuse_predicted(inputs, place)
150
+ return unless inputs.any? { |name, value| name.to_s == "prediction" && predicted?(value) }
151
+
152
+ raise Error, "#{place} takes no prediction of type content: DSPy would take it as predicted-outputs settings"
153
+ end
154
+
155
+ # A dict of predicted outputs, which DSPy moves into the call's settings (dspy/predict/predict.py:186-195).
156
+ def predicted?(value)
157
+ shaped = value.is_a?(::Hash) ? value.transform_keys(&:to_s) : {}
158
+
159
+ shaped["type"] == "content" && shaped.key?("content")
160
+ end
161
+ end
162
+ end
163
+ end
164
+ end
@@ -0,0 +1,11 @@
1
+ # frozen_string_literal: true
2
+
3
+ module DSPyRb
4
+ VERSION = "0.1.0"
5
+
6
+ # Must match python/pyproject.toml's pin.
7
+ DSPY_VERSION = "3.5.0"
8
+
9
+ # Must match python/pyproject.toml's requires-python.
10
+ PYTHON_VERSION = "3.12"
11
+ end
@@ -0,0 +1,100 @@
1
+ # frozen_string_literal: true
2
+
3
+ module DSPyRb
4
+ module Wire
5
+ # Where a value departs from a type of the wire or a struct of the gem's: a path of keys and indexes, never a value.
6
+ module Departure
7
+ TOP = "its top"
8
+
9
+ class << self
10
+ # Where `value` departs from `type`, or nil when it fits.
11
+ def at(type, value, path = nil)
12
+ return in_shape(type, value, path) if struct?(type) && !value.is_a?(type)
13
+ return in_either(type, value, path) if type.is_a?(Dry::Types::Sum)
14
+ return in_items(type.member, value, path) if type.respond_to?(:member) && value.is_a?(::Array)
15
+
16
+ here(path) unless fits?(type, value)
17
+ end
18
+
19
+ # `value` as `type` takes it; a refusal names `place` and where it departs, never the value.
20
+ def taken(type, value, place)
21
+ # A key that is no name has no path to name it by, so it is refused by its class first.
22
+ Json.keyed(value, place) if struct?(type) && value.is_a?(::Hash)
23
+
24
+ # By `call`, since a struct's own `[]` may be the constructor that asks for this.
25
+ type.call(value)
26
+ rescue Dry::Types::CoercionError
27
+ # No cause: the library's error quotes the value, and Ruby and error trackers print an error's causes.
28
+ raise Error, refusal(type, value, place), cause: nil
29
+ end
30
+
31
+ private
32
+
33
+ def refusal(type, value, place)
34
+ path = at(type, value)
35
+
36
+ return "#{place} cannot take the value given" if path.nil? || path == TOP
37
+ return "#{place} cannot take #{path} as given" unless struct?(type)
38
+
39
+ key = path[/\A[^.\[]+/].to_sym
40
+
41
+ return "#{place} takes no #{key}" unless type.attribute_names.include?(key)
42
+ return "#{place} needs #{key}" unless value.key?(key)
43
+
44
+ "#{place} cannot take #{path} as given"
45
+ end
46
+
47
+ def struct?(type)
48
+ type.is_a?(::Class) && type < Dry::Struct
49
+ end
50
+
51
+ def in_shape(shape, value, path)
52
+ return here(path) unless value.is_a?(::Hash)
53
+
54
+ keys = shape.schema.keys
55
+ unknown = value.keys - keys.map(&:name)
56
+
57
+ return join(path, unknown.first) if unknown.any?
58
+
59
+ keys.lazy.filter_map { in_key(_1, value, join(path, _1.name)) }.first
60
+ end
61
+
62
+ def in_key(key, value, path)
63
+ return at(key.type, value[key.name], path) if value.key?(key.name)
64
+
65
+ path if key.required? && !key.type.default?
66
+ end
67
+
68
+ # The form the value went furthest into is the one it meant.
69
+ def in_either(sum, value, path)
70
+ faults = [sum.left, sum.right].map { at(_1, value, path) }
71
+
72
+ return if faults.include?(nil)
73
+
74
+ deepest = faults.max_by(&:size)
75
+
76
+ deepest.size > path.to_s.size ? deepest : here(path)
77
+ end
78
+
79
+ def in_items(type, items, path)
80
+ items.each_with_index.lazy.filter_map { |item, index| at(type, item, "#{path}[#{index}]") }.first
81
+ end
82
+
83
+ def fits?(type, value)
84
+ type.call(value)
85
+ true
86
+ rescue StandardError
87
+ false
88
+ end
89
+
90
+ def here(path)
91
+ path || TOP
92
+ end
93
+
94
+ def join(path, key)
95
+ [path, key].compact.join(".")
96
+ end
97
+ end
98
+ end
99
+ end
100
+ end
@@ -0,0 +1,220 @@
1
+ # frozen_string_literal: true
2
+
3
+ module DSPyRb
4
+ module Wire
5
+ # A signature's field, with its type and description only when given.
6
+ class Field < Shape
7
+ attribute :name, Types::Name
8
+ attribute :role, Types::Strict::String.enum("input", "output")
9
+ attribute? :type, Types::Name
10
+ attribute? :desc, Types::Text
11
+ end
12
+
13
+ # One argument of a Ruby tool, with its type and description only when given.
14
+ class ToolArg < Shape
15
+ attribute :name, Types::Name
16
+ attribute? :type, Types::Name
17
+ attribute? :desc, Types::Text
18
+ attribute :required, Types::Strict::Bool
19
+
20
+ # Left out for nil, which an argument that is not required defaults to when it declares none.
21
+ attribute? :default, Types::JsonValue
22
+ end
23
+
24
+ # A Ruby tool, for Python's stand-in that DSPy reads as it reads a function.
25
+ class Tool < Shape
26
+ attribute :name, Types::Name
27
+ attribute? :desc, Types::Text
28
+ attribute :args, Types::Strict::Array.of(ToolArg)
29
+ end
30
+
31
+ # A predictor as DSPy builds it.
32
+ class Predictor < Shape
33
+ attribute :kind, Types::Strict::String.enum("predict", "chain_of_thought", "react")
34
+ attribute :fields, Types::Strict::Array.of(Field)
35
+ attribute? :reasoning, Types::Strict::String.enum("written")
36
+ attribute? :instructions, Types::Text
37
+ attribute? :demos, Types::Strict::Array.of(Example)
38
+
39
+ # A ReAct's tools, its turn budget, and the signature's own instructions, which ReAct writes into its text.
40
+ attribute? :tools, Types::Strict::Array.of(Tool)
41
+ attribute? :max_iters, Types::Count
42
+ attribute? :task, Types::Text
43
+
44
+ # Marked by an optimizer, as DSPy marks the program it gives: a compiled module's predictors stay as they are.
45
+ attribute? :compiled, Types::Strict::Bool
46
+
47
+ # A compile's teacher, whose tools' callbacks say so, for Ruby to call the teacher's tools.
48
+ attribute? :teacher, Types::Strict::Bool
49
+ end
50
+
51
+ # One of DSPy's own metrics by its name and DSPy's options for it: DSPyRb::Metric's description.
52
+ class Metric < Shape
53
+ attribute :name,
54
+ Types::Strict::String.enum(
55
+ "answer_exact_match",
56
+ "answer_passage_match",
57
+ "semantic_f1",
58
+ "complete_and_grounded",
59
+ "gsm8k_metric",
60
+ "math_metric"
61
+ )
62
+ attribute? :frac, Types::Number
63
+ attribute? :threshold, Types::Number
64
+ attribute? :decompositional, Types::Strict::Bool
65
+ end
66
+
67
+ # One of DSPy's own datasets (dspy/datasets/) by its class's name in snake case, with the options its class takes.
68
+ class DSPyDataset < Shape
69
+ attribute :name, Types::Strict::String.enum("hot_pot_qa", "gsm8k", "math", "colors")
70
+ attribute? :train_seed, Types::Strict::Integer
71
+ attribute? :train_size, Types::Strict::Integer
72
+ attribute? :eval_seed, Types::Strict::Integer
73
+ attribute? :dev_size, Types::Strict::Integer
74
+ attribute? :test_size, Types::Strict::Integer
75
+ attribute? :input_keys, Types::Strict::Array.of(Types::Name)
76
+ attribute? :only_hard_examples, Types::Strict::Bool
77
+ attribute? :keep_details, Types::Strict::Bool | Types::Text
78
+ attribute? :unofficial_dev, Types::Strict::Bool
79
+ attribute? :sort_by_suffix, Types::Strict::Bool
80
+ attribute? :subset, Types::Name
81
+ end
82
+
83
+ # A dataset DSPy's DataLoader loads through Hugging Face's load_dataset (dspy/datasets/dataloader.py:16-61).
84
+ class HubDataset < Shape
85
+ attribute :dataset_name, Types::Name
86
+ attribute :arguments, Types::Strict::Array.of(Types::JsonValue)
87
+ attribute :options, Types::Values
88
+ attribute? :fields, Types::Strict::Array.of(Types::Name)
89
+ attribute? :input_keys, Types::Strict::Array.of(Types::Name)
90
+ end
91
+
92
+ # A file DSPy's DataLoader reads (dspy/datasets/dataloader.py:63-121), with the fields and input keys it keeps.
93
+ class DataFile < Shape
94
+ attribute :format, Types::Strict::String.enum("csv", "json", "parquet")
95
+ attribute :file_path, Types::Path
96
+ attribute? :fields, Types::Strict::Array.of(Types::Name)
97
+ attribute? :input_keys, Types::Strict::Array.of(Types::Name)
98
+ end
99
+
100
+ # One parameter of a Ruby metric, as Ruby reports it, so Python's stand-in takes what the metric takes.
101
+ class Parameter < Shape
102
+ attribute? :name, Types::Name
103
+ attribute :kind, Types::Strict::String.enum("req", "opt", "rest", "keyreq", "key", "keyrest")
104
+ end
105
+
106
+ # A Ruby metric, by the name DSPy shows for it, and its parameters.
107
+ class RubyMetric < Shape
108
+ attribute :ruby, Types::Name
109
+ attribute :parameters, Types::Strict::Array.of(Parameter)
110
+ end
111
+
112
+ # A predictor of a Ruby program at the path of instance variables it is held at, else the earlier path holding it.
113
+ class Part < Shape
114
+ attribute :path, Types::Name
115
+ attribute? :predictor, Predictor
116
+ attribute? :same, Types::Name
117
+ end
118
+
119
+ # A Ruby program DSPy calls back, by its class's name; for a compile, its parts and the compiled marks it holds.
120
+ class RubyProgram < Shape
121
+ attribute :ruby, Types::Name
122
+ attribute? :parts, Types::Strict::Array.of(Part)
123
+
124
+ # Its own mark, as a predictor's is, apart from the paths of its compiled modules, which any variable may name.
125
+ attribute? :compiled, Types::Strict::Bool
126
+ attribute? :compiled_modules, Types::Strict::Array.of(Types::Name)
127
+
128
+ # A compile's teacher, whose program callbacks say so, for Ruby to call the teacher's forward.
129
+ attribute? :teacher, Types::Strict::Bool
130
+
131
+ # Its Ruby source, which MIPROv2's program-aware proposer reads as it reads a Python program's.
132
+ attribute? :source, Types::Strict::String
133
+ end
134
+
135
+ # A model, DSPy's open option set, and the variable naming its key: DSPyRb::LM's description.
136
+ class LM < Shape
137
+ # No key travels in a request: Python reads it from its own environment.
138
+ REFUSED = "api_key: is refused: set the key in DSPyRb.config.env, under the provider's own variable or the " \
139
+ "one api_key_env: names"
140
+
141
+ # DSPy would send it to the provider as an option of the call.
142
+ NAMED = "api_key_env: is refused here: name the key's variable as the LM is made, in " \
143
+ "DSPyRb::LM[model, api_key_env:]"
144
+
145
+ # Its model, option set and DSPy's connection settings, which a copy would take (base_lm.py:351-366, lm.py:49-57).
146
+ KEPT = %i[
147
+ model
148
+ kwargs
149
+ api_base
150
+ base_url
151
+ custom_llm_provider
152
+ api_version
153
+ organization
154
+ project
155
+ headers
156
+ extra_headers
157
+ extra_query
158
+ azure_ad_token_provider
159
+ ].freeze
160
+
161
+ # Refused here, never repeating the key; the constraint carries api_key's rule into wire.json for Python.
162
+ Options = Types::Values.constructor { |options| options.key?(:api_key) ? raise(Error, REFUSED) : options }
163
+ .constructor { |options| options.key?(:api_key_env) ? raise(Error, NAMED) : options }
164
+ .constrained(excludes: :api_key)
165
+
166
+ # One copy's options, refused as an LM's are, and any that would change where its calls go or their key.
167
+ Copy = Types::Values.constructor { |options| Options[kept(options)] }.constrained(excludes: :api_key)
168
+
169
+ attribute :model, Types::Name
170
+ attribute :options, Options
171
+ attribute? :api_key_env, Types::Name
172
+
173
+ # The copies made from it in order, each made in Python by DSPy's own lm.copy(**options).
174
+ attribute? :copies, Types::Strict::Array.of(Copy)
175
+
176
+ # `options` as given; one of KEPT is refused by its name, never its value.
177
+ def self.kept(options)
178
+ moved = KEPT.find { options.key?(_1) }
179
+
180
+ return options unless moved
181
+
182
+ remedy = "for another model, host or provider, make a new DSPyRb::LM"
183
+
184
+ raise Error, "#{moved}: is refused in a copy, which keeps its LM's model, host and key: #{remedy}"
185
+ end
186
+
187
+ private_class_method :kept
188
+ end
189
+
190
+ # DSPy's chat, JSON or XML adapter with its options.
191
+ class Adapter < Shape
192
+ attribute :kind, Types::Strict::String.enum("chat", "json", "xml")
193
+ attribute :options, Types::Values
194
+
195
+ def self.chat(**options)
196
+ new(kind: "chat", options:)
197
+ end
198
+
199
+ def self.json(**options)
200
+ new(kind: "json", options:)
201
+ end
202
+
203
+ def self.xml(**options)
204
+ new(kind: "xml", options:)
205
+ end
206
+ end
207
+
208
+ # DSPy's own test model's answers and options (dspy/utils/dummies.py:16): DSPyRb::DummyLM's description.
209
+ class DummyLM < Shape
210
+ # Each text a String, though Ruby's reader gives a Symbol for a key Python writes back.
211
+ Text = Types::Text.constructor(->(text) { text.is_a?(::Symbol) ? text.to_s : text })
212
+
213
+ attribute :answers, Types::Strict::Array.of(Types::Values) | Types::Strict::Hash.map(Text, Types::Values)
214
+ attribute? :follow_examples, Types::Strict::Bool
215
+ attribute? :reasoning, Types::Strict::Bool
216
+ attribute? :adapter, Adapter
217
+ attribute? :copies, Types::Strict::Array.of(LM::Copy)
218
+ end
219
+ end
220
+ end
@@ -0,0 +1,79 @@
1
+ # frozen_string_literal: true
2
+
3
+ module DSPyRb
4
+ module Wire
5
+ # One message a call sent or received.
6
+ class Message < Shape
7
+ attribute :role, Types::Name
8
+ attribute :text, Types::Text
9
+ attribute? :thinking, Types::Text
10
+ end
11
+
12
+ # DSPy's counts: prompt tokens include cache reads and writes, completion tokens reasoning.
13
+ class Usage < Shape
14
+ attribute :prompt_tokens, Types::Count
15
+ attribute :completion_tokens, Types::Count
16
+ attribute :cached_tokens, Types::Count
17
+ attribute :cache_creation_tokens, Types::Count
18
+ attribute :reasoning_tokens, Types::Count
19
+ end
20
+
21
+ # What a call was sent with.
22
+ class Settings < Shape
23
+ attribute? :temperature, Types::Number
24
+ attribute? :max_tokens, Types::Count
25
+ attribute? :reasoning_effort, Types::Name
26
+ attribute? :thinking_budget, Types::Count
27
+ end
28
+
29
+ # A Python exception, its message scrubbed.
30
+ class Failure < Shape
31
+ attribute :ancestry, Types::Strict::Array.of(Types::Name)
32
+ attribute :message, Types::Text
33
+ attribute :retryable, Types::Strict::Bool
34
+ end
35
+
36
+ # DSPyRb::PendingCall: one model call as its gates see it, before it is sent.
37
+ class PendingCall < Shape
38
+ # The id its Call carries once it is sent.
39
+ attribute :id, Types::Name
40
+ attribute? :component, Types::Name
41
+ attribute :model, Types::Name
42
+ attribute :messages, Types::Strict::Array.of(Message)
43
+ attribute :settings, Settings
44
+
45
+ # The candidates DSPy asks for, each a request of its own (clients/execution.py:65-71).
46
+ attribute :n, Types::Count
47
+
48
+ # The call it would have been, for its listeners once it is known never to go: unsent, at no cost.
49
+ def unsent
50
+ Call.new(**attributes.except(:n), cache_hit: false, duration_ms: 0, outcome: "unsent", cost: 0.0)
51
+ end
52
+ end
53
+
54
+ # DSPyRb::Call: one model call, as it completed or failed, or one its gates saw that was never sent.
55
+ class Call < Shape
56
+ # A UUID made as the call reaches DSPy's send point, unique across processes and restarts.
57
+ attribute :id, Types::Name
58
+ attribute? :component, Types::Name
59
+
60
+ # Byte for byte: what identifies the text a tuner sent; absent for a direct call, which no predictor makes.
61
+ attribute? :instruction, Types::Text
62
+ attribute :model, Types::Name
63
+ attribute? :response_model, Types::Name
64
+ attribute :messages, Types::Strict::Array.of(Message)
65
+ attribute? :usage, Usage
66
+ attribute :settings, Settings
67
+ attribute :cache_hit, Types::Strict::Bool
68
+ attribute :duration_ms, Types::Count
69
+ attribute :outcome, Types::Strict::String.enum("completed", "failed", "unsent")
70
+ attribute? :error, Failure
71
+
72
+ # DSPy's figure in US dollars, as its history holds it (dspy/clients/execution.py:562); absent with no price.
73
+ attribute? :cost, Types::Number
74
+
75
+ # Where that figure comes from, or why there is none, as DSPy's history holds it (clients/execution.py:565-566).
76
+ attribute? :cost_details, Types::Values
77
+ end
78
+ end
79
+ end