1use agent::{Message, MessageSegment, ThreadStore};
2use anyhow::{Context, Result, anyhow, bail};
3use assistant_tool::ToolWorkingSet;
4use client::proto::LspWorkProgress;
5use futures::channel::mpsc;
6use futures::{FutureExt as _, StreamExt as _, future};
7use gpui::{App, AppContext as _, AsyncApp, Entity, Task};
8use handlebars::Handlebars;
9use language::{Buffer, DiagnosticSeverity, OffsetRangeExt as _};
10use language_model::{
11 LanguageModel, LanguageModelCompletionEvent, LanguageModelRequest, LanguageModelRequestMessage,
12 MessageContent, Role, TokenUsage,
13};
14use project::lsp_store::OpenLspBufferHandle;
15use project::{DiagnosticSummary, Project, ProjectPath};
16use serde::{Deserialize, Serialize};
17use std::cell::RefCell;
18use std::fmt::Write as _;
19use std::fs;
20use std::fs::File;
21use std::io::Write as _;
22use std::path::Path;
23use std::path::PathBuf;
24use std::rc::Rc;
25use std::sync::Arc;
26use std::time::Duration;
27use unindent::Unindent as _;
28use util::ResultExt as _;
29use util::command::new_smol_command;
30use util::markdown::MarkdownCodeBlock;
31
32use crate::assertions::{AssertionsReport, RanAssertion, RanAssertionResult};
33use crate::example::{Example, ExampleContext, FailedAssertion, JudgeAssertion};
34use crate::{AgentAppState, ToolMetrics};
35
36pub const ZED_REPO_URL: &str = "https://github.com/zed-industries/zed.git";
37
38#[derive(Clone)]
39pub struct ExampleInstance {
40 pub thread: Rc<dyn Example>,
41 pub name: String,
42 pub run_directory: PathBuf,
43 pub log_prefix: String,
44 /// The repetition number for this example (0-based)
45 /// When running multiple repetitions of the same example, each instance is assigned a unique repetition number.
46 /// This affects the worktree path and log prefix to avoid clobbering results between runs.
47 pub repetition: usize,
48 pub repo_path: PathBuf,
49 /// Path to the directory containing the requests and responses for the agentic loop
50 worktrees_dir: PathBuf,
51}
52
53#[derive(Debug, Serialize, Clone)]
54pub struct RunOutput {
55 pub repository_diff: String,
56 pub diagnostic_summary_before: DiagnosticSummary,
57 pub diagnostic_summary_after: DiagnosticSummary,
58 pub diagnostics_before: Option<String>,
59 pub diagnostics_after: Option<String>,
60 pub response_count: usize,
61 pub token_usage: TokenUsage,
62 pub tool_metrics: ToolMetrics,
63 pub all_messages: String,
64 pub programmatic_assertions: AssertionsReport,
65}
66
67#[derive(Debug, Clone, Serialize, Deserialize)]
68pub struct JudgeDiffInput {
69 pub repository_diff: String,
70 pub assertion: String,
71}
72
73#[derive(Debug, Clone, Serialize, Deserialize)]
74pub struct JudgeThreadInput {
75 pub messages: String,
76 pub assertion: String,
77}
78
79#[derive(Debug, Clone, Serialize, Deserialize)]
80pub struct JudgeOutput {
81 pub thread: AssertionsReport,
82 pub diff: AssertionsReport,
83}
84
85impl ExampleInstance {
86 pub fn new(
87 thread: Rc<dyn Example>,
88 repos_dir: &Path,
89 run_dir: &Path,
90 worktrees_dir: &Path,
91 repetition: usize,
92 ) -> Self {
93 let name = thread.meta().name.to_string();
94 let run_directory = run_dir
95 .join(&name)
96 .join(repetition.to_string())
97 .to_path_buf();
98
99 let repo_path = repo_path_for_url(repos_dir, &thread.meta().url);
100
101 Self {
102 name,
103 thread,
104 log_prefix: String::new(),
105 run_directory,
106 repetition,
107 repo_path,
108 worktrees_dir: worktrees_dir.to_path_buf(),
109 }
110 }
111
112 pub fn repo_url(&self) -> String {
113 self.thread.meta().url
114 }
115
116 pub fn revision(&self) -> String {
117 self.thread.meta().revision
118 }
119
120 pub fn worktree_name(&self) -> String {
121 format!("{}-{}", self.name, self.repetition)
122 }
123
124 pub fn set_log_prefix_style(&mut self, color: &str, name_width: usize) {
125 self.log_prefix = format!(
126 "{}{:<width$}\x1b[0m | ",
127 color,
128 self.worktree_name(),
129 width = name_width
130 );
131 }
132
133 /// Set up the example by checking out the specified Git revision
134 pub async fn fetch(&mut self) -> Result<()> {
135 let meta = self.thread.meta();
136
137 let revision_exists = run_git(
138 &self.repo_path,
139 &["rev-parse", &format!("{}^{{commit}}", &meta.revision)],
140 )
141 .await
142 .is_ok();
143
144 if !revision_exists {
145 println!("{}Fetching revision {}", self.log_prefix, &meta.revision);
146 run_git(
147 &self.repo_path,
148 &["fetch", "--depth", "1", "origin", &meta.revision],
149 )
150 .await?;
151 }
152 Ok(())
153 }
154
155 /// Set up the example by checking out the specified Git revision
156 pub async fn setup(&mut self) -> Result<()> {
157 let worktree_path = self.worktree_path();
158 let meta = self.thread.meta();
159 if worktree_path.is_dir() {
160 println!("{}Resetting existing worktree", self.log_prefix);
161
162 // TODO: consider including "-x" to remove ignored files. The downside of this is that
163 // it will also remove build artifacts, and so prevent incremental reuse there.
164 run_git(&worktree_path, &["clean", "--force", "-d"]).await?;
165 run_git(&worktree_path, &["reset", "--hard", "HEAD"]).await?;
166 run_git(&worktree_path, &["checkout", &meta.revision]).await?;
167 } else {
168 println!("{}Creating worktree", self.log_prefix);
169
170 let worktree_path_string = worktree_path.to_string_lossy().to_string();
171
172 run_git(
173 &self.repo_path,
174 &[
175 "worktree",
176 "add",
177 "-f",
178 &worktree_path_string,
179 &meta.revision,
180 ],
181 )
182 .await?;
183 }
184
185 if meta.url == ZED_REPO_URL {
186 std::fs::write(worktree_path.join(".rules"), std::fs::read(".rules")?)?;
187 }
188
189 std::fs::create_dir_all(&self.run_directory)?;
190
191 Ok(())
192 }
193
194 pub fn worktree_path(&self) -> PathBuf {
195 self.worktrees_dir
196 .join(self.worktree_name())
197 .join(self.thread.meta().repo_name())
198 }
199
200 pub fn run(
201 &self,
202 model: Arc<dyn LanguageModel>,
203 app_state: Arc<AgentAppState>,
204 cx: &mut App,
205 ) -> Task<Result<RunOutput>> {
206 let project = Project::local(
207 app_state.client.clone(),
208 app_state.node_runtime.clone(),
209 app_state.user_store.clone(),
210 app_state.languages.clone(),
211 app_state.fs.clone(),
212 None,
213 cx,
214 );
215
216 let worktree = project.update(cx, |project, cx| {
217 project.create_worktree(self.worktree_path(), true, cx)
218 });
219
220 let tools = cx.new(|_| ToolWorkingSet::default());
221 let prompt_store = None;
222 let thread_store = ThreadStore::load(
223 project.clone(),
224 tools,
225 prompt_store,
226 app_state.prompt_builder.clone(),
227 cx,
228 );
229 let meta = self.thread.meta();
230 let this = self.clone();
231
232 cx.spawn(async move |cx| {
233 let worktree = worktree.await?;
234
235 // Wait for worktree scan to finish before choosing a file to open.
236 worktree
237 .update(cx, |worktree, _cx| {
238 worktree.as_local().unwrap().scan_complete()
239 })?
240 .await;
241
242 struct LanguageServerState {
243 _lsp_open_handle: OpenLspBufferHandle,
244 language_file_buffer: Entity<Buffer>,
245 }
246
247 let mut diagnostics_before = None;
248 let mut diagnostic_summary_before = DiagnosticSummary::default();
249
250 let lsp = if let Some(language_server) = &meta.language_server {
251 // Open a file that matches the language to cause LSP to start.
252 let language_file = worktree.read_with(cx, |worktree, _cx| {
253 worktree
254 .files(false, 0)
255 .find_map(|e| {
256 if e.path.clone().extension().and_then(|ext| ext.to_str())
257 == Some(&language_server.file_extension)
258 {
259 Some(ProjectPath {
260 worktree_id: worktree.id(),
261 path: e.path.clone(),
262 })
263 } else {
264 None
265 }
266 })
267 .context("Failed to find a file for example language")
268 })??;
269
270 let open_language_file_buffer_task = project.update(cx, |project, cx| {
271 project.open_buffer(language_file.clone(), cx)
272 })?;
273
274 let language_file_buffer = open_language_file_buffer_task.await?;
275
276 let lsp_open_handle = project.update(cx, |project, cx| {
277 project.register_buffer_with_language_servers(&language_file_buffer, cx)
278 })?;
279
280 wait_for_lang_server(&project, &language_file_buffer, this.log_prefix.clone(), cx).await?;
281
282 diagnostic_summary_before = project.read_with(cx, |project, cx| {
283 project.diagnostic_summary(false, cx)
284 })?;
285
286 diagnostics_before = query_lsp_diagnostics(project.clone(), cx).await?;
287 if diagnostics_before.is_some() && language_server.allow_preexisting_diagnostics {
288 return Err(anyhow!("Example has pre-existing diagnostics. If you want to run this example regardless, set `allow_preexisting_diagnostics` to `true` in `base.toml`"));
289 }
290
291 Some(LanguageServerState {
292 _lsp_open_handle: lsp_open_handle,
293 language_file_buffer,
294 })
295 } else {
296 None
297 };
298
299 if std::env::var("ZED_EVAL_SETUP_ONLY").is_ok() {
300 return Err(anyhow!("Setup only mode"));
301 }
302
303 let last_diff_file_path = this.run_directory.join("last.diff");
304
305 // Write an empty "last.diff" so that it can be opened in Zed for convenient view of the
306 // history using undo/redo.
307 std::fs::write(&last_diff_file_path, "")?;
308
309 let thread_store = thread_store.await?;
310
311 let profile_id = meta.profile_id.clone();
312 thread_store.update(cx, |thread_store, cx| thread_store.load_profile_by_id(profile_id, cx)).expect("Failed to load profile");
313
314 let thread =
315 thread_store.update(cx, |thread_store, cx| thread_store.create_thread(cx))?;
316
317
318 thread.update(cx, |thread, _cx| {
319 let mut request_count = 0;
320 let previous_diff = Rc::new(RefCell::new("".to_string()));
321 let example_output_dir = this.run_directory.clone();
322 let last_diff_file_path = last_diff_file_path.clone();
323 let messages_json_file_path = example_output_dir.join("last.messages.json");
324 let this = this.clone();
325 thread.set_request_callback(move |request, response_events| {
326 request_count += 1;
327 let messages_file_path = example_output_dir.join(format!("{request_count}.messages.md"));
328 let diff_file_path = example_output_dir.join(format!("{request_count}.diff"));
329 let last_messages_file_path = example_output_dir.join("last.messages.md");
330 let request_markdown = RequestMarkdown::new(request);
331 let response_events_markdown = response_events_to_markdown(response_events);
332 let dialog = ThreadDialog::new(request, response_events);
333 let dialog_json = serde_json::to_string_pretty(&dialog.to_combined_request()).unwrap_or_default();
334
335 let messages = format!("{}\n\n{}", request_markdown.messages, response_events_markdown);
336 fs::write(&messages_file_path, messages.clone()).expect("failed to write messages file");
337 fs::write(&last_messages_file_path, messages).expect("failed to write last messages file");
338 fs::write(&messages_json_file_path, dialog_json).expect("failed to write last.messages.json");
339
340 let diff_result = smol::block_on(this.repository_diff());
341 match diff_result {
342 Ok(diff) => {
343 if diff != previous_diff.borrow().clone() {
344 fs::write(&diff_file_path, &diff).expect("failed to write diff file");
345 fs::write(&last_diff_file_path, &diff).expect("failed to write last diff file");
346 *previous_diff.borrow_mut() = diff;
347 }
348 }
349 Err(err) => {
350 let error_message = format!("{err:?}");
351 fs::write(&diff_file_path, &error_message).expect("failed to write diff error to file");
352 fs::write(&last_diff_file_path, &error_message).expect("failed to write last diff file");
353 }
354 }
355
356 if request_count == 1 {
357 let tools_file_path = example_output_dir.join("tools.md");
358 fs::write(tools_file_path, request_markdown.tools).expect("failed to write tools file");
359 }
360 });
361 })?;
362
363 let mut example_cx = ExampleContext::new(meta.clone(), this.log_prefix.clone(), thread.clone(), model.clone(), cx.clone());
364 let result = this.thread.conversation(&mut example_cx).await;
365
366 if let Err(err) = result {
367 if !err.is::<FailedAssertion>() {
368 return Err(err);
369 }
370 }
371
372 println!("{}Stopped", this.log_prefix);
373
374 println!("{}Getting repository diff", this.log_prefix);
375 let repository_diff = this.repository_diff().await?;
376
377 std::fs::write(last_diff_file_path, &repository_diff)?;
378
379
380 let mut diagnostics_after = None;
381 let mut diagnostic_summary_after = Default::default();
382
383 if let Some(language_server_state) = lsp {
384 wait_for_lang_server(&project, &language_server_state.language_file_buffer, this.log_prefix.clone(), cx).await?;
385
386 println!("{}Getting diagnostics", this.log_prefix);
387 diagnostics_after = cx
388 .update(|cx| {
389 let project = project.clone();
390 cx.spawn(async move |cx| query_lsp_diagnostics(project, cx).await)
391 })?
392 .await?;
393 println!("{}Got diagnostics", this.log_prefix);
394
395 diagnostic_summary_after = project.read_with(cx, |project, cx| {
396 project.diagnostic_summary(false, cx)
397 })?;
398
399 }
400
401 if let Some(diagnostics_before) = &diagnostics_before {
402 fs::write(this.run_directory.join("diagnostics_before.txt"), diagnostics_before)?;
403 }
404
405 if let Some(diagnostics_after) = &diagnostics_after {
406 fs::write(this.run_directory.join("diagnostics_after.txt"), diagnostics_after)?;
407 }
408
409 thread.update(cx, |thread, _cx| {
410 let response_count = thread
411 .messages()
412 .filter(|message| message.role == language_model::Role::Assistant)
413 .count();
414 RunOutput {
415 repository_diff,
416 diagnostic_summary_before,
417 diagnostic_summary_after,
418 diagnostics_before,
419 diagnostics_after,
420 response_count,
421 token_usage: thread.cumulative_token_usage(),
422 tool_metrics: example_cx.tool_metrics.lock().unwrap().clone(),
423 all_messages: messages_to_markdown(thread.messages()),
424 programmatic_assertions: example_cx.assertions,
425 }
426 })
427 })
428 }
429
430 async fn repository_diff(&self) -> Result<String> {
431 let worktree_path = self.worktree_path();
432 run_git(&worktree_path, &["add", "."]).await?;
433 let mut diff_args = vec!["diff", "--staged"];
434 if self.thread.meta().url == ZED_REPO_URL {
435 diff_args.push(":(exclude).rules");
436 }
437 run_git(&worktree_path, &diff_args).await
438 }
439
440 pub async fn judge(
441 &self,
442 model: Arc<dyn LanguageModel>,
443 run_output: &RunOutput,
444 cx: &AsyncApp,
445 ) -> JudgeOutput {
446 let mut output_file =
447 File::create(self.run_directory.join("judge.md")).expect("failed to create judge.md");
448
449 let diff_task = self.judge_diff(model.clone(), &run_output, cx);
450 let thread_task = self.judge_thread(model.clone(), &run_output, cx);
451
452 let (diff_result, thread_result) = futures::join!(diff_task, thread_task);
453
454 let (diff_response, diff_output) = diff_result;
455 let (thread_response, thread_output) = thread_result;
456
457 writeln!(
458 &mut output_file,
459 "# Judgment\n\n## Thread\n\n{thread_response}\n\n## Diff\n\n{diff_response}",
460 )
461 .log_err();
462
463 JudgeOutput {
464 thread: thread_output,
465 diff: diff_output,
466 }
467 }
468
469 async fn judge_diff(
470 &self,
471 model: Arc<dyn LanguageModel>,
472 run_output: &RunOutput,
473 cx: &AsyncApp,
474 ) -> (String, AssertionsReport) {
475 let diff_assertions = self.thread.diff_assertions();
476
477 if diff_assertions.is_empty() {
478 return (
479 "No diff assertions".to_string(),
480 AssertionsReport::default(),
481 );
482 }
483
484 println!("{}Running diff judge", self.log_prefix);
485
486 let judge_diff_prompt = include_str!("judge_diff_prompt.hbs");
487 let judge_diff_prompt_name = "judge_diff_prompt";
488 let mut hbs = Handlebars::new();
489 hbs.register_template_string(judge_diff_prompt_name, judge_diff_prompt)
490 .unwrap();
491
492 let to_prompt = |assertion: String| {
493 hbs.render(
494 judge_diff_prompt_name,
495 &JudgeDiffInput {
496 repository_diff: run_output.repository_diff.clone(),
497 assertion,
498 },
499 )
500 .unwrap()
501 };
502
503 let (responses, report) = self
504 .judge_assertions(model, diff_assertions, to_prompt, cx)
505 .await;
506
507 println!(
508 "{}Judge - Diff score: {}%",
509 self.log_prefix,
510 report.passed_percentage()
511 );
512
513 (responses, report)
514 }
515
516 async fn judge_thread(
517 &self,
518 model: Arc<dyn LanguageModel>,
519 run_output: &RunOutput,
520 cx: &AsyncApp,
521 ) -> (String, AssertionsReport) {
522 let thread_assertions = self.thread.thread_assertions();
523
524 if thread_assertions.is_empty() {
525 return (
526 "No thread assertions".to_string(),
527 AssertionsReport::default(),
528 );
529 }
530
531 let judge_thread_prompt = include_str!("judge_thread_prompt.hbs");
532 let judge_thread_prompt_name = "judge_thread_prompt";
533 let mut hbs = Handlebars::new();
534 hbs.register_template_string(judge_thread_prompt_name, judge_thread_prompt)
535 .unwrap();
536
537 let complete_messages = &run_output.all_messages;
538 let to_prompt = |assertion: String| {
539 hbs.render(
540 judge_thread_prompt_name,
541 &JudgeThreadInput {
542 messages: complete_messages.clone(),
543 assertion,
544 },
545 )
546 .unwrap()
547 };
548
549 let (responses, report) = self
550 .judge_assertions(model, thread_assertions, to_prompt, cx)
551 .await;
552
553 println!(
554 "{}Judge - Thread score: {}%",
555 self.log_prefix,
556 report.passed_percentage()
557 );
558
559 (responses, report)
560 }
561
562 async fn judge_assertions(
563 &self,
564 model: Arc<dyn LanguageModel>,
565 assertions: Vec<JudgeAssertion>,
566 to_prompt: impl Fn(String) -> String,
567 cx: &AsyncApp,
568 ) -> (String, AssertionsReport) {
569 let assertions = assertions.into_iter().map(|assertion| {
570 let request = LanguageModelRequest {
571 thread_id: None,
572 prompt_id: None,
573 mode: None,
574 messages: vec![LanguageModelRequestMessage {
575 role: Role::User,
576 content: vec![MessageContent::Text(to_prompt(assertion.description))],
577 cache: false,
578 }],
579 temperature: None,
580 tools: Vec::new(),
581 tool_choice: None,
582 stop: Vec::new(),
583 };
584
585 let model = model.clone();
586 let log_prefix = self.log_prefix.clone();
587 async move {
588 let response = send_language_model_request(model, request, cx).await;
589
590 let (response, result) = match response {
591 Ok(response) => (
592 response.clone(),
593 parse_assertion_result(&response).map_err(|err| err.to_string()),
594 ),
595 Err(err) => (err.to_string(), Err(err.to_string())),
596 };
597
598 if result.is_ok() {
599 println!("{}✅ {}", log_prefix, assertion.id);
600 } else {
601 println!("{}❌ {}", log_prefix, assertion.id);
602 }
603
604 (
605 response,
606 RanAssertion {
607 id: assertion.id,
608 result,
609 },
610 )
611 }
612 });
613
614 let mut responses = String::new();
615 let mut report = AssertionsReport::default();
616
617 for (response, assertion) in future::join_all(assertions).await {
618 writeln!(&mut responses, "# {}", assertion.id).unwrap();
619 writeln!(&mut responses, "{}\n\n", response).unwrap();
620 report.ran.push(assertion);
621 }
622
623 (responses, report)
624 }
625}
626
627pub fn wait_for_lang_server(
628 project: &Entity<Project>,
629 buffer: &Entity<Buffer>,
630 log_prefix: String,
631 cx: &mut AsyncApp,
632) -> Task<Result<()>> {
633 if std::env::var("ZED_EVAL_SKIP_LS").is_ok() {
634 return Task::ready(Ok(()));
635 }
636
637 println!("{}⏵ Waiting for language server", log_prefix);
638
639 let (mut tx, mut rx) = mpsc::channel(1);
640
641 let lsp_store = project
642 .update(cx, |project, _| project.lsp_store())
643 .unwrap();
644
645 let has_lang_server = buffer
646 .update(cx, |buffer, cx| {
647 lsp_store.update(cx, |lsp_store, cx| {
648 lsp_store
649 .language_servers_for_local_buffer(&buffer, cx)
650 .next()
651 .is_some()
652 })
653 })
654 .unwrap_or(false);
655
656 if has_lang_server {
657 project
658 .update(cx, |project, cx| project.save_buffer(buffer.clone(), cx))
659 .unwrap()
660 .detach();
661 }
662
663 let subscriptions =
664 [
665 cx.subscribe(&lsp_store, {
666 let log_prefix = log_prefix.clone();
667 move |_, event, _| match event {
668 project::LspStoreEvent::LanguageServerUpdate {
669 message:
670 client::proto::update_language_server::Variant::WorkProgress(
671 LspWorkProgress {
672 message: Some(message),
673 ..
674 },
675 ),
676 ..
677 } => println!("{}⟲ {message}", log_prefix),
678 _ => {}
679 }
680 }),
681 cx.subscribe(&project, {
682 let buffer = buffer.clone();
683 move |project, event, cx| match event {
684 project::Event::LanguageServerAdded(_, _, _) => {
685 let buffer = buffer.clone();
686 project
687 .update(cx, |project, cx| project.save_buffer(buffer, cx))
688 .detach();
689 }
690 project::Event::DiskBasedDiagnosticsFinished { .. } => {
691 tx.try_send(()).ok();
692 }
693 _ => {}
694 }
695 }),
696 ];
697
698 cx.spawn(async move |cx| {
699 let timeout = cx.background_executor().timer(Duration::new(60 * 5, 0));
700 let result = futures::select! {
701 _ = rx.next() => {
702 println!("{}⚑ Language server idle", log_prefix);
703 anyhow::Ok(())
704 },
705 _ = timeout.fuse() => {
706 Err(anyhow!("LSP wait timed out after 5 minutes"))
707 }
708 };
709 drop(subscriptions);
710 result
711 })
712}
713
714pub async fn query_lsp_diagnostics(
715 project: Entity<Project>,
716 cx: &mut AsyncApp,
717) -> Result<Option<String>> {
718 let paths_with_diagnostics = project.update(cx, |project, cx| {
719 project
720 .diagnostic_summaries(true, cx)
721 .filter(|(_, _, summary)| summary.error_count > 0 || summary.warning_count > 0)
722 .map(|(project_path, _, _)| project_path)
723 .collect::<Vec<_>>()
724 })?;
725
726 if paths_with_diagnostics.is_empty() {
727 return Ok(None);
728 }
729
730 let mut output = String::new();
731 for project_path in paths_with_diagnostics {
732 let buffer = project
733 .update(cx, |project, cx| project.open_buffer(project_path, cx))?
734 .await?;
735 let snapshot = buffer.read_with(cx, |buffer, _cx| buffer.snapshot())?;
736
737 for (_, group) in snapshot.diagnostic_groups(None) {
738 let entry = &group.entries[group.primary_ix];
739 let range = entry.range.to_point(&snapshot);
740 let severity = match entry.diagnostic.severity {
741 DiagnosticSeverity::ERROR => "error",
742 DiagnosticSeverity::WARNING => "warning",
743 _ => continue,
744 };
745
746 writeln!(
747 output,
748 "{} at line {}: {}",
749 severity,
750 range.start.row + 1,
751 entry.diagnostic.message
752 )?;
753 }
754 }
755 anyhow::Ok(Some(output))
756}
757
758fn parse_assertion_result(response: &str) -> Result<RanAssertionResult> {
759 let analysis = get_tag("analysis", response)?.to_string();
760 let passed = match get_tag("passed", response)?.to_lowercase().as_str() {
761 "true" => true,
762 "false" => false,
763 value @ _ => bail!("invalid judge `passed` tag: {value}"),
764 };
765 Ok(RanAssertionResult {
766 analysis: Some(analysis),
767 passed,
768 })
769}
770
771fn get_tag(name: &'static str, response: &str) -> Result<String> {
772 let start_tag = format!("<{}>", name);
773 let end_tag = format!("</{}>", name);
774
775 let start_ix = response
776 .find(&start_tag)
777 .context(format!("{} start tag not found", name))?;
778 let content_start_ix = start_ix + start_tag.len();
779
780 let end_ix = content_start_ix
781 + response[content_start_ix..]
782 .find(&end_tag)
783 .context(format!("{} end tag not found", name))?;
784
785 let content = response[content_start_ix..end_ix].trim().unindent();
786
787 anyhow::Ok(content)
788}
789
790pub fn repo_path_for_url(repos_dir: &Path, repo_url: &str) -> PathBuf {
791 let repo_name = repo_url
792 .trim_start_matches("https://")
793 .replace(|c: char| !c.is_alphanumeric(), "-");
794 Path::new(repos_dir).join(repo_name)
795}
796
797pub async fn run_git(repo_path: &Path, args: &[&str]) -> Result<String> {
798 let output = new_smol_command("git")
799 .current_dir(repo_path)
800 .args(args)
801 .output()
802 .await?;
803
804 if output.status.success() {
805 Ok(String::from_utf8(output.stdout)?.trim().to_string())
806 } else {
807 Err(anyhow!(
808 "`git {}` within `{}` failed with status: {}\nstderr:\n{}\nstdout:\n{}",
809 args.join(" "),
810 repo_path.display(),
811 output.status,
812 String::from_utf8_lossy(&output.stderr),
813 String::from_utf8_lossy(&output.stdout),
814 ))
815 }
816}
817
818fn messages_to_markdown<'a>(message_iter: impl IntoIterator<Item = &'a Message>) -> String {
819 let mut messages = String::new();
820 let mut assistant_message_number: u32 = 1;
821
822 for message in message_iter {
823 push_role(&message.role, &mut messages, &mut assistant_message_number);
824
825 for segment in &message.segments {
826 match segment {
827 MessageSegment::Text(text) => {
828 messages.push_str(&text);
829 messages.push_str("\n\n");
830 }
831 MessageSegment::Thinking { text, signature } => {
832 messages.push_str("**Thinking**:\n\n");
833 if let Some(sig) = signature {
834 messages.push_str(&format!("Signature: {}\n\n", sig));
835 }
836 messages.push_str(&text);
837 messages.push_str("\n");
838 }
839 MessageSegment::RedactedThinking(items) => {
840 messages.push_str(&format!(
841 "**Redacted Thinking**: {} item(s)\n\n",
842 items.len()
843 ));
844 }
845 }
846 }
847 }
848
849 messages
850}
851
852fn push_role(role: &Role, buf: &mut String, assistant_message_number: &mut u32) {
853 match role {
854 Role::System => buf.push_str("# ⚙️ SYSTEM\n\n"),
855 Role::User => buf.push_str("# 👤 USER\n\n"),
856 Role::Assistant => {
857 buf.push_str(&format!("# 🤖 ASSISTANT {assistant_message_number}\n\n"));
858 *assistant_message_number = *assistant_message_number + 1;
859 }
860 }
861}
862
863pub async fn send_language_model_request(
864 model: Arc<dyn LanguageModel>,
865 request: LanguageModelRequest,
866 cx: &AsyncApp,
867) -> anyhow::Result<String> {
868 match model.stream_completion_text(request, &cx).await {
869 Ok(mut stream) => {
870 let mut full_response = String::new();
871 while let Some(chunk_result) = stream.stream.next().await {
872 match chunk_result {
873 Ok(chunk_str) => {
874 full_response.push_str(&chunk_str);
875 }
876 Err(err) => {
877 return Err(anyhow!(
878 "Error receiving response from language model: {err}"
879 ));
880 }
881 }
882 }
883 Ok(full_response)
884 }
885 Err(err) => Err(anyhow!(
886 "Failed to get response from language model. Error was: {err}"
887 )),
888 }
889}
890
891pub struct RequestMarkdown {
892 pub tools: String,
893 pub messages: String,
894}
895
896impl RequestMarkdown {
897 pub fn new(request: &LanguageModelRequest) -> Self {
898 let mut tools = String::new();
899 let mut messages = String::new();
900 let mut assistant_message_number: u32 = 1;
901
902 // Print the tools
903 if !request.tools.is_empty() {
904 for tool in &request.tools {
905 write!(&mut tools, "# {}\n\n", tool.name).unwrap();
906 write!(&mut tools, "{}\n\n", tool.description).unwrap();
907 write!(
908 &mut tools,
909 "{}\n",
910 MarkdownCodeBlock {
911 tag: "json",
912 text: &format!("{:#}", tool.input_schema)
913 }
914 )
915 .unwrap();
916 }
917 }
918
919 // Print the messages
920 for message in &request.messages {
921 push_role(&message.role, &mut messages, &mut assistant_message_number);
922
923 for content in &message.content {
924 match content {
925 MessageContent::Text(text) => {
926 messages.push_str(text);
927 messages.push_str("\n\n");
928 }
929 MessageContent::Image(_) => {
930 messages.push_str("[IMAGE DATA]\n\n");
931 }
932 MessageContent::Thinking { text, signature } => {
933 messages.push_str("**Thinking**:\n\n");
934 if let Some(sig) = signature {
935 messages.push_str(&format!("Signature: {}\n\n", sig));
936 }
937 messages.push_str(text);
938 messages.push_str("\n");
939 }
940 MessageContent::RedactedThinking(items) => {
941 messages.push_str(&format!(
942 "**Redacted Thinking**: {} item(s)\n\n",
943 items.len()
944 ));
945 }
946 MessageContent::ToolUse(tool_use) => {
947 messages.push_str(&format!(
948 "**Tool Use**: {} (ID: {})\n",
949 tool_use.name, tool_use.id
950 ));
951 messages.push_str(&format!(
952 "{}\n",
953 MarkdownCodeBlock {
954 tag: "json",
955 text: &format!("{:#}", tool_use.input)
956 }
957 ));
958 }
959 MessageContent::ToolResult(tool_result) => {
960 messages.push_str(&format!(
961 "**Tool Result**: {} (ID: {})\n\n",
962 tool_result.tool_name, tool_result.tool_use_id
963 ));
964 if tool_result.is_error {
965 messages.push_str("**ERROR:**\n");
966 }
967 messages.push_str(&format!("{}\n\n", tool_result.content));
968
969 if let Some(output) = tool_result.output.as_ref() {
970 writeln!(
971 messages,
972 "**Debug Output**:\n\n```json\n{}\n```\n",
973 serde_json::to_string_pretty(output).unwrap()
974 )
975 .unwrap();
976 }
977 }
978 }
979 }
980 }
981
982 Self { tools, messages }
983 }
984}
985
986pub fn response_events_to_markdown(
987 response_events: &[std::result::Result<LanguageModelCompletionEvent, String>],
988) -> String {
989 let mut response = String::new();
990 // Print the response events if any
991 response.push_str("# Response\n\n");
992 let mut text_buffer = String::new();
993 let mut thinking_buffer = String::new();
994
995 let flush_buffers =
996 |output: &mut String, text_buffer: &mut String, thinking_buffer: &mut String| {
997 if !text_buffer.is_empty() {
998 output.push_str(&format!("**Text**:\n{}\n\n", text_buffer));
999 text_buffer.clear();
1000 }
1001 if !thinking_buffer.is_empty() {
1002 output.push_str(&format!("**Thinking**:\n{}\n\n", thinking_buffer));
1003 thinking_buffer.clear();
1004 }
1005 };
1006
1007 for event in response_events {
1008 match event {
1009 Ok(LanguageModelCompletionEvent::Text(text)) => {
1010 text_buffer.push_str(text);
1011 }
1012 Ok(LanguageModelCompletionEvent::Thinking { text, .. }) => {
1013 thinking_buffer.push_str(text);
1014 }
1015 Ok(LanguageModelCompletionEvent::Stop(reason)) => {
1016 flush_buffers(&mut response, &mut text_buffer, &mut thinking_buffer);
1017 response.push_str(&format!("**Stop**: {:?}\n\n", reason));
1018 }
1019 Ok(LanguageModelCompletionEvent::ToolUse(tool_use)) => {
1020 flush_buffers(&mut response, &mut text_buffer, &mut thinking_buffer);
1021 response.push_str(&format!(
1022 "**Tool Use**: {} (ID: {})\n",
1023 tool_use.name, tool_use.id
1024 ));
1025 response.push_str(&format!(
1026 "{}\n",
1027 MarkdownCodeBlock {
1028 tag: "json",
1029 text: &format!("{:#}", tool_use.input)
1030 }
1031 ));
1032 }
1033 Ok(
1034 LanguageModelCompletionEvent::UsageUpdate(_)
1035 | LanguageModelCompletionEvent::StartMessage { .. }
1036 | LanguageModelCompletionEvent::StatusUpdate { .. },
1037 ) => {}
1038 Err(error) => {
1039 flush_buffers(&mut response, &mut text_buffer, &mut thinking_buffer);
1040 response.push_str(&format!("**Error**: {}\n\n", error));
1041 }
1042 }
1043 }
1044
1045 flush_buffers(&mut response, &mut text_buffer, &mut thinking_buffer);
1046
1047 response
1048}
1049
1050#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
1051pub struct ThreadDialog {
1052 pub request: LanguageModelRequest,
1053 pub response_events: Vec<std::result::Result<LanguageModelCompletionEvent, String>>,
1054}
1055
1056impl ThreadDialog {
1057 pub fn new(
1058 request: &LanguageModelRequest,
1059 response_events: &[std::result::Result<LanguageModelCompletionEvent, String>],
1060 ) -> Self {
1061 Self {
1062 request: request.clone(),
1063 response_events: response_events.to_vec(),
1064 }
1065 }
1066
1067 /// Represents all request and response messages in a unified format.
1068 ///
1069 /// Specifically, it appends the assistant's response (derived from response events)
1070 /// as a new message to existing messages in the request.
1071 pub fn to_combined_request(&self) -> LanguageModelRequest {
1072 let mut request = self.request.clone();
1073 if let Some(assistant_message) = self.response_events_to_message() {
1074 request.messages.push(assistant_message);
1075 }
1076 request
1077 }
1078 fn response_events_to_message(&self) -> Option<LanguageModelRequestMessage> {
1079 let response_events = &self.response_events;
1080 let mut content: Vec<MessageContent> = Vec::new();
1081 let mut current_text = String::new();
1082
1083 let flush_text = |text: &mut String, content: &mut Vec<MessageContent>| {
1084 if !text.is_empty() {
1085 content.push(MessageContent::Text(std::mem::take(text)));
1086 }
1087 };
1088
1089 for event in response_events {
1090 match event {
1091 Ok(LanguageModelCompletionEvent::Text(text)) => {
1092 current_text.push_str(text);
1093 }
1094
1095 Ok(LanguageModelCompletionEvent::ToolUse(tool_use)) => {
1096 flush_text(&mut current_text, &mut content);
1097 if tool_use.is_input_complete {
1098 content.push(MessageContent::ToolUse(tool_use.clone()));
1099 }
1100 }
1101 Ok(LanguageModelCompletionEvent::Thinking { text, signature }) => {
1102 flush_text(&mut current_text, &mut content);
1103 content.push(MessageContent::Thinking {
1104 text: text.clone(),
1105 signature: signature.clone(),
1106 });
1107 }
1108
1109 // Skip these
1110 Ok(LanguageModelCompletionEvent::UsageUpdate(_))
1111 | Ok(LanguageModelCompletionEvent::StatusUpdate { .. })
1112 | Ok(LanguageModelCompletionEvent::StartMessage { .. })
1113 | Ok(LanguageModelCompletionEvent::Stop(_)) => {}
1114
1115 Err(error) => {
1116 flush_text(&mut current_text, &mut content);
1117 content.push(MessageContent::Text(format!("ERROR: {}", error)));
1118 }
1119 }
1120 }
1121
1122 flush_text(&mut current_text, &mut content);
1123
1124 if !content.is_empty() {
1125 Some(LanguageModelRequestMessage {
1126 role: Role::Assistant,
1127 content,
1128 cache: false,
1129 })
1130 } else {
1131 None
1132 }
1133 }
1134}
1135
1136#[cfg(test)]
1137mod test {
1138 use super::*;
1139
1140 #[test]
1141 fn test_parse_judge_output() {
1142 let response = r#"
1143 <analysis>The model did a good job but there were still compilations errors.</analysis>
1144 <passed>true</passed>
1145 "#
1146 .unindent();
1147
1148 let output = parse_assertion_result(&response).unwrap();
1149 assert_eq!(
1150 output.analysis,
1151 Some("The model did a good job but there were still compilations errors.".into())
1152 );
1153 assert_eq!(output.passed, true);
1154
1155 let response = r#"
1156 Text around ignored
1157
1158 <analysis>
1159 Failed to compile:
1160 - Error 1
1161 - Error 2
1162 </analysis>
1163
1164 <passed>false</passed>
1165 "#
1166 .unindent();
1167
1168 let output = parse_assertion_result(&response).unwrap();
1169 assert_eq!(
1170 output.analysis,
1171 Some("Failed to compile:\n- Error 1\n- Error 2".into())
1172 );
1173 assert_eq!(output.passed, false);
1174 }
1175}