x_ai.rs

  1use anyhow::Result;
  2use collections::BTreeMap;
  3use futures::{FutureExt, StreamExt, future::BoxFuture};
  4use gpui::{AnyView, App, AsyncApp, Context, Entity, Task, Window};
  5use http_client::HttpClient;
  6use language_model::{
  7    ApiKeyState, AuthenticateError, EnvVar, IconOrSvg, LanguageModel, LanguageModelCompletionError,
  8    LanguageModelCompletionEvent, LanguageModelId, LanguageModelName, LanguageModelProvider,
  9    LanguageModelProviderId, LanguageModelProviderName, LanguageModelProviderState,
 10    LanguageModelRequest, LanguageModelToolChoice, LanguageModelToolSchemaFormat, RateLimiter,
 11    Role, env_var,
 12};
 13use open_ai::ResponseStreamEvent;
 14pub use settings::XaiAvailableModel as AvailableModel;
 15use settings::{Settings, SettingsStore};
 16use std::sync::{Arc, LazyLock};
 17use strum::IntoEnumIterator;
 18use ui::{ButtonLink, ConfiguredApiCard, List, ListBulletItem, prelude::*};
 19use ui_input::InputField;
 20use util::ResultExt;
 21use x_ai::{Model, XAI_API_URL};
 22
 23const PROVIDER_ID: LanguageModelProviderId = LanguageModelProviderId::new("x_ai");
 24const PROVIDER_NAME: LanguageModelProviderName = LanguageModelProviderName::new("xAI");
 25
 26const API_KEY_ENV_VAR_NAME: &str = "XAI_API_KEY";
 27static API_KEY_ENV_VAR: LazyLock<EnvVar> = env_var!(API_KEY_ENV_VAR_NAME);
 28
 29#[derive(Default, Clone, Debug, PartialEq)]
 30pub struct XAiSettings {
 31    pub api_url: String,
 32    pub available_models: Vec<AvailableModel>,
 33}
 34
 35pub struct XAiLanguageModelProvider {
 36    http_client: Arc<dyn HttpClient>,
 37    state: Entity<State>,
 38}
 39
 40pub struct State {
 41    api_key_state: ApiKeyState,
 42}
 43
 44impl State {
 45    fn is_authenticated(&self) -> bool {
 46        self.api_key_state.has_key()
 47    }
 48
 49    fn set_api_key(&mut self, api_key: Option<String>, cx: &mut Context<Self>) -> Task<Result<()>> {
 50        let api_url = XAiLanguageModelProvider::api_url(cx);
 51        self.api_key_state
 52            .store(api_url, api_key, |this| &mut this.api_key_state, cx)
 53    }
 54
 55    fn authenticate(&mut self, cx: &mut Context<Self>) -> Task<Result<(), AuthenticateError>> {
 56        let api_url = XAiLanguageModelProvider::api_url(cx);
 57        self.api_key_state
 58            .load_if_needed(api_url, |this| &mut this.api_key_state, cx)
 59    }
 60}
 61
 62impl XAiLanguageModelProvider {
 63    pub fn new(http_client: Arc<dyn HttpClient>, cx: &mut App) -> Self {
 64        let state = cx.new(|cx| {
 65            cx.observe_global::<SettingsStore>(|this: &mut State, cx| {
 66                let api_url = Self::api_url(cx);
 67                this.api_key_state
 68                    .handle_url_change(api_url, |this| &mut this.api_key_state, cx);
 69                cx.notify();
 70            })
 71            .detach();
 72            State {
 73                api_key_state: ApiKeyState::new(Self::api_url(cx), (*API_KEY_ENV_VAR).clone()),
 74            }
 75        });
 76
 77        Self { http_client, state }
 78    }
 79
 80    fn create_language_model(&self, model: x_ai::Model) -> Arc<dyn LanguageModel> {
 81        Arc::new(XAiLanguageModel {
 82            id: LanguageModelId::from(model.id().to_string()),
 83            model,
 84            state: self.state.clone(),
 85            http_client: self.http_client.clone(),
 86            request_limiter: RateLimiter::new(4),
 87        })
 88    }
 89
 90    fn settings(cx: &App) -> &XAiSettings {
 91        &crate::AllLanguageModelSettings::get_global(cx).x_ai
 92    }
 93
 94    fn api_url(cx: &App) -> SharedString {
 95        let api_url = &Self::settings(cx).api_url;
 96        if api_url.is_empty() {
 97            XAI_API_URL.into()
 98        } else {
 99            SharedString::new(api_url.as_str())
100        }
101    }
102}
103
104impl LanguageModelProviderState for XAiLanguageModelProvider {
105    type ObservableEntity = State;
106
107    fn observable_entity(&self) -> Option<Entity<Self::ObservableEntity>> {
108        Some(self.state.clone())
109    }
110}
111
112impl LanguageModelProvider for XAiLanguageModelProvider {
113    fn id(&self) -> LanguageModelProviderId {
114        PROVIDER_ID
115    }
116
117    fn name(&self) -> LanguageModelProviderName {
118        PROVIDER_NAME
119    }
120
121    fn icon(&self) -> IconOrSvg {
122        IconOrSvg::Icon(IconName::AiXAi)
123    }
124
125    fn default_model(&self, _cx: &App) -> Option<Arc<dyn LanguageModel>> {
126        Some(self.create_language_model(x_ai::Model::default()))
127    }
128
129    fn default_fast_model(&self, _cx: &App) -> Option<Arc<dyn LanguageModel>> {
130        Some(self.create_language_model(x_ai::Model::default_fast()))
131    }
132
133    fn provided_models(&self, cx: &App) -> Vec<Arc<dyn LanguageModel>> {
134        let mut models = BTreeMap::default();
135
136        for model in x_ai::Model::iter() {
137            if !matches!(model, x_ai::Model::Custom { .. }) {
138                models.insert(model.id().to_string(), model);
139            }
140        }
141
142        for model in &Self::settings(cx).available_models {
143            models.insert(
144                model.name.clone(),
145                x_ai::Model::Custom {
146                    name: model.name.clone(),
147                    display_name: model.display_name.clone(),
148                    max_tokens: model.max_tokens,
149                    max_output_tokens: model.max_output_tokens,
150                    max_completion_tokens: model.max_completion_tokens,
151                    supports_images: model.supports_images,
152                    supports_tools: model.supports_tools,
153                    parallel_tool_calls: model.parallel_tool_calls,
154                },
155            );
156        }
157
158        models
159            .into_values()
160            .map(|model| self.create_language_model(model))
161            .collect()
162    }
163
164    fn is_authenticated(&self, cx: &App) -> bool {
165        self.state.read(cx).is_authenticated()
166    }
167
168    fn authenticate(&self, cx: &mut App) -> Task<Result<(), AuthenticateError>> {
169        self.state.update(cx, |state, cx| state.authenticate(cx))
170    }
171
172    fn configuration_view(
173        &self,
174        _target_agent: language_model::ConfigurationViewTargetAgent,
175        window: &mut Window,
176        cx: &mut App,
177    ) -> AnyView {
178        cx.new(|cx| ConfigurationView::new(self.state.clone(), window, cx))
179            .into()
180    }
181
182    fn reset_credentials(&self, cx: &mut App) -> Task<Result<()>> {
183        self.state
184            .update(cx, |state, cx| state.set_api_key(None, cx))
185    }
186}
187
188pub struct XAiLanguageModel {
189    id: LanguageModelId,
190    model: x_ai::Model,
191    state: Entity<State>,
192    http_client: Arc<dyn HttpClient>,
193    request_limiter: RateLimiter,
194}
195
196impl XAiLanguageModel {
197    fn stream_completion(
198        &self,
199        request: open_ai::Request,
200        cx: &AsyncApp,
201    ) -> BoxFuture<
202        'static,
203        Result<
204            futures::stream::BoxStream<'static, Result<ResponseStreamEvent>>,
205            LanguageModelCompletionError,
206        >,
207    > {
208        let http_client = self.http_client.clone();
209
210        let (api_key, api_url) = self.state.read_with(cx, |state, cx| {
211            let api_url = XAiLanguageModelProvider::api_url(cx);
212            (state.api_key_state.key(&api_url), api_url)
213        });
214
215        let future = self.request_limiter.stream(async move {
216            let provider = PROVIDER_NAME;
217            let Some(api_key) = api_key else {
218                return Err(LanguageModelCompletionError::NoApiKey { provider });
219            };
220            let request = open_ai::stream_completion(
221                http_client.as_ref(),
222                provider.0.as_str(),
223                &api_url,
224                &api_key,
225                request,
226            );
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<InputField>,
360    state: Entity<State>,
361    load_credentials_task: Option<Task<()>>,
362}
363
364impl ConfigurationView {
365    fn new(state: Entity<State>, window: &mut Window, cx: &mut Context<Self>) -> Self {
366        let api_key_editor = cx.new(|cx| {
367            InputField::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) = Some(state.update(cx, |state, cx| state.authenticate(cx))) {
384                    // We don't log an error, because "not signed in" is also an error.
385                    let _ = task.await;
386                }
387                this.update(cx, |this, cx| {
388                    this.load_credentials_task = None;
389                    cx.notify();
390                })
391                .log_err();
392            }
393        }));
394
395        Self {
396            api_key_editor,
397            state,
398            load_credentials_task,
399        }
400    }
401
402    fn save_api_key(&mut self, _: &menu::Confirm, window: &mut Window, cx: &mut Context<Self>) {
403        let api_key = self.api_key_editor.read(cx).text(cx).trim().to_string();
404        if api_key.is_empty() {
405            return;
406        }
407
408        // url changes can cause the editor to be displayed again
409        self.api_key_editor
410            .update(cx, |editor, cx| editor.set_text("", window, cx));
411
412        let state = self.state.clone();
413        cx.spawn_in(window, async move |_, cx| {
414            state
415                .update(cx, |state, cx| state.set_api_key(Some(api_key), cx))
416                .await
417        })
418        .detach_and_log_err(cx);
419    }
420
421    fn reset_api_key(&mut self, window: &mut Window, cx: &mut Context<Self>) {
422        self.api_key_editor
423            .update(cx, |input, cx| input.set_text("", window, cx));
424
425        let state = self.state.clone();
426        cx.spawn_in(window, async move |_, cx| {
427            state
428                .update(cx, |state, cx| state.set_api_key(None, cx))
429                .await
430        })
431        .detach_and_log_err(cx);
432    }
433
434    fn should_render_editor(&self, cx: &mut Context<Self>) -> bool {
435        !self.state.read(cx).is_authenticated()
436    }
437}
438
439impl Render for ConfigurationView {
440    fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
441        let env_var_set = self.state.read(cx).api_key_state.is_from_env_var();
442        let configured_card_label = if env_var_set {
443            format!("API key set in {API_KEY_ENV_VAR_NAME} environment variable")
444        } else {
445            let api_url = XAiLanguageModelProvider::api_url(cx);
446            if api_url == XAI_API_URL {
447                "API key configured".to_string()
448            } else {
449                format!("API key configured for {}", api_url)
450            }
451        };
452
453        let api_key_section = if self.should_render_editor(cx) {
454            v_flex()
455                .on_action(cx.listener(Self::save_api_key))
456                .child(Label::new("To use Zed's agent with xAI, you need to add an API key. Follow these steps:"))
457                .child(
458                    List::new()
459                        .child(
460                            ListBulletItem::new("")
461                                .child(Label::new("Create one by visiting"))
462                                .child(ButtonLink::new("xAI console", "https://console.x.ai/team/default/api-keys"))
463                        )
464                        .child(
465                            ListBulletItem::new("Paste your API key below and hit enter to start using the agent")
466                        ),
467                )
468                .child(self.api_key_editor.clone())
469                .child(
470                    Label::new(format!(
471                        "You can also set the {API_KEY_ENV_VAR_NAME} environment variable and restart Zed."
472                    ))
473                    .size(LabelSize::Small)
474                    .color(Color::Muted),
475                )
476                .child(
477                    Label::new("Note that xAI is a custom OpenAI-compatible provider.")
478                        .size(LabelSize::Small)
479                        .color(Color::Muted),
480                )
481                .into_any_element()
482        } else {
483            ConfiguredApiCard::new(configured_card_label)
484                .disabled(env_var_set)
485                .when(env_var_set, |this| {
486                    this.tooltip_label(format!("To reset your API key, unset the {API_KEY_ENV_VAR_NAME} environment variable."))
487                })
488                .on_click(cx.listener(|this, _, window, cx| this.reset_api_key(window, cx)))
489                .into_any_element()
490        };
491
492        if self.load_credentials_task.is_some() {
493            div().child(Label::new("Loading credentials…")).into_any()
494        } else {
495            v_flex().size_full().child(api_key_section).into_any()
496        }
497    }
498}