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
24pub async fn run_prediction(
25 example: &mut Example,
26 provider: Option<PredictionProvider>,
27 repetition_count: usize,
28 app_state: Arc<EpAppState>,
29 mut cx: AsyncApp,
30) -> anyhow::Result<()> {
31 let provider = provider.context("provider is required")?;
32
33 if let Some(existing_prediction) = example.predictions.first() {
34 if existing_prediction.provider == provider {
35 return Ok(());
36 } else {
37 example.predictions.clear();
38 }
39 }
40
41 run_context_retrieval(example, app_state.clone(), cx.clone()).await?;
42
43 if matches!(
44 provider,
45 PredictionProvider::Teacher | PredictionProvider::TeacherNonBatching
46 ) {
47 let _step_progress = Progress::global().start(Step::Predict, &example.spec.name);
48
49 if example.prompt.is_none() {
50 run_format_prompt(example, PromptFormat::Teacher, app_state.clone(), cx).await?;
51 }
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 = if batched {
239 AnthropicClient::batch(&crate::paths::LLM_CACHE_DB.as_ref())
240 } else {
241 AnthropicClient::plain()
242 };
243 let llm_client = llm_client.context("Failed to create LLM client")?;
244
245 let prompt = example.prompt.as_ref().context("Prompt is required")?;
246
247 let messages = vec![anthropic::Message {
248 role: anthropic::Role::User,
249 content: vec![anthropic::RequestContent::Text {
250 text: prompt.input.clone(),
251 cache_control: None,
252 }],
253 }];
254
255 let Some(response) = llm_client
256 .generate(llm_model_name, max_tokens, messages)
257 .await?
258 else {
259 // Request stashed for batched processing
260 return Ok(());
261 };
262
263 let actual_output = response
264 .content
265 .into_iter()
266 .filter_map(|content| match content {
267 anthropic::ResponseContent::Text { text } => Some(text),
268 _ => None,
269 })
270 .collect::<Vec<String>>()
271 .join("\n");
272
273 let actual_patch = TeacherPrompt::parse(example, &actual_output)?;
274
275 let prediction = ExamplePrediction {
276 actual_patch,
277 actual_output,
278 provider: PredictionProvider::Teacher,
279 };
280
281 example.predictions.push(prediction);
282 Ok(())
283}
284
285pub async fn sync_batches(provider: &PredictionProvider) -> anyhow::Result<()> {
286 match provider {
287 PredictionProvider::Teacher => {
288 let cache_path = crate::paths::LLM_CACHE_DB.as_ref();
289 let llm_client =
290 AnthropicClient::batch(cache_path).context("Failed to create LLM client")?;
291 llm_client
292 .sync_batches()
293 .await
294 .context("Failed to sync batches")?;
295 }
296 _ => (),
297 };
298 Ok(())
299}