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,369 @@
1
+ """The server: hello and describe answered as each arrives, calls on the pool, nested calls on their waiting thread."""
2
+
3
+ import dataclasses
4
+ import platform
5
+ from concurrent.futures import ThreadPoolExecutor
6
+ from dataclasses import KW_ONLY, dataclass, field
7
+ from functools import cached_property
8
+ from typing import Final, assert_never, cast
9
+
10
+ import dspy
11
+ from dspy.propose import grounded_proposer
12
+ from dspy.teleprompt import simba_utils
13
+
14
+ from dspy_rb.server import build, calls, conversion, data, evaluation, facts, optimization, standins, state, traffic
15
+ from dspy_rb.server.pulse import Pulse
16
+ from dspy_rb.server.ruby import Lost, Ruby, RubyAbort
17
+ from dspy_rb.server.traffic import Exchange, Halted, Traffic
18
+ from dspy_rb.values import Malformed, Mismatch
19
+ from dspy_rb.wire import lines
20
+ from dspy_rb.wire.channel import Channel
21
+ from dspy_rb.wire.shapes import (
22
+ CALLED,
23
+ COUNTED,
24
+ LM,
25
+ PACKAGE,
26
+ PROTOCOL,
27
+ Called,
28
+ CallRequest,
29
+ Cancel,
30
+ Cancelled,
31
+ Compile,
32
+ Compiled,
33
+ Completed,
34
+ Describe,
35
+ Described,
36
+ DescribeLM,
37
+ DescribeTool,
38
+ DummyLM,
39
+ Evaluate,
40
+ Evaluated,
41
+ Failed,
42
+ FromRuby,
43
+ Generate,
44
+ Generated,
45
+ Hello,
46
+ LMDescribed,
47
+ Load,
48
+ LoadState,
49
+ Measure,
50
+ Measured,
51
+ Permute,
52
+ Pooled,
53
+ Raised,
54
+ Refused,
55
+ Reply,
56
+ Request,
57
+ Returned,
58
+ SaveState,
59
+ ToolDescribed,
60
+ Unfit,
61
+ Welcome,
62
+ )
63
+
64
+ # DSPy's own num_threads (dspy/dsp/utils/settings.py:31).
65
+ DEFAULT_THREADS: Final = 8
66
+
67
+ # Ruby's own answers to a callback, whose id is Python's.
68
+ ANSWERS: Final = ("returned", "raised")
69
+
70
+
71
+ @dataclass
72
+ class Server:
73
+ """Answers one channel's requests until the end of its input."""
74
+
75
+ channel: Channel
76
+ _: KW_ONLY
77
+ threads: int = DEFAULT_THREADS
78
+ _lms: build.LMTable = field(init=False, default_factory=build.LMTable)
79
+ _traffic: Traffic = field(init=False, default_factory=Traffic)
80
+ _fatal: BaseException | None = field(init=False, default=None)
81
+
82
+ # Set once the server stops taking requests for a fault: a call still queued then never starts.
83
+ _closing: bool = field(init=False, default=False)
84
+
85
+ @cached_property
86
+ def _pool(self) -> ThreadPoolExecutor:
87
+ return ThreadPoolExecutor(self.threads, thread_name_prefix="dspy_rb")
88
+
89
+ @cached_property
90
+ def _pulse(self) -> Pulse:
91
+ return Pulse.started(self.channel, self._traffic)
92
+
93
+ @cached_property
94
+ def _gate(self) -> standins.Gate:
95
+ return standins.gate(self.ruby)
96
+
97
+ @cached_property
98
+ def ruby(self) -> Ruby:
99
+ """The Ruby side, as DSPy's code calls back to it: each nested request served on the thread that waits."""
100
+ return Ruby(self.channel, self._traffic, serve=self._respond)
101
+
102
+ def run(self) -> None:
103
+ """Answer each request until the end of input, raising a BaseException a call raised."""
104
+ calls.install()
105
+
106
+ # Where MIPROv2's program-aware proposer reads a program's source (dspy/propose/grounded_proposer.py:286).
107
+ setattr(grounded_proposer, "get_dspy_source_code", standins.source_code) # noqa: B010 - a module's function.
108
+
109
+ # Where SIMBA's rule strategy reads a program's class source (dspy/teleprompt/simba_utils.py:144).
110
+ setattr(simba_utils, "inspect", standins.INSPECT) # noqa: B010 - a module's import.
111
+
112
+ # Started before the first line, and stopped at the end of input, when Ruby waits for nothing more.
113
+ pulse = self._pulse
114
+
115
+ try:
116
+ for line in self.channel.lines():
117
+ received = lines.read(line)
118
+
119
+ if isinstance(received, Malformed):
120
+ self._refuse(received)
121
+ else:
122
+ self._take(received)
123
+ finally:
124
+ pulse.stop()
125
+
126
+ self.ruby.lose()
127
+
128
+ if self._fatal is not None:
129
+ raise self._fatal
130
+
131
+ def drain(self, *, cancel: bool = False) -> None:
132
+ """Wait for the calls running, which write their replies; with `cancel`, the calls queued never start."""
133
+ self._closing = self._closing or cancel
134
+ self._pool.shutdown(wait=True, cancel_futures=self._closing)
135
+
136
+ def _take(self, message: FromRuby) -> None:
137
+ match message:
138
+ case Returned() | Raised():
139
+ # One whose thread stopped waiting, for a cancel, is dropped.
140
+ self.ruby.deliver(message.id, message)
141
+ case Cancel(of=of):
142
+ self._traffic.cancel(of)
143
+ self.ruby.wake()
144
+ case Hello() | Describe() | DescribeTool() | DescribeLM() | Permute():
145
+ self._respond(message, self._traffic.open(message))
146
+ case _:
147
+ self._pooled(message)
148
+
149
+ def _pooled(self, request: Pooled) -> None:
150
+ if request.within is None:
151
+ self._pool.submit(self._call, request, self._traffic.open(request))
152
+ elif not self.ruby.nest(request.within, request):
153
+ reason = f"no callback {request.within} is waiting"
154
+
155
+ self.channel.write(lines.line_or_raise(Refused(id=request.id, reason=reason)))
156
+
157
+ def _refuse(self, invalid: Malformed) -> None:
158
+ # An answer Ruby could not write whole names a callback of Python's, never a request of Ruby's.
159
+ if invalid.kind in ANSWERS and invalid.reply.id is not None:
160
+ self.ruby.fail(invalid.reply.id, invalid.reply.reason)
161
+ elif invalid.kind != "cancel":
162
+ self.channel.write(lines.line_or_raise(invalid.reply))
163
+
164
+ def _call(self, request: Pooled, exchange: Exchange) -> None:
165
+ if self._closing:
166
+ self._traffic.finish(exchange)
167
+ return
168
+
169
+ try:
170
+ self._respond(request, exchange)
171
+ except BaseException as fatal: # noqa: BLE001 - it ends the server, and run raises it.
172
+ self._fatal = self._fatal or fatal
173
+ self._closing = True
174
+ self.channel.stop()
175
+
176
+ def _respond(self, request: Request, exchange: Exchange) -> BaseException | None:
177
+ gate = self._gate if isinstance(request, CALLED) and request.gated else None
178
+ recorder = facts.Recorder(self.channel, exchange, pulse=self._pulse, gate=gate)
179
+ reply, raised = self._reply(request, exchange, recorder)
180
+
181
+ # Answered before its reply is written: from then on nothing more starts for it.
182
+ self._traffic.finish(exchange)
183
+
184
+ if reply is not None:
185
+ with recorder.settled() as (unrecorded, running):
186
+ self.channel.write(_line(request.id, reply, unrecorded, running))
187
+
188
+ return raised
189
+
190
+ def _reply(
191
+ self,
192
+ request: Request,
193
+ exchange: Exchange,
194
+ recorder: facts.Recorder,
195
+ ) -> tuple[Reply | None, BaseException | None]:
196
+ try:
197
+ reply = self._handle(request, exchange, recorder)
198
+ except Lost as lost:
199
+ # Ruby has gone, so nothing is written.
200
+ return None, lost
201
+ except Halted as halted:
202
+ return Cancelled(id=request.id), halted
203
+ except lines.RefusedError as refusal:
204
+ return Refused(id=request.id, reason=str(refusal)), refusal
205
+ except state.UnfitError as unfit:
206
+ return Unfit(id=request.id, reason=str(unfit)), unfit
207
+ except (RubyAbort, Exception) as error: # noqa: BLE001 - a request that raised is answered as failed, with its class.
208
+ return Failed(id=request.id, error=facts.failure(error)), error
209
+
210
+ # Stopped still, though code it ran caught the Halted and went on: what it gave was cut short.
211
+ return (Cancelled(id=request.id) if exchange.stopped() else reply), None
212
+
213
+ def _handle(self, request: Request, exchange: Exchange, recorder: facts.Recorder) -> Reply:
214
+ reply: Reply
215
+
216
+ match request:
217
+ case Hello():
218
+ reply = self._welcome(request)
219
+ case Describe():
220
+ built = build.predictor(request.predictor, self.ruby)
221
+ reply = Described(id=request.id, instruction=facts.instruction(built.leaf))
222
+ case DescribeTool():
223
+ reply = self._tool(request)
224
+ case DescribeLM():
225
+ reply = LMDescribed(id=request.id, kwargs=build.kwargs(request.lm, self.ruby, request.id))
226
+ case CallRequest() | Evaluate() | Measure() | Generate() | Compile():
227
+ reply = self._called(request, exchange, recorder)
228
+ case SaveState():
229
+ reply = state.saved(request, self.ruby)
230
+ case LoadState():
231
+ reply = state.loaded(request, self.ruby)
232
+ case Load():
233
+ reply = data.load(request)
234
+ case Permute():
235
+ reply = data.permute(request)
236
+ case _:
237
+ assert_never(request)
238
+
239
+ return reply
240
+
241
+ # A request whose DSPy code may call a model, each under its own context.
242
+ def _called(self, request: Called, exchange: Exchange, recorder: facts.Recorder) -> Reply:
243
+ match request:
244
+ case CallRequest():
245
+ return self._complete(request, exchange, recorder)
246
+ case Evaluate():
247
+ return self._evaluate(request, exchange, recorder)
248
+ case Measure():
249
+ return self._measure(request, exchange, recorder)
250
+ case Generate():
251
+ return self._generate(request, exchange, recorder)
252
+ case Compile():
253
+ return self._compile(request, exchange, recorder)
254
+
255
+ assert_never(request)
256
+
257
+ def _welcome(self, request: Hello) -> Welcome:
258
+ return Welcome(
259
+ id=request.id,
260
+ protocol=PROTOCOL,
261
+ package=PACKAGE,
262
+ dspy=dspy.__version__,
263
+ python=platform.python_version(),
264
+ )
265
+
266
+ def _tool(self, request: DescribeTool) -> ToolDescribed:
267
+ described = standins.tool(request.tool, self.ruby)
268
+ args = {name: conversion.value(schema, f"args.{name}") for name, schema in (described.args or {}).items()}
269
+
270
+ return ToolDescribed(id=request.id, args=args, text=str(described))
271
+
272
+ def _complete(self, request: CallRequest, exchange: Exchange, recorder: facts.Recorder) -> Completed:
273
+ # A part of the program copy whose callback asked runs as itself, its demos, text and trace the copy's own.
274
+ routed = standins.part(exchange.program, request.component)
275
+ module = routed or build.predictor(request.predictor, self.ruby).module
276
+
277
+ with dspy.context(**self._context(request, exchange, recorder)):
278
+ prediction = module(**conversion.retyped(request.inputs, request.typed))
279
+
280
+ return Completed(id=request.id, outputs=conversion.outputs(prediction), typed=conversion.typed(prediction))
281
+
282
+ def _evaluate(self, request: Evaluate, exchange: Exchange, recorder: facts.Recorder) -> Evaluated:
283
+ program = build.program(request.program, self.ruby)
284
+ metric = evaluation.metric(request.metric, self.ruby)
285
+
286
+ # Set before any call starts, so each judge's calls go apart from the program's.
287
+ exchange.named = evaluation.judges(metric)
288
+
289
+ with dspy.context(**self._context(request, exchange, recorder)):
290
+ return evaluation.evaluate(request, program, metric)
291
+
292
+ def _measure(self, request: Measure, exchange: Exchange, recorder: facts.Recorder) -> Measured:
293
+ metric = evaluation.builtin(request.metric)
294
+
295
+ exchange.named = evaluation.judges(metric)
296
+
297
+ with dspy.context(**self._context(request, exchange, recorder)):
298
+ return evaluation.measure(request, metric)
299
+
300
+ def _generate(self, request: Generate, exchange: Exchange, recorder: facts.Recorder) -> Generated:
301
+ context = self._context(request, exchange, recorder)
302
+
303
+ # The LM put in force, which a Generate always names: building it again would give a DummyLM of its own.
304
+ lm = cast("dspy.BaseLM", context["lm"])
305
+
306
+ # Options pass whole: DSPy takes cache and rollout_id and refuses messages= (clients/base_lm.py:182-188).
307
+ with dspy.context(**context):
308
+ outputs = lm(request.prompt, **request.options)
309
+
310
+ return Generated(
311
+ id=request.id,
312
+ outputs=[conversion.value(output, f"output {index}") for index, output in enumerate(outputs)],
313
+ )
314
+
315
+ def _compile(self, request: Compile, exchange: Exchange, recorder: facts.Recorder) -> Compiled:
316
+ with dspy.context(**self._context(request, exchange, recorder)):
317
+ return optimization.compiled(request, self.ruby)
318
+
319
+ def _context(self, request: Called, exchange: Exchange, recorder: facts.Recorder) -> dict[str, object]:
320
+ context: dict[str, object] = {traffic.KEY: exchange, calls.KEY: recorder}
321
+
322
+ # With none named, a configured LM serves it, as in DSPy, or none does, as for a metric that calls no model.
323
+ if request.lm is not None:
324
+ context["lm"] = self._lm(request, request.lm)
325
+
326
+ # A nested call keeps the trace of the thread it is served on, which is that request's own.
327
+ if exchange.parent is None:
328
+ context["trace"] = []
329
+
330
+ # A kept LM's history holds every call running at once, as DSPy trims it unlocked (base_lm.py:28-30).
331
+ if isinstance(request.lm, LM):
332
+ workers = evaluation.threads(request) if isinstance(request, Evaluate) else 0
333
+
334
+ context["max_history_size"] = max(self.threads, workers)
335
+
336
+ # Left out when absent, as None would override a configured one; a DummyLM reads it (adapters/utils.py:24-29).
337
+ if request.adapter is not None:
338
+ context["adapter"] = build.adapter(request.adapter)
339
+
340
+ return context
341
+
342
+ def _lm(self, request: Called, description: LM | DummyLM) -> dspy.BaseLM:
343
+ match description:
344
+ # A compile's own, never shared: an optimizer may write into its LM (dspy/teleprompt/simba_utils.py:22-24).
345
+ case LM() if isinstance(request, Compile):
346
+ return build.lm(description)
347
+ case LM():
348
+ return self._lms.get(description)
349
+ case DummyLM():
350
+ # It opens no connection, the reason the table keeps an LM, so each request builds its own.
351
+ return build.dummy_lm(description, self.ruby, request.id)
352
+
353
+ assert_never(description)
354
+
355
+
356
+ def _line(request: int, reply: Reply, unrecorded: int, running: int) -> str:
357
+ # A reply that spends carries the counts beside the calls written before it.
358
+ counted = reply
359
+
360
+ if isinstance(reply, COUNTED):
361
+ counted = dataclasses.replace(reply, unrecorded=unrecorded, running=running)
362
+
363
+ written = lines.line(counted)
364
+
365
+ if not isinstance(written, Mismatch):
366
+ return written
367
+
368
+ # A reply Ruby would refuse fails only its own request, naming where it broke.
369
+ return lines.line_or_raise(Failed(id=request, error=facts.broken(written), unrecorded=unrecorded, running=running))