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