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