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,281 @@
1
+ """Descriptions into DSPy's own objects: a fresh predictor, DummyLM or program stand-in per call, and built LMs."""
2
+
3
+ import functools
4
+ import hashlib
5
+ import json
6
+ import os
7
+ import threading
8
+ from collections import OrderedDict
9
+ from dataclasses import dataclass, field, replace
10
+ from typing import Final, assert_never, cast
11
+
12
+ import dspy
13
+ from dspy.utils import dummies
14
+
15
+ from dspy_rb.server import conversion, standins
16
+ from dspy_rb.server.ruby import Ruby
17
+ from dspy_rb.wire.lines import RefusedError, dump
18
+ from dspy_rb.wire.shapes import LM, Adapter, DummyLM, Example, Field, Part, Predictor, RubyProgram, Values
19
+
20
+ # A new lm15 LM opens a new connection for every call, so built LMs are kept.
21
+ KEPT_LMS: Final = 64
22
+
23
+ ADAPTERS: Final[dict[str, type[dspy.Adapter]]] = {
24
+ "chat": dspy.ChatAdapter,
25
+ "json": dspy.JSONAdapter,
26
+ "xml": dspy.XMLAdapter,
27
+ }
28
+
29
+
30
+ @dataclass(frozen=True)
31
+ class Built:
32
+ """A DSPy predictor and its leaf Predict, which holds the instructions and makes the model call."""
33
+
34
+ module: dspy.Module
35
+ leaf: dspy.Predict
36
+
37
+
38
+ def predictor(description: Predictor, ruby: Ruby) -> Built:
39
+ """DSPy's own predictor for `description`, its instructions applied last and its demos set, on the leaf."""
40
+ built = _kind(description, _signature(description.fields), ruby)
41
+
42
+ apply(built.leaf, description.instructions, description.demos)
43
+
44
+ if description.compiled:
45
+ built.module._compiled = True # noqa: SLF001 - DSPy's own mark, which its optimizers set and read.
46
+
47
+ return built
48
+
49
+
50
+ def apply(leaf: dspy.Predict, instructions: str | None, demos: list[Example] | None) -> None:
51
+ """Set the instructions and demos given on the Predict that makes a predictor's calls, where optimizers set them."""
52
+ if instructions is not None:
53
+ # Applied last: a signature rebuild after them would reshape the raw text (dspy/signatures/signature.py:225).
54
+ leaf.signature = leaf.signature.with_instructions(instructions)
55
+
56
+ # Every call reads its demos from the leaf (dspy/predict/predict.py:156).
57
+ if demos is not None:
58
+ leaf.demos = [conversion.example(each) for each in demos]
59
+
60
+
61
+ def program(description: Predictor | RubyProgram, ruby: Ruby) -> dspy.Module:
62
+ """DSPy's own predictor for a description, or the stand-in that calls a Ruby program back, holding its parts."""
63
+ match description:
64
+ case Predictor():
65
+ built = predictor(description, ruby).module
66
+ case RubyProgram():
67
+ built = _holding(
68
+ standins.program(description.ruby, ruby, teacher=description.teacher, source=description.source),
69
+ description,
70
+ ruby,
71
+ )
72
+
73
+ # Each leaf named as DSPy names it, which a step of DSPy's trace then carries to a Ruby metric.
74
+ for name, leaf in built.named_predictors():
75
+ setattr(leaf, conversion.NAMED, name)
76
+
77
+ return built
78
+
79
+
80
+ def adapter(description: Adapter) -> dspy.Adapter:
81
+ """DSPy's own adapter of `description`'s kind, its options passed whole for DSPy to check."""
82
+ return ADAPTERS[description.kind](**description.options)
83
+
84
+
85
+ def dummy_lm(description: DummyLM, ruby: Ruby, request: int) -> dummies.DummyLM:
86
+ """DSPy's own DummyLM for `description`, named by `request`: a list's answers each asked of Ruby in turn."""
87
+ flags = {"follow_examples": description.follow_examples, "reasoning": description.reasoning}
88
+ given = {name: flag for name, flag in flags.items() if flag is not None}
89
+
90
+ built = dummies.DummyLM(
91
+ _answers(description.answers, ruby, request),
92
+ adapter=None if description.adapter is None else adapter(description.adapter),
93
+ **given,
94
+ )
95
+
96
+ return _copied(built, description)
97
+
98
+
99
+ def lm(description: LM) -> dspy.LM:
100
+ """DSPy's own LM for `description`, built anew, its key read from the variable api_key_env names."""
101
+ options: dict[str, object] = dict(description.options)
102
+
103
+ if description.api_key_env is not None:
104
+ key = os.environ.get(description.api_key_env)
105
+
106
+ if key is None:
107
+ reason = f"{description.api_key_env}, which api_key_env names, is not set"
108
+
109
+ raise RefusedError(reason)
110
+
111
+ options["api_key"] = key
112
+
113
+ return _copied(dspy.LM(description.model, **options), description)
114
+
115
+
116
+ def kwargs(description: LM | DummyLM, ruby: Ruby, request: int) -> Values:
117
+ """DSPy's own lm.kwargs of the LM a call builds from `description`, as JSON; an LM's key is never read for it."""
118
+ built = (
119
+ dummy_lm(description, ruby, request)
120
+ if isinstance(description, DummyLM)
121
+ else lm(replace(description, api_key_env=None))
122
+ )
123
+
124
+ return {name: conversion.value(item, f"kwargs.{name}") for name, item in built.kwargs.items()}
125
+
126
+
127
+ @dataclass
128
+ class LMTable:
129
+ """Built LMs by their description's digest, the least recently used dropped first."""
130
+
131
+ _built: OrderedDict[str, dspy.LM] = field(init=False, default_factory=OrderedDict[str, dspy.LM])
132
+ _lock: threading.Lock = field(init=False, default_factory=threading.Lock)
133
+
134
+ def get(self, description: LM) -> dspy.LM:
135
+ """Give the LM `description` names, built once and kept."""
136
+ key = hashlib.sha256(json.dumps(dump(description), sort_keys=True).encode()).hexdigest()
137
+
138
+ with self._lock:
139
+ kept = self._built.pop(key, None)
140
+
141
+ if kept is None:
142
+ kept = lm(description)
143
+
144
+ self._built[key] = kept
145
+
146
+ if len(self._built) > KEPT_LMS:
147
+ self._built.popitem(last=False)
148
+
149
+ return kept
150
+
151
+
152
+ # Each copy Ruby made, by DSPy's own copy (base_lm.py:317-370), tagged as built; DSPy's copies keep the tag.
153
+ def _copied[Model: dspy.BaseLM](built: Model, description: LM | DummyLM) -> Model:
154
+ for options in description.copies or []:
155
+ built = built.copy(**options)
156
+
157
+ setattr(built, standins.BUILT, (description, dict(built.kwargs)))
158
+
159
+ return built
160
+
161
+
162
+ # Each part at its path, under a module for each of Ruby's, so DSPy names them as Ruby does (base_module.py:24-68).
163
+ def _holding(made: dspy.Module, description: RubyProgram, ruby: Ruby) -> dspy.Module:
164
+ modules = {"": made}
165
+
166
+ for part in description.parts or []:
167
+ within, _, name = part.path.rpartition(".")
168
+
169
+ _hold(_module(modules, within), name, _part(made, part, ruby), part.path)
170
+
171
+ if description.compiled:
172
+ made._compiled = True # noqa: SLF001 - DSPy's own mark, which an optimizer sets on what it gives.
173
+
174
+ for path in description.compiled_modules or []:
175
+ _module(modules, path)._compiled = True # noqa: SLF001 - DSPy's own mark, which keeps a sub-module frozen.
176
+
177
+ return made
178
+
179
+
180
+ # The module at `path`, made under the module holding it the first time a path reaches it.
181
+ def _module(modules: dict[str, dspy.Module], path: str) -> dspy.Module:
182
+ held = modules.get(path)
183
+
184
+ if held is None:
185
+ within, _, name = path.rpartition(".")
186
+ held = dspy.Module()
187
+
188
+ _hold(_module(modules, within), name, held, path)
189
+ modules[path] = held
190
+
191
+ return held
192
+
193
+
194
+ # The predictor described, else the one object at an earlier path, as DSPy holds one at two (base_module.py:37-39).
195
+ def _part(made: dspy.Module, part: Part, ruby: Ruby) -> object:
196
+ if part.same is not None:
197
+ return functools.reduce(getattr, part.same.split("."), made)
198
+
199
+ return predictor(cast("Predictor", part.predictor), ruby).module
200
+
201
+
202
+ # Ruby keeps a variable apart from a method of its name; in Python, it would hide what the module holds.
203
+ def _hold(module: dspy.Module, name: str, held: object, path: str) -> None:
204
+ # Listed, not read: reading forward makes DSPy warn (dspy/primitives/module.py:336-349).
205
+ if name in dir(module):
206
+ reason = f"a Ruby program's {path} would hide the {name} its DSPy module holds: rename the variable"
207
+
208
+ raise RefusedError(reason)
209
+
210
+ setattr(module, name, held)
211
+
212
+
213
+ def _kind(description: Predictor, signature: type[dspy.Signature], ruby: Ruby) -> Built:
214
+ _refuse_strays(description)
215
+
216
+ match description.kind:
217
+ case "predict":
218
+ leaf = dspy.Predict(signature)
219
+
220
+ return Built(module=leaf, leaf=leaf)
221
+ case "chain_of_thought":
222
+ written = str if description.reasoning == "written" else None
223
+ module = dspy.ChainOfThought(signature, rationale_field_type=written)
224
+
225
+ return Built(module=module, leaf=module.predict)
226
+ case "react":
227
+ # The signature's own text goes in first, since ReAct writes it into its own (predict/react.py:127-135).
228
+ task = signature if description.task is None else signature.with_instructions(description.task)
229
+ tools = [standins.tool(each, ruby, teacher=description.teacher) for each in description.tools or []]
230
+ turns = {} if description.max_iters is None else {"max_iters": description.max_iters}
231
+ react = dspy.ReAct(task, tools=tools, **turns)
232
+
233
+ return Built(module=react, leaf=react.react)
234
+
235
+ assert_never(description.kind)
236
+
237
+
238
+ # Each key only one kind takes, refused on any other, which DSPy would build without it.
239
+ def _refuse_strays(description: Predictor) -> None:
240
+ owned = {
241
+ "reasoning": ("chain_of_thought", description.reasoning),
242
+ "tools": ("react", description.tools),
243
+ "max_iters": ("react", description.max_iters),
244
+ "task": ("react", description.task),
245
+ }
246
+ strays = [key for key, (kind, given) in owned.items() if given is not None and kind != description.kind]
247
+
248
+ if strays:
249
+ reason = f"a {description.kind} takes no {', '.join(strays)}: those are another kind's"
250
+
251
+ raise RefusedError(reason)
252
+
253
+
254
+ # A list as DSPy's iterator of one, each answer asked of Ruby; texts' as DSPy finds them.
255
+ def _answers(
256
+ answers: list[Values] | dict[str, Values],
257
+ ruby: Ruby,
258
+ request: int,
259
+ ) -> list[dict[str, object]] | dict[str, dict[str, object]]:
260
+ if isinstance(answers, list):
261
+ # DSPy declares a list but reads answers with next (utils/dummies.py:80-82), so an iterator may stand in.
262
+ return cast("list[dict[str, object]]", standins.Remaining(answers, ruby, request))
263
+
264
+ return {text: dict(fields) for text, fields in answers.items()}
265
+
266
+
267
+ def _signature(fields: list[Field]) -> type[dspy.Signature]:
268
+ inputs = ", ".join(_declared(each) for each in fields if each.role == "input")
269
+ outputs = ", ".join(_declared(each) for each in fields if each.role == "output")
270
+ signature = dspy.make_signature(f"{inputs} -> {outputs}")
271
+
272
+ for each in fields:
273
+ # A description only when given: desc=None would show the model the word None.
274
+ if each.desc is not None:
275
+ signature = signature.with_updated_fields(each.name, desc=each.desc)
276
+
277
+ return signature
278
+
279
+
280
+ def _declared(declared: Field) -> str:
281
+ return declared.name if declared.type is None else f"{declared.name}: {declared.type}"
@@ -0,0 +1,215 @@
1
+ """DSPy's seams around a model call: its request checked as it is made, counted as it goes out, recorded as it ends."""
2
+
3
+ import asyncio
4
+ import functools
5
+ import os
6
+ import threading
7
+ from collections.abc import Awaitable, Callable
8
+ from dataclasses import dataclass, field
9
+ from pathlib import Path
10
+ from typing import Final
11
+
12
+ import dspy
13
+ from dspy.clients import execution
14
+ from dspy.clients.call_result import CallResult
15
+ from dspy.clients.execution import PreparedCall
16
+ from dspy.lm15 import ImagePart, Message, Request
17
+ from dspy.utils.dummies import DummyLM
18
+
19
+ from dspy_rb.server import facts
20
+ from dspy_rb.server.traffic import Exchange
21
+ from dspy_rb.wire.channel import Channel
22
+
23
+ # The request's recorder, beside its exchange in DSPy's context, which ParallelExecutor copies into each worker.
24
+ KEY: Final = "dspy_rb_recorder"
25
+
26
+ # The self-test's calls: one sync, one async.
27
+ CHECKS: Final = 2
28
+
29
+ REFUSED: Final = "text held DSPy's custom-type markers, so the call was not sent: remove the markers from the text"
30
+
31
+ type Execute = Callable[[dspy.BaseLM, PreparedCall], CallResult]
32
+ type AExecute = Callable[[dspy.BaseLM, PreparedCall], Awaitable[CallResult]]
33
+ type Snapshot = Callable[[Request], Request]
34
+
35
+ # Each seam as its owner, its name, and what it holds.
36
+ type Seams = tuple[tuple[object, str, object], ...]
37
+
38
+
39
+ @dataclass
40
+ class _Seams:
41
+ """DSPy's seams in this process: wrapped once, by the first server to run."""
42
+
43
+ installed: bool = False
44
+ lock: threading.Lock = field(default_factory=threading.Lock)
45
+
46
+
47
+ SEAMS: Final = _Seams()
48
+
49
+
50
+ def install() -> None:
51
+ """Wrap DSPy's seams once in this process, then prove them with calls of its own, or put them back."""
52
+ with SEAMS.lock:
53
+ if SEAMS.installed:
54
+ return
55
+
56
+ found: Seams = (
57
+ (execution, "execute", execution.execute),
58
+ (execution, "aexecute", execution.aexecute),
59
+ (execution, "snapshot_request", execution.snapshot_request),
60
+ )
61
+ marked: Seams = (
62
+ (execution, "execute", _marked(execution.execute)),
63
+ (execution, "aexecute", _amarked(execution.aexecute)),
64
+ (execution, "snapshot_request", _checked(execution.snapshot_request)),
65
+ )
66
+
67
+ _put(marked)
68
+
69
+ try:
70
+ _prove()
71
+ except BaseException:
72
+ _put(found)
73
+ raise
74
+
75
+ SEAMS.installed = True
76
+
77
+
78
+ def _put(seams: Seams) -> None:
79
+ # A module's function replaced in place, which no type checker types.
80
+ for owner, name, value in seams:
81
+ setattr(owner, name, value)
82
+
83
+
84
+ def current() -> facts.Recorder | None:
85
+ """Give the recorder of the request whose DSPy code runs here, if any; none of one a forked child inherited."""
86
+ recorder = dspy.settings.get(KEY)
87
+
88
+ # A forked child would write its parent's request's lines to its parent's channel.
89
+ return recorder if isinstance(recorder, facts.Recorder) and recorder.pid == os.getpid() else None
90
+
91
+
92
+ def _marked(execute: Execute) -> Execute:
93
+ @functools.wraps(execute)
94
+ def marked(lm: dspy.BaseLM, call: PreparedCall) -> CallResult:
95
+ recorder = current()
96
+
97
+ if recorder is None:
98
+ return execute(lm, call)
99
+
100
+ start = recorder.sent(lm, call)
101
+
102
+ try:
103
+ result = execute(lm, call)
104
+ except BaseException as raised:
105
+ recorder.ended(start, lm, call, raised)
106
+ raise
107
+
108
+ recorder.ended(start, lm, call, result)
109
+
110
+ return result
111
+
112
+ return marked
113
+
114
+
115
+ def _amarked(aexecute: AExecute) -> AExecute:
116
+ @functools.wraps(aexecute)
117
+ async def amarked(lm: dspy.BaseLM, call: PreparedCall) -> CallResult:
118
+ recorder = current()
119
+
120
+ if recorder is None:
121
+ return await aexecute(lm, call)
122
+
123
+ # Ruby's gates are asked from a sync call alone, which every request of Ruby's makes: this one goes unsent.
124
+ if recorder.gate is not None:
125
+ message = "ruby-on-dspy asks a model call's gates only from a sync call, so this async call was not sent"
126
+
127
+ raise RuntimeError(message)
128
+
129
+ start = recorder.sent(lm, call)
130
+
131
+ try:
132
+ result = await aexecute(lm, call)
133
+ except BaseException as raised:
134
+ recorder.ended(start, lm, call, raised)
135
+ raise
136
+
137
+ recorder.ended(start, lm, call, result)
138
+
139
+ return result
140
+
141
+ return amarked
142
+
143
+
144
+ def _checked(snapshot: Snapshot) -> Snapshot:
145
+ @functools.wraps(snapshot)
146
+ def checked(request: Request) -> Request:
147
+ system = request.system if isinstance(request.system, tuple) else ()
148
+
149
+ if _unmade(system) or any(_unmade(message.parts) for message in request.messages):
150
+ raise PermissionError(REFUSED)
151
+
152
+ return snapshot(request)
153
+
154
+ return checked
155
+
156
+
157
+ def _unmade(parts: tuple[object, ...]) -> bool:
158
+ # A media part in a form DSPy's own types never make, a tool result's own parts included.
159
+ return any(getattr(part, "path", None) is not None or _unmade(getattr(part, "content", ())) for part in parts)
160
+
161
+
162
+ def _prove() -> None:
163
+ # A call and an acall through BaseLM's own (clients/base_lm.py:206, 223), each counted at its mark as one line.
164
+ probe = DummyLM([{"answer": "ok"}, {"answer": "ok"}], adapter=dspy.ChatAdapter())
165
+ requests, replies = os.pipe()
166
+
167
+ # Its reply end read back through its request end, which never waits for a line that was not written.
168
+ os.set_blocking(requests, False)
169
+ channel = Channel.opened(requests, replies)
170
+ recorder = facts.Recorder(channel, Exchange(1))
171
+ unseen: dict[str, object] = {"callbacks": [], "disable_history": True, "usage_tracker": None, KEY: recorder}
172
+
173
+ async def acalled() -> None:
174
+ with dspy.context(**unseen):
175
+ await dspy.BaseLM.acall(probe, "ruby-on-dspy's own check")
176
+
177
+ try:
178
+ with dspy.context(**unseen):
179
+ dspy.BaseLM.__call__(probe, "ruby-on-dspy's own check")
180
+
181
+ # On a thread of its own, since the server's may already run a loop.
182
+ awaiting = threading.Thread(target=asyncio.run, args=(acalled(),), name="dspy_rb-check")
183
+
184
+ awaiting.start()
185
+ awaiting.join()
186
+
187
+ with recorder.settled() as counts:
188
+ written = (channel.requests.read(65_536) or b"").count(b"\n")
189
+ finally:
190
+ channel.close()
191
+
192
+ if counts != (0, 0) or written != CHECKS:
193
+ message = (
194
+ f"DSPy {dspy.__version__}'s model calls do not pass ruby-on-dspy's mark as it relies on: counts {counts}, "
195
+ f"{written} lines"
196
+ )
197
+
198
+ raise RuntimeError(message)
199
+
200
+ _prove_checked(probe)
201
+
202
+
203
+ def _prove_checked(probe: DummyLM) -> None:
204
+ # A part in a form DSPy's types never make, refused before DSPy's snapshot takes it.
205
+ request = Request(model=probe.model, messages=(Message.user([ImagePart(path=Path(os.devnull, "check"))]),))
206
+
207
+ try:
208
+ execution.prepare(probe, request, {})
209
+ except OSError as raised:
210
+ if raised.args == (REFUSED,):
211
+ return
212
+
213
+ message = f"DSPy {dspy.__version__}'s requests do not pass ruby-on-dspy's check as it relies on"
214
+
215
+ raise RuntimeError(message)
@@ -0,0 +1,180 @@
1
+ """Every rule for a value crossing the wire: Python's values as JSON, outputs included, and Examples into DSPy's."""
2
+
3
+ import copy
4
+ import functools
5
+ import json
6
+ import math
7
+ from collections.abc import Callable, Iterator
8
+ from typing import Any, Final, cast
9
+
10
+ import dspy
11
+ import pydantic
12
+
13
+ from dspy_rb.wire.shapes import Example, JsonValue, Score, TraceStep, Typed, Values
14
+
15
+ # The attribute naming each leaf the gem builds as DSPy's named_predictors does; DSPy's deepcopy keeps it.
16
+ NAMED: Final = "dspy_rb_name"
17
+
18
+ # DSPy's own types Ruby holds as its own, by name, each made again from what JSON carried of it.
19
+ TYPES: Final[dict[str, Callable[[Any], object]]] = {
20
+ "Reasoning": lambda content: dspy.Reasoning(content=content),
21
+ "History": lambda fields: dspy.History(**fields),
22
+ }
23
+
24
+ # DSPy's trace: each predictor's call, with its inputs and its prediction (dspy/predict/predict.py:247-251).
25
+ type Trace = list[tuple[dspy.Predict, dict[object, object], dspy.Prediction]]
26
+
27
+
28
+ def outputs(prediction: dspy.Prediction) -> dict[str, JsonValue]:
29
+ """Give the prediction's fields as JSON values; one JSON cannot carry fails the call, naming where."""
30
+ # Raw items: toDict() would turn a Reasoning into a dict.
31
+ return {name: value(item, f"output {name}") for name, item in prediction.items()}
32
+
33
+
34
+ def typed(fields: dspy.Prediction | dspy.Example | None) -> list[Typed] | None:
35
+ """Give where a prediction's or an example's fields hold DSPy's Reasoning or History; None where none do."""
36
+ found = [] if fields is None else list(_typed(dict(fields.items()), ()))
37
+
38
+ return found or None
39
+
40
+
41
+ def retyped(values: Values, types: list[Typed] | None) -> dict[str, object]:
42
+ """Give `values` with each value `types` names, at any depth, as DSPy's own type again, as Python holds it."""
43
+ held: dict[str, Any] = copy.deepcopy(values)
44
+
45
+ for each in types or []:
46
+ *within, last = each.path
47
+ place: Any = functools.reduce(lambda found, key: found[key], within, cast("Any", held))
48
+
49
+ place[last] = TYPES[each.type](place[last])
50
+
51
+ return held
52
+
53
+
54
+ def value(item: object, path: str) -> JsonValue:
55
+ """Give `item` as the JSON value Ruby reads; anything JSON cannot carry raises ValueError, naming `path`."""
56
+ match item:
57
+ # Reasoning is str-like: adapters treat it as its text (dspy/adapters/types/reasoning.py:14-22).
58
+ case dspy.Reasoning():
59
+ return item.content
60
+ case pydantic.BaseModel():
61
+ return value(item.model_dump(mode="json"), path)
62
+ case float() if not math.isfinite(item):
63
+ message = f"{path} is {item}, which JSON cannot carry"
64
+
65
+ raise ValueError(message)
66
+ case str() | int() | float() | None:
67
+ return item
68
+ case list() | tuple():
69
+ members = cast("list[object] | tuple[object, ...]", item)
70
+
71
+ return [value(member, f"{path}[{index}]") for index, member in enumerate(members)]
72
+ case set() | frozenset():
73
+ return _sorted(list(cast("set[object] | frozenset[object]", item)), path)
74
+ case dict():
75
+ return _fields(cast("dict[object, object]", item), path)
76
+ case _:
77
+ message = f"{path} is {_kind(item)}, which JSON cannot carry"
78
+
79
+ raise ValueError(message)
80
+
81
+
82
+ def example(description: Example) -> dspy.Example:
83
+ """Give DSPy's own Example for a wire one, its input keys set only when given."""
84
+ # The record as the base, since Example(**record) takes a field named base for one (primitives/example.py:91-126).
85
+ built = dspy.Example(retyped(description.record, description.typed))
86
+
87
+ return built if description.input_keys is None else built.with_inputs(*description.input_keys)
88
+
89
+
90
+ def wire_example(example: dspy.Example | dict[str, object]) -> Example:
91
+ """Give a DSPy Example as it crosses: every field in order, dspy_ ones too, and its input keys, sorted, once set."""
92
+ # A demo DSPy loads from a file stays a dict, with no input keys (dspy/predict/predict.py:113-116).
93
+ if isinstance(example, dict):
94
+ return Example(record={name: value(item, name) for name, item in example.items()})
95
+
96
+ record = {name: value(item, name) for name, item in example.items(include_dspy=True)}
97
+
98
+ # DSPy has no reader of the input keys, which it holds as a set (primitives/example.py:109, 252).
99
+ keys = example._input_keys # noqa: SLF001 - the one place they are held.
100
+
101
+ return Example(record=record, input_keys=None if keys is None else sorted(keys), typed=typed(example))
102
+
103
+
104
+ def trace(steps: Trace) -> list[TraceStep]:
105
+ """Give DSPy's trace as it crosses: each step's predictor by the name the gem gave it, its inputs and outputs."""
106
+ return [
107
+ TraceStep(predictor=getattr(leaf, NAMED, None), inputs=_fields(inputs, "trace"), outputs=outputs(made))
108
+ for leaf, inputs, made in steps
109
+ ]
110
+
111
+
112
+ def score(item: object) -> Score:
113
+ """Give a metric's score as it crosses: a Prediction's fields, or the value itself."""
114
+ if isinstance(item, dspy.Prediction):
115
+ return Score(prediction=outputs(item))
116
+
117
+ return Score(value=value(item, "score"))
118
+
119
+
120
+ # Each by the keys and indexes JSON carries it at, as Ruby finds its own.
121
+ def _typed(item: object, path: tuple[str | int, ...]) -> Iterator[Typed]:
122
+ match item:
123
+ case dspy.Reasoning() | dspy.History():
124
+ yield Typed(path=[*path], type="Reasoning" if isinstance(item, dspy.Reasoning) else "History")
125
+ case dict():
126
+ for key, each in cast("dict[object, object]", item).items():
127
+ yield from _typed(each, (*path, _key(key, "typed")))
128
+ case list() | tuple():
129
+ for index, each in enumerate(cast("list[object] | tuple[object, ...]", item)):
130
+ yield from _typed(each, (*path, index))
131
+ case _:
132
+ return
133
+
134
+
135
+ # A set's order changes with the hash seed, as HotPotQA's gold_titles do (dspy/datasets/hotpotqa.py:39, 63).
136
+ def _sorted(members: list[object], path: str) -> list[JsonValue]:
137
+ try:
138
+ ordered = sorted(cast("list[Any]", members))
139
+ except TypeError:
140
+ # Items of more than one type have no order of their own; their JSON texts do.
141
+ ordered = sorted(members, key=lambda member: json.dumps(value(member, path), sort_keys=True))
142
+
143
+ return [value(member, f"{path}[{index}]") for index, member in enumerate(ordered)]
144
+
145
+
146
+ def _fields(item: dict[object, object], path: str) -> dict[str, JsonValue]:
147
+ fields: dict[str, JsonValue] = {}
148
+
149
+ for key, each in item.items():
150
+ name = _key(key, path)
151
+
152
+ # 1 and "1" are one key once written, and neither may be dropped for the other.
153
+ if name in fields:
154
+ message = f"{path} has two keys JSON writes as {name}"
155
+
156
+ raise ValueError(message)
157
+
158
+ fields[name] = value(each, f"{path}.{name}")
159
+
160
+ return fields
161
+
162
+
163
+ def _key(key: object, path: str) -> str:
164
+ if isinstance(key, str):
165
+ return key
166
+
167
+ # JSON writes these keys as their own text, and has no text for any other.
168
+ if key is None or isinstance(key, int | float):
169
+ return json.dumps(key)
170
+
171
+ message = f"{path} has a key that is {_kind(key)}, which JSON cannot carry"
172
+
173
+ raise ValueError(message)
174
+
175
+
176
+ def _kind(item: object) -> str:
177
+ # Its type as a message names it, with its article, never the item itself.
178
+ name = type(item).__name__
179
+
180
+ return f"{'an' if name[:1].lower() in 'aeiou' else 'a'} {name}"