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