example.rs

  1use crate::PredictionProvider;
  2use crate::paths::WORKTREES_DIR;
  3use crate::qa::QaResult;
  4use anyhow::{Context as _, Result};
  5use collections::HashMap;
  6use edit_prediction::example_spec::ExampleSpec;
  7use edit_prediction::udiff::OpenedBuffers;
  8use gpui::Entity;
  9use http_client::Url;
 10use language::{Anchor, Buffer};
 11use project::Project;
 12use serde::{Deserialize, Serialize};
 13use std::{
 14    borrow::Cow,
 15    collections::VecDeque,
 16    io::Read,
 17    path::{Path, PathBuf},
 18    sync::Arc,
 19};
 20use zeta_prompt::RelatedFile;
 21
 22#[derive(Clone, Debug, Serialize, Deserialize)]
 23pub struct Example {
 24    #[serde(flatten)]
 25    pub spec: ExampleSpec,
 26
 27    /// The full content of the file where an edit is being predicted, and the
 28    /// actual cursor offset.
 29    #[serde(skip_serializing_if = "Option::is_none")]
 30    pub prompt_inputs: Option<ExamplePromptInputs>,
 31
 32    /// The input and expected output from the edit prediction model.
 33    #[serde(skip_serializing_if = "Option::is_none")]
 34    pub prompt: Option<ExamplePrompt>,
 35
 36    /// The actual predictions from the model.
 37    #[serde(default, skip_serializing_if = "Vec::is_empty")]
 38    pub predictions: Vec<ExamplePrediction>,
 39
 40    /// The scores, for how well the actual predictions match the expected
 41    /// predictions.
 42    #[serde(default, skip_serializing_if = "Vec::is_empty")]
 43    pub score: Vec<ExampleScore>,
 44
 45    /// QA evaluation results for each prediction (indexed parallel to `predictions`).
 46    #[serde(default, skip_serializing_if = "Vec::is_empty")]
 47    pub qa: Vec<Option<QaResult>>,
 48
 49    /// The application state used to process this example.
 50    #[serde(skip)]
 51    pub state: Option<ExampleState>,
 52}
 53
 54#[derive(Clone, Debug)]
 55pub struct ExampleState {
 56    pub project: Entity<Project>,
 57    pub buffer: Entity<Buffer>,
 58    pub cursor_position: Anchor,
 59    pub _open_buffers: OpenedBuffers,
 60}
 61
 62#[derive(Clone, Debug, Serialize, Deserialize)]
 63pub struct ExamplePromptInputs {
 64    pub content: String,
 65    pub cursor_row: u32,
 66    pub cursor_column: u32,
 67    pub cursor_offset: usize,
 68    pub edit_history: Vec<Arc<zeta_prompt::Event>>,
 69    pub related_files: Option<Vec<RelatedFile>>,
 70}
 71
 72#[derive(Clone, Debug, Serialize, Deserialize)]
 73pub struct ExamplePrompt {
 74    pub input: String,
 75    pub expected_output: String,
 76    pub provider: PredictionProvider,
 77}
 78
 79#[derive(Clone, Debug, Serialize, Deserialize)]
 80pub struct ExamplePrediction {
 81    #[serde(default, skip_serializing_if = "Option::is_none")]
 82    pub actual_patch: Option<String>,
 83    #[serde(deserialize_with = "deserialize_null_as_empty_string")]
 84    pub actual_output: String,
 85    #[serde(default, skip_serializing_if = "Option::is_none")]
 86    pub error: Option<String>,
 87    pub provider: PredictionProvider,
 88}
 89
 90fn deserialize_null_as_empty_string<'de, D>(deserializer: D) -> Result<String, D::Error>
 91where
 92    D: serde::Deserializer<'de>,
 93{
 94    let opt = Option::<String>::deserialize(deserializer)?;
 95    Ok(opt.unwrap_or_default())
 96}
 97
 98#[derive(Clone, Debug, Serialize, Deserialize)]
 99pub struct ExampleScore {
100    pub delta_chr_f: f32,
101    pub braces_disbalance: usize,
102    #[serde(default)]
103    pub exact_lines_tp: usize,
104    #[serde(default)]
105    pub exact_lines_fp: usize,
106    #[serde(default)]
107    pub exact_lines_fn: usize,
108}
109
110impl Example {
111    pub fn repo_name(&self) -> Result<RepoName<'_>> {
112        // git@github.com:owner/repo.git
113        if self.spec.repository_url.contains('@') {
114            let (owner, repo) = self
115                .spec
116                .repository_url
117                .split_once(':')
118                .context("expected : in git url")?
119                .1
120                .split_once('/')
121                .context("expected / in git url")?;
122            Ok(RepoName {
123                owner: Cow::Borrowed(owner),
124                name: Cow::Borrowed(repo.trim_end_matches(".git")),
125            })
126        // http://github.com/owner/repo.git
127        } else {
128            let url = Url::parse(&self.spec.repository_url)?;
129            let mut segments = url.path_segments().context("empty http url")?;
130            let owner = segments
131                .next()
132                .context("expected owner path segment")?
133                .to_string();
134            let repo = segments
135                .next()
136                .context("expected repo path segment")?
137                .trim_end_matches(".git")
138                .to_string();
139            assert!(segments.next().is_none());
140
141            Ok(RepoName {
142                owner: Cow::Owned(owner),
143                name: Cow::Owned(repo),
144            })
145        }
146    }
147}
148
149pub struct RepoName<'a> {
150    pub owner: Cow<'a, str>,
151    pub name: Cow<'a, str>,
152}
153
154impl RepoName<'_> {
155    pub fn worktree_path(&self) -> PathBuf {
156        WORKTREES_DIR
157            .join(self.owner.as_ref())
158            .join(self.name.as_ref())
159    }
160}
161
162pub fn read_example_files(inputs: &[PathBuf]) -> Vec<Example> {
163    let mut examples = Vec::new();
164
165    for path in inputs {
166        let is_stdin = path.as_path() == Path::new("-");
167        let content = if is_stdin {
168            let mut buffer = String::new();
169            std::io::stdin()
170                .read_to_string(&mut buffer)
171                .expect("Failed to read from stdin");
172            buffer
173        } else {
174            std::fs::read_to_string(path)
175                .unwrap_or_else(|_| panic!("Failed to read path: {:?}", &path))
176        };
177        let filename = path.file_stem().unwrap().to_string_lossy().to_string();
178        let ext = if !is_stdin {
179            path.extension()
180                .map(|ext| ext.to_string_lossy().to_string())
181                .unwrap_or_else(|| panic!("{} should have an extension", path.display()))
182        } else {
183            "jsonl".to_string()
184        };
185
186        match ext.as_ref() {
187            "json" => {
188                let mut example =
189                    serde_json::from_str::<Example>(&content).unwrap_or_else(|error| {
190                        panic!("Failed to parse example file: {}\n{error}", path.display())
191                    });
192                if example.spec.name.is_empty() {
193                    example.spec.name = filename;
194                }
195                examples.push(example);
196            }
197            "jsonl" => examples.extend(
198                content
199                    .lines()
200                    .enumerate()
201                    .map(|(line_ix, line)| {
202                        let mut example =
203                            serde_json::from_str::<Example>(line).unwrap_or_else(|error| {
204                                panic!(
205                                    "Failed to parse example on {}:{}\n{error}",
206                                    path.display(),
207                                    line_ix + 1
208                                )
209                            });
210                        if example.spec.name.is_empty() {
211                            example.spec.name = format!("{filename}-{line_ix}")
212                        }
213                        example
214                    })
215                    .collect::<Vec<Example>>(),
216            ),
217            "md" => {
218                let mut example = parse_markdown_example(&content).unwrap();
219                if example.spec.name.is_empty() {
220                    example.spec.name = filename;
221                }
222                examples.push(example);
223            }
224            ext => {
225                panic!("{} has invalid example extension `{ext}`", path.display())
226            }
227        }
228    }
229
230    examples
231}
232
233pub fn sort_examples_by_repo_and_rev(examples: &mut [Example]) {
234    examples.sort_by(|a, b| {
235        a.spec
236            .repository_url
237            .cmp(&b.spec.repository_url)
238            .then(b.spec.revision.cmp(&a.spec.revision))
239    });
240}
241
242pub fn group_examples_by_repo(examples: Vec<Example>) -> VecDeque<Vec<Example>> {
243    let mut examples_by_repo = HashMap::default();
244    for example in examples {
245        examples_by_repo
246            .entry(example.spec.repository_url.clone())
247            .or_insert_with(Vec::new)
248            .push(example);
249    }
250    examples_by_repo.into_values().collect()
251}
252
253fn parse_markdown_example(input: &str) -> Result<Example> {
254    let spec = ExampleSpec::from_markdown(input)?;
255    Ok(Example {
256        spec,
257        prompt_inputs: None,
258        prompt: None,
259        predictions: Vec::new(),
260        score: Vec::new(),
261        qa: Vec::new(),
262        state: None,
263    })
264}