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,364 @@
1
+ """Stand-ins: Python callables for Ruby's, so DSPy reads each with its own code, and each call asks Ruby."""
2
+
3
+ import inspect
4
+ import keyword
5
+ import threading
6
+ import types
7
+ from collections.abc import Callable
8
+ from dataclasses import dataclass, field
9
+ from typing import ClassVar, Final, Self, cast
10
+
11
+ import dspy
12
+ from dspy.propose import utils
13
+
14
+ from dspy_rb.server import conversion
15
+ from dspy_rb.server.ruby import Ruby
16
+ from dspy_rb.wire.shapes import (
17
+ LM,
18
+ DummyLM,
19
+ GateCall,
20
+ InForce,
21
+ MetricCall,
22
+ NextCall,
23
+ Parameter,
24
+ PendingCall,
25
+ ProgramCall,
26
+ Returned,
27
+ RubyMetric,
28
+ Tool,
29
+ ToolArg,
30
+ ToolCall,
31
+ Values,
32
+ )
33
+
34
+ type Metric = Callable[..., object]
35
+ type Gate = Callable[[PendingCall, dspy.BaseLM], None]
36
+
37
+ # The attribute each LM built for Ruby holds: the description it was built from, and its options then.
38
+ BUILT: Final = "dspy_rb_built"
39
+
40
+ # Ruby's kinds of parameter as Python's; an optional one defaults to None, which Ruby reads as nil.
41
+ KINDS: Final = {
42
+ "req": inspect.Parameter.POSITIONAL_OR_KEYWORD,
43
+ "opt": inspect.Parameter.POSITIONAL_OR_KEYWORD,
44
+ "rest": inspect.Parameter.VAR_POSITIONAL,
45
+ "keyreq": inspect.Parameter.KEYWORD_ONLY,
46
+ "key": inspect.Parameter.KEYWORD_ONLY,
47
+ "keyrest": inspect.Parameter.VAR_KEYWORD,
48
+ }
49
+
50
+
51
+ def metric(description: RubyMetric, ruby: Ruby) -> Metric:
52
+ """Give a function taking the Ruby metric's parameters, which asks it for each score with what DSPy passed."""
53
+ signature = inspect.Signature([_parameter(each, index) for index, each in enumerate(description.parameters)])
54
+
55
+ def standin(*given: object) -> object:
56
+ # Bound as a hand-written function's call is, so a count the metric cannot take raises Python's TypeError.
57
+ signature.bind(*given)
58
+
59
+ example, prediction, trace, pred_name, pred_trace = (*given, None, None, None, None, None)[:5]
60
+
61
+ def asked(callback: int, request: int) -> MetricCall:
62
+ return MetricCall(
63
+ id=callback,
64
+ request=request,
65
+ given=len(given),
66
+ example=conversion.wire_example(cast("dspy.Example", example)),
67
+ prediction=None if prediction is None else conversion.outputs(cast("dspy.Prediction", prediction)),
68
+ typed=conversion.typed(cast("dspy.Prediction | None", prediction)),
69
+ trace=None if trace is None else conversion.trace(cast("conversion.Trace", trace)),
70
+ pred_name=cast("str | None", pred_name),
71
+ pred_trace=None if pred_trace is None else conversion.trace(cast("conversion.Trace", pred_trace)),
72
+ in_force=in_force(),
73
+ )
74
+
75
+ return returned(ruby.ask(asked))
76
+
77
+ # DSPy names a table's column and a saved file's key after a function's own name (evaluate/evaluate.py:190, 199).
78
+ standin.__name__ = description.ruby
79
+ standin.__qualname__ = description.ruby
80
+ setattr(standin, "__signature__", signature) # noqa: B010 - functions declare no such attribute.
81
+
82
+ return standin
83
+
84
+
85
+ def in_force(lm: dspy.BaseLM | None = None) -> InForce | None:
86
+ """Describe `lm`, else dspy.settings.lm, as Ruby described it, with DSPy's changes since; None where unknown."""
87
+ model = dspy.settings.lm if lm is None else lm
88
+ built = cast("tuple[LM | DummyLM, dict[str, object]] | None", getattr(model, BUILT, None))
89
+
90
+ if built is None:
91
+ return None
92
+
93
+ described, options = built
94
+ now = cast("dspy.BaseLM", model).kwargs
95
+ changes = {name: value for name, value in now.items() if name not in options or options[name] != value}
96
+
97
+ # An option removed is no change a copy can make, and a key never crosses.
98
+ if "api_key" in changes or any(name not in now for name in options):
99
+ return None
100
+
101
+ return InForce(lm=described, changes={name: conversion.value(value, name) for name, value in changes.items()})
102
+
103
+
104
+ def gate(ruby: Ruby) -> Gate:
105
+ """Give the gate that asks Ruby's gates of each call before it goes, raising what refuses it."""
106
+
107
+ # Its code reads the LM the call goes to, which may be a predictor's own (dspy/predict/predict.py:160).
108
+ def standin(pending: PendingCall, lm: dspy.BaseLM) -> None:
109
+ def asked(callback: int, request: int) -> GateCall:
110
+ return GateCall(id=callback, request=request, pending=pending, in_force=in_force(lm))
111
+
112
+ returned(ruby.ask(asked))
113
+
114
+ return standin
115
+
116
+
117
+ # DSPy's own repr, by its predictors, not the dataclass's, which would print the server's state.
118
+ @dataclass(eq=False, repr=False)
119
+ class _Program(dspy.Module):
120
+ """A Ruby program as DSPy calls one: each call asks Ruby with an example's inputs."""
121
+
122
+ ruby: Ruby
123
+
124
+ # A compile's teacher, whose calls ask the teacher's Ruby program.
125
+ _teacher: bool | None = None
126
+
127
+ # The program's Ruby source, which DSPy's optimizers read in place of a Python class's; a class for each program.
128
+ ruby_source: ClassVar[str | None] = None
129
+
130
+ def forward(self, **inputs: object) -> object:
131
+ """Ask Ruby's program for its prediction on `inputs`, the calls of its parts served by this copy's own."""
132
+
133
+ def asked(callback: int, request: int) -> ProgramCall:
134
+ values = {name: conversion.value(item, name) for name, item in inputs.items()}
135
+
136
+ return ProgramCall(id=callback, request=request, inputs=values, teacher=self._teacher, in_force=in_force())
137
+
138
+ return returned(self.ruby.ask(asked, self))
139
+
140
+
141
+ def program(name: str, ruby: Ruby, *, teacher: bool | None, source: str | None) -> dspy.Module:
142
+ """Give a module that calls Ruby's program back, its class named as the Ruby class and holding its source."""
143
+ return cast("type[_Program]", type(name, (_Program,), {"ruby_source": source}))(ruby, teacher)
144
+
145
+
146
+ def source_code(module: dspy.Module) -> str:
147
+ """Give the Ruby source a program's stand-in holds, else DSPy's own reading of a module's Python source."""
148
+ return class_source(type(module)) if isinstance(module, _Program) else utils.get_dspy_source_code(module)
149
+
150
+
151
+ def class_source(cls: type[object]) -> str:
152
+ """Give the Ruby source a program stand-in's class holds, else Python's own source of a class."""
153
+ if not issubclass(cls, _Program):
154
+ return inspect.getsource(cls)
155
+
156
+ # As Python raises for a class it can't read: its own read searches this module, which may hold one of that name.
157
+ if cls.ruby_source is None:
158
+ message = "could not get source code"
159
+
160
+ raise OSError(message)
161
+
162
+ return cls.ruby_source
163
+
164
+
165
+ # Python's inspect, a program stand-in's class read as its Ruby source, as SIMBA reads a class (simba_utils.py:144).
166
+ INSPECT: Final = types.SimpleNamespace(**{**vars(inspect), "getsource": class_source})
167
+
168
+
169
+ def part(program: dspy.Module | None, component: str | None) -> dspy.Module | None:
170
+ """Give the predictor a program's stand-in holds where a call's component names it; None where it holds none."""
171
+ held: object = program
172
+ names = [] if component is None else component.split(".")
173
+
174
+ # By attributes, not named_predictors, so a frozen module's calls run its own (base_module.py:41-45).
175
+ while names and held is not None and (held is program or type(held) is dspy.Module):
176
+ held = vars(held).get(names.pop(0))
177
+
178
+ return held if isinstance(held, dspy.Module) and type(held) is not dspy.Module else None
179
+
180
+
181
+ # The default of a tool stand-in's optional argument: DSPy's call left it out, and Ruby fills the one it declares.
182
+ LEFT_OUT: Final = object()
183
+
184
+
185
+ @dataclass(eq=False)
186
+ class _Answers(threading.local):
187
+ """A Ruby tool asked by its stand-in, and its last answer on each thread, which the stand-in keeps in no local."""
188
+
189
+ name: str
190
+ ruby: Ruby
191
+
192
+ # A compile's teacher's, whose calls ask the teacher's Ruby tool.
193
+ teacher: bool | None
194
+ _answer: Returned | BaseException | None = field(init=False, default=None)
195
+
196
+ def standin(self) -> object:
197
+ """Ask Ruby's tool, its code given the tool's arguments after `self` as its only other locals (see `tool`)."""
198
+ # Raised in this frame, named as the tool, so the traceback DSPy shows the model ends as a function's own.
199
+ if self.failed(locals()):
200
+ raise self.error()
201
+
202
+ return self.value()
203
+
204
+ def failed(self, args: dict[str, object]) -> bool:
205
+ """Ask Ruby's tool with the arguments DSPy's call gave, any left out dropped; whether its answer is raised."""
206
+ given = {key: item for key, item in args.items() if item is not self and item is not LEFT_OUT}
207
+
208
+ def asked(callback: int, request: int) -> ToolCall:
209
+ values = {key: conversion.value(item, key) for key, item in given.items()}
210
+
211
+ return ToolCall(
212
+ id=callback,
213
+ request=request,
214
+ tool=self.name,
215
+ args=values,
216
+ teacher=self.teacher,
217
+ in_force=in_force(),
218
+ )
219
+
220
+ self._answer = self.ruby.ask(asked)
221
+
222
+ return isinstance(self._answer, BaseException)
223
+
224
+ def error(self) -> BaseException:
225
+ """Give what Ruby's answer stands for, to raise."""
226
+ return cast("BaseException", self._answer)
227
+
228
+ def value(self) -> object:
229
+ """Give what Ruby's tool returned."""
230
+ return returned(cast("Returned", self._answer))
231
+
232
+ # Shared, as a function is: GEPA deep-copies candidates (gepa_utils.py:209), and a thread-local cannot be pickled.
233
+ def __deepcopy__(self, memo: dict[int, object]) -> Self:
234
+ """Give itself, so a copy of its tool asks the same Ruby tool, its answers still each thread's own."""
235
+ del memo
236
+
237
+ return self
238
+
239
+
240
+ def tool(description: Tool, ruby: Ruby, *, teacher: bool | None = None) -> dspy.Tool:
241
+ """Give DSPy's Tool for a Ruby tool: a function DSPy reads and calls as a Python user's, each call asking Ruby."""
242
+ name = description.name
243
+ names = [each.name for each in description.args]
244
+ positional = _positional(description.args)
245
+
246
+ # A name no argument has, for the receiver its code reads by its place, ahead of the arguments.
247
+ receiver = "self"
248
+
249
+ while receiver in names:
250
+ receiver = f"_{receiver}"
251
+
252
+ # Python binds DSPy's call as a hand-written function's, raising its own TypeError for an absent argument.
253
+ template = _Answers.standin
254
+ code = template.__code__.replace(
255
+ co_argcount=1 + positional,
256
+ co_kwonlyargcount=len(names) - positional,
257
+ co_nlocals=1 + len(names),
258
+ co_varnames=(receiver, *names),
259
+ co_name=name,
260
+ co_qualname=name,
261
+ )
262
+ function = types.FunctionType(code, template.__globals__)
263
+ hints = {each.name: _annotation(each.type) for each in description.args if each.type is not None}
264
+ described = {each.name: each.desc for each in description.args if each.desc is not None}
265
+
266
+ # Each read by dspy.Tool, as a hand-written function's are (adapters/types/tool.py:155-163).
267
+ function.__doc__ = description.desc
268
+ function.__annotations__ = hints
269
+ function.__defaults__ = tuple(LEFT_OUT for each in description.args[:positional] if not each.required) or None
270
+ function.__kwdefaults__ = {
271
+ each.name: LEFT_OUT for each in description.args[positional:] if not each.required
272
+ } or None
273
+ setattr(function, "__signature__", _signature(receiver, description.args, positional, hints)) # noqa: B010 - functions declare no such attribute.
274
+
275
+ return dspy.Tool(types.MethodType(function, _Answers(name, ruby, teacher)), arg_desc=described or None)
276
+
277
+
278
+ @dataclass(frozen=True)
279
+ class Remaining:
280
+ """A DummyLM's list as DSPy reads it, one answer a call: each the one at the index Ruby gives, which Ruby keeps."""
281
+
282
+ answers: list[Values]
283
+ ruby: Ruby
284
+
285
+ # The request that named the DummyLM, whose Ruby side answers, though a nested request inheriting it calls.
286
+ request: int
287
+
288
+ def __iter__(self) -> Self:
289
+ """Give itself, as an iterator does."""
290
+ return self
291
+
292
+ # Asked on the calling thread, so an acall's next blocks its event loop (clients/engines/dummy_engine.py:51-52).
293
+ def __next__(self) -> dict[str, object]:
294
+ """Ask Ruby for the index of the next answer not yet used, and give that answer; none left ends the list."""
295
+
296
+ def asked(callback: int, _: int) -> NextCall:
297
+ return NextCall(id=callback, request=self.request)
298
+
299
+ index = returned(self.ruby.ask(asked))
300
+
301
+ if index is None:
302
+ raise StopIteration
303
+
304
+ # A Boolean is an int to Python, so answers[True] would be answers[1].
305
+ if isinstance(index, bool) or not isinstance(index, int) or not 0 <= index < len(self.answers):
306
+ message = f"Ruby gave {index!r}, which is no index of the {len(self.answers)} answers"
307
+
308
+ raise IndexError(message)
309
+
310
+ return dict(self.answers[index])
311
+
312
+
313
+ def returned(outcome: Returned | BaseException) -> object:
314
+ """Give what Ruby's code returned, a Prediction for a prediction's outputs; raise what its answer stands for."""
315
+ if isinstance(outcome, BaseException):
316
+ raise outcome
317
+
318
+ if outcome.prediction is None:
319
+ return outcome.value
320
+
321
+ return dspy.Prediction(**conversion.retyped(outcome.prediction, outcome.typed))
322
+
323
+
324
+ # A name Python cannot take, as a Ruby one may be (`from`, an anonymous `*`), goes by its place.
325
+ def _parameter(described: Parameter, index: int) -> inspect.Parameter:
326
+ name = described.name or ""
327
+ taken = name if name.isidentifier() and not keyword.iskeyword(name) else f"_{index}"
328
+ default = None if described.kind in {"opt", "key"} else inspect.Parameter.empty
329
+
330
+ return inspect.Parameter(taken, KINDS[described.kind], default=default)
331
+
332
+
333
+ # Python takes no required positional parameter after a default one, so from there arguments are keyword-only.
334
+ def _positional(args: list[ToolArg]) -> int:
335
+ defaulted = False
336
+
337
+ for index, each in enumerate(args):
338
+ if each.required and defaulted:
339
+ return index
340
+
341
+ defaulted = defaulted or not each.required
342
+
343
+ return len(args)
344
+
345
+
346
+ # What DSPy reads of the stand-in, its receiver dropped as a bound method's, with the defaults Ruby declares.
347
+ def _signature(receiver: str, args: list[ToolArg], positional: int, hints: dict[str, object]) -> inspect.Signature:
348
+ empty = inspect.Parameter.empty
349
+ parameters = [
350
+ inspect.Parameter(
351
+ each.name,
352
+ inspect.Parameter.POSITIONAL_OR_KEYWORD if index < positional else inspect.Parameter.KEYWORD_ONLY,
353
+ default=empty if each.required else each.default,
354
+ annotation=hints.get(each.name, empty),
355
+ )
356
+ for index, each in enumerate(args)
357
+ ]
358
+
359
+ return inspect.Signature([inspect.Parameter(receiver, inspect.Parameter.POSITIONAL_OR_KEYWORD), *parameters])
360
+
361
+
362
+ def _annotation(text: str) -> object:
363
+ # Parsed by DSPy's own signature parser, as a signature's field types are.
364
+ return dspy.make_signature(f"value: {text} -> output").fields["value"].annotation
@@ -0,0 +1,104 @@
1
+ """A program's state: DSPy's own save and load, and what a compile or a load gave, checked that Ruby holds it all."""
2
+
3
+ from typing import Literal, cast
4
+
5
+ import dspy
6
+
7
+ from dspy_rb.server import build, conversion, facts
8
+ from dspy_rb.server.ruby import Ruby
9
+ from dspy_rb.wire.shapes import (
10
+ JsonValue,
11
+ LoadState,
12
+ Predictor,
13
+ PredictorState,
14
+ ProgramState,
15
+ RubyProgram,
16
+ SaveState,
17
+ StateLoaded,
18
+ StateSaved,
19
+ )
20
+
21
+ type Source = Literal["compiled", "loaded"]
22
+
23
+
24
+ class UnfitError(Exception):
25
+ """State a compile or a load gave that a Ruby program cannot hold; a compile still ran."""
26
+
27
+
28
+ def saved(request: SaveState, ruby: Ruby) -> StateSaved:
29
+ """Write the program's state to its JSON file, as DSPy's own save does."""
30
+ build.program(request.program, ruby).save(request.path)
31
+
32
+ return StateSaved(id=request.id)
33
+
34
+
35
+ def loaded(request: LoadState, ruby: Ruby) -> StateLoaded:
36
+ """Load the program's state from its JSON file, as DSPy's own load does, and read it back as a compile's is."""
37
+ program = build.program(request.program, ruby)
38
+
39
+ program.load(request.path)
40
+
41
+ return StateLoaded(id=request.id, state=read(program, request.program, ruby, "loaded"))
42
+
43
+
44
+ def read(result: dspy.Module, description: Predictor | RubyProgram, ruby: Ruby, source: Source) -> ProgramState:
45
+ """Read each predictor DSPy's optimizers see in a compiled or loaded `result`, refusing state Ruby cannot hold."""
46
+ rebuilt = build.program(description, ruby)
47
+ leaves = dict(rebuilt.named_predictors())
48
+ state = ProgramState(
49
+ predictors=[_predictor(name, leaf, leaves.get(name)) for name, leaf in result.named_predictors()],
50
+ compiled=result._compiled, # noqa: SLF001 - DSPy's own mark, which an optimizer sets on what it gives.
51
+ )
52
+
53
+ # What Ruby holds once it applies the state, built again as each of its calls builds it.
54
+ for each in state.predictors:
55
+ if each.name in leaves:
56
+ build.apply(leaves[each.name], each.instructions, each.demos)
57
+
58
+ _check(rebuilt, result, source)
59
+
60
+ return state
61
+
62
+
63
+ # Its raw text only when it differs from what Ruby holds already.
64
+ def _predictor(name: str, leaf: dspy.Predict, held: dspy.Predict | None) -> PredictorState:
65
+ instructions = facts.instruction(leaf)
66
+ unchanged = held is not None and facts.instruction(held) == instructions
67
+
68
+ return PredictorState(
69
+ name=name,
70
+ instructions=None if unchanged else instructions,
71
+ demos=[conversion.wire_example(each) for each in leaf.demos],
72
+ )
73
+
74
+
75
+ # Each state as it crosses, so a value the wire reshapes, as a set or a tuple, is no difference.
76
+ def _check(rebuilt: dspy.Module, result: dspy.Module, source: Source) -> None:
77
+ holds = cast("dict[str, JsonValue]", conversion.value(rebuilt.dump_state(), "state"))
78
+ gave = cast("dict[str, JsonValue]", conversion.value(result.dump_state(), "state"))
79
+
80
+ for name in [*gave, *(each for each in holds if each not in gave)]:
81
+ where = _difference(holds.get(name), gave.get(name), "")
82
+
83
+ if where is not None:
84
+ what = f"{name}'s {where}" if where else name
85
+ reason = f"a Ruby program cannot hold the {source} {what}"
86
+
87
+ raise UnfitError(reason)
88
+
89
+
90
+ # Where two states first differ, by key and index; None where they do not.
91
+ def _difference(holds: JsonValue, gave: JsonValue, path: str) -> str | None:
92
+ if holds == gave:
93
+ return None
94
+
95
+ inner: list[tuple[JsonValue, JsonValue, str]] = []
96
+
97
+ if isinstance(holds, dict) and isinstance(gave, dict):
98
+ keys = [*gave, *(key for key in holds if key not in gave)]
99
+ inner = [(holds.get(key), gave.get(key), f"{path}.{key}" if path else key) for key in keys]
100
+ elif isinstance(holds, list) and isinstance(gave, list) and len(holds) == len(gave):
101
+ pairs = enumerate(zip(holds, gave, strict=True))
102
+ inner = [(held, given, f"{path}[{index}]") for index, (held, given) in pairs]
103
+
104
+ return next((found for each in inner if (found := _difference(*each)) is not None), path)
@@ -0,0 +1,93 @@
1
+ """Each Ruby request as it is served, the request whose callback it serves, and the settings key that carries it."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import threading
6
+ from dataclasses import dataclass, field
7
+ from typing import Final
8
+
9
+ import dspy
10
+
11
+ from dspy_rb.wire.shapes import CallRequest, Evaluate, Request
12
+
13
+ # dspy.context keeps any key and reaches DSPy's workers (utils/parallelizer.py:150-155), where a contextvar would not.
14
+ KEY: Final = "dspy_rb"
15
+
16
+
17
+ # Predictors whose calls go by a component of their own, each with it, as the judges of one of DSPy's metrics do.
18
+ type Judges = tuple[tuple[dspy.Predict, str], ...]
19
+
20
+
21
+ class Halted(BaseException):
22
+ """The request was cancelled or has answered, up its chain: nothing more starts for it, and it answers cancelled."""
23
+
24
+
25
+ @dataclass(eq=False)
26
+ class Exchange:
27
+ """One Ruby request being served: its id, its component, and the exchange it was made within, if any."""
28
+
29
+ request: int
30
+ component: str | None = None
31
+ parent: Exchange | None = None
32
+ cancelled: bool = False
33
+
34
+ # Set before its reply is written: from then on nothing more starts for it, nor for what it was made within.
35
+ finished: bool = False
36
+
37
+ named: Judges = ()
38
+
39
+ # The program copy whose callback it was made within, whose own parts serve its calls.
40
+ program: dspy.Module | None = None
41
+
42
+ def component_of(self, leaf: dspy.Predict | None) -> str | None:
43
+ """Give the component a call `leaf` makes goes by: its own when named apart, else its request's."""
44
+ return next((name for each, name in self.named if each is leaf), self.component)
45
+
46
+ def stopped(self) -> bool:
47
+ """Whether this request, or one it was made within, was cancelled or has answered."""
48
+ return self.cancelled or self.finished or (self.parent is not None and self.parent.stopped())
49
+
50
+
51
+ def current() -> Exchange | None:
52
+ """Give the exchange of the request whose DSPy code runs on this thread, if any."""
53
+ exchange = dspy.settings.get(KEY)
54
+
55
+ return exchange if isinstance(exchange, Exchange) else None
56
+
57
+
58
+ @dataclass
59
+ class Traffic:
60
+ """The exchanges being served, by their Ruby request's id, for a cancel to find."""
61
+
62
+ _open: dict[int, Exchange] = field(init=False, default_factory=dict[int, Exchange])
63
+ _lock: threading.Lock = field(init=False, default_factory=threading.Lock)
64
+
65
+ def open(self, request: Request, parent: Exchange | None = None, program: dspy.Module | None = None) -> Exchange:
66
+ """Open `request`'s exchange as its line is read, so a cancel read after it always finds it."""
67
+ component = request.component if isinstance(request, CallRequest | Evaluate) else None
68
+ exchange = Exchange(request.id, component, parent, program=program)
69
+
70
+ with self._lock:
71
+ self._open[request.id] = exchange
72
+
73
+ return exchange
74
+
75
+ def busy(self) -> bool:
76
+ """Whether any request is open."""
77
+ with self._lock:
78
+ return bool(self._open)
79
+
80
+ def finish(self, exchange: Exchange) -> None:
81
+ """Mark `exchange` answered, before its reply is written."""
82
+ exchange.finished = True
83
+
84
+ with self._lock:
85
+ self._open.pop(exchange.request, None)
86
+
87
+ def cancel(self, request: int) -> None:
88
+ """Mark the exchange of `request` cancelled; one already answered has nothing left to stop."""
89
+ with self._lock:
90
+ exchange = self._open.get(request)
91
+
92
+ if exchange is not None:
93
+ exchange.cancelled = True
@@ -0,0 +1,51 @@
1
+ """The Python side's values: data, immutable, beside the wire's generated views."""
2
+
3
+ from dataclasses import dataclass
4
+ from typing import override
5
+
6
+ from dspy_rb.wire.shapes import Refused
7
+
8
+
9
+ @dataclass(frozen=True, kw_only=True)
10
+ class Spawning:
11
+ """A spawned server's settings, as Ruby passes them: its threads, and whether DSPy logs."""
12
+
13
+ threads: int
14
+ logging: bool
15
+
16
+
17
+ @dataclass(frozen=True)
18
+ class Mismatch:
19
+ """Where a value departs from the wire's definition, and how; never the value itself."""
20
+
21
+ path: str
22
+ problem: str
23
+
24
+ @override
25
+ def __str__(self) -> str:
26
+ return f"{self.path or 'the line'}: {self.problem}"
27
+
28
+
29
+ @dataclass(frozen=True)
30
+ class Malformed:
31
+ """A line that is not one the wire defines: `reply` refuses it, under its id when it has one; `kind` it claims."""
32
+
33
+ reply: Refused
34
+ kind: str | None = None
35
+
36
+
37
+ @dataclass(frozen=True)
38
+ class Wake:
39
+ """A cancel arrived: a thread waiting on Ruby looks at its exchange again."""
40
+
41
+
42
+ @dataclass(frozen=True)
43
+ class Gone:
44
+ """The end of Ruby's input: no callback will be answered."""
45
+
46
+
47
+ @dataclass(frozen=True)
48
+ class Broken:
49
+ """Ruby's answer to a callback could not be read."""
50
+
51
+ reason: str
@@ -0,0 +1 @@
1
+ """The wire as Python sees it: the one reader and writer of its lines, the pipes they travel, and its typed views."""