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