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