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,83 @@
1
+ # frozen_string_literal: true
2
+
3
+ module DSPyRb
4
+ # The `ruby-on-dspy setup` and `ruby-on-dspy doctor` commands, which exe/ruby-on-dspy alone loads.
5
+ module CLI
6
+ # sysexits' EX_USAGE.
7
+ USAGE = 64
8
+
9
+ class << self
10
+ def run(arguments, out: $stdout, err: $stderr)
11
+ case arguments
12
+ in ["setup"] then setup(out, [])
13
+ in ["setup", "--with", group] if Setup::Environment::GROUPS.key?(group) then setup(out, [group])
14
+ in ["doctor"] then doctor(out)
15
+ else
16
+ err.puts("usage: ruby-on-dspy setup [--with data] | ruby-on-dspy doctor")
17
+ USAGE
18
+ end
19
+ end
20
+
21
+ def checks
22
+ [
23
+ uv,
24
+ check("python folder", Dir.exist?(Setup::Environment.python_folder), Setup::Environment.python_folder),
25
+ environment,
26
+ data,
27
+ *served
28
+ ]
29
+ end
30
+
31
+ private
32
+
33
+ def setup(out, groups)
34
+ Setup::Environment.setup(out:, groups:)
35
+ 0
36
+ end
37
+
38
+ def doctor(out)
39
+ found = checks
40
+
41
+ found.each { |check| out.puts("#{check.passed ? "ok " : "FAIL"} #{check.name}: #{check.detail}") }
42
+
43
+ found.all?(&:passed) ? 0 : 1
44
+ end
45
+
46
+ def uv
47
+ found = Setup::Uv.found(Setup::Environment.uv_path)
48
+
49
+ return check("uv", true, "#{Setup::Uv.version(found)} at #{found}") if found
50
+
51
+ check("uv", false, "none: `ruby-on-dspy setup` fetches uv #{Setup::Uv::RELEASE}")
52
+ end
53
+
54
+ def environment
55
+ Setup::Environment.python
56
+
57
+ check("environment", true, Setup::Environment.venv)
58
+ rescue SetupError => e
59
+ check("environment", false, e.message)
60
+ end
61
+
62
+ # Optional, so it passes either way.
63
+ def data
64
+ return check("data group", true, "installed") if Setup::Environment.installed?("data")
65
+
66
+ check("data group", true, "not installed: `ruby-on-dspy setup --with data` adds DSPy's dataset loaders")
67
+ end
68
+
69
+ def served
70
+ welcome = Runtime::Registry.current.welcome
71
+ versions = "ruby-on-dspy #{welcome.package}, DSPy #{welcome.dspy}, Python #{welcome.python}"
72
+
73
+ [check("hello", true, versions), check("describe", true, Predict["question -> answer"].instruction)]
74
+ rescue Error => e
75
+ [check("Python", false, e.message)]
76
+ end
77
+
78
+ def check(name, passed, detail)
79
+ Values::Check.new(name:, passed:, detail:)
80
+ end
81
+ end
82
+ end
83
+ end
@@ -0,0 +1,81 @@
1
+ # frozen_string_literal: true
2
+
3
+ module DSPyRb
4
+ # DSPy's own test model (dspy/utils/dummies.py:16), its answers scripted: DSPyRb::DummyLM[[{ category: "bug" }]].
5
+ class DummyLM
6
+ extend Dry::Initializer
7
+
8
+ # What Python builds it from: its answers and DSPy's options for it; a refusal names the class being made.
9
+ param :description, proc { |given, lm| described(given, lm.class) }
10
+
11
+ # The indexes of a list's answers no call has used, kept here, since Python builds a DummyLM for each request.
12
+ option :unused, default: proc { Thread::Queue.new(indexes) }, reader: :private
13
+
14
+ # DSPy's four parameters (dspy/utils/dummies.py:69-75); nil leaves DSPy's default.
15
+ def self.[](answers, follow_examples: nil, reasoning: nil, adapter: nil)
16
+ given = { answers: checked(answers, to_s), follow_examples:, reasoning:, adapter: }
17
+
18
+ new(Wire::Departure.taken(Wire::DummyLM, given.compact, to_s))
19
+ end
20
+
21
+ # Each answer as JSON carries it, a refusal naming its place; answers of another shape are left for the wire.
22
+ def self.checked(answers, place)
23
+ at = ->(key, answer) { Wire::Json.values(answer, "#{place}'s answers[#{key.inspect}]") }
24
+
25
+ case answers
26
+ when ::Array then answers.each_with_index.map { |answer, index| at[index, answer] }
27
+ when ::Hash then texts(answers, place).to_h { |text, answer| [text, at[text, answer]] }
28
+ else answers
29
+ end
30
+ end
31
+
32
+ # A Symbol key as its String, refused when that String is a key too; any other as given, for the wire to refuse.
33
+ def self.texts(answers, place)
34
+ twice = answers.keys.grep(::Symbol).map(&:to_s).find { answers.key?(_1) }
35
+
36
+ raise Error, "#{place}'s answers[#{twice.inspect}] is given twice, as a Symbol and as a String" if twice
37
+
38
+ answers.transform_keys { _1.is_a?(::Symbol) ? _1.to_s : _1 }
39
+ end
40
+
41
+ # The description `new` takes; anything else is its builder's.
42
+ def self.described(given, made)
43
+ return given if given.is_a?(Wire::DummyLM)
44
+
45
+ raise Error, "#{made}.new takes the description Python builds it from: make one with #{made}[answers]"
46
+ end
47
+
48
+ private_class_method :checked, :texts, :described
49
+
50
+ # DSPy's lm(prompt, **options), as DSPyRb::LM#call: its list of outputs, each answer as the adapter formats it.
51
+ def call(prompt, **options)
52
+ Execution::Step.new.generate(self, prompt, options, place: "#{self.class}#call")
53
+ end
54
+
55
+ # DSPy's lm.copy(**options), as DSPyRb::LM#copy, going on with this one's script: the two share its unused answers.
56
+ def copy(**options)
57
+ options = Wire::Json.values(options, "#{self.class}#copy")
58
+
59
+ self.class.new(description.new(copies: [*description.copies, options]), unused:)
60
+ end
61
+
62
+ # DSPy's lm.kwargs, as DSPyRb::LM#kwargs.
63
+ def kwargs
64
+ Execution::Step.new.kwargs(self)
65
+ end
66
+
67
+ # Each answer's index once, whatever thread or process asks; nil once none is left.
68
+ def next_index
69
+ unused.pop(timeout: 0)
70
+ end
71
+
72
+ private
73
+
74
+ # Text-keyed answers have none: DSPy finds them in the prompt.
75
+ def indexes
76
+ answers = description.answers
77
+
78
+ answers.is_a?(::Array) ? answers.each_index : []
79
+ end
80
+ end
81
+ end
@@ -0,0 +1,44 @@
1
+ # frozen_string_literal: true
2
+
3
+ module DSPyRb
4
+ # DSPy's LM, which Python builds from its description and calls: DSPyRb::LM["openai/gpt-4.1-mini"].call("Hi").
5
+ class LM
6
+ extend Dry::Initializer
7
+
8
+ # What Python builds it from: a model and DSPy's options.
9
+ param :description, proc { |given, lm| described(given, lm.class) }
10
+
11
+ # DSPy's options whole, the variable naming its key apart.
12
+ def self.[](model, api_key_env: nil, **options)
13
+ options = Wire::Json.values(options, to_s)
14
+
15
+ new(Wire::Departure.taken(Wire::LM, { model:, options:, api_key_env: }.compact, to_s))
16
+ end
17
+
18
+ # The description `new` takes; anything else is its builders'.
19
+ def self.described(given, made)
20
+ return given if given.is_a?(Wire::LM)
21
+
22
+ raise Error, "#{made}.new takes the description Python builds it from: make one with #{made}[model]"
23
+ end
24
+
25
+ private_class_method :described
26
+
27
+ # DSPy's lm(prompt, **options): a candidate's each output, text or a Hash for DSPy's dict; options pass whole.
28
+ def call(prompt, **options)
29
+ Execution::Step.new.generate(self, prompt, options, place: "#{self.class}#call")
30
+ end
31
+
32
+ # DSPy's lm.copy(**options), made in Python from this LM by DSPy's own copy, its model and key kept.
33
+ def copy(**options)
34
+ options = Wire::Json.values(options, "#{self.class}#copy")
35
+
36
+ self.class.new(description.new(copies: [*description.copies, options]))
37
+ end
38
+
39
+ # DSPy's lm.kwargs, frozen: each call's default options, a copy's included; never a key, key-like values hidden.
40
+ def kwargs
41
+ Execution::Step.new.kwargs(self)
42
+ end
43
+ end
44
+ end
@@ -0,0 +1,74 @@
1
+ # frozen_string_literal: true
2
+
3
+ module DSPyRb
4
+ # DSPy's DataLoader: its loaders and its sampling, run in Python by DSPy's own code.
5
+ module DataLoader
6
+ class << self
7
+ # Rows by split, or one split's list; a local folder goes in full, since Python's working folder may differ.
8
+ def from_huggingface(dataset_name, *arguments, input_keys: nil, fields: nil, **options)
9
+ dataset_name = File.expand_path(dataset_name) if dataset_name.is_a?(::String) && File.exist?(dataset_name)
10
+ arguments = Wire::Json.value(arguments, "DataLoader.from_huggingface's arguments")
11
+ source = { dataset_name:, arguments:, options:, **names(input_keys:, fields:) }
12
+
13
+ Execution::Rows.new.load(Wire::HubDataset, source.compact, "DataLoader.from_huggingface")
14
+ end
15
+
16
+ def from_csv(file_path, fields: nil, input_keys: nil)
17
+ file("csv", file_path, fields, input_keys)
18
+ end
19
+
20
+ def from_json(file_path, fields: nil, input_keys: nil)
21
+ file("json", file_path, fields, input_keys)
22
+ end
23
+
24
+ def from_parquet(file_path, fields: nil, input_keys: nil)
25
+ file("parquet", file_path, fields, input_keys)
26
+ end
27
+
28
+ # `count` of the rows, as DSPy's sample(dataset, n) draws them from Python's global random.
29
+ def sample(dataset, count)
30
+ unless count.is_a?(::Integer)
31
+ raise Error, "DataLoader.sample takes an Integer count, not #{Error.class_of(count)}"
32
+ end
33
+
34
+ Execution::Rows.new.permute(dataset, "sample", k: count).first
35
+ end
36
+
37
+ # The rows split as DSPy's train_test_split splits them, seeded by random_state; nil leaves DSPy's default.
38
+ def train_test_split(dataset, train_size: nil, test_size: nil, random_state: nil)
39
+ refuse_split({ train_size:, test_size: }, random_state)
40
+
41
+ options = { train_size:, test_size:, random_state: }.compact
42
+ train, test = Execution::Rows.new.permute(dataset, "train_test_split", **options)
43
+
44
+ { train:, test: }.freeze
45
+ end
46
+
47
+ private
48
+
49
+ def file(format, file_path, fields, input_keys)
50
+ source = { format:, file_path:, **names(fields:, input_keys:) }
51
+
52
+ Execution::Rows.new.load(Wire::DataFile, source.compact, "DataLoader.from_#{format}")
53
+ end
54
+
55
+ # Each list of names as the wire carries it.
56
+ def names(**lists)
57
+ lists.transform_values { Wire::Json.names(_1) }
58
+ end
59
+
60
+ # Each refused by its kind alone; a number DSPy cannot split by is DSPy's own to refuse.
61
+ def refuse_split(sizes, random_state)
62
+ sizes.each do |name, size|
63
+ next if size.nil? || Wire::Types::Number.valid?(size)
64
+
65
+ raise Error, "DataLoader.train_test_split takes #{name} as an Integer or a Float, not #{Error.class_of(size)}"
66
+ end
67
+
68
+ return if random_state.nil? || random_state.is_a?(::Integer)
69
+
70
+ raise Error, "DataLoader.train_test_split takes random_state as an Integer, not #{Error.class_of(random_state)}"
71
+ end
72
+ end
73
+ end
74
+ end
@@ -0,0 +1,37 @@
1
+ # frozen_string_literal: true
2
+
3
+ module DSPyRb
4
+ # DSPy's own datasets, each loaded in Python by DSPy's class of that name as a Values::Dataset: Dataset.gsm8k.
5
+ module Dataset
6
+ class << self
7
+ # DSPy's HotPotQA, with its own options and its Dataset's (train_seed:, train_size:, dev_size:, ...).
8
+ def hot_pot_qa(**options)
9
+ loaded("hot_pot_qa", options)
10
+ end
11
+
12
+ def gsm8k
13
+ loaded("gsm8k")
14
+ end
15
+
16
+ def math(subset:)
17
+ loaded("math", { subset: })
18
+ end
19
+
20
+ # DSPy's Colors, which needs no download, with its own option and its Dataset's.
21
+ def colors(**options)
22
+ loaded("colors", options)
23
+ end
24
+
25
+ private
26
+
27
+ # Each option as DSPy takes it; nil leaves DSPy's default. The name is the loader's, never an option's.
28
+ def loaded(name, options = {})
29
+ raise Error, "Dataset.#{name} takes no name" if options.key?(:name)
30
+
31
+ fields = { **options, name:, input_keys: Wire::Json.names(options[:input_keys]) }
32
+
33
+ Execution::Rows.new.load(Wire::DSPyDataset, fields.compact, "Dataset.#{name}")
34
+ end
35
+ end
36
+ end
37
+ end
@@ -0,0 +1,38 @@
1
+ # frozen_string_literal: true
2
+
3
+ module DSPyRb
4
+ # Python's random.Random(seed), so a shuffle or a sample of Ruby rows comes in Python's own order: PythonRandom[0].
5
+ class PythonRandom
6
+ extend Dry::Initializer
7
+
8
+ # Python's seed, refused alike by `new` and `[]`.
9
+ param :seed, proc { |given| seeded(given) }, reader: :private
10
+
11
+ def self.[](seed)
12
+ new(seed)
13
+ end
14
+
15
+ # An Integer, any other refused by its class alone.
16
+ def self.seeded(given)
17
+ return given if given.is_a?(::Integer)
18
+
19
+ raise Error, "PythonRandom takes an Integer seed, not #{Error.class_of(given)}"
20
+ end
21
+
22
+ private_class_method :seeded
23
+
24
+ # random.Random(seed).shuffle's order, as a new Array; each call starts from a fresh Random(seed).
25
+ def shuffle(rows)
26
+ Execution::Rows.new.permute(rows, "shuffle", seed:).first
27
+ end
28
+
29
+ # A fresh random.Random(seed).sample(rows, count); a count the rows cannot give is Python's own to refuse.
30
+ def sample(rows, count)
31
+ unless count.is_a?(::Integer)
32
+ raise Error, "PythonRandom#sample takes an Integer count, not #{Error.class_of(count)}"
33
+ end
34
+
35
+ Execution::Rows.new.permute(rows, "sample", seed:, k: count).first
36
+ end
37
+ end
38
+ end
@@ -0,0 +1,135 @@
1
+ # frozen_string_literal: true
2
+
3
+ module DSPyRb
4
+ # Every error ruby-on-dspy raises.
5
+ class Error < StandardError
6
+ # A value's class with its article ("an Integer"), never the value; nil, true and false by name.
7
+ def self.class_of(value)
8
+ return value.inspect if value.nil? || value.equal?(true) || value.equal?(false)
9
+
10
+ name = value.class.name || value.class.inspect
11
+
12
+ "#{name.match?(/\A[AEIOU]/) ? "an" : "a"} #{name}"
13
+ end
14
+ end
15
+
16
+ # The Python environment is missing or does not match this gem.
17
+ class SetupError < Error; end
18
+
19
+ # An error raised for one request: what it spent, as far as Ruby knows, and its id once it had one.
20
+ class RequestError < Error
21
+ attr_reader :spend, :request
22
+
23
+ def initialize(message, spend, request = nil)
24
+ @spend = spend
25
+ @request = request
26
+ super(message)
27
+ end
28
+ end
29
+
30
+ # Python refused a request; nothing ran.
31
+ class Refused < RequestError; end
32
+
33
+ # DSPy gave state a Ruby program cannot hold, so nothing was applied; `spend` says what a compile that ran cost.
34
+ class StateError < RequestError; end
35
+
36
+ # The Python process was lost, or wrote nothing for a whole window.
37
+ class Unavailable < RequestError; end
38
+
39
+ # A line of Python's that breaks the wire, named by where; it fails only the request it belongs to.
40
+ class Malformed < RequestError; end
41
+
42
+ # A request Python answered as cancelled: the request whose callback it served was cancelled or had answered.
43
+ class Cancelled < RequestError
44
+ def initialize(spend, request = nil)
45
+ super("cancelled: the request it was made within had stopped", spend, request)
46
+ end
47
+ end
48
+
49
+ # An error Python raised in a request.
50
+ class DSPyError < RequestError
51
+ attr_reader :failure
52
+
53
+ def initialize(failure, spend, request = nil)
54
+ @failure = failure
55
+ super(account, spend, request)
56
+ end
57
+
58
+ def python_class
59
+ failure.ancestry.first
60
+ end
61
+
62
+ def ancestry
63
+ failure.ancestry
64
+ end
65
+
66
+ def retryable
67
+ failure.retryable
68
+ end
69
+
70
+ # A Python class's name is a Ruby constant's only when it starts with a capital (zlib.error, _Private are not).
71
+ CONSTANT = /\A[A-Z]\w*\z/
72
+
73
+ def self.for(failure, spend, request = nil)
74
+ name = failure.ancestry.find { declared?(_1) }
75
+
76
+ (name ? DSPyRb.const_get(name, false) : self).new(failure, spend, request)
77
+ end
78
+
79
+ def self.declared?(name)
80
+ name.match?(CONSTANT) && DSPyRb.const_defined?(name, false) && DSPyRb.const_get(name, false) <= self
81
+ end
82
+
83
+ private
84
+
85
+ # DSPy's own account, as Python scrubbed it.
86
+ def account
87
+ "#{python_class}: #{failure.message}"
88
+ end
89
+ end
90
+
91
+ # DSPy 3.5.0's errors, each under its DSPy parent (dspy/utils/exceptions.py).
92
+ class LMError < DSPyError; end
93
+ class AdapterParseError < DSPyError; end
94
+ class LMTransportError < LMError; end
95
+ class LMLockTimeoutError < LMError; end
96
+ class LMCollectionLimitError < LMError; end
97
+ class LMProviderError < LMError; end
98
+ class LMUnexpectedError < LMError; end
99
+ class LMStreamAssemblyError < LMUnexpectedError; end
100
+ class LMRateLimitError < LMProviderError; end
101
+ class LMTimeoutError < LMProviderError; end
102
+ class LMServerError < LMProviderError; end
103
+ class LMInvalidRequestError < LMProviderError; end
104
+ class ContextWindowExceededError < LMInvalidRequestError; end
105
+ class LMAuthError < LMProviderError; end
106
+ class LMBillingError < LMProviderError; end
107
+ class LMUnsupportedModelError < LMInvalidRequestError; end
108
+ class LMConfigurationError < LMError; end
109
+ class LMUnsupportedFeatureError < LMError; end
110
+
111
+ # Python's scrub cuts DSPy's account of a missing key at "API key", so the gem says it plainly and where the key goes.
112
+ class LMNotConfiguredError < LMConfigurationError
113
+ # The variable DSPy 3.5.0 reads a key from, by the model's prefix (dspy/_vendor/lm15/access.py:76, 132, 164, 186).
114
+ VARIABLES = {
115
+ "openai" => "OPENAI_API_KEY",
116
+ "anthropic" => "ANTHROPIC_API_KEY",
117
+ "gemini" => "GEMINI_API_KEY or GOOGLE_API_KEY"
118
+ }.freeze
119
+
120
+ # A missing key alone, as Python cuts DSPy's "[model] no API key found ..." (dspy/_vendor/lm15/router.py:1063-1068).
121
+ MISSING_KEY = %r{\A\[(?:(?<provider>[^/\]]+)/)?[^\]]*\] no \[cut\]\z}
122
+
123
+ private
124
+
125
+ def account
126
+ missing = failure.message.match(MISSING_KEY)
127
+
128
+ return super unless missing
129
+
130
+ variable = VARIABLES.fetch(missing[:provider], "the provider's key")
131
+
132
+ "#{super.delete_suffix("[cut]")}API key (set #{variable} in your environment or in DSPyRb.config.env)"
133
+ end
134
+ end
135
+ end
@@ -0,0 +1,53 @@
1
+ # frozen_string_literal: true
2
+
3
+ module DSPyRb
4
+ # DSPy's Evaluate: DSPyRb::Evaluate[devset:, metric:, num_threads: 8].call(program), run by DSPy in Python.
5
+ class Evaluate
6
+ extend Dry::Initializer
7
+
8
+ param :devset, Values::Types::Examples, reader: :private
9
+ param :metric, Values::Types::Metric, reader: :private
10
+
11
+ # As `[]` makes them.
12
+ param :options, proc { |given, evaluate| taken_options(given, evaluate.class) }, reader: :private
13
+
14
+ # Each of DSPy's options by its name; nil leaves DSPy's default.
15
+ def self.[](devset:, metric: nil, **options)
16
+ new(devset, metric, Wire::Departure.taken(Wire::EvaluateOptions, options.compact, name))
17
+ end
18
+
19
+ # Options given to `new` of `made`, any other refused by the place alone.
20
+ def self.taken_options(given, made)
21
+ Wire::Departure.taken(Wire::Types.Instance(Wire::EvaluateOptions), given, "#{made.name}.new")
22
+ end
23
+
24
+ private_class_method :taken_options
25
+
26
+ # DSPy's EvaluationResult for a DSPyRb::Predict, ChainOfThought, ReAct or Module; DSPy applies its overrides.
27
+ def call(program, metric: nil, devset: nil, **overrides)
28
+ evaluation = Execution::Evaluation.new(scoring(metric || self.metric), devset: devset || self.devset)
29
+
30
+ overrides = Wire::Departure.taken(Wire::EvaluateOverrides, overrides.compact, "#{self.class.name}#call")
31
+
32
+ evaluation.evaluate(program, predictor(program), options, overrides)
33
+ end
34
+
35
+ private
36
+
37
+ # DSPy's own metric, told by its exact class since a subclass may override call, runs in Python; others are Ruby's.
38
+ def scoring(metric)
39
+ metric.instance_of?(Metric) ? metric.description : metric
40
+ end
41
+
42
+ # The description Python builds a predictor from; none for a Module, which Python calls back.
43
+ def predictor(program)
44
+ case program
45
+ when Predict then program.predictor
46
+ when Module then nil
47
+ else
48
+ raise Error,
49
+ "#{self.class.name}#call scores a DSPyRb::Predict, its kinds or a Module, not #{Error.class_of(program)}"
50
+ end
51
+ end
52
+ end
53
+ end
@@ -0,0 +1,61 @@
1
+ # frozen_string_literal: true
2
+
3
+ module DSPyRb
4
+ # One of DSPy's own metrics, which Python builds from its description and runs: DSPyRb::Metric.semantic_f1.
5
+ class Metric
6
+ extend Dry::Initializer
7
+
8
+ # What Python builds it from: the metric's name and DSPy's options for it; a refusal names the class being made.
9
+ param :description, proc { |given, metric| described(given, metric.class) }
10
+
11
+ # dspy/evaluate/metrics.py:285; nil leaves DSPy's default, as for each option below.
12
+ def self.answer_exact_match(frac: nil)
13
+ built("answer_exact_match", frac:)
14
+ end
15
+
16
+ # dspy/evaluate/metrics.py:320
17
+ def self.answer_passage_match
18
+ built("answer_passage_match")
19
+ end
20
+
21
+ # DSPy's SemanticF1 (dspy/evaluate/auto_evaluation.py:50).
22
+ def self.semantic_f1(threshold: nil, decompositional: nil)
23
+ built("semantic_f1", threshold:, decompositional:)
24
+ end
25
+
26
+ # DSPy's CompleteAndGrounded (dspy/evaluate/auto_evaluation.py:109).
27
+ def self.complete_and_grounded(threshold: nil)
28
+ built("complete_and_grounded", threshold:)
29
+ end
30
+
31
+ # dspy/datasets/gsm8k.py:79
32
+ def self.gsm8k_metric
33
+ built("gsm8k_metric")
34
+ end
35
+
36
+ # dspy/datasets/math.py:27-33
37
+ def self.math_metric
38
+ built("math_metric")
39
+ end
40
+
41
+ def self.built(metric, **options)
42
+ new(Wire::Departure.taken(Wire::Metric, { name: metric, **options.compact }, "#{self}.#{metric}"))
43
+ end
44
+
45
+ # The description `new` takes; anything else is its builders'.
46
+ def self.described(given, made)
47
+ return given if given.is_a?(Wire::Metric)
48
+
49
+ raise Error,
50
+ "#{made}.new takes the description Python builds it from: make one with the builder named for DSPy's " \
51
+ "metric, such as #{made}.semantic_f1"
52
+ end
53
+
54
+ private_class_method :built, :described
55
+
56
+ # DSPy's score: a value, or a Prediction carrying what its judge calls spent.
57
+ def call(example, prediction)
58
+ Execution::Evaluation.new(description).measure(example, prediction)
59
+ end
60
+ end
61
+ end
@@ -0,0 +1,63 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "English"
4
+
5
+ module DSPyRb
6
+ module Execution
7
+ # One of a context's around hooks, running the code the gem runs for the caller on a thread of its own.
8
+ class Around
9
+ extend Dry::Initializer
10
+
11
+ param :hook, Wire::Types.Interface(:call), reader: :private
12
+ option :runs, default: proc { 0 }, reader: :private
13
+ option :value, default: proc {}, reader: :private
14
+ option :returned, default: proc { false }, reader: :private
15
+
16
+ class << self
17
+ # What the block gives, run inside every hook, the outermost first; a hook that rescued it gives its own.
18
+ def run(hooks, &block)
19
+ hooks.reverse.reduce(block) { |inner, hook| -> { new(hook).call(&inner) } }.call
20
+ end
21
+
22
+ # As run, but what the block raised, of any kind, is raised though a hook rescued it, as a gate's refusal is.
23
+ def guarded(hooks)
24
+ raised = nil
25
+
26
+ value = run(hooks) do
27
+ given = yield
28
+ kept = true
29
+
30
+ given
31
+ ensure
32
+ raised = $ERROR_INFO unless kept
33
+ end
34
+
35
+ raise raised if raised
36
+
37
+ value
38
+ end
39
+ end
40
+
41
+ # The block runs exactly once, else the code fails.
42
+ def call(&)
43
+ given = hook.call { once(&) }
44
+
45
+ raise Error, "an around hook did not run its block" if runs.zero?
46
+ raise Error, "an around hook ran its block twice" if runs > 1
47
+
48
+ returned ? value : given
49
+ end
50
+
51
+ private
52
+
53
+ def once
54
+ raise Error, "an around hook ran its block twice" if (@runs += 1) > 1
55
+
56
+ @value = yield
57
+ @returned = true
58
+
59
+ value
60
+ end
61
+ end
62
+ end
63
+ end