- what dspy-rb needs;
- how to add the gem and install DSPy;
- how to make a first call;
- how to start DSPy with your app, and ship it in a Docker image.
Requirements
- Ruby 3.2 or later
- macOS or Linux, on arm64 or x86_64
- an API key for your model’s provider, such as OpenAI
Install the gem and DSPy
1
Add the gem
Until dspy-rb is on RubyGems, Bundler installs it from GitHub. Add it to your Gemfile:Then install it:
Gemfile
2
Install DSPy
dspy-rb setup installs Python 3.12 and DSPy 3.5.0 in ~/.cache/dspy-rb, without touching any Python you have. The first run downloads them, which takes about a minute.Each copy of the gem you install, a release or a commit from GitHub, gets an environment of its own there, so after you update the gem, run bundle exec dspy-rb setup again. Until you do, calls raise DSPyRb::SetupError.3
Check the install
dspy-rb doctor checks the install and starts DSPy once, without calling a model. It prints six lines, each starting with ok.setup also removes the environments of gem copies you’ve uninstalled. If a copy’s whole Ruby or app folder is gone, it keeps the environment and says so; delete it yourself once that Ruby or app is gone for good.Make a first call
A first call checks that DSPy can reach your model with your key. Start a script,first_call.rb, that names the model DSPy calls:
"question -> answer":
OPENAI_API_KEY, run the script:
Output
config.env passes it to DSPy, as the tutorial shows.
DSPy caches answers in
~/.dspy_cache, so the same call returns the same answer at once, without calling the model. cache: false in DSPyRb::LM[...] turns it off.Start DSPy with your app
DSPy starts on the first call, which takes a few seconds, and stops when Ruby exits. In a web app, that makes the first request slow. To start DSPy before the first request, callDSPyRb.start in config/puma.rb. Don’t call it in an initializer: consoles and rake tasks load initializers too, and each would start DSPy.
- With Rails’ default Puma, which runs no workers, call it in
after_booted. - With Puma workers, call it in
before_worker_boot. Each worker starts its own DSPy, which uses about 250 MB.
on_booted and on_worker_boot.
Ship DSPy in a Docker image
Docker is optional. If you ship your app in a Docker image, install DSPy while the image builds, in a folder the final image keeps.DSPY_RB_ENVIRONMENT names that folder, in place of ~/.cache/dspy-rb. With Rails’ Dockerfile, add two lines:
Dockerfile
DSPY_RB_ENVIRONMENT points both setup and your app at the same folder. The final stage copies /rails, so the image carries DSPy.
setup assumes one machine uses the install folder. If another machine or container shares it, setup can remove the environments that one built.
Next
A new Rails app
Create Helpdesk, add dspy-rb and make a first prediction in the console.