1use std::{
2 error::Error,
3 fmt::{self, Debug},
4 path::Path,
5 sync::{Arc, Mutex},
6 time::Duration,
7};
8
9use crate::{
10 ToolMetrics,
11 assertions::{AssertionsReport, RanAssertion, RanAssertionResult},
12};
13use agent::{ContextLoadResult, Thread, ThreadEvent};
14use anyhow::{Result, anyhow};
15use assistant_settings::AgentProfileId;
16use async_trait::async_trait;
17use buffer_diff::DiffHunkStatus;
18use collections::HashMap;
19use futures::{FutureExt as _, StreamExt, channel::mpsc, select_biased};
20use gpui::{App, AppContext, AsyncApp, Entity};
21use language_model::{LanguageModel, Role, StopReason};
22
23pub const THREAD_EVENT_TIMEOUT: Duration = Duration::from_secs(60 * 2);
24
25#[async_trait(?Send)]
26pub trait Example {
27 fn meta(&self) -> ExampleMetadata;
28 async fn conversation(&self, cx: &mut ExampleContext) -> Result<()>;
29 fn diff_assertions(&self) -> Vec<JudgeAssertion> {
30 Vec::new()
31 }
32 fn thread_assertions(&self) -> Vec<JudgeAssertion> {
33 Vec::new()
34 }
35}
36
37#[derive(Clone, Debug)]
38pub struct JudgeAssertion {
39 pub id: String,
40 pub description: String,
41}
42
43#[derive(Clone, Debug)]
44pub struct ExampleMetadata {
45 pub name: String,
46 pub url: String,
47 pub revision: String,
48 pub language_server: Option<LanguageServer>,
49 pub max_assertions: Option<usize>,
50 pub profile_id: AgentProfileId,
51 pub existing_thread_json: Option<String>,
52}
53
54#[derive(Clone, Debug)]
55pub struct LanguageServer {
56 pub file_extension: String,
57 pub allow_preexisting_diagnostics: bool,
58}
59
60impl ExampleMetadata {
61 pub fn repo_name(&self) -> String {
62 self.url
63 .split('/')
64 .next_back()
65 .unwrap_or(&"")
66 .trim_end_matches(".git")
67 .into()
68 }
69}
70
71pub struct FailedAssertion(pub String);
72
73impl fmt::Debug for FailedAssertion {
74 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
75 write!(f, "Assertion failure: {}", self.0)
76 }
77}
78
79impl fmt::Display for FailedAssertion {
80 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
81 write!(f, "{}", self.0)
82 }
83}
84
85impl Error for FailedAssertion {}
86
87pub struct ExampleContext {
88 meta: ExampleMetadata,
89 log_prefix: String,
90 agent_thread: Entity<agent::Thread>,
91 app: AsyncApp,
92 model: Arc<dyn LanguageModel>,
93 pub assertions: AssertionsReport,
94 pub tool_metrics: Arc<Mutex<ToolMetrics>>,
95}
96
97impl ExampleContext {
98 pub fn new(
99 meta: ExampleMetadata,
100 log_prefix: String,
101 agent_thread: Entity<agent::Thread>,
102 model: Arc<dyn LanguageModel>,
103 app: AsyncApp,
104 ) -> Self {
105 let assertions = AssertionsReport::new(meta.max_assertions);
106
107 Self {
108 meta,
109 log_prefix,
110 agent_thread,
111 assertions,
112 model,
113 app,
114 tool_metrics: Arc::new(Mutex::new(ToolMetrics::default())),
115 }
116 }
117
118 pub fn push_user_message(&mut self, text: impl ToString) {
119 self.app
120 .update_entity(&self.agent_thread, |thread, cx| {
121 thread.insert_user_message(
122 text.to_string(),
123 ContextLoadResult::default(),
124 None,
125 Vec::new(),
126 cx,
127 );
128 })
129 .unwrap();
130 }
131
132 pub fn assert(&mut self, expected: bool, message: impl ToString) -> Result<()> {
133 let message = message.to_string();
134 self.log_assertion(
135 if expected {
136 Ok(())
137 } else {
138 Err(anyhow::Error::from(FailedAssertion(message.clone())))
139 },
140 message,
141 )
142 }
143
144 pub fn assert_some<T>(&mut self, option: Option<T>, message: impl ToString) -> Result<T> {
145 let message = message.to_string();
146 self.log_assertion(
147 match option {
148 Some(value) => Ok(value),
149 None => Err(anyhow::Error::from(FailedAssertion(message.clone()))),
150 },
151 message,
152 )
153 }
154
155 #[allow(dead_code)]
156 pub fn assert_eq<T: PartialEq + Debug>(
157 &mut self,
158 left: T,
159 right: T,
160 message: impl ToString,
161 ) -> Result<()> {
162 let message = message.to_string();
163 self.log_assertion(
164 if left == right {
165 Ok(())
166 } else {
167 println!(
168 "{}{}",
169 self.log_prefix,
170 pretty_assertions::Comparison::new(&left, &right)
171 );
172 Err(anyhow::Error::from(FailedAssertion(message.clone())))
173 },
174 message,
175 )
176 }
177
178 fn log_assertion<T>(&mut self, result: Result<T>, message: String) -> Result<T> {
179 if let Some(max) = self.meta.max_assertions {
180 if self.assertions.run_count() > max {
181 return Err(anyhow!(
182 "More assertions were run than the stated max_assertions of {}",
183 max
184 ));
185 }
186 }
187
188 self.assertions.ran.push(RanAssertion {
189 id: message.clone(),
190 result: Ok(RanAssertionResult {
191 analysis: None,
192 passed: result.is_ok(),
193 }),
194 });
195
196 if result.is_ok() {
197 println!("{}✅ {}", self.log_prefix, message);
198 } else {
199 println!("{}❌ {}", self.log_prefix, message);
200 }
201
202 result
203 }
204
205 pub async fn run_to_end(&mut self) -> Result<Response> {
206 self.run_turns(u32::MAX).await
207 }
208
209 pub async fn run_turn(&mut self) -> Result<Response> {
210 self.run_turns(1).await
211 }
212
213 pub async fn run_turns(&mut self, iterations: u32) -> Result<Response> {
214 let (mut tx, mut rx) = mpsc::channel(1);
215
216 let tool_metrics = self.tool_metrics.clone();
217 let log_prefix = self.log_prefix.clone();
218 let _subscription = self.app.subscribe(
219 &self.agent_thread,
220 move |thread, event: &ThreadEvent, cx| match event {
221 ThreadEvent::ShowError(thread_error) => {
222 tx.try_send(Err(anyhow!(thread_error.clone()))).ok();
223 }
224 ThreadEvent::Stopped(reason) => match reason {
225 Ok(StopReason::EndTurn) => {
226 tx.close_channel();
227 }
228 Ok(StopReason::ToolUse) => {
229 if thread.read(cx).remaining_turns() == 0 {
230 tx.close_channel();
231 }
232 }
233 Ok(StopReason::MaxTokens) => {
234 tx.try_send(Err(anyhow!("Exceeded maximum tokens"))).ok();
235 }
236 Err(err) => {
237 tx.try_send(Err(anyhow!(err.clone()))).ok();
238 }
239 },
240 ThreadEvent::NewRequest
241 | ThreadEvent::StreamedAssistantText(_, _)
242 | ThreadEvent::StreamedAssistantThinking(_, _)
243 | ThreadEvent::UsePendingTools { .. }
244 | ThreadEvent::CompletionCanceled => {}
245 ThreadEvent::ToolFinished {
246 tool_use_id,
247 pending_tool_use,
248 ..
249 } => {
250 thread.update(cx, |thread, _cx| {
251 if let Some(tool_use) = pending_tool_use {
252 let mut tool_metrics = tool_metrics.lock().unwrap();
253 if let Some(tool_result) = thread.tool_result(&tool_use_id) {
254 let message = if tool_result.is_error {
255 format!("✖︎ {}", tool_use.name)
256 } else {
257 format!("✔︎ {}", tool_use.name)
258 };
259 println!("{log_prefix}{message}");
260 tool_metrics
261 .insert(tool_result.tool_name.clone(), !tool_result.is_error);
262 } else {
263 let message =
264 format!("TOOL FINISHED WITHOUT RESULT: {}", tool_use.name);
265 println!("{log_prefix}{message}");
266 tool_metrics.insert(tool_use.name.clone(), true);
267 }
268 }
269 });
270 }
271 ThreadEvent::InvalidToolInput { .. } => {
272 println!("{log_prefix} invalid tool input");
273 }
274 ThreadEvent::MissingToolUse {
275 tool_use_id: _,
276 ui_text,
277 } => {
278 println!("{log_prefix} {ui_text}");
279 }
280 ThreadEvent::ToolConfirmationNeeded => {
281 panic!(
282 "{}Bug: Tool confirmation should not be required in eval",
283 log_prefix
284 );
285 }
286 ThreadEvent::StreamedCompletion
287 | ThreadEvent::MessageAdded(_)
288 | ThreadEvent::MessageEdited(_)
289 | ThreadEvent::MessageDeleted(_)
290 | ThreadEvent::SummaryChanged
291 | ThreadEvent::SummaryGenerated
292 | ThreadEvent::ReceivedTextChunk
293 | ThreadEvent::StreamedToolUse { .. }
294 | ThreadEvent::CheckpointChanged
295 | ThreadEvent::CancelEditing => {
296 tx.try_send(Ok(())).ok();
297 if std::env::var("ZED_EVAL_DEBUG").is_ok() {
298 println!("{}Event: {:#?}", log_prefix, event);
299 }
300 }
301 },
302 );
303
304 let model = self.model.clone();
305
306 let message_count_before = self.app.update_entity(&self.agent_thread, |thread, cx| {
307 thread.set_remaining_turns(iterations);
308 thread.send_to_model(model, None, cx);
309 thread.messages().len()
310 })?;
311
312 loop {
313 select_biased! {
314 result = rx.next() => {
315 if let Some(result) = result {
316 result?;
317 } else {
318 break;
319 }
320 }
321 _ = self.app.background_executor().timer(THREAD_EVENT_TIMEOUT).fuse() => {
322 return Err(anyhow!("Agentic loop stalled - waited {:?} without any events", THREAD_EVENT_TIMEOUT));
323 }
324 }
325 }
326
327 let messages = self.app.read_entity(&self.agent_thread, |thread, cx| {
328 let mut messages = Vec::new();
329 for message in thread.messages().skip(message_count_before) {
330 messages.push(Message {
331 _role: message.role,
332 text: message.to_string(),
333 tool_use: thread
334 .tool_uses_for_message(message.id, cx)
335 .into_iter()
336 .map(|tool_use| ToolUse {
337 name: tool_use.name.to_string(),
338 value: tool_use.input,
339 })
340 .collect(),
341 });
342 }
343 messages
344 })?;
345
346 let response = Response::new(messages);
347
348 Ok(response)
349 }
350
351 pub fn edits(&self) -> HashMap<Arc<Path>, FileEdits> {
352 self.agent_thread
353 .read_with(&self.app, |thread, cx| {
354 let action_log = thread.action_log().read(cx);
355 HashMap::from_iter(action_log.changed_buffers(cx).into_iter().map(
356 |(buffer, diff)| {
357 let snapshot = buffer.read(cx).snapshot();
358
359 let file = snapshot.file().unwrap();
360 let diff = diff.read(cx);
361 let base_text = diff.base_text().text();
362
363 let hunks = diff
364 .hunks(&snapshot, cx)
365 .map(|hunk| FileEditHunk {
366 base_text: base_text[hunk.diff_base_byte_range.clone()].to_string(),
367 text: snapshot
368 .text_for_range(hunk.range.clone())
369 .collect::<String>(),
370 status: hunk.status(),
371 })
372 .collect();
373
374 (file.path().clone(), FileEdits { hunks })
375 },
376 ))
377 })
378 .unwrap()
379 }
380
381 pub fn agent_thread(&self) -> Entity<Thread> {
382 self.agent_thread.clone()
383 }
384}
385
386impl AppContext for ExampleContext {
387 type Result<T> = anyhow::Result<T>;
388
389 fn new<T: 'static>(
390 &mut self,
391 build_entity: impl FnOnce(&mut gpui::Context<T>) -> T,
392 ) -> Self::Result<Entity<T>> {
393 self.app.new(build_entity)
394 }
395
396 fn reserve_entity<T: 'static>(&mut self) -> Self::Result<gpui::Reservation<T>> {
397 self.app.reserve_entity()
398 }
399
400 fn insert_entity<T: 'static>(
401 &mut self,
402 reservation: gpui::Reservation<T>,
403 build_entity: impl FnOnce(&mut gpui::Context<T>) -> T,
404 ) -> Self::Result<Entity<T>> {
405 self.app.insert_entity(reservation, build_entity)
406 }
407
408 fn update_entity<T, R>(
409 &mut self,
410 handle: &Entity<T>,
411 update: impl FnOnce(&mut T, &mut gpui::Context<T>) -> R,
412 ) -> Self::Result<R>
413 where
414 T: 'static,
415 {
416 self.app.update_entity(handle, update)
417 }
418
419 fn read_entity<T, R>(
420 &self,
421 handle: &Entity<T>,
422 read: impl FnOnce(&T, &App) -> R,
423 ) -> Self::Result<R>
424 where
425 T: 'static,
426 {
427 self.app.read_entity(handle, read)
428 }
429
430 fn update_window<T, F>(&mut self, window: gpui::AnyWindowHandle, f: F) -> Result<T>
431 where
432 F: FnOnce(gpui::AnyView, &mut gpui::Window, &mut App) -> T,
433 {
434 self.app.update_window(window, f)
435 }
436
437 fn read_window<T, R>(
438 &self,
439 window: &gpui::WindowHandle<T>,
440 read: impl FnOnce(Entity<T>, &App) -> R,
441 ) -> Result<R>
442 where
443 T: 'static,
444 {
445 self.app.read_window(window, read)
446 }
447
448 fn background_spawn<R>(
449 &self,
450 future: impl std::future::Future<Output = R> + Send + 'static,
451 ) -> gpui::Task<R>
452 where
453 R: Send + 'static,
454 {
455 self.app.background_spawn(future)
456 }
457
458 fn read_global<G, R>(&self, callback: impl FnOnce(&G, &App) -> R) -> Self::Result<R>
459 where
460 G: gpui::Global,
461 {
462 self.app.read_global(callback)
463 }
464}
465
466#[derive(Debug)]
467pub struct Response {
468 messages: Vec<Message>,
469}
470
471impl Response {
472 pub fn new(messages: Vec<Message>) -> Self {
473 Self { messages }
474 }
475
476 pub fn expect_tool(
477 &self,
478 tool_name: &'static str,
479 cx: &mut ExampleContext,
480 ) -> Result<&ToolUse> {
481 let result = self.find_tool_call(tool_name);
482 cx.assert_some(result, format!("called `{}`", tool_name))
483 }
484
485 pub fn find_tool_call(&self, tool_name: &str) -> Option<&ToolUse> {
486 self.messages.iter().rev().find_map(|msg| {
487 msg.tool_use
488 .iter()
489 .find(|tool_use| tool_use.name == tool_name)
490 })
491 }
492
493 #[allow(dead_code)]
494 pub fn tool_uses(&self) -> impl Iterator<Item = &ToolUse> {
495 self.messages.iter().flat_map(|msg| &msg.tool_use)
496 }
497
498 pub fn texts(&self) -> impl Iterator<Item = String> {
499 self.messages.iter().map(|message| message.text.clone())
500 }
501}
502
503#[derive(Debug)]
504pub struct Message {
505 _role: Role,
506 text: String,
507 tool_use: Vec<ToolUse>,
508}
509
510#[derive(Debug)]
511pub struct ToolUse {
512 pub name: String,
513 value: serde_json::Value,
514}
515
516impl ToolUse {
517 pub fn parse_input<Input>(&self) -> Result<Input>
518 where
519 Input: for<'de> serde::Deserialize<'de>,
520 {
521 serde_json::from_value::<Input>(self.value.clone()).map_err(|err| anyhow!(err))
522 }
523}
524
525#[derive(Debug, Eq, PartialEq)]
526pub struct FileEdits {
527 pub hunks: Vec<FileEditHunk>,
528}
529
530#[derive(Debug, Eq, PartialEq)]
531pub struct FileEditHunk {
532 pub base_text: String,
533 pub text: String,
534 pub status: DiffHunkStatus,
535}
536
537impl FileEdits {
538 pub fn has_added_line(&self, line: &str) -> bool {
539 self.hunks.iter().any(|hunk| {
540 hunk.status == DiffHunkStatus::added_none()
541 && hunk.base_text.is_empty()
542 && hunk.text.contains(line)
543 })
544 }
545}