x_ai.rs

  1use anyhow::{Result, anyhow};
  2use collections::BTreeMap;
  3use futures::{FutureExt, StreamExt, future, future::BoxFuture};
  4use gpui::{AnyView, App, AsyncApp, Context, Entity, Task, Window};
  5use http_client::HttpClient;
  6use language_model::{
  7    AuthenticateError, LanguageModel, LanguageModelCompletionError, LanguageModelCompletionEvent,
  8    LanguageModelId, LanguageModelName, LanguageModelProvider, LanguageModelProviderId,
  9    LanguageModelProviderName, LanguageModelProviderState, LanguageModelRequest,
 10    LanguageModelToolChoice, LanguageModelToolSchemaFormat, RateLimiter, Role,
 11};
 12use open_ai::ResponseStreamEvent;
 13pub use settings::XaiAvailableModel as AvailableModel;
 14use settings::{Settings, SettingsStore};
 15use std::sync::{Arc, LazyLock};
 16use strum::IntoEnumIterator;
 17use ui::{ElevationIndex, List, Tooltip, prelude::*};
 18use ui_input::SingleLineInput;
 19use util::{ResultExt, truncate_and_trailoff};
 20use x_ai::{Model, XAI_API_URL};
 21use zed_env_vars::{EnvVar, env_var};
 22
 23use crate::{api_key::ApiKeyState, ui::InstructionListItem};
 24
 25const PROVIDER_ID: LanguageModelProviderId = LanguageModelProviderId::new("x_ai");
 26const PROVIDER_NAME: LanguageModelProviderName = LanguageModelProviderName::new("xAI");
 27
 28const API_KEY_ENV_VAR_NAME: &str = "XAI_API_KEY";
 29static API_KEY_ENV_VAR: LazyLock<EnvVar> = env_var!(API_KEY_ENV_VAR_NAME);
 30
 31#[derive(Default, Clone, Debug, PartialEq)]
 32pub struct XAiSettings {
 33    pub api_url: String,
 34    pub available_models: Vec<AvailableModel>,
 35}
 36
 37pub struct XAiLanguageModelProvider {
 38    http_client: Arc<dyn HttpClient>,
 39    state: gpui::Entity<State>,
 40}
 41
 42pub struct State {
 43    api_key_state: ApiKeyState,
 44}
 45
 46impl State {
 47    fn is_authenticated(&self) -> bool {
 48        self.api_key_state.has_key()
 49    }
 50
 51    fn set_api_key(&mut self, api_key: Option<String>, cx: &mut Context<Self>) -> Task<Result<()>> {
 52        let api_url = XAiLanguageModelProvider::api_url(cx);
 53        self.api_key_state
 54            .store(api_url, api_key, |this| &mut this.api_key_state, cx)
 55    }
 56
 57    fn authenticate(&mut self, cx: &mut Context<Self>) -> Task<Result<(), AuthenticateError>> {
 58        let api_url = XAiLanguageModelProvider::api_url(cx);
 59        self.api_key_state.load_if_needed(
 60            api_url,
 61            &API_KEY_ENV_VAR,
 62            |this| &mut this.api_key_state,
 63            cx,
 64        )
 65    }
 66}
 67
 68impl XAiLanguageModelProvider {
 69    pub fn new(http_client: Arc<dyn HttpClient>, cx: &mut App) -> Self {
 70        let state = cx.new(|cx| {
 71            cx.observe_global::<SettingsStore>(|this: &mut State, cx| {
 72                let api_url = Self::api_url(cx);
 73                this.api_key_state.handle_url_change(
 74                    api_url,
 75                    &API_KEY_ENV_VAR,
 76                    |this| &mut this.api_key_state,
 77                    cx,
 78                );
 79                cx.notify();
 80            })
 81            .detach();
 82            State {
 83                api_key_state: ApiKeyState::new(Self::api_url(cx)),
 84            }
 85        });
 86
 87        Self { http_client, state }
 88    }
 89
 90    fn create_language_model(&self, model: x_ai::Model) -> Arc<dyn LanguageModel> {
 91        Arc::new(XAiLanguageModel {
 92            id: LanguageModelId::from(model.id().to_string()),
 93            model,
 94            state: self.state.clone(),
 95            http_client: self.http_client.clone(),
 96            request_limiter: RateLimiter::new(4),
 97        })
 98    }
 99
100    fn settings(cx: &App) -> &XAiSettings {
101        &crate::AllLanguageModelSettings::get_global(cx).x_ai
102    }
103
104    fn api_url(cx: &App) -> SharedString {
105        let api_url = &Self::settings(cx).api_url;
106        if api_url.is_empty() {
107            XAI_API_URL.into()
108        } else {
109            SharedString::new(api_url.as_str())
110        }
111    }
112}
113
114impl LanguageModelProviderState for XAiLanguageModelProvider {
115    type ObservableEntity = State;
116
117    fn observable_entity(&self) -> Option<gpui::Entity<Self::ObservableEntity>> {
118        Some(self.state.clone())
119    }
120}
121
122impl LanguageModelProvider for XAiLanguageModelProvider {
123    fn id(&self) -> LanguageModelProviderId {
124        PROVIDER_ID
125    }
126
127    fn name(&self) -> LanguageModelProviderName {
128        PROVIDER_NAME
129    }
130
131    fn icon(&self) -> IconName {
132        IconName::AiXAi
133    }
134
135    fn default_model(&self, _cx: &App) -> Option<Arc<dyn LanguageModel>> {
136        Some(self.create_language_model(x_ai::Model::default()))
137    }
138
139    fn default_fast_model(&self, _cx: &App) -> Option<Arc<dyn LanguageModel>> {
140        Some(self.create_language_model(x_ai::Model::default_fast()))
141    }
142
143    fn provided_models(&self, cx: &App) -> Vec<Arc<dyn LanguageModel>> {
144        let mut models = BTreeMap::default();
145
146        for model in x_ai::Model::iter() {
147            if !matches!(model, x_ai::Model::Custom { .. }) {
148                models.insert(model.id().to_string(), model);
149            }
150        }
151
152        for model in &Self::settings(cx).available_models {
153            models.insert(
154                model.name.clone(),
155                x_ai::Model::Custom {
156                    name: model.name.clone(),
157                    display_name: model.display_name.clone(),
158                    max_tokens: model.max_tokens,
159                    max_output_tokens: model.max_output_tokens,
160                    max_completion_tokens: model.max_completion_tokens,
161                },
162            );
163        }
164
165        models
166            .into_values()
167            .map(|model| self.create_language_model(model))
168            .collect()
169    }
170
171    fn is_authenticated(&self, cx: &App) -> bool {
172        self.state.read(cx).is_authenticated()
173    }
174
175    fn authenticate(&self, cx: &mut App) -> Task<Result<(), AuthenticateError>> {
176        self.state.update(cx, |state, cx| state.authenticate(cx))
177    }
178
179    fn configuration_view(
180        &self,
181        _target_agent: language_model::ConfigurationViewTargetAgent,
182        window: &mut Window,
183        cx: &mut App,
184    ) -> AnyView {
185        cx.new(|cx| ConfigurationView::new(self.state.clone(), window, cx))
186            .into()
187    }
188
189    fn reset_credentials(&self, cx: &mut App) -> Task<Result<()>> {
190        self.state
191            .update(cx, |state, cx| state.set_api_key(None, cx))
192    }
193}
194
195pub struct XAiLanguageModel {
196    id: LanguageModelId,
197    model: x_ai::Model,
198    state: gpui::Entity<State>,
199    http_client: Arc<dyn HttpClient>,
200    request_limiter: RateLimiter,
201}
202
203impl XAiLanguageModel {
204    fn stream_completion(
205        &self,
206        request: open_ai::Request,
207        cx: &AsyncApp,
208    ) -> BoxFuture<'static, Result<futures::stream::BoxStream<'static, Result<ResponseStreamEvent>>>>
209    {
210        let http_client = self.http_client.clone();
211
212        let Ok((api_key, api_url)) = self.state.read_with(cx, |state, cx| {
213            let api_url = XAiLanguageModelProvider::api_url(cx);
214            (state.api_key_state.key(&api_url), api_url)
215        }) else {
216            return future::ready(Err(anyhow!("App state dropped"))).boxed();
217        };
218
219        let future = self.request_limiter.stream(async move {
220            let Some(api_key) = api_key else {
221                return Err(LanguageModelCompletionError::NoApiKey {
222                    provider: PROVIDER_NAME,
223                });
224            };
225            let request =
226                open_ai::stream_completion(http_client.as_ref(), &api_url, &api_key, request);
227            let response = request.await?;
228            Ok(response)
229        });
230
231        async move { Ok(future.await?.boxed()) }.boxed()
232    }
233}
234
235impl LanguageModel for XAiLanguageModel {
236    fn id(&self) -> LanguageModelId {
237        self.id.clone()
238    }
239
240    fn name(&self) -> LanguageModelName {
241        LanguageModelName::from(self.model.display_name().to_string())
242    }
243
244    fn provider_id(&self) -> LanguageModelProviderId {
245        PROVIDER_ID
246    }
247
248    fn provider_name(&self) -> LanguageModelProviderName {
249        PROVIDER_NAME
250    }
251
252    fn supports_tools(&self) -> bool {
253        self.model.supports_tool()
254    }
255
256    fn supports_images(&self) -> bool {
257        self.model.supports_images()
258    }
259
260    fn supports_tool_choice(&self, choice: LanguageModelToolChoice) -> bool {
261        match choice {
262            LanguageModelToolChoice::Auto
263            | LanguageModelToolChoice::Any
264            | LanguageModelToolChoice::None => true,
265        }
266    }
267    fn tool_input_format(&self) -> LanguageModelToolSchemaFormat {
268        let model_id = self.model.id().trim().to_lowercase();
269        if model_id.eq(x_ai::Model::Grok4.id()) || model_id.eq(x_ai::Model::GrokCodeFast1.id()) {
270            LanguageModelToolSchemaFormat::JsonSchemaSubset
271        } else {
272            LanguageModelToolSchemaFormat::JsonSchema
273        }
274    }
275
276    fn telemetry_id(&self) -> String {
277        format!("x_ai/{}", self.model.id())
278    }
279
280    fn max_token_count(&self) -> u64 {
281        self.model.max_token_count()
282    }
283
284    fn max_output_tokens(&self) -> Option<u64> {
285        self.model.max_output_tokens()
286    }
287
288    fn count_tokens(
289        &self,
290        request: LanguageModelRequest,
291        cx: &App,
292    ) -> BoxFuture<'static, Result<u64>> {
293        count_xai_tokens(request, self.model.clone(), cx)
294    }
295
296    fn stream_completion(
297        &self,
298        request: LanguageModelRequest,
299        cx: &AsyncApp,
300    ) -> BoxFuture<
301        'static,
302        Result<
303            futures::stream::BoxStream<
304                'static,
305                Result<LanguageModelCompletionEvent, LanguageModelCompletionError>,
306            >,
307            LanguageModelCompletionError,
308        >,
309    > {
310        let request = crate::provider::open_ai::into_open_ai(
311            request,
312            self.model.id(),
313            self.model.supports_parallel_tool_calls(),
314            self.model.supports_prompt_cache_key(),
315            self.max_output_tokens(),
316            None,
317        );
318        let completions = self.stream_completion(request, cx);
319        async move {
320            let mapper = crate::provider::open_ai::OpenAiEventMapper::new();
321            Ok(mapper.map_stream(completions.await?).boxed())
322        }
323        .boxed()
324    }
325}
326
327pub fn count_xai_tokens(
328    request: LanguageModelRequest,
329    model: Model,
330    cx: &App,
331) -> BoxFuture<'static, Result<u64>> {
332    cx.background_spawn(async move {
333        let messages = request
334            .messages
335            .into_iter()
336            .map(|message| tiktoken_rs::ChatCompletionRequestMessage {
337                role: match message.role {
338                    Role::User => "user".into(),
339                    Role::Assistant => "assistant".into(),
340                    Role::System => "system".into(),
341                },
342                content: Some(message.string_contents()),
343                name: None,
344                function_call: None,
345            })
346            .collect::<Vec<_>>();
347
348        let model_name = if model.max_token_count() >= 100_000 {
349            "gpt-4o"
350        } else {
351            "gpt-4"
352        };
353        tiktoken_rs::num_tokens_from_messages(model_name, &messages).map(|tokens| tokens as u64)
354    })
355    .boxed()
356}
357
358struct ConfigurationView {
359    api_key_editor: Entity<SingleLineInput>,
360    state: gpui::Entity<State>,
361    load_credentials_task: Option<Task<()>>,
362}
363
364impl ConfigurationView {
365    fn new(state: gpui::Entity<State>, window: &mut Window, cx: &mut Context<Self>) -> Self {
366        let api_key_editor = cx.new(|cx| {
367            SingleLineInput::new(
368                window,
369                cx,
370                "xai-0000000000000000000000000000000000000000000000000",
371            )
372            .label("API key")
373        });
374
375        cx.observe(&state, |_, _, cx| {
376            cx.notify();
377        })
378        .detach();
379
380        let load_credentials_task = Some(cx.spawn_in(window, {
381            let state = state.clone();
382            async move |this, cx| {
383                if let Some(task) = state
384                    .update(cx, |state, cx| state.authenticate(cx))
385                    .log_err()
386                {
387                    // We don't log an error, because "not signed in" is also an error.
388                    let _ = task.await;
389                }
390                this.update(cx, |this, cx| {
391                    this.load_credentials_task = None;
392                    cx.notify();
393                })
394                .log_err();
395            }
396        }));
397
398        Self {
399            api_key_editor,
400            state,
401            load_credentials_task,
402        }
403    }
404
405    fn save_api_key(&mut self, _: &menu::Confirm, window: &mut Window, cx: &mut Context<Self>) {
406        let api_key = self.api_key_editor.read(cx).text(cx).trim().to_string();
407        if api_key.is_empty() {
408            return;
409        }
410
411        // url changes can cause the editor to be displayed again
412        self.api_key_editor
413            .update(cx, |editor, cx| editor.set_text("", window, cx));
414
415        let state = self.state.clone();
416        cx.spawn_in(window, async move |_, cx| {
417            state
418                .update(cx, |state, cx| state.set_api_key(Some(api_key), cx))?
419                .await
420        })
421        .detach_and_log_err(cx);
422    }
423
424    fn reset_api_key(&mut self, window: &mut Window, cx: &mut Context<Self>) {
425        self.api_key_editor
426            .update(cx, |input, cx| input.set_text("", window, cx));
427
428        let state = self.state.clone();
429        cx.spawn_in(window, async move |_, cx| {
430            state
431                .update(cx, |state, cx| state.set_api_key(None, cx))?
432                .await
433        })
434        .detach_and_log_err(cx);
435    }
436
437    fn should_render_editor(&self, cx: &mut Context<Self>) -> bool {
438        !self.state.read(cx).is_authenticated()
439    }
440}
441
442impl Render for ConfigurationView {
443    fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
444        let env_var_set = self.state.read(cx).api_key_state.is_from_env_var();
445
446        let api_key_section = if self.should_render_editor(cx) {
447            v_flex()
448                .on_action(cx.listener(Self::save_api_key))
449                .child(Label::new("To use Zed's agent with xAI, you need to add an API key. Follow these steps:"))
450                .child(
451                    List::new()
452                        .child(InstructionListItem::new(
453                            "Create one by visiting",
454                            Some("xAI console"),
455                            Some("https://console.x.ai/team/default/api-keys"),
456                        ))
457                        .child(InstructionListItem::text_only(
458                            "Paste your API key below and hit enter to start using the agent",
459                        )),
460                )
461                .child(self.api_key_editor.clone())
462                .child(
463                    Label::new(format!(
464                        "You can also assign the {API_KEY_ENV_VAR_NAME} environment variable and restart Zed."
465                    ))
466                    .size(LabelSize::Small)
467                    .color(Color::Muted),
468                )
469                .child(
470                    Label::new("Note that xAI is a custom OpenAI-compatible provider.")
471                        .size(LabelSize::Small)
472                        .color(Color::Muted),
473                )
474                .into_any()
475        } else {
476            h_flex()
477                .mt_1()
478                .p_1()
479                .justify_between()
480                .rounded_md()
481                .border_1()
482                .border_color(cx.theme().colors().border)
483                .bg(cx.theme().colors().background)
484                .child(
485                    h_flex()
486                        .gap_1()
487                        .child(Icon::new(IconName::Check).color(Color::Success))
488                        .child(Label::new(if env_var_set {
489                            format!("API key set in {API_KEY_ENV_VAR_NAME} environment variable")
490                        } else {
491                            let api_url = XAiLanguageModelProvider::api_url(cx);
492                            if api_url == XAI_API_URL {
493                                "API key configured".to_string()
494                            } else {
495                                format!("API key configured for {}", truncate_and_trailoff(&api_url, 32))
496                            }
497                        })),
498                )
499                .child(
500                    Button::new("reset-api-key", "Reset API Key")
501                        .label_size(LabelSize::Small)
502                        .icon(IconName::Undo)
503                        .icon_size(IconSize::Small)
504                        .icon_position(IconPosition::Start)
505                        .layer(ElevationIndex::ModalSurface)
506                        .when(env_var_set, |this| {
507                            this.tooltip(Tooltip::text(format!("To reset your API key, unset the {API_KEY_ENV_VAR_NAME} environment variable.")))
508                        })
509                        .on_click(cx.listener(|this, _, window, cx| this.reset_api_key(window, cx))),
510                )
511                .into_any()
512        };
513
514        if self.load_credentials_task.is_some() {
515            div().child(Label::new("Loading credentials…")).into_any()
516        } else {
517            v_flex().size_full().child(api_key_section).into_any()
518        }
519    }
520}