example.rs

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