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    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;
 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 api_key_and_url = self.state.read_with(cx, |state, cx| {
223            let api_url = XAiLanguageModelProvider::api_url(cx);
224            let api_key = state.api_key_state.key(&api_url);
225            (api_key, api_url)
226        });
227        let (api_key, api_url) = match api_key_and_url {
228            Ok(api_key_and_url) => api_key_and_url,
229            Err(err) => {
230                return futures::future::ready(Err(err)).boxed();
231            }
232        };
233
234        let future = self.request_limiter.stream(async move {
235            let Some(api_key) = api_key else {
236                return Err(LanguageModelCompletionError::NoApiKey {
237                    provider: PROVIDER_NAME,
238                });
239            };
240            let request =
241                open_ai::stream_completion(http_client.as_ref(), &api_url, &api_key, request);
242            let response = request.await?;
243            Ok(response)
244        });
245
246        async move { Ok(future.await?.boxed()) }.boxed()
247    }
248}
249
250impl LanguageModel for XAiLanguageModel {
251    fn id(&self) -> LanguageModelId {
252        self.id.clone()
253    }
254
255    fn name(&self) -> LanguageModelName {
256        LanguageModelName::from(self.model.display_name().to_string())
257    }
258
259    fn provider_id(&self) -> LanguageModelProviderId {
260        PROVIDER_ID
261    }
262
263    fn provider_name(&self) -> LanguageModelProviderName {
264        PROVIDER_NAME
265    }
266
267    fn supports_tools(&self) -> bool {
268        self.model.supports_tool()
269    }
270
271    fn supports_images(&self) -> bool {
272        self.model.supports_images()
273    }
274
275    fn supports_tool_choice(&self, choice: LanguageModelToolChoice) -> bool {
276        match choice {
277            LanguageModelToolChoice::Auto
278            | LanguageModelToolChoice::Any
279            | LanguageModelToolChoice::None => true,
280        }
281    }
282    fn tool_input_format(&self) -> LanguageModelToolSchemaFormat {
283        let model_id = self.model.id().trim().to_lowercase();
284        if model_id.eq(x_ai::Model::Grok4.id()) || model_id.eq(x_ai::Model::GrokCodeFast1.id()) {
285            LanguageModelToolSchemaFormat::JsonSchemaSubset
286        } else {
287            LanguageModelToolSchemaFormat::JsonSchema
288        }
289    }
290
291    fn telemetry_id(&self) -> String {
292        format!("x_ai/{}", self.model.id())
293    }
294
295    fn max_token_count(&self) -> u64 {
296        self.model.max_token_count()
297    }
298
299    fn max_output_tokens(&self) -> Option<u64> {
300        self.model.max_output_tokens()
301    }
302
303    fn count_tokens(
304        &self,
305        request: LanguageModelRequest,
306        cx: &App,
307    ) -> BoxFuture<'static, Result<u64>> {
308        count_xai_tokens(request, self.model.clone(), cx)
309    }
310
311    fn stream_completion(
312        &self,
313        request: LanguageModelRequest,
314        cx: &AsyncApp,
315    ) -> BoxFuture<
316        'static,
317        Result<
318            futures::stream::BoxStream<
319                'static,
320                Result<LanguageModelCompletionEvent, LanguageModelCompletionError>,
321            >,
322            LanguageModelCompletionError,
323        >,
324    > {
325        let request = crate::provider::open_ai::into_open_ai(
326            request,
327            self.model.id(),
328            self.model.supports_parallel_tool_calls(),
329            self.model.supports_prompt_cache_key(),
330            self.max_output_tokens(),
331            None,
332        );
333        let completions = self.stream_completion(request, cx);
334        async move {
335            let mapper = crate::provider::open_ai::OpenAiEventMapper::new();
336            Ok(mapper.map_stream(completions.await?).boxed())
337        }
338        .boxed()
339    }
340}
341
342pub fn count_xai_tokens(
343    request: LanguageModelRequest,
344    model: Model,
345    cx: &App,
346) -> BoxFuture<'static, Result<u64>> {
347    cx.background_spawn(async move {
348        let messages = request
349            .messages
350            .into_iter()
351            .map(|message| tiktoken_rs::ChatCompletionRequestMessage {
352                role: match message.role {
353                    Role::User => "user".into(),
354                    Role::Assistant => "assistant".into(),
355                    Role::System => "system".into(),
356                },
357                content: Some(message.string_contents()),
358                name: None,
359                function_call: None,
360            })
361            .collect::<Vec<_>>();
362
363        let model_name = if model.max_token_count() >= 100_000 {
364            "gpt-4o"
365        } else {
366            "gpt-4"
367        };
368        tiktoken_rs::num_tokens_from_messages(model_name, &messages).map(|tokens| tokens as u64)
369    })
370    .boxed()
371}
372
373struct ConfigurationView {
374    api_key_editor: Entity<SingleLineInput>,
375    state: gpui::Entity<State>,
376    load_credentials_task: Option<Task<()>>,
377}
378
379impl ConfigurationView {
380    fn new(state: gpui::Entity<State>, window: &mut Window, cx: &mut Context<Self>) -> Self {
381        let api_key_editor = cx.new(|cx| {
382            SingleLineInput::new(
383                window,
384                cx,
385                "xai-0000000000000000000000000000000000000000000000000",
386            )
387            .label("API key")
388        });
389
390        cx.observe(&state, |_, _, cx| {
391            cx.notify();
392        })
393        .detach();
394
395        let load_credentials_task = Some(cx.spawn_in(window, {
396            let state = state.clone();
397            async move |this, cx| {
398                if let Some(task) = state
399                    .update(cx, |state, cx| state.authenticate(cx))
400                    .log_err()
401                {
402                    // We don't log an error, because "not signed in" is also an error.
403                    let _ = task.await;
404                }
405                this.update(cx, |this, cx| {
406                    this.load_credentials_task = None;
407                    cx.notify();
408                })
409                .log_err();
410            }
411        }));
412
413        Self {
414            api_key_editor,
415            state,
416            load_credentials_task,
417        }
418    }
419
420    fn save_api_key(&mut self, _: &menu::Confirm, window: &mut Window, cx: &mut Context<Self>) {
421        let api_key = self.api_key_editor.read(cx).text(cx).trim().to_string();
422        if api_key.is_empty() {
423            return;
424        }
425
426        let state = self.state.clone();
427        cx.spawn_in(window, async move |_, cx| {
428            state
429                .update(cx, |state, cx| state.set_api_key(Some(api_key), cx))?
430                .await
431        })
432        .detach_and_log_err(cx);
433    }
434
435    fn reset_api_key(&mut self, window: &mut Window, cx: &mut Context<Self>) {
436        self.api_key_editor.update(cx, |input, cx| {
437            input.editor.update(cx, |editor, cx| {
438                editor.set_text("", window, cx);
439            });
440        });
441
442        let state = self.state.clone();
443        cx.spawn_in(window, async move |_, cx| {
444            state
445                .update(cx, |state, cx| state.set_api_key(None, cx))?
446                .await
447        })
448        .detach_and_log_err(cx);
449    }
450
451    fn should_render_editor(&self, cx: &mut Context<Self>) -> bool {
452        !self.state.read(cx).is_authenticated()
453    }
454}
455
456impl Render for ConfigurationView {
457    fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
458        let env_var_set = self.state.read(cx).api_key_state.is_from_env_var();
459
460        let api_key_section = if self.should_render_editor(cx) {
461            v_flex()
462                .on_action(cx.listener(Self::save_api_key))
463                .child(Label::new("To use Zed's agent with xAI, you need to add an API key. Follow these steps:"))
464                .child(
465                    List::new()
466                        .child(InstructionListItem::new(
467                            "Create one by visiting",
468                            Some("xAI console"),
469                            Some("https://console.x.ai/team/default/api-keys"),
470                        ))
471                        .child(InstructionListItem::text_only(
472                            "Paste your API key below and hit enter to start using the agent",
473                        )),
474                )
475                .child(self.api_key_editor.clone())
476                .child(
477                    Label::new(format!(
478                        "You can also assign the {API_KEY_ENV_VAR_NAME} environment variable and restart Zed."
479                    ))
480                    .size(LabelSize::Small)
481                    .color(Color::Muted),
482                )
483                .child(
484                    Label::new("Note that xAI is a custom OpenAI-compatible provider.")
485                        .size(LabelSize::Small)
486                        .color(Color::Muted),
487                )
488                .into_any()
489        } else {
490            h_flex()
491                .mt_1()
492                .p_1()
493                .justify_between()
494                .rounded_md()
495                .border_1()
496                .border_color(cx.theme().colors().border)
497                .bg(cx.theme().colors().background)
498                .child(
499                    h_flex()
500                        .gap_1()
501                        .child(Icon::new(IconName::Check).color(Color::Success))
502                        .child(Label::new(if env_var_set {
503                            format!("API key set in {API_KEY_ENV_VAR_NAME} environment variable.")
504                        } else {
505                            "API key configured.".to_string()
506                        })),
507                )
508                .child(
509                    Button::new("reset-api-key", "Reset API Key")
510                        .label_size(LabelSize::Small)
511                        .icon(IconName::Undo)
512                        .icon_size(IconSize::Small)
513                        .icon_position(IconPosition::Start)
514                        .layer(ElevationIndex::ModalSurface)
515                        .when(env_var_set, |this| {
516                            this.tooltip(Tooltip::text(format!("To reset your API key, unset the {API_KEY_ENV_VAR_NAME} environment variable.")))
517                        })
518                        .on_click(cx.listener(|this, _, window, cx| this.reset_api_key(window, cx))),
519                )
520                .into_any()
521        };
522
523        if self.load_credentials_task.is_some() {
524            div().child(Label::new("Loading credentials…")).into_any()
525        } else {
526            v_flex().size_full().child(api_key_section).into_any()
527        }
528    }
529}