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<
215 'static,
216 Result<
217 futures::stream::BoxStream<'static, Result<ResponseStreamEvent>>,
218 LanguageModelCompletionError,
219 >,
220 > {
221 let http_client = self.http_client.clone();
222
223 let Ok((api_key, api_url)) = self.state.read_with(cx, |state, cx| {
224 let api_url = XAiLanguageModelProvider::api_url(cx);
225 (state.api_key_state.key(&api_url), api_url)
226 }) else {
227 return future::ready(Err(anyhow!("App state dropped").into())).boxed();
228 };
229
230 let future = self.request_limiter.stream(async move {
231 let provider = PROVIDER_NAME;
232 let Some(api_key) = api_key else {
233 return Err(LanguageModelCompletionError::NoApiKey { provider });
234 };
235 let request = open_ai::stream_completion(
236 http_client.as_ref(),
237 provider.0.as_str(),
238 &api_url,
239 &api_key,
240 request,
241 );
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<InputField>,
375 state: Entity<State>,
376 load_credentials_task: Option<Task<()>>,
377}
378
379impl ConfigurationView {
380 fn new(state: Entity<State>, window: &mut Window, cx: &mut Context<Self>) -> Self {
381 let api_key_editor = cx.new(|cx| {
382 InputField::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 // url changes can cause the editor to be displayed again
427 self.api_key_editor
428 .update(cx, |editor, cx| editor.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(Some(api_key), cx))?
434 .await
435 })
436 .detach_and_log_err(cx);
437 }
438
439 fn reset_api_key(&mut self, window: &mut Window, cx: &mut Context<Self>) {
440 self.api_key_editor
441 .update(cx, |input, cx| input.set_text("", window, cx));
442
443 let state = self.state.clone();
444 cx.spawn_in(window, async move |_, cx| {
445 state
446 .update(cx, |state, cx| state.set_api_key(None, cx))?
447 .await
448 })
449 .detach_and_log_err(cx);
450 }
451
452 fn should_render_editor(&self, cx: &mut Context<Self>) -> bool {
453 !self.state.read(cx).is_authenticated()
454 }
455}
456
457impl Render for ConfigurationView {
458 fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
459 let env_var_set = self.state.read(cx).api_key_state.is_from_env_var();
460 let configured_card_label = if env_var_set {
461 format!("API key set in {API_KEY_ENV_VAR_NAME} environment variable")
462 } else {
463 let api_url = XAiLanguageModelProvider::api_url(cx);
464 if api_url == XAI_API_URL {
465 "API key configured".to_string()
466 } else {
467 format!("API key configured for {}", api_url)
468 }
469 };
470
471 let api_key_section = if self.should_render_editor(cx) {
472 v_flex()
473 .on_action(cx.listener(Self::save_api_key))
474 .child(Label::new("To use Zed's agent with xAI, you need to add an API key. Follow these steps:"))
475 .child(
476 List::new()
477 .child(InstructionListItem::new(
478 "Create one by visiting",
479 Some("xAI console"),
480 Some("https://console.x.ai/team/default/api-keys"),
481 ))
482 .child(InstructionListItem::text_only(
483 "Paste your API key below and hit enter to start using the agent",
484 )),
485 )
486 .child(self.api_key_editor.clone())
487 .child(
488 Label::new(format!(
489 "You can also assign the {API_KEY_ENV_VAR_NAME} environment variable and restart Zed."
490 ))
491 .size(LabelSize::Small)
492 .color(Color::Muted),
493 )
494 .child(
495 Label::new("Note that xAI is a custom OpenAI-compatible provider.")
496 .size(LabelSize::Small)
497 .color(Color::Muted),
498 )
499 .into_any_element()
500 } else {
501 ConfiguredApiCard::new(configured_card_label)
502 .disabled(env_var_set)
503 .when(env_var_set, |this| {
504 this.tooltip_label(format!("To reset your API key, unset the {API_KEY_ENV_VAR_NAME} environment variable."))
505 })
506 .on_click(cx.listener(|this, _, window, cx| this.reset_api_key(window, cx)))
507 .into_any_element()
508 };
509
510 if self.load_credentials_task.is_some() {
511 div().child(Label::new("Loading credentials…")).into_any()
512 } else {
513 v_flex().size_full().child(api_key_section).into_any()
514 }
515 }
516}