auto_command.rs

  1use anyhow::{anyhow, Result};
  2use assistant_slash_command::{
  3    ArgumentCompletion, SlashCommand, SlashCommandOutput, SlashCommandOutputSection,
  4    SlashCommandResult,
  5};
  6use feature_flags::FeatureFlag;
  7use futures::StreamExt;
  8use gpui::{AppContext, AsyncAppContext, Task, WeakView};
  9use language::{CodeLabel, LspAdapterDelegate};
 10use language_model::{
 11    LanguageModelCompletionEvent, LanguageModelRegistry, LanguageModelRequest,
 12    LanguageModelRequestMessage, Role,
 13};
 14use semantic_index::{FileSummary, SemanticDb};
 15use smol::channel;
 16use std::sync::{atomic::AtomicBool, Arc};
 17use ui::{BorrowAppContext, WindowContext};
 18use util::ResultExt;
 19use workspace::Workspace;
 20
 21use crate::slash_command::create_label_for_command;
 22
 23pub struct AutoSlashCommandFeatureFlag;
 24
 25impl FeatureFlag for AutoSlashCommandFeatureFlag {
 26    const NAME: &'static str = "auto-slash-command";
 27}
 28
 29pub(crate) struct AutoCommand;
 30
 31impl SlashCommand for AutoCommand {
 32    fn name(&self) -> String {
 33        "auto".into()
 34    }
 35
 36    fn description(&self) -> String {
 37        "Automatically infer what context to add".into()
 38    }
 39
 40    fn menu_text(&self) -> String {
 41        self.description()
 42    }
 43
 44    fn label(&self, cx: &AppContext) -> CodeLabel {
 45        create_label_for_command("auto", &["--prompt"], cx)
 46    }
 47
 48    fn complete_argument(
 49        self: Arc<Self>,
 50        _arguments: &[String],
 51        _cancel: Arc<AtomicBool>,
 52        workspace: Option<WeakView<Workspace>>,
 53        cx: &mut WindowContext,
 54    ) -> Task<Result<Vec<ArgumentCompletion>>> {
 55        // There's no autocomplete for a prompt, since it's arbitrary text.
 56        // However, we can use this opportunity to kick off a drain of the backlog.
 57        // That way, it can hopefully be done resummarizing by the time we've actually
 58        // typed out our prompt. This re-runs on every keystroke during autocomplete,
 59        // but in the future, we could instead do it only once, when /auto is first entered.
 60        let Some(workspace) = workspace.and_then(|ws| ws.upgrade()) else {
 61            log::warn!("workspace was dropped or unavailable during /auto autocomplete");
 62
 63            return Task::ready(Ok(Vec::new()));
 64        };
 65
 66        let project = workspace.read(cx).project().clone();
 67        let Some(project_index) =
 68            cx.update_global(|index: &mut SemanticDb, cx| index.project_index(project, cx))
 69        else {
 70            return Task::ready(Err(anyhow!("No project indexer, cannot use /auto")));
 71        };
 72
 73        let cx: &mut AppContext = cx;
 74
 75        cx.spawn(|cx: gpui::AsyncAppContext| async move {
 76            let task = project_index.read_with(&cx, |project_index, cx| {
 77                project_index.flush_summary_backlogs(cx)
 78            })?;
 79
 80            cx.background_executor().spawn(task).await;
 81
 82            anyhow::Ok(Vec::new())
 83        })
 84    }
 85
 86    fn requires_argument(&self) -> bool {
 87        true
 88    }
 89
 90    fn run(
 91        self: Arc<Self>,
 92        arguments: &[String],
 93        _context_slash_command_output_sections: &[SlashCommandOutputSection<language::Anchor>],
 94        _context_buffer: language::BufferSnapshot,
 95        workspace: WeakView<Workspace>,
 96        _delegate: Option<Arc<dyn LspAdapterDelegate>>,
 97        cx: &mut WindowContext,
 98    ) -> Task<SlashCommandResult> {
 99        let Some(workspace) = workspace.upgrade() else {
100            return Task::ready(Err(anyhow::anyhow!("workspace was dropped")));
101        };
102        if arguments.is_empty() {
103            return Task::ready(Err(anyhow!("missing prompt")));
104        };
105        let argument = arguments.join(" ");
106        let original_prompt = argument.to_string();
107        let project = workspace.read(cx).project().clone();
108        let Some(project_index) =
109            cx.update_global(|index: &mut SemanticDb, cx| index.project_index(project, cx))
110        else {
111            return Task::ready(Err(anyhow!("no project indexer")));
112        };
113
114        let task = cx.spawn(|cx: gpui::AsyncWindowContext| async move {
115            let summaries = project_index
116                .read_with(&cx, |project_index, cx| project_index.all_summaries(cx))?
117                .await?;
118
119            commands_for_summaries(&summaries, &original_prompt, &cx).await
120        });
121
122        // As a convenience, append /auto's argument to the end of the prompt
123        // so you don't have to write it again.
124        let original_prompt = argument.to_string();
125
126        cx.background_executor().spawn(async move {
127            let commands = task.await?;
128            let mut prompt = String::new();
129
130            log::info!(
131                "Translating this response into slash-commands: {:?}",
132                commands
133            );
134
135            for command in commands {
136                prompt.push('/');
137                prompt.push_str(&command.name);
138                prompt.push(' ');
139                prompt.push_str(&command.arg);
140                prompt.push('\n');
141            }
142
143            prompt.push('\n');
144            prompt.push_str(&original_prompt);
145
146            Ok(SlashCommandOutput {
147                text: prompt,
148                sections: Vec::new(),
149                run_commands_in_text: true,
150            })
151        })
152    }
153}
154
155const PROMPT_INSTRUCTIONS_BEFORE_SUMMARY: &str = include_str!("prompt_before_summary.txt");
156const PROMPT_INSTRUCTIONS_AFTER_SUMMARY: &str = include_str!("prompt_after_summary.txt");
157
158fn summaries_prompt(summaries: &[FileSummary], original_prompt: &str) -> String {
159    let json_summaries = serde_json::to_string(summaries).unwrap();
160
161    format!("{PROMPT_INSTRUCTIONS_BEFORE_SUMMARY}\n{json_summaries}\n{PROMPT_INSTRUCTIONS_AFTER_SUMMARY}\n{original_prompt}")
162}
163
164/// The slash commands that the model is told about, and which we look for in the inference response.
165const SUPPORTED_SLASH_COMMANDS: &[&str] = &["search", "file"];
166
167#[derive(Debug, Clone)]
168struct CommandToRun {
169    name: String,
170    arg: String,
171}
172
173/// Given the pre-indexed file summaries for this project, as well as the original prompt
174/// string passed to `/auto`, get a list of slash commands to run, along with their arguments.
175///
176/// The prompt's output does not include the slashes (to reduce the chance that it makes a mistake),
177/// so taking one of these returned Strings and turning it into a real slash-command-with-argument
178/// involves prepending a slash to it.
179///
180/// This function will validate that each of the returned lines begins with one of SUPPORTED_SLASH_COMMANDS.
181/// Any other lines it encounters will be discarded, with a warning logged.
182async fn commands_for_summaries(
183    summaries: &[FileSummary],
184    original_prompt: &str,
185    cx: &AsyncAppContext,
186) -> Result<Vec<CommandToRun>> {
187    if summaries.is_empty() {
188        log::warn!("Inferring no context because there were no summaries available.");
189        return Ok(Vec::new());
190    }
191
192    // Use the globally configured model to translate the summaries into slash-commands,
193    // because Qwen2-7B-Instruct has not done a good job at that task.
194    let Some(model) = cx.update(|cx| LanguageModelRegistry::read_global(cx).active_model())? else {
195        log::warn!("Can't infer context because there's no active model.");
196        return Ok(Vec::new());
197    };
198    // Only go up to 90% of the actual max token count, to reduce chances of
199    // exceeding the token count due to inaccuracies in the token counting heuristic.
200    let max_token_count = (model.max_token_count() * 9) / 10;
201
202    // Rather than recursing (which would require this async function use a pinned box),
203    // we use an explicit stack of arguments and answers for when we need to "recurse."
204    let mut stack = vec![summaries];
205    let mut final_response = Vec::new();
206    let mut prompts = Vec::new();
207
208    // TODO We only need to create multiple Requests because we currently
209    // don't have the ability to tell if a CompletionProvider::complete response
210    // was a "too many tokens in this request" error. If we had that, then
211    // we could try the request once, instead of having to make separate requests
212    // to check the token count and then afterwards to run the actual prompt.
213    let make_request = |prompt: String| LanguageModelRequest {
214        messages: vec![LanguageModelRequestMessage {
215            role: Role::User,
216            content: vec![prompt.into()],
217            // Nothing in here will benefit from caching
218            cache: false,
219        }],
220        tools: Vec::new(),
221        stop: Vec::new(),
222        temperature: None,
223    };
224
225    while let Some(current_summaries) = stack.pop() {
226        // The split can result in one slice being empty and the other having one element.
227        // Whenever that happens, skip the empty one.
228        if current_summaries.is_empty() {
229            continue;
230        }
231
232        log::info!(
233            "Inferring prompt context using {} file summaries",
234            current_summaries.len()
235        );
236
237        let prompt = summaries_prompt(&current_summaries, original_prompt);
238        let start = std::time::Instant::now();
239        // Per OpenAI, 1 token ~= 4 chars in English (we go with 4.5 to overestimate a bit, because failed API requests cost a lot of perf)
240        // Verifying this against an actual model.count_tokens() confirms that it's usually within ~5% of the correct answer, whereas
241        // getting the correct answer from tiktoken takes hundreds of milliseconds (compared to this arithmetic being ~free).
242        // source: https://help.openai.com/en/articles/4936856-what-are-tokens-and-how-to-count-them
243        let token_estimate = prompt.len() * 2 / 9;
244        let duration = start.elapsed();
245        log::info!(
246            "Time taken to count tokens for prompt of length {:?}B: {:?}",
247            prompt.len(),
248            duration
249        );
250
251        if token_estimate < max_token_count {
252            prompts.push(prompt);
253        } else if current_summaries.len() == 1 {
254            log::warn!("Inferring context for a single file's summary failed because the prompt's token length exceeded the model's token limit.");
255        } else {
256            log::info!(
257                "Context inference using file summaries resulted in a prompt containing {token_estimate} tokens, which exceeded the model's max of {max_token_count}. Retrying as two separate prompts, each including half the number of summaries.",
258            );
259            let (left, right) = current_summaries.split_at(current_summaries.len() / 2);
260            stack.push(right);
261            stack.push(left);
262        }
263    }
264
265    let all_start = std::time::Instant::now();
266
267    let (tx, rx) = channel::bounded(1024);
268
269    let completion_streams = prompts
270        .into_iter()
271        .map(|prompt| {
272            let request = make_request(prompt.clone());
273            let model = model.clone();
274            let tx = tx.clone();
275            let stream = model.stream_completion(request, &cx);
276
277            (stream, tx)
278        })
279        .collect::<Vec<_>>();
280
281    cx.background_executor()
282        .spawn(async move {
283            let futures = completion_streams
284                .into_iter()
285                .enumerate()
286                .map(|(ix, (stream, tx))| async move {
287                    let start = std::time::Instant::now();
288                    let events = stream.await?;
289                    log::info!("Time taken for awaiting /await chunk stream #{ix}: {:?}", start.elapsed());
290
291                    let completion: String = events
292                        .filter_map(|event| async {
293                            if let Ok(LanguageModelCompletionEvent::Text(text)) = event {
294                                Some(text)
295                            } else {
296                                None
297                            }
298                        })
299                        .collect()
300                        .await;
301
302                    log::info!("Time taken for all /auto chunks to come back for #{ix}: {:?}", start.elapsed());
303
304                    for line in completion.split('\n') {
305                        if let Some(first_space) = line.find(' ') {
306                            let command = &line[..first_space].trim();
307                            let arg = &line[first_space..].trim();
308
309                            tx.send(CommandToRun {
310                                name: command.to_string(),
311                                arg: arg.to_string(),
312                            })
313                            .await?;
314                        } else if !line.trim().is_empty() {
315                            // All slash-commands currently supported in context inference need a space for the argument.
316                            log::warn!(
317                                "Context inference returned a non-blank line that contained no spaces (meaning no argument for the slash command): {:?}",
318                                line
319                            );
320                        }
321                    }
322
323                    anyhow::Ok(())
324                })
325                .collect::<Vec<_>>();
326
327            let _ = futures::future::try_join_all(futures).await.log_err();
328
329            let duration = all_start.elapsed();
330            eprintln!("All futures completed in {:?}", duration);
331        })
332        .await;
333
334    drop(tx); // Close the channel so that rx.collect() won't hang. This is safe because all futures have completed.
335    let results = rx.collect::<Vec<_>>().await;
336    eprintln!(
337        "Finished collecting from the channel with {} results",
338        results.len()
339    );
340    for command in results {
341        // Don't return empty or duplicate commands
342        if !command.name.is_empty()
343            && !final_response
344                .iter()
345                .any(|cmd: &CommandToRun| cmd.name == command.name && cmd.arg == command.arg)
346        {
347            if SUPPORTED_SLASH_COMMANDS
348                .iter()
349                .any(|supported| &command.name == supported)
350            {
351                final_response.push(command);
352            } else {
353                log::warn!(
354                    "Context inference returned an unrecognized slash command: {:?}",
355                    command
356                );
357            }
358        }
359    }
360
361    // Sort the commands by name (reversed just so that /search appears before /file)
362    final_response.sort_by(|cmd1, cmd2| cmd1.name.cmp(&cmd2.name).reverse());
363
364    Ok(final_response)
365}