1use crate::{
2 PromptFormat,
3 example::{Example, ExamplePrompt},
4 headless::EpAppState,
5 load_project::run_load_project,
6 progress::{Progress, Step},
7 retrieve_context::run_context_retrieval,
8};
9use anyhow::{Context as _, Result, ensure};
10use edit_prediction::{
11 EditPredictionStore,
12 zeta2::{zeta2_output_for_patch, zeta2_prompt_input},
13};
14use gpui::AsyncApp;
15use std::sync::Arc;
16use zeta_prompt::format_zeta_prompt;
17
18pub async fn run_format_prompt(
19 example: &mut Example,
20 prompt_format: PromptFormat,
21 app_state: Arc<EpAppState>,
22 mut cx: AsyncApp,
23) -> Result<()> {
24 run_context_retrieval(example, app_state.clone(), cx.clone()).await?;
25
26 let _step_progress = Progress::global().start(Step::FormatPrompt, &example.name);
27
28 match prompt_format {
29 PromptFormat::Teacher => {
30 let prompt = TeacherPrompt::format_prompt(example);
31 example.prompt = Some(ExamplePrompt {
32 input: prompt,
33 expected_output: example.expected_patch.clone(), // TODO
34 format: prompt_format,
35 });
36 }
37 PromptFormat::Zeta2 => {
38 run_load_project(example, app_state, cx.clone()).await?;
39
40 let ep_store = cx.update(|cx| {
41 EditPredictionStore::try_global(cx).context("EditPredictionStore not initialized")
42 })??;
43
44 let state = example.state.as_ref().context("state must be set")?;
45 let snapshot = state.buffer.read_with(&cx, |buffer, _| buffer.snapshot())?;
46 let project = state.project.clone();
47 let (_, input) = ep_store.update(&mut cx, |ep_store, cx| {
48 anyhow::Ok(zeta2_prompt_input(
49 &snapshot,
50 example
51 .context
52 .as_ref()
53 .context("context must be set")?
54 .files
55 .clone(),
56 ep_store.edit_history_for_project(&project, cx),
57 example.cursor_path.clone(),
58 example
59 .buffer
60 .as_ref()
61 .context("buffer must be set")?
62 .cursor_offset,
63 ))
64 })??;
65 let prompt = format_zeta_prompt(&input);
66 let expected_output = zeta2_output_for_patch(&input, &example.expected_patch.clone())?;
67 example.prompt = Some(ExamplePrompt {
68 input: prompt,
69 expected_output,
70 format: prompt_format,
71 });
72 }
73 };
74 Ok(())
75}
76
77pub struct TeacherPrompt;
78
79impl TeacherPrompt {
80 const PROMPT: &str = include_str!("teacher.prompt.md");
81 pub(crate) const EDITABLE_REGION_START: &str = "<|editable_region_start|>\n";
82 pub(crate) const EDITABLE_REGION_END: &str = "<|editable_region_end|>";
83
84 /// Truncate edit history to this number of last lines
85 const MAX_HISTORY_LINES: usize = 128;
86
87 pub fn format_prompt(example: &Example) -> String {
88 let edit_history = Self::format_edit_history(&example.edit_history);
89 let context = Self::format_context(example);
90 let editable_region = Self::format_editable_region(example);
91
92 let prompt = Self::PROMPT
93 .replace("{{context}}", &context)
94 .replace("{{edit_history}}", &edit_history)
95 .replace("{{editable_region}}", &editable_region);
96
97 prompt
98 }
99
100 pub fn parse(example: &Example, response: &str) -> Result<String> {
101 // Ideally, we should always be able to find cursor position in the retrieved context.
102 // In reality, sometimes we don't find it for these reasons:
103 // 1. `example.cursor_position` contains _more_ context than included in the retrieved context
104 // (can be fixed by getting cursor coordinates at the load_example stage)
105 // 2. Context retriever just didn't include cursor line.
106 //
107 // In that case, fallback to using `cursor_position` as excerpt.
108 let cursor_file = &example
109 .buffer
110 .as_ref()
111 .context("`buffer` should be filled in in the context collection step")?
112 .content;
113
114 // Extract updated (new) editable region from the model response
115 let new_editable_region = extract_last_codeblock(response);
116
117 // Reconstruct old editable region we sent to the model
118 let old_editable_region = Self::format_editable_region(example);
119 let old_editable_region = Self::extract_editable_region(&old_editable_region);
120 ensure!(
121 cursor_file.contains(&old_editable_region),
122 "Something's wrong: editable_region is not found in the cursor file"
123 );
124
125 // Apply editable region to a larger context and compute diff.
126 // This is needed to get a better context lines around the editable region
127 let edited_file = cursor_file.replace(&old_editable_region, &new_editable_region);
128 let diff = language::unified_diff(&cursor_file, &edited_file);
129
130 let diff = indoc::formatdoc! {"
131 --- a/{path}
132 +++ b/{path}
133 {diff}",
134 path = example.cursor_path.to_string_lossy(),
135 diff = diff,
136 };
137
138 Ok(diff)
139 }
140
141 fn format_edit_history(edit_history: &str) -> String {
142 // Strip comments ("garbage lines") from edit history
143 let lines = edit_history
144 .lines()
145 .filter(|&s| Self::is_udiff_content_line(s))
146 .collect::<Vec<_>>();
147
148 let history_lines = if lines.len() > Self::MAX_HISTORY_LINES {
149 &lines[lines.len() - Self::MAX_HISTORY_LINES..]
150 } else {
151 &lines
152 };
153
154 if history_lines.is_empty() {
155 return "(No edit history)".to_string();
156 }
157
158 history_lines.join("\n")
159 }
160
161 fn format_context(example: &Example) -> String {
162 assert!(example.context.is_some(), "Missing context retriever step");
163
164 let mut prompt = String::new();
165 zeta_prompt::write_related_files(&mut prompt, &example.context.as_ref().unwrap().files);
166
167 prompt
168 }
169
170 fn format_editable_region(example: &Example) -> String {
171 let mut result = String::new();
172
173 let path_str = example.cursor_path.to_string_lossy();
174 result.push_str(&format!("`````path=\"{path_str}\"\n"));
175 result.push_str(Self::EDITABLE_REGION_START);
176
177 // TODO: control number of lines around cursor
178 result.push_str(&example.cursor_position);
179 if !example.cursor_position.ends_with('\n') {
180 result.push('\n');
181 }
182
183 result.push_str(&format!("{}\n", Self::EDITABLE_REGION_END));
184 result.push_str("`````");
185
186 result
187 }
188
189 fn extract_editable_region(text: &str) -> String {
190 let start = text
191 .find(Self::EDITABLE_REGION_START)
192 .map_or(0, |pos| pos + Self::EDITABLE_REGION_START.len());
193 let end = text.find(Self::EDITABLE_REGION_END).unwrap_or(text.len());
194
195 let region = &text[start..end];
196
197 region.replace("<|user_cursor|>", "")
198 }
199
200 fn is_udiff_content_line(s: &str) -> bool {
201 s.starts_with("-")
202 || s.starts_with("+")
203 || s.starts_with(" ")
204 || s.starts_with("---")
205 || s.starts_with("+++")
206 || s.starts_with("@@")
207 }
208}
209
210fn extract_last_codeblock(text: &str) -> String {
211 let mut last_block = None;
212 let mut search_start = 0;
213
214 while let Some(start) = text[search_start..].find("```") {
215 let start = start + search_start;
216 let bytes = text.as_bytes();
217 let mut backtick_end = start;
218
219 while backtick_end < bytes.len() && bytes[backtick_end] == b'`' {
220 backtick_end += 1;
221 }
222
223 let backtick_count = backtick_end - start;
224 let closing_backticks = "`".repeat(backtick_count);
225
226 while backtick_end < bytes.len() && bytes[backtick_end] != b'\n' {
227 backtick_end += 1;
228 }
229
230 if let Some(end_pos) = text[backtick_end..].find(&closing_backticks) {
231 let code_block = &text[backtick_end + 1..backtick_end + end_pos];
232 last_block = Some(code_block.to_string());
233 search_start = backtick_end + end_pos + backtick_count;
234 } else {
235 break;
236 }
237 }
238
239 last_block.unwrap_or_else(|| text.to_string())
240}
241
242#[cfg(test)]
243mod tests {
244 use super::*;
245
246 #[test]
247 fn test_extract_last_code_block() {
248 let text = indoc::indoc! {"
249 Some thinking
250
251 ```
252 first block
253 ```
254
255 `````path='something' lines=1:2
256 last block
257 `````
258 "};
259 let last_block = extract_last_codeblock(text);
260 assert_eq!(last_block, "last block\n");
261 }
262
263 #[test]
264 fn test_extract_editable_region() {
265 let text = indoc::indoc! {"
266 some lines
267 are
268 here
269 <|editable_region_start|>
270 one
271 two three
272
273 <|editable_region_end|>
274 more
275 lines here
276 "};
277 let parsed = TeacherPrompt::extract_editable_region(text);
278 assert_eq!(
279 parsed,
280 indoc::indoc! {"
281 one
282 two three
283
284 "}
285 );
286 }
287}