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                    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::NewRequest
238                | ThreadEvent::StreamedAssistantText(_, _)
239                | ThreadEvent::StreamedAssistantThinking(_, _)
240                | ThreadEvent::UsePendingTools { .. }
241                | ThreadEvent::CompletionCanceled => {}
242                ThreadEvent::ToolFinished {
243                    tool_use_id,
244                    pending_tool_use,
245                    ..
246                } => {
247                    thread.update(cx, |thread, _cx| {
248                        if let Some(tool_use) = pending_tool_use {
249                            let mut tool_metrics = tool_metrics.lock().unwrap();
250                            if let Some(tool_result) = thread.tool_result(&tool_use_id) {
251                                let message = if tool_result.is_error {
252                                    format!("✖︎ {}", tool_use.name)
253                                } else {
254                                    format!("✔︎ {}", tool_use.name)
255                                };
256                                println!("{log_prefix}{message}");
257                                tool_metrics
258                                    .insert(tool_result.tool_name.clone(), !tool_result.is_error);
259                            } else {
260                                let message =
261                                    format!("TOOL FINISHED WITHOUT RESULT: {}", tool_use.name);
262                                println!("{log_prefix}{message}");
263                                tool_metrics.insert(tool_use.name.clone(), true);
264                            }
265                        }
266                    });
267                }
268                ThreadEvent::InvalidToolInput { .. } => {
269                    println!("{log_prefix} invalid tool input");
270                }
271                ThreadEvent::ToolConfirmationNeeded => {
272                    panic!(
273                        "{}Bug: Tool confirmation should not be required in eval",
274                        log_prefix
275                    );
276                }
277                ThreadEvent::StreamedCompletion
278                | ThreadEvent::MessageAdded(_)
279                | ThreadEvent::MessageEdited(_)
280                | ThreadEvent::MessageDeleted(_)
281                | ThreadEvent::SummaryChanged
282                | ThreadEvent::SummaryGenerated
283                | ThreadEvent::ReceivedTextChunk
284                | ThreadEvent::StreamedToolUse { .. }
285                | ThreadEvent::CheckpointChanged
286                | ThreadEvent::CancelEditing => {
287                    tx.try_send(Ok(())).ok();
288                    if std::env::var("ZED_EVAL_DEBUG").is_ok() {
289                        println!("{}Event: {:#?}", log_prefix, event);
290                    }
291                }
292            },
293        );
294
295        let model = self.model.clone();
296
297        let message_count_before = self.app.update_entity(&self.agent_thread, |thread, cx| {
298            thread.set_remaining_turns(iterations);
299            thread.send_to_model(model, None, cx);
300            thread.messages().len()
301        })?;
302
303        loop {
304            select_biased! {
305                result = rx.next() => {
306                    if let Some(result) = result {
307                        result?;
308                    } else {
309                        break;
310                    }
311                }
312                _ = self.app.background_executor().timer(THREAD_EVENT_TIMEOUT).fuse() => {
313                    return Err(anyhow!("Agentic loop stalled - waited {:?} without any events", THREAD_EVENT_TIMEOUT));
314                }
315            }
316        }
317
318        let messages = self.app.read_entity(&self.agent_thread, |thread, cx| {
319            let mut messages = Vec::new();
320            for message in thread.messages().skip(message_count_before) {
321                messages.push(Message {
322                    _role: message.role,
323                    text: message.to_string(),
324                    tool_use: thread
325                        .tool_uses_for_message(message.id, cx)
326                        .into_iter()
327                        .map(|tool_use| ToolUse {
328                            name: tool_use.name.to_string(),
329                            value: tool_use.input,
330                        })
331                        .collect(),
332                });
333            }
334            messages
335        })?;
336
337        let response = Response::new(messages);
338
339        Ok(response)
340    }
341
342    pub fn edits(&self) -> HashMap<Arc<Path>, FileEdits> {
343        self.agent_thread
344            .read_with(&self.app, |thread, cx| {
345                let action_log = thread.action_log().read(cx);
346                HashMap::from_iter(action_log.changed_buffers(cx).into_iter().map(
347                    |(buffer, diff)| {
348                        let snapshot = buffer.read(cx).snapshot();
349
350                        let file = snapshot.file().unwrap();
351                        let diff = diff.read(cx);
352                        let base_text = diff.base_text().text();
353
354                        let hunks = diff
355                            .hunks(&snapshot, cx)
356                            .map(|hunk| FileEditHunk {
357                                base_text: base_text[hunk.diff_base_byte_range.clone()].to_string(),
358                                text: snapshot
359                                    .text_for_range(hunk.range.clone())
360                                    .collect::<String>(),
361                                status: hunk.status(),
362                            })
363                            .collect();
364
365                        (file.path().clone(), FileEdits { hunks })
366                    },
367                ))
368            })
369            .unwrap()
370    }
371
372    pub fn agent_thread(&self) -> Entity<Thread> {
373        self.agent_thread.clone()
374    }
375}
376
377impl AppContext for ExampleContext {
378    type Result<T> = anyhow::Result<T>;
379
380    fn new<T: 'static>(
381        &mut self,
382        build_entity: impl FnOnce(&mut gpui::Context<T>) -> T,
383    ) -> Self::Result<Entity<T>> {
384        self.app.new(build_entity)
385    }
386
387    fn reserve_entity<T: 'static>(&mut self) -> Self::Result<gpui::Reservation<T>> {
388        self.app.reserve_entity()
389    }
390
391    fn insert_entity<T: 'static>(
392        &mut self,
393        reservation: gpui::Reservation<T>,
394        build_entity: impl FnOnce(&mut gpui::Context<T>) -> T,
395    ) -> Self::Result<Entity<T>> {
396        self.app.insert_entity(reservation, build_entity)
397    }
398
399    fn update_entity<T, R>(
400        &mut self,
401        handle: &Entity<T>,
402        update: impl FnOnce(&mut T, &mut gpui::Context<T>) -> R,
403    ) -> Self::Result<R>
404    where
405        T: 'static,
406    {
407        self.app.update_entity(handle, update)
408    }
409
410    fn read_entity<T, R>(
411        &self,
412        handle: &Entity<T>,
413        read: impl FnOnce(&T, &App) -> R,
414    ) -> Self::Result<R>
415    where
416        T: 'static,
417    {
418        self.app.read_entity(handle, read)
419    }
420
421    fn update_window<T, F>(&mut self, window: gpui::AnyWindowHandle, f: F) -> Result<T>
422    where
423        F: FnOnce(gpui::AnyView, &mut gpui::Window, &mut App) -> T,
424    {
425        self.app.update_window(window, f)
426    }
427
428    fn read_window<T, R>(
429        &self,
430        window: &gpui::WindowHandle<T>,
431        read: impl FnOnce(Entity<T>, &App) -> R,
432    ) -> Result<R>
433    where
434        T: 'static,
435    {
436        self.app.read_window(window, read)
437    }
438
439    fn background_spawn<R>(
440        &self,
441        future: impl std::future::Future<Output = R> + Send + 'static,
442    ) -> gpui::Task<R>
443    where
444        R: Send + 'static,
445    {
446        self.app.background_spawn(future)
447    }
448
449    fn read_global<G, R>(&self, callback: impl FnOnce(&G, &App) -> R) -> Self::Result<R>
450    where
451        G: gpui::Global,
452    {
453        self.app.read_global(callback)
454    }
455}
456
457#[derive(Debug)]
458pub struct Response {
459    messages: Vec<Message>,
460}
461
462impl Response {
463    pub fn new(messages: Vec<Message>) -> Self {
464        Self { messages }
465    }
466
467    pub fn expect_tool(
468        &self,
469        tool_name: &'static str,
470        cx: &mut ExampleContext,
471    ) -> Result<&ToolUse> {
472        let result = self.messages.iter().find_map(|msg| {
473            msg.tool_use
474                .iter()
475                .find(|tool_use| tool_use.name == tool_name)
476        });
477        cx.assert_some(result, format!("called `{}`", tool_name))
478    }
479
480    #[allow(dead_code)]
481    pub fn tool_uses(&self) -> impl Iterator<Item = &ToolUse> {
482        self.messages.iter().flat_map(|msg| &msg.tool_use)
483    }
484
485    pub fn texts(&self) -> impl Iterator<Item = String> {
486        self.messages.iter().map(|message| message.text.clone())
487    }
488}
489
490#[derive(Debug)]
491pub struct Message {
492    _role: Role,
493    text: String,
494    tool_use: Vec<ToolUse>,
495}
496
497#[derive(Debug)]
498pub struct ToolUse {
499    pub name: String,
500    value: serde_json::Value,
501}
502
503impl ToolUse {
504    pub fn parse_input<Input>(&self) -> Result<Input>
505    where
506        Input: for<'de> serde::Deserialize<'de>,
507    {
508        serde_json::from_value::<Input>(self.value.clone()).map_err(|err| anyhow!(err))
509    }
510}
511
512#[derive(Debug, Eq, PartialEq)]
513pub struct FileEdits {
514    pub hunks: Vec<FileEditHunk>,
515}
516
517#[derive(Debug, Eq, PartialEq)]
518pub struct FileEditHunk {
519    pub base_text: String,
520    pub text: String,
521    pub status: DiffHunkStatus,
522}
523
524impl FileEdits {
525    pub fn has_added_line(&self, line: &str) -> bool {
526        self.hunks.iter().any(|hunk| {
527            hunk.status == DiffHunkStatus::added_none()
528                && hunk.base_text.is_empty()
529                && hunk.text.contains(line)
530        })
531    }
532}