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
checksums.yaml
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
---
|
|
2
|
+
SHA256:
|
|
3
|
+
metadata.gz: 01f33b3f2af5d12139c99b94900a553e6c15f7b61c8dad532712c2351b59f8ef
|
|
4
|
+
data.tar.gz: deaa48594386a9769b3082e27b736403afb69814b0ba0585a6cb050398a5155c
|
|
5
|
+
SHA512:
|
|
6
|
+
metadata.gz: 853231fb8fdbeab947e974ed85a5cd2f5443c1133740b66204b708f63ef5c583d5abeb97d41f507b06ba012132af10952f8cf11d6f4c66db46f87d975bf876bc
|
|
7
|
+
data.tar.gz: a3cecf8020abd882e1b8906198accf86062285ca08fd65ffc158ea6cb3424df0ef9c5685eebc7bc254f0cdfd770d05c8435282b6035ed1849410fde1f3ff5da7
|
data/CHANGELOG.md
ADDED
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
# Changelog
|
|
2
|
+
|
|
3
|
+
## 0.1.0 (2026-12-01)
|
|
4
|
+
|
|
5
|
+
The first release, under active development. Ruby on DSPy gives you DSPy's API in Ruby, and the real DSPy 3.5.0 runs it.
|
|
6
|
+
|
|
7
|
+
### What you can do
|
|
8
|
+
|
|
9
|
+
- Declare a task as a signature: a `DSPyRb::Signature` class with typed fields, or a string such as `"question -> answer"`.
|
|
10
|
+
- Ask a model with `DSPyRb::Predict`, or with `DSPyRb::ChainOfThought` to have it reason first.
|
|
11
|
+
- Write a program as a `DSPyRb::Module` with a `forward` method.
|
|
12
|
+
- Call a model directly with `DSPyRb::LM#call`, as DSPy's `lm(prompt)` does.
|
|
13
|
+
- Give a model your Ruby tools (`DSPyRb::Tool`) and run DSPy's agent, `DSPyRb::ReAct`.
|
|
14
|
+
- Score a program with `DSPyRb::Evaluate`, using your own metric or DSPy's own from `DSPyRb::Metric`.
|
|
15
|
+
- Load DSPy's datasets with `DSPyRb::Dataset`, and your own CSV, JSON, Parquet or Hugging Face data with `DSPyRb::DataLoader`.
|
|
16
|
+
- Shuffle and sample exactly as DSPy does with `DSPyRb::PythonRandom`.
|
|
17
|
+
- Hold rows of data as `DSPyRb::Example`, and give predictors demos.
|
|
18
|
+
- Read and replace each predictor's instructions and demos by name.
|
|
19
|
+
- Compile a program with DSPy's `DSPyRb::LabeledFewShot`, which gives each predictor demos from your trainset: `DSPyRb::LabeledFewShot[k: 4].compile(program, trainset:)`. It returns a copy and leaves your program as it was.
|
|
20
|
+
- Compile with DSPy's `DSPyRb::BootstrapFewShot`, which keeps as demos the runs your metric passes: `DSPyRb::BootstrapFewShot[metric: method(:exact), max_rounds: 2].compile(program, trainset:, teacher:)`. A teacher program of your own and `teacher_settings: { lm: }` work as in DSPy.
|
|
21
|
+
- Compile with DSPy's `DSPyRb::GEPA`, which rewrites each predictor's instructions from your metric's feedback: `DSPyRb::GEPA[metric: method(:feedback), auto: "light", reflection_lm: DSPyRb::LM["openai/gpt-5"]].compile(program, trainset:, valset:)`. A GEPA metric takes five arguments, `(example, prediction, trace, pred_name, pred_trace)`, and returns a score or `DSPyRb::Prediction[score:, feedback:]`.
|
|
22
|
+
- With `track_stats: true`, the copy GEPA gives has `detailed_results`: DSPy's own `to_dict()` as a frozen Hash, read with DSPy's names, as `detailed_results[:best_idx]`. Keys inside are text, so validation row 0 is `"0"`, and a best output is `[candidate, outputs]`. Copies carry it, as DSPy's do, and `save` doesn't write it, as in DSPy.
|
|
23
|
+
- GEPA's `log_dir` keeps its run in that folder. A later compile there scores your program on the valset again, then picks the run up where it stopped, as in DSPy. `seed: nil` gives an unseeded run.
|
|
24
|
+
- Compile with DSPy's `DSPyRb::MIPROv2`, which proposes instructions, then picks instructions and demos by trials your metric scores: `DSPyRb::MIPROv2[metric: method(:exact), auto: "light"].compile(program, trainset:)`. `prompt_model:` and `task_model:` take a `DSPyRb::LM`. To set the budgets yourself, give `auto: nil` and `num_candidates:`, and `num_trials:` to `compile`. `seed: nil` gives an unseeded run.
|
|
25
|
+
- Compile with DSPy's `DSPyRb::BootstrapFewShotWithOptuna`, which bootstraps demos, then picks among them by trials your metric scores: `DSPyRb::BootstrapFewShotWithOptuna[metric: method(:exact)].compile(program, trainset:, max_demos: 2)`.
|
|
26
|
+
- Compile with DSPy's `DSPyRb::BootstrapFewShotWithRandomSearch`, which bootstraps several sets of demos and keeps the one that scores best on your valset: `DSPyRb::BootstrapFewShotWithRandomSearch[metric: method(:exact), num_candidate_programs: 8].compile(program, trainset:, valset:)`.
|
|
27
|
+
- Compile with DSPy's `DSPyRb::SIMBA`, which compares runs whose scores differ and adds demos and rules for each predictor, the rules written by its prompt model: `DSPyRb::SIMBA[metric: method(:exact), prompt_model: DSPyRb::LM["openai/gpt-4.1"]].compile(program, trainset:)`. Your metric gets `nil` for a run that raised, as DSPy passes it `None`. `seed: nil` given to `compile` gives an unseeded run.
|
|
28
|
+
- A metric gets what DSPy passes it. While bootstrapping, that is a third argument, the trace, as `[name, inputs, outputs]` steps, so give your metric an optional `trace = nil`. DSPy sees your metric's own parameters, so one that takes too few fails as a Python one would; a proc takes any number.
|
|
29
|
+
- Save a program's instructions and demos to DSPy's own JSON file with `program.save("program.json")`, and load them back with `load`. A Module loads in place and returns itself, as in DSPy; a predictor's `load` returns a copy. Python's DSPy reads the files the gem writes, and the gem reads DSPy's.
|
|
30
|
+
- Change the model, adapter or listener for one block with `DSPyRb.context`.
|
|
31
|
+
- Read the LM in force with `DSPyRb.lm`, as DSPy's `dspy.settings.lm`: the innermost `DSPyRb.context`'s, else `config.lm`, else `nil`. In code DSPy calls back (a `forward`, a tool, a metric) with none set there, it's DSPy's own, such as a teacher's LM or a new round's copy. In a gate, it's the LM the call goes to, such as the copy SIMBA gives each trial.
|
|
32
|
+
- Ask for another answer with a copy of the LM in force, as DSPy's own retries do: `DSPyRb.context(lm: DSPyRb.lm.copy(rollout_id: 2, temperature: 1.0)) { ... }`. It works for a predictor, a `ReAct` and your own `Module`.
|
|
33
|
+
- Read an LM's default call options with `kwargs`, as DSPy's `lm.kwargs`: `DSPyRb.lm.kwargs[:rollout_id]`. It never reads the LM's key, and shows a value that looks like a key as `"[hidden]"`.
|
|
34
|
+
- Let each model call go, or refuse it before it's sent, with a gate: `DSPyRb.context(before_call: ->(pending) { ... })`. `DSPyRb.config.before_call` sets one for calls made where no context does.
|
|
35
|
+
- Run your own code around tools, metrics, a program's `forward`, gates and listeners called off your thread with `DSPyRb.context(around:)`, to carry request state such as a tenant.
|
|
36
|
+
- Test with `DSPyRb::DummyLM`, DSPy's own test model: scripted answers, no key, no network, no cost.
|
|
37
|
+
|
|
38
|
+
### What it promises
|
|
39
|
+
|
|
40
|
+
- Every prediction and evaluation result carries its `spend`: each model call, with its model, messages, usage, cost and duration.
|
|
41
|
+
- Every error from a request that made model calls carries its `spend` too, except an error your listener raised.
|
|
42
|
+
- A program's `spend` adds up every model call made inside it.
|
|
43
|
+
- `on_call` listeners see each model call as it finishes. Every listener takes every call, outermost first.
|
|
44
|
+
- A listener that raises stops the whole call it was made under at once, an evaluate or a compile included. The first error is raised once every listener has taken that call.
|
|
45
|
+
- Every model call a compile makes, its teacher's, each round's, MIPROv2's proposals and trials and SIMBA's rules included, reaches your gates and listeners.
|
|
46
|
+
- Each model call has an `id`, unique across processes, the same in its gate and in its listeners.
|
|
47
|
+
- A gate can refuse a call before it's sent, by raising any error. Nothing is sent, the whole call stops, and it raises the gate's own error. Gates are asked outermost first, and one that refuses ends the asking.
|
|
48
|
+
- Every call a gate saw reaches your listeners once: as the call, or with outcome `"unsent"` when it was never sent, at no cost and in no `spend`. A few cases leave a call unreported, so give each reservation an expiry longer than your slowest call:
|
|
49
|
+
- DSPy's process is lost: it crashes or freezes, or shutdown passes `grace`.
|
|
50
|
+
- A call couldn't be recorded or read, or still runs an hour after its request ended. It goes unreported, and so does every call of that request that never went.
|
|
51
|
+
- A gate never returns.
|
|
52
|
+
- A listener raises an error outside `StandardError`, or an around hook raises or skips its block around a listener called off your thread.
|
|
53
|
+
- Your Ruby process ends first.
|
|
54
|
+
- A gate that gives no answer within 60 s has its call refused with a `DSPyRb::Error`. Its own code is never cut short.
|
|
55
|
+
- A gate can't make model calls, and with no gate set nothing is asked.
|
|
56
|
+
- Keys come from the app's environment, such as `OPENAI_API_KEY`, or from `config.env` for keys kept elsewhere, such as encrypted credentials.
|
|
57
|
+
- A key in the app's environment or `config.env` never travels with a call: DSPy reads it itself, which is why `api_key:` is refused. A credential you pass as an LM option, such as `aws_secret_access_key:` or an `Authorization` header, travels with the LM's settings, so keep it in the environment instead. `config.env` prints variable names only, and `inspect` and error messages hide key-like text.
|
|
58
|
+
- Error messages are plain. Every error the gem raises is a `DSPyRb::Error`, and a wrong argument is named, never its value: `DSPyRb::Evaluate takes no num_thread`.
|
|
59
|
+
- DSPy's errors keep DSPy's names, and `retryable` says whether a retry may help.
|
|
60
|
+
- A missing key's error says which variable to set, and where.
|
|
61
|
+
- Ruby code DSPy calls back (tools, metrics, gates, a program's `forward` under `Evaluate` or a compile) sees the caller's `Fiber[]` storage.
|
|
62
|
+
|
|
63
|
+
### Setup and requirements
|
|
64
|
+
|
|
65
|
+
- Ruby 3.3.1 or later, on macOS or Linux, arm64 or x86_64.
|
|
66
|
+
- Add `gem "ruby-on-dspy"`, then run `bundle exec ruby-on-dspy setup`. It installs Python 3.12 and DSPy 3.5.0, every package pinned, in a folder of their own. You need no Python or uv of your own.
|
|
67
|
+
- `bundle exec ruby-on-dspy doctor` checks the install without calling a model.
|
|
68
|
+
- Most dataset loaders, and `Metric.math_metric`, need `setup --with data`. Without it they raise `DSPyRb::Refused`.
|
|
69
|
+
- `setup` installs optuna too, which `MIPROv2` and `BootstrapFewShotWithOptuna` run their trials on.
|
|
70
|
+
- The install lives in `~/.cache/ruby-on-dspy`. Set `RUBY_ON_DSPY_ENVIRONMENT` to move it, both for `setup` and for your app.
|
|
71
|
+
- Each installed copy of the gem gets its own environment, so two apps on different commits never break each other.
|
|
72
|
+
- `setup` removes environments whose copy of the gem is gone, naming each and its size. If the folder that held the copy is gone too, as with a removed Ruby or a deleted app, it keeps the environment and says so; delete it yourself if that Ruby or app is gone for good.
|
|
73
|
+
- Configure with `DSPyRb.configure`: `lm`, `adapter`, `env`, `threads`, `grace`, `logging` and `before_call`.
|
|
74
|
+
- `api_key:` is refused. For a key under a variable of your own naming, pass `api_key_env:` to `DSPyRb::LM[...]` and put the variable in `config.env`. `LM#call` refuses `api_key_env:`, which DSPy would send to the provider.
|
|
75
|
+
|
|
76
|
+
### Good to know
|
|
77
|
+
|
|
78
|
+
- DSPy runs in one Python process of about 250 MB, started on the first call or by `DSPyRb.start`. Each forked worker starts its own.
|
|
79
|
+
- Many threads can call at once, 8 by default. Wrap thread-pool jobs in `DSPyRb.capture { ... }` to keep your settings.
|
|
80
|
+
- The gem never cuts a long call. Limit one with the LM's `timeout:` and `num_retries:`.
|
|
81
|
+
- If DSPy's process is lost or freezes, the call raises `DSPyRb::Unavailable`, and the next call starts it again.
|
|
82
|
+
- `cost` is DSPy's estimate in US dollars. `nil` means unknown, never free. `config.env` can point DSPy at another price list.
|
|
83
|
+
- A tool's call and its result show in `spend.calls[...].messages` under every adapter. Under the chat and XML adapters they show, as before, as DSPy writes them in its `tool_calls` and `tool_call_results` fields. Under the JSON adapter, which calls tools natively, they were missing; now the call shows as its name and arguments, `{"name": "lookup", "args": {"key": "Rome"}}`, and the result as its text, each on a line of its own.
|
|
84
|
+
- `LM#call` outputs carry no `spend`. Watch them with `on_call`, or make them inside a program.
|
|
85
|
+
- `setup`'s cleanup assumes one machine uses the environment folder. Shared with another machine or container, it can remove the other's environments.
|
|
86
|
+
- A gate should answer at once, from what your app already holds. It runs on one of DSPy's threads, so other calls wait while it does. To wait for budget, reserve it before the work, or refuse and retry from your job queue.
|
|
87
|
+
- A listener that counts billed calls skips those with outcome `"unsent"`.
|
|
88
|
+
- The same `rollout_id` again is answered from DSPy's cache, with `cache_hit` true and nothing billed, once the first call has finished and on the same machine. A new `rollout_id` is a new, billed call, even at temperature 0. Two identical calls at once are both sent and billed, so guard a double click in your app.
|
|
89
|
+
- A copy keeps its LM's model, host and key: `copy` refuses `model:`, `kwargs:`, `api_key_env:` and DSPy's connection settings, such as `api_base:` and `custom_llm_provider:`. For another model, host or provider, make a new `DSPyRb::LM`. A `DummyLM`'s copy goes on with its script, and a `DummyLM` never caches, so a repeated `rollout_id` takes its next answer.
|
|
90
|
+
- Code DSPy calls back (a `forward`, a tool, a metric) runs its calls on the LM and adapter DSPy has in force there, unless it sets its own with `DSPyRb.context`; with none in force, DSPy's own error says so.
|
|
91
|
+
- A compile can't tell two `DummyLM`s' lists of answers apart, a copy and its original included, so one in force beside another in `teacher_settings` is refused: use the same `DummyLM` in both, or give the other its answers by text.
|
|
92
|
+
- Lines DSPy prints as it runs, such as `BootstrapFewShot`'s count of the traces it kept, show on your app's stderr.
|
|
93
|
+
- A compile or a load whose state your program can't hold, such as a model of its own for one predictor, raises `DSPyRb::StateError`. Nothing is applied. A compile's error says what it spent.
|
|
94
|
+
- Saving and loading use DSPy's JSON file only, never a pickle: a path not ending in `.json`, or `save_program: true`, raises `DSPyRb::Error`.
|
|
95
|
+
- A Module loads in place, so a load that would change a frozen part of it raises `DSPyRb::Error` and changes nothing.
|
|
96
|
+
- GEPA's `instruction_proposer` and `code_proposer`, and its Weights & Biases and MLflow options, are refused.
|
|
97
|
+
- GEPA's `log_dir` holds a pickle GEPA reads back to resume, so give it a folder only your app writes.
|
|
98
|
+
- DSPy checks an optimizer's options itself, such as GEPA's need for exactly one budget and a `reflection_lm`, when you compile, not when you make the optimizer.
|
|
99
|
+
- MIPROv2 sends your program's Ruby source to the model that proposes instructions, as DSPy sends a Python program's: your `DSPyRb::Module` classes and the signature classes their predictors use. Some keys in it show as `[hidden]`: a string given to a name such as `api_key` or `password`, and text in a string or comment that starts like a key, such as `sk-` or `AIza`. Any other key is sent as written, so keep keys out of your source. Pass `program_aware_proposer: false` to `compile` to keep the source out. A Module whose class has no source file, such as one made with `Class.new`, is proposed for without it, as in DSPy, which prints why on your app's stderr.
|
|
100
|
+
- SIMBA sends your program's Ruby source to its prompt model as it writes a rule, as DSPy sends a Python program's: the same text MIPROv2 sends, with the same keys hidden. For a Module whose class has no source file, SIMBA writes no rules, as DSPy writes none for a class it can't read, and can still add demos.
|
|
101
|
+
- A `ChainOfThought`'s `reasoning` is a `DSPyRb::Values::Reasoning`, a String, and a `ReAct`'s `history` a `DSPyRb::Values::History`, a Hash. Each reaches DSPy as DSPy's own type when you give it to a predictor, return it in a `Prediction` or keep it in an `Example`, in a Hash or Array of yours too, and a metric's example and prediction, and `Evaluate`'s results, hold them as such. Text made from one, such as `"#{pred.reasoning}"`, is plain, as in Python. YAML writes them as plain text and a plain Hash.
|
|
102
|
+
- A list or Hash your `forward` gives a predictor reaches DSPy as it is at that call. DSPy keeps the object itself, so when your code changes it afterward, as DSPy's tool-use tutorial appends to its trajectory, what DSPy reads back from that call later, such as SIMBA's rule prompt, GEPA's reflection and the demos an optimizer keeps, shows it as it ended in Python, and as it was at each call in Ruby. Give each call a new list, such as `steps = [*steps, step]`, and the two match.
|
|
103
|
+
- Input names DSPy keeps for itself are refused before anything is sent: `config`, `demos`, `lm`, `signature` and `new_signature`, and for a ReAct also `max_iters` and `history`. They're refused in a signature, at a call, and in an example's inputs under `Evaluate` or a compile that calls a predictor, a valset's too; for a Module, that example fails at its predictor's call. Rename the input. A `Predict` can still take an input named `history`. An input named `prediction` takes text or a Hash, but not one shaped as predicted outputs (`type: "content"` with a `content` key), which DSPy would take as the call's settings.
|
|
104
|
+
- Text holding DSPy's custom-type markers (`<<CUSTOM-TYPE-START-IDENTIFIER>>`), which DSPy reserves for its own types, is refused with a plain error before anything is sent, as reserved input names are; a tool's result or error holding them reaches the model as that plain error. Remove the markers from the text.
|
|
105
|
+
- An around hook must run the block it's given exactly once; one that doesn't, or runs it again, fails that code with a `DSPyRb::Error`. A hook can't hide a gate's refusal or a listener's raise: the call is still refused or stopped, whatever the hook rescues. Around tools, metrics and `forward`, a hook is plain Ruby, so it may rescue an error and return a fallback.
|
|
106
|
+
|
|
107
|
+
### Not supported yet
|
|
108
|
+
|
|
109
|
+
- DSPy's optimizers other than `LabeledFewShot`, `BootstrapFewShot`, `GEPA`, `MIPROv2`, `BootstrapFewShotWithOptuna`, `BootstrapFewShotWithRandomSearch` and `SIMBA`. You can tune a program yourself by reading and replacing its instructions and demos.
|
|
110
|
+
- What MIPROv2, SIMBA and `BootstrapFewShotWithRandomSearch` attach to the program they give, such as `score`, `candidate_programs` and `trial_logs`.
|
|
111
|
+
- Field types other than `String`, `Integer`, `Float`, `Types::Boolean`, and lists, dicts, optionals and literals of them.
|
|
112
|
+
- Counting calls to an embedding model in `spend`.
|
data/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Samuel Ralak
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
data/README.md
ADDED
|
@@ -0,0 +1,442 @@
|
|
|
1
|
+
# Ruby on DSPy
|
|
2
|
+
|
|
3
|
+
Ruby bindings for [DSPy](https://dspy.ai).
|
|
4
|
+
|
|
5
|
+
> **Under active development.** Until 1.0, a minor release may change the API; the [CHANGELOG](CHANGELOG.md) says what changed and what to do.
|
|
6
|
+
|
|
7
|
+
Ruby on DSPy (`ruby-on-dspy`) gives you DSPy's API in Ruby. Signatures, predictors, programs, tools and evaluations are Ruby classes, and the real DSPy 3.5.0 runs them, so you get DSPy's exact prompts, behaviour and results without leaving Ruby.
|
|
8
|
+
|
|
9
|
+
Unlike [DSPy.rb](https://github.com/vicentereig/dspy.rb), a Ruby reimplementation, it runs DSPy itself.
|
|
10
|
+
|
|
11
|
+
## How it works
|
|
12
|
+
|
|
13
|
+
`ruby-on-dspy setup` installs Python 3.12 and DSPy into a folder of their own (see Install); your system Python is never used. The first call starts one Python process. Each call goes to it over a pipe, DSPy runs it, and the outputs come back with every model call it made. Tools and metrics you write in Ruby are called back in Ruby. Many threads can call at once. The process stops when Ruby exits, and each forked worker starts its own.
|
|
14
|
+
|
|
15
|
+
## Install
|
|
16
|
+
|
|
17
|
+
```ruby
|
|
18
|
+
gem "ruby-on-dspy"
|
|
19
|
+
```
|
|
20
|
+
|
|
21
|
+
```bash
|
|
22
|
+
bundle install
|
|
23
|
+
bundle exec ruby-on-dspy setup # installs DSPy, every package pinned
|
|
24
|
+
bundle exec ruby-on-dspy doctor # checks the install, without calling a model
|
|
25
|
+
```
|
|
26
|
+
|
|
27
|
+
- Add `--with data` to `setup` for DSPy's datasets.
|
|
28
|
+
- The install lives in `~/.cache/ruby-on-dspy`, one environment for each installed copy of the gem. `setup` removes environments whose gem copy is gone. If the folder that held the copy is gone too (a removed Ruby or app), it keeps the environment and says so, for you to delete. To keep it elsewhere, set `RUBY_ON_DSPY_ENVIRONMENT` to a folder, both when you run `setup` and when your app runs.
|
|
29
|
+
- Docker is optional: ruby-on-dspy never needs it. In a Docker image, run `setup` while building, with `RUBY_ON_DSPY_ENVIRONMENT` set to a folder the final image keeps.
|
|
30
|
+
|
|
31
|
+
## Configure
|
|
32
|
+
|
|
33
|
+
```ruby
|
|
34
|
+
DSPyRb.configure do |c|
|
|
35
|
+
c.lm = DSPyRb::LM["openai/gpt-4.1-mini", temperature: 1.0]
|
|
36
|
+
end
|
|
37
|
+
```
|
|
38
|
+
|
|
39
|
+
| Setting | What it does |
|
|
40
|
+
|---|---|
|
|
41
|
+
| `lm` | The model, as `provider/model`, with DSPy's LM options (`temperature`, `max_tokens`, `timeout`, ...). |
|
|
42
|
+
| `adapter` | How prompts are formatted: `DSPyRb::Adapter.chat`, `.json` or `.xml`. Unset, DSPy's default. |
|
|
43
|
+
| `env` | Keys and other variables for DSPy beyond the app's own environment, read when it starts. A key here or in the environment never travels with a call. |
|
|
44
|
+
| `threads` | How many calls run at once. Default 8. |
|
|
45
|
+
| `grace` | Seconds that running calls get to finish at shutdown. Default 30. |
|
|
46
|
+
| `logging` | `false` silences DSPy's logs, which are on by default. |
|
|
47
|
+
| `before_call` | A gate for model calls made where no context sets one, such as in a console or a rake task. Unset, none. |
|
|
48
|
+
|
|
49
|
+
A key under a variable of your own naming: `DSPyRb::LM["openai/gpt-4.1-mini", api_key_env: "TEAM_OPENAI_KEY"]`, with that variable in `env`. A credential passed as an LM option, such as `aws_secret_access_key:` or an `Authorization` header, travels with the LM's settings, so keep credentials in the environment.
|
|
50
|
+
|
|
51
|
+
A key in the app's environment, such as `OPENAI_API_KEY`, reaches DSPy as it is. `env` is for keys kept elsewhere, such as an app's encrypted credentials.
|
|
52
|
+
|
|
53
|
+
DSPy starts on the first call; `DSPyRb.start` starts it earlier, at boot for example. In a server that forks workers, call it in each worker after the fork, as in the server's worker-boot hook: each worker runs its own.
|
|
54
|
+
|
|
55
|
+
## Signatures
|
|
56
|
+
|
|
57
|
+
A signature declares a task's inputs and outputs:
|
|
58
|
+
|
|
59
|
+
```ruby
|
|
60
|
+
class TriageTicket < DSPyRb::Signature
|
|
61
|
+
instructions "Classify the support ticket."
|
|
62
|
+
input :ticket, String
|
|
63
|
+
output :category, DSPyRb::Types::Literal["billing", "bug", "other"]
|
|
64
|
+
output :urgent, DSPyRb::Types::Boolean, desc: "Needs a reply today"
|
|
65
|
+
end
|
|
66
|
+
```
|
|
67
|
+
|
|
68
|
+
For plain text fields, a string does: `"question -> answer"`.
|
|
69
|
+
|
|
70
|
+
Field types: `String`, `Integer`, `Float`, `Types::Boolean`, and `Types::List`, `Types::Dict`, `Types::Optional` and `Types::Literal` of them.
|
|
71
|
+
|
|
72
|
+
Some input names are DSPy's own call options and are refused: `config`, `demos`, `lm`, `signature` and `new_signature`, and for a ReAct `max_iters` and `history`. An input named `prediction` takes text or a Hash, but not one shaped as predicted outputs (`type: "content"` with a `content` key), which DSPy would take as the call's settings.
|
|
73
|
+
|
|
74
|
+
Text holding DSPy's custom-type markers (`<<CUSTOM-TYPE-START-IDENTIFIER>>`), which DSPy reserves for its own types, is refused before anything is sent. Remove the markers from the text.
|
|
75
|
+
|
|
76
|
+
## Predictors
|
|
77
|
+
|
|
78
|
+
`Predict` asks the model for the outputs. `ChainOfThought` has it reason first, and adds a `reasoning` output.
|
|
79
|
+
|
|
80
|
+
```ruby
|
|
81
|
+
triage = DSPyRb::Predict[TriageTicket]
|
|
82
|
+
result = triage.call(ticket: "The export button crashes the app.")
|
|
83
|
+
|
|
84
|
+
result.category # => "bug"
|
|
85
|
+
result[:category] # the same
|
|
86
|
+
|
|
87
|
+
DSPyRb::Predict[TriageTicket, instructions: "Classify tickets for the billing team."]
|
|
88
|
+
```
|
|
89
|
+
|
|
90
|
+
Build predictors, LMs and examples with `[]`, as shown.
|
|
91
|
+
|
|
92
|
+
## Programs
|
|
93
|
+
|
|
94
|
+
A program is a `DSPyRb::Module`: hold predictors in instance variables and call them in `forward`.
|
|
95
|
+
|
|
96
|
+
```ruby
|
|
97
|
+
class Answer < DSPyRb::Module
|
|
98
|
+
def initialize
|
|
99
|
+
super
|
|
100
|
+
@answer = DSPyRb::ChainOfThought["question -> answer"]
|
|
101
|
+
end
|
|
102
|
+
|
|
103
|
+
def forward(question:)
|
|
104
|
+
@answer.call(question:)
|
|
105
|
+
end
|
|
106
|
+
end
|
|
107
|
+
|
|
108
|
+
Answer.new.call(question: "Who wrote Hamlet?").answer
|
|
109
|
+
```
|
|
110
|
+
|
|
111
|
+
Change the model, adapter or listener for one block. Settings you leave out keep the outer values.
|
|
112
|
+
|
|
113
|
+
```ruby
|
|
114
|
+
DSPyRb.context(lm: DSPyRb::LM["openai/gpt-4.1"]) do
|
|
115
|
+
Answer.new.call(question: "Who wrote Hamlet?")
|
|
116
|
+
end
|
|
117
|
+
```
|
|
118
|
+
|
|
119
|
+
## Calling a model directly
|
|
120
|
+
|
|
121
|
+
`LM#call` sends a prompt as it is, as DSPy's `lm(prompt)` does, and returns the outputs, one per candidate:
|
|
122
|
+
|
|
123
|
+
```ruby
|
|
124
|
+
lm = DSPyRb::LM["openai/gpt-4.1-mini"]
|
|
125
|
+
lm.call("Say hello in French.") # => ["Bonjour !"]
|
|
126
|
+
lm.call("Name a colour.", n: 2) # => ["Teal", "Amber"]
|
|
127
|
+
```
|
|
128
|
+
|
|
129
|
+
- Options go to DSPy as given (`temperature:`, `max_tokens:`, `n:`, `cache:`, `timeout:`, ...). Keys belong in `config.env`; `api_key:` is refused.
|
|
130
|
+
- An output is text, or a Hash where DSPy returns one.
|
|
131
|
+
- No adapter formats the request. A `DummyLM`'s scripted answer is formatted by the adapter in force, as in DSPy.
|
|
132
|
+
- The outputs carry no `spend`. Watch the calls with `on_call`, or make them inside a program, whose `spend` counts them and any it could not record.
|
|
133
|
+
|
|
134
|
+
### Another answer to the same question
|
|
135
|
+
|
|
136
|
+
To get a different answer to the same input, as for "suggest another reply", copy the LM in force with a new `rollout_id`:
|
|
137
|
+
|
|
138
|
+
```ruby
|
|
139
|
+
lm = DSPyRb.lm.copy(rollout_id: attempt, temperature: 1.0)
|
|
140
|
+
DSPyRb.context(lm:) { Reply.new.call(ticket:) }
|
|
141
|
+
```
|
|
142
|
+
|
|
143
|
+
- `DSPyRb.lm` is the LM in force: the innermost context's, else `config.lm`, else `nil`. In code DSPy calls back, such as a `forward` under a compile, it's the LM DSPy has in force there.
|
|
144
|
+
- `DSPyRb.lm.kwargs` gives its default call options, as DSPy's `lm.kwargs`. Read `DSPyRb.lm.kwargs[:rollout_id]` in a listener to tell your attempts apart, or in a gate, which sees the LM each call goes to, such as the copy SIMBA gives each trial. It never reads the key, and a value that looks like one shows as `"[hidden]"`.
|
|
145
|
+
- The same `rollout_id` again is answered from DSPy's cache, with nothing billed, once the first call has finished, on the same machine. A new one is a new, billed call. Keep the temperature above 0.
|
|
146
|
+
- Two identical requests at the same moment are both sent, so guard a double click in your app: disable the button while it runs, or give the job a unique key in your queue.
|
|
147
|
+
- `copy` refuses `model:`, `api_key_env:`, `kwargs:` and every setting that changes the host or provider (`api_base:`, `custom_llm_provider:`, ...), so your key never goes anywhere else: for another model or host, make a new `DSPyRb::LM`. A `DummyLM` copy keeps its script, and a `DummyLM` never caches.
|
|
148
|
+
|
|
149
|
+
## Examples and demos
|
|
150
|
+
|
|
151
|
+
An `Example` is a row of data. Demos show the model worked examples.
|
|
152
|
+
|
|
153
|
+
```ruby
|
|
154
|
+
example = DSPyRb::Example[question: "What is 2+2?", answer: "4"].with_inputs(:question)
|
|
155
|
+
example[:question] # => "What is 2+2?"
|
|
156
|
+
|
|
157
|
+
answer = DSPyRb::Predict["question -> answer", demos: [example]]
|
|
158
|
+
Answer.new.with_demos("answer.predict" => [example]) # a copy, demos set by predictor name
|
|
159
|
+
```
|
|
160
|
+
|
|
161
|
+
## Tools and ReAct
|
|
162
|
+
|
|
163
|
+
`ReAct` is DSPy's agent: the model calls your tools, then calls `submit` with the outputs. A tool is a Ruby class with typed arguments and a `call` that takes them as keywords.
|
|
164
|
+
|
|
165
|
+
```ruby
|
|
166
|
+
class SearchDocs < DSPyRb::Tool
|
|
167
|
+
desc "Search the product documentation."
|
|
168
|
+
arg :query, String
|
|
169
|
+
arg :limit, Integer, default: 5, desc: "how many passages"
|
|
170
|
+
|
|
171
|
+
def call(query:, limit:)
|
|
172
|
+
Docs.search(query).first(limit)
|
|
173
|
+
end
|
|
174
|
+
end
|
|
175
|
+
|
|
176
|
+
agent = DSPyRb::ReAct["question -> answer", tools: [SearchDocs.new], max_iters: 4]
|
|
177
|
+
result = agent.call(question: "How do I export a report?")
|
|
178
|
+
|
|
179
|
+
result.answer
|
|
180
|
+
result.termination_reason # => "submit"
|
|
181
|
+
```
|
|
182
|
+
|
|
183
|
+
A tool result or error holding DSPy's custom-type markers reaches the model as a plain error, and the agent goes on.
|
|
184
|
+
|
|
185
|
+
A tool that needs other objects takes them when it's made:
|
|
186
|
+
|
|
187
|
+
```ruby
|
|
188
|
+
class SearchIndex < DSPyRb::Tool
|
|
189
|
+
extend Dry::Initializer
|
|
190
|
+
|
|
191
|
+
option :index
|
|
192
|
+
|
|
193
|
+
desc "Search the product documentation."
|
|
194
|
+
arg :query, String
|
|
195
|
+
|
|
196
|
+
def call(query:)
|
|
197
|
+
index.search(query)
|
|
198
|
+
end
|
|
199
|
+
end
|
|
200
|
+
|
|
201
|
+
DSPyRb::ReAct["question -> answer", tools: [SearchIndex.new(index: Docs.index)]]
|
|
202
|
+
```
|
|
203
|
+
|
|
204
|
+
- Defaults live in `arg` only. `call` takes every argument as a required keyword, and any the model leaves out arrive with their defaults.
|
|
205
|
+
- Arguments and signature fields can't be reserved words such as `from` or `class`.
|
|
206
|
+
- A tool is named after its class in snake case (`search_docs`); `tool_name "..."` changes it.
|
|
207
|
+
- `call` returns strings, numbers, booleans, `nil`, arrays and hashes of them, or a `DSPyRb::Prediction`. Anything else reaches the model as an error.
|
|
208
|
+
- When a tool raises, the model sees the error and the agent goes on. An `Interrupt`, a stop or a killed thread ends the agent.
|
|
209
|
+
- Under `Evaluate`, a tool can run on several threads at once.
|
|
210
|
+
|
|
211
|
+
## Evaluate
|
|
212
|
+
|
|
213
|
+
`Evaluate` scores a program on a devset with your metric. The program can be a predictor, a `ReAct` or your own `DSPyRb::Module`.
|
|
214
|
+
|
|
215
|
+
```ruby
|
|
216
|
+
devset = [DSPyRb::Example[question: "What is 2+2?", answer: "4"].with_inputs(:question)]
|
|
217
|
+
exact = ->(example, prediction) { example[:answer] == prediction.answer }
|
|
218
|
+
|
|
219
|
+
result = DSPyRb::Evaluate[devset:, metric: exact, num_threads: 8].call(DSPyRb::Predict["question -> answer"])
|
|
220
|
+
result.score # => 100.0
|
|
221
|
+
example, prediction, score = result.results.first
|
|
222
|
+
result.spend.calls # every model call, your metric's included
|
|
223
|
+
```
|
|
224
|
+
|
|
225
|
+
- A metric returns `true` or `false`, a number, or a `Prediction` with a `score`. It runs on up to `num_threads` threads at once, so keep any shared state thread-safe.
|
|
226
|
+
- A metric that raises scores `failure_score` (default 0). After `max_errors` failures (default 10), the evaluate stops and raises.
|
|
227
|
+
- Options passed to `call` apply to that call only.
|
|
228
|
+
- DSPy's built-in metrics: `DSPyRb::Metric.answer_exact_match`, `.answer_passage_match`, `.semantic_f1`, `.complete_and_grounded`, `.gsm8k_metric`, and `.math_metric` with the data group. Pass one as `metric:`, or score one example: `DSPyRb::Metric.semantic_f1.call(example, prediction).score`.
|
|
229
|
+
|
|
230
|
+
## Datasets
|
|
231
|
+
|
|
232
|
+
DSPy's datasets and `DataLoader` return Examples. Most need `setup --with data`, and raise `DSPyRb::Refused` without it; `Dataset.colors`, `DataLoader.sample`, `train_test_split` and `PythonRandom` work either way.
|
|
233
|
+
|
|
234
|
+
```ruby
|
|
235
|
+
hotpot = DSPyRb::Dataset.hot_pot_qa(train_seed: 1, train_size: 20, eval_seed: 2023, dev_size: 50, test_size: 0)
|
|
236
|
+
hotpot.train.first[:question]
|
|
237
|
+
|
|
238
|
+
tickets = DSPyRb::DataLoader.from_csv("tickets.csv", input_keys: [:ticket])
|
|
239
|
+
split = DSPyRb::DataLoader.train_test_split(tickets, train_size: 0.8, random_state: 0)
|
|
240
|
+
split[:train]
|
|
241
|
+
|
|
242
|
+
DSPyRb::PythonRandom[0].shuffle(tickets)
|
|
243
|
+
```
|
|
244
|
+
|
|
245
|
+
- `Dataset.gsm8k`, `.math(subset:)` and `.colors` load DSPy's other datasets, with DSPy's options and defaults; a misspelled option raises. Reading a split a dataset doesn't have raises `DSPyRb::DSPyError`.
|
|
246
|
+
- `DataLoader` also reads `from_json`, `from_parquet` and `from_huggingface`. Without `split:`, `from_huggingface` returns every split, keyed by name (`[:train]`).
|
|
247
|
+
- To shuffle or sample exactly as DSPy's examples do, use `DSPyRb::PythonRandom[seed]`, not Ruby's `shuffle`. Each call starts from the seed, so it repeats. `DataLoader.sample` draws from DSPy's shared random; to repeat a sample, use `PythonRandom`.
|
|
248
|
+
- A loaded column that an `Example` reader would hide (`class`, `values`, `keys`, `size` and the like) raises; leave it out with `fields:`.
|
|
249
|
+
- Downloads go to the Hugging Face cache. In `config.env`, set `HF_HOME` to move it, or `HF_HUB_OFFLINE` to work offline.
|
|
250
|
+
|
|
251
|
+
## Tuning
|
|
252
|
+
|
|
253
|
+
An optimizer reads and replaces each predictor's instructions and demos, by name:
|
|
254
|
+
|
|
255
|
+
```ruby
|
|
256
|
+
program = Answer.new
|
|
257
|
+
program.named_predictors # => [["answer.predict", #<DSPyRb::ChainOfThought ...>]]
|
|
258
|
+
program.instructions # => { "answer.predict" => "Given the fields `question`, ..." }
|
|
259
|
+
program.with_instructions("answer.predict" => "Answer in one word.") # a copy with new instructions
|
|
260
|
+
```
|
|
261
|
+
|
|
262
|
+
Copies share every instance variable that isn't a predictor (a cache, a log), so keep per-trial state out of them.
|
|
263
|
+
|
|
264
|
+
DSPy's optimizers compile a program for you. `LabeledFewShot` gives each predictor `k` labelled examples as demos:
|
|
265
|
+
|
|
266
|
+
```ruby
|
|
267
|
+
compiled = DSPyRb::LabeledFewShot[k: 4].compile(Answer.new, trainset:)
|
|
268
|
+
compiled.demos # => { "answer.predict" => [...] }
|
|
269
|
+
```
|
|
270
|
+
|
|
271
|
+
`compile` returns a copy; your program is unchanged. `sample: false` takes the first `k` instead of DSPy's fixed draw of `k`.
|
|
272
|
+
|
|
273
|
+
`BootstrapFewShot` runs a teacher over the trainset and keeps the runs your metric passes as demos:
|
|
274
|
+
|
|
275
|
+
```ruby
|
|
276
|
+
def exact(example, prediction, trace = nil)
|
|
277
|
+
example.answer == prediction.answer
|
|
278
|
+
end
|
|
279
|
+
|
|
280
|
+
optimizer = DSPyRb::BootstrapFewShot[metric: method(:exact), max_rounds: 2]
|
|
281
|
+
compiled = optimizer.compile(Answer.new, trainset:, teacher: Answer.new)
|
|
282
|
+
```
|
|
283
|
+
|
|
284
|
+
The teacher is the program itself unless you give one. DSPy passes the metric a `trace` while it bootstraps, so give it `trace = nil`. Every call the compile makes reaches your gates and listeners.
|
|
285
|
+
|
|
286
|
+
`GEPA` rewrites each predictor's instructions from your metric's feedback. Its metric takes five arguments, and returns a score, or a score with feedback when GEPA names the predictor it asks about:
|
|
287
|
+
|
|
288
|
+
```ruby
|
|
289
|
+
def feedback(example, prediction, trace = nil, pred_name = nil, pred_trace = nil)
|
|
290
|
+
score = example.answer == prediction.answer ? 1.0 : 0.0
|
|
291
|
+
pred_name ? DSPyRb::Prediction[score:, feedback: "The answer is #{example.answer}."] : score
|
|
292
|
+
end
|
|
293
|
+
|
|
294
|
+
reflection_lm = DSPyRb::LM["openai/gpt-5", temperature: 1.0]
|
|
295
|
+
optimizer = DSPyRb::GEPA[metric: method(:feedback), auto: "light", reflection_lm:, track_stats: true]
|
|
296
|
+
compiled = optimizer.compile(Answer.new, trainset:, valset:)
|
|
297
|
+
compiled.detailed_results[:best_idx] # => 0
|
|
298
|
+
```
|
|
299
|
+
|
|
300
|
+
`detailed_results` is DSPy's `to_dict()`, frozen, with DSPy's names; keys inside are text, so validation row 0 is `"0"`. Copies carry it, as in DSPy, and `save` doesn't write it. DSPy checks GEPA's options when you compile, such as its one budget and its `reflection_lm`, whose calls reach your gates and listeners. `log_dir:` keeps the run in a folder a later compile resumes from; GEPA reads back a pickle there, so give it a folder only your app writes.
|
|
301
|
+
|
|
302
|
+
`MIPROv2` proposes instructions, then picks each predictor's instructions and demos by trials your metric scores. `BootstrapFewShotWithOptuna` picks among bootstrapped demos the same way:
|
|
303
|
+
|
|
304
|
+
```ruby
|
|
305
|
+
compiled = DSPyRb::MIPROv2[metric: method(:exact), auto: "light"].compile(Answer.new, trainset:)
|
|
306
|
+
picked = DSPyRb::BootstrapFewShotWithOptuna[metric: method(:exact)].compile(Answer.new, trainset:, max_demos: 2)
|
|
307
|
+
```
|
|
308
|
+
|
|
309
|
+
To set MIPROv2's budgets yourself, give `auto: nil` and `num_candidates:`, and `num_trials:` to `compile`. MIPROv2 sends your program's Ruby source to the model that proposes instructions, as DSPy sends a Python program's: your `DSPyRb::Module` classes and the signature classes they use. A string given to a name such as `api_key`, and text that starts like a key, such as `sk-`, show as `[hidden]`; any other key is sent as written, so keep keys out of your source. `program_aware_proposer: false` keeps the source out.
|
|
310
|
+
|
|
311
|
+
`BootstrapFewShotWithRandomSearch` bootstraps several sets of demos and keeps the one that scores best on the valset. `SIMBA` adds demos, and rules its prompt model writes from runs whose scores differ:
|
|
312
|
+
|
|
313
|
+
```ruby
|
|
314
|
+
searched = DSPyRb::BootstrapFewShotWithRandomSearch[metric: method(:exact)].compile(Answer.new, trainset:, valset:)
|
|
315
|
+
reflected = DSPyRb::SIMBA[metric: method(:exact)].compile(Answer.new, trainset:)
|
|
316
|
+
```
|
|
317
|
+
|
|
318
|
+
SIMBA sends your Module's Ruby source to its prompt model with each rule, as DSPy sends a Python program's: the text MIPROv2 sends, with key-like text shown as `[hidden]`. No option keeps it out; `program_aware_proposer:` is MIPROv2's alone. Its metric gets `nil` for a run that raised.
|
|
319
|
+
|
|
320
|
+
Save what a compile gave as DSPy's own JSON file, and load it into a fresh program later:
|
|
321
|
+
|
|
322
|
+
```ruby
|
|
323
|
+
compiled.save("answer.json")
|
|
324
|
+
Answer.new.load("answer.json") # in place, as in DSPy; it returns the program
|
|
325
|
+
```
|
|
326
|
+
|
|
327
|
+
A predictor's `load` returns a copy. The path ends in `.json`; pickles are never read or written.
|
|
328
|
+
|
|
329
|
+
## Usage and cost
|
|
330
|
+
|
|
331
|
+
Every prediction carries its `spend`, and so does every error from a request that made model calls, except your listener's own:
|
|
332
|
+
|
|
333
|
+
- `calls`: each model call, with its model, messages, usage, cost and duration. `cost` is DSPy's estimate in US dollars. `nil` means unknown, never free, and `cost_details` says why. A call served from DSPy's cache (`cache_hit`) shows the cost of the call it repeats, though nothing was billed.
|
|
334
|
+
- `unrecorded`: calls sent but not recorded, which only a fault in the gem causes. Normally 0; otherwise the real spend may be higher than `calls` shows.
|
|
335
|
+
- `running`: calls still running at the reply. They go on, are billed, and reach your listener as they end, for up to an hour.
|
|
336
|
+
|
|
337
|
+
Prices come from the list DSPy ships, so a model newer than it may have none. To use another list, name it in `config.env`:
|
|
338
|
+
|
|
339
|
+
```ruby
|
|
340
|
+
c.env = {
|
|
341
|
+
"LITELLM_LOCAL_MODEL_COST_MAP" => "False",
|
|
342
|
+
"LITELLM_MODEL_COST_MAP_URL" => "file:///path/to/prices.json"
|
|
343
|
+
}
|
|
344
|
+
```
|
|
345
|
+
|
|
346
|
+
- DSPy reads the list once, as it starts. Without the URL, it fetches LiteLLM's current list.
|
|
347
|
+
- DSPy keeps its own list if yours names fewer than half as many models, so add to a full copy.
|
|
348
|
+
- The list also tells DSPy what each model supports, so a new one can change the requests it sends.
|
|
349
|
+
|
|
350
|
+
A program's `spend` adds up every model call made inside it. To watch calls as they finish:
|
|
351
|
+
|
|
352
|
+
```ruby
|
|
353
|
+
DSPyRb.context(on_call: ->(call) { puts call.usage }) do
|
|
354
|
+
Answer.new.call(question: "Who wrote Hamlet?")
|
|
355
|
+
end
|
|
356
|
+
```
|
|
357
|
+
|
|
358
|
+
Listeners can run on several threads at once. Each takes every call, outermost first. One that raises stops the whole call it was made under at once, an evaluate or a compile included; once every listener has taken that call, that call raises the first error. Calls already sent still finish and are billed; a gate stops a call before it is sent.
|
|
359
|
+
|
|
360
|
+
### Budgets: gates
|
|
361
|
+
|
|
362
|
+
A gate sees each model call before it is sent, and refuses it by raising. With a listener, it keeps a hard budget:
|
|
363
|
+
|
|
364
|
+
```ruby
|
|
365
|
+
budget = JobBudget.new(limit: BigDecimal("0.50")) # your own counter: reserve, settle, left
|
|
366
|
+
|
|
367
|
+
DSPyRb.context(before_call: ->(pending) { budget.reserve(pending) }, # raises JobBudget::Exceeded when it won't fit
|
|
368
|
+
on_call: ->(call) { budget.settle(call) }) do
|
|
369
|
+
Answer.new.call(question: "Who wrote Hamlet?")
|
|
370
|
+
end
|
|
371
|
+
```
|
|
372
|
+
|
|
373
|
+
- Reserve an estimate for each call the gate lets through, and settle it with the real cost in the listener. Calls run at once, so a gate that only checks what is left can let several through together and overshoot. A `nil` cost means unknown, never free: settle it at the estimate.
|
|
374
|
+
- A call DSPy answers from its cache has `cache_hit` true and shows the cost of the call it repeats, though nothing was billed: settle it at zero. A repeat still passes the gate, which runs before the cache is read.
|
|
375
|
+
|
|
376
|
+
- A gate answers at once, from what your app already holds. It never waits: to wait for budget, reserve it before the work, or refuse and retry later from your job queue.
|
|
377
|
+
- A refusal stops the whole call, as a listener's raise does, and nothing more is sent: calls already sent still finish and reach your listeners. A gate that takes longer than 60 s refuses its call.
|
|
378
|
+
- `pending.id` is the `id` of the `call` your listeners get. A call that never went, refused or overtaken by a stop, reaches them once with `outcome` `"unsent"` and `cost` `0.0`, since nothing was billed, at times just after the call returns: its reservation is released there.
|
|
379
|
+
- Expire each reservation an hour after the work ends, longer if it raised while a call was running: the gem follows a running call for up to an hour past its reply, and a few cases never report back, such as a lost DSPy process or a gate that never returns.
|
|
380
|
+
- Gates stack, outermost first. `config.before_call` is the gate where no context sets one; make it refuse to keep calls from running unbudgeted.
|
|
381
|
+
|
|
382
|
+
### Your request's state: `around:`
|
|
383
|
+
|
|
384
|
+
Tools, metrics, a program's `forward`, gates and listeners called off your thread run on the gem's threads. They see your `Fiber[]` values; for anything else, such as `Current` attributes, wrap them with `around:`:
|
|
385
|
+
|
|
386
|
+
```ruby
|
|
387
|
+
DSPyRb.context(around: ->(&run) { Current.set(tenant:) { run.call } }) do
|
|
388
|
+
agent.call(question: "Where is my order?")
|
|
389
|
+
end
|
|
390
|
+
```
|
|
391
|
+
|
|
392
|
+
Hooks stack, outermost first, and each must run its block exactly once. Around tools, metrics and `forward`, a hook is plain Ruby: it may rescue an error and return a fallback. It can't hide a gate's refusal or a listener's raise: the call is still refused or stopped.
|
|
393
|
+
|
|
394
|
+
## Errors
|
|
395
|
+
|
|
396
|
+
Every error the gem raises is a `DSPyRb::Error`, and a wrong argument raises one that names it, such as `DSPyRb::Evaluate takes no num_thread`. Ruby's own errors stay as they are: `ArgumentError` for a misspelled keyword or a wrong number of arguments, `KeyError` for `fetch` of a missing field, and `NoMethodError` for an unknown one.
|
|
397
|
+
|
|
398
|
+
| Error | Means |
|
|
399
|
+
|---|---|
|
|
400
|
+
| `SetupError` | The install is missing or doesn't match the gem. Run `ruby-on-dspy setup`. |
|
|
401
|
+
| `DSPyError` | DSPy or the provider raised. Subclasses keep DSPy's names (`LMRateLimitError`, `LMAuthError`, `ContextWindowExceededError`, ...); `retryable` says whether a retry may help. |
|
|
402
|
+
| `Refused` | DSPy refused the request; nothing ran. |
|
|
403
|
+
| `StateError` | DSPy gave state your program can't hold, from a compile or a saved file. Nothing is applied; `spend` says what a compile cost. |
|
|
404
|
+
| `Unavailable` | DSPy's process was lost, or froze (wrote nothing for 30 s during a request); it is started again on the next call. Also raised when no thread comes free within an hour. |
|
|
405
|
+
| `Cancelled` | A request made from a tool or metric after the request around it had stopped. |
|
|
406
|
+
|
|
407
|
+
## Testing
|
|
408
|
+
|
|
409
|
+
`DSPyRb::DummyLM` is DSPy's own test model. It answers from a script, with no key, no network and no price:
|
|
410
|
+
|
|
411
|
+
```ruby
|
|
412
|
+
lm = DSPyRb::DummyLM[[{ category: "bug", urgent: true }]]
|
|
413
|
+
|
|
414
|
+
DSPyRb.context(lm:) do
|
|
415
|
+
DSPyRb::Predict[TriageTicket].call(ticket: "The export button crashes the app.").category # => "bug"
|
|
416
|
+
end
|
|
417
|
+
```
|
|
418
|
+
|
|
419
|
+
- A list's answers are used in order, one per model call. Keyed by text, an answer goes to the call whose last message holds its key, the first in the order given: `DSPyRb::DummyLM[{ "crashes" => { category: "bug", urgent: true } }]`. DSPy looks only at the last message, its own words in it included, so key by text your input there holds; an earlier message, such as a tool's result, isn't searched. Calls made on several threads take their answers by text.
|
|
420
|
+
- An answer names the fields DSPy asks for. `ChainOfThought` reads its reasoning from `plan`, or from `reasoning` with `reasoning: :written`. Each `ReAct` turn is `next_thought` and `tool_calls`, the last calling `submit`.
|
|
421
|
+
- Out of answers, DSPy answers `answer: "No more responses"`, and a predictor with other fields raises `DSPyRb::AdapterParseError`. A reply that fails to parse uses two answers.
|
|
422
|
+
- `config.lm` and `DSPyRb.context(lm:)` take it as they take an `LM`. Its calls are in `spend`, with model `dummy`, 0 tokens and no price.
|
|
423
|
+
|
|
424
|
+
## Good to know
|
|
425
|
+
|
|
426
|
+
- The gem never cuts a long call: it waits as long as DSPy does, a provider's `Retry-After` included. To limit one, set the LM's `timeout:` and `num_retries:`. A Ruby timeout cancels the request, but a model call already running finishes and is billed.
|
|
427
|
+
- Wrap thread-pool jobs in `DSPyRb.capture { ... }` to keep your settings.
|
|
428
|
+
- Calls to an embedding model are not counted in `spend`.
|
|
429
|
+
- DSPy's process uses about 250 MB of memory.
|
|
430
|
+
|
|
431
|
+
## Requirements
|
|
432
|
+
|
|
433
|
+
- Ruby 3.3.1 or later
|
|
434
|
+
- macOS or Linux, on arm64 or x86_64
|
|
435
|
+
|
|
436
|
+
## Contributing
|
|
437
|
+
|
|
438
|
+
See [CONTRIBUTING.md](CONTRIBUTING.md).
|
|
439
|
+
|
|
440
|
+
## License
|
|
441
|
+
|
|
442
|
+
MIT
|