qa.rs

  1//! Quality assessment of predictions using LLM-as-a-judge.
  2//!
  3//! This module uses LLM Batch APIs to evaluate prediction quality.
  4//! Caching is handled by the underlying client.
  5
  6use crate::BatchProvider;
  7use crate::example::Example;
  8use crate::format_prompt::extract_cursor_excerpt_from_example;
  9use crate::llm_client::{LlmClient, model_for_backend};
 10use crate::word_diff::unified_to_word_diff;
 11use anyhow::Result;
 12use serde::{Deserialize, Serialize};
 13use std::io::{BufWriter, Write};
 14use std::path::PathBuf;
 15
 16const PROMPT_TEMPLATE: &str = include_str!("prompts/qa.md");
 17
 18/// Arguments for the QA command.
 19#[derive(Debug, Clone, clap::Args)]
 20pub struct QaArgs {
 21    /// Use synchronous API instead of batch
 22    #[clap(long)]
 23    pub no_batch: bool,
 24
 25    /// Wait for batch to complete (polls every 30s)
 26    #[clap(long)]
 27    pub wait: bool,
 28
 29    /// Which LLM provider to use (anthropic or openai)
 30    #[clap(long, default_value = "openai")]
 31    pub backend: BatchProvider,
 32}
 33
 34/// Result of QA evaluation for a single prediction.
 35#[derive(Debug, Clone, Serialize, Deserialize)]
 36pub struct QaResult {
 37    /// Free-form reasoning from the judge.
 38    #[serde(default, skip_serializing_if = "Option::is_none")]
 39    pub reasoning: Option<String>,
 40
 41    /// Does the prediction undo/revert changes the user intentionally made?
 42    #[serde(default, skip_serializing_if = "Option::is_none")]
 43    pub reverts_edits: Option<bool>,
 44
 45    /// Confidence score (1-5) for user acceptance likelihood.
 46    #[serde(default, skip_serializing_if = "Option::is_none")]
 47    pub confidence: Option<u8>,
 48
 49    /// The raw response from the model.
 50    #[serde(default, skip_serializing_if = "Option::is_none")]
 51    pub response: Option<String>,
 52
 53    /// Error message if parsing or request failed.
 54    #[serde(default, skip_serializing_if = "Option::is_none")]
 55    pub error: Option<String>,
 56}
 57
 58/// Build the assessment prompt for an example.
 59pub fn build_prompt(example: &Example) -> Option<String> {
 60    let prediction = example.predictions.first()?;
 61    let actual_patch = prediction.actual_patch.as_ref()?;
 62    let prompt_inputs = example.prompt_inputs.as_ref()?;
 63
 64    let actual_patch_word_diff = unified_to_word_diff(actual_patch);
 65
 66    // Format cursor excerpt (reuse from format_prompt)
 67    let cursor_excerpt = extract_cursor_excerpt_from_example(example)?;
 68
 69    let mut edit_history = String::new();
 70    for event in &prompt_inputs.edit_history {
 71        match event.as_ref() {
 72            zeta_prompt::Event::BufferChange {
 73                path,
 74                old_path,
 75                diff,
 76                predicted: _,
 77                in_open_source_repo: _,
 78            } => {
 79                edit_history.push_str(&format!("--- a{}\n", old_path.display()));
 80                edit_history.push_str(&format!("+++ b{}\n", path.display()));
 81                let diff_word_diff = unified_to_word_diff(diff);
 82                edit_history.push_str(&diff_word_diff);
 83                edit_history.push_str("\n\n");
 84            }
 85        }
 86    }
 87
 88    Some(
 89        PROMPT_TEMPLATE
 90            .replace("{edit_history}", &edit_history)
 91            .replace("{cursor_excerpt}", &cursor_excerpt)
 92            .replace("{actual_patch_word_diff}", &actual_patch_word_diff),
 93    )
 94}
 95
 96/// Extract a code block from a response.
 97fn extract_codeblock(response: &str) -> Option<String> {
 98    let lines: Vec<&str> = response.lines().collect();
 99    for (i, line) in lines.iter().enumerate() {
100        if line.starts_with("```") {
101            let start = i + 1;
102            for (j, end_line) in lines[start..].iter().enumerate() {
103                if end_line.starts_with("```") {
104                    return Some(lines[start..start + j].join("\n"));
105                }
106            }
107            return Some(lines[start..].join("\n"));
108        }
109    }
110    None
111}
112
113/// Parse the LLM response into a QaResult.
114pub(crate) fn parse_response(response_text: &str) -> QaResult {
115    let codeblock = extract_codeblock(response_text);
116
117    // Try parsing codeblock first, then fall back to raw response
118    for text_to_parse in [codeblock.as_deref(), Some(response_text.trim())] {
119        let Some(text) = text_to_parse else {
120            continue;
121        };
122
123        if let Ok(parsed) = serde_json::from_str::<serde_json::Value>(text) {
124            return QaResult {
125                reasoning: parsed
126                    .get("reasoning")
127                    .and_then(|v| v.as_str())
128                    .map(|s| s.to_string()),
129                reverts_edits: parsed.get("reverts_edits").and_then(|v| v.as_bool()),
130                confidence: parsed
131                    .get("confidence")
132                    .and_then(|v| v.as_u64())
133                    .map(|v| v as u8),
134                response: Some(response_text.to_string()),
135                error: None,
136            };
137        }
138    }
139
140    // If all parsing attempts fail, return error
141    QaResult {
142        reasoning: Some(response_text.to_string()),
143        reverts_edits: None,
144        confidence: None,
145        response: Some(response_text.to_string()),
146        error: Some("Could not parse JSON from response".to_string()),
147    }
148}
149
150/// Run the QA evaluation on a set of examples.
151pub async fn run_qa(
152    examples: &mut [Example],
153    args: &QaArgs,
154    output_path: Option<&PathBuf>,
155) -> Result<()> {
156    let model = model_for_backend(args.backend);
157    let client = LlmClient::new(args.backend, !args.no_batch)?;
158
159    eprintln!(
160        "Using model: {}, backend: {:?}, batching: {}",
161        model, args.backend, !args.no_batch
162    );
163
164    // First pass: send requests (client handles caching internally)
165    let mut prompts: Vec<(usize, String)> = Vec::new();
166    let mut skipped_count = 0;
167
168    for (idx, example) in examples.iter().enumerate() {
169        let Some(prompt) = build_prompt(example) else {
170            skipped_count += 1;
171            continue;
172        };
173        prompts.push((idx, prompt));
174    }
175
176    if skipped_count > 0 {
177        eprintln!("Skipping {} items with missing actual_patch", skipped_count);
178    }
179
180    eprintln!("{} items to process", prompts.len());
181
182    // Process all items
183    let mut results: Vec<(usize, Option<QaResult>)> = Vec::new();
184
185    if args.no_batch {
186        // Synchronous processing
187        for (i, (idx, prompt)) in prompts.iter().enumerate() {
188            eprint!("\rProcessing {}/{}", i + 1, prompts.len());
189
190            let response = client.generate(model, 1024, prompt).await?;
191            let result = response.map(|text| parse_response(&text));
192            results.push((*idx, result));
193        }
194        eprintln!();
195    } else {
196        // Queue all for batching
197        for (idx, prompt) in &prompts {
198            let response = client.generate(model, 1024, prompt).await?;
199            let result = response.map(|text| parse_response(&text));
200            results.push((*idx, result));
201        }
202
203        // Sync batches (upload pending, download finished)
204        client.sync_batches().await?;
205
206        if args.wait {
207            eprintln!("Waiting for batch to complete...");
208            loop {
209                std::thread::sleep(std::time::Duration::from_secs(30));
210                client.sync_batches().await?;
211
212                // Re-check all items that didn't have results
213                let mut all_done = true;
214                for (result_idx, (idx, prompt)) in prompts.iter().enumerate() {
215                    if results[result_idx].1.is_none() {
216                        let response = client.generate(model, 1024, prompt).await?;
217                        if let Some(text) = response {
218                            results[result_idx] = (*idx, Some(parse_response(&text)));
219                        } else {
220                            all_done = false;
221                        }
222                    }
223                }
224
225                let done_count = results.iter().filter(|(_, r)| r.is_some()).count();
226                if all_done {
227                    break;
228                }
229                eprintln!("Still waiting... {}/{} results", done_count, prompts.len());
230            }
231        } else {
232            let pending_count = results.iter().filter(|(_, r)| r.is_none()).count();
233            if pending_count > 0 {
234                eprintln!(
235                    "Batch submitted. {} pending. Run again later to retrieve results.",
236                    pending_count
237                );
238            }
239        }
240    }
241
242    // Build results map by index
243    let mut results_by_idx: std::collections::HashMap<usize, QaResult> =
244        std::collections::HashMap::new();
245    for (idx, result) in results {
246        if let Some(r) = result {
247            results_by_idx.insert(idx, r);
248        }
249    }
250
251    // Output results
252    let mut writer: Box<dyn Write> = if let Some(path) = output_path {
253        Box::new(BufWriter::new(std::fs::File::create(path)?))
254    } else {
255        Box::new(std::io::stdout())
256    };
257
258    let mut num_total = 0;
259    let mut num_reverts_edits = 0;
260
261    for (idx, example) in examples.iter_mut().enumerate() {
262        // Skip examples that couldn't be processed
263        if build_prompt(example).is_none() {
264            continue;
265        }
266
267        let result = results_by_idx.get(&idx).cloned();
268
269        if result.as_ref().and_then(|r| r.reverts_edits) == Some(true) {
270            num_reverts_edits += 1;
271        }
272        num_total += 1;
273
274        // Populate QA results for each prediction (currently only first prediction is evaluated)
275        example.qa = example
276            .predictions
277            .iter()
278            .enumerate()
279            .map(|(i, _)| if i == 0 { result.clone() } else { None })
280            .collect();
281
282        writeln!(writer, "{}", serde_json::to_string(&example)?)?;
283    }
284
285    if let Some(path) = output_path {
286        eprintln!("Results written to {}", path.display());
287    }
288
289    eprintln!("Processed:     {} items", num_total);
290    if num_total > 0 {
291        eprintln!(
292            "Reverts edits: {} ({:.2}%)",
293            num_reverts_edits,
294            num_reverts_edits as f64 / num_total as f64 * 100.0
295        );
296    }
297
298    Ok(())
299}