predict.rs

  1use crate::{
  2    FormatPromptArgs, PredictArgs, PredictionProvider, TeacherBackend,
  3    anthropic_client::AnthropicClient,
  4    example::{Example, ExamplePrediction, ExamplePrompt},
  5    format_prompt::{TeacherPrompt, run_format_prompt},
  6    headless::EpAppState,
  7    load_project::run_load_project,
  8    openai_client::OpenAiClient,
  9    paths::{LATEST_EXAMPLE_RUN_DIR, RUN_DIR},
 10    progress::{ExampleProgress, InfoStyle, Step},
 11    retrieve_context::run_context_retrieval,
 12};
 13use anyhow::Context as _;
 14use edit_prediction::{DebugEvent, EditPredictionStore};
 15use futures::{FutureExt as _, StreamExt as _, future::Shared};
 16use gpui::{AppContext as _, AsyncApp, Task};
 17use std::{
 18    fs,
 19    sync::{
 20        Arc, Mutex, OnceLock,
 21        atomic::{AtomicUsize, Ordering::SeqCst},
 22    },
 23};
 24
 25static ANTHROPIC_CLIENT: OnceLock<AnthropicClient> = OnceLock::new();
 26static OPENAI_CLIENT: OnceLock<OpenAiClient> = OnceLock::new();
 27
 28pub async fn run_prediction(
 29    example: &mut Example,
 30    args: &PredictArgs,
 31    app_state: Arc<EpAppState>,
 32    example_progress: &ExampleProgress,
 33    mut cx: AsyncApp,
 34) -> anyhow::Result<()> {
 35    let repetition_count = args.repetitions;
 36
 37    if let Some(existing_prediction) = example.predictions.first() {
 38        let has_prediction = existing_prediction.actual_patch.is_some()
 39            || !existing_prediction.actual_output.is_empty();
 40        if has_prediction {
 41            match args.provider {
 42                None => return Ok(()),
 43                Some(provider) if existing_prediction.provider == provider => return Ok(()),
 44                Some(_) => example.predictions.clear(),
 45            }
 46        }
 47    }
 48
 49    let Some(provider) = args.provider else {
 50        anyhow::bail!(
 51            "No existing predictions found. Use --provider to specify which model to use for prediction."
 52        );
 53    };
 54
 55    run_context_retrieval(example, app_state.clone(), example_progress, cx.clone()).await?;
 56
 57    if let PredictionProvider::Teacher(backend) | PredictionProvider::TeacherNonBatching(backend) =
 58        provider
 59    {
 60        let _step_progress = example_progress.start(Step::Predict);
 61
 62        run_format_prompt(
 63            example,
 64            &FormatPromptArgs { provider },
 65            app_state.clone(),
 66            example_progress,
 67            cx,
 68        )
 69        .await?;
 70
 71        let batched = matches!(provider, PredictionProvider::Teacher(..));
 72        return predict_teacher(example, backend, batched, repetition_count, args.cache_only).await;
 73    }
 74
 75    run_load_project(example, app_state.clone(), example_progress, cx.clone()).await?;
 76
 77    let step_progress = example_progress.start(Step::Predict);
 78
 79    if matches!(
 80        provider,
 81        PredictionProvider::Zeta1 | PredictionProvider::Zeta2(_)
 82    ) {
 83        step_progress.set_substatus("authenticating");
 84        static AUTHENTICATED: OnceLock<Shared<Task<()>>> = OnceLock::new();
 85        AUTHENTICATED
 86            .get_or_init(|| {
 87                let client = app_state.client.clone();
 88                cx.spawn(async move |cx| {
 89                    if let Err(e) = client.sign_in_with_optional_connect(true, cx).await {
 90                        eprintln!("Authentication failed: {}", e);
 91                    }
 92                })
 93                .shared()
 94            })
 95            .clone()
 96            .await;
 97    }
 98
 99    let ep_store = cx
100        .update(|cx| EditPredictionStore::try_global(cx))
101        .context("EditPredictionStore not initialized")?;
102
103    ep_store.update(&mut cx, |store, _cx| {
104        let model = match provider {
105            PredictionProvider::Zeta1 => edit_prediction::EditPredictionModel::Zeta1,
106            PredictionProvider::Zeta2(version) => {
107                edit_prediction::EditPredictionModel::Zeta2 { version }
108            }
109            PredictionProvider::Sweep => edit_prediction::EditPredictionModel::Sweep,
110            PredictionProvider::Mercury => edit_prediction::EditPredictionModel::Mercury,
111            PredictionProvider::Teacher(..)
112            | PredictionProvider::TeacherNonBatching(..)
113            | PredictionProvider::Repair => {
114                unreachable!()
115            }
116        };
117        store.set_edit_prediction_model(model);
118    });
119    step_progress.set_substatus("configuring model");
120    let state = example.state.as_ref().context("state must be set")?;
121    let run_dir = RUN_DIR.join(&example.spec.name);
122
123    let updated_example = Arc::new(Mutex::new(example.clone()));
124    let current_run_ix = Arc::new(AtomicUsize::new(0));
125
126    let mut debug_rx = ep_store.update(&mut cx, |store, cx| store.debug_info(&state.project, cx));
127    let debug_task = cx.background_spawn({
128        let updated_example = updated_example.clone();
129        let current_run_ix = current_run_ix.clone();
130        let run_dir = run_dir.clone();
131        async move {
132            while let Some(event) = debug_rx.next().await {
133                let run_ix = current_run_ix.load(SeqCst);
134                let mut updated_example = updated_example.lock().unwrap();
135
136                let run_dir = if repetition_count > 1 {
137                    run_dir.join(format!("{:03}", run_ix))
138                } else {
139                    run_dir.clone()
140                };
141
142                match event {
143                    DebugEvent::EditPredictionStarted(request) => {
144                        assert_eq!(updated_example.predictions.len(), run_ix + 1);
145
146                        if let Some(prompt) = request.prompt {
147                            fs::write(run_dir.join("prediction_prompt.md"), &prompt)?;
148                            if matches!(provider, PredictionProvider::Zeta2(_)) {
149                                updated_example.prompt.get_or_insert(ExamplePrompt {
150                                    input: prompt,
151                                    expected_output: String::new(),
152                                    rejected_output: None,
153                                    provider,
154                                });
155                            }
156                        }
157                    }
158                    DebugEvent::EditPredictionFinished(request) => {
159                        assert_eq!(updated_example.predictions.len(), run_ix + 1);
160
161                        if let Some(output) = request.model_output {
162                            fs::write(run_dir.join("prediction_response.md"), &output)?;
163                            updated_example
164                                .predictions
165                                .last_mut()
166                                .unwrap()
167                                .actual_output = output;
168                        }
169                        if run_ix >= repetition_count {
170                            break;
171                        }
172                    }
173                    _ => {}
174                }
175            }
176            anyhow::Ok(())
177        }
178    });
179
180    for ix in 0..repetition_count {
181        current_run_ix.store(ix, SeqCst);
182        let run_dir = if repetition_count > 1 {
183            run_dir.join(format!("{:03}", ix))
184        } else {
185            run_dir.clone()
186        };
187
188        fs::create_dir_all(&run_dir)?;
189        if LATEST_EXAMPLE_RUN_DIR.is_symlink() {
190            fs::remove_file(&*LATEST_EXAMPLE_RUN_DIR)?;
191        }
192        #[cfg(unix)]
193        std::os::unix::fs::symlink(&run_dir, &*LATEST_EXAMPLE_RUN_DIR)?;
194        #[cfg(windows)]
195        std::os::windows::fs::symlink_dir(&run_dir, &*LATEST_EXAMPLE_RUN_DIR)?;
196
197        updated_example
198            .lock()
199            .unwrap()
200            .predictions
201            .push(ExamplePrediction {
202                actual_patch: None,
203                actual_output: String::new(),
204                error: None,
205                provider,
206            });
207
208        step_progress.set_substatus("requesting prediction");
209        let prediction = ep_store
210            .update(&mut cx, |store, cx| {
211                store.request_prediction(
212                    &state.project,
213                    &state.buffer,
214                    state.cursor_position,
215                    cloud_llm_client::PredictEditsRequestTrigger::Cli,
216                    cx,
217                )
218            })
219            .await?;
220
221        let actual_patch = prediction.and_then(|prediction| {
222            let prediction = prediction.prediction.ok()?;
223            prediction
224                .edit_preview
225                .as_unified_diff(prediction.snapshot.file(), &prediction.edits)
226        });
227
228        let has_prediction = actual_patch.as_ref().is_some_and(|p| !p.is_empty());
229
230        updated_example
231            .lock()
232            .unwrap()
233            .predictions
234            .last_mut()
235            .unwrap()
236            .actual_patch = actual_patch;
237
238        if ix == repetition_count - 1 {
239            let (info, style) = if has_prediction {
240                ("predicted", InfoStyle::Normal)
241            } else {
242                ("no prediction", InfoStyle::Warning)
243            };
244            step_progress.set_info(info, style);
245        }
246    }
247
248    ep_store.update(&mut cx, |store, _| {
249        store.remove_project(&state.project);
250    });
251    debug_task.await?;
252
253    *example = Arc::into_inner(updated_example)
254        .ok_or_else(|| anyhow::anyhow!("Failed to unwrap Arc"))?
255        .into_inner()
256        .map_err(|_| anyhow::anyhow!("Failed to unwrap Mutex"))?;
257    Ok(())
258}
259
260async fn predict_teacher(
261    example: &mut Example,
262    backend: TeacherBackend,
263    batched: bool,
264    repetition_count: usize,
265    cache_only: bool,
266) -> anyhow::Result<()> {
267    match backend {
268        TeacherBackend::Sonnet45 => {
269            predict_anthropic(example, backend, batched, repetition_count, cache_only).await
270        }
271        TeacherBackend::Gpt52 => {
272            predict_openai(example, backend, batched, repetition_count, cache_only).await
273        }
274    }
275}
276
277async fn predict_anthropic(
278    example: &mut Example,
279    backend: TeacherBackend,
280    batched: bool,
281    repetition_count: usize,
282    cache_only: bool,
283) -> anyhow::Result<()> {
284    let llm_model_name = backend.model_name();
285    let max_tokens = 16384;
286    let llm_client = ANTHROPIC_CLIENT.get_or_init(|| {
287        let client = if batched {
288            AnthropicClient::batch(&crate::paths::LLM_CACHE_DB)
289        } else {
290            AnthropicClient::plain()
291        };
292        client.expect("Failed to create Anthropic client")
293    });
294
295    let prompt = example.prompt.as_ref().context("Prompt is required")?;
296
297    for ix in 0..repetition_count {
298        let messages = vec![anthropic::Message {
299            role: anthropic::Role::User,
300            content: vec![anthropic::RequestContent::Text {
301                text: prompt.input.clone(),
302                cache_control: None,
303            }],
304        }];
305
306        let seed = if repetition_count > 1 { Some(ix) } else { None };
307        let Some(response) = llm_client
308            .generate(llm_model_name, max_tokens, messages, seed, cache_only)
309            .await?
310        else {
311            // Request stashed for batched processing
312            return Ok(());
313        };
314
315        let actual_output = response
316            .content
317            .into_iter()
318            .filter_map(|content| match content {
319                anthropic::ResponseContent::Text { text } => Some(text),
320                _ => None,
321            })
322            .collect::<Vec<String>>()
323            .join("\n");
324
325        let actual_patch = TeacherPrompt::parse(example, &actual_output)?;
326
327        let prediction = ExamplePrediction {
328            actual_patch: Some(actual_patch),
329            actual_output,
330            error: None,
331            provider: if batched {
332                PredictionProvider::Teacher(backend)
333            } else {
334                PredictionProvider::TeacherNonBatching(backend)
335            },
336        };
337
338        example.predictions.push(prediction);
339    }
340    Ok(())
341}
342
343async fn predict_openai(
344    example: &mut Example,
345    backend: TeacherBackend,
346    batched: bool,
347    repetition_count: usize,
348    cache_only: bool,
349) -> anyhow::Result<()> {
350    let llm_model_name = backend.model_name();
351    let max_tokens = 16384;
352    let llm_client = OPENAI_CLIENT.get_or_init(|| {
353        let client = if batched {
354            OpenAiClient::batch(&crate::paths::LLM_CACHE_DB)
355        } else {
356            OpenAiClient::plain()
357        };
358        client.expect("Failed to create OpenAI client")
359    });
360
361    let prompt = example.prompt.as_ref().context("Prompt is required")?;
362
363    for ix in 0..repetition_count {
364        let messages = vec![open_ai::RequestMessage::User {
365            content: open_ai::MessageContent::Plain(prompt.input.clone()),
366        }];
367
368        let seed = if repetition_count > 1 { Some(ix) } else { None };
369        let Some(response) = llm_client
370            .generate(llm_model_name, max_tokens, messages, seed, cache_only)
371            .await?
372        else {
373            // Request stashed for batched processing
374            return Ok(());
375        };
376
377        let actual_output = response
378            .choices
379            .into_iter()
380            .filter_map(|choice| match choice.message {
381                open_ai::RequestMessage::Assistant { content, .. } => content.map(|c| match c {
382                    open_ai::MessageContent::Plain(text) => text,
383                    open_ai::MessageContent::Multipart(parts) => parts
384                        .into_iter()
385                        .filter_map(|p| match p {
386                            open_ai::MessagePart::Text { text } => Some(text),
387                            _ => None,
388                        })
389                        .collect::<Vec<_>>()
390                        .join(""),
391                }),
392                _ => None,
393            })
394            .collect::<Vec<String>>()
395            .join("\n");
396
397        let actual_patch = TeacherPrompt::parse(example, &actual_output)?;
398
399        let prediction = ExamplePrediction {
400            actual_patch: Some(actual_patch),
401            actual_output,
402            error: None,
403            provider: if batched {
404                PredictionProvider::Teacher(backend)
405            } else {
406                PredictionProvider::TeacherNonBatching(backend)
407            },
408        };
409
410        example.predictions.push(prediction);
411    }
412    Ok(())
413}
414
415pub async fn sync_batches(provider: Option<&PredictionProvider>) -> anyhow::Result<()> {
416    match provider {
417        Some(PredictionProvider::Teacher(backend)) => match backend {
418            TeacherBackend::Sonnet45 => {
419                let llm_client = ANTHROPIC_CLIENT.get_or_init(|| {
420                    AnthropicClient::batch(&crate::paths::LLM_CACHE_DB)
421                        .expect("Failed to create Anthropic client")
422                });
423                llm_client
424                    .sync_batches()
425                    .await
426                    .context("Failed to sync Anthropic batches")?;
427            }
428            TeacherBackend::Gpt52 => {
429                let llm_client = OPENAI_CLIENT.get_or_init(|| {
430                    OpenAiClient::batch(&crate::paths::LLM_CACHE_DB)
431                        .expect("Failed to create OpenAI client")
432                });
433                llm_client
434                    .sync_batches()
435                    .await
436                    .context("Failed to sync OpenAI batches")?;
437            }
438        },
439        _ => (),
440    };
441    Ok(())
442}