format_prompt.rs

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