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