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