format_prompt.rs

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