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 error: None,
201 provider,
202 });
203
204 step_progress.set_substatus("requesting prediction");
205 let prediction = ep_store
206 .update(&mut cx, |store, cx| {
207 store.request_prediction(
208 &state.project,
209 &state.buffer,
210 state.cursor_position,
211 cloud_llm_client::PredictEditsRequestTrigger::Cli,
212 cx,
213 )
214 })
215 .await?;
216
217 let actual_patch = prediction.and_then(|prediction| {
218 let prediction = prediction.prediction.ok()?;
219 prediction
220 .edit_preview
221 .as_unified_diff(prediction.snapshot.file(), &prediction.edits)
222 });
223
224 let has_prediction = actual_patch.as_ref().is_some_and(|p| !p.is_empty());
225
226 updated_example
227 .lock()
228 .unwrap()
229 .predictions
230 .last_mut()
231 .unwrap()
232 .actual_patch = actual_patch;
233
234 if ix == repetition_count - 1 {
235 let (info, style) = if has_prediction {
236 ("predicted", InfoStyle::Normal)
237 } else {
238 ("no prediction", InfoStyle::Warning)
239 };
240 step_progress.set_info(info, style);
241 }
242 }
243
244 ep_store.update(&mut cx, |store, _| {
245 store.remove_project(&state.project);
246 });
247 debug_task.await?;
248
249 *example = Arc::into_inner(updated_example)
250 .ok_or_else(|| anyhow::anyhow!("Failed to unwrap Arc"))?
251 .into_inner()
252 .map_err(|_| anyhow::anyhow!("Failed to unwrap Mutex"))?;
253 Ok(())
254}
255
256async fn predict_anthropic(
257 example: &mut Example,
258 _repetition_count: usize,
259 version: ZetaVersion,
260 batched: bool,
261) -> anyhow::Result<()> {
262 let llm_model_name = "claude-sonnet-4-5";
263 let max_tokens = 16384;
264 let llm_client = ANTHROPIC_CLIENT.get_or_init(|| {
265 let client = if batched {
266 AnthropicClient::batch(&crate::paths::LLM_CACHE_DB)
267 } else {
268 AnthropicClient::plain()
269 };
270 client.expect("Failed to create Anthropic client")
271 });
272
273 let prompt = example.prompt.as_ref().context("Prompt is required")?;
274
275 let messages = vec![anthropic::Message {
276 role: anthropic::Role::User,
277 content: vec![anthropic::RequestContent::Text {
278 text: prompt.input.clone(),
279 cache_control: None,
280 }],
281 }];
282
283 let Some(response) = llm_client
284 .generate(llm_model_name, max_tokens, messages)
285 .await?
286 else {
287 // Request stashed for batched processing
288 return Ok(());
289 };
290
291 let actual_output = response
292 .content
293 .into_iter()
294 .filter_map(|content| match content {
295 anthropic::ResponseContent::Text { text } => Some(text),
296 _ => None,
297 })
298 .collect::<Vec<String>>()
299 .join("\n");
300
301 let actual_patch = TeacherPrompt::parse(&example, &actual_output)?;
302
303 let prediction = ExamplePrediction {
304 actual_patch: Some(actual_patch),
305 actual_output,
306 error: None,
307 provider: if batched {
308 PredictionProvider::Teacher(version)
309 } else {
310 PredictionProvider::TeacherNonBatching(version)
311 },
312 };
313
314 example.predictions.push(prediction);
315 Ok(())
316}
317
318pub async fn sync_batches(provider: Option<&PredictionProvider>) -> anyhow::Result<()> {
319 match provider {
320 Some(PredictionProvider::Teacher(..)) => {
321 let llm_client = ANTHROPIC_CLIENT.get_or_init(|| {
322 AnthropicClient::batch(&crate::paths::LLM_CACHE_DB)
323 .expect("Failed to create Anthropic client")
324 });
325 llm_client
326 .sync_batches()
327 .await
328 .context("Failed to sync batches")?;
329 }
330 _ => (),
331 };
332 Ok(())
333}