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};
19use zeta_prompt::ZetaPromptInput;
20
21#[derive(Clone, Debug, Serialize, Deserialize)]
22pub struct Example {
23 #[serde(flatten)]
24 pub spec: ExampleSpec,
25
26 /// The full content of the file where an edit is being predicted, and the
27 /// actual cursor offset.
28 #[serde(skip_serializing_if = "Option::is_none")]
29 pub prompt_inputs: Option<ZetaPromptInput>,
30
31 /// The input and expected output from the edit prediction model.
32 #[serde(skip_serializing_if = "Option::is_none")]
33 pub prompt: Option<ExamplePrompt>,
34
35 /// The actual predictions from the model.
36 #[serde(default, skip_serializing_if = "Vec::is_empty")]
37 pub predictions: Vec<ExamplePrediction>,
38
39 /// The scores, for how well the actual predictions match the expected
40 /// predictions.
41 #[serde(default, skip_serializing_if = "Vec::is_empty")]
42 pub score: Vec<ExampleScore>,
43
44 /// QA evaluation results for each prediction (indexed parallel to `predictions`).
45 #[serde(default, skip_serializing_if = "Vec::is_empty")]
46 pub qa: Vec<Option<QaResult>>,
47
48 /// The Zed version used to generate this example.
49 pub zed_version: Option<String>,
50
51 /// The application state used to process this example.
52 #[serde(skip)]
53 pub state: Option<ExampleState>,
54}
55
56#[derive(Clone, Debug)]
57pub struct ExampleState {
58 pub project: Entity<Project>,
59 pub buffer: Entity<Buffer>,
60 pub cursor_position: Anchor,
61 pub _open_buffers: OpenedBuffers,
62}
63
64#[derive(Clone, Debug, Serialize, Deserialize)]
65pub struct ExamplePrompt {
66 pub input: String,
67 pub expected_output: String,
68 pub rejected_output: Option<String>, // For DPO
69 #[serde(default)]
70 pub prefill: Option<String>,
71 pub provider: PredictionProvider,
72}
73
74#[derive(Clone, Debug, Serialize, Deserialize)]
75pub struct ExamplePrediction {
76 #[serde(default, skip_serializing_if = "Option::is_none")]
77 pub actual_patch: Option<String>,
78 #[serde(deserialize_with = "deserialize_null_as_empty_string")]
79 pub actual_output: String,
80 #[serde(default, skip_serializing_if = "Option::is_none")]
81 pub actual_cursor: Option<ActualCursor>,
82 #[serde(default, skip_serializing_if = "Option::is_none")]
83 pub error: Option<String>,
84 pub provider: PredictionProvider,
85}
86
87#[derive(Clone, Debug, Serialize, Deserialize)]
88pub struct ActualCursor {
89 pub path: String,
90 pub row: u32,
91 pub column: u32,
92 pub offset: usize,
93 #[serde(default, skip_serializing_if = "Option::is_none")]
94 pub editable_region_offset: Option<usize>,
95}
96
97impl ActualCursor {
98 /// Construct an `ActualCursor` from a cursor offset within the new editable region.
99 ///
100 /// - `path`: file path the cursor is in
101 /// - `editable_region_cursor_offset`: byte offset of the cursor within the new editable region text
102 /// - `new_editable_region`: the full new editable region text (after marker removal)
103 /// - `content`: the full file content (before the edit)
104 /// - `editable_region_byte_offset`: byte offset where the editable region starts in `content`
105 /// - `editable_region_start_line`: 0-based line number where the editable region starts in `content`
106 pub fn from_editable_region(
107 path: &std::path::Path,
108 editable_region_cursor_offset: usize,
109 new_editable_region: &str,
110 content: &str,
111 editable_region_byte_offset: usize,
112 editable_region_start_line: usize,
113 ) -> Self {
114 let global_offset = editable_region_byte_offset + editable_region_cursor_offset;
115 let new_region_prefix = &new_editable_region[..editable_region_cursor_offset];
116 let row = (editable_region_start_line + new_region_prefix.matches('\n').count()) as u32;
117 let column = match new_region_prefix.rfind('\n') {
118 Some(pos) => (editable_region_cursor_offset - pos - 1) as u32,
119 None => {
120 let content_prefix = &content[..editable_region_byte_offset];
121 let content_column = match content_prefix.rfind('\n') {
122 Some(pos) => editable_region_byte_offset - pos - 1,
123 None => editable_region_byte_offset,
124 };
125 (content_column + editable_region_cursor_offset) as u32
126 }
127 };
128 ActualCursor {
129 path: path.to_string_lossy().to_string(),
130 row,
131 column,
132 offset: global_offset,
133 editable_region_offset: Some(editable_region_cursor_offset),
134 }
135 }
136}
137
138fn deserialize_null_as_empty_string<'de, D>(deserializer: D) -> Result<String, D::Error>
139where
140 D: serde::Deserializer<'de>,
141{
142 let opt = Option::<String>::deserialize(deserializer)?;
143 Ok(opt.unwrap_or_default())
144}
145
146#[derive(Clone, Debug, Serialize, Deserialize)]
147pub struct ExampleScore {
148 pub delta_chr_f: f32,
149 pub braces_disbalance: usize,
150 #[serde(default)]
151 pub exact_lines_tp: usize,
152 #[serde(default)]
153 pub exact_lines_fp: usize,
154 #[serde(default)]
155 pub exact_lines_fn: usize,
156 #[serde(default)]
157 pub reversal_ratio: f32,
158 #[serde(default, skip_serializing_if = "Option::is_none")]
159 pub cursor_distance: Option<usize>,
160 #[serde(default, skip_serializing_if = "Option::is_none")]
161 pub cursor_exact_match: Option<bool>,
162 pub wrong_editable_region: Option<bool>,
163 #[serde(default)]
164 pub has_isolated_whitespace_changes: bool,
165 #[serde(default)]
166 pub inserted_tokens: usize,
167 #[serde(default)]
168 pub deleted_tokens: usize,
169}
170
171impl Example {
172 pub fn repo_name(&self) -> Result<RepoName<'_>> {
173 // git@github.com:owner/repo.git
174 if self.spec.repository_url.contains('@') {
175 let (owner, repo) = self
176 .spec
177 .repository_url
178 .split_once(':')
179 .context("expected : in git url")?
180 .1
181 .split_once('/')
182 .context("expected / in git url")?;
183 Ok(RepoName {
184 owner: Cow::Borrowed(owner),
185 name: Cow::Borrowed(repo.trim_end_matches(".git")),
186 })
187 // http://github.com/owner/repo.git
188 } else {
189 let url = Url::parse(&self.spec.repository_url)?;
190 let mut segments = url.path_segments().context("empty http url")?;
191 let owner = segments
192 .next()
193 .context("expected owner path segment")?
194 .to_string();
195 let repo = segments
196 .next()
197 .context("expected repo path segment")?
198 .trim_end_matches(".git")
199 .to_string();
200 assert!(segments.next().is_none());
201
202 Ok(RepoName {
203 owner: Cow::Owned(owner),
204 name: Cow::Owned(repo),
205 })
206 }
207 }
208}
209
210pub struct RepoName<'a> {
211 pub owner: Cow<'a, str>,
212 pub name: Cow<'a, str>,
213}
214
215impl RepoName<'_> {
216 pub fn worktree_path(&self) -> PathBuf {
217 WORKTREES_DIR
218 .join(self.owner.as_ref())
219 .join(self.name.as_ref())
220 }
221}
222
223pub fn read_example_files(inputs: &[PathBuf]) -> Vec<Example> {
224 let mut examples = Vec::new();
225
226 for path in inputs {
227 let is_stdin = path.as_path() == Path::new("-");
228 let content = if is_stdin {
229 let mut buffer = String::new();
230 std::io::stdin()
231 .read_to_string(&mut buffer)
232 .expect("Failed to read from stdin");
233 buffer
234 } else {
235 std::fs::read_to_string(path)
236 .unwrap_or_else(|_| panic!("Failed to read path: {:?}", &path))
237 };
238 let filename = path.file_stem().unwrap().to_string_lossy().to_string();
239 let ext = if !is_stdin {
240 path.extension()
241 .map(|ext| ext.to_string_lossy().to_string())
242 .unwrap_or_else(|| panic!("{} should have an extension", path.display()))
243 } else {
244 "jsonl".to_string()
245 };
246
247 match ext.as_ref() {
248 "json" => {
249 let mut example =
250 serde_json::from_str::<Example>(&content).unwrap_or_else(|error| {
251 panic!("Failed to parse example file: {}\n{error}", path.display())
252 });
253 if example.spec.name.is_empty() {
254 example.spec.name = filename;
255 }
256 examples.push(example);
257 }
258 "jsonl" => examples.extend(
259 content
260 .lines()
261 .enumerate()
262 .map(|(line_ix, line)| {
263 let mut example =
264 serde_json::from_str::<Example>(line).unwrap_or_else(|error| {
265 panic!(
266 "Failed to parse example on {}:{}\n{error}",
267 path.display(),
268 line_ix + 1
269 )
270 });
271 if example.spec.name.is_empty() {
272 example.spec.name = format!("{filename}-{line_ix}")
273 }
274 example
275 })
276 .collect::<Vec<Example>>(),
277 ),
278 "md" => {
279 let mut example = parse_markdown_example(&content).unwrap();
280 if example.spec.name.is_empty() {
281 example.spec.name = filename;
282 }
283 examples.push(example);
284 }
285 ext => {
286 panic!("{} has invalid example extension `{ext}`", path.display())
287 }
288 }
289 }
290
291 examples
292}
293
294pub fn sort_examples_by_repo_and_rev(examples: &mut [Example]) {
295 examples.sort_by(|a, b| {
296 a.spec
297 .repository_url
298 .cmp(&b.spec.repository_url)
299 .then(b.spec.revision.cmp(&a.spec.revision))
300 });
301}
302
303pub fn group_examples_by_repo(examples: Vec<Example>) -> VecDeque<Vec<Example>> {
304 let mut examples_by_repo: HashMap<String, Vec<Example>> = HashMap::default();
305 let mut ungrouped = Vec::new();
306 for example in examples {
307 if example.spec.repository_url.is_empty() {
308 ungrouped.push(example);
309 } else {
310 examples_by_repo
311 .entry(example.spec.repository_url.clone())
312 .or_insert_with(Vec::new)
313 .push(example);
314 }
315 }
316 let mut result: VecDeque<Vec<Example>> = examples_by_repo.into_values().collect();
317 for example in ungrouped {
318 result.push_back(vec![example]);
319 }
320 result
321}
322
323fn parse_markdown_example(input: &str) -> Result<Example> {
324 let spec = ExampleSpec::from_markdown(input)?;
325 Ok(Example {
326 spec,
327 prompt_inputs: None,
328 prompt: None,
329 predictions: Vec::new(),
330 score: Vec::new(),
331 qa: Vec::new(),
332 state: None,
333 zed_version: None,
334 })
335}