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