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