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