1use agent::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 last_request: LanguageModelRequest,
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 let thread =
311 thread_store.update(cx, |thread_store, cx| thread_store.create_thread(cx))?;
312 let last_request = Rc::new(RefCell::new(None));
313
314 thread.update(cx, |thread, _cx| {
315 let mut request_count = 0;
316 let last_request = Rc::clone(&last_request);
317 let previous_diff = Rc::new(RefCell::new("".to_string()));
318 let example_output_dir = this.run_directory.clone();
319 let last_diff_file_path = last_diff_file_path.clone();
320 let messages_json_file_path = example_output_dir.join("last.messages.json");
321 let this = this.clone();
322 thread.set_request_callback(move |request, response_events| {
323 *last_request.borrow_mut() = Some(request.clone());
324
325 request_count += 1;
326 let messages_file_path = example_output_dir.join(format!("{request_count}.messages.md"));
327 let diff_file_path = example_output_dir.join(format!("{request_count}.diff"));
328 let last_messages_file_path = example_output_dir.join("last.messages.md");
329 let request_markdown = RequestMarkdown::new(request);
330 let response_events_markdown = response_events_to_markdown(response_events);
331 let dialog = ThreadDialog::new(request, response_events);
332 let dialog_json = serde_json::to_string_pretty(&dialog.to_combined_request()).unwrap_or_default();
333
334 let messages = format!("{}\n\n{}", request_markdown.messages, response_events_markdown);
335 fs::write(&messages_file_path, messages.clone()).expect("failed to write messages file");
336 fs::write(&last_messages_file_path, messages).expect("failed to write last messages file");
337 fs::write(&messages_json_file_path, dialog_json).expect("failed to write last.messages.json");
338
339 let diff_result = smol::block_on(this.repository_diff());
340 match diff_result {
341 Ok(diff) => {
342 if diff != previous_diff.borrow().clone() {
343 fs::write(&diff_file_path, &diff).expect("failed to write diff file");
344 fs::write(&last_diff_file_path, &diff).expect("failed to write last diff file");
345 *previous_diff.borrow_mut() = diff;
346 }
347 }
348 Err(err) => {
349 let error_message = format!("{err:?}");
350 fs::write(&diff_file_path, &error_message).expect("failed to write diff error to file");
351 fs::write(&last_diff_file_path, &error_message).expect("failed to write last diff file");
352 }
353 }
354
355 if request_count == 1 {
356 let tools_file_path = example_output_dir.join("tools.md");
357 fs::write(tools_file_path, request_markdown.tools).expect("failed to write tools file");
358 }
359 });
360 })?;
361
362 let mut example_cx = ExampleContext::new(meta.clone(), this.log_prefix.clone(), thread.clone(), model.clone(), cx.clone());
363 let result = this.thread.conversation(&mut example_cx).await;
364
365 if let Err(err) = result {
366 if !err.is::<FailedAssertion>() {
367 return Err(err);
368 }
369 }
370
371 println!("{}Stopped", this.log_prefix);
372
373 println!("{}Getting repository diff", this.log_prefix);
374 let repository_diff = this.repository_diff().await?;
375
376 std::fs::write(last_diff_file_path, &repository_diff)?;
377
378
379 let mut diagnostics_after = None;
380 let mut diagnostic_summary_after = Default::default();
381
382 if let Some(language_server_state) = lsp {
383 wait_for_lang_server(&project, &language_server_state.language_file_buffer, this.log_prefix.clone(), cx).await?;
384
385 println!("{}Getting diagnostics", this.log_prefix);
386 diagnostics_after = cx
387 .update(|cx| {
388 let project = project.clone();
389 cx.spawn(async move |cx| query_lsp_diagnostics(project, cx).await)
390 })?
391 .await?;
392 println!("{}Got diagnostics", this.log_prefix);
393
394 diagnostic_summary_after = project.read_with(cx, |project, cx| {
395 project.diagnostic_summary(false, cx)
396 })?;
397
398 }
399
400 let Some(last_request) = last_request.borrow_mut().take() else {
401 return Err(anyhow!("No requests ran."));
402 };
403
404 if let Some(diagnostics_before) = &diagnostics_before {
405 fs::write(this.run_directory.join("diagnostics_before.txt"), diagnostics_before)?;
406 }
407
408 if let Some(diagnostics_after) = &diagnostics_after {
409 fs::write(this.run_directory.join("diagnostics_after.txt"), diagnostics_after)?;
410 }
411
412 thread.update(cx, |thread, _cx| {
413 let response_count = thread
414 .messages()
415 .filter(|message| message.role == language_model::Role::Assistant)
416 .count();
417 RunOutput {
418 repository_diff,
419 diagnostic_summary_before,
420 diagnostic_summary_after,
421 diagnostics_before,
422 diagnostics_after,
423 response_count,
424 token_usage: thread.cumulative_token_usage(),
425 tool_metrics: example_cx.tool_metrics.lock().unwrap().clone(),
426 last_request,
427 programmatic_assertions: example_cx.assertions,
428 }
429 })
430 })
431 }
432
433 async fn repository_diff(&self) -> Result<String> {
434 let worktree_path = self.worktree_path();
435 run_git(&worktree_path, &["add", "."]).await?;
436 let mut diff_args = vec!["diff", "--staged"];
437 if self.thread.meta().url == ZED_REPO_URL {
438 diff_args.push(":(exclude).rules");
439 }
440 run_git(&worktree_path, &diff_args).await
441 }
442
443 pub async fn judge(
444 &self,
445 model: Arc<dyn LanguageModel>,
446 run_output: &RunOutput,
447 cx: &AsyncApp,
448 ) -> JudgeOutput {
449 let mut output_file =
450 File::create(self.run_directory.join("judge.md")).expect("failed to create judge.md");
451
452 let diff_task = self.judge_diff(model.clone(), &run_output, cx);
453 let thread_task = self.judge_thread(model.clone(), &run_output, cx);
454
455 let (diff_result, thread_result) = futures::join!(diff_task, thread_task);
456
457 let (diff_response, diff_output) = diff_result;
458 let (thread_response, thread_output) = thread_result;
459
460 writeln!(
461 &mut output_file,
462 "# Judgment\n\n## Thread\n\n{thread_response}\n\n## Diff\n\n{diff_response}",
463 )
464 .log_err();
465
466 JudgeOutput {
467 thread: thread_output,
468 diff: diff_output,
469 }
470 }
471
472 async fn judge_diff(
473 &self,
474 model: Arc<dyn LanguageModel>,
475 run_output: &RunOutput,
476 cx: &AsyncApp,
477 ) -> (String, AssertionsReport) {
478 let diff_assertions = self.thread.diff_assertions();
479
480 if diff_assertions.is_empty() {
481 return (
482 "No diff assertions".to_string(),
483 AssertionsReport::default(),
484 );
485 }
486
487 println!("{}Running diff judge", self.log_prefix);
488
489 let judge_diff_prompt = include_str!("judge_diff_prompt.hbs");
490 let judge_diff_prompt_name = "judge_diff_prompt";
491 let mut hbs = Handlebars::new();
492 hbs.register_template_string(judge_diff_prompt_name, judge_diff_prompt)
493 .unwrap();
494
495 let to_prompt = |assertion: String| {
496 hbs.render(
497 judge_diff_prompt_name,
498 &JudgeDiffInput {
499 repository_diff: run_output.repository_diff.clone(),
500 assertion,
501 },
502 )
503 .unwrap()
504 };
505
506 let (responses, report) = self
507 .judge_assertions(model, diff_assertions, to_prompt, cx)
508 .await;
509
510 println!(
511 "{}Judge - Diff score: {}%",
512 self.log_prefix,
513 report.passed_percentage()
514 );
515
516 (responses, report)
517 }
518
519 async fn judge_thread(
520 &self,
521 model: Arc<dyn LanguageModel>,
522 run_output: &RunOutput,
523 cx: &AsyncApp,
524 ) -> (String, AssertionsReport) {
525 let thread_assertions = self.thread.thread_assertions();
526
527 if thread_assertions.is_empty() {
528 return (
529 "No diff assertions".to_string(),
530 AssertionsReport::default(),
531 );
532 }
533
534 let judge_thread_prompt = include_str!("judge_thread_prompt.hbs");
535 let judge_diff_prompt_name = "judge_thread_prompt";
536 let mut hbs = Handlebars::new();
537 hbs.register_template_string(judge_diff_prompt_name, judge_thread_prompt)
538 .unwrap();
539
540 let request_markdown = RequestMarkdown::new(&run_output.last_request);
541 let to_prompt = |assertion: String| {
542 hbs.render(
543 judge_diff_prompt_name,
544 &JudgeThreadInput {
545 messages: request_markdown.messages.clone(),
546 assertion,
547 },
548 )
549 .unwrap()
550 };
551
552 let (responses, report) = self
553 .judge_assertions(model, thread_assertions, to_prompt, cx)
554 .await;
555
556 println!(
557 "{}Judge - Thread score: {}%",
558 self.log_prefix,
559 report.passed_percentage()
560 );
561
562 (responses, report)
563 }
564
565 async fn judge_assertions(
566 &self,
567 model: Arc<dyn LanguageModel>,
568 assertions: Vec<JudgeAssertion>,
569 to_prompt: impl Fn(String) -> String,
570 cx: &AsyncApp,
571 ) -> (String, AssertionsReport) {
572 let assertions = assertions.into_iter().map(|assertion| {
573 let request = LanguageModelRequest {
574 thread_id: None,
575 prompt_id: None,
576 mode: None,
577 messages: vec![LanguageModelRequestMessage {
578 role: Role::User,
579 content: vec![MessageContent::Text(to_prompt(assertion.description))],
580 cache: false,
581 }],
582 temperature: None,
583 tools: Vec::new(),
584 stop: Vec::new(),
585 };
586
587 let model = model.clone();
588 let log_prefix = self.log_prefix.clone();
589 async move {
590 let response = send_language_model_request(model, request, cx).await;
591
592 let (response, result) = match response {
593 Ok(response) => (
594 response.clone(),
595 parse_assertion_result(&response).map_err(|err| err.to_string()),
596 ),
597 Err(err) => (err.to_string(), Err(err.to_string())),
598 };
599
600 if result.is_ok() {
601 println!("{}✅ {}", log_prefix, assertion.id);
602 } else {
603 println!("{}❌ {}", log_prefix, assertion.id);
604 }
605
606 (
607 response,
608 RanAssertion {
609 id: assertion.id,
610 result,
611 },
612 )
613 }
614 });
615
616 let mut responses = String::new();
617 let mut report = AssertionsReport::default();
618
619 for (response, assertion) in future::join_all(assertions).await {
620 writeln!(&mut responses, "# {}", assertion.id).unwrap();
621 writeln!(&mut responses, "{}\n\n", response).unwrap();
622 report.ran.push(assertion);
623 }
624
625 (responses, report)
626 }
627}
628
629pub fn wait_for_lang_server(
630 project: &Entity<Project>,
631 buffer: &Entity<Buffer>,
632 log_prefix: String,
633 cx: &mut AsyncApp,
634) -> Task<Result<()>> {
635 if std::env::var("ZED_EVAL_SKIP_LS").is_ok() {
636 return Task::ready(Ok(()));
637 }
638
639 println!("{}⏵ Waiting for language server", log_prefix);
640
641 let (mut tx, mut rx) = mpsc::channel(1);
642
643 let lsp_store = project
644 .update(cx, |project, _| project.lsp_store())
645 .unwrap();
646
647 let has_lang_server = buffer
648 .update(cx, |buffer, cx| {
649 lsp_store.update(cx, |lsp_store, cx| {
650 lsp_store
651 .language_servers_for_local_buffer(&buffer, cx)
652 .next()
653 .is_some()
654 })
655 })
656 .unwrap_or(false);
657
658 if has_lang_server {
659 project
660 .update(cx, |project, cx| project.save_buffer(buffer.clone(), cx))
661 .unwrap()
662 .detach();
663 }
664
665 let subscriptions =
666 [
667 cx.subscribe(&lsp_store, {
668 let log_prefix = log_prefix.clone();
669 move |_, event, _| match event {
670 project::LspStoreEvent::LanguageServerUpdate {
671 message:
672 client::proto::update_language_server::Variant::WorkProgress(
673 LspWorkProgress {
674 message: Some(message),
675 ..
676 },
677 ),
678 ..
679 } => println!("{}⟲ {message}", log_prefix),
680 _ => {}
681 }
682 }),
683 cx.subscribe(&project, {
684 let buffer = buffer.clone();
685 move |project, event, cx| match event {
686 project::Event::LanguageServerAdded(_, _, _) => {
687 let buffer = buffer.clone();
688 project
689 .update(cx, |project, cx| project.save_buffer(buffer, cx))
690 .detach();
691 }
692 project::Event::DiskBasedDiagnosticsFinished { .. } => {
693 tx.try_send(()).ok();
694 }
695 _ => {}
696 }
697 }),
698 ];
699
700 cx.spawn(async move |cx| {
701 let timeout = cx.background_executor().timer(Duration::new(60 * 5, 0));
702 let result = futures::select! {
703 _ = rx.next() => {
704 println!("{}⚑ Language server idle", log_prefix);
705 anyhow::Ok(())
706 },
707 _ = timeout.fuse() => {
708 Err(anyhow!("LSP wait timed out after 5 minutes"))
709 }
710 };
711 drop(subscriptions);
712 result
713 })
714}
715
716pub async fn query_lsp_diagnostics(
717 project: Entity<Project>,
718 cx: &mut AsyncApp,
719) -> Result<Option<String>> {
720 let paths_with_diagnostics = project.update(cx, |project, cx| {
721 project
722 .diagnostic_summaries(true, cx)
723 .filter(|(_, _, summary)| summary.error_count > 0 || summary.warning_count > 0)
724 .map(|(project_path, _, _)| project_path)
725 .collect::<Vec<_>>()
726 })?;
727
728 if paths_with_diagnostics.is_empty() {
729 return Ok(None);
730 }
731
732 let mut output = String::new();
733 for project_path in paths_with_diagnostics {
734 let buffer = project
735 .update(cx, |project, cx| project.open_buffer(project_path, cx))?
736 .await?;
737 let snapshot = buffer.read_with(cx, |buffer, _cx| buffer.snapshot())?;
738
739 for (_, group) in snapshot.diagnostic_groups(None) {
740 let entry = &group.entries[group.primary_ix];
741 let range = entry.range.to_point(&snapshot);
742 let severity = match entry.diagnostic.severity {
743 DiagnosticSeverity::ERROR => "error",
744 DiagnosticSeverity::WARNING => "warning",
745 _ => continue,
746 };
747
748 writeln!(
749 output,
750 "{} at line {}: {}",
751 severity,
752 range.start.row + 1,
753 entry.diagnostic.message
754 )?;
755 }
756 }
757 anyhow::Ok(Some(output))
758}
759
760fn parse_assertion_result(response: &str) -> Result<RanAssertionResult> {
761 let analysis = get_tag("analysis", response)?.to_string();
762 let passed = match get_tag("passed", response)?.to_lowercase().as_str() {
763 "true" => true,
764 "false" => false,
765 value @ _ => bail!("invalid judge `passed` tag: {value}"),
766 };
767 Ok(RanAssertionResult {
768 analysis: Some(analysis),
769 passed,
770 })
771}
772
773fn get_tag(name: &'static str, response: &str) -> Result<String> {
774 let start_tag = format!("<{}>", name);
775 let end_tag = format!("</{}>", name);
776
777 let start_ix = response
778 .find(&start_tag)
779 .context(format!("{} start tag not found", name))?;
780 let content_start_ix = start_ix + start_tag.len();
781
782 let end_ix = content_start_ix
783 + response[content_start_ix..]
784 .find(&end_tag)
785 .context(format!("{} end tag not found", name))?;
786
787 let content = response[content_start_ix..end_ix].trim().unindent();
788
789 anyhow::Ok(content)
790}
791
792pub fn repo_path_for_url(repos_dir: &Path, repo_url: &str) -> PathBuf {
793 let repo_name = repo_url
794 .trim_start_matches("https://")
795 .replace(|c: char| !c.is_alphanumeric(), "-");
796 Path::new(repos_dir).join(repo_name)
797}
798
799pub async fn run_git(repo_path: &Path, args: &[&str]) -> Result<String> {
800 let output = new_smol_command("git")
801 .current_dir(repo_path)
802 .args(args)
803 .output()
804 .await?;
805
806 if output.status.success() {
807 Ok(String::from_utf8(output.stdout)?.trim().to_string())
808 } else {
809 Err(anyhow!(
810 "`git {}` within `{}` failed with status: {}\nstderr:\n{}\nstdout:\n{}",
811 args.join(" "),
812 repo_path.display(),
813 output.status,
814 String::from_utf8_lossy(&output.stderr),
815 String::from_utf8_lossy(&output.stdout),
816 ))
817 }
818}
819
820pub async fn send_language_model_request(
821 model: Arc<dyn LanguageModel>,
822 request: LanguageModelRequest,
823 cx: &AsyncApp,
824) -> anyhow::Result<String> {
825 match model.stream_completion_text(request, &cx).await {
826 Ok(mut stream) => {
827 let mut full_response = String::new();
828 while let Some(chunk_result) = stream.stream.next().await {
829 match chunk_result {
830 Ok(chunk_str) => {
831 full_response.push_str(&chunk_str);
832 }
833 Err(err) => {
834 return Err(anyhow!(
835 "Error receiving response from language model: {err}"
836 ));
837 }
838 }
839 }
840 Ok(full_response)
841 }
842 Err(err) => Err(anyhow!(
843 "Failed to get response from language model. Error was: {err}"
844 )),
845 }
846}
847
848pub struct RequestMarkdown {
849 pub tools: String,
850 pub messages: String,
851}
852
853impl RequestMarkdown {
854 pub fn new(request: &LanguageModelRequest) -> Self {
855 let mut tools = String::new();
856 let mut messages = String::new();
857 let mut assistant_message_number: u32 = 1;
858
859 // Print the tools
860 if !request.tools.is_empty() {
861 for tool in &request.tools {
862 write!(&mut tools, "# {}\n\n", tool.name).unwrap();
863 write!(&mut tools, "{}\n\n", tool.description).unwrap();
864 write!(
865 &mut tools,
866 "{}\n",
867 MarkdownCodeBlock {
868 tag: "json",
869 text: &format!("{:#}", tool.input_schema)
870 }
871 )
872 .unwrap();
873 }
874 }
875
876 // Print the messages
877 for message in &request.messages {
878 match message.role {
879 Role::System => messages.push_str("# ⚙️ SYSTEM\n\n"),
880 Role::User => messages.push_str("# 👤 USER\n\n"),
881 Role::Assistant => {
882 messages.push_str(&format!("# 🤖 ASSISTANT {assistant_message_number}\n\n"));
883 assistant_message_number += 1;
884 }
885 };
886
887 for content in &message.content {
888 match content {
889 MessageContent::Text(text) => {
890 messages.push_str(text);
891 messages.push_str("\n\n");
892 }
893 MessageContent::Image(_) => {
894 messages.push_str("[IMAGE DATA]\n\n");
895 }
896 MessageContent::Thinking { text, signature } => {
897 messages.push_str("**Thinking**:\n\n");
898 if let Some(sig) = signature {
899 messages.push_str(&format!("Signature: {}\n\n", sig));
900 }
901 messages.push_str(text);
902 messages.push_str("\n");
903 }
904 MessageContent::RedactedThinking(items) => {
905 messages.push_str(&format!(
906 "**Redacted Thinking**: {} item(s)\n\n",
907 items.len()
908 ));
909 }
910 MessageContent::ToolUse(tool_use) => {
911 messages.push_str(&format!(
912 "**Tool Use**: {} (ID: {})\n",
913 tool_use.name, tool_use.id
914 ));
915 messages.push_str(&format!(
916 "{}\n",
917 MarkdownCodeBlock {
918 tag: "json",
919 text: &format!("{:#}", tool_use.input)
920 }
921 ));
922 }
923 MessageContent::ToolResult(tool_result) => {
924 messages.push_str(&format!(
925 "**Tool Result**: {} (ID: {})\n\n",
926 tool_result.tool_name, tool_result.tool_use_id
927 ));
928 if tool_result.is_error {
929 messages.push_str("**ERROR:**\n");
930 }
931 messages.push_str(&format!("{}\n\n", tool_result.content));
932 }
933 }
934 }
935 }
936
937 Self { tools, messages }
938 }
939}
940
941pub fn response_events_to_markdown(
942 response_events: &[std::result::Result<LanguageModelCompletionEvent, String>],
943) -> String {
944 let mut response = String::new();
945 // Print the response events if any
946 response.push_str("# Response\n\n");
947 let mut text_buffer = String::new();
948 let mut thinking_buffer = String::new();
949
950 let flush_buffers =
951 |output: &mut String, text_buffer: &mut String, thinking_buffer: &mut String| {
952 if !text_buffer.is_empty() {
953 output.push_str(&format!("**Text**:\n{}\n\n", text_buffer));
954 text_buffer.clear();
955 }
956 if !thinking_buffer.is_empty() {
957 output.push_str(&format!("**Thinking**:\n{}\n\n", thinking_buffer));
958 thinking_buffer.clear();
959 }
960 };
961
962 for event in response_events {
963 match event {
964 Ok(LanguageModelCompletionEvent::Text(text)) => {
965 text_buffer.push_str(text);
966 }
967 Ok(LanguageModelCompletionEvent::Thinking { text, .. }) => {
968 thinking_buffer.push_str(text);
969 }
970 Ok(LanguageModelCompletionEvent::Stop(reason)) => {
971 flush_buffers(&mut response, &mut text_buffer, &mut thinking_buffer);
972 response.push_str(&format!("**Stop**: {:?}\n\n", reason));
973 }
974 Ok(LanguageModelCompletionEvent::ToolUse(tool_use)) => {
975 flush_buffers(&mut response, &mut text_buffer, &mut thinking_buffer);
976 response.push_str(&format!(
977 "**Tool Use**: {} (ID: {})\n",
978 tool_use.name, tool_use.id
979 ));
980 response.push_str(&format!(
981 "{}\n",
982 MarkdownCodeBlock {
983 tag: "json",
984 text: &format!("{:#}", tool_use.input)
985 }
986 ));
987 }
988 Ok(
989 LanguageModelCompletionEvent::UsageUpdate(_)
990 | LanguageModelCompletionEvent::StartMessage { .. },
991 ) => {}
992 Err(error) => {
993 flush_buffers(&mut response, &mut text_buffer, &mut thinking_buffer);
994 response.push_str(&format!("**Error**: {}\n\n", error));
995 }
996 }
997 }
998
999 flush_buffers(&mut response, &mut text_buffer, &mut thinking_buffer);
1000
1001 response
1002}
1003
1004#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
1005pub struct ThreadDialog {
1006 pub request: LanguageModelRequest,
1007 pub response_events: Vec<std::result::Result<LanguageModelCompletionEvent, String>>,
1008}
1009
1010impl ThreadDialog {
1011 pub fn new(
1012 request: &LanguageModelRequest,
1013 response_events: &[std::result::Result<LanguageModelCompletionEvent, String>],
1014 ) -> Self {
1015 Self {
1016 request: request.clone(),
1017 response_events: response_events.to_vec(),
1018 }
1019 }
1020
1021 /// Represents all request and response messages in a unified format.
1022 ///
1023 /// Specifically, it appends the assistant's response (derived from response events)
1024 /// as a new message to existing messages in the request.
1025 pub fn to_combined_request(&self) -> LanguageModelRequest {
1026 let mut request = self.request.clone();
1027 if let Some(assistant_message) = self.response_events_to_message() {
1028 request.messages.push(assistant_message);
1029 }
1030 request
1031 }
1032 fn response_events_to_message(&self) -> Option<LanguageModelRequestMessage> {
1033 let response_events = &self.response_events;
1034 let mut content: Vec<MessageContent> = Vec::new();
1035 let mut current_text = String::new();
1036
1037 let flush_text = |text: &mut String, content: &mut Vec<MessageContent>| {
1038 if !text.is_empty() {
1039 content.push(MessageContent::Text(std::mem::take(text)));
1040 }
1041 };
1042
1043 for event in response_events {
1044 match event {
1045 Ok(LanguageModelCompletionEvent::Text(text)) => {
1046 current_text.push_str(text);
1047 }
1048
1049 Ok(LanguageModelCompletionEvent::ToolUse(tool_use)) => {
1050 flush_text(&mut current_text, &mut content);
1051 if tool_use.is_input_complete {
1052 content.push(MessageContent::ToolUse(tool_use.clone()));
1053 }
1054 }
1055 Ok(LanguageModelCompletionEvent::Thinking { text, signature }) => {
1056 flush_text(&mut current_text, &mut content);
1057 content.push(MessageContent::Thinking {
1058 text: text.clone(),
1059 signature: signature.clone(),
1060 });
1061 }
1062
1063 // Skip these
1064 Ok(LanguageModelCompletionEvent::UsageUpdate(_))
1065 | Ok(LanguageModelCompletionEvent::StartMessage { .. })
1066 | Ok(LanguageModelCompletionEvent::Stop(_)) => {}
1067
1068 Err(error) => {
1069 flush_text(&mut current_text, &mut content);
1070 content.push(MessageContent::Text(format!("ERROR: {}", error)));
1071 }
1072 }
1073 }
1074
1075 flush_text(&mut current_text, &mut content);
1076
1077 if !content.is_empty() {
1078 Some(LanguageModelRequestMessage {
1079 role: Role::Assistant,
1080 content,
1081 cache: false,
1082 })
1083 } else {
1084 None
1085 }
1086 }
1087}
1088
1089#[cfg(test)]
1090mod test {
1091 use super::*;
1092
1093 #[test]
1094 fn test_parse_judge_output() {
1095 let response = r#"
1096 <analysis>The model did a good job but there were still compilations errors.</analysis>
1097 <passed>true</passed>
1098 "#
1099 .unindent();
1100
1101 let output = parse_assertion_result(&response).unwrap();
1102 assert_eq!(
1103 output.analysis,
1104 Some("The model did a good job but there were still compilations errors.".into())
1105 );
1106 assert_eq!(output.passed, true);
1107
1108 let response = r#"
1109 Text around ignored
1110
1111 <analysis>
1112 Failed to compile:
1113 - Error 1
1114 - Error 2
1115 </analysis>
1116
1117 <passed>false</passed>
1118 "#
1119 .unindent();
1120
1121 let output = parse_assertion_result(&response).unwrap();
1122 assert_eq!(
1123 output.analysis,
1124 Some("Failed to compile:\n- Error 1\n- Error 2".into())
1125 );
1126 assert_eq!(output.passed, false);
1127 }
1128}