1mod assertions;
2mod example;
3mod examples;
4mod explorer;
5mod ids;
6mod instance;
7mod tool_metrics;
8
9use assertions::display_error_row;
10use instance::{ExampleInstance, JudgeOutput, RunOutput, run_git};
11pub(crate) use tool_metrics::*;
12
13use ::fs::RealFs;
14use anyhow::anyhow;
15use clap::Parser;
16use client::{Client, ProxySettings, UserStore};
17use collections::{HashMap, HashSet};
18use extension::ExtensionHostProxy;
19use futures::future;
20use gpui::http_client::read_proxy_from_env;
21use gpui::{App, AppContext, Application, AsyncApp, Entity, SemanticVersion, UpdateGlobal};
22use gpui_tokio::Tokio;
23use language::LanguageRegistry;
24use language_model::{ConfiguredModel, LanguageModel, LanguageModelRegistry};
25use node_runtime::{NodeBinaryOptions, NodeRuntime};
26use project::Project;
27use project::project_settings::ProjectSettings;
28use prompt_store::PromptBuilder;
29use release_channel::AppVersion;
30use reqwest_client::ReqwestClient;
31use settings::{Settings, SettingsStore};
32use std::cell::RefCell;
33use std::collections::VecDeque;
34use std::env;
35use std::path::{Path, PathBuf};
36use std::rc::Rc;
37use std::sync::{Arc, LazyLock};
38use util::ResultExt as _;
39
40static CARGO_MANIFEST_DIR: LazyLock<PathBuf> =
41 LazyLock::new(|| PathBuf::from(env!("CARGO_MANIFEST_DIR")));
42
43#[derive(Parser, Debug)]
44#[command(name = "eval", disable_version_flag = true)]
45struct Args {
46 /// Runs all examples and threads that contain these substrings. If unspecified, all examples and threads are run.
47 #[arg(value_name = "EXAMPLE_SUBSTRING")]
48 filter: Vec<String>,
49 /// Model to use (default: "claude-3-7-sonnet-latest")
50 #[arg(long, default_value = "claude-3-7-sonnet-latest")]
51 model: String,
52 #[arg(long, value_delimiter = ',', default_value = "rs,ts")]
53 languages: Vec<String>,
54 /// How many times to run each example.
55 #[arg(long, default_value = "1")]
56 repetitions: usize,
57 /// Maximum number of examples to run concurrently.
58 #[arg(long, default_value = "10")]
59 concurrency: usize,
60}
61
62fn main() {
63 dotenv::from_filename(CARGO_MANIFEST_DIR.join(".env")).ok();
64
65 env_logger::init();
66
67 let system_id = ids::get_or_create_id(&ids::eval_system_id_path()).ok();
68 let installation_id = ids::get_or_create_id(&ids::eval_installation_id_path()).ok();
69 let session_id = uuid::Uuid::new_v4().to_string();
70 let run_timestamp = chrono::Local::now().format("%Y-%m-%d_%H-%M-%S");
71 let run_id = match env::var("GITHUB_RUN_ID") {
72 Ok(run_id) => format!("github/{}", run_id),
73 Err(_) => format!("local/{}", run_timestamp),
74 };
75
76 let root_dir = Path::new(std::env!("CARGO_MANIFEST_DIR"))
77 .parent()
78 .unwrap()
79 .parent()
80 .unwrap()
81 .canonicalize()
82 .unwrap();
83 let eval_crate_dir = root_dir.join("crates").join("eval");
84 let repos_dir = eval_crate_dir.join("repos");
85 let worktrees_dir = eval_crate_dir.join("worktrees");
86 let examples_dir = eval_crate_dir.join("src").join("examples");
87 let run_dir = eval_crate_dir
88 .join("runs")
89 .join(format!("{}", run_timestamp));
90 std::fs::create_dir_all(&run_dir).unwrap();
91 std::fs::create_dir_all(&repos_dir).unwrap();
92 std::fs::create_dir_all(&worktrees_dir).unwrap();
93 std::fs::create_dir_all(&examples_dir).unwrap();
94 std::fs::create_dir_all(&paths::config_dir()).unwrap();
95
96 let zed_commit_sha = commit_sha_for_path(&root_dir);
97 let zed_branch_name = git_branch_for_path(&root_dir);
98 let args = Args::parse();
99 let languages: HashSet<String> = args.languages.into_iter().collect();
100
101 let http_client = Arc::new(ReqwestClient::new());
102 let app = Application::headless().with_http_client(http_client.clone());
103 let all_threads = examples::all(&examples_dir);
104
105 app.run(move |cx| {
106 let app_state = init(cx);
107
108 let telemetry = app_state.client.telemetry();
109 telemetry.start(system_id, installation_id, session_id, cx);
110
111 let enable_telemetry = env::var("ZED_EVAL_TELEMETRY").map_or(false, |value| value == "1")
112 && telemetry.has_checksum_seed();
113 if enable_telemetry {
114 println!("Telemetry enabled");
115 telemetry::event!(
116 "Agent Eval Started",
117 zed_commit_sha = zed_commit_sha,
118 zed_branch_name = zed_branch_name,
119 run_id = run_id,
120 );
121 }
122
123 let mut cumulative_tool_metrics = ToolMetrics::default();
124
125 let model_registry = LanguageModelRegistry::read_global(cx);
126 let model = find_model("claude-3-7-sonnet-latest", model_registry, cx).unwrap();
127 let model_provider_id = model.provider_id();
128 let model_provider = model_registry.provider(&model_provider_id).unwrap();
129
130 LanguageModelRegistry::global(cx).update(cx, |registry, cx| {
131 registry.set_default_model(
132 Some(ConfiguredModel {
133 provider: model_provider.clone(),
134 model: model.clone(),
135 }),
136 cx,
137 );
138 });
139
140 let authenticate_task = model_provider.authenticate(cx);
141
142 cx.spawn(async move |cx| {
143 authenticate_task.await.unwrap();
144
145 let mut examples = Vec::new();
146
147 const COLORS: [&str; 12] = [
148 "\x1b[31m", // Red
149 "\x1b[32m", // Green
150 "\x1b[33m", // Yellow
151 "\x1b[34m", // Blue
152 "\x1b[35m", // Magenta
153 "\x1b[36m", // Cyan
154 "\x1b[91m", // Bright Red
155 "\x1b[92m", // Bright Green
156 "\x1b[93m", // Bright Yellow
157 "\x1b[94m", // Bright Blue
158 "\x1b[95m", // Bright Magenta
159 "\x1b[96m", // Bright Cyan
160 ];
161
162 let mut skipped = Vec::new();
163
164 for thread in all_threads {
165 let meta = thread.meta();
166 if !args.filter.is_empty() && !args.filter.iter().any(|sub| meta.name.contains(sub))
167 {
168 skipped.push(meta.name);
169 continue;
170 }
171
172 if let Some(language) = meta.language_server {
173 if !languages.contains(&language.file_extension) {
174 panic!(
175 "Eval for {:?} could not be run because no language server was found for extension {:?}",
176 meta.name,
177 language.file_extension
178 );
179 }
180 }
181
182 // TODO: This creates a worktree per repetition. Ideally these examples should
183 // either be run sequentially on the same worktree, or reuse worktrees when there
184 // are more examples to run than the concurrency limit.
185 for repetition_number in 0..args.repetitions {
186 let example_instance = ExampleInstance::new(
187 thread.clone(),
188 &repos_dir,
189 &run_dir,
190 &worktrees_dir,
191 repetition_number,
192 );
193
194 examples.push(example_instance);
195 }
196 }
197
198 if !skipped.is_empty() {
199 println!("Skipped threads: {}", skipped.join(", "));
200 }
201
202 if examples.is_empty() {
203 eprintln!("Filter matched no examples");
204 return cx.update(|cx| cx.quit());
205 }
206
207 let mut repo_urls = HashSet::default();
208 let mut clone_tasks = Vec::new();
209
210 let max_name_width = examples
211 .iter()
212 .map(|e| e.worktree_name().len())
213 .max()
214 .unwrap_or(0);
215
216 for (i, example_instance) in examples.iter_mut().enumerate() {
217 let color = COLORS[i % COLORS.len()].to_string();
218 example_instance.set_log_prefix_style(&color, max_name_width);
219
220 println!(
221 "{}Logging to: {}",
222 example_instance.log_prefix,
223 example_instance.run_directory.display()
224 );
225
226 let repo_url = example_instance.repo_url();
227 if repo_urls.insert(repo_url.clone()) {
228 let repo_path = example_instance.repo_path.clone();
229
230 if !repo_path.join(".git").is_dir() {
231 println!(
232 "{:<width$} < {}",
233 "↓ Cloning",
234 repo_url,
235 width = max_name_width
236 );
237
238 let git_task = cx.spawn(async move |_cx| {
239 std::fs::create_dir_all(&repo_path)?;
240 run_git(&repo_path, &["init"]).await?;
241 run_git(&repo_path, &["remote", "add", "origin", &repo_url]).await
242 });
243
244 clone_tasks.push(git_task);
245 } else {
246 println!(
247 "{:<width$} < {}",
248 "✔︎ Already cloned",
249 repo_url,
250 width = max_name_width
251 );
252
253 let actual_origin =
254 run_git(&repo_path, &["remote", "get-url", "origin"]).await?;
255 if actual_origin != repo_url {
256 return Err(anyhow!(
257 "remote origin {} does not match expected origin {}",
258 actual_origin,
259 repo_url,
260 ));
261 }
262 }
263 }
264 }
265
266 future::join_all(clone_tasks).await;
267
268 for example_instance in examples.iter_mut() {
269 example_instance.fetch().await?;
270 }
271
272 let examples = Rc::new(RefCell::new(VecDeque::from(examples)));
273 let results_by_example_name = Rc::new(RefCell::new(HashMap::default()));
274
275 future::join_all((0..args.concurrency).map(|_| {
276 let app_state = app_state.clone();
277 let model = model.clone();
278 let zed_commit_sha = zed_commit_sha.clone();
279 let zed_branch_name = zed_branch_name.clone();
280 let run_id = run_id.clone();
281 let examples = examples.clone();
282 let results = results_by_example_name.clone();
283 cx.spawn(async move |cx| {
284 loop {
285 let Some(mut example) = examples.borrow_mut().pop_front() else {
286 break;
287 };
288 let result = async {
289 example.setup().await?;
290 let run_output = cx
291 .update(|cx| example.run(model.clone(), app_state.clone(), cx))?
292 .await?;
293 let judge_output = judge_example(
294 example.clone(),
295 model.clone(),
296 &zed_commit_sha,
297 &zed_branch_name,
298 &run_id,
299 &run_output,
300 enable_telemetry,
301 cx,
302 )
303 .await;
304 anyhow::Ok((run_output, judge_output))
305 }
306 .await;
307 results
308 .borrow_mut()
309 .entry(example.name.clone())
310 .or_insert(Vec::new())
311 .push((example.clone(), result));
312 }
313 })
314 }))
315 .await;
316
317 print_report(
318 &mut results_by_example_name.borrow_mut(),
319 &mut cumulative_tool_metrics,
320 &run_dir,
321 )?;
322
323 app_state.client.telemetry().flush_events().await;
324
325 cx.update(|cx| cx.quit())
326 })
327 .detach_and_log_err(cx);
328 });
329}
330
331/// Subset of `workspace::AppState` needed by `HeadlessAssistant`, with additional fields.
332pub struct AgentAppState {
333 pub languages: Arc<LanguageRegistry>,
334 pub client: Arc<Client>,
335 pub user_store: Entity<UserStore>,
336 pub fs: Arc<dyn fs::Fs>,
337 pub node_runtime: NodeRuntime,
338
339 // Additional fields not present in `workspace::AppState`.
340 pub prompt_builder: Arc<PromptBuilder>,
341}
342
343pub fn init(cx: &mut App) -> Arc<AgentAppState> {
344 release_channel::init(SemanticVersion::default(), cx);
345 gpui_tokio::init(cx);
346
347 let mut settings_store = SettingsStore::new(cx);
348 settings_store
349 .set_default_settings(settings::default_settings().as_ref(), cx)
350 .unwrap();
351 cx.set_global(settings_store);
352 client::init_settings(cx);
353
354 // Set User-Agent so we can download language servers from GitHub
355 let user_agent = format!(
356 "Zed/{} ({}; {})",
357 AppVersion::global(cx),
358 std::env::consts::OS,
359 std::env::consts::ARCH
360 );
361 let proxy_str = ProxySettings::get_global(cx).proxy.to_owned();
362 let proxy_url = proxy_str
363 .as_ref()
364 .and_then(|input| input.parse().ok())
365 .or_else(read_proxy_from_env);
366 let http = {
367 let _guard = Tokio::handle(cx).enter();
368
369 ReqwestClient::proxy_and_user_agent(proxy_url, &user_agent)
370 .expect("could not start HTTP client")
371 };
372 cx.set_http_client(Arc::new(http));
373
374 Project::init_settings(cx);
375
376 let client = Client::production(cx);
377 cx.set_http_client(client.http_client());
378
379 let git_binary_path = None;
380 let fs = Arc::new(RealFs::new(
381 git_binary_path,
382 cx.background_executor().clone(),
383 ));
384
385 let mut languages = LanguageRegistry::new(cx.background_executor().clone());
386 languages.set_language_server_download_dir(paths::languages_dir().clone());
387 let languages = Arc::new(languages);
388
389 let user_store = cx.new(|cx| UserStore::new(client.clone(), cx));
390
391 extension::init(cx);
392
393 let (tx, rx) = async_watch::channel(None);
394 cx.observe_global::<SettingsStore>(move |cx| {
395 let settings = &ProjectSettings::get_global(cx).node;
396 let options = NodeBinaryOptions {
397 allow_path_lookup: !settings.ignore_system_version,
398 allow_binary_download: true,
399 use_paths: settings.path.as_ref().map(|node_path| {
400 let node_path = PathBuf::from(shellexpand::tilde(node_path).as_ref());
401 let npm_path = settings
402 .npm_path
403 .as_ref()
404 .map(|path| PathBuf::from(shellexpand::tilde(&path).as_ref()));
405 (
406 node_path.clone(),
407 npm_path.unwrap_or_else(|| {
408 let base_path = PathBuf::new();
409 node_path.parent().unwrap_or(&base_path).join("npm")
410 }),
411 )
412 }),
413 };
414 tx.send(Some(options)).log_err();
415 })
416 .detach();
417 let node_runtime = NodeRuntime::new(client.http_client(), None, rx);
418
419 let extension_host_proxy = ExtensionHostProxy::global(cx);
420
421 language::init(cx);
422 language_extension::init(extension_host_proxy.clone(), languages.clone());
423 language_model::init(client.clone(), cx);
424 language_models::init(user_store.clone(), client.clone(), fs.clone(), cx);
425 languages::init(languages.clone(), node_runtime.clone(), cx);
426 prompt_store::init(cx);
427 let stdout_is_a_pty = false;
428 let prompt_builder = PromptBuilder::load(fs.clone(), stdout_is_a_pty, cx);
429 agent::init(
430 fs.clone(),
431 client.clone(),
432 prompt_builder.clone(),
433 languages.clone(),
434 cx,
435 );
436 assistant_tools::init(client.http_client(), cx);
437
438 SettingsStore::update_global(cx, |store, cx| {
439 store.set_user_settings(include_str!("../runner_settings.json"), cx)
440 })
441 .unwrap();
442
443 Arc::new(AgentAppState {
444 languages,
445 client,
446 user_store,
447 fs,
448 node_runtime,
449 prompt_builder,
450 })
451}
452
453pub fn find_model(
454 model_name: &str,
455 model_registry: &LanguageModelRegistry,
456 cx: &App,
457) -> anyhow::Result<Arc<dyn LanguageModel>> {
458 let model = model_registry
459 .available_models(cx)
460 .find(|model| model.id().0 == model_name);
461
462 let Some(model) = model else {
463 return Err(anyhow!(
464 "No language model named {} was available. Available models: {}",
465 model_name,
466 model_registry
467 .available_models(cx)
468 .map(|model| model.id().0.clone())
469 .collect::<Vec<_>>()
470 .join(", ")
471 ));
472 };
473
474 Ok(model)
475}
476
477pub fn commit_sha_for_path(repo_path: &Path) -> String {
478 futures::executor::block_on(run_git(repo_path, &["rev-parse", "HEAD"])).unwrap()
479}
480
481pub fn git_branch_for_path(repo_path: &Path) -> String {
482 match std::env::var("GITHUB_REF_NAME") {
483 Ok(branch) => branch,
484 Err(_) => {
485 futures::executor::block_on(run_git(repo_path, &["rev-parse", "--abbrev-ref", "HEAD"]))
486 .unwrap_or_else(|_| "unknown".to_string())
487 }
488 }
489}
490
491async fn judge_example(
492 example: ExampleInstance,
493 model: Arc<dyn LanguageModel>,
494 zed_commit_sha: &str,
495 zed_branch_name: &str,
496 run_id: &str,
497 run_output: &RunOutput,
498 enable_telemetry: bool,
499 cx: &AsyncApp,
500) -> JudgeOutput {
501 let judge_output = example.judge(model.clone(), &run_output, cx).await;
502
503 if enable_telemetry {
504 telemetry::event!(
505 "Agent Example Evaluated",
506 zed_commit_sha = zed_commit_sha,
507 zed_branch_name = zed_branch_name,
508 run_id = run_id,
509 example_name = example.name.clone(),
510 example_repetition = example.repetition,
511 diff_evaluation = judge_output.diff.clone(),
512 thread_evaluation = judge_output.thread.clone(),
513 tool_metrics = run_output.tool_metrics,
514 response_count = run_output.response_count,
515 token_usage = run_output.token_usage,
516 model = model.telemetry_id(),
517 model_provider = model.provider_id().to_string(),
518 repository_url = example.repo_url(),
519 repository_revision = example.revision(),
520 diagnostic_summary_before = run_output.diagnostic_summary_before,
521 diagnostic_summary_after = run_output.diagnostic_summary_after,
522 diagnostics_before = run_output.diagnostics_before,
523 diagnostics_after = run_output.diagnostics_after,
524 );
525 }
526
527 judge_output
528}
529
530const HEADER_WIDTH: usize = 65;
531
532fn print_h1(header: &str) {
533 println!("\n\n{:=^HEADER_WIDTH$}", "");
534 println!("{:^HEADER_WIDTH$}", header);
535 println!("{:=^HEADER_WIDTH$}\n", "");
536}
537
538fn print_h2(header: &str) {
539 println!("\n{:-^HEADER_WIDTH$}", "");
540 println!("{:^HEADER_WIDTH$}", header);
541 println!("{:-^HEADER_WIDTH$}\n", "");
542}
543
544fn print_report(
545 results_by_example_name: &mut HashMap<
546 String,
547 Vec<(ExampleInstance, anyhow::Result<(RunOutput, JudgeOutput)>)>,
548 >,
549 cumulative_tool_metrics: &mut ToolMetrics,
550 run_dir: &Path,
551) -> anyhow::Result<()> {
552 print_h1("EVAL RESULTS");
553
554 let mut diff_scores = Vec::new();
555 let mut thread_scores = Vec::new();
556 let mut programmatic_scores = Vec::new();
557 let mut error_count = 0;
558
559 for (example_name, results) in results_by_example_name.iter_mut() {
560 print_h2(example_name);
561
562 results.sort_unstable_by_key(|(example, _)| example.repetition);
563 let mut example_cumulative_tool_metrics = ToolMetrics::default();
564
565 let mut table_rows = String::new();
566
567 for (example, result) in results.iter() {
568 match result {
569 Err(err) => {
570 display_error_row(&mut table_rows, example.repetition, err.to_string())?;
571 error_count += 1;
572 }
573 Ok((run_output, judge_output)) => {
574 cumulative_tool_metrics.merge(&run_output.tool_metrics);
575 example_cumulative_tool_metrics.merge(&run_output.tool_metrics);
576
577 if !run_output.programmatic_assertions.total_count() > 0 {
578 for assertion in &run_output.programmatic_assertions.ran {
579 assertions::display_table_row(
580 &mut table_rows,
581 example.repetition,
582 assertion,
583 )?;
584 }
585
586 programmatic_scores
587 .push(run_output.programmatic_assertions.passed_percentage())
588 }
589
590 if !judge_output.diff.is_empty() {
591 diff_scores.push(judge_output.diff.passed_percentage());
592
593 for assertion in &judge_output.diff.ran {
594 assertions::display_table_row(
595 &mut table_rows,
596 example.repetition,
597 assertion,
598 )?;
599 }
600 }
601
602 if !judge_output.thread.is_empty() {
603 thread_scores.push(judge_output.thread.passed_percentage());
604
605 for assertion in &judge_output.thread.ran {
606 assertions::display_table_row(
607 &mut table_rows,
608 example.repetition,
609 assertion,
610 )?;
611 }
612 }
613 }
614 }
615 }
616
617 if !table_rows.is_empty() {
618 assertions::print_table_header();
619 print!("{}", table_rows);
620
621 assertions::print_table_divider();
622
623 for (example, result) in results.iter() {
624 if let Ok((run_output, judge_output)) = result {
625 assertions::print_table_round_summary(
626 &example.repetition.to_string(),
627 [
628 &run_output.programmatic_assertions,
629 &judge_output.diff,
630 &judge_output.thread,
631 ]
632 .into_iter(),
633 )
634 }
635 }
636
637 assertions::print_table_divider();
638
639 assertions::print_table_round_summary(
640 "avg",
641 results.iter().flat_map(|(_, result)| {
642 result.iter().flat_map(|(run_output, judge_output)| {
643 [
644 &run_output.programmatic_assertions,
645 &judge_output.diff,
646 &judge_output.thread,
647 ]
648 .into_iter()
649 })
650 }),
651 );
652
653 assertions::print_table_footer();
654 }
655
656 if !example_cumulative_tool_metrics.is_empty() {
657 println!("{}", &example_cumulative_tool_metrics);
658 }
659 }
660
661 if results_by_example_name.len() > 1 {
662 print_h1("AGGREGATE");
663
664 if error_count > 0 {
665 println!("\n{error_count} examples failed to run!");
666 }
667
668 let programmatic_score_count = programmatic_scores.len();
669 if programmatic_score_count > 0 {
670 let average_programmatic_score = (programmatic_scores.into_iter().sum::<f32>()
671 / (programmatic_score_count as f32))
672 .floor();
673 println!("Average programmatic score: {average_programmatic_score}%");
674 }
675
676 let diff_score_count = diff_scores.len();
677 if diff_score_count > 0 {
678 let average_diff_score =
679 (diff_scores.into_iter().sum::<f32>() / (diff_score_count as f32)).floor();
680 println!("Average diff score: {average_diff_score}%");
681 }
682
683 let thread_score_count = thread_scores.len();
684
685 if thread_score_count > 0 {
686 let average_thread_score =
687 (thread_scores.into_iter().sum::<f32>() / (thread_score_count as f32)).floor();
688 println!("Average thread score: {average_thread_score}%");
689 }
690
691 println!("");
692
693 print_h2("CUMULATIVE TOOL METRICS");
694 println!("{}", cumulative_tool_metrics);
695 }
696
697 let explorer_output_path = run_dir.join("overview.html");
698 let mut json_paths: Vec<PathBuf> = results_by_example_name
699 .values()
700 .flat_map(|results| {
701 results.iter().map(|(example, _)| {
702 let absolute_path = example.run_directory.join("last.messages.json");
703 pathdiff::diff_paths(&absolute_path, run_dir)
704 .unwrap_or_else(|| absolute_path.clone())
705 })
706 })
707 .collect::<Vec<_>>();
708 json_paths.sort();
709 if let Err(err) = explorer::generate_explorer_html(&json_paths, &explorer_output_path) {
710 eprintln!("Failed to generate explorer HTML: {}", err);
711 }
712
713 Ok(())
714}