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 actual_cursor: Option<ActualCursor>,
90 #[serde(default, skip_serializing_if = "Option::is_none")]
91 pub error: Option<String>,
92 pub provider: PredictionProvider,
93}
94
95#[derive(Clone, Debug, Serialize, Deserialize)]
96pub struct ActualCursor {
97 pub path: String,
98 pub row: u32,
99 pub column: u32,
100 pub offset: usize,
101 #[serde(default, skip_serializing_if = "Option::is_none")]
102 pub editable_region_offset: Option<usize>,
103}
104
105impl ActualCursor {
106 /// Construct an `ActualCursor` from a cursor offset within the new editable region.
107 ///
108 /// - `path`: file path the cursor is in
109 /// - `editable_region_cursor_offset`: byte offset of the cursor within the new editable region text
110 /// - `new_editable_region`: the full new editable region text (after marker removal)
111 /// - `content`: the full file content (before the edit)
112 /// - `editable_region_byte_offset`: byte offset where the editable region starts in `content`
113 /// - `editable_region_start_line`: 0-based line number where the editable region starts in `content`
114 pub fn from_editable_region(
115 path: &std::path::Path,
116 editable_region_cursor_offset: usize,
117 new_editable_region: &str,
118 content: &str,
119 editable_region_byte_offset: usize,
120 editable_region_start_line: usize,
121 ) -> Self {
122 let global_offset = editable_region_byte_offset + editable_region_cursor_offset;
123 let new_region_prefix = &new_editable_region[..editable_region_cursor_offset];
124 let row = (editable_region_start_line + new_region_prefix.matches('\n').count()) as u32;
125 let column = match new_region_prefix.rfind('\n') {
126 Some(pos) => (editable_region_cursor_offset - pos - 1) as u32,
127 None => {
128 let content_prefix = &content[..editable_region_byte_offset];
129 let content_column = match content_prefix.rfind('\n') {
130 Some(pos) => editable_region_byte_offset - pos - 1,
131 None => editable_region_byte_offset,
132 };
133 (content_column + editable_region_cursor_offset) as u32
134 }
135 };
136 ActualCursor {
137 path: path.to_string_lossy().to_string(),
138 row,
139 column,
140 offset: global_offset,
141 editable_region_offset: Some(editable_region_cursor_offset),
142 }
143 }
144}
145
146fn deserialize_null_as_empty_string<'de, D>(deserializer: D) -> Result<String, D::Error>
147where
148 D: serde::Deserializer<'de>,
149{
150 let opt = Option::<String>::deserialize(deserializer)?;
151 Ok(opt.unwrap_or_default())
152}
153
154#[derive(Clone, Debug, Serialize, Deserialize)]
155pub struct ExampleScore {
156 pub delta_chr_f: f32,
157 pub braces_disbalance: usize,
158 #[serde(default)]
159 pub exact_lines_tp: usize,
160 #[serde(default)]
161 pub exact_lines_fp: usize,
162 #[serde(default)]
163 pub exact_lines_fn: usize,
164 #[serde(default)]
165 pub reversal_ratio: f32,
166 #[serde(default, skip_serializing_if = "Option::is_none")]
167 pub cursor_distance: Option<usize>,
168 #[serde(default, skip_serializing_if = "Option::is_none")]
169 pub cursor_exact_match: Option<bool>,
170 pub wrong_editable_region: Option<bool>,
171 #[serde(default)]
172 pub has_isolated_whitespace_changes: bool,
173}
174
175impl Example {
176 pub fn repo_name(&self) -> Result<RepoName<'_>> {
177 // git@github.com:owner/repo.git
178 if self.spec.repository_url.contains('@') {
179 let (owner, repo) = self
180 .spec
181 .repository_url
182 .split_once(':')
183 .context("expected : in git url")?
184 .1
185 .split_once('/')
186 .context("expected / in git url")?;
187 Ok(RepoName {
188 owner: Cow::Borrowed(owner),
189 name: Cow::Borrowed(repo.trim_end_matches(".git")),
190 })
191 // http://github.com/owner/repo.git
192 } else {
193 let url = Url::parse(&self.spec.repository_url)?;
194 let mut segments = url.path_segments().context("empty http url")?;
195 let owner = segments
196 .next()
197 .context("expected owner path segment")?
198 .to_string();
199 let repo = segments
200 .next()
201 .context("expected repo path segment")?
202 .trim_end_matches(".git")
203 .to_string();
204 assert!(segments.next().is_none());
205
206 Ok(RepoName {
207 owner: Cow::Owned(owner),
208 name: Cow::Owned(repo),
209 })
210 }
211 }
212}
213
214pub struct RepoName<'a> {
215 pub owner: Cow<'a, str>,
216 pub name: Cow<'a, str>,
217}
218
219impl RepoName<'_> {
220 pub fn worktree_path(&self) -> PathBuf {
221 WORKTREES_DIR
222 .join(self.owner.as_ref())
223 .join(self.name.as_ref())
224 }
225}
226
227pub fn read_example_files(inputs: &[PathBuf]) -> Vec<Example> {
228 let mut examples = Vec::new();
229
230 for path in inputs {
231 let is_stdin = path.as_path() == Path::new("-");
232 let content = if is_stdin {
233 let mut buffer = String::new();
234 std::io::stdin()
235 .read_to_string(&mut buffer)
236 .expect("Failed to read from stdin");
237 buffer
238 } else {
239 std::fs::read_to_string(path)
240 .unwrap_or_else(|_| panic!("Failed to read path: {:?}", &path))
241 };
242 let filename = path.file_stem().unwrap().to_string_lossy().to_string();
243 let ext = if !is_stdin {
244 path.extension()
245 .map(|ext| ext.to_string_lossy().to_string())
246 .unwrap_or_else(|| panic!("{} should have an extension", path.display()))
247 } else {
248 "jsonl".to_string()
249 };
250
251 match ext.as_ref() {
252 "json" => {
253 let mut example =
254 serde_json::from_str::<Example>(&content).unwrap_or_else(|error| {
255 panic!("Failed to parse example file: {}\n{error}", path.display())
256 });
257 if example.spec.name.is_empty() {
258 example.spec.name = filename;
259 }
260 examples.push(example);
261 }
262 "jsonl" => examples.extend(
263 content
264 .lines()
265 .enumerate()
266 .map(|(line_ix, line)| {
267 let mut example =
268 serde_json::from_str::<Example>(line).unwrap_or_else(|error| {
269 panic!(
270 "Failed to parse example on {}:{}\n{error}",
271 path.display(),
272 line_ix + 1
273 )
274 });
275 if example.spec.name.is_empty() {
276 example.spec.name = format!("{filename}-{line_ix}")
277 }
278 example
279 })
280 .collect::<Vec<Example>>(),
281 ),
282 "md" => {
283 let mut example = parse_markdown_example(&content).unwrap();
284 if example.spec.name.is_empty() {
285 example.spec.name = filename;
286 }
287 examples.push(example);
288 }
289 ext => {
290 panic!("{} has invalid example extension `{ext}`", path.display())
291 }
292 }
293 }
294
295 examples
296}
297
298pub fn sort_examples_by_repo_and_rev(examples: &mut [Example]) {
299 examples.sort_by(|a, b| {
300 a.spec
301 .repository_url
302 .cmp(&b.spec.repository_url)
303 .then(b.spec.revision.cmp(&a.spec.revision))
304 });
305}
306
307pub fn group_examples_by_repo(examples: Vec<Example>) -> VecDeque<Vec<Example>> {
308 let mut examples_by_repo: HashMap<String, Vec<Example>> = HashMap::default();
309 let mut ungrouped = Vec::new();
310 for example in examples {
311 if example.spec.repository_url.is_empty() {
312 ungrouped.push(example);
313 } else {
314 examples_by_repo
315 .entry(example.spec.repository_url.clone())
316 .or_insert_with(Vec::new)
317 .push(example);
318 }
319 }
320 let mut result: VecDeque<Vec<Example>> = examples_by_repo.into_values().collect();
321 for example in ungrouped {
322 result.push_back(vec![example]);
323 }
324 result
325}
326
327fn parse_markdown_example(input: &str) -> Result<Example> {
328 let spec = ExampleSpec::from_markdown(input)?;
329 Ok(Example {
330 spec,
331 prompt_inputs: None,
332 prompt: None,
333 predictions: Vec::new(),
334 score: Vec::new(),
335 qa: Vec::new(),
336 state: None,
337 })
338}