format_prompt.rs

  1use crate::{
  2    FormatPromptArgs, PredictionProvider,
  3    example::{Example, ExamplePrompt},
  4    headless::EpAppState,
  5    progress::{ExampleProgress, Step},
  6    retrieve_context::run_context_retrieval,
  7};
  8use anyhow::{Context as _, Result, anyhow};
  9use edit_prediction::{cursor_excerpt::editable_and_context_ranges_for_cursor_position, udiff};
 10use gpui::{AppContext, AsyncApp};
 11use language::{Buffer, OffsetRangeExt, Point};
 12use similar::DiffableStr;
 13use std::sync::Arc;
 14use std::{fmt::Write as _, ops::Range};
 15use zeta_prompt::ZetaVersion;
 16use zeta_prompt::format_zeta_prompt;
 17
 18pub async fn run_format_prompt(
 19    example: &mut Example,
 20    args: &FormatPromptArgs,
 21    app_state: Arc<EpAppState>,
 22    example_progress: &ExampleProgress,
 23    cx: AsyncApp,
 24) -> Result<()> {
 25    run_context_retrieval(example, app_state.clone(), example_progress, cx.clone()).await?;
 26
 27    let step_progress = example_progress.start(Step::FormatPrompt);
 28
 29    let prompt_inputs = example
 30        .prompt_inputs
 31        .as_ref()
 32        .context("prompt_inputs must be set after context retrieval")?;
 33
 34    let language = app_state
 35        .languages
 36        .load_language_for_file_path(&example.spec.cursor_path)
 37        .await
 38        .ok();
 39    let snapshot_fut = cx.update(|cx| {
 40        Buffer::build_snapshot(
 41            prompt_inputs.content.as_str().into(),
 42            language,
 43            Some(app_state.languages.clone()),
 44            cx,
 45        )
 46    });
 47    let cursor_point = Point::new(prompt_inputs.cursor_row, prompt_inputs.cursor_column);
 48    let snapshot = cx.background_spawn(snapshot_fut).await;
 49
 50    match args.provider {
 51        PredictionProvider::Teacher(_) | PredictionProvider::TeacherNonBatching(_) => {
 52            step_progress.set_substatus("formatting teacher prompt");
 53
 54            let (editable_range, context_range) = editable_and_context_ranges_for_cursor_position(
 55                cursor_point,
 56                &snapshot,
 57                edit_prediction::zeta2::max_editable_tokens(ZetaVersion::default()),
 58                edit_prediction::zeta2::MAX_CONTEXT_TOKENS,
 59            );
 60            let editable_range = editable_range.to_offset(&snapshot);
 61            let context_range = context_range.to_offset(&snapshot);
 62
 63            let prompt = TeacherPrompt::format_prompt(example, editable_range, context_range);
 64            example.prompt = Some(ExamplePrompt {
 65                input: prompt,
 66                expected_output: String::new(),
 67                rejected_output: None,
 68                provider: args.provider,
 69            });
 70        }
 71        PredictionProvider::Zeta2(version) => {
 72            step_progress.set_substatus("formatting zeta2 prompt");
 73
 74            let (editable_range, context_range) = editable_and_context_ranges_for_cursor_position(
 75                cursor_point,
 76                &snapshot,
 77                edit_prediction::zeta2::max_editable_tokens(version),
 78                edit_prediction::zeta2::MAX_CONTEXT_TOKENS,
 79            );
 80            let editable_range = editable_range.to_offset(&snapshot);
 81            let context_range = context_range.to_offset(&snapshot);
 82
 83            let context_start = context_range.start;
 84            let cursor_offset_in_excerpt = prompt_inputs.cursor_offset - context_start;
 85            let editable_range_in_excerpt =
 86                (editable_range.start - context_start)..(editable_range.end - context_start);
 87            let input = zeta_prompt::ZetaPromptInput {
 88                cursor_path: example.spec.cursor_path.clone(),
 89                cursor_excerpt: prompt_inputs.content[context_range].to_string().into(),
 90                editable_range_in_excerpt,
 91                cursor_offset_in_excerpt,
 92                excerpt_start_row: prompt_inputs.excerpt_start_row,
 93                events: prompt_inputs.edit_history.clone(),
 94                related_files: prompt_inputs.related_files.clone().unwrap_or_default(),
 95            };
 96            let prompt = format_zeta_prompt(&input, version);
 97            let (expected_patch, expected_cursor_offset) = example
 98                .spec
 99                .expected_patches_with_cursor_positions()
100                .into_iter()
101                .next()
102                .context("expected patches is empty")?;
103            let expected_output =
104                zeta2_output_for_patch(&input, &expected_patch, expected_cursor_offset, version)?;
105            let rejected_output = example
106                .spec
107                .rejected_patch
108                .as_ref()
109                .and_then(|patch| zeta2_output_for_patch(&input, patch, None, version).ok());
110
111            example.prompt = Some(ExamplePrompt {
112                input: prompt,
113                expected_output,
114                rejected_output,
115                provider: args.provider,
116            });
117        }
118        _ => {
119            panic!("Cannot format prompt for {:?}", args.provider);
120        }
121    };
122    Ok(())
123}
124
125pub fn zeta2_output_for_patch(
126    input: &zeta_prompt::ZetaPromptInput,
127    patch: &str,
128    cursor_offset: Option<usize>,
129    version: ZetaVersion,
130) -> Result<String> {
131    let mut old_editable_region =
132        input.cursor_excerpt[input.editable_range_in_excerpt.clone()].to_string();
133
134    if !old_editable_region.ends_with_newline() {
135        old_editable_region.push('\n');
136    }
137
138    let (mut result, first_hunk_offset) =
139        udiff::apply_diff_to_string_with_hunk_offset(patch, &old_editable_region).with_context(
140            || {
141                format!(
142                    "Patch:\n```\n{}```\n\nEditable region:\n```\n{}```",
143                    patch, old_editable_region
144                )
145            },
146        )?;
147
148    if let Some(cursor_offset) = cursor_offset {
149        // The cursor_offset is relative to the start of the hunk's new text (context + additions).
150        // We need to add where the hunk context matched in the editable region to compute
151        // the actual cursor position in the result.
152        let hunk_start = first_hunk_offset.unwrap_or(0);
153        let offset = (hunk_start + cursor_offset).min(result.len());
154        result.insert_str(offset, zeta_prompt::CURSOR_MARKER);
155    }
156
157    match version {
158        ZetaVersion::V0120GitMergeMarkers | ZetaVersion::V0131GitMergeMarkersPrefix => {
159            if !result.ends_with('\n') {
160                result.push('\n');
161            }
162            result.push_str(zeta_prompt::v0120_git_merge_markers::END_MARKER);
163        }
164        _ => (),
165    }
166
167    Ok(result)
168}
169
170pub struct TeacherPrompt;
171
172impl TeacherPrompt {
173    pub(crate) const EDITABLE_REGION_START: &str = "<|editable_region_start|>\n";
174    pub(crate) const EDITABLE_REGION_END: &str = "\n<|editable_region_end|>";
175    pub(crate) const USER_CURSOR_MARKER: &str = "<|user_cursor|>";
176    pub(crate) const NO_EDITS: &str = "NO_EDITS";
177
178    /// Truncate edit history to this number of last lines
179    const MAX_HISTORY_LINES: usize = 128;
180
181    pub fn format_prompt(
182        example: &Example,
183        editable_range: Range<usize>,
184        context_range: Range<usize>,
185    ) -> String {
186        let edit_history = Self::format_edit_history(&example.spec.edit_history);
187        let context = Self::format_context(example);
188        let cursor_excerpt = Self::format_cursor_excerpt(example, editable_range, context_range);
189
190        let prompt_template = crate::prompt_assets::get_prompt("teacher.md");
191        let prompt = prompt_template
192            .replace("{{context}}", &context)
193            .replace("{{edit_history}}", &edit_history)
194            .replace("{{cursor_excerpt}}", &cursor_excerpt);
195
196        prompt
197    }
198
199    pub fn parse(example: &Example, response: &str) -> Result<(String, Option<usize>)> {
200        // Extract updated (new) editable region from the model response.
201        // The model may include editable region markers in its output, so we need to strip them.
202        let new_editable_region = extract_last_codeblock(response);
203
204        // Check if the model indicated no edits are needed
205        if new_editable_region.trim() == Self::NO_EDITS {
206            return Ok((String::new(), None));
207        }
208
209        let new_editable_region = Self::extract_editable_region(&new_editable_region)?;
210        let cursor_offset = new_editable_region.find(Self::USER_CURSOR_MARKER);
211        let mut new_editable_region = new_editable_region.replace(Self::USER_CURSOR_MARKER, "");
212        let old_editable_region = Self::extract_editable_region(
213            &example
214                .prompt
215                .as_ref()
216                .context("example prompt missing")?
217                .input,
218        )?
219        .replace(Self::USER_CURSOR_MARKER, "");
220
221        let prompt_inputs = example
222            .prompt_inputs
223            .as_ref()
224            .context("example is missing prompt inputs")?;
225
226        // Normalize leading newlines: if old starts with newline but new doesn't,
227        // prepend newline to new to preserve whitespace structure.
228        // This handles the case where the model drops the leading blank line.
229        if old_editable_region.starts_with('\n') && !new_editable_region.starts_with('\n') {
230            new_editable_region.insert(0, '\n');
231        }
232
233        let (editable_region_offset, _) = prompt_inputs
234            .content
235            .match_indices(&old_editable_region)
236            .min_by_key(|(index, _)| index.abs_diff(prompt_inputs.cursor_offset))
237            .context("editable region not found in prompt content")?;
238        let editable_region_start_line = prompt_inputs.content[..editable_region_offset]
239            .matches('\n')
240            .count();
241
242        // Use full context so cursor offset (relative to editable region start) aligns with diff content
243        let editable_region_lines = old_editable_region.lines().count() as u32;
244        let diff = language::unified_diff_with_context(
245            &old_editable_region,
246            &new_editable_region,
247            editable_region_start_line as u32,
248            editable_region_start_line as u32,
249            editable_region_lines,
250        );
251
252        let diff = indoc::formatdoc! {"
253            --- a/{path}
254            +++ b/{path}
255            {diff}",
256            path = example.spec.cursor_path.to_string_lossy(),
257            diff = diff,
258        };
259
260        Ok((diff, cursor_offset))
261    }
262
263    fn format_edit_history(edit_history: &str) -> String {
264        // Strip comments ("garbage lines") from edit history
265        let lines = edit_history
266            .lines()
267            .filter(|&s| Self::is_udiff_content_line(s))
268            .collect::<Vec<_>>();
269
270        let history_lines = if lines.len() > Self::MAX_HISTORY_LINES {
271            &lines[lines.len() - Self::MAX_HISTORY_LINES..]
272        } else {
273            &lines
274        };
275
276        if history_lines.is_empty() {
277            return "(No edit history)".to_string();
278        }
279
280        history_lines.join("\n")
281    }
282
283    pub fn format_context(example: &Example) -> String {
284        let related_files = example
285            .prompt_inputs
286            .as_ref()
287            .and_then(|pi| pi.related_files.as_ref());
288
289        let Some(related_files) = related_files else {
290            return "(No context)".to_string();
291        };
292
293        if related_files.is_empty() {
294            return "(No context)".to_string();
295        }
296
297        let mut prompt = String::new();
298        for file in related_files {
299            let path_str = file.path.to_string_lossy();
300            writeln!(&mut prompt, "`````{path_str}").ok();
301
302            let mut prev_row = 0;
303            for excerpt in &file.excerpts {
304                if excerpt.row_range.start > prev_row {
305                    prompt.push_str("\n");
306                }
307                prompt.push_str(&excerpt.text);
308                prompt.push('\n');
309                prev_row = excerpt.row_range.end;
310            }
311            if prev_row < file.max_row {
312                prompt.push_str("\n");
313            }
314            prompt.push_str("\n`````\n");
315        }
316
317        prompt
318    }
319
320    fn format_cursor_excerpt(
321        example: &Example,
322        editable_range: Range<usize>,
323        context_range: Range<usize>,
324    ) -> String {
325        let mut result = String::new();
326
327        let prompt_inputs = example.prompt_inputs.as_ref().unwrap();
328
329        let path_str = example.spec.cursor_path.to_string_lossy();
330        result.push_str(&format!("`````{path_str}\n"));
331        result.push_str(&prompt_inputs.content[context_range.start..editable_range.start]);
332        result.push_str(Self::EDITABLE_REGION_START);
333        result.push_str(&prompt_inputs.content[editable_range.start..prompt_inputs.cursor_offset]);
334        result.push_str(Self::USER_CURSOR_MARKER);
335        result.push_str(&prompt_inputs.content[prompt_inputs.cursor_offset..editable_range.end]);
336        result.push_str(Self::EDITABLE_REGION_END);
337        result.push_str(&prompt_inputs.content[editable_range.end..context_range.end]);
338        result.push_str("\n`````");
339
340        result
341    }
342
343    pub fn extract_editable_region(text: &str) -> Result<String> {
344        let start = text
345            .rfind(Self::EDITABLE_REGION_START)
346            .map_or(0, |pos| pos + Self::EDITABLE_REGION_START.len());
347        let end = text.rfind(Self::EDITABLE_REGION_END).unwrap_or(text.len());
348
349        if start >= end {
350            return Err(anyhow!("Invalid editable region markers"));
351        }
352
353        let region = &text[start..end];
354        Ok(region.strip_suffix('\n').unwrap_or(region).to_string())
355    }
356
357    fn is_udiff_content_line(s: &str) -> bool {
358        s.starts_with("-")
359            || s.starts_with("+")
360            || s.starts_with(" ")
361            || s.starts_with("---")
362            || s.starts_with("+++")
363            || s.starts_with("@@")
364    }
365}
366
367/// Extract the cursor excerpt from an example.
368/// First tries to extract from an existing prompt, then falls back to constructing from prompt_inputs.
369pub fn extract_cursor_excerpt_from_example(example: &Example) -> Option<String> {
370    // If we have the original prompt, extract the cursor excerpt from it
371    if let Some(prompt) = &example.prompt {
372        // Find "# 3. Current File" section and extract the content
373        if let Some(start) = prompt.input.find("# 3. Current File") {
374            let content_start = prompt.input[start..].find('`').map(|i| start + i)?;
375            let backtick_count = prompt.input[content_start..]
376                .chars()
377                .take_while(|&c| c == '`')
378                .count();
379            let content_start = content_start + backtick_count;
380
381            // Find the path line and skip it
382            let newline_pos = prompt.input[content_start..].find('\n')?;
383            let text_start = content_start + newline_pos + 1;
384
385            // Find the closing backticks
386            let closing_pattern = "`".repeat(backtick_count);
387            let text_end = prompt.input[text_start..].find(&closing_pattern)?;
388            let cursor_excerpt = &prompt.input[text_start..text_start + text_end];
389
390            let path_str = example.spec.cursor_path.to_string_lossy();
391            return Some(format!("`````{path_str}\n{cursor_excerpt}`````"));
392        }
393    }
394
395    // Fallback: construct from prompt_inputs if available
396    let prompt_inputs = example.prompt_inputs.as_ref()?;
397    let content = &prompt_inputs.content;
398    let cursor_offset = prompt_inputs.cursor_offset;
399
400    // Simple fallback: just show content around cursor with markers
401    let path_str = example.spec.cursor_path.to_string_lossy();
402    let mut result = format!("`````{path_str}\n");
403    result.push_str(TeacherPrompt::EDITABLE_REGION_START);
404    result.push_str(&content[..cursor_offset]);
405    result.push_str(TeacherPrompt::USER_CURSOR_MARKER);
406    result.push_str(&content[cursor_offset..]);
407    result.push_str(TeacherPrompt::EDITABLE_REGION_END);
408    result.push_str("\n`````");
409
410    Some(result)
411}
412
413fn extract_last_codeblock(text: &str) -> String {
414    let mut last_block = None;
415    let mut search_start = 0;
416
417    while let Some(start) = text[search_start..].find("```") {
418        let start = start + search_start;
419        let bytes = text.as_bytes();
420        let mut backtick_end = start;
421
422        while backtick_end < bytes.len() && bytes[backtick_end] == b'`' {
423            backtick_end += 1;
424        }
425
426        let backtick_count = backtick_end - start;
427        let closing_pattern = format!("\n{}", "`".repeat(backtick_count));
428
429        while backtick_end < bytes.len() && bytes[backtick_end] != b'\n' {
430            backtick_end += 1;
431        }
432
433        if let Some(end_pos) = text[backtick_end..].find(&closing_pattern) {
434            let code_block = &text[backtick_end + 1..backtick_end + end_pos + 1];
435            last_block = Some(code_block.to_string());
436            search_start = backtick_end + end_pos + closing_pattern.len();
437        } else {
438            break;
439        }
440    }
441
442    last_block.unwrap_or_else(|| text.to_string())
443}
444
445#[cfg(test)]
446mod tests {
447    use super::*;
448
449    #[test]
450    fn test_extract_last_code_block() {
451        let text = indoc::indoc! {"
452            Some thinking
453
454            ```
455            first block
456            ```
457
458            `````path='something' lines=1:2
459            last block
460            `````
461            "};
462        let last_block = extract_last_codeblock(text);
463        assert_eq!(last_block, "last block\n");
464    }
465
466    #[test]
467    fn test_extract_codeblock_with_nested_fences() {
468        let text = indoc::indoc! {"
469            `````
470            content with ``` inline
471            and ```python nested
472            more content
473            `````
474            "};
475        let last_block = extract_last_codeblock(text);
476        assert_eq!(
477            last_block,
478            "content with ``` inline\nand ```python nested\nmore content\n"
479        );
480    }
481
482    #[test]
483    fn test_extract_codeblock_ignores_inline_backticks() {
484        let text = indoc::indoc! {"
485            `````
486            here is some `code` with inline backticks
487            and here```more```stuff
488            `````
489            "};
490        let last_block = extract_last_codeblock(text);
491        assert_eq!(
492            last_block,
493            "here is some `code` with inline backticks\nand here```more```stuff\n"
494        );
495    }
496
497    #[test]
498    fn test_extract_editable_region() {
499        let text = indoc::indoc! {"
500            some lines
501            are
502            here
503            <|editable_region_start|>
504            one
505            two three
506
507            <|editable_region_end|>
508            more
509            lines here
510            "};
511        let parsed = TeacherPrompt::extract_editable_region(text).unwrap();
512        assert_eq!(
513            parsed,
514            indoc::indoc! {"
515            one
516            two three"}
517        );
518    }
519
520    #[test]
521    fn test_extract_last_codeblock_nested_bibtex() {
522        let text = indoc::indoc! {r#"
523            Looking at the edit history, I can see that a Citation section was just added.
524
525            `````
526            ## Collaborations
527            Our mission is to create a 4D generative model.
528
529            ## Citation
530
531            If you found Unique3D helpful, please cite our report:
532            ```bibtex
533            @misc{wu2024unique3d,
534                  title={Unique3D},
535            }
536            ```
537            `````
538            "#};
539        let last_block = extract_last_codeblock(text);
540        assert_eq!(
541            last_block,
542            indoc::indoc! {r#"
543            ## Collaborations
544            Our mission is to create a 4D generative model.
545
546            ## Citation
547
548            If you found Unique3D helpful, please cite our report:
549            ```bibtex
550            @misc{wu2024unique3d,
551                  title={Unique3D},
552            }
553            ```
554            "#}
555        );
556    }
557
558    #[test]
559    fn test_extract_editable_region_no_markers() {
560        let text = indoc::indoc! {"
561            one
562            two three"};
563        let parsed = TeacherPrompt::extract_editable_region(text).unwrap();
564        assert_eq!(
565            parsed,
566            indoc::indoc! {"
567            one
568            two three"}
569        );
570    }
571
572    #[test]
573    fn test_parse_no_edits_response() {
574        let response = indoc::indoc! {"
575            The code is already complete. There is no clear next edit to make.
576
577            `````
578            NO_EDITS
579            `````
580        "};
581        let codeblock = extract_last_codeblock(response);
582        assert_eq!(codeblock.trim(), TeacherPrompt::NO_EDITS);
583    }
584}