x_ai.rs

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