predict.rs

  1use crate::{
  2    PredictionProvider, PromptFormat,
  3    anthropic_client::AnthropicClient,
  4    example::{Example, ExamplePrediction},
  5    format_prompt::{TeacherPrompt, run_format_prompt},
  6    headless::EpAppState,
  7    load_project::run_load_project,
  8    paths::{LATEST_EXAMPLE_RUN_DIR, RUN_DIR},
  9    progress::{InfoStyle, Progress, Step},
 10    retrieve_context::run_context_retrieval,
 11};
 12use anyhow::Context as _;
 13use edit_prediction::{DebugEvent, EditPredictionStore};
 14use futures::{FutureExt as _, StreamExt as _, future::Shared};
 15use gpui::{AppContext as _, AsyncApp, Task};
 16use std::{
 17    fs,
 18    sync::{
 19        Arc, Mutex, OnceLock,
 20        atomic::{AtomicUsize, Ordering::SeqCst},
 21    },
 22};
 23
 24static ANTHROPIC_CLIENT: OnceLock<AnthropicClient> = OnceLock::new();
 25
 26pub async fn run_prediction(
 27    example: &mut Example,
 28    provider: Option<PredictionProvider>,
 29    repetition_count: usize,
 30    app_state: Arc<EpAppState>,
 31    mut cx: AsyncApp,
 32) -> anyhow::Result<()> {
 33    let provider = provider.context("provider is required")?;
 34
 35    if let Some(existing_prediction) = example.predictions.first() {
 36        if existing_prediction.provider == provider {
 37            return Ok(());
 38        } else {
 39            example.predictions.clear();
 40        }
 41    }
 42
 43    run_context_retrieval(example, app_state.clone(), cx.clone()).await?;
 44
 45    if matches!(
 46        provider,
 47        PredictionProvider::Teacher | PredictionProvider::TeacherNonBatching
 48    ) {
 49        let _step_progress = Progress::global().start(Step::Predict, &example.spec.name);
 50
 51        run_format_prompt(example, PromptFormat::Teacher, app_state.clone(), cx).await?;
 52
 53        let batched = matches!(provider, PredictionProvider::Teacher);
 54        return predict_anthropic(example, repetition_count, batched).await;
 55    }
 56
 57    run_load_project(example, app_state.clone(), cx.clone()).await?;
 58
 59    let step_progress = Progress::global().start(Step::Predict, &example.spec.name);
 60
 61    if matches!(
 62        provider,
 63        PredictionProvider::Zeta1 | PredictionProvider::Zeta2
 64    ) {
 65        step_progress.set_substatus("authenticating");
 66        static AUTHENTICATED: OnceLock<Shared<Task<()>>> = OnceLock::new();
 67        AUTHENTICATED
 68            .get_or_init(|| {
 69                let client = app_state.client.clone();
 70                cx.spawn(async move |cx| {
 71                    if let Err(e) = client.sign_in_with_optional_connect(true, cx).await {
 72                        eprintln!("Authentication failed: {}", e);
 73                    }
 74                })
 75                .shared()
 76            })
 77            .clone()
 78            .await;
 79    }
 80
 81    let ep_store = cx
 82        .update(|cx| EditPredictionStore::try_global(cx))
 83        .context("EditPredictionStore not initialized")?;
 84
 85    ep_store.update(&mut cx, |store, _cx| {
 86        let model = match provider {
 87            PredictionProvider::Zeta1 => edit_prediction::EditPredictionModel::Zeta1,
 88            PredictionProvider::Zeta2 => edit_prediction::EditPredictionModel::Zeta2,
 89            PredictionProvider::Sweep => edit_prediction::EditPredictionModel::Sweep,
 90            PredictionProvider::Mercury => edit_prediction::EditPredictionModel::Mercury,
 91            PredictionProvider::Teacher | PredictionProvider::TeacherNonBatching => {
 92                unreachable!()
 93            }
 94        };
 95        store.set_edit_prediction_model(model);
 96    });
 97    step_progress.set_substatus("configuring model");
 98    let state = example.state.as_ref().context("state must be set")?;
 99    let run_dir = RUN_DIR.join(&example.spec.name);
100
101    let updated_example = Arc::new(Mutex::new(example.clone()));
102    let current_run_ix = Arc::new(AtomicUsize::new(0));
103
104    let mut debug_rx = ep_store.update(&mut cx, |store, cx| store.debug_info(&state.project, cx));
105    let debug_task = cx.background_spawn({
106        let updated_example = updated_example.clone();
107        let current_run_ix = current_run_ix.clone();
108        let run_dir = run_dir.clone();
109        async move {
110            while let Some(event) = debug_rx.next().await {
111                let run_ix = current_run_ix.load(SeqCst);
112                let mut updated_example = updated_example.lock().unwrap();
113
114                let run_dir = if repetition_count > 1 {
115                    run_dir.join(format!("{:03}", run_ix))
116                } else {
117                    run_dir.clone()
118                };
119
120                match event {
121                    DebugEvent::EditPredictionStarted(request) => {
122                        assert_eq!(updated_example.predictions.len(), run_ix + 1);
123
124                        if let Some(prompt) = request.prompt {
125                            fs::write(run_dir.join("prediction_prompt.md"), &prompt)?;
126                        }
127                    }
128                    DebugEvent::EditPredictionFinished(request) => {
129                        assert_eq!(updated_example.predictions.len(), run_ix + 1);
130
131                        if let Some(output) = request.model_output {
132                            fs::write(run_dir.join("prediction_response.md"), &output)?;
133                            updated_example
134                                .predictions
135                                .last_mut()
136                                .unwrap()
137                                .actual_output = output;
138                        }
139                        if run_ix >= repetition_count {
140                            break;
141                        }
142                    }
143                    _ => {}
144                }
145            }
146            anyhow::Ok(())
147        }
148    });
149
150    for ix in 0..repetition_count {
151        current_run_ix.store(ix, SeqCst);
152        let run_dir = if repetition_count > 1 {
153            run_dir.join(format!("{:03}", ix))
154        } else {
155            run_dir.clone()
156        };
157
158        fs::create_dir_all(&run_dir)?;
159        if LATEST_EXAMPLE_RUN_DIR.is_symlink() {
160            fs::remove_file(&*LATEST_EXAMPLE_RUN_DIR)?;
161        }
162        #[cfg(unix)]
163        std::os::unix::fs::symlink(&run_dir, &*LATEST_EXAMPLE_RUN_DIR)?;
164        #[cfg(windows)]
165        std::os::windows::fs::symlink_dir(&run_dir, &*LATEST_EXAMPLE_RUN_DIR)?;
166
167        updated_example
168            .lock()
169            .unwrap()
170            .predictions
171            .push(ExamplePrediction {
172                actual_patch: String::new(),
173                actual_output: String::new(),
174                provider,
175            });
176
177        step_progress.set_substatus("requesting prediction");
178        let prediction = ep_store
179            .update(&mut cx, |store, cx| {
180                store.request_prediction(
181                    &state.project,
182                    &state.buffer,
183                    state.cursor_position,
184                    cloud_llm_client::PredictEditsRequestTrigger::Cli,
185                    cx,
186                )
187            })
188            .await?;
189
190        let actual_patch = prediction
191            .and_then(|prediction| {
192                let prediction = prediction.prediction.ok()?;
193                prediction
194                    .edit_preview
195                    .as_unified_diff(prediction.snapshot.file(), &prediction.edits)
196            })
197            .unwrap_or_default();
198
199        let has_prediction = !actual_patch.is_empty();
200
201        updated_example
202            .lock()
203            .unwrap()
204            .predictions
205            .last_mut()
206            .unwrap()
207            .actual_patch = actual_patch;
208
209        if ix == repetition_count - 1 {
210            let (info, style) = if has_prediction {
211                ("predicted", InfoStyle::Normal)
212            } else {
213                ("no prediction", InfoStyle::Warning)
214            };
215            step_progress.set_info(info, style);
216        }
217    }
218
219    ep_store.update(&mut cx, |store, _| {
220        store.remove_project(&state.project);
221    });
222    debug_task.await?;
223
224    *example = Arc::into_inner(updated_example)
225        .ok_or_else(|| anyhow::anyhow!("Failed to unwrap Arc"))?
226        .into_inner()
227        .map_err(|_| anyhow::anyhow!("Failed to unwrap Mutex"))?;
228    Ok(())
229}
230
231async fn predict_anthropic(
232    example: &mut Example,
233    _repetition_count: usize,
234    batched: bool,
235) -> anyhow::Result<()> {
236    let llm_model_name = "claude-sonnet-4-5";
237    let max_tokens = 16384;
238    let llm_client = ANTHROPIC_CLIENT.get_or_init(|| {
239        let client = if batched {
240            AnthropicClient::batch(&crate::paths::LLM_CACHE_DB)
241        } else {
242            AnthropicClient::plain()
243        };
244        client.expect("Failed to create Anthropic client")
245    });
246
247    let prompt = example.prompt.as_ref().context("Prompt is required")?;
248
249    let messages = vec![anthropic::Message {
250        role: anthropic::Role::User,
251        content: vec![anthropic::RequestContent::Text {
252            text: prompt.input.clone(),
253            cache_control: None,
254        }],
255    }];
256
257    let Some(response) = llm_client
258        .generate(llm_model_name, max_tokens, messages)
259        .await?
260    else {
261        // Request stashed for batched processing
262        return Ok(());
263    };
264
265    let actual_output = response
266        .content
267        .into_iter()
268        .filter_map(|content| match content {
269            anthropic::ResponseContent::Text { text } => Some(text),
270            _ => None,
271        })
272        .collect::<Vec<String>>()
273        .join("\n");
274
275    let actual_patch = TeacherPrompt::parse(example, &actual_output)?;
276
277    let prediction = ExamplePrediction {
278        actual_patch,
279        actual_output,
280        provider: PredictionProvider::Teacher,
281    };
282
283    example.predictions.push(prediction);
284    Ok(())
285}
286
287pub async fn sync_batches(provider: &PredictionProvider) -> anyhow::Result<()> {
288    match provider {
289        PredictionProvider::Teacher => {
290            let llm_client = ANTHROPIC_CLIENT.get_or_init(|| {
291                AnthropicClient::batch(&crate::paths::LLM_CACHE_DB)
292                    .expect("Failed to create Anthropic client")
293            });
294            llm_client
295                .sync_batches()
296                .await
297                .context("Failed to sync batches")?;
298        }
299        _ => (),
300    };
301    Ok(())
302}