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    #[serde(default, skip_serializing_if = "Option::is_none")]
 69    pub excerpt_start_row: Option<u32>,
 70    pub edit_history: Vec<Arc<zeta_prompt::Event>>,
 71    pub related_files: Option<Vec<RelatedFile>>,
 72}
 73
 74#[derive(Clone, Debug, Serialize, Deserialize)]
 75pub struct ExamplePrompt {
 76    pub input: String,
 77    pub expected_output: String,
 78    pub rejected_output: Option<String>, // For DPO
 79    pub provider: PredictionProvider,
 80}
 81
 82#[derive(Clone, Debug, Serialize, Deserialize)]
 83pub struct ExamplePrediction {
 84    #[serde(default, skip_serializing_if = "Option::is_none")]
 85    pub actual_patch: Option<String>,
 86    #[serde(deserialize_with = "deserialize_null_as_empty_string")]
 87    pub actual_output: String,
 88    #[serde(default, skip_serializing_if = "Option::is_none")]
 89    pub error: Option<String>,
 90    pub provider: PredictionProvider,
 91}
 92
 93fn deserialize_null_as_empty_string<'de, D>(deserializer: D) -> Result<String, D::Error>
 94where
 95    D: serde::Deserializer<'de>,
 96{
 97    let opt = Option::<String>::deserialize(deserializer)?;
 98    Ok(opt.unwrap_or_default())
 99}
100
101#[derive(Clone, Debug, Serialize, Deserialize)]
102pub struct ExampleScore {
103    pub delta_chr_f: f32,
104    pub braces_disbalance: usize,
105    #[serde(default)]
106    pub exact_lines_tp: usize,
107    #[serde(default)]
108    pub exact_lines_fp: usize,
109    #[serde(default)]
110    pub exact_lines_fn: usize,
111    #[serde(default)]
112    pub reversal_ratio: f32,
113}
114
115impl Example {
116    pub fn repo_name(&self) -> Result<RepoName<'_>> {
117        // git@github.com:owner/repo.git
118        if self.spec.repository_url.contains('@') {
119            let (owner, repo) = self
120                .spec
121                .repository_url
122                .split_once(':')
123                .context("expected : in git url")?
124                .1
125                .split_once('/')
126                .context("expected / in git url")?;
127            Ok(RepoName {
128                owner: Cow::Borrowed(owner),
129                name: Cow::Borrowed(repo.trim_end_matches(".git")),
130            })
131        // http://github.com/owner/repo.git
132        } else {
133            let url = Url::parse(&self.spec.repository_url)?;
134            let mut segments = url.path_segments().context("empty http url")?;
135            let owner = segments
136                .next()
137                .context("expected owner path segment")?
138                .to_string();
139            let repo = segments
140                .next()
141                .context("expected repo path segment")?
142                .trim_end_matches(".git")
143                .to_string();
144            assert!(segments.next().is_none());
145
146            Ok(RepoName {
147                owner: Cow::Owned(owner),
148                name: Cow::Owned(repo),
149            })
150        }
151    }
152}
153
154pub struct RepoName<'a> {
155    pub owner: Cow<'a, str>,
156    pub name: Cow<'a, str>,
157}
158
159impl RepoName<'_> {
160    pub fn worktree_path(&self) -> PathBuf {
161        WORKTREES_DIR
162            .join(self.owner.as_ref())
163            .join(self.name.as_ref())
164    }
165}
166
167pub fn read_example_files(inputs: &[PathBuf]) -> Vec<Example> {
168    let mut examples = Vec::new();
169
170    for path in inputs {
171        let is_stdin = path.as_path() == Path::new("-");
172        let content = if is_stdin {
173            let mut buffer = String::new();
174            std::io::stdin()
175                .read_to_string(&mut buffer)
176                .expect("Failed to read from stdin");
177            buffer
178        } else {
179            std::fs::read_to_string(path)
180                .unwrap_or_else(|_| panic!("Failed to read path: {:?}", &path))
181        };
182        let filename = path.file_stem().unwrap().to_string_lossy().to_string();
183        let ext = if !is_stdin {
184            path.extension()
185                .map(|ext| ext.to_string_lossy().to_string())
186                .unwrap_or_else(|| panic!("{} should have an extension", path.display()))
187        } else {
188            "jsonl".to_string()
189        };
190
191        match ext.as_ref() {
192            "json" => {
193                let mut example =
194                    serde_json::from_str::<Example>(&content).unwrap_or_else(|error| {
195                        panic!("Failed to parse example file: {}\n{error}", path.display())
196                    });
197                if example.spec.name.is_empty() {
198                    example.spec.name = filename;
199                }
200                examples.push(example);
201            }
202            "jsonl" => examples.extend(
203                content
204                    .lines()
205                    .enumerate()
206                    .map(|(line_ix, line)| {
207                        let mut example =
208                            serde_json::from_str::<Example>(line).unwrap_or_else(|error| {
209                                panic!(
210                                    "Failed to parse example on {}:{}\n{error}",
211                                    path.display(),
212                                    line_ix + 1
213                                )
214                            });
215                        if example.spec.name.is_empty() {
216                            example.spec.name = format!("{filename}-{line_ix}")
217                        }
218                        example
219                    })
220                    .collect::<Vec<Example>>(),
221            ),
222            "md" => {
223                let mut example = parse_markdown_example(&content).unwrap();
224                if example.spec.name.is_empty() {
225                    example.spec.name = filename;
226                }
227                examples.push(example);
228            }
229            ext => {
230                panic!("{} has invalid example extension `{ext}`", path.display())
231            }
232        }
233    }
234
235    examples
236}
237
238pub fn sort_examples_by_repo_and_rev(examples: &mut [Example]) {
239    examples.sort_by(|a, b| {
240        a.spec
241            .repository_url
242            .cmp(&b.spec.repository_url)
243            .then(b.spec.revision.cmp(&a.spec.revision))
244    });
245}
246
247pub fn group_examples_by_repo(examples: Vec<Example>) -> VecDeque<Vec<Example>> {
248    let mut examples_by_repo: HashMap<String, Vec<Example>> = HashMap::default();
249    let mut ungrouped = Vec::new();
250    for example in examples {
251        if example.spec.repository_url.is_empty() {
252            ungrouped.push(example);
253        } else {
254            examples_by_repo
255                .entry(example.spec.repository_url.clone())
256                .or_insert_with(Vec::new)
257                .push(example);
258        }
259    }
260    let mut result: VecDeque<Vec<Example>> = examples_by_repo.into_values().collect();
261    for example in ungrouped {
262        result.push_back(vec![example]);
263    }
264    result
265}
266
267fn parse_markdown_example(input: &str) -> Result<Example> {
268    let spec = ExampleSpec::from_markdown(input)?;
269    Ok(Example {
270        spec,
271        prompt_inputs: None,
272        prompt: None,
273        predictions: Vec::new(),
274        score: Vec::new(),
275        qa: Vec::new(),
276        state: None,
277    })
278}