1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
//! Typed prompt engineering and LM program optimization.
//!
//! dsir is a Rust port of [DSPy](https://github.com/stanfordnlp/dspy): you declare what
//! you want the LM to produce (a [`Signature`]), pick a prompting strategy (a [`Module`]
//! like [`Predict`] or [`ChainOfThought`]), and let an [`Optimizer`] tune the program's
//! instructions and demos on your training data. The type system enforces correctness
//! at every layer — field types, strategy swaps, and augmentation composition are all
//! compile-time checked.
//!
//! # The mental model
//!
//! Three concepts, three layers:
//!
//! | Layer | Concept | Key types | Who |
//! |-------|---------|-----------|-----|
//! | **Signatures** | "Given these inputs, produce these outputs" | [`Signature`], `#[derive(Signature)]` | Everyone |
//! | **Modules** | Prompting strategies that implement a signature | [`Module`], [`Predict`], [`ChainOfThought`] | Everyone |
//! | **Optimization** | Auto-tuning instructions and demos | [`Optimizer`], [`COPRO`], [`GEPA`], [`MIPROv2`] | When you need better results |
//!
//! A [`Predict`] is the leaf — the only thing that actually calls the LM. Every other
//! module ([`ChainOfThought`], custom pipelines) delegates to one or more `Predict` leaves.
//! Optimizers discover these leaves automatically via Facet reflection and mutate their
//! instructions and few-shot demos.
//!
//! # Quick start
//!
//! ```no_run
//! use dsir::*;
//!
//! #[derive(Signature, Clone, Debug)]
//! /// Answer questions accurately and concisely.
//! struct QA {
//! #[input] question: String,
//! #[output] answer: String,
//! }
//!
//! # async fn example() -> Result<(), PredictError> {
//! // 1. Configure the LM
//! let lm = LM::builder()
//! .model("openai:gpt-4o-mini".to_string())
//! .build()
//! .await
//! .unwrap();
//! dsir::configure(lm, ChatAdapter);
//!
//! // 2. Pick a strategy
//! let cot = ChainOfThought::<QA>::new();
//!
//! // 3. Call it
//! let result = cot.call(QAInput { question: "What is 2+2?".into() }).await?;
//! println!("{}", result.reasoning); // chain-of-thought text
//! println!("{}", result.answer); // the actual answer, via Deref
//! # Ok(())
//! # }
//! ```
//!
//! `ChainOfThought<QA>` returns [`Predicted<WithReasoning<QAOutput>>`](Predicted), not
//! `Predicted<QAOutput>`. You access `.reasoning` directly and `.answer` through auto-deref
//! ([`WithReasoning<O>`] derefs to `O`). This pattern holds for all augmentations — the
//! compiler tells you what changed when you swap strategies.
//!
//! # What doesn't work (yet)
//!
//! - **Typed MIPRO is still instruction-only** on the static `Optimizer::compile` path
//! (`TODO(trace-demos)`). The dyn path ([`MIPROv2::compile_dyn`](crate::MIPROv2::compile_dyn))
//! seeds demos from successful traces.
//! - **`CallMetadata` is not extensible.** Modules can't attach custom metadata (e.g.
//! "which attempt won in BestOfN"). This should probably be a trait with associated
//! types, but it isn't.
//! - **Container traversal is partial.** The optimizer walker handles `Option`, `Vec`,
//! `HashMap<String, _>`, and `Box`. `Rc`/`Arc` containing `Predict` leaves return
//! explicit container errors (not silent skips).
//!
//! # Dynamic runtime path
//!
//! For runtime-configurable programs use [`DynSignature`] (JSON schema or string DSL),
//! [`DynPredict`] / [`DynModule`], [`ProgramGraph`] / [`StrategyFactory`], and
//! [`Lab`](crate::Lab) with `compile_dyn` optimizers. Typed `#[derive(Signature)]`
//! remains the primary API for static Rust programs.
//!
//! User guides (repository `docs/user/`):
//! - Dynamic signatures — `building-blocks/dyn-signatures.md`
//! - Program graph — `dynamic-programs/program-graph.md`
//! - Lab — `lab/overview.md`
//! - compile_dyn — `optimizers/compile-dyn.md`
//!
//! # Examples
//!
//! Runnable examples live in `crates/dsir/examples/`:
//!
//! ```bash
//! cargo run -p dsir --example 01_predict # Signature → Predict (live LM)
//! cargo run -p dsir --example 04_bootstrap # BootstrapFewShot (offline)
//! cargo run -p dsir --example 05_lab # Lab workflow (offline)
//! cargo run -p dsir --example 06_graph # ProgramGraph (offline)
//! ```
//!
//! See `docs/user/guides/examples.md` for the full index.
//!
//! # Crate organization
//!
//! - [`adapter`] — Prompt formatting and LM response parsing ([`ChatAdapter`])
//! - [`core`] — [`Module`] trait, [`Signature`] / [`DynSignature`], [`SignatureSchema`], LM client
//! - [`predictors`] — [`Predict`], [`DynPredict`], typed [`Example`]
//! - [`graph`] — [`ProgramGraph`], [`StrategyFactory`], structural search
//! - [`modules`] — [`ChainOfThought`], [`ReAct`], [`BestOfN`], [`Refine`], [`Agent`]
//! - [`evaluate`] — [`TypedMetric`], [`DynMetric`], [`evaluate_trainset`]
//! - [`optimizer`] — [`Optimizer`], [`COPRO`], [`GEPA`], [`MIPROv2`], `compile_dyn`
//! - [`lab`] — self-improvement authoring, compare, promote, registry client
//! - [`data`] — [`DataLoader`] for JSON/CSV/Parquet/HuggingFace datasets
//! - [`trace`] — Execution graph recording for debugging
//! - [`utils`] — Response caching
// TODO(dsrs-facet-lint-scope): remove this crate-level allow once Facet's generated
// extension-attr dispatch no longer triggers rust-lang/rust#52234 on in-crate usage.
extern crate self as dsir;
pub use *;
pub use *;
pub use *;
pub use *;
pub use Example as RawExample;
pub use RawExample as UntypedExample;
pub use *;
pub use *;
pub use *;
pub use *;
pub use *;
pub use *;
pub use *;
pub use *;
pub use *;
pub use *;
pub use *;
pub use BamlConvertError;
pub use BamlType; // attribute macro
pub use Shape;
pub use ;
pub use ;
pub use Flag;
pub use *;
pub use Facet;
/// Pre-built signature for use in doc examples. Not part of the public API.
=> ;
// Pattern for field definitions without descriptions
=> ;
}
=> ;
}
/// Source: <https://github.com/wholesome-ghoul/hashmap_macro/blob/master/src/lib.rs>
/// Author: <https://github.com/wholesome-ghoul>
/// License: MIT
/// Description: This macro creates a HashMap from a list of key-value pairs.
/// Reason for Reuse: Want to avoid adding a dependency for a simple macro.