overbrainer 0.9.0

Distill a large LLM into a smaller open-weights model: generate questions, collect answers, fine-tune, visualize.
Documentation
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
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
use std::collections::{BTreeMap, BTreeSet};
use std::sync::Arc;

use serde::Serialize;
use tokio::sync::Semaphore;
use tokio::task::JoinSet;

use super::{
    Ctx, Item, PipelineError, RoleClient, complete_with_retry, item_error, without_topics,
};
use crate::config::{Protocol, Topic};
use crate::dataset::{
    Appender, Example, Exclusion, FinishReason, Id, Message, Meta, Question, ReasoningKind, Role,
    read, rewrite,
};
use crate::events::{Event, EventBus, Stage, StageStats};
use crate::llm::{Completion, LlmClient, LlmError, RetryPolicy};
use crate::prompts;

#[derive(Serialize)]
struct Context<'a> {
    topic: &'a str,
    description: Option<&'a str>,
}

/// Asks the parent to answer every question of the selected topics that has no answer
/// yet, writing `data/answers.jsonl` one line per completed request.
///
/// Requests run concurrently, at most `pipeline.concurrency` at a time, each with
/// retries. Unusable answers are kept with `meta.excluded` set (see [`classify`]).
/// A failed question is reported and left for the next run; an error that would fail
/// every request (such as a rejected key) stops the stage.
///
/// # Errors
///
/// Returns a [`PipelineError`] when a file or template fails, when a task panics, or
/// when the provider rejects the requests.
pub async fn answers<C: LlmClient + 'static>(
    ctx: &Ctx<'_>,
    parent: Arc<RoleClient<C>>,
) -> Result<StageStats, PipelineError> {
    let topics = ctx.topics()?;
    let questions: Vec<Question> = read(&ctx.files.questions)?;
    let mut existing: Vec<Example> = read(&ctx.files.answers)?;
    if ctx.force {
        existing = without_topics(existing, &topics, |example| &example.topic);
        rewrite(&ctx.files.answers, &existing)?;
    }
    warn_about_reasoning(ctx, &parent);
    let answered: BTreeSet<&Id> = existing.iter().map(|example| &example.id).collect();
    let selected: Vec<&Question> = questions
        .iter()
        .filter(|question| topics.iter().any(|topic| topic.name == question.topic))
        .collect();
    let pending: Vec<Question> = selected
        .iter()
        .filter(|question| !answered.contains(&question.id))
        .map(|question| (*question).clone())
        .collect();
    let mut stats = StageStats {
        skipped: selected.len() - pending.len(),
        ..StageStats::default()
    };
    // Every selected question is one item; questions answered in an earlier run are
    // reported done at once, so progress across runs counts what earlier runs finished.
    ctx.bus.publish(Event::StageStarted {
        stage: Stage::Answers,
        total: selected.len(),
    });
    ctx.bus.publish(Event::StageModel {
        stage: Stage::Answers,
        model: parent.model.model.clone(),
    });
    for question in &selected {
        if answered.contains(&question.id) {
            ctx.bus.publish(Event::ItemDone {
                stage: Stage::Answers,
                id: question.id.to_string(),
                usage: None,
                cost: None,
                excluded: false,
            });
        }
    }
    let systems = system_prompts(ctx, &topics)?;
    let mut tasks = spawn_all(ctx, &parent, pending, &systems);
    let mut out = Appender::open(&ctx.files.answers)?;
    while let Some(joined) = tasks.join_next().await {
        let (question, system, result) = joined.map_err(PipelineError::Task)?;
        match result {
            Ok(completion) => save(
                ctx,
                &parent,
                &mut out,
                &mut stats,
                (question, system, completion),
            )?,
            Err(error) => {
                let item = Item {
                    stage: Stage::Answers,
                    id: question.id.to_string(),
                };
                if let Err(stop) = item_error(ctx, &item, error, &mut stats) {
                    tasks.abort_all();
                    let kept = keep_finished(ctx, &parent, &mut tasks, &mut out, &mut stats).await;
                    return Err(stopped(stop, kept, stats));
                }
            },
        }
    }
    ctx.bus.publish(Event::StageFinished {
        stage: Stage::Answers,
        stats: stats.clone(),
    });
    Ok(stats)
}

type Outcome = (Question, String, Result<Completion, LlmError>);

/// Spawns one task per question. Each task waits for a semaphore permit, so at most
/// `pipeline.concurrency` requests are in flight.
fn spawn_all<C: LlmClient + 'static>(
    ctx: &Ctx<'_>,
    parent: &Arc<RoleClient<C>>,
    pending: Vec<Question>,
    systems: &BTreeMap<String, String>,
) -> JoinSet<Outcome> {
    let semaphore = Arc::new(Semaphore::new(ctx.settings.pipeline.concurrency));
    let policy = ctx.policy();
    let mut tasks = JoinSet::new();
    for question in pending {
        let system = systems.get(&question.topic).cloned().unwrap_or_default();
        tasks.spawn(ask(
            Arc::clone(parent),
            Arc::clone(&semaphore),
            policy,
            ctx.bus.clone(),
            (question, system),
        ));
    }
    tasks
}

async fn ask<C: LlmClient>(
    parent: Arc<RoleClient<C>>,
    semaphore: Arc<Semaphore>,
    policy: RetryPolicy,
    bus: EventBus,
    (question, system): (Question, String),
) -> Outcome {
    let item = Item {
        stage: Stage::Answers,
        id: question.id.to_string(),
    };
    let Ok(_permit) = semaphore.acquire_owned().await else {
        let error = LlmError::InvalidResponse("the request queue was closed".to_string());
        return (question, system, Err(error));
    };
    let request = parent.request(Some(system.clone()), question.text.clone());
    let result = complete_with_retry(&parent.client, &policy, &request, &item, &bus).await;
    (question, system, result)
}

/// Builds the example of an answered question, records it and appends it.
fn save<C: LlmClient>(
    ctx: &Ctx<'_>,
    parent: &RoleClient<C>,
    out: &mut Appender,
    stats: &mut StageStats,
    (question, system, completion): (Question, String, Completion),
) -> Result<(), PipelineError> {
    let example = example(ctx, parent, question, system, completion);
    record(ctx, parent, &example, stats);
    out.append(&example)?;
    Ok(())
}

/// After a fatal error, waits for the aborted tasks and saves the answers that had
/// already finished, so they are not paid for twice. Cancelled tasks and failed
/// requests are left for the next run.
async fn keep_finished<C: LlmClient>(
    ctx: &Ctx<'_>,
    parent: &RoleClient<C>,
    tasks: &mut JoinSet<Outcome>,
    out: &mut Appender,
    stats: &mut StageStats,
) -> Result<(), PipelineError> {
    while let Some(joined) = tasks.join_next().await {
        if let Ok((question, system, Ok(completion))) = joined {
            save(ctx, parent, out, stats, (question, system, completion))?;
        }
    }
    Ok(())
}

/// The error of a stage stopped by the fatal provider error `stop`, once the answers
/// that had finished were saved (`kept`). When saving them failed, that disk error is
/// returned, and the provider error, which would otherwise be lost, is logged.
fn stopped(
    mut stop: PipelineError,
    kept: Result<(), PipelineError>,
    stats: StageStats,
) -> PipelineError {
    if let Err(disk) = kept {
        log_lost(&stop);
        return disk;
    }
    if let PipelineError::Llm { spent, .. } = &mut stop {
        **spent = stats;
    }
    stop
}

fn log_lost(stop: &PipelineError) {
    let cause = std::error::Error::source(stop)
        .map(|source| format!(": {source}"))
        .unwrap_or_default();
    tracing::error!("{stop}{cause}; saving the answers that had finished then failed too");
}

/// The system prompt of each topic, rendered once.
fn system_prompts(
    ctx: &Ctx<'_>,
    topics: &[&Topic],
) -> Result<BTreeMap<String, String>, PipelineError> {
    topics
        .iter()
        .map(|topic| {
            let system = ctx.prompts.render(
                prompts::ANSWER_SYSTEM,
                Context {
                    topic: &topic.name,
                    description: topic.description.as_deref(),
                },
            )?;
            Ok((topic.name.clone(), system))
        })
        .collect()
}

fn example<C: LlmClient>(
    ctx: &Ctx<'_>,
    parent: &RoleClient<C>,
    question: Question,
    system: String,
    mut completion: Completion,
) -> Example {
    if completion.reasoning.kind == ReasoningKind::Raw && hides_raw_reasoning(ctx, parent) {
        completion.reasoning.kind = ReasoningKind::Summary;
    }
    let mut meta = Meta {
        model: parent.model.model.clone(),
        input_tokens: completion.usage.input_tokens,
        output_tokens: completion.usage.output_tokens,
        finish_reason: completion.finish,
        reasoning_kind: completion.reasoning.kind,
        excluded: None,
    };
    let (reply, excluded) = assistant(completion, parent.model.reasoning);
    meta.excluded = excluded;
    let mut messages = Vec::with_capacity(3);
    if ctx.settings.pipeline.include_system_prompt {
        messages.push(Message {
            role: Role::System,
            content: system,
            reasoning_content: None,
        });
    }
    messages.push(Message {
        role: Role::User,
        content: question.text,
        reasoning_content: None,
    });
    messages.push(reply);
    Example {
        id: question.id,
        topic: question.topic,
        subtopic: question.subtopic,
        messages,
        meta,
    }
}

/// The assistant message of `completion` and why it cannot be trained on, if it
/// cannot. A usable answer keeps its reasoning only when it is raw, so a summary is
/// never trained on; an excluded answer keeps whatever it got, for inspection.
fn assistant(completion: Completion, reasoning_requested: bool) -> (Message, Option<Exclusion>) {
    let excluded = classify(&completion, reasoning_requested);
    let raw = completion.reasoning.kind == ReasoningKind::Raw;
    let reasoning_content = completion
        .reasoning
        .text
        .filter(|_| raw || excluded.is_some());
    let reply = Message {
        role: Role::Assistant,
        content: completion.content,
        reasoning_content,
    };
    (reply, excluded)
}

fn record<C: LlmClient>(
    ctx: &Ctx<'_>,
    parent: &RoleClient<C>,
    example: &Example,
    stats: &mut StageStats,
) {
    let usage = crate::llm::Usage {
        input_tokens: example.meta.input_tokens,
        output_tokens: example.meta.output_tokens,
    };
    stats.add_usage(usage, parent.price.as_ref());
    if example.meta.excluded.is_some() {
        stats.excluded += 1;
    } else {
        stats.done += 1;
    }
    ctx.bus.publish(Event::ItemDone {
        stage: Stage::Answers,
        id: example.id.to_string(),
        usage: Some(usage),
        cost: parent.price.as_ref().map(|price| price.cost(usage)),
        excluded: example.meta.excluded.is_some(),
    });
}

/// Why an answer cannot be used for training, if it cannot: hit the token limit,
/// refused, empty, or (when reasoning was requested) without raw reasoning.
#[must_use]
pub fn classify(completion: &Completion, reasoning_requested: bool) -> Option<Exclusion> {
    match completion.finish {
        FinishReason::Length => return Some(Exclusion::Truncated),
        FinishReason::Refusal | FinishReason::ContentFilter => return Some(Exclusion::Refused),
        FinishReason::Stop | FinishReason::Other => {},
    }
    if completion.content.trim().is_empty() {
        return Some(Exclusion::Empty);
    }
    (reasoning_requested && completion.reasoning.kind != ReasoningKind::Raw)
        .then_some(Exclusion::NoRawReasoning)
}

/// Warning shown when reasoning is requested from a parent known not to return raw
/// reasoning: the `anthropic` protocol always, and `OpenAI`, Claude or Gemini models on
/// the `openai` protocol, which hide or summarize it. The open-weight `gpt-oss` models
/// return raw reasoning and get no warning.
///
/// The answers stage never trusts reasoning from such a parent: what it reports as raw
/// is stored as a summary, so it is never trained on.
#[must_use]
pub fn raw_reasoning_warning(protocol: Protocol, model: &str) -> Option<&'static str> {
    if protocol == Protocol::Anthropic {
        return Some(
            "the anthropic protocol never returns raw reasoning: every answer will be excluded from training",
        );
    }
    let model = model.to_ascii_lowercase();
    let name = model.rsplit('/').next().unwrap_or(&model);
    if name.starts_with("gpt-oss") {
        return None;
    }
    let mut chars = name.chars();
    let o_series = chars.next() == Some('o') && chars.next().is_some_and(|c| c.is_ascii_digit());
    let hidden = model.starts_with("openai/")
        || model.starts_with("anthropic/")
        || name.starts_with("gpt-")
        || name.starts_with("claude")
        || name.starts_with("gemini")
        || o_series;
    hidden.then_some(
        "this model hides or summarizes its reasoning, so none of it is treated as raw: every answer will be excluded from training",
    )
}

/// Whether the parent is known not to return raw reasoning (see
/// [`raw_reasoning_warning`]), whatever the response claims.
fn hides_raw_reasoning<C>(ctx: &Ctx<'_>, parent: &RoleClient<C>) -> bool {
    ctx.settings
        .providers
        .get(&parent.model.provider)
        .is_some_and(|provider| {
            raw_reasoning_warning(provider.protocol, &parent.model.model).is_some()
        })
}

fn warn_about_reasoning<C>(ctx: &Ctx<'_>, parent: &RoleClient<C>) {
    let Some(provider) = ctx.settings.providers.get(&parent.model.provider) else {
        return;
    };
    if parent.model.reasoning
        && let Some(warning) = raw_reasoning_warning(provider.protocol, &parent.model.model)
    {
        tracing::warn!("parent {}: {warning}", parent.model.model);
    }
}

#[cfg(test)]
mod tests {
    use std::io;

    use tracing::Level;

    use super::*;
    use crate::dataset::DatasetError;
    use crate::llm::{Reasoning, Usage};

    #[test]
    fn a_disk_error_after_a_fatal_stop_still_logs_the_provider_error() {
        let stop = PipelineError::Llm {
            stage: Stage::Answers,
            source: LlmError::Status {
                status: 401,
                message: "authentication failed".to_string(),
                retry_after: None,
            },
            spent: Box::default(),
        };
        let disk = PipelineError::Dataset(DatasetError::Io {
            path: "data/answers.jsonl".into(),
            source: io::Error::other("no space left"),
        });
        let (returned, logs) =
            crate::logging::capture(|| stopped(stop, Err(disk), StageStats::default()));
        assert!(
            matches!(returned, PipelineError::Dataset(_)),
            "the disk error is returned"
        );
        let errors = logs.since(Level::ERROR, 0);
        assert!(
            errors.iter().any(
                |line| line.message.contains("answers stopped") && line.message.contains("401")
            ),
            "{errors:?}"
        );
    }

    fn completion(content: &str, kind: ReasoningKind, finish: FinishReason) -> Completion {
        Completion {
            content: content.to_string(),
            reasoning: Reasoning {
                text: (kind != ReasoningKind::None).then(|| "r".to_string()),
                kind,
            },
            usage: Usage::default(),
            finish,
        }
    }

    #[test]
    fn exclusion_reasons() {
        use FinishReason::{ContentFilter, Length, Refusal, Stop};
        use ReasoningKind::{None, Raw, Summary};
        assert_eq!(classify(&completion("a", Raw, Stop), true), Option::None);
        assert_eq!(
            classify(&completion("a", Raw, Length), true),
            Some(Exclusion::Truncated)
        );
        assert_eq!(
            classify(&completion("", None, Refusal), true),
            Some(Exclusion::Refused)
        );
        assert_eq!(
            classify(&completion("a", None, ContentFilter), false),
            Some(Exclusion::Refused)
        );
        assert_eq!(
            classify(&completion("  ", Raw, Stop), true),
            Some(Exclusion::Empty)
        );
        assert_eq!(
            classify(&completion("a", Summary, Stop), true),
            Some(Exclusion::NoRawReasoning)
        );
        assert_eq!(classify(&completion("a", None, Stop), false), Option::None);
    }

    #[test]
    fn warnings_for_models_without_raw_reasoning() {
        assert!(raw_reasoning_warning(Protocol::Anthropic, "claude-opus-5").is_some());
        for model in [
            "openai/gpt-6",
            "gpt-5-mini",
            "o3",
            "anthropic/claude-sonnet-5",
            "google/gemini-3-pro",
            "gemini-2.5-flash",
        ] {
            assert!(
                raw_reasoning_warning(Protocol::Openai, model).is_some(),
                "{model}"
            );
        }
        for model in [
            "deepseek-r1",
            "qwen/qwen3-235b-a22b",
            "ollama3",
            "google/gemma-3-27b-it",
        ] {
            assert!(
                raw_reasoning_warning(Protocol::Openai, model).is_none(),
                "{model}"
            );
        }
    }

    #[test]
    fn gpt_oss_models_return_raw_reasoning() {
        for model in [
            "openai/gpt-oss-120b",
            "gpt-oss-20b",
            "groq/openai/gpt-oss-20b",
        ] {
            assert!(
                raw_reasoning_warning(Protocol::Openai, model).is_none(),
                "{model}"
            );
        }
    }

    #[test]
    fn only_raw_reasoning_is_kept_on_usable_answers() {
        use FinishReason::Stop;
        use ReasoningKind::{Raw, Redacted, Summary};
        for kind in [Summary, Redacted] {
            let (reply, excluded) = assistant(completion("a", kind, Stop), false);
            assert_eq!(excluded, Option::None, "{kind:?} stays usable");
            assert_eq!(
                reply.reasoning_content,
                Option::None,
                "{kind:?} is not trained"
            );
        }
        let (reply, excluded) = assistant(completion("a", Raw, Stop), false);
        assert_eq!(excluded, Option::None);
        assert_eq!(reply.reasoning_content.as_deref(), Some("r"));
        assert_eq!(reply.content, "a");
        for kind in [Summary, Redacted] {
            let (reply, excluded) = assistant(completion("a", kind, Stop), true);
            assert_eq!(excluded, Some(Exclusion::NoRawReasoning));
            assert_eq!(
                reply.reasoning_content.as_deref(),
                Some("r"),
                "an excluded answer keeps its reasoning for inspection"
            );
        }
    }
}