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,120 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "digest"
4
+
5
+ module DSPyRb
6
+ module Setup
7
+ # The locked Python environment, and `ruby-on-dspy setup`.
8
+ module Environment
9
+ PROJECT = File.expand_path("../../../python", __dir__)
10
+
11
+ # Each optional group of python/pyproject.toml, by the packages it adds, which setup installs only when asked.
12
+ GROUPS = { "data" => %w[datasets math_equivalence] }.freeze
13
+
14
+ class << self
15
+ def root
16
+ DSPyRb.config.environment
17
+ end
18
+
19
+ def python_folder
20
+ File.join(root, "python")
21
+ end
22
+
23
+ # One per gem folder too: Bundler checks out each git commit of the gem to a folder of its own.
24
+ def venv
25
+ File.join(root, VERSION, Digest::SHA256.hexdigest(PROJECT)[0, 12], "venv")
26
+ end
27
+
28
+ # A uv placed here beforehand serves offline.
29
+ def uv_path
30
+ File.join(root, "uv", Uv::RELEASE, "uv")
31
+ end
32
+
33
+ # Never built at runtime.
34
+ def python
35
+ path = File.join(venv, "bin", "python")
36
+
37
+ unless File.executable?(path)
38
+ raise SetupError,
39
+ "no ruby-on-dspy environment for #{PROJECT} at #{venv}: run `ruby-on-dspy setup` with this bundle " \
40
+ "(RUBY_ON_DSPY_ENVIRONMENT says where)"
41
+ end
42
+
43
+ return path if served == PROJECT
44
+
45
+ raise SetupError,
46
+ "the environment at #{venv} serves ruby-on-dspy from #{served || "nowhere"}, not #{PROJECT}: run " \
47
+ "`ruby-on-dspy setup`"
48
+ end
49
+
50
+ def setup(out: $stdout, releases: Uv::RELEASES, checksums: Uv::CHECKSUMS, groups: [])
51
+ refuse_unknown(groups)
52
+ uv = Uv.found(uv_path) || fetch_uv(releases, checksums, out)
53
+
54
+ out.puts("ruby-on-dspy setup: uv #{Uv.version(uv)} at #{uv}")
55
+ run(uv, "python", "install", "--no-bin", PYTHON_VERSION)
56
+ sync(uv, groups)
57
+ File.write(File.join(site_packages, "dspy_rb.pth"), "#{PROJECT}\n")
58
+ out.puts("ruby-on-dspy setup: the environment is at #{venv}, serving ruby-on-dspy from #{PROJECT}")
59
+ Stale.remove(root, built: venv, out:)
60
+ end
61
+
62
+ # Whether the environment holds each package `group` adds.
63
+ def installed?(group)
64
+ GROUPS.fetch(group).all? do |package|
65
+ Dir.glob(File.join("lib", "python*", "site-packages", "#{package}-*.dist-info"), base: venv).any?
66
+ end
67
+ end
68
+
69
+ private
70
+
71
+ def refuse_unknown(groups)
72
+ unknown = groups - GROUPS.keys
73
+
74
+ raise SetupError, "no group #{unknown.join(", ")}: #{GROUPS.keys.join(", ")} can be added" if unknown.any?
75
+ end
76
+
77
+ # Compiled as installed: Python warns of math_equivalence's invalid escape the first time it compiles it.
78
+ def sync(program, groups)
79
+ asked = groups.flat_map { ["--group", _1] }
80
+
81
+ run(program, "sync", "--locked", "--no-default-groups", *asked, "--compile-bytecode", "--project", PROJECT)
82
+ end
83
+
84
+ def fetch_uv(releases, checksums, out)
85
+ out.puts("ruby-on-dspy setup: no uv #{Uv::RELEASE} or later on the PATH; fetching it from #{releases}")
86
+ Uv.fetch(releases, into: uv_path, checksums:)
87
+ end
88
+
89
+ def run(program, *arguments)
90
+ environment = {
91
+ "UV_PROJECT_ENVIRONMENT" => venv,
92
+ "UV_PYTHON_INSTALL_DIR" => python_folder,
93
+ # A managed CPython: the default would link the environment to whatever Python the machine has.
94
+ "UV_PYTHON_PREFERENCE" => "only-managed"
95
+ }
96
+
97
+ return if system(environment, program, *arguments)
98
+
99
+ raise SetupError, "`uv #{arguments.join(" ")}` failed; its output above says why"
100
+ end
101
+
102
+ # Found from the venv, as the root's own path may read as a pattern.
103
+ def site_packages
104
+ found = Dir.glob(File.join("lib", "python*", "site-packages"), base: venv).first
105
+
106
+ raise SetupError, "uv made no site-packages under #{venv}" unless found
107
+
108
+ File.join(venv, found)
109
+ end
110
+
111
+ # The gem folder the environment's dspy_rb.pth names, a guard on the folder the venv's path is keyed by.
112
+ def served
113
+ pth = File.join(site_packages, "dspy_rb.pth")
114
+
115
+ File.read(pth).chomp if File.exist?(pth)
116
+ end
117
+ end
118
+ end
119
+ end
120
+ end
@@ -0,0 +1,102 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "fileutils"
4
+ require "find"
5
+
6
+ module DSPyRb
7
+ module Setup
8
+ # Environments whose gem copy is gone, which setup removes; the app never does.
9
+ module Stale
10
+ # The one line setup writes: an absolute folder, with no NUL and no second line.
11
+ NAMED = %r{\A/[^\0\n]*\z}
12
+
13
+ # A removed Ruby or app takes that folder with it, but so does an unmounted volume.
14
+ HOLDER_GONE = "the folder that held its gem is gone; delete it if that Ruby or app is gone for good"
15
+
16
+ class << self
17
+ def remove(root, built:, out:)
18
+ Dir.glob("*/*", base: root).each do |path|
19
+ folder = File.join(root, path)
20
+
21
+ # The old layout keeps its venv right in the version folder.
22
+ venv = path.end_with?("/venv") ? folder : File.join(folder, "venv")
23
+
24
+ sweep(folder, venv, out) if venv != built && removable?(folder)
25
+ # Another setup removed it first, or is building beside it.
26
+ rescue Errno::ENOENT, Errno::ENOTEMPTY
27
+ next
28
+ rescue SystemCallError => e
29
+ kept(out, folder, SystemCallError.new(nil, e.errno).message)
30
+ end
31
+ end
32
+
33
+ private
34
+
35
+ def sweep(folder, venv, out)
36
+ named = served(venv)
37
+
38
+ return unless named
39
+ return kept(out, folder, "its dspy_rb.pth names no absolute folder") unless named.match?(NAMED)
40
+ return unless gone?(named)
41
+ return kept(out, folder, HOLDER_GONE) unless held?(named)
42
+
43
+ megabytes = megabytes(folder)
44
+
45
+ # Checked again, as a setup may have put the gem copy back meanwhile.
46
+ return unless served(venv) == named && stale?(named)
47
+
48
+ FileUtils.rm_r(folder)
49
+ out.puts("ruby-on-dspy setup: removed #{folder} (#{megabytes} MB of files)")
50
+ tidy(File.dirname(folder))
51
+ end
52
+
53
+ # Left as it is when another setup builds in it meanwhile, or it cannot be removed.
54
+ def tidy(version)
55
+ Dir.rmdir(version) if Dir.empty?(version)
56
+ rescue SystemCallError
57
+ nil
58
+ end
59
+
60
+ def kept(out, folder, reason)
61
+ out.puts("ruby-on-dspy setup: kept #{folder}: #{reason}")
62
+ end
63
+
64
+ # A version folder's own, so never the shared CPython or uv; a symlink may lead out of the root.
65
+ def removable?(folder)
66
+ parent = File.dirname(folder)
67
+
68
+ Gem::Version.correct?(File.basename(parent)) && [folder, parent].none? { File.symlink?(_1) }
69
+ end
70
+
71
+ # None while a setup is still building the environment.
72
+ def served(venv)
73
+ pth = Dir.glob("lib/python*/site-packages/dspy_rb.pth", base: venv).first
74
+
75
+ File.binread(File.join(venv, pth)).chomp if pth
76
+ end
77
+
78
+ # Only "no such file" is gone; any other error keeps the environment.
79
+ def gone?(named)
80
+ File.stat(named)
81
+ false
82
+ rescue Errno::ENOENT
83
+ true
84
+ end
85
+
86
+ # The folder that held the gem copy, as `named` is the copy's python folder.
87
+ def held?(named)
88
+ File.directory?(File.dirname(named, 2))
89
+ end
90
+
91
+ def stale?(named)
92
+ gone?(named) && held?(named)
93
+ end
94
+
95
+ # The files' total; uv links or clones them from its cache, so less may come free (`uv help sync`).
96
+ def megabytes(folder)
97
+ Find.find(folder).map { File.lstat(_1) }.select(&:file?).sum(&:size) / 1_000_000
98
+ end
99
+ end
100
+ end
101
+ end
102
+ end
@@ -0,0 +1,122 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "digest"
4
+ require "fileutils"
5
+ require "net/http"
6
+ require "open-uri"
7
+ require "open3"
8
+ require "openssl"
9
+ require "timeout"
10
+ require "rbconfig"
11
+ require "rubygems/package"
12
+ require "stringio"
13
+ require "zlib"
14
+
15
+ module DSPyRb
16
+ module Setup
17
+ # The uv that builds the environment; the user's own install is never touched.
18
+ module Uv
19
+ RELEASE = "0.9.5"
20
+
21
+ # uv's installation docs, GitHub Releases.
22
+ RELEASES = "https://github.com/astral-sh/uv/releases/download"
23
+
24
+ # Each archive's SHA-256, pinned with the gem so a replaced release asset is refused; each matched its .sha256.
25
+ CHECKSUMS = {
26
+ "aarch64-apple-darwin" => "dc098ff224d78ed418e121fd374f655949d2c7031a70f6f6604eaf016a130433",
27
+ "x86_64-apple-darwin" => "58b1d4a25aa8ff99147c2550b33dcf730207fe7e0f9a0d5d36a1bbf36b845aca",
28
+ "aarch64-unknown-linux-gnu" => "9db0c2f6683099f86bfeea47f4134e915f382512278de95b2a0e625957594ff3",
29
+ "x86_64-unknown-linux-gnu" => "2cf10babba653310606f8b49876cfb679928669e7ddaa1fb41fb00ce73e64f66",
30
+ "aarch64-unknown-linux-musl" => "42b9b83933a289fe9c0e48f4973dee49ce0dfb95e19ea0b525ca0dbca3bce71f",
31
+ "x86_64-unknown-linux-musl" => "3665ffb6c429c31ad6c778ac0489b7746e691acf025cf530b3510b2f9b1660ff"
32
+ }.freeze
33
+ OPEN_TIMEOUT = 30
34
+ READ_TIMEOUT = 120
35
+
36
+ # What a fetch can fail with short of an answer: DNS, a refused or reset connection, TLS, a timeout.
37
+ UNREACHED = [
38
+ SocketError,
39
+ SystemCallError,
40
+ IOError,
41
+ Timeout::Error,
42
+ OpenSSL::SSL::SSLError,
43
+ Net::ProtocolError,
44
+ OpenURI::HTTPRedirect
45
+ ].freeze
46
+
47
+ class << self
48
+ def found(managed)
49
+ on_path = ENV.fetch("PATH", "").split(File::PATH_SEPARATOR).map { File.join(_1, "uv") }.find { File.executable?(_1) }
50
+ version = on_path && version(on_path)
51
+
52
+ return on_path if version && Gem::Version.new(version) >= Gem::Version.new(RELEASE)
53
+
54
+ managed if File.executable?(managed)
55
+ end
56
+
57
+ def version(program)
58
+ output, status = Open3.capture2(program, "--version")
59
+
60
+ output[/\d+\.\d+\.\d+/] if status.success?
61
+ end
62
+
63
+ def fetch(releases, into:, checksums: CHECKSUMS)
64
+ pinned = checksums.fetch(target) do
65
+ raise SetupError, "ruby-on-dspy pins no uv #{RELEASE} binary for #{target}"
66
+ end
67
+
68
+ archive = "#{releases}/#{RELEASE}/uv-#{target}.tar.gz"
69
+ tarball = download(archive)
70
+
71
+ unless Digest::SHA256.hexdigest(tarball) == pinned
72
+ raise SetupError, "#{archive} is not the uv #{RELEASE} this gem pins: its checksum differs"
73
+ end
74
+
75
+ install(unpack(tarball, "uv-#{target}/uv"), into)
76
+ end
77
+
78
+ private
79
+
80
+ def target
81
+ cpu = RbConfig::CONFIG["host_cpu"].sub(/\Aarm64\z/, "aarch64")
82
+
83
+ case RbConfig::CONFIG["host_os"]
84
+ when /darwin/ then "#{cpu}-apple-darwin"
85
+ when /linux/ then "#{cpu}-unknown-linux-#{Dir.glob("/lib/ld-musl-*").empty? ? "gnu" : "musl"}"
86
+ else raise SetupError, "uv publishes no binary ruby-on-dspy can use on #{RbConfig::CONFIG["host_os"]}"
87
+ end
88
+ end
89
+
90
+ # open-uri follows GitHub's redirects to where a release's files are kept.
91
+ def download(url)
92
+ URI(url).open(open_timeout: OPEN_TIMEOUT, read_timeout: READ_TIMEOUT, &:read)
93
+ rescue OpenURI::HTTPError => e
94
+ raise SetupError, "#{url} answered #{e.message}"
95
+ rescue *UNREACHED => e
96
+ raise SetupError, "#{url} could not be fetched (#{e.class}: #{e.message})"
97
+ end
98
+
99
+ def unpack(tarball, name)
100
+ entry = Gem::Package::TarReader.new(Zlib::GzipReader.new(StringIO.new(tarball))).find { _1.full_name == name }
101
+
102
+ raise SetupError, "the uv archive holds no #{name}" unless entry
103
+
104
+ entry.read
105
+ rescue Zlib::Error, Gem::Package::Error, EOFError => e
106
+ raise SetupError, "the uv archive cannot be read (#{e.class}: #{e.message})"
107
+ end
108
+
109
+ # Written beside its place, then renamed into it, so a failed fetch leaves no half binary.
110
+ def install(binary, path)
111
+ FileUtils.mkdir_p(File.dirname(path))
112
+ File.binwrite("#{path}.partial", binary)
113
+ File.chmod(0o755, "#{path}.partial")
114
+ File.rename("#{path}.partial", path)
115
+ path
116
+ rescue SystemCallError => e
117
+ raise SetupError, "uv could not be placed at #{path} (#{e.class}: #{e.message})"
118
+ end
119
+ end
120
+ end
121
+ end
122
+ end
@@ -0,0 +1,100 @@
1
+ # frozen_string_literal: true
2
+
3
+ module DSPyRb
4
+ # A DSPy signature declared in Ruby.
5
+ class Signature
6
+ NAME = /\A[A-Za-z_][A-Za-z0-9_]*\z/
7
+
8
+ # Python 3.12's keywords (keyword.kwlist), which no Python field or parameter may be named.
9
+ KEYWORDS = <<~NAMES.split.freeze
10
+ False None True and as assert async await break class continue def del elif else except finally for from global
11
+ if import in is lambda nonlocal not or pass raise return try while with yield
12
+ NAMES
13
+
14
+ class << self
15
+ def inherited(subclass)
16
+ super
17
+ subclass.instance_variable_set(:@fields, fields.dup)
18
+ subclass.instance_variable_set(:@instructions, instructions)
19
+ end
20
+
21
+ def instructions(text = nil)
22
+ return @instructions if text.nil?
23
+ raise Error, "#{self}.instructions takes text, not #{Error.class_of(text)}" unless text.is_a?(::String)
24
+
25
+ @instructions = text
26
+ end
27
+
28
+ def input(name, type = nil, desc: nil)
29
+ declare(name, "input", type, desc, "#{self}.input")
30
+ end
31
+
32
+ def output(name, type = nil, desc: nil)
33
+ declare(name, "output", type, desc, "#{self}.output")
34
+ end
35
+
36
+ def fields
37
+ (@fields || []).dup.freeze
38
+ end
39
+
40
+ # Names only, refused as a whole for the builder at `place`: a typed or described field takes the class form.
41
+ def parse(text, place)
42
+ inputs, outputs, *rest = text.split("->", -1).map { |side| side.split(",").map(&:strip).reject(&:empty?) }
43
+
44
+ unless outputs && rest.empty? && [*inputs, *outputs].all? { _1.match?(NAME) }
45
+ raise Error,
46
+ "#{place} takes a signature's string form as \"inputs -> outputs\", of names alone: a typed or " \
47
+ "described field takes the class form"
48
+ end
49
+
50
+ # Each field refused naming the builder, never the class made here, which has no name.
51
+ Class.new(self) do
52
+ inputs.each { declare(_1, "input", nil, nil, place) }
53
+
54
+ outputs.each { declare(_1, "output", nil, nil, place) }
55
+ end
56
+ end
57
+
58
+ # A field's or tool argument's name refused at `place`; only a keyword is quoted, as another may be any value.
59
+ def refuse_name(name, place, noun)
60
+ unless name.match?(NAME)
61
+ raise Error, "#{place} takes a name of letters, digits and underscores, not starting with a digit"
62
+ end
63
+
64
+ raise Error, "#{place} takes no #{noun} named #{name}, a Python keyword" if KEYWORDS.include?(name)
65
+ end
66
+
67
+ # The signature the builder at `place` was given, a class or its string form.
68
+ def for(signature, place)
69
+ return parse(signature, place) if signature.is_a?(::String)
70
+ return signature if signature.is_a?(::Class) && signature <= Signature
71
+
72
+ raise Error,
73
+ "#{place} takes a signature as a DSPyRb::Signature class or its string form, not " \
74
+ "#{Error.class_of(signature)}"
75
+ end
76
+
77
+ private
78
+
79
+ # A field declared at `place`, which a refusal names.
80
+ def declare(name, role, type, desc, place)
81
+ name = name.to_s
82
+
83
+ refuse_name(name, place, "field")
84
+ raise Error, "#{place} takes no second field named #{name}" if fields.any? { _1.name == name }
85
+
86
+ refuse_hidden(name, place) if role == "output"
87
+ Values::Types.refuse_reserved({ name => nil }, place) if role == "input"
88
+
89
+ field = { name:, role:, type: type && Types.annotation(type, place), desc: }.compact
90
+
91
+ (@fields ||= []) << Wire::Departure.taken(Wire::Field, field, place)
92
+ end
93
+
94
+ # Refused as it is declared, by the rule every Prediction keeps.
95
+ def refuse_hidden(name, place)
96
+ Values::Types.shown({ name => nil }, Prediction, "an output", remedy: "name it otherwise in #{place}")
97
+ end
98
+ end
99
+ end
100
+ end
@@ -0,0 +1,44 @@
1
+ # frozen_string_literal: true
2
+
3
+ module DSPyRb
4
+ # The types a signature's fields may name, each as the Python annotation DSPy parses.
5
+ module Types
6
+ # True or false.
7
+ module Boolean; end
8
+
9
+ List = Values::List
10
+ Dict = Values::Dict
11
+ Optional = Values::Optional
12
+ Literal = Values::Literal
13
+
14
+ ANNOTATIONS = {
15
+ ::String => "str",
16
+ ::Integer => "int",
17
+ ::Float => "float",
18
+ Boolean => "bool"
19
+ }.freeze
20
+
21
+ class << self
22
+ # The annotation of a type given at `place`, the declaration a refusal names.
23
+ def annotation(type, place)
24
+ ANNOTATIONS.fetch(type) { composite(type, place) }
25
+ end
26
+
27
+ private
28
+
29
+ def composite(type, place)
30
+ case type
31
+ when List then "list[#{annotation(type.of, place)}]"
32
+ when Dict then "dict[#{annotation(type.key, place)}, #{annotation(type.value, place)}]"
33
+ when Optional then "Optional[#{annotation(type.of, place)}]"
34
+ when Literal then "Literal[#{type.values.map { JSON.generate(_1) }.join(", ")}]"
35
+ else
36
+ # A class by its name, as code names it; any other object by its class alone.
37
+ raise Error,
38
+ "#{place} takes a type that is String, Integer, Float, Types::Boolean, or a List, Dict, Optional or " \
39
+ "Literal of those, not #{type.is_a?(::Module) ? type : Error.class_of(type)}"
40
+ end
41
+ end
42
+ end
43
+ end
44
+ end
@@ -0,0 +1,64 @@
1
+ # frozen_string_literal: true
2
+
3
+ module DSPyRb
4
+ # A Module's Ruby source, as MIPROv2's proposer reads a Python one's (dspy/propose/utils.py:146-188).
5
+ module Source
6
+ # A key by its provider's prefix, holding a digit, so words such as key-value stay.
7
+ KEY = /(?i)\b(?:(?:sk|key)[-_]|aiza)(?=[A-Za-z0-9_\-*.]*\d)[A-Za-z0-9_\-*.]{4,}/
8
+
9
+ # Its signatures and sub-modules, then its own class, joined as DSPy joins them; none where its own can't be read.
10
+ def self.text(program)
11
+ own = read(program.class)
12
+ header = (classes(program).uniq - [program.class]).filter_map { read(_1) }
13
+
14
+ "#{header.join("\n\n")}\n\n#{own}" if own
15
+ end
16
+
17
+ # Each part's signature, or a sub-module's classes, its parts' before its own, as DSPy recurses.
18
+ def self.classes(program)
19
+ held = Parts.new(program).to_enum(:walk).filter_map { |path, part| part unless path.include?(".") }
20
+
21
+ held.flat_map { _1.is_a?(Module) ? [*classes(_1), _1.class] : [_1.instance_variable_get(:@signature)] }
22
+ end
23
+
24
+ # A class as its file defines it, in UTF-8, its keys hidden; none for one made by Class.new, or whose file is gone.
25
+ def self.read(klass)
26
+ file, line = klass&.name && Object.const_source_location(klass.name)
27
+
28
+ return unless file && File.file?(file)
29
+
30
+ found = nodes(Prism.parse_file(file).value).find { defines?(_1, klass, line) }
31
+
32
+ hidden(found.slice.encode(Encoding::UTF_8, invalid: :replace, undef: :replace)) if found
33
+ end
34
+
35
+ def self.defines?(node, klass, line)
36
+ node.is_a?(Prism::ClassNode) && node.location.start_line == line && node.name.to_s == klass.name.split("::").last
37
+ end
38
+
39
+ # A class's text, each string and comment in it hidden as `hide` hides it, the last first so offsets hold.
40
+ def self.hidden(text)
41
+ parsed = Prism.parse(text)
42
+ spots = nodes(parsed.value).grep(Prism::StringNode).map(&:content_loc) + parsed.comments.map(&:location)
43
+
44
+ spots.sort_by { -_1.start_offset }.each_with_object(text.dup) { |spot, shown| hide(spot, text, shown) }
45
+ end
46
+
47
+ # A string after a name that may hold a key, as in `api_key = "..."`, hidden whole; else its prefixed keys alone.
48
+ def self.hide(spot, text, shown)
49
+ named = text.byteslice([spot.start_offset - 64, 0].max...spot.start_offset).scrub[/([\w-]+)\W*\z/, 1].to_s
50
+ kept = Secrets::NAME.match?(named) ? Secrets::HIDDEN : spot.slice.gsub(KEY, Secrets::HIDDEN)
51
+
52
+ shown.bytesplice(spot.start_offset, spot.length, kept)
53
+ end
54
+
55
+ # A node and each node under it, in the order they're written.
56
+ def self.nodes(node)
57
+ [node, *node.compact_child_nodes.flat_map { nodes(_1) }]
58
+ end
59
+
60
+ private_class_method :classes, :read, :defines?, :hidden, :hide, :nodes
61
+ end
62
+
63
+ private_constant :Source
64
+ end
@@ -0,0 +1,9 @@
1
+ # frozen_string_literal: true
2
+
3
+ module DSPyRb
4
+ # DSPy's BootstrapFewShot, demos from the teacher's runs the metric passes: DSPyRb::BootstrapFewShot[metric:].
5
+ class BootstrapFewShot < Optimizer
6
+ OPTIONS = Wire::BootstrapFewShotOptions
7
+ COMPILING = Wire::BootstrapFewShotCompile
8
+ end
9
+ end
@@ -0,0 +1,9 @@
1
+ # frozen_string_literal: true
2
+
3
+ module DSPyRb
4
+ # DSPy's BootstrapFewShotWithOptuna, picking bootstrapped demos by trials: compile(program, trainset:, max_demos:).
5
+ class BootstrapFewShotWithOptuna < Optimizer
6
+ OPTIONS = Wire::BootstrapFewShotWithOptunaOptions
7
+ COMPILING = Wire::BootstrapFewShotWithOptunaCompile
8
+ end
9
+ end
@@ -0,0 +1,9 @@
1
+ # frozen_string_literal: true
2
+
3
+ module DSPyRb
4
+ # DSPy's BootstrapFewShotWithRandomSearch, keeping the best on the valset of several bootstrapped sets of demos.
5
+ class BootstrapFewShotWithRandomSearch < Optimizer
6
+ OPTIONS = Wire::BootstrapFewShotWithRandomSearchOptions
7
+ COMPILING = Wire::BootstrapFewShotWithRandomSearchCompile
8
+ end
9
+ end
@@ -0,0 +1,9 @@
1
+ # frozen_string_literal: true
2
+
3
+ module DSPyRb
4
+ # DSPy's GEPA, which evolves each predictor's instructions from the metric's feedback: DSPyRb::GEPA[metric:, auto:].
5
+ class GEPA < Optimizer
6
+ OPTIONS = Wire::GEPAOptions
7
+ COMPILING = Wire::GEPACompile
8
+ end
9
+ end
@@ -0,0 +1,14 @@
1
+ # frozen_string_literal: true
2
+
3
+ module DSPyRb
4
+ # DSPy's LabeledFewShot, demos drawn from the trainset, no model called: DSPyRb::LabeledFewShot[k: 4].compile(...).
5
+ class LabeledFewShot < Optimizer
6
+ OPTIONS = Wire::LabeledFewShotOptions
7
+ COMPILING = Wire::LabeledFewShotCompile
8
+
9
+ private
10
+
11
+ # It calls no model, so each row is a demo, never a call's inputs (dspy/teleprompt/vanilla.py:10-25).
12
+ def refuse_reserved(*); end
13
+ end
14
+ end
@@ -0,0 +1,16 @@
1
+ # frozen_string_literal: true
2
+
3
+ module DSPyRb
4
+ # DSPy's MIPROv2, which proposes instructions and picks them with demos by trials: DSPyRb::MIPROv2[metric:, auto:].
5
+ class MIPROv2 < Optimizer
6
+ OPTIONS = Wire::MIPROv2Options
7
+ COMPILING = Wire::MIPROv2Compile
8
+
9
+ private
10
+
11
+ # A Module's source, as its program-aware proposer reads a Python one's (dspy/propose/grounded_proposer.py:284-291).
12
+ def source(student, compiling)
13
+ Source.text(student) if student.is_a?(Module) && compiling.program_aware_proposer != false
14
+ end
15
+ end
16
+ end