mercury.rs

  1use crate::{
  2    DebugEvent, EditPredictionFinishedDebugEvent, EditPredictionId, EditPredictionModelInput,
  3    EditPredictionStartedDebugEvent, open_ai_response::text_from_response,
  4    prediction::EditPredictionResult, zeta1::compute_edits,
  5};
  6use anyhow::{Context as _, Result};
  7use futures::AsyncReadExt as _;
  8use gpui::{
  9    App, AppContext as _, Entity, Global, SharedString, Task,
 10    http_client::{self, AsyncBody, Method},
 11};
 12use language::{OffsetRangeExt as _, ToOffset, ToPoint as _};
 13use language_model::{ApiKeyState, EnvVar, env_var};
 14use std::{mem, ops::Range, path::Path, sync::Arc, time::Instant};
 15use zeta_prompt::ZetaPromptInput;
 16
 17const MERCURY_API_URL: &str = "https://api.inceptionlabs.ai/v1/edit/completions";
 18const MAX_REWRITE_TOKENS: usize = 150;
 19const MAX_CONTEXT_TOKENS: usize = 350;
 20
 21pub struct Mercury {
 22    pub api_token: Entity<ApiKeyState>,
 23}
 24
 25impl Mercury {
 26    pub fn new(cx: &mut App) -> Self {
 27        Mercury {
 28            api_token: mercury_api_token(cx),
 29        }
 30    }
 31
 32    pub(crate) fn request_prediction(
 33        &self,
 34        EditPredictionModelInput {
 35            buffer,
 36            snapshot,
 37            position,
 38            events,
 39            related_files,
 40            debug_tx,
 41            ..
 42        }: EditPredictionModelInput,
 43        cx: &mut App,
 44    ) -> Task<Result<Option<EditPredictionResult>>> {
 45        self.api_token.update(cx, |key_state, cx| {
 46            _ = key_state.load_if_needed(MERCURY_CREDENTIALS_URL, |s| s, cx);
 47        });
 48        let Some(api_token) = self.api_token.read(cx).key(&MERCURY_CREDENTIALS_URL) else {
 49            return Task::ready(Ok(None));
 50        };
 51        let full_path: Arc<Path> = snapshot
 52            .file()
 53            .map(|file| file.full_path(cx))
 54            .unwrap_or_else(|| "untitled".into())
 55            .into();
 56
 57        let http_client = cx.http_client();
 58        let cursor_point = position.to_point(&snapshot);
 59        let buffer_snapshotted_at = Instant::now();
 60        let active_buffer = buffer.clone();
 61
 62        let result = cx.background_spawn(async move {
 63            let (editable_range, context_range) =
 64                crate::cursor_excerpt::editable_and_context_ranges_for_cursor_position(
 65                    cursor_point,
 66                    &snapshot,
 67                    MAX_CONTEXT_TOKENS,
 68                    MAX_REWRITE_TOKENS,
 69                );
 70
 71            let related_files = crate::filter_redundant_excerpts(
 72                related_files,
 73                full_path.as_ref(),
 74                context_range.start.row..context_range.end.row,
 75            );
 76
 77            let context_offset_range = context_range.to_offset(&snapshot);
 78
 79            let editable_offset_range = editable_range.to_offset(&snapshot);
 80
 81            let inputs = zeta_prompt::ZetaPromptInput {
 82                events,
 83                related_files,
 84                cursor_offset_in_excerpt: cursor_point.to_offset(&snapshot)
 85                    - context_range.start.to_offset(&snapshot),
 86                cursor_path: full_path.clone(),
 87                cursor_excerpt: snapshot
 88                    .text_for_range(context_range)
 89                    .collect::<String>()
 90                    .into(),
 91                editable_range_in_excerpt: (editable_offset_range.start
 92                    - context_offset_range.start)
 93                    ..(editable_offset_range.end - context_offset_range.start),
 94            };
 95
 96            let prompt = build_prompt(&inputs);
 97
 98            if let Some(debug_tx) = &debug_tx {
 99                debug_tx
100                    .unbounded_send(DebugEvent::EditPredictionStarted(
101                        EditPredictionStartedDebugEvent {
102                            buffer: active_buffer.downgrade(),
103                            prompt: Some(prompt.clone()),
104                            position,
105                        },
106                    ))
107                    .ok();
108            }
109
110            let request_body = open_ai::Request {
111                model: "mercury-coder".into(),
112                messages: vec![open_ai::RequestMessage::User {
113                    content: open_ai::MessageContent::Plain(prompt),
114                }],
115                stream: false,
116                max_completion_tokens: None,
117                stop: vec![],
118                temperature: None,
119                tool_choice: None,
120                parallel_tool_calls: None,
121                tools: vec![],
122                prompt_cache_key: None,
123                reasoning_effort: None,
124            };
125
126            let buf = serde_json::to_vec(&request_body)?;
127            let body: AsyncBody = buf.into();
128
129            let request = http_client::Request::builder()
130                .uri(MERCURY_API_URL)
131                .header("Content-Type", "application/json")
132                .header("Authorization", format!("Bearer {}", api_token))
133                .header("Connection", "keep-alive")
134                .method(Method::POST)
135                .body(body)
136                .context("Failed to create request")?;
137
138            let mut response = http_client
139                .send(request)
140                .await
141                .context("Failed to send request")?;
142
143            let mut body: Vec<u8> = Vec::new();
144            response
145                .body_mut()
146                .read_to_end(&mut body)
147                .await
148                .context("Failed to read response body")?;
149
150            let response_received_at = Instant::now();
151            if !response.status().is_success() {
152                anyhow::bail!(
153                    "Request failed with status: {:?}\nBody: {}",
154                    response.status(),
155                    String::from_utf8_lossy(&body),
156                );
157            };
158
159            let mut response: open_ai::Response =
160                serde_json::from_slice(&body).context("Failed to parse response")?;
161
162            let id = mem::take(&mut response.id);
163            let response_str = text_from_response(response).unwrap_or_default();
164
165            if let Some(debug_tx) = &debug_tx {
166                debug_tx
167                    .unbounded_send(DebugEvent::EditPredictionFinished(
168                        EditPredictionFinishedDebugEvent {
169                            buffer: active_buffer.downgrade(),
170                            model_output: Some(response_str.clone()),
171                            position,
172                        },
173                    ))
174                    .ok();
175            }
176
177            let response_str = response_str.strip_prefix("```\n").unwrap_or(&response_str);
178            let response_str = response_str.strip_suffix("\n```").unwrap_or(&response_str);
179
180            let mut edits = Vec::new();
181            const NO_PREDICTION_OUTPUT: &str = "None";
182
183            if response_str != NO_PREDICTION_OUTPUT {
184                let old_text = snapshot
185                    .text_for_range(editable_offset_range.clone())
186                    .collect::<String>();
187                edits = compute_edits(
188                    old_text,
189                    &response_str,
190                    editable_offset_range.start,
191                    &snapshot,
192                );
193            }
194
195            anyhow::Ok((id, edits, snapshot, response_received_at, inputs))
196        });
197
198        cx.spawn(async move |cx| {
199            let (id, edits, old_snapshot, response_received_at, inputs) =
200                result.await.context("Mercury edit prediction failed")?;
201            anyhow::Ok(Some(
202                EditPredictionResult::new(
203                    EditPredictionId(id.into()),
204                    &buffer,
205                    &old_snapshot,
206                    edits.into(),
207                    buffer_snapshotted_at,
208                    response_received_at,
209                    inputs,
210                    cx,
211                )
212                .await,
213            ))
214        })
215    }
216}
217
218fn build_prompt(inputs: &ZetaPromptInput) -> String {
219    const RECENTLY_VIEWED_SNIPPETS_START: &str = "<|recently_viewed_code_snippets|>\n";
220    const RECENTLY_VIEWED_SNIPPETS_END: &str = "<|/recently_viewed_code_snippets|>\n";
221    const RECENTLY_VIEWED_SNIPPET_START: &str = "<|recently_viewed_code_snippet|>\n";
222    const RECENTLY_VIEWED_SNIPPET_END: &str = "<|/recently_viewed_code_snippet|>\n";
223    const CURRENT_FILE_CONTENT_START: &str = "<|current_file_content|>\n";
224    const CURRENT_FILE_CONTENT_END: &str = "<|/current_file_content|>\n";
225    const CODE_TO_EDIT_START: &str = "<|code_to_edit|>\n";
226    const CODE_TO_EDIT_END: &str = "<|/code_to_edit|>\n";
227    const EDIT_DIFF_HISTORY_START: &str = "<|edit_diff_history|>\n";
228    const EDIT_DIFF_HISTORY_END: &str = "<|/edit_diff_history|>\n";
229    const CURSOR_TAG: &str = "<|cursor|>";
230    const CODE_SNIPPET_FILE_PATH_PREFIX: &str = "code_snippet_file_path: ";
231    const CURRENT_FILE_PATH_PREFIX: &str = "current_file_path: ";
232
233    let mut prompt = String::new();
234
235    push_delimited(
236        &mut prompt,
237        RECENTLY_VIEWED_SNIPPETS_START..RECENTLY_VIEWED_SNIPPETS_END,
238        |prompt| {
239            for related_file in inputs.related_files.iter() {
240                for related_excerpt in &related_file.excerpts {
241                    push_delimited(
242                        prompt,
243                        RECENTLY_VIEWED_SNIPPET_START..RECENTLY_VIEWED_SNIPPET_END,
244                        |prompt| {
245                            prompt.push_str(CODE_SNIPPET_FILE_PATH_PREFIX);
246                            prompt.push_str(related_file.path.to_string_lossy().as_ref());
247                            prompt.push('\n');
248                            prompt.push_str(related_excerpt.text.as_ref());
249                        },
250                    );
251                }
252            }
253        },
254    );
255
256    push_delimited(
257        &mut prompt,
258        CURRENT_FILE_CONTENT_START..CURRENT_FILE_CONTENT_END,
259        |prompt| {
260            prompt.push_str(CURRENT_FILE_PATH_PREFIX);
261            prompt.push_str(inputs.cursor_path.as_os_str().to_string_lossy().as_ref());
262            prompt.push('\n');
263
264            prompt.push_str(&inputs.cursor_excerpt[0..inputs.editable_range_in_excerpt.start]);
265            push_delimited(prompt, CODE_TO_EDIT_START..CODE_TO_EDIT_END, |prompt| {
266                prompt.push_str(
267                    &inputs.cursor_excerpt
268                        [inputs.editable_range_in_excerpt.start..inputs.cursor_offset_in_excerpt],
269                );
270                prompt.push_str(CURSOR_TAG);
271                prompt.push_str(
272                    &inputs.cursor_excerpt
273                        [inputs.cursor_offset_in_excerpt..inputs.editable_range_in_excerpt.end],
274                );
275            });
276            prompt.push_str(&inputs.cursor_excerpt[inputs.editable_range_in_excerpt.end..]);
277        },
278    );
279
280    push_delimited(
281        &mut prompt,
282        EDIT_DIFF_HISTORY_START..EDIT_DIFF_HISTORY_END,
283        |prompt| {
284            for event in inputs.events.iter() {
285                zeta_prompt::write_event(prompt, &event);
286            }
287        },
288    );
289
290    prompt
291}
292
293fn push_delimited(prompt: &mut String, delimiters: Range<&str>, cb: impl FnOnce(&mut String)) {
294    prompt.push_str(delimiters.start);
295    cb(prompt);
296    prompt.push('\n');
297    prompt.push_str(delimiters.end);
298}
299
300pub const MERCURY_CREDENTIALS_URL: SharedString =
301    SharedString::new_static("https://api.inceptionlabs.ai/v1/edit/completions");
302pub const MERCURY_CREDENTIALS_USERNAME: &str = "mercury-api-token";
303pub static MERCURY_TOKEN_ENV_VAR: std::sync::LazyLock<EnvVar> = env_var!("MERCURY_AI_TOKEN");
304
305struct GlobalMercuryApiKey(Entity<ApiKeyState>);
306
307impl Global for GlobalMercuryApiKey {}
308
309pub fn mercury_api_token(cx: &mut App) -> Entity<ApiKeyState> {
310    if let Some(global) = cx.try_global::<GlobalMercuryApiKey>() {
311        return global.0.clone();
312    }
313    let entity =
314        cx.new(|_| ApiKeyState::new(MERCURY_CREDENTIALS_URL, MERCURY_TOKEN_ENV_VAR.clone()));
315    cx.set_global(GlobalMercuryApiKey(entity.clone()));
316    entity
317}
318
319pub fn load_mercury_api_token(cx: &mut App) -> Task<Result<(), language_model::AuthenticateError>> {
320    mercury_api_token(cx).update(cx, |key_state, cx| {
321        key_state.load_if_needed(MERCURY_CREDENTIALS_URL, |s| s, cx)
322    })
323}