predict.rs

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