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