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.
- checksums.yaml +7 -0
- data/CHANGELOG.md +112 -0
- data/LICENSE +21 -0
- data/README.md +442 -0
- data/exe/ruby-on-dspy +7 -0
- data/lib/dspy_rb/cli.rb +83 -0
- data/lib/dspy_rb/clients/dummy_lm.rb +81 -0
- data/lib/dspy_rb/clients/lm.rb +44 -0
- data/lib/dspy_rb/datasets/data_loader.rb +74 -0
- data/lib/dspy_rb/datasets/dataset.rb +37 -0
- data/lib/dspy_rb/datasets/python_random.rb +38 -0
- data/lib/dspy_rb/errors.rb +135 -0
- data/lib/dspy_rb/evaluate/evaluate.rb +53 -0
- data/lib/dspy_rb/evaluate/metric.rb +61 -0
- data/lib/dspy_rb/execution/around.rb +63 -0
- data/lib/dspy_rb/execution/collector.rb +61 -0
- data/lib/dspy_rb/execution/context.rb +160 -0
- data/lib/dspy_rb/execution/evaluation.rb +90 -0
- data/lib/dspy_rb/execution/optimization.rb +71 -0
- data/lib/dspy_rb/execution/program.rb +126 -0
- data/lib/dspy_rb/execution/rows.rb +41 -0
- data/lib/dspy_rb/execution/scorer.rb +68 -0
- data/lib/dspy_rb/execution/step.rb +116 -0
- data/lib/dspy_rb/execution/toolbox.rb +28 -0
- data/lib/dspy_rb/predict/chain_of_thought.rb +22 -0
- data/lib/dspy_rb/predict/predict.rb +101 -0
- data/lib/dspy_rb/predict/react.rb +80 -0
- data/lib/dspy_rb/primitives/module.rb +105 -0
- data/lib/dspy_rb/primitives/parts.rb +121 -0
- data/lib/dspy_rb/runtime/channel/callback.rb +105 -0
- data/lib/dspy_rb/runtime/channel/ending.rb +35 -0
- data/lib/dspy_rb/runtime/channel/exchange.rb +176 -0
- data/lib/dspy_rb/runtime/channel/gate.rb +74 -0
- data/lib/dspy_rb/runtime/channel/listener.rb +125 -0
- data/lib/dspy_rb/runtime/channel/meter.rb +46 -0
- data/lib/dspy_rb/runtime/channel/reporter.rb +68 -0
- data/lib/dspy_rb/runtime/channel/settler.rb +69 -0
- data/lib/dspy_rb/runtime/channel/traffic.rb +121 -0
- data/lib/dspy_rb/runtime/channel/watchdog.rb +36 -0
- data/lib/dspy_rb/runtime/channel/writer.rb +77 -0
- data/lib/dspy_rb/runtime/channel.rb +145 -0
- data/lib/dspy_rb/runtime/child.rb +48 -0
- data/lib/dspy_rb/runtime/python.rb +43 -0
- data/lib/dspy_rb/runtime/registry.rb +48 -0
- data/lib/dspy_rb/runtime/startup.rb +53 -0
- data/lib/dspy_rb/secrets.rb +25 -0
- data/lib/dspy_rb/setup/environment.rb +120 -0
- data/lib/dspy_rb/setup/stale.rb +102 -0
- data/lib/dspy_rb/setup/uv.rb +122 -0
- data/lib/dspy_rb/signatures/signature.rb +100 -0
- data/lib/dspy_rb/signatures/types.rb +44 -0
- data/lib/dspy_rb/source.rb +64 -0
- data/lib/dspy_rb/teleprompt/bootstrap_few_shot.rb +9 -0
- data/lib/dspy_rb/teleprompt/bootstrap_few_shot_with_optuna.rb +9 -0
- data/lib/dspy_rb/teleprompt/bootstrap_few_shot_with_random_search.rb +9 -0
- data/lib/dspy_rb/teleprompt/gepa.rb +9 -0
- data/lib/dspy_rb/teleprompt/labeled_few_shot.rb +14 -0
- data/lib/dspy_rb/teleprompt/mipro_v2.rb +16 -0
- data/lib/dspy_rb/teleprompt/optimizer.rb +127 -0
- data/lib/dspy_rb/teleprompt/simba.rb +16 -0
- data/lib/dspy_rb/tool.rb +108 -0
- data/lib/dspy_rb/values/check.rb +14 -0
- data/lib/dspy_rb/values/context.rb +46 -0
- data/lib/dspy_rb/values/dataset.rb +55 -0
- data/lib/dspy_rb/values/dict.rb +17 -0
- data/lib/dspy_rb/values/env.rb +23 -0
- data/lib/dspy_rb/values/evaluation_result.rb +31 -0
- data/lib/dspy_rb/values/example.rb +134 -0
- data/lib/dspy_rb/values/fault.rb +15 -0
- data/lib/dspy_rb/values/history.rb +13 -0
- data/lib/dspy_rb/values/list.rb +16 -0
- data/lib/dspy_rb/values/literal.rb +27 -0
- data/lib/dspy_rb/values/loss.rb +12 -0
- data/lib/dspy_rb/values/optional.rb +16 -0
- data/lib/dspy_rb/values/prediction.rb +58 -0
- data/lib/dspy_rb/values/reasoning.rb +13 -0
- data/lib/dspy_rb/values/spend.rb +27 -0
- data/lib/dspy_rb/values/types.rb +164 -0
- data/lib/dspy_rb/version.rb +11 -0
- data/lib/dspy_rb/wire/departure.rb +100 -0
- data/lib/dspy_rb/wire/descriptions.rb +220 -0
- data/lib/dspy_rb/wire/facts.rb +79 -0
- data/lib/dspy_rb/wire/in_flight.rb +128 -0
- data/lib/dspy_rb/wire/json.rb +76 -0
- data/lib/dspy_rb/wire/optimizers.rb +240 -0
- data/lib/dspy_rb/wire/records.rb +44 -0
- data/lib/dspy_rb/wire/replies.rb +188 -0
- data/lib/dspy_rb/wire/requests.rb +214 -0
- data/lib/dspy_rb/wire/shape.rb +25 -0
- data/lib/dspy_rb/wire/types.rb +23 -0
- data/lib/dspy_rb/wire.rb +34 -0
- data/lib/dspy_rb.rb +191 -0
- data/lib/ruby-on-dspy.rb +4 -0
- data/python/dspy_rb/__init__.py +1 -0
- data/python/dspy_rb/__main__.py +76 -0
- data/python/dspy_rb/server/__init__.py +1 -0
- data/python/dspy_rb/server/build.py +281 -0
- data/python/dspy_rb/server/calls.py +215 -0
- data/python/dspy_rb/server/conversion.py +180 -0
- data/python/dspy_rb/server/data.py +169 -0
- data/python/dspy_rb/server/evaluation.py +107 -0
- data/python/dspy_rb/server/facts.py +357 -0
- data/python/dspy_rb/server/optimization.py +98 -0
- data/python/dspy_rb/server/pulse.py +68 -0
- data/python/dspy_rb/server/ruby.py +206 -0
- data/python/dspy_rb/server/serve.py +369 -0
- data/python/dspy_rb/server/standins.py +364 -0
- data/python/dspy_rb/server/state.py +104 -0
- data/python/dspy_rb/server/traffic.py +93 -0
- data/python/dspy_rb/values.py +51 -0
- data/python/dspy_rb/wire/__init__.py +1 -0
- data/python/dspy_rb/wire/channel.py +107 -0
- data/python/dspy_rb/wire/lines.py +269 -0
- data/python/dspy_rb/wire/shapes.py +1220 -0
- data/python/dspy_rb/wire/wire.json +4592 -0
- data/python/pyproject.toml +86 -0
- data/python/uv.lock +1576 -0
- metadata +230 -0
|
@@ -0,0 +1,169 @@
|
|
|
1
|
+
"""DSPy's own data code, run as a Python user runs it: its datasets and DataLoader, and Python's random orders."""
|
|
2
|
+
|
|
3
|
+
import importlib.util
|
|
4
|
+
import random
|
|
5
|
+
import threading
|
|
6
|
+
from collections.abc import Callable, Mapping
|
|
7
|
+
from typing import Any, Final, assert_never, cast
|
|
8
|
+
|
|
9
|
+
import dspy
|
|
10
|
+
from dspy.datasets import MATH, Colors, DataLoader, HotPotQA
|
|
11
|
+
from dspy.datasets.gsm8k import GSM8K
|
|
12
|
+
|
|
13
|
+
from dspy_rb.server import conversion, facts
|
|
14
|
+
from dspy_rb.wire.lines import RefusedError, dump
|
|
15
|
+
from dspy_rb.wire.shapes import DataFile, DSPyDataset, HubDataset, Load, Loaded, Permute, Permuted, Split
|
|
16
|
+
|
|
17
|
+
# DSPy's own datasets, by Ruby's names for their classes.
|
|
18
|
+
DATASETS: Final[dict[str, Callable[..., object]]] = {
|
|
19
|
+
"hot_pot_qa": HotPotQA,
|
|
20
|
+
"gsm8k": GSM8K,
|
|
21
|
+
"math": MATH,
|
|
22
|
+
"colors": Colors,
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
# A dataset's splits, read as attributes, a Dataset's as properties that may raise (datasets/dataset.py:58-77).
|
|
26
|
+
SPLITS: Final = ("train", "dev", "test")
|
|
27
|
+
|
|
28
|
+
# Each draw's own keys beside its count, as random.Random and DSPy's DataLoader take them.
|
|
29
|
+
DRAWS: Final = {
|
|
30
|
+
"shuffle": {"seed"},
|
|
31
|
+
"sample": {"seed", "k"},
|
|
32
|
+
"train_test_split": {"train_size", "test_size", "random_state"},
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
# Hugging Face's datasets, which every loader but Colors needs, comes with the data group alone.
|
|
36
|
+
WITHOUT_GROUP: Final = "the data group is not installed: run `ruby-on-dspy setup --with data`"
|
|
37
|
+
|
|
38
|
+
# DSPy's DataLoader draws from Python's global random (datasets/dataloader.py:123-174), so draws take turns.
|
|
39
|
+
GLOBAL: Final = threading.Lock()
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def load(request: Load) -> Loaded:
|
|
43
|
+
"""Load as DSPy loads: a dataset's splits, each its Examples or its error, or what the DataLoader gave."""
|
|
44
|
+
source = request.source
|
|
45
|
+
|
|
46
|
+
if not (isinstance(source, DSPyDataset) and source.name == "colors"):
|
|
47
|
+
need("datasets")
|
|
48
|
+
|
|
49
|
+
match source:
|
|
50
|
+
case DSPyDataset():
|
|
51
|
+
return Loaded(id=request.id, splits=_splits(_dataset(source)))
|
|
52
|
+
case HubDataset():
|
|
53
|
+
return _given(request.id, _hub(source))
|
|
54
|
+
case DataFile():
|
|
55
|
+
return _given(request.id, _file(source))
|
|
56
|
+
|
|
57
|
+
assert_never(source)
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def permute(request: Permute) -> Permuted:
|
|
61
|
+
"""Give a count of rows' indices in Python's order, as random.Random(seed) or DSPy's DataLoader orders them."""
|
|
62
|
+
given = {key for key in cast("dict[str, object]", dump(request)) if key not in {"id", "kind", "draw", "count"}}
|
|
63
|
+
strays = sorted(given - DRAWS[request.draw])
|
|
64
|
+
|
|
65
|
+
if strays:
|
|
66
|
+
reason = f"a {request.draw} takes no {', '.join(strays)}"
|
|
67
|
+
|
|
68
|
+
raise RefusedError(reason)
|
|
69
|
+
|
|
70
|
+
indices = list(range(request.count))
|
|
71
|
+
|
|
72
|
+
match request.draw:
|
|
73
|
+
case "shuffle":
|
|
74
|
+
random.Random(request.seed).shuffle(indices) # noqa: S311 - Python's own order is the point, as a user's is.
|
|
75
|
+
|
|
76
|
+
return Permuted(id=request.id, parts=[indices])
|
|
77
|
+
case "sample":
|
|
78
|
+
return Permuted(id=request.id, parts=[_sample(request, indices)])
|
|
79
|
+
case "train_test_split":
|
|
80
|
+
return Permuted(id=request.id, parts=_split(request, indices))
|
|
81
|
+
|
|
82
|
+
assert_never(request.draw)
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def need(module: str) -> None:
|
|
86
|
+
"""Refuse a request whose DSPy code imports what only the data group installs, naming the setup that adds it."""
|
|
87
|
+
if importlib.util.find_spec(module) is None:
|
|
88
|
+
raise RefusedError(WITHOUT_GROUP)
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def _dataset(source: DSPyDataset) -> object:
|
|
92
|
+
# Its options as a Python user passes them, for DSPy to check.
|
|
93
|
+
options = cast("dict[str, object]", dump(source))
|
|
94
|
+
|
|
95
|
+
del options["name"]
|
|
96
|
+
|
|
97
|
+
return DATASETS[source.name](**options)
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
def _splits(dataset: object) -> list[Split]:
|
|
101
|
+
splits: list[Split] = []
|
|
102
|
+
|
|
103
|
+
for name in SPLITS:
|
|
104
|
+
try:
|
|
105
|
+
examples = [conversion.wire_example(each) for each in cast("list[dspy.Example]", getattr(dataset, name))]
|
|
106
|
+
except Exception as error: # noqa: BLE001 - a split DSPy cannot read is that split's error alone.
|
|
107
|
+
splits.append(Split(name=name, error=facts.failure(error)))
|
|
108
|
+
else:
|
|
109
|
+
splits.append(Split(name=name, examples=examples))
|
|
110
|
+
|
|
111
|
+
return splits
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
def _hub(source: HubDataset) -> Mapping[str, list[dspy.Example]] | list[dspy.Example]:
|
|
115
|
+
# DSPy takes its fields and input keys as tuples alone (datasets/dataloader.py:25-29).
|
|
116
|
+
return DataLoader().from_huggingface(
|
|
117
|
+
source.dataset_name,
|
|
118
|
+
*source.arguments,
|
|
119
|
+
input_keys=tuple(source.input_keys or ()),
|
|
120
|
+
fields=None if source.fields is None else tuple(source.fields),
|
|
121
|
+
**source.options,
|
|
122
|
+
)
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
def _file(source: DataFile) -> list[dspy.Example]:
|
|
126
|
+
loader = DataLoader()
|
|
127
|
+
read = {"csv": loader.from_csv, "json": loader.from_json, "parquet": loader.from_parquet}[source.format]
|
|
128
|
+
|
|
129
|
+
return read(source.file_path, fields=source.fields, input_keys=tuple(source.input_keys or ()))
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
def _given(request: int, examples: Mapping[str, list[dspy.Example]] | list[dspy.Example]) -> Loaded:
|
|
133
|
+
if isinstance(examples, Mapping):
|
|
134
|
+
splits = [
|
|
135
|
+
Split(name=name, examples=[conversion.wire_example(each) for each in split])
|
|
136
|
+
for name, split in examples.items()
|
|
137
|
+
]
|
|
138
|
+
|
|
139
|
+
return Loaded(id=request, splits=splits)
|
|
140
|
+
|
|
141
|
+
return Loaded(id=request, examples=[conversion.wire_example(each) for each in examples])
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
def _sample(request: Permute, indices: list[int]) -> list[int]:
|
|
145
|
+
if request.k is None:
|
|
146
|
+
reason = "a sample takes k"
|
|
147
|
+
|
|
148
|
+
raise RefusedError(reason)
|
|
149
|
+
|
|
150
|
+
if request.seed is not None:
|
|
151
|
+
return random.Random(request.seed).sample(indices, request.k) # noqa: S311 - Python's own order is the point.
|
|
152
|
+
|
|
153
|
+
with GLOBAL:
|
|
154
|
+
return cast("list[int]", DataLoader().sample(cast("list[dspy.Example]", indices), request.k))
|
|
155
|
+
|
|
156
|
+
|
|
157
|
+
def _split(request: Permute, indices: list[int]) -> list[list[int]]:
|
|
158
|
+
# Those given alone, so DSPy's own defaults stand for the rest.
|
|
159
|
+
sizes: dict[str, Any] = {
|
|
160
|
+
"train_size": request.train_size,
|
|
161
|
+
"test_size": request.test_size,
|
|
162
|
+
"random_state": request.random_state,
|
|
163
|
+
}
|
|
164
|
+
given = {key: value for key, value in sizes.items() if value is not None}
|
|
165
|
+
|
|
166
|
+
with GLOBAL:
|
|
167
|
+
split = DataLoader().train_test_split(cast("list[dspy.Example]", indices), **given)
|
|
168
|
+
|
|
169
|
+
return [cast("list[int]", split["train"]), cast("list[int]", split["test"])]
|
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
"""DSPy's Evaluate and its metrics, run as DSPy runs them, over a predictor or a Ruby program."""
|
|
2
|
+
|
|
3
|
+
from collections.abc import Callable
|
|
4
|
+
from functools import partial
|
|
5
|
+
from typing import Final, cast
|
|
6
|
+
|
|
7
|
+
import dspy
|
|
8
|
+
from dspy.datasets import MATH
|
|
9
|
+
from dspy.datasets.gsm8k import gsm8k_metric
|
|
10
|
+
from dspy.evaluate import CompleteAndGrounded, SemanticF1, answer_exact_match, answer_passage_match
|
|
11
|
+
|
|
12
|
+
from dspy_rb.server import conversion, data, standins
|
|
13
|
+
from dspy_rb.server.ruby import Ruby
|
|
14
|
+
from dspy_rb.server.traffic import Judges
|
|
15
|
+
from dspy_rb.wire import lines
|
|
16
|
+
from dspy_rb.wire.shapes import (
|
|
17
|
+
Evaluate,
|
|
18
|
+
Evaluated,
|
|
19
|
+
Measure,
|
|
20
|
+
Measured,
|
|
21
|
+
Metric,
|
|
22
|
+
Result,
|
|
23
|
+
RubyMetric,
|
|
24
|
+
)
|
|
25
|
+
|
|
26
|
+
# DSPy's metrics by Ruby's names; MATH's reads nothing of its dataset (datasets/math.py:27-33), so none is loaded.
|
|
27
|
+
FUNCTIONS: Final[dict[str, Callable[..., object]]] = {
|
|
28
|
+
"answer_exact_match": answer_exact_match,
|
|
29
|
+
"answer_passage_match": answer_passage_match,
|
|
30
|
+
"gsm8k_metric": gsm8k_metric,
|
|
31
|
+
"math_metric": MATH.__new__(MATH).metric,
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
# DSPy's metric modules, whose judges are predictors of their own.
|
|
35
|
+
MODULES: Final[dict[str, type[dspy.Module]]] = {
|
|
36
|
+
"semantic_f1": SemanticF1,
|
|
37
|
+
"complete_and_grounded": CompleteAndGrounded,
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def metric(description: Metric | RubyMetric, ruby: Ruby) -> Callable[..., object]:
|
|
42
|
+
"""Give one of DSPy's own metrics, or the stand-in that asks Ruby's."""
|
|
43
|
+
match description:
|
|
44
|
+
case RubyMetric():
|
|
45
|
+
return standins.metric(description, ruby)
|
|
46
|
+
case Metric():
|
|
47
|
+
return builtin(description)
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def builtin(description: Metric) -> Callable[..., object]:
|
|
51
|
+
"""Give DSPy's own metric, its options passed as a Python user passes them, for DSPy to check."""
|
|
52
|
+
if description.name == "math_metric":
|
|
53
|
+
data.need("math_equivalence")
|
|
54
|
+
|
|
55
|
+
options = cast("dict[str, object]", lines.dump(description))
|
|
56
|
+
|
|
57
|
+
del options["name"]
|
|
58
|
+
|
|
59
|
+
if description.name in MODULES:
|
|
60
|
+
return MODULES[description.name](**options)
|
|
61
|
+
|
|
62
|
+
# A function with options is a partial, so DSPy names its column `partial`, as it does a Python user's.
|
|
63
|
+
function = FUNCTIONS[description.name]
|
|
64
|
+
|
|
65
|
+
return partial(function, **options) if options else function
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def judges(measured: Callable[..., object]) -> Judges:
|
|
69
|
+
"""Name each judge of one of DSPy's metric modules by the module's class and DSPy's path to it."""
|
|
70
|
+
if not isinstance(measured, dspy.Module):
|
|
71
|
+
return ()
|
|
72
|
+
|
|
73
|
+
return tuple((leaf, f"{type(measured).__name__}.{name}") for name, leaf in measured.named_predictors())
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def evaluate(request: Evaluate, scored: dspy.Module, metric: Callable[..., object]) -> Evaluated:
|
|
77
|
+
"""Run DSPy's own Evaluate, made with the options given and called with the overrides, which DSPy itself applies."""
|
|
78
|
+
devset = [conversion.example(each) for each in request.devset]
|
|
79
|
+
options = cast("dict[str, object]", lines.dump(request.options))
|
|
80
|
+
overrides = cast("dict[str, object]", lines.dump(request.overrides))
|
|
81
|
+
result = dspy.Evaluate(devset=devset, metric=metric, **options)(scored, **overrides)
|
|
82
|
+
scored_results = cast("list[tuple[dspy.Example, dspy.Prediction, object]]", result.results)
|
|
83
|
+
results = [
|
|
84
|
+
Result(
|
|
85
|
+
prediction=conversion.outputs(prediction),
|
|
86
|
+
typed=conversion.typed(prediction),
|
|
87
|
+
score=conversion.score(score),
|
|
88
|
+
)
|
|
89
|
+
for _, prediction, score in scored_results
|
|
90
|
+
]
|
|
91
|
+
|
|
92
|
+
return Evaluated(id=request.id, score=cast("float", result.score), results=results)
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
def measure(request: Measure, measured: Callable[..., object]) -> Measured:
|
|
96
|
+
"""Call one of DSPy's metrics once, on the example and the outputs given."""
|
|
97
|
+
score = measured(conversion.example(request.example), dspy.Prediction(**request.prediction))
|
|
98
|
+
|
|
99
|
+
return Measured(id=request.id, score=conversion.score(score))
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
def threads(request: Evaluate) -> int:
|
|
103
|
+
"""Give how many workers DSPy's Evaluate runs: its call's num_threads, else its own, else DSPy's setting."""
|
|
104
|
+
called = request.overrides.num_threads
|
|
105
|
+
|
|
106
|
+
# The call's unless None (evaluate/evaluate.py:151), then DSPy's setting for any falsy one (parallelizer.py:50).
|
|
107
|
+
return (called if called is not None else request.options.num_threads) or dspy.settings.num_threads
|
|
@@ -0,0 +1,357 @@
|
|
|
1
|
+
"""Each model call's facts, read from DSPy's PreparedCall and CallResult, and each error described for Ruby."""
|
|
2
|
+
|
|
3
|
+
import json
|
|
4
|
+
import logging
|
|
5
|
+
import os
|
|
6
|
+
import re
|
|
7
|
+
import threading
|
|
8
|
+
import time
|
|
9
|
+
import uuid
|
|
10
|
+
from collections.abc import Callable, Generator
|
|
11
|
+
from contextlib import contextmanager
|
|
12
|
+
from dataclasses import dataclass, field
|
|
13
|
+
from typing import Final, TypedDict, cast
|
|
14
|
+
|
|
15
|
+
import dspy
|
|
16
|
+
from dspy.clients.call_result import CallResult
|
|
17
|
+
from dspy.clients.execution import PreparedCall
|
|
18
|
+
from dspy.clients.lm15_boundary import history_messages
|
|
19
|
+
from dspy.lm15 import Request
|
|
20
|
+
|
|
21
|
+
from dspy_rb.server import traffic
|
|
22
|
+
from dspy_rb.server.pulse import Pulse
|
|
23
|
+
from dspy_rb.server.traffic import Exchange
|
|
24
|
+
from dspy_rb.values import Mismatch
|
|
25
|
+
from dspy_rb.wire import lines
|
|
26
|
+
from dspy_rb.wire.channel import Channel
|
|
27
|
+
from dspy_rb.wire.shapes import (
|
|
28
|
+
CUT_AT,
|
|
29
|
+
KEY_LIKE,
|
|
30
|
+
Call,
|
|
31
|
+
Failure,
|
|
32
|
+
JsonValue,
|
|
33
|
+
Message,
|
|
34
|
+
PendingCall,
|
|
35
|
+
Progress,
|
|
36
|
+
Settings,
|
|
37
|
+
Usage,
|
|
38
|
+
)
|
|
39
|
+
|
|
40
|
+
MESSAGE_LIMIT: Final = 500
|
|
41
|
+
LOGGER: Final = logging.getLogger(__name__)
|
|
42
|
+
|
|
43
|
+
# Records must never hold a key, and a provider's message may echo one: Ruby's rules, carried in the wire's definition.
|
|
44
|
+
SECRET_START: Final = re.compile(CUT_AT)
|
|
45
|
+
KEYS: Final = re.compile(KEY_LIKE)
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
class _Details(TypedDict, total=False):
|
|
49
|
+
cached_tokens: int
|
|
50
|
+
cache_creation_tokens: int
|
|
51
|
+
reasoning_tokens: int
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
class _Usage(TypedDict, total=False):
|
|
55
|
+
"""A cached reply's counts are empty."""
|
|
56
|
+
|
|
57
|
+
prompt_tokens: int
|
|
58
|
+
completion_tokens: int
|
|
59
|
+
prompt_tokens_details: _Details | None
|
|
60
|
+
completion_tokens_details: _Details | None
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
class _Function(TypedDict):
|
|
64
|
+
name: str
|
|
65
|
+
arguments: str
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
class _ToolCall(TypedDict):
|
|
69
|
+
id: str
|
|
70
|
+
type: str
|
|
71
|
+
function: _Function
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
class _Output(TypedDict, total=False):
|
|
75
|
+
text: str | None
|
|
76
|
+
reasoning_content: str
|
|
77
|
+
tool_calls: list[_ToolCall]
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
class _Part(TypedDict, total=False):
|
|
81
|
+
type: str
|
|
82
|
+
text: str
|
|
83
|
+
name: str
|
|
84
|
+
input: dict[str, JsonValue]
|
|
85
|
+
content: list["_Part"]
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
class _Record(TypedDict):
|
|
89
|
+
role: str
|
|
90
|
+
content: str | list[_Part]
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
@dataclass(frozen=True)
|
|
94
|
+
class Sent:
|
|
95
|
+
"""A model call as it went out: its id, the Predict that made it, None for a direct call, and when."""
|
|
96
|
+
|
|
97
|
+
id: str
|
|
98
|
+
leaf: dspy.Predict | None
|
|
99
|
+
at: float
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
@dataclass
|
|
103
|
+
class Recorder:
|
|
104
|
+
"""One request's model calls: each counted as it goes out, and written to Ruby as it ends, else counted."""
|
|
105
|
+
|
|
106
|
+
channel: Channel
|
|
107
|
+
exchange: Exchange
|
|
108
|
+
|
|
109
|
+
# Watches its calls while they run, so Python writes Ruby the alive line while Ruby waits for their progress.
|
|
110
|
+
pulse: Pulse | None = None
|
|
111
|
+
|
|
112
|
+
# Ruby's gates, for a request whose context has them: asked of each call before it goes, raising what refuses it.
|
|
113
|
+
gate: Callable[[PendingCall, dspy.BaseLM], None] | None = None
|
|
114
|
+
|
|
115
|
+
# The process it was made in, whose calls alone it records.
|
|
116
|
+
pid: int = field(init=False, default_factory=os.getpid)
|
|
117
|
+
_running: int = field(init=False, default=0)
|
|
118
|
+
_unrecorded: int = field(init=False, default=0)
|
|
119
|
+
|
|
120
|
+
# Set as the reply is written: from then on, each call that ends is one Ruby follows, so it writes a line.
|
|
121
|
+
_replied: bool = field(init=False, default=False)
|
|
122
|
+
|
|
123
|
+
# Held to count or write a call and to reply: each call is then before the reply, or running in it.
|
|
124
|
+
_lock: threading.Lock = field(init=False, default_factory=threading.Lock)
|
|
125
|
+
|
|
126
|
+
@contextmanager
|
|
127
|
+
def settled(self) -> Generator[tuple[int, int]]:
|
|
128
|
+
"""Hold still, for the reply, the counts of the calls not recorded and of those still running."""
|
|
129
|
+
with self._lock:
|
|
130
|
+
self._replied = True
|
|
131
|
+
|
|
132
|
+
yield self._unrecorded, self._running
|
|
133
|
+
|
|
134
|
+
def running(self) -> int:
|
|
135
|
+
"""Count the calls still running, as the pulse asks at each beat."""
|
|
136
|
+
with self._lock:
|
|
137
|
+
return self._running
|
|
138
|
+
|
|
139
|
+
def sent(self, lm: dspy.BaseLM, call: PreparedCall) -> Sent | None:
|
|
140
|
+
"""Ask the gates of a call, then count it as it goes out, raising Halted once its request has stopped."""
|
|
141
|
+
made = str(uuid.uuid4())
|
|
142
|
+
|
|
143
|
+
# Before the call counts as running: one its gates refuse never goes out.
|
|
144
|
+
if self.gate is not None:
|
|
145
|
+
self.gate(self._pending(made, lm, call), lm)
|
|
146
|
+
|
|
147
|
+
start = _start(made)
|
|
148
|
+
|
|
149
|
+
# Under the reply's lock: a call is counted running exactly when it can still go out.
|
|
150
|
+
with self._lock:
|
|
151
|
+
if self.exchange.stopped():
|
|
152
|
+
raise traffic.Halted
|
|
153
|
+
|
|
154
|
+
self._running += 1
|
|
155
|
+
|
|
156
|
+
if self.pulse is not None:
|
|
157
|
+
self.pulse.watch(self)
|
|
158
|
+
|
|
159
|
+
return start
|
|
160
|
+
|
|
161
|
+
def ended(
|
|
162
|
+
self,
|
|
163
|
+
start: Sent | None,
|
|
164
|
+
lm: dspy.BaseLM,
|
|
165
|
+
call: PreparedCall,
|
|
166
|
+
outcome: CallResult | BaseException,
|
|
167
|
+
) -> None:
|
|
168
|
+
"""Write a call to Ruby as it ended: what came back and what it cost, or how it failed; else count it."""
|
|
169
|
+
line = None if start is None else self._line(start, lm, call, outcome)
|
|
170
|
+
|
|
171
|
+
with self._lock:
|
|
172
|
+
self._running -= 1
|
|
173
|
+
|
|
174
|
+
if line is not None:
|
|
175
|
+
self.channel.write(line)
|
|
176
|
+
elif self._replied:
|
|
177
|
+
self.channel.write(lines.line_or_raise(Progress(id=self.exchange.request)))
|
|
178
|
+
else:
|
|
179
|
+
self._unrecorded += 1
|
|
180
|
+
|
|
181
|
+
def _pending(self, made: str, lm: dspy.BaseLM, call: PreparedCall) -> PendingCall:
|
|
182
|
+
return PendingCall(
|
|
183
|
+
id=made,
|
|
184
|
+
component=self.exchange.component_of(_leaf()),
|
|
185
|
+
model=lm.model,
|
|
186
|
+
messages=_messages(call.request),
|
|
187
|
+
settings=_settings(call.request),
|
|
188
|
+
n=call.n,
|
|
189
|
+
)
|
|
190
|
+
|
|
191
|
+
def _line(
|
|
192
|
+
self,
|
|
193
|
+
start: Sent,
|
|
194
|
+
lm: dspy.BaseLM,
|
|
195
|
+
call: PreparedCall,
|
|
196
|
+
outcome: CallResult | BaseException,
|
|
197
|
+
) -> str | None:
|
|
198
|
+
try:
|
|
199
|
+
line = lines.line(Progress(id=self.exchange.request, call=self._call(start, lm, call, outcome)))
|
|
200
|
+
except Exception:
|
|
201
|
+
LOGGER.exception("ruby-on-dspy could not read a model call's facts; the reply counts it unrecorded")
|
|
202
|
+
return None
|
|
203
|
+
|
|
204
|
+
if isinstance(line, Mismatch):
|
|
205
|
+
LOGGER.error("ruby-on-dspy could not record a model call (%s); the reply counts it unrecorded", line)
|
|
206
|
+
return None
|
|
207
|
+
|
|
208
|
+
return line
|
|
209
|
+
|
|
210
|
+
def _call(self, start: Sent, lm: dspy.BaseLM, call: PreparedCall, outcome: CallResult | BaseException) -> Call:
|
|
211
|
+
sent = _messages(call.request)
|
|
212
|
+
result = None if isinstance(outcome, BaseException) else outcome
|
|
213
|
+
|
|
214
|
+
return Call(
|
|
215
|
+
id=start.id,
|
|
216
|
+
component=self.exchange.component_of(start.leaf),
|
|
217
|
+
instruction=None if start.leaf is None else instruction(start.leaf),
|
|
218
|
+
model=lm.model,
|
|
219
|
+
response_model=None if result is None else result.response_model,
|
|
220
|
+
messages=sent if result is None else [*sent, *_reply(cast("list[str | _Output]", result.outputs))],
|
|
221
|
+
usage=None if result is None else _usage(cast("_Usage", result.usage)),
|
|
222
|
+
settings=_settings(call.request),
|
|
223
|
+
cache_hit=result is not None and result.cache_hit,
|
|
224
|
+
duration_ms=round((time.monotonic() - start.at) * 1000),
|
|
225
|
+
outcome="completed" if result is not None else "failed",
|
|
226
|
+
error=failure(outcome) if isinstance(outcome, BaseException) else None,
|
|
227
|
+
cost=None if result is None else result.cost,
|
|
228
|
+
cost_details=None if result is None else cast("dict[str, JsonValue]", result.cost_details) or None,
|
|
229
|
+
)
|
|
230
|
+
|
|
231
|
+
|
|
232
|
+
def instruction(leaf: dspy.Predict) -> str:
|
|
233
|
+
"""Read the raw text `leaf` holds, which DSPy sets to its default when none was given."""
|
|
234
|
+
return cast("str", leaf.signature.__doc__)
|
|
235
|
+
|
|
236
|
+
|
|
237
|
+
def failure(error: BaseException) -> Failure:
|
|
238
|
+
"""Describe an exception: its class and bases, its scrubbed message, and DSPy's retryable verdict."""
|
|
239
|
+
return Failure(
|
|
240
|
+
ancestry=[cls.__name__ for cls in type(error).__mro__[:-1]],
|
|
241
|
+
message=scrub(str(error)),
|
|
242
|
+
retryable=isinstance(error, Exception) and dspy.is_retryable_lm_error(error),
|
|
243
|
+
)
|
|
244
|
+
|
|
245
|
+
|
|
246
|
+
def broken(mismatch: Mismatch) -> Failure:
|
|
247
|
+
"""Describe a reply that breaks the definition, named for the Mismatch: where, and how; never retryable."""
|
|
248
|
+
return Failure(ancestry=[type(mismatch).__name__], message=scrub(str(mismatch)), retryable=False)
|
|
249
|
+
|
|
250
|
+
|
|
251
|
+
def scrub(text: str) -> str:
|
|
252
|
+
"""`text`'s first line, cut where a header or key may start, key-like words redacted, and kept short."""
|
|
253
|
+
line = _utf8(text).split("\n", 1)[0]
|
|
254
|
+
cut = SECRET_START.search(line)
|
|
255
|
+
|
|
256
|
+
if cut is not None:
|
|
257
|
+
line = line[: cut.start()] + "[cut]"
|
|
258
|
+
|
|
259
|
+
return KEYS.sub("[redacted]", line)[:MESSAGE_LIMIT]
|
|
260
|
+
|
|
261
|
+
|
|
262
|
+
def _start(made: str) -> Sent | None:
|
|
263
|
+
# Read inside DSPy's call, which a fault here would fail: the call is counted unrecorded instead.
|
|
264
|
+
try:
|
|
265
|
+
return Sent(id=made, leaf=_leaf(), at=time.monotonic())
|
|
266
|
+
except Exception:
|
|
267
|
+
LOGGER.exception("ruby-on-dspy could not read a model call's start; the reply counts it unrecorded")
|
|
268
|
+
return None
|
|
269
|
+
|
|
270
|
+
|
|
271
|
+
def _leaf() -> dspy.Predict | None:
|
|
272
|
+
# The innermost Predict on the call path makes the model call; a ChainOfThought holds one, and a direct call none.
|
|
273
|
+
modules = reversed(dspy.settings.caller_modules or [])
|
|
274
|
+
|
|
275
|
+
return next((module for module in modules if isinstance(module, dspy.Predict)), None)
|
|
276
|
+
|
|
277
|
+
|
|
278
|
+
def _messages(request: Request) -> list[Message]:
|
|
279
|
+
records = cast("list[_Record]", history_messages(request))
|
|
280
|
+
|
|
281
|
+
return [Message(role=record["role"], text=_text(record["content"])) for record in records]
|
|
282
|
+
|
|
283
|
+
|
|
284
|
+
def _reply(outputs: list[str | _Output]) -> list[Message]:
|
|
285
|
+
# A call of several candidates is one call with an output for each (clients/execution.py:497-507).
|
|
286
|
+
return [_assistant(output) for output in outputs]
|
|
287
|
+
|
|
288
|
+
|
|
289
|
+
def _assistant(output: str | _Output) -> Message:
|
|
290
|
+
if isinstance(output, str):
|
|
291
|
+
return Message(role="assistant", text=_utf8(output))
|
|
292
|
+
|
|
293
|
+
thinking = output.get("reasoning_content")
|
|
294
|
+
|
|
295
|
+
# Each tool call read as the part DSPy sends it back in (dspy/clients/call_result.py:48-52).
|
|
296
|
+
calls = [
|
|
297
|
+
_Part(type="tool_call", name=call["function"]["name"], input=json.loads(call["function"]["arguments"]))
|
|
298
|
+
for call in output.get("tool_calls", [])
|
|
299
|
+
]
|
|
300
|
+
|
|
301
|
+
return Message(
|
|
302
|
+
role="assistant",
|
|
303
|
+
text=_text([_Part(text=output.get("text") or ""), *calls]),
|
|
304
|
+
thinking=None if thinking is None else _utf8(thinking),
|
|
305
|
+
)
|
|
306
|
+
|
|
307
|
+
|
|
308
|
+
def _text(content: str | list[_Part]) -> str:
|
|
309
|
+
if isinstance(content, str):
|
|
310
|
+
return _utf8(content)
|
|
311
|
+
|
|
312
|
+
# A tool's call or result has no text of its own (dspy/_vendor/lm15/serde.py:201-212), so each takes a line.
|
|
313
|
+
text = "".join(part.get("text", "") for part in content)
|
|
314
|
+
tools = [_tool(part) for part in content if part.get("type") in {"tool_call", "tool_result"}]
|
|
315
|
+
|
|
316
|
+
return _utf8("\n".join([text, *tools] if text else tools))
|
|
317
|
+
|
|
318
|
+
|
|
319
|
+
def _tool(part: _Part) -> str:
|
|
320
|
+
if part.get("type") == "tool_result":
|
|
321
|
+
return _text(part.get("content", []))
|
|
322
|
+
|
|
323
|
+
# As DSPy's ToolCalls shows a call, by its name and args alone (dspy/adapters/types/tool.py:398-399).
|
|
324
|
+
return json.dumps({"name": part.get("name"), "args": part.get("input", {})}, ensure_ascii=False)
|
|
325
|
+
|
|
326
|
+
|
|
327
|
+
def _usage(usage: _Usage) -> Usage | None:
|
|
328
|
+
if "prompt_tokens" not in usage or "completion_tokens" not in usage:
|
|
329
|
+
return None
|
|
330
|
+
|
|
331
|
+
prompt = usage.get("prompt_tokens_details") or _Details()
|
|
332
|
+
completion = usage.get("completion_tokens_details") or _Details()
|
|
333
|
+
|
|
334
|
+
return Usage(
|
|
335
|
+
prompt_tokens=usage["prompt_tokens"],
|
|
336
|
+
completion_tokens=usage["completion_tokens"],
|
|
337
|
+
cached_tokens=prompt.get("cached_tokens", 0),
|
|
338
|
+
cache_creation_tokens=prompt.get("cache_creation_tokens", 0),
|
|
339
|
+
reasoning_tokens=completion.get("reasoning_tokens", 0),
|
|
340
|
+
)
|
|
341
|
+
|
|
342
|
+
|
|
343
|
+
def _settings(request: Request) -> Settings:
|
|
344
|
+
config = request.config
|
|
345
|
+
reasoning = config.reasoning
|
|
346
|
+
|
|
347
|
+
return Settings(
|
|
348
|
+
temperature=config.temperature,
|
|
349
|
+
max_tokens=config.max_tokens,
|
|
350
|
+
reasoning_effort=None if reasoning is None else reasoning.effort,
|
|
351
|
+
thinking_budget=None if reasoning is None else reasoning.thinking_budget,
|
|
352
|
+
)
|
|
353
|
+
|
|
354
|
+
|
|
355
|
+
def _utf8(text: str) -> str:
|
|
356
|
+
# A lone surrogate cannot be written as UTF-8, and one would spoil the whole reply line.
|
|
357
|
+
return text.encode("utf-8", "replace").decode("utf-8")
|