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