Program LLMs in R instead of hand-tuning prompt strings.
Declare a task’s inputs and typed outputs once, swap reasoning and tool-use strategies without rewriting prompts, measure quality on labeled data, and let an optimizer fit instructions and examples to your metric. Built on ellmer and inspired by DSPy.
Why program instead of prompt?
A hand-written prompt mixes three fragile things into one string: what you want, how to coax a particular model, and which examples to show. dsprrr keeps them separate so you can test, compare, and optimize LLM features like any other R code.
Hand-tuned prompt
# Task and wording tangled in one string
chat$chat(paste(
"Route this ticket. Return urgency",
"(low/high) and team. Ticket:", ticket
))- Free-text output you have to parse by hand
- Hard to test across rows or compare versions
- Breaks quietly when you change models
Declarative dsprrr program
sig <- signature(
"ticket -> urgency: enum('low', 'high')"
)
router <- chain_of_thought(sig) |>
compile(
BootstrapFewShot(metric = metric),
trainset = train
)- Typed R list returned via structured schemas
- Swap strategies or chain steps in one line
- Measure with
evaluate(), re-compile for any model
If you have a one-off prompt that already works and no data to measure it against, plain ellmer is enough. dsprrr earns its keep once an LLM call becomes a repeatable workflow you need to measure, compose, or port across models.
The R modeling mental model
If you have ever fit a model in R, you already know the loop:
1. Declare
Like y ~ x
State inputs, typed outputs, and task intent without writing prompt plumbing.
2. Build
Like a model spec
Choose direct prediction, chain-of-thought, ReAct tools, or %>>% pipelines.
3. Measure
Like yardstick
Score predictions across a data frame and inspect prompts, traces, and cost.
4. Optimize
Like fit()
Search instructions and few-shot demos on training data to raise your metric.
How the pieces fit
One support-ticket workflow from declaration to a saved, compiled program:
02
Modules
Swap how it thinks. The same signature can run as one structured call, with step-by-step reasoning first, or in a tool-calling loop. Run any module on one input with run() or over a data frame with run_dataset().
chat <- ellmer::chat_openai(model = "gpt-6-luna")
router <- module(sig) # one call
router_cot <- chain_of_thought(sig) # reason first
lookup <- ellmer::tool(
function(q) "Duplicate charges go to billing.",
description = "Look up routing policy",
arguments = list(q = ellmer::type_string())
)
router_agent <- react(sig, tools = list(lookup))
run(router, ticket = "Charged twice!", .llm = chat)03
Pipelines
Compose multi-step programs. Chain modules with %>>% or wire inputs explicitly with pipeline() and step(). A pipeline is itself a module, so run(), evaluate(), and compile() work across all steps together.
04
Metrics & evaluation
Measure instead of eyeballing. Split your labeled rows, run the module over the validation set, and score every prediction. Inspect misses, prompts (get_last_prompt()), traces (summarize_traces()), and spend (session_cost()).
tickets <- tibble::tribble(
~ticket, ~urgency, ~team,
"Charged twice for my order", "high", "billing",
"Change my profile photo?", "low", "account",
"App deletes files on sync", "high", "technical",
"Need last year's invoice", "low", "billing",
"Unknown login on my account", "high", "account",
"Export fails in Safari", "low", "technical"
)
splits <- split_dataset(tickets, prop = 0.67, seed = 1)
metric <- metric_exact_match(field = "urgency")
baseline <- evaluate(
router, splits$val, metric = metric, .llm = chat
)
baseline$mean_score05
Optimizers & persistence
Fit prompts to your data. compile() returns a new module whose demos or instructions were chosen to raise your metric on training rows (BootstrapFewShot, MIPROv2, GEPA, and more). Verify on held-out rows, then save with save_program(). Switch models? Swap chat and re-compile.
optimizer <- BootstrapFewShot(
metric = metric,
max_bootstrapped_demos = 2L,
max_labeled_demos = 0L
)
optimized <- router |>
compile(optimizer, splits$train, .llm = chat)
evaluate(
optimized, splits$val, metric, .llm = chat
)
save_program(optimized, "ticket_router.rds")Works with your R stack
Runs on any chat ellmer supports: OpenAI, Anthropic, Google, Ollama, Bedrock, and more.
Expose modules as vitals solvers and reuse vitals scorers directly as dsprrr metrics.
Connect document stores to RAG modules and ReAct agents with ragnar_tool().
Tune LLM parameters alongside workflows with the llm_predict() parsnip spec.
Version compiled configs with pin_module_config() and orchestrate batch runs.
Built-in memory and disk cache, run_async(), run_stream(), and token/cost logs.
Where to go next
New to dsprrr
Go from your first typed call to structured extraction, demos, optimization, and saving a compiled module.
Already using ellmer
Understand signatures, R6 module state, traces, and when a plain ellmer prompt is still the right tool.
Coming from Python DSPy
Translate signatures, modules, teleprompters, and pipelines between Python DSPy and idiomatic R.
Ready to optimize
Compare all eleven teleprompters — from LabeledFewShot and BootstrapFewShot to MIPROv2 and GEPA.
Installation
Install the released version from CRAN:
install.packages("dsprrr")Or install the development version from GitHub:
# install.packages("pak")
pak::pak("JamesHWade/dsprrr")Set a provider API key in your .Renviron (for example OPENAI_API_KEY or ANTHROPIC_API_KEY), then run dsprrr_sitrep() to verify your setup. Installing from source requires a C compiler (Rtools on Windows, Xcode Command Line Tools on macOS, or your Linux distribution’s build tools); the compiled helper preserves exact filesystem identities for safe persistence.
Experimental features: rlm_module() lets a model explore a large R object by writing code (How RLM works), flex() lets GEPA rewrite a whole program (Flex), with_decisions() and ReAnchor() calibrate decision thresholds (Calibrated decisions), and Omni() and the agentic harnesses compose optimizers (Omni, agentic harnesses).
dsprrr is experimental; the API may change. It is inspired by DSPy from Stanford NLP, builds on ellmer for model access, and bridges to vitals for evaluation.