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_streaming_tools(&self) -> bool {
261        true
262    }
263
264    fn supports_tool_choice(&self, choice: LanguageModelToolChoice) -> bool {
265        match choice {
266            LanguageModelToolChoice::Auto
267            | LanguageModelToolChoice::Any
268            | LanguageModelToolChoice::None => true,
269        }
270    }
271    fn tool_input_format(&self) -> LanguageModelToolSchemaFormat {
272        if self.model.requires_json_schema_subset() {
273            LanguageModelToolSchemaFormat::JsonSchemaSubset
274        } else {
275            LanguageModelToolSchemaFormat::JsonSchema
276        }
277    }
278
279    fn telemetry_id(&self) -> String {
280        format!("x_ai/{}", self.model.id())
281    }
282
283    fn max_token_count(&self) -> u64 {
284        self.model.max_token_count()
285    }
286
287    fn max_output_tokens(&self) -> Option<u64> {
288        self.model.max_output_tokens()
289    }
290
291    fn supports_split_token_display(&self) -> bool {
292        true
293    }
294
295    fn count_tokens(
296        &self,
297        request: LanguageModelRequest,
298        cx: &App,
299    ) -> BoxFuture<'static, Result<u64>> {
300        count_xai_tokens(request, self.model.clone(), cx)
301    }
302
303    fn stream_completion(
304        &self,
305        request: LanguageModelRequest,
306        cx: &AsyncApp,
307    ) -> BoxFuture<
308        'static,
309        Result<
310            futures::stream::BoxStream<
311                'static,
312                Result<LanguageModelCompletionEvent, LanguageModelCompletionError>,
313            >,
314            LanguageModelCompletionError,
315        >,
316    > {
317        let request = crate::provider::open_ai::into_open_ai(
318            request,
319            self.model.id(),
320            self.model.supports_parallel_tool_calls(),
321            self.model.supports_prompt_cache_key(),
322            self.max_output_tokens(),
323            None,
324        );
325        let completions = self.stream_completion(request, cx);
326        async move {
327            let mapper = crate::provider::open_ai::OpenAiEventMapper::new();
328            Ok(mapper.map_stream(completions.await?).boxed())
329        }
330        .boxed()
331    }
332}
333
334pub fn count_xai_tokens(
335    request: LanguageModelRequest,
336    model: Model,
337    cx: &App,
338) -> BoxFuture<'static, Result<u64>> {
339    cx.background_spawn(async move {
340        let messages = request
341            .messages
342            .into_iter()
343            .map(|message| tiktoken_rs::ChatCompletionRequestMessage {
344                role: match message.role {
345                    Role::User => "user".into(),
346                    Role::Assistant => "assistant".into(),
347                    Role::System => "system".into(),
348                },
349                content: Some(message.string_contents()),
350                name: None,
351                function_call: None,
352            })
353            .collect::<Vec<_>>();
354
355        let model_name = if model.max_token_count() >= 100_000 {
356            "gpt-4o"
357        } else {
358            "gpt-4"
359        };
360        tiktoken_rs::num_tokens_from_messages(model_name, &messages).map(|tokens| tokens as u64)
361    })
362    .boxed()
363}
364
365struct ConfigurationView {
366    api_key_editor: Entity<InputField>,
367    state: Entity<State>,
368    load_credentials_task: Option<Task<()>>,
369}
370
371impl ConfigurationView {
372    fn new(state: Entity<State>, window: &mut Window, cx: &mut Context<Self>) -> Self {
373        let api_key_editor = cx.new(|cx| {
374            InputField::new(
375                window,
376                cx,
377                "xai-0000000000000000000000000000000000000000000000000",
378            )
379            .label("API key")
380        });
381
382        cx.observe(&state, |_, _, cx| {
383            cx.notify();
384        })
385        .detach();
386
387        let load_credentials_task = Some(cx.spawn_in(window, {
388            let state = state.clone();
389            async move |this, cx| {
390                if let Some(task) = Some(state.update(cx, |state, cx| state.authenticate(cx))) {
391                    // We don't log an error, because "not signed in" is also an error.
392                    let _ = task.await;
393                }
394                this.update(cx, |this, cx| {
395                    this.load_credentials_task = None;
396                    cx.notify();
397                })
398                .log_err();
399            }
400        }));
401
402        Self {
403            api_key_editor,
404            state,
405            load_credentials_task,
406        }
407    }
408
409    fn save_api_key(&mut self, _: &menu::Confirm, window: &mut Window, cx: &mut Context<Self>) {
410        let api_key = self.api_key_editor.read(cx).text(cx).trim().to_string();
411        if api_key.is_empty() {
412            return;
413        }
414
415        // url changes can cause the editor to be displayed again
416        self.api_key_editor
417            .update(cx, |editor, cx| editor.set_text("", window, cx));
418
419        let state = self.state.clone();
420        cx.spawn_in(window, async move |_, cx| {
421            state
422                .update(cx, |state, cx| state.set_api_key(Some(api_key), cx))
423                .await
424        })
425        .detach_and_log_err(cx);
426    }
427
428    fn reset_api_key(&mut self, window: &mut Window, cx: &mut Context<Self>) {
429        self.api_key_editor
430            .update(cx, |input, cx| input.set_text("", window, cx));
431
432        let state = self.state.clone();
433        cx.spawn_in(window, async move |_, cx| {
434            state
435                .update(cx, |state, cx| state.set_api_key(None, cx))
436                .await
437        })
438        .detach_and_log_err(cx);
439    }
440
441    fn should_render_editor(&self, cx: &mut Context<Self>) -> bool {
442        !self.state.read(cx).is_authenticated()
443    }
444}
445
446impl Render for ConfigurationView {
447    fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
448        let env_var_set = self.state.read(cx).api_key_state.is_from_env_var();
449        let configured_card_label = if env_var_set {
450            format!("API key set in {API_KEY_ENV_VAR_NAME} environment variable")
451        } else {
452            let api_url = XAiLanguageModelProvider::api_url(cx);
453            if api_url == XAI_API_URL {
454                "API key configured".to_string()
455            } else {
456                format!("API key configured for {}", api_url)
457            }
458        };
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(
467                            ListBulletItem::new("")
468                                .child(Label::new("Create one by visiting"))
469                                .child(ButtonLink::new("xAI console", "https://console.x.ai/team/default/api-keys"))
470                        )
471                        .child(
472                            ListBulletItem::new("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 set 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_element()
489        } else {
490            ConfiguredApiCard::new(configured_card_label)
491                .disabled(env_var_set)
492                .when(env_var_set, |this| {
493                    this.tooltip_label(format!("To reset your API key, unset the {API_KEY_ENV_VAR_NAME} environment variable."))
494                })
495                .on_click(cx.listener(|this, _, window, cx| this.reset_api_key(window, cx)))
496                .into_any_element()
497        };
498
499        if self.load_credentials_task.is_some() {
500            div().child(Label::new("Loading credentials…")).into_any()
501        } else {
502            v_flex().size_full().child(api_key_section).into_any()
503        }
504    }
505}