example.rs

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