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,116 @@
1
+ # frozen_string_literal: true
2
+
3
+ module DSPyRb
4
+ module Execution
5
+ # A request made from the context in force, its spend and stop taken by the program collecting it.
6
+ class Step
7
+ extend Dry::Initializer
8
+
9
+ # The predictor making the request, or the one it evaluates, by which a program holding it names it.
10
+ param :program, Wire::Types.Interface(:component_name).optional, default: proc {}, reader: :private
11
+ option :context, default: proc { Context.current }, reader: :private
12
+
13
+ # Whether `model` is a DummyLM of a list, which asks Ruby for each next answer; one by text asks nothing.
14
+ def self.scripted?(model)
15
+ description = model&.description
16
+
17
+ description.is_a?(Wire::DummyLM) && description.answers.is_a?(::Array)
18
+ end
19
+
20
+ # Only a predictor's call needs an LM; with none, an evaluate or a metric runs as in DSPy until it calls a model.
21
+ def call(predictor, inputs, serve: nil)
22
+ Values::Types.refuse_reserved(inputs, "#{program.class.name}#call", predictor.kind)
23
+ raise Error, "no LM: set DSPyRb.config.lm, or pass one to DSPyRb.context" unless own_lm || context.callback
24
+
25
+ typed = Values::Types.typed(inputs)
26
+
27
+ ask(Wire::CallRequest, Wire::Completed, serve:, predictor:, inputs:, typed:) do |reply, spend|
28
+ Values::Prediction.of(Values::Types.retyped(reply.outputs, reply.typed), spend)
29
+ end
30
+ end
31
+
32
+ # A direct call of `model` under the adapter in force, a bad prompt or option refused here, naming `place`.
33
+ def generate(model, prompt, options, place:)
34
+ raise Error, "#{place} takes a prompt of text, not #{Error.class_of(prompt)}" unless prompt.is_a?(::String)
35
+
36
+ prompt = Wire::Json.value(prompt, "#{place}'s prompt")
37
+ options = Wire::Departure.taken(Wire::LM::Options, Wire::Json.values(options, place), place)
38
+
39
+ ask(Wire::Generate, Wire::Generated, model:, prompt:, options:) { |reply, _| Values::Types.frozen(reply.outputs) }
40
+ end
41
+
42
+ # DSPy's default instruction for a predictor, read back; it needs no LM.
43
+ def described(predictor)
44
+ Context.reply(Wire::Describe, Wire::Described, predictor:).instruction
45
+ end
46
+
47
+ # DSPy's own view of a Ruby tool, read back; it needs no LM.
48
+ def tool(description)
49
+ Context.reply(Wire::DescribeTool, Wire::ToolDescribed, tool: description)
50
+ end
51
+
52
+ # DSPy's own lm.kwargs of the LM Python builds from `model`, key-like values hidden; it calls no model.
53
+ def kwargs(model)
54
+ read = Context.reply(Wire::DescribeLM, Wire::LMDescribed, lm: model.description).kwargs
55
+
56
+ Values::Types.frozen(Secrets.hidden(read))
57
+ end
58
+
59
+ # Ruby's own LM a call made here names: its context's, else the configured one outside a callback; else nil.
60
+ def own_lm
61
+ context.lm || configured(:lm)
62
+ end
63
+
64
+ # The block takes the reply asked for and the spend; another reply raises its error.
65
+ def ask(shape, answer, serve: nil, model: own_lm, **fields)
66
+ collector = context.collector
67
+
68
+ collector&.stop_if_stopped
69
+ exchange = Context.ask(shape, serve: served(model, serve), **request(shape, model, fields))
70
+ spend = exchange.spend
71
+
72
+ collector&.add(spend)
73
+
74
+ return yield(exchange.reply, spend) if exchange.reply.is_a?(answer)
75
+
76
+ failed(exchange.error, collector)
77
+ end
78
+
79
+ private
80
+
81
+ # The settings in force that `shape` takes, under the fields given.
82
+ def request(shape, model, fields)
83
+ settings = {
84
+ component: program && context.collector&.name(program),
85
+ lm: model&.description,
86
+ adapter: context.adapter || configured(:adapter)
87
+ }
88
+
89
+ settings.slice(*shape.attribute_names).merge(fields).compact
90
+ end
91
+
92
+ # In a callback none: DSPy's own settings are in force there, which its optimizers set.
93
+ def configured(setting)
94
+ DSPyRb.config[setting] unless context.callback
95
+ end
96
+
97
+ # A DummyLM of a list, told by its description, answers its own next callback; any other is `serve`'s.
98
+ def served(model, serve)
99
+ return serve unless Step.scripted?(model)
100
+
101
+ lambda do |message|
102
+ return model.next_index if message.is_a?(Wire::NextCall)
103
+
104
+ serve ? serve.call(message) : throw(Runtime::Channel::Callback::UNSERVED)
105
+ end
106
+ end
107
+
108
+ def failed(error, collector)
109
+ # Kept from within the request, as a nested listener's raise is, not its own end: it stops the program too.
110
+ collector&.hold(error) unless error.is_a?(RequestError)
111
+
112
+ raise error
113
+ end
114
+ end
115
+ end
116
+ end
@@ -0,0 +1,28 @@
1
+ # frozen_string_literal: true
2
+
3
+ module DSPyRb
4
+ module Execution
5
+ # A ReAct's Ruby tools, each called back as DSPy asks: with the arguments it parsed, and the defaults it left out.
6
+ class Toolbox
7
+ extend Dry::Initializer
8
+
9
+ param :tools, Wire::Types::Strict::Array, reader: :private
10
+
11
+ # What the tool DSPy names returns.
12
+ def call(message)
13
+ raise Error, "a ReAct takes no #{message.kind} callback" unless message.is_a?(Wire::ToolCall)
14
+
15
+ tool = named.fetch(message.tool) { raise Error, "no tool is named #{message.tool}" }
16
+
17
+ tool.call(**tool.class.defaults, **message.args)
18
+ end
19
+
20
+ private
21
+
22
+ # The last of a name wins, as in DSPy's own table of them (dspy/predict/react.py:74).
23
+ def named
24
+ tools.to_h { [_1.class.tool_name, _1] }
25
+ end
26
+ end
27
+ end
28
+ end
@@ -0,0 +1,22 @@
1
+ # frozen_string_literal: true
2
+
3
+ module DSPyRb
4
+ # DSPy's ChainOfThought: DSPyRb::ChainOfThought[signature, reasoning: :written].
5
+ class ChainOfThought < Predict
6
+ # Written reasoning, or DSPy's own when left out.
7
+ def self.[](signature, instructions: nil, reasoning: nil, demos: nil)
8
+ raise Error, "#{name} takes reasoning: :written, or none" unless [nil, :written].include?(reasoning)
9
+
10
+ built(signature, kind: "chain_of_thought", instructions:, demos:, reasoning: reasoning&.to_s)
11
+ end
12
+
13
+ def reasoning
14
+ predictor.reasoning&.to_sym
15
+ end
16
+
17
+ # DSPy holds its leaf at `predict` (dspy/predict/chain_of_thought.py:54).
18
+ def component_name(name)
19
+ "#{name}.predict"
20
+ end
21
+ end
22
+ end
@@ -0,0 +1,101 @@
1
+ # frozen_string_literal: true
2
+
3
+ module DSPyRb
4
+ # DSPy's Predict, which Python builds afresh for each call: DSPyRb::Predict[signature, instructions: "..."].
5
+ class Predict
6
+ extend Dry::Initializer
7
+
8
+ # What Python builds it from: its kind, fields, demos, and the text given here, else in the signature.
9
+ param :predictor, proc { |given, program| described(given, program.class) }
10
+
11
+ # The named Signature class it was built from, whose source MIPROv2 reads; an anonymous one can't be Marshal'd.
12
+ option :signature, proc { _1 if _1&.name }, default: proc {}, reader: :private
13
+
14
+ def self.[](signature, instructions: nil, demos: nil)
15
+ built(signature, kind: "predict", instructions:, demos:)
16
+ end
17
+
18
+ # Python's description of a predictor of its form (`kind`, and a ChainOfThought's `reasoning`) for `signature`.
19
+ def self.built(signature, instructions:, demos:, **form)
20
+ signature = Signature.for(signature, name)
21
+ instructions ||= signature.instructions
22
+ demos &&= Values::Types::Examples[demos].map(&:wire)
23
+
24
+ described = { fields: signature.fields, instructions:, demos:, **form }
25
+
26
+ new(Wire::Departure.taken(Wire::Predictor, described.compact, name), signature:)
27
+ end
28
+
29
+ # The description `new` takes for `kind`; anything else refused, naming its builder, as ReAct[signature, tools:].
30
+ def self.described(given, kind)
31
+ return Values::Types.refuse_marked(given, "a #{kind.name}") if given.is_a?(Wire::Predictor)
32
+
33
+ parameters = kind.method(:[]).parameters
34
+ needed = parameters.filter_map { |form, argument| { req: argument, keyreq: "#{argument}:" }[form] }
35
+ builder = "#{kind.name}[#{needed.join(", ")}]"
36
+
37
+ raise Error, "#{kind.name}.new takes the description Python builds it from: make one with #{builder}"
38
+ end
39
+
40
+ private_class_method :built, :described
41
+
42
+ def call(**inputs)
43
+ Execution::Step.new(self).call(predictor, inputs)
44
+ end
45
+
46
+ def with_instructions(text)
47
+ changed = { **predictor.attributes, instructions: text }
48
+
49
+ rebuilt(Wire::Departure.taken(Wire::Predictor, changed, "#{self.class}#with_instructions"))
50
+ end
51
+
52
+ def with_demos(examples)
53
+ rebuilt(predictor.new(demos: Values::Types::Examples[examples].map(&:wire)))
54
+ end
55
+
56
+ # Whether DSPy marks it compiled, as an optimizer marks the program it gives.
57
+ def compiled?
58
+ predictor.compiled == true
59
+ end
60
+
61
+ # GEPA's detailed results, DSPy's to_dict, on the copy a GEPA compile with track_stats: true gives; else nil.
62
+ def detailed_results
63
+ instance_variable_get(Execution::Optimization::RESULTS)
64
+ end
65
+
66
+ # DSPy's own JSON state, which DSPy writes to the file at `path`; never a pickle.
67
+ def save(path, save_program: false)
68
+ Execution::Program.new(Parts.new(self)).save(path, save_program:)
69
+ end
70
+
71
+ # A copy holding the state DSPy saved at `path`, as its other changes give one.
72
+ def load(path)
73
+ Execution::Program.new(Parts.new(self)).load(path)
74
+ end
75
+
76
+ # The Examples DSPy shows the model before the inputs.
77
+ def demos
78
+ (predictor.demos || []).map { Values::Example.of(_1) }
79
+ end
80
+
81
+ # The text given here or in its signature; nil leaves DSPy's default.
82
+ def given_instruction
83
+ predictor.instructions
84
+ end
85
+
86
+ # The text DSPy holds: the one given, else DSPy's default, read back.
87
+ def instruction
88
+ given_instruction || Execution::Step.new(self).described(predictor)
89
+ end
90
+
91
+ def component_name(name)
92
+ name
93
+ end
94
+
95
+ private
96
+
97
+ def rebuilt(predictor)
98
+ self.class.new(predictor, signature:)
99
+ end
100
+ end
101
+ end
@@ -0,0 +1,80 @@
1
+ # frozen_string_literal: true
2
+
3
+ module DSPyRb
4
+ # DSPy's ReAct over Ruby tools, ending by submit: DSPyRb::ReAct[signature, tools: [Search.new], max_iters: 4].
5
+ class ReAct < Predict
6
+ # Its own frozen copy of the tools, as Python holds those it was described with; none is refused naming the builder.
7
+ option :tools, proc { |given, react| taken_tools(given, react.class) }, default: proc { needs_tools }
8
+
9
+ # The signature's instructions go into ReAct's own text as its task; no max_iters leaves DSPy's 20.
10
+ def self.[](signature, tools:, max_iters: nil)
11
+ signature = taken_signature(signature)
12
+ described = {
13
+ kind: "react",
14
+ fields: signature.fields,
15
+ tools: usable(tools).map { _1.class.description },
16
+ max_iters:,
17
+ task: signature.instructions
18
+ }
19
+
20
+ new(Wire::Departure.taken(Wire::Predictor, described.compact, name), tools:, signature:)
21
+ end
22
+
23
+ # Refused by place and class alone.
24
+ def self.usable(tools)
25
+ raise Error, "a ReAct's tools come as an Array, not #{Error.class_of(tools)}" unless tools.is_a?(::Array)
26
+
27
+ stray = tools.index { !_1.is_a?(Tool) }
28
+
29
+ return tools unless stray
30
+
31
+ raise Error, "a ReAct's tools are DSPyRb::Tool instances: item #{stray} is #{Error.class_of(tools[stray])}"
32
+ end
33
+
34
+ # The signature given, refused naming the builder for an input DSPy's ReAct takes as its own option.
35
+ def self.taken_signature(given)
36
+ signature = Signature.for(given, name)
37
+ inputs = signature.fields.filter_map { [_1.name, nil] if _1.role == "input" }.to_h
38
+
39
+ Values::Types.refuse_reserved(inputs, name, "react")
40
+ signature
41
+ end
42
+
43
+ # Tools given to `new` of `made`, any but an Array refused by the place alone.
44
+ def self.taken_tools(given, made)
45
+ Values::Types.frozen(Wire::Departure.taken(Wire::Types::Strict::Array, given, "#{made.name}.new"))
46
+ end
47
+
48
+ private_class_method :usable, :taken_signature, :taken_tools
49
+
50
+ def call(**inputs)
51
+ Execution::Step.new(self).call(predictor, inputs, serve: Execution::Toolbox.new(tools))
52
+ end
53
+
54
+ # Its turn budget; nil leaves DSPy's 20.
55
+ def max_iters
56
+ predictor.max_iters
57
+ end
58
+
59
+ # The signature's instructions, which DSPy writes into ReAct's own text.
60
+ def task
61
+ predictor.task
62
+ end
63
+
64
+ # DSPy 3.5 makes a ReAct's model calls through one Predict, held at `react` (dspy/predict/react.py:79).
65
+ def component_name(name)
66
+ "#{name}.react"
67
+ end
68
+
69
+ private
70
+
71
+ def rebuilt(predictor)
72
+ self.class.new(predictor, tools:, signature:)
73
+ end
74
+
75
+ # As `new` is refused without tools, advising its builder.
76
+ def needs_tools
77
+ raise Error, "#{self.class.name}.new needs tools: make one with #{self.class.name}[signature, tools:]"
78
+ end
79
+ end
80
+ end
@@ -0,0 +1,105 @@
1
+ # frozen_string_literal: true
2
+
3
+ module DSPyRb
4
+ # A DSPy program written in Ruby.
5
+ class Module
6
+ def call(**inputs)
7
+ parent = Execution::Context.current.collector
8
+ collector = Execution::Collector.new(parent ? parent.names : Parts.new(self).names, parent)
9
+ prediction = parent ? run(collector, inputs) : bounded(collector, inputs)
10
+
11
+ prediction.with_spend(collector.spend)
12
+ end
13
+
14
+ def forward(**)
15
+ raise Error, "#{self.class} defines no forward"
16
+ end
17
+
18
+ # A compiled sub-module's are left out, as DSPy keeps one from its optimizers.
19
+ def named_predictors
20
+ Parts.new(self).names(compiled: false).map { |predictor, name| [name, predictor] }
21
+ end
22
+
23
+ def instructions
24
+ named_predictors.to_h { |name, predictor| [name, predictor.instruction] }
25
+ end
26
+
27
+ def with_instructions(texts)
28
+ replaced(texts, &:with_instructions)
29
+ end
30
+
31
+ def demos
32
+ named_predictors.to_h { |name, predictor| [name, predictor.demos] }
33
+ end
34
+
35
+ def with_demos(demos)
36
+ replaced(demos, &:with_demos)
37
+ end
38
+
39
+ # Whether DSPy marks it compiled, as an optimizer marks the program it gives.
40
+ def compiled?
41
+ instance_variable_get(Parts::MARK) == true
42
+ end
43
+
44
+ # GEPA's detailed results, DSPy's to_dict, on the copy a GEPA compile with track_stats: true gives; else nil.
45
+ def detailed_results
46
+ instance_variable_get(Execution::Optimization::RESULTS)
47
+ end
48
+
49
+ # DSPy's own JSON state, which DSPy writes to the file at `path`; never a pickle.
50
+ def save(path, save_program: false)
51
+ Execution::Program.new(Parts.new(self)).save(path, save_program:)
52
+ end
53
+
54
+ # The state DSPy saved at `path`, applied to this module in place, as DSPy's load does; gives back the module.
55
+ def load(path)
56
+ Execution::Program.new(Parts.new(self)).load(path)
57
+ end
58
+
59
+ private
60
+
61
+ # A copy with each predictor named here replaced by what the block makes of it and the value given for it.
62
+ def replaced(by_name)
63
+ refuse_unnamed(by_name)
64
+
65
+ named = named_predictors.to_h
66
+
67
+ replacements = by_name.to_h do |name, given|
68
+ predictor = named.fetch(name.to_s) { raise Error, "#{self.class} has no predictor named #{name}" }
69
+
70
+ [predictor, yield(predictor, given)]
71
+ end
72
+
73
+ Parts.new(self).substitute(replacements.compare_by_identity)
74
+ end
75
+
76
+ # Texts or demos given otherwise than by each predictor's name are refused by their class alone.
77
+ def refuse_unnamed(by_name)
78
+ return if by_name.is_a?(::Hash)
79
+
80
+ raise Error,
81
+ "#{self.class} takes its predictors' texts and demos by name, as a Hash, not #{Error.class_of(by_name)}"
82
+ end
83
+
84
+ def run(collector, inputs)
85
+ prediction = Execution::Context.within(Execution::Context.current.new(collector:)) { forward(**inputs) }
86
+
87
+ return prediction if prediction.is_a?(Prediction)
88
+
89
+ raise Error, "#{self.class}#forward returned #{Error.class_of(prediction)}, not a DSPyRb::Prediction"
90
+ end
91
+
92
+ # A kept error is the call's own, raised though forward rescued it or raised another.
93
+ def bounded(collector, inputs)
94
+ outcome = begin
95
+ run(collector, inputs)
96
+ rescue StandardError
97
+ raise unless collector.stopped
98
+ end
99
+
100
+ raise collector.stopped if collector.stopped
101
+
102
+ outcome
103
+ end
104
+ end
105
+ end
@@ -0,0 +1,121 @@
1
+ # frozen_string_literal: true
2
+
3
+ module DSPyRb
4
+ # A program's parts as DSPy sees them: each Predict and Module it holds by path, the compiled ones frozen.
5
+ class Parts
6
+ extend Dry::Initializer
7
+
8
+ # The variable Module#compiled? reads, a name of the gem's apart from a user's own.
9
+ MARK = :@__dspy_rb_compiled
10
+
11
+ # A Module, or a predictor of any kind, which holds no parts.
12
+ param :program
13
+
14
+ # Each part it holds by its path, a module before its own; `compiled: false` skips what DSPy freezes.
15
+ def walk(prefix = nil, compiled: true, &visit)
16
+ parts_of(program).each do |variable, part|
17
+ path = [prefix, variable.to_s.delete_prefix("@")].compact.join(".")
18
+
19
+ next unless compiled || !frozen_by_dspy?(part)
20
+
21
+ visit.call(path, part)
22
+ Parts.new(part).walk(path, compiled:, &visit) if part.is_a?(Module)
23
+ end
24
+ end
25
+
26
+ # The first name a predictor is held at wins (dspy/primitives/base_module.py:37-39).
27
+ def names(compiled: true)
28
+ {}.compare_by_identity.tap do |found|
29
+ walk(compiled:) { |path, part| found[part] ||= part.component_name(path) unless part.is_a?(Module) }
30
+ end
31
+ end
32
+
33
+ # A copy holding, for each predictor `replacements` holds, its replacement, every module on the way copied.
34
+ def substitute(replacements)
35
+ copy = program.dup
36
+
37
+ parts_of(program).each do |variable, part|
38
+ replaced = part.is_a?(Module) ? Parts.new(part).substitute(replacements) : replacements.fetch(part, part)
39
+
40
+ copy.instance_variable_set(variable, replaced)
41
+ end
42
+
43
+ copy
44
+ end
45
+
46
+ # The program itself, each predictor `replacements` holds rebound to its replacement, in every module on the way.
47
+ def rebind(replacements)
48
+ writes = bindings(replacements)
49
+ frozen = writes.map(&:first).find(&:frozen?)
50
+
51
+ raise Error, "#{program.class}#load loads in place, and cannot change a frozen #{frozen.class}" if frozen
52
+
53
+ writes.each { |holder, variable, part| holder.instance_variable_set(variable, part) }
54
+
55
+ program
56
+ end
57
+
58
+ # A copy marked as an optimizer marks the program it gives: a Module by MARK, a predictor in its description.
59
+ def marked(compiled)
60
+ return program.dup.tap { _1.instance_variable_set(MARK, compiled) } if program.is_a?(Module)
61
+
62
+ rebuilt(program.predictor.new(compiled:))
63
+ end
64
+
65
+ # By its class, so a predictor of the user's with a forward of its own is still a predictor.
66
+ def module?(value)
67
+ value.is_a?(Module)
68
+ end
69
+
70
+ protected
71
+
72
+ # Each write that changes a part, as the module written, its variable and the part it then holds.
73
+ def bindings(replacements)
74
+ parts_of(program).flat_map do |variable, part|
75
+ next Parts.new(part).bindings(replacements) if part.is_a?(Module)
76
+
77
+ replaced = replacements.fetch(part, part)
78
+
79
+ replaced.equal?(part) ? [] : [[program, variable, replaced]]
80
+ end
81
+ end
82
+
83
+ private
84
+
85
+ # A predictor of the program's own kind from its description, keeping its signature, and a ReAct its tools.
86
+ def rebuilt(described)
87
+ kept = { tools: (program.tools if program.is_a?(ReAct)), signature: program.instance_variable_get(:@signature) }
88
+
89
+ program.class.new(described, **kept.compact)
90
+ end
91
+
92
+ # A compiled module DSPy keeps frozen, though a Predict is a parameter, never frozen (base_module.py:36-58).
93
+ def frozen_by_dspy?(part)
94
+ part.compiled? && (part.is_a?(Module) || part.predictor.kind != "predict")
95
+ end
96
+
97
+ # DSPy names one in an Array or a Hash `hops[0]` (base_module.py:60-66); the gem takes each in its own variable.
98
+ def parts_of(held)
99
+ held.instance_variables.filter_map do |variable|
100
+ value = held.instance_variable_get(variable)
101
+
102
+ next [variable, value] if part?(value)
103
+ next unless holds_parts?(value)
104
+
105
+ raise Error, "#{held.class}'s #{variable} holds predictors inside it: hold each in its own variable"
106
+ end
107
+ end
108
+
109
+ def part?(value)
110
+ value.is_a?(Predict) || value.is_a?(Module)
111
+ end
112
+
113
+ def holds_parts?(value)
114
+ items = value.is_a?(::Hash) ? value.values : value
115
+
116
+ items.is_a?(::Array) && items.any? { |item| part?(item) }
117
+ end
118
+ end
119
+
120
+ private_constant :Parts
121
+ end
@@ -0,0 +1,105 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "English"
4
+
5
+ module DSPyRb
6
+ module Runtime
7
+ class Channel
8
+ # Serves one of Python's callbacks on a thread of its own, and always answers it, by Python's id.
9
+ class Callback
10
+ extend Dry::Initializer
11
+
12
+ # What ends its request, as only KeyboardInterrupt and SystemExit escape DSPy's handlers in Python.
13
+ FATAL = [SignalException, SystemExit, NoMemoryError].freeze
14
+
15
+ # Thrown by a request's serve for a callback it takes not, refused as a request's that takes none is.
16
+ UNSERVED = :dspy_rb_unserved
17
+
18
+ param :id, Wire::Types::Id
19
+ option :channel, Wire::Types.Instance(Channel), reader: :private
20
+
21
+ # The Ruby request it serves, as its line names it.
22
+ option :request, Wire::Types::Id.optional, default: proc {}, reader: :private
23
+ option :message, Wire::Types.Instance(Wire::Shape).optional, default: proc {}, reader: :private
24
+
25
+ # Why it is answered without running: its line could not be read.
26
+ option :refusal, Wire::Types::Text.optional, default: proc {}, reader: :private
27
+
28
+ # Given itself as the thread's argument, so the thread serves this callback whatever the reader takes next.
29
+ def start
30
+ Thread.new(self, &:serve)
31
+ end
32
+
33
+ # A pooled request goes to the Python thread waiting for it, its spend counted in this request's.
34
+ def ask(shape, **)
35
+ return channel.ask(shape, **) unless Wire::POOLED.include?(shape)
36
+
37
+ channel.ask(shape, within: id, parent: request && channel.exchange(request), **)
38
+ end
39
+
40
+ def serve
41
+ Thread.current.report_on_exception = false
42
+ exchange = request && channel.exchange(request)
43
+
44
+ # Its answer is written though the thread is killed or raised into; the Ruby code alone is interruptible.
45
+ Thread.handle_interrupt(Object => :never) do
46
+ answer = Thread.handle_interrupt(Object => :immediate) { run(exchange) }
47
+ ensure
48
+ channel.notify(answer || failed(exchange, $ERROR_INFO))
49
+ end
50
+ end
51
+
52
+ private
53
+
54
+ def run(exchange)
55
+ return refused(refusal) if refusal
56
+ return refused("no request #{request} waits for this callback") if exchange.nil? || exchange.stopped?
57
+ return gated(exchange) if message.is_a?(Wire::GateCall)
58
+
59
+ served(exchange)
60
+ end
61
+
62
+ def served(exchange)
63
+ answer = exchange.serve && catch(UNSERVED) { Wire::Returned.new(id:, **exchange.serve.call(self, message)) }
64
+
65
+ answer || refused("request #{request} takes no callbacks")
66
+ end
67
+
68
+ def gated(exchange)
69
+ Gate.new(exchange, message.pending, channel:).ask { served(exchange) }
70
+ end
71
+
72
+ def refused(reason)
73
+ raised(Error.name, reason, fatal: true)
74
+ end
75
+
76
+ def failed(exchange, error)
77
+ return raised("Thread", "the callback's thread was killed", fatal: true) unless error
78
+
79
+ fatal = FATAL.any? { error.is_a?(_1) }
80
+
81
+ exchange&.keep(error) if fatal
82
+ raised(error.class.name || error.class.inspect, error.message, fatal:, of: of(error))
83
+ end
84
+
85
+ # The nested request whose own Python exception Python raises in this one's place.
86
+ def of(error)
87
+ case error
88
+ when Cancelled, DSPyError then error.request
89
+ end
90
+ end
91
+
92
+ def raised(ruby_class, message, fatal:, of: nil)
93
+ text = message.encode(Encoding::UTF_8, invalid: :replace, undef: :replace).scrub
94
+
95
+ # DSPy shows both to the model as a tool's result (dspy/predict/react.py:251).
96
+ text = Values::Types.marked("the exception's message") if Values::Types.marked?(text)
97
+ ruby_class = Error.name if Values::Types.marked?(ruby_class)
98
+ error = Wire::RubyFailure.new({ ruby_class:, message: text, fatal:, of: }.compact)
99
+
100
+ Wire::Raised.new(id:, error:)
101
+ end
102
+ end
103
+ end
104
+ end
105
+ end