1use agent::{RequestKind, ThreadEvent, ThreadStore};
2use anyhow::{Context as _, Result, anyhow};
3use assistant_tool::ToolWorkingSet;
4use client::proto::LspWorkProgress;
5use collections::HashMap;
6use dap::DapRegistry;
7use futures::channel::{mpsc, oneshot};
8use futures::{FutureExt, StreamExt as _};
9use gpui::{App, AsyncApp, Entity, Task};
10use handlebars::Handlebars;
11use language::{DiagnosticSeverity, OffsetRangeExt};
12use language_model::{
13 LanguageModel, LanguageModelRequest, LanguageModelRequestMessage, MessageContent, Role,
14 StopReason, TokenUsage,
15};
16use project::{LspStore, Project, ProjectPath};
17use serde::{Deserialize, Serialize};
18use std::fmt::Write as _;
19use std::fs::File;
20use std::io::Write as _;
21use std::sync::{Arc, Mutex};
22use std::time::Duration;
23use std::{
24 fs,
25 path::{Path, PathBuf},
26};
27use unindent::Unindent as _;
28use util::ResultExt as _;
29use util::command::new_smol_command;
30use util::serde::default_true;
31
32use crate::AgentAppState;
33
34pub const EXAMPLES_DIR: &str = "./crates/eval/examples";
35pub const REPOS_DIR: &str = "./crates/eval/repos";
36pub const WORKTREES_DIR: &str = "./crates/eval/worktrees";
37
38#[derive(Clone, Debug, Deserialize)]
39pub struct ExampleBase {
40 pub url: String,
41 pub revision: String,
42 pub language_extension: Option<String>,
43 pub insert_id: Option<String>,
44 #[serde(default = "default_true")]
45 pub require_lsp: bool,
46}
47
48#[derive(Clone, Debug)]
49pub struct Example {
50 pub name: String,
51 /// Content of `base.toml`
52 pub base: ExampleBase,
53 /// Content of `prompt.md`
54 pub prompt: String,
55 /// Content of `criteria.md`
56 pub criteria: String,
57 /// Markdown log file to append to
58 pub log_file: Arc<Mutex<File>>,
59}
60
61#[derive(Debug, Serialize, Deserialize, Clone)]
62pub struct RunOutput {
63 pub repository_diff: String,
64 pub diagnostics: String,
65 pub response_count: usize,
66 pub token_usage: TokenUsage,
67 pub tool_use_counts: HashMap<Arc<str>, u32>,
68}
69
70#[derive(Debug, Clone, Serialize, Deserialize)]
71pub struct JudgeInput {
72 pub repository_diff: String,
73 pub criteria: String,
74}
75
76#[derive(Debug, Clone, Serialize, Deserialize)]
77pub struct JudgeOutput {
78 pub analysis: String,
79 pub score: u32,
80}
81
82impl Example {
83 /// Load an example from a directory containing base.toml, prompt.md, and criteria.md
84 pub fn load_from_directory(dir_path: &Path, run_dir: &Path) -> Result<Self> {
85 let name = dir_path.file_name().unwrap().to_string_lossy().to_string();
86 let base_path = dir_path.join("base.toml");
87 let prompt_path = dir_path.join("prompt.md");
88 let criteria_path = dir_path.join("criteria.md");
89
90 let log_file_path = run_dir.join(format!(
91 "{}.md",
92 dir_path.file_name().unwrap().to_str().unwrap()
93 ));
94 let log_file = Arc::new(Mutex::new(File::create(&log_file_path).unwrap()));
95 println!("{}> Logging to {:?}", name, log_file_path);
96
97 Ok(Example {
98 name,
99 base: toml::from_str(&fs::read_to_string(&base_path)?)?,
100 prompt: fs::read_to_string(prompt_path.clone())?,
101 criteria: fs::read_to_string(criteria_path.clone())?,
102 log_file,
103 })
104 }
105
106 pub fn worktree_path(&self) -> PathBuf {
107 Path::new(WORKTREES_DIR)
108 .canonicalize()
109 .context(format!("No such directory {WORKTREES_DIR}"))
110 .unwrap()
111 .join(&self.name)
112 }
113
114 /// Set up the example by checking out the specified Git revision
115 pub async fn setup(&self) -> Result<()> {
116 let repo_path = repo_path_for_url(&self.base.url);
117
118 run_git(
119 &repo_path,
120 &["fetch", "--depth", "1", "origin", &self.base.revision],
121 )
122 .await?;
123
124 let worktree_path = self.worktree_path();
125
126 if worktree_path.is_dir() {
127 println!("{}> Resetting existing worktree", self.name);
128
129 // TODO: consider including "-x" to remove ignored files. The downside of this is that
130 // it will also remove build artifacts, and so prevent incremental reuse there.
131 run_git(&worktree_path, &["clean", "--force", "-d"]).await?;
132 run_git(&worktree_path, &["reset", "--hard", "HEAD"]).await?;
133 run_git(&worktree_path, &["checkout", &self.base.revision]).await?;
134 } else {
135 println!("{}> Creating worktree", self.name);
136
137 let worktree_path_string = worktree_path.to_string_lossy().to_string();
138
139 run_git(
140 &repo_path,
141 &[
142 "worktree",
143 "add",
144 "-f",
145 &worktree_path_string,
146 &self.base.revision,
147 ],
148 )
149 .await?;
150 }
151
152 Ok(())
153 }
154
155 pub fn run(
156 &self,
157 model: Arc<dyn LanguageModel>,
158 app_state: Arc<AgentAppState>,
159 cx: &mut App,
160 ) -> Task<Result<RunOutput>> {
161 let project = Project::local(
162 app_state.client.clone(),
163 app_state.node_runtime.clone(),
164 app_state.user_store.clone(),
165 app_state.languages.clone(),
166 Arc::new(DapRegistry::default()),
167 app_state.fs.clone(),
168 None,
169 cx,
170 );
171
172 let worktree_path = self.worktree_path();
173 let worktree = project.update(cx, |project, cx| {
174 project.create_worktree(&worktree_path, true, cx)
175 });
176
177 let tools = Arc::new(ToolWorkingSet::default());
178 let thread_store =
179 ThreadStore::load(project.clone(), tools, app_state.prompt_builder.clone(), cx);
180 let this = self.clone();
181
182 cx.spawn(async move |cx| {
183 let worktree = worktree.await?;
184
185 // Wait for worktree scan to finish before choosing a file to open.
186 worktree
187 .update(cx, |worktree, _cx| {
188 worktree.as_local().unwrap().scan_complete()
189 })?
190 .await;
191
192 let lsp_open_handle_and_store = if this.base.require_lsp {
193 let language_extension = this.base.language_extension.as_deref().context(
194 "language_extension field is required in base.toml when `require_lsp == true`",
195 )?;
196
197 // Open a file that matches the language to cause LSP to start.
198 let language_file = worktree.read_with(cx, |worktree, _cx| {
199 worktree
200 .files(false, 0)
201 .find_map(|e| {
202 if e.path.clone().extension().and_then(|ext| ext.to_str())
203 == Some(language_extension)
204 {
205 Some(ProjectPath {
206 worktree_id: worktree.id(),
207 path: e.path.clone(),
208 })
209 } else {
210 None
211 }
212 })
213 .context("Failed to find a file for example language")
214 })??;
215
216 let open_language_file_buffer_task = project.update(cx, |project, cx| {
217 project.open_buffer(language_file.clone(), cx)
218 })?;
219
220 let language_file_buffer = open_language_file_buffer_task.await?;
221
222 let (lsp_open_handle, lsp_store) = project.update(cx, |project, cx| {
223 (
224 project.register_buffer_with_language_servers(&language_file_buffer, cx),
225 project.lsp_store().clone(),
226 )
227 })?;
228
229 // TODO: remove this once the diagnostics tool waits for new diagnostics
230 cx.background_executor().timer(Duration::new(5, 0)).await;
231 wait_for_lang_server(&lsp_store, this.name.clone(), cx).await?;
232
233 lsp_store.update(cx, |lsp_store, cx| {
234 lsp_open_handle.update(cx, |buffer, cx| {
235 buffer.update(cx, |buffer, cx| {
236 let has_language_server = lsp_store
237 .language_servers_for_local_buffer(buffer, cx)
238 .next()
239 .is_some();
240 if has_language_server {
241 Ok(())
242 } else {
243 Err(anyhow!(
244 "`{:?}` was opened to cause the language server to start, \
245 but no language servers are registered for its buffer. \
246 Set `require_lsp = false` in `base.toml` to skip this.",
247 language_file
248 ))
249 }
250 })
251 })
252 })??;
253
254 Some((lsp_open_handle, lsp_store))
255 } else {
256 None
257 };
258
259 if std::env::var("ZED_EVAL_SETUP_ONLY").is_ok() {
260 return Err(anyhow!("Setup only mode"));
261 }
262
263 let thread_store = thread_store.await;
264 let thread =
265 thread_store.update(cx, |thread_store, cx| thread_store.create_thread(cx))?;
266
267 {
268 let mut log_file = this.log_file.lock().unwrap();
269 writeln!(&mut log_file, "👤 USER:").log_err();
270 writeln!(&mut log_file, "{}", this.prompt).log_err();
271 writeln!(&mut log_file, "🤖 ASSISTANT:").log_err();
272 log_file.flush().log_err();
273 }
274
275 let tool_use_counts: Arc<Mutex<HashMap<Arc<str>, u32>>> =
276 Mutex::new(HashMap::default()).into();
277
278 let (tx, rx) = oneshot::channel();
279 let mut tx = Some(tx);
280
281 let subscription = cx.subscribe(&thread, {
282 let log_file = this.log_file.clone();
283 let name = this.name.clone();
284 let tool_use_counts = tool_use_counts.clone();
285 move |thread, event: &ThreadEvent, cx| {
286 let mut log_file = log_file.lock().unwrap();
287
288 match event {
289 ThreadEvent::Stopped(reason) => match reason {
290 Ok(StopReason::EndTurn) => {
291 if let Some(tx) = tx.take() {
292 tx.send(Ok(())).ok();
293 }
294 }
295 Ok(StopReason::MaxTokens) => {
296 if let Some(tx) = tx.take() {
297 tx.send(Err(anyhow!("Exceeded maximum tokens"))).ok();
298 }
299 }
300 Ok(StopReason::ToolUse) => {}
301 Err(error) => {
302 if let Some(tx) = tx.take() {
303 tx.send(Err(anyhow!(error.clone()))).ok();
304 }
305 }
306 },
307 ThreadEvent::ShowError(thread_error) => {
308 if let Some(tx) = tx.take() {
309 tx.send(Err(anyhow!(thread_error.clone()))).ok();
310 }
311 }
312 ThreadEvent::StreamedAssistantText(_, chunk) => {
313 write!(&mut log_file, "{}", chunk).log_err();
314 }
315 ThreadEvent::StreamedAssistantThinking(_, chunk) => {
316 write!(&mut log_file, "{}", chunk).log_err();
317 }
318 ThreadEvent::UsePendingTools { tool_uses } => {
319 writeln!(&mut log_file, "\n\nUSING TOOLS:").log_err();
320 for tool_use in tool_uses {
321 writeln!(&mut log_file, "{}: {}", tool_use.name, tool_use.input)
322 .log_err();
323 }
324 }
325 ThreadEvent::ToolFinished {
326 tool_use_id,
327 pending_tool_use,
328 ..
329 } => {
330 if let Some(tool_use) = pending_tool_use {
331 let message = format!("TOOL FINISHED: {}", tool_use.name);
332 println!("{name}> {message}");
333 writeln!(&mut log_file, "\n{}", message).log_err();
334 }
335 if let Some(tool_result) = thread.read(cx).tool_result(tool_use_id) {
336 writeln!(&mut log_file, "\n{}\n", tool_result.content).log_err();
337 let mut tool_use_counts = tool_use_counts.lock().unwrap();
338 *tool_use_counts
339 .entry(tool_result.tool_name.clone())
340 .or_insert(0) += 1;
341 }
342 }
343 _ => {}
344 }
345
346 log_file.flush().log_err();
347 }
348 })?;
349
350 thread.update(cx, |thread, cx| {
351 let context = vec![];
352 thread.insert_user_message(this.prompt.clone(), context, None, cx);
353 thread.send_to_model(model, RequestKind::Chat, cx);
354 })?;
355
356 rx.await??;
357
358 if let Some((_, lsp_store)) = lsp_open_handle_and_store.as_ref() {
359 wait_for_lang_server(lsp_store, this.name.clone(), cx).await?;
360 }
361
362 let repository_diff = this.repository_diff().await?;
363 let diagnostics = cx
364 .update(move |cx| {
365 cx.spawn(async move |cx| query_lsp_diagnostics(project, cx).await)
366 })?
367 .await?;
368
369 drop(subscription);
370 drop(lsp_open_handle_and_store);
371
372 thread.update(cx, |thread, _cx| {
373 let response_count = thread
374 .messages()
375 .filter(|message| message.role == language_model::Role::Assistant)
376 .count();
377 RunOutput {
378 repository_diff,
379 diagnostics,
380 response_count,
381 token_usage: thread.cumulative_token_usage(),
382 tool_use_counts: tool_use_counts.lock().unwrap().clone(),
383 }
384 })
385 })
386 }
387
388 pub async fn judge(
389 &mut self,
390 model: Arc<dyn LanguageModel>,
391 repository_diff: String,
392 cx: &AsyncApp,
393 ) -> Result<JudgeOutput> {
394 let judge_prompt = include_str!("judge_prompt.hbs");
395 let judge_prompt_name = "judge_prompt";
396 let mut handlebars = Handlebars::new();
397 handlebars.register_template_string(judge_prompt_name, judge_prompt)?;
398 let prompt = handlebars.render(
399 judge_prompt_name,
400 &JudgeInput {
401 repository_diff,
402 criteria: self.criteria.clone(),
403 },
404 )?;
405
406 let request = LanguageModelRequest {
407 messages: vec![LanguageModelRequestMessage {
408 role: Role::User,
409 content: vec![MessageContent::Text(prompt)],
410 cache: false,
411 }],
412 temperature: None,
413 tools: Vec::new(),
414 stop: Vec::new(),
415 };
416
417 let response = send_language_model_request(model, request, cx).await?;
418
419 let mut log_file = self.log_file.lock().unwrap();
420
421 writeln!(&mut log_file, "\n\n").log_err();
422 writeln!(&mut log_file, "========================================").log_err();
423 writeln!(&mut log_file, " JUDGE OUTPUT ").log_err();
424 writeln!(&mut log_file, "========================================").log_err();
425 writeln!(&mut log_file, "\n{}", &response).log_err();
426
427 parse_judge_output(&response)
428 }
429
430 pub async fn repository_diff(&self) -> Result<String> {
431 let worktree_path = self.worktree_path();
432 run_git(&worktree_path, &["add", "-N"]).await?;
433 run_git(&worktree_path, &["diff"]).await
434 }
435}
436
437fn wait_for_lang_server(
438 lsp_store: &Entity<LspStore>,
439 name: String,
440 cx: &mut AsyncApp,
441) -> Task<Result<()>> {
442 if cx
443 .update(|cx| !has_pending_lang_server_work(lsp_store, cx))
444 .unwrap()
445 || std::env::var("ZED_EVAL_SKIP_LS_WAIT").is_ok()
446 {
447 return Task::ready(anyhow::Ok(()));
448 }
449
450 println!("{}> ⏵ Waiting for language server", name);
451
452 let (mut tx, mut rx) = mpsc::channel(1);
453
454 let subscription =
455 cx.subscribe(&lsp_store, {
456 let name = name.clone();
457 move |lsp_store, event, cx| {
458 match event {
459 project::LspStoreEvent::LanguageServerUpdate {
460 message:
461 client::proto::update_language_server::Variant::WorkProgress(
462 LspWorkProgress {
463 message: Some(message),
464 ..
465 },
466 ),
467 ..
468 } => println!("{name}> ⟲ {message}"),
469 _ => {}
470 }
471
472 if !has_pending_lang_server_work(&lsp_store, cx) {
473 tx.try_send(()).ok();
474 }
475 }
476 });
477
478 cx.spawn(async move |cx| {
479 let timeout = cx.background_executor().timer(Duration::new(60 * 5, 0));
480 let result = futures::select! {
481 _ = rx.next() => {
482 println!("{}> ⚑ Language server idle", name);
483 anyhow::Ok(())
484 },
485 _ = timeout.fuse() => {
486 Err(anyhow!("LSP wait timed out after 5 minutes"))
487 }
488 };
489 drop(subscription);
490 result
491 })
492}
493
494fn has_pending_lang_server_work(lsp_store: &Entity<LspStore>, cx: &App) -> bool {
495 lsp_store
496 .read(cx)
497 .language_server_statuses()
498 .any(|(_, status)| !status.pending_work.is_empty())
499}
500
501async fn query_lsp_diagnostics(project: Entity<Project>, cx: &mut AsyncApp) -> Result<String> {
502 let paths_with_diagnostics = project.update(cx, |project, cx| {
503 project
504 .diagnostic_summaries(true, cx)
505 .filter(|(_, _, summary)| summary.error_count > 0 || summary.warning_count > 0)
506 .map(|(project_path, _, _)| project_path)
507 .collect::<Vec<_>>()
508 })?;
509
510 let mut output = String::new();
511 for project_path in paths_with_diagnostics {
512 let buffer = project
513 .update(cx, |project, cx| project.open_buffer(project_path, cx))?
514 .await?;
515 let snapshot = buffer.read_with(cx, |buffer, _cx| buffer.snapshot())?;
516
517 for (_, group) in snapshot.diagnostic_groups(None) {
518 let entry = &group.entries[group.primary_ix];
519 let range = entry.range.to_point(&snapshot);
520 let severity = match entry.diagnostic.severity {
521 DiagnosticSeverity::ERROR => "error",
522 DiagnosticSeverity::WARNING => "warning",
523 _ => continue,
524 };
525
526 writeln!(
527 output,
528 "{} at line {}: {}",
529 severity,
530 range.start.row + 1,
531 entry.diagnostic.message
532 )?;
533 }
534 }
535 anyhow::Ok(output)
536}
537
538fn parse_judge_output(response: &str) -> Result<JudgeOutput> {
539 let analysis = get_tag("analysis", response)?.to_string();
540 let score = get_tag("score", response)?
541 .parse()
542 .context("error parsing score")?;
543
544 Ok(JudgeOutput { analysis, score })
545}
546
547fn get_tag(name: &'static str, response: &str) -> Result<String> {
548 let start_tag = format!("<{}>", name);
549 let end_tag = format!("</{}>", name);
550
551 let start_ix = response
552 .find(&start_tag)
553 .context(format!("{} start tag not found", name))?;
554 let content_start_ix = start_ix + start_tag.len();
555
556 let end_ix = content_start_ix
557 + response[content_start_ix..]
558 .find(&end_tag)
559 .context(format!("{} end tag not found", name))?;
560
561 let content = response[content_start_ix..end_ix].trim().unindent();
562
563 anyhow::Ok(content)
564}
565
566pub fn repo_path_for_url(repo_url: &str) -> PathBuf {
567 let repo_name = repo_url
568 .trim_start_matches("https://")
569 .replace(|c: char| !c.is_alphanumeric(), "-");
570 Path::new(REPOS_DIR)
571 .canonicalize()
572 .context(format!("No such directory {REPOS_DIR}"))
573 .unwrap()
574 .join(repo_name)
575}
576
577pub async fn run_git(repo_path: &Path, args: &[&str]) -> Result<String> {
578 let output = new_smol_command("git")
579 .current_dir(repo_path)
580 .args(args)
581 .output()
582 .await?;
583
584 if output.status.success() {
585 Ok(String::from_utf8(output.stdout)?.trim().to_string())
586 } else {
587 Err(anyhow!(
588 "`git {}` within `{}` failed with status: {}\nstderr:\n{}\nstdout:\n{}",
589 args.join(" "),
590 repo_path.display(),
591 output.status,
592 String::from_utf8_lossy(&output.stderr),
593 String::from_utf8_lossy(&output.stdout),
594 ))
595 }
596}
597
598pub async fn send_language_model_request(
599 model: Arc<dyn LanguageModel>,
600 request: LanguageModelRequest,
601 cx: &AsyncApp,
602) -> anyhow::Result<String> {
603 match model.stream_completion_text(request, &cx).await {
604 Ok(mut stream) => {
605 let mut full_response = String::new();
606 while let Some(chunk_result) = stream.stream.next().await {
607 match chunk_result {
608 Ok(chunk_str) => {
609 print!("{}", &chunk_str);
610 full_response.push_str(&chunk_str);
611 }
612 Err(err) => {
613 return Err(anyhow!(
614 "Error receiving response from language model: {err}"
615 ));
616 }
617 }
618 }
619 Ok(full_response)
620 }
621 Err(err) => Err(anyhow!(
622 "Failed to get response from language model. Error was: {err}"
623 )),
624 }
625}
626
627#[cfg(test)]
628mod test {
629 use super::*;
630
631 #[test]
632 fn test_parse_judge_output() {
633 let response = r#"
634 <analysis>The model did a good job but there were still compilations errors.</analysis>
635 <score>3</score>
636 "#
637 .unindent();
638
639 let output = parse_judge_output(&response).unwrap();
640 assert_eq!(
641 output.analysis,
642 "The model did a good job but there were still compilations errors."
643 );
644 assert_eq!(output.score, 3);
645
646 let response = r#"
647 Text around ignored
648
649 <analysis>
650 Failed to compile:
651 - Error 1
652 - Error 2
653 </analysis>
654
655 <score>1</score>
656 "#
657 .unindent();
658
659 let output = parse_judge_output(&response).unwrap();
660 assert_eq!(output.analysis, "Failed to compile:\n- Error 1\n- Error 2");
661 assert_eq!(output.score, 1);
662 }
663}