1use anyhow::{Result, anyhow};
2use fs::Fs;
3use futures::{FutureExt, StreamExt, future::BoxFuture, stream::BoxStream};
4use futures::{Stream, TryFutureExt, stream};
5use gpui::{AnyView, App, AsyncApp, Context, CursorStyle, Entity, Task};
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, LanguageModelRequestTool, LanguageModelToolChoice, LanguageModelToolUse,
12 LanguageModelToolUseId, MessageContent, RateLimiter, Role, StopReason, TokenUsage, env_var,
13};
14use menu;
15use ollama::{
16 ChatMessage, ChatOptions, ChatRequest, ChatResponseDelta, OLLAMA_API_URL, OllamaFunctionCall,
17 OllamaFunctionTool, OllamaToolCall, get_models, show_model, stream_chat_completion,
18};
19pub use settings::OllamaAvailableModel as AvailableModel;
20use settings::{Settings, SettingsStore, update_settings_file};
21use std::pin::Pin;
22use std::sync::LazyLock;
23use std::sync::atomic::{AtomicU64, Ordering};
24use std::{collections::HashMap, sync::Arc};
25use ui::{
26 ButtonLike, ButtonLink, ConfiguredApiCard, ElevationIndex, List, ListBulletItem, Tooltip,
27 prelude::*,
28};
29use ui_input::InputField;
30
31use crate::AllLanguageModelSettings;
32
33const OLLAMA_DOWNLOAD_URL: &str = "https://ollama.com/download";
34const OLLAMA_LIBRARY_URL: &str = "https://ollama.com/library";
35const OLLAMA_SITE: &str = "https://ollama.com/";
36
37const PROVIDER_ID: LanguageModelProviderId = LanguageModelProviderId::new("ollama");
38const PROVIDER_NAME: LanguageModelProviderName = LanguageModelProviderName::new("Ollama");
39
40const API_KEY_ENV_VAR_NAME: &str = "OLLAMA_API_KEY";
41static API_KEY_ENV_VAR: LazyLock<EnvVar> = env_var!(API_KEY_ENV_VAR_NAME);
42
43#[derive(Default, Debug, Clone, PartialEq)]
44pub struct OllamaSettings {
45 pub api_url: String,
46 pub auto_discover: bool,
47 pub available_models: Vec<AvailableModel>,
48}
49
50pub struct OllamaLanguageModelProvider {
51 http_client: Arc<dyn HttpClient>,
52 state: Entity<State>,
53}
54
55pub struct State {
56 api_key_state: ApiKeyState,
57 http_client: Arc<dyn HttpClient>,
58 fetched_models: Vec<ollama::Model>,
59 fetch_model_task: Option<Task<Result<()>>>,
60}
61
62impl State {
63 fn is_authenticated(&self) -> bool {
64 !self.fetched_models.is_empty()
65 }
66
67 fn set_api_key(&mut self, api_key: Option<String>, cx: &mut Context<Self>) -> Task<Result<()>> {
68 let api_url = OllamaLanguageModelProvider::api_url(cx);
69 let task = self
70 .api_key_state
71 .store(api_url, api_key, |this| &mut this.api_key_state, cx);
72
73 self.fetched_models.clear();
74 cx.spawn(async move |this, cx| {
75 let result = task.await;
76 this.update(cx, |this, cx| this.restart_fetch_models_task(cx))
77 .ok();
78 result
79 })
80 }
81
82 fn authenticate(&mut self, cx: &mut Context<Self>) -> Task<Result<(), AuthenticateError>> {
83 let api_url = OllamaLanguageModelProvider::api_url(cx);
84 let task = self
85 .api_key_state
86 .load_if_needed(api_url, |this| &mut this.api_key_state, cx);
87
88 // Always try to fetch models - if no API key is needed (local Ollama), it will work
89 // If API key is needed and provided, it will work
90 // If API key is needed and not provided, it will fail gracefully
91 cx.spawn(async move |this, cx| {
92 let result = task.await;
93 this.update(cx, |this, cx| this.restart_fetch_models_task(cx))
94 .ok();
95 result
96 })
97 }
98
99 fn fetch_models(&mut self, cx: &mut Context<Self>) -> Task<Result<()>> {
100 let http_client = Arc::clone(&self.http_client);
101 let api_url = OllamaLanguageModelProvider::api_url(cx);
102 let api_key = self.api_key_state.key(&api_url);
103
104 // As a proxy for the server being "authenticated", we'll check if its up by fetching the models
105 cx.spawn(async move |this, cx| {
106 let models = get_models(http_client.as_ref(), &api_url, api_key.as_deref()).await?;
107
108 let tasks = models
109 .into_iter()
110 // Since there is no metadata from the Ollama API
111 // indicating which models are embedding models,
112 // simply filter out models with "-embed" in their name
113 .filter(|model| !model.name.contains("-embed"))
114 .map(|model| {
115 let http_client = Arc::clone(&http_client);
116 let api_url = api_url.clone();
117 let api_key = api_key.clone();
118 async move {
119 let name = model.name.as_str();
120 let model =
121 show_model(http_client.as_ref(), &api_url, api_key.as_deref(), name)
122 .await?;
123 let ollama_model = ollama::Model::new(
124 name,
125 None,
126 model.context_length,
127 Some(model.supports_tools()),
128 Some(model.supports_vision()),
129 Some(model.supports_thinking()),
130 );
131 Ok(ollama_model)
132 }
133 });
134
135 // Rate-limit capability fetches
136 // since there is an arbitrary number of models available
137 let mut ollama_models: Vec<_> = futures::stream::iter(tasks)
138 .buffer_unordered(5)
139 .collect::<Vec<Result<_>>>()
140 .await
141 .into_iter()
142 .collect::<Result<Vec<_>>>()?;
143
144 ollama_models.sort_by(|a, b| a.name.cmp(&b.name));
145
146 this.update(cx, |this, cx| {
147 this.fetched_models = ollama_models;
148 cx.notify();
149 })
150 })
151 }
152
153 fn restart_fetch_models_task(&mut self, cx: &mut Context<Self>) {
154 let task = self.fetch_models(cx);
155 self.fetch_model_task.replace(task);
156 }
157}
158
159impl OllamaLanguageModelProvider {
160 pub fn new(http_client: Arc<dyn HttpClient>, cx: &mut App) -> Self {
161 let this = Self {
162 http_client: http_client.clone(),
163 state: cx.new(|cx| {
164 cx.observe_global::<SettingsStore>({
165 let mut last_settings = OllamaLanguageModelProvider::settings(cx).clone();
166 move |this: &mut State, cx| {
167 let current_settings = OllamaLanguageModelProvider::settings(cx);
168 let settings_changed = current_settings != &last_settings;
169 if settings_changed {
170 let url_changed = last_settings.api_url != current_settings.api_url;
171 last_settings = current_settings.clone();
172 if url_changed {
173 this.fetched_models.clear();
174 this.authenticate(cx).detach();
175 }
176 cx.notify();
177 }
178 }
179 })
180 .detach();
181
182 State {
183 http_client,
184 fetched_models: Default::default(),
185 fetch_model_task: None,
186 api_key_state: ApiKeyState::new(Self::api_url(cx), (*API_KEY_ENV_VAR).clone()),
187 }
188 }),
189 };
190 this
191 }
192
193 fn settings(cx: &App) -> &OllamaSettings {
194 &AllLanguageModelSettings::get_global(cx).ollama
195 }
196
197 fn api_url(cx: &App) -> SharedString {
198 let api_url = &Self::settings(cx).api_url;
199 if api_url.is_empty() {
200 OLLAMA_API_URL.into()
201 } else {
202 SharedString::new(api_url.as_str())
203 }
204 }
205}
206
207impl LanguageModelProviderState for OllamaLanguageModelProvider {
208 type ObservableEntity = State;
209
210 fn observable_entity(&self) -> Option<Entity<Self::ObservableEntity>> {
211 Some(self.state.clone())
212 }
213}
214
215impl LanguageModelProvider for OllamaLanguageModelProvider {
216 fn id(&self) -> LanguageModelProviderId {
217 PROVIDER_ID
218 }
219
220 fn name(&self) -> LanguageModelProviderName {
221 PROVIDER_NAME
222 }
223
224 fn icon(&self) -> IconOrSvg {
225 IconOrSvg::Icon(IconName::AiOllama)
226 }
227
228 fn default_model(&self, _: &App) -> Option<Arc<dyn LanguageModel>> {
229 // We shouldn't try to select default model, because it might lead to a load call for an unloaded model.
230 // In a constrained environment where user might not have enough resources it'll be a bad UX to select something
231 // to load by default.
232 None
233 }
234
235 fn default_fast_model(&self, _: &App) -> Option<Arc<dyn LanguageModel>> {
236 // See explanation for default_model.
237 None
238 }
239
240 fn provided_models(&self, cx: &App) -> Vec<Arc<dyn LanguageModel>> {
241 let mut models: HashMap<String, ollama::Model> = HashMap::new();
242 let settings = OllamaLanguageModelProvider::settings(cx);
243
244 // Add models from the Ollama API
245 if settings.auto_discover {
246 for model in self.state.read(cx).fetched_models.iter() {
247 models.insert(model.name.clone(), model.clone());
248 }
249 }
250
251 // Override with available models from settings
252 merge_settings_into_models(&mut models, &settings.available_models);
253
254 let mut models = models
255 .into_values()
256 .map(|model| {
257 Arc::new(OllamaLanguageModel {
258 id: LanguageModelId::from(model.name.clone()),
259 model,
260 http_client: self.http_client.clone(),
261 request_limiter: RateLimiter::new(4),
262 state: self.state.clone(),
263 }) as Arc<dyn LanguageModel>
264 })
265 .collect::<Vec<_>>();
266 models.sort_by_key(|model| model.name());
267 models
268 }
269
270 fn is_authenticated(&self, cx: &App) -> bool {
271 self.state.read(cx).is_authenticated()
272 }
273
274 fn authenticate(&self, cx: &mut App) -> Task<Result<(), AuthenticateError>> {
275 self.state.update(cx, |state, cx| state.authenticate(cx))
276 }
277
278 fn configuration_view(
279 &self,
280 _target_agent: language_model::ConfigurationViewTargetAgent,
281 window: &mut Window,
282 cx: &mut App,
283 ) -> AnyView {
284 let state = self.state.clone();
285 cx.new(|cx| ConfigurationView::new(state, window, cx))
286 .into()
287 }
288
289 fn reset_credentials(&self, cx: &mut App) -> Task<Result<()>> {
290 self.state
291 .update(cx, |state, cx| state.set_api_key(None, cx))
292 }
293}
294
295pub struct OllamaLanguageModel {
296 id: LanguageModelId,
297 model: ollama::Model,
298 http_client: Arc<dyn HttpClient>,
299 request_limiter: RateLimiter,
300 state: Entity<State>,
301}
302
303impl OllamaLanguageModel {
304 fn to_ollama_request(&self, request: LanguageModelRequest) -> ChatRequest {
305 let supports_vision = self.model.supports_vision.unwrap_or(false);
306
307 let mut messages = Vec::with_capacity(request.messages.len());
308
309 for mut msg in request.messages.into_iter() {
310 let images = if supports_vision {
311 msg.content
312 .iter()
313 .filter_map(|content| match content {
314 MessageContent::Image(image) => Some(image.source.to_string()),
315 _ => None,
316 })
317 .collect::<Vec<String>>()
318 } else {
319 vec![]
320 };
321
322 match msg.role {
323 Role::User => {
324 for tool_result in msg
325 .content
326 .extract_if(.., |x| matches!(x, MessageContent::ToolResult(..)))
327 {
328 match tool_result {
329 MessageContent::ToolResult(tool_result) => {
330 messages.push(ChatMessage::Tool {
331 tool_name: tool_result.tool_name.to_string(),
332 content: tool_result.content.to_str().unwrap_or("").to_string(),
333 })
334 }
335 _ => unreachable!("Only tool result should be extracted"),
336 }
337 }
338 if !msg.content.is_empty() {
339 messages.push(ChatMessage::User {
340 content: msg.string_contents(),
341 images: if images.is_empty() {
342 None
343 } else {
344 Some(images)
345 },
346 })
347 }
348 }
349 Role::Assistant => {
350 let content = msg.string_contents();
351 let mut thinking = None;
352 let mut tool_calls = Vec::new();
353 for content in msg.content.into_iter() {
354 match content {
355 MessageContent::Thinking { text, .. } if !text.is_empty() => {
356 thinking = Some(text)
357 }
358 MessageContent::ToolUse(tool_use) => {
359 tool_calls.push(OllamaToolCall {
360 id: Some(tool_use.id.to_string()),
361 function: OllamaFunctionCall {
362 name: tool_use.name.to_string(),
363 arguments: tool_use.input,
364 },
365 });
366 }
367 _ => (),
368 }
369 }
370 messages.push(ChatMessage::Assistant {
371 content,
372 tool_calls: Some(tool_calls),
373 images: if images.is_empty() {
374 None
375 } else {
376 Some(images)
377 },
378 thinking,
379 })
380 }
381 Role::System => messages.push(ChatMessage::System {
382 content: msg.string_contents(),
383 }),
384 }
385 }
386 ChatRequest {
387 model: self.model.name.clone(),
388 messages,
389 keep_alive: self.model.keep_alive.clone().unwrap_or_default(),
390 stream: true,
391 options: Some(ChatOptions {
392 num_ctx: Some(self.model.max_tokens),
393 stop: Some(request.stop),
394 temperature: request.temperature.or(Some(1.0)),
395 ..Default::default()
396 }),
397 think: self
398 .model
399 .supports_thinking
400 .map(|supports_thinking| supports_thinking && request.thinking_allowed),
401 tools: if self.model.supports_tools.unwrap_or(false) {
402 request.tools.into_iter().map(tool_into_ollama).collect()
403 } else {
404 vec![]
405 },
406 }
407 }
408}
409
410impl LanguageModel for OllamaLanguageModel {
411 fn id(&self) -> LanguageModelId {
412 self.id.clone()
413 }
414
415 fn name(&self) -> LanguageModelName {
416 LanguageModelName::from(self.model.display_name().to_string())
417 }
418
419 fn provider_id(&self) -> LanguageModelProviderId {
420 PROVIDER_ID
421 }
422
423 fn provider_name(&self) -> LanguageModelProviderName {
424 PROVIDER_NAME
425 }
426
427 fn supports_tools(&self) -> bool {
428 self.model.supports_tools.unwrap_or(false)
429 }
430
431 fn supports_images(&self) -> bool {
432 self.model.supports_vision.unwrap_or(false)
433 }
434
435 fn supports_tool_choice(&self, choice: LanguageModelToolChoice) -> bool {
436 match choice {
437 LanguageModelToolChoice::Auto => false,
438 LanguageModelToolChoice::Any => false,
439 LanguageModelToolChoice::None => false,
440 }
441 }
442
443 fn telemetry_id(&self) -> String {
444 format!("ollama/{}", self.model.id())
445 }
446
447 fn max_token_count(&self) -> u64 {
448 self.model.max_token_count()
449 }
450
451 fn count_tokens(
452 &self,
453 request: LanguageModelRequest,
454 _cx: &App,
455 ) -> BoxFuture<'static, Result<u64>> {
456 // There is no endpoint for this _yet_ in Ollama
457 // see: https://github.com/ollama/ollama/issues/1716 and https://github.com/ollama/ollama/issues/3582
458 let token_count = request
459 .messages
460 .iter()
461 .map(|msg| msg.string_contents().chars().count())
462 .sum::<usize>()
463 / 4;
464
465 async move { Ok(token_count as u64) }.boxed()
466 }
467
468 fn stream_completion(
469 &self,
470 request: LanguageModelRequest,
471 cx: &AsyncApp,
472 ) -> BoxFuture<
473 'static,
474 Result<
475 BoxStream<'static, Result<LanguageModelCompletionEvent, LanguageModelCompletionError>>,
476 LanguageModelCompletionError,
477 >,
478 > {
479 let request = self.to_ollama_request(request);
480
481 let http_client = self.http_client.clone();
482 let (api_key, api_url) = self.state.read_with(cx, |state, cx| {
483 let api_url = OllamaLanguageModelProvider::api_url(cx);
484 (state.api_key_state.key(&api_url), api_url)
485 });
486
487 let future = self.request_limiter.stream(async move {
488 let stream =
489 stream_chat_completion(http_client.as_ref(), &api_url, api_key.as_deref(), request)
490 .await?;
491 let stream = map_to_language_model_completion_events(stream);
492 Ok(stream)
493 });
494
495 future.map_ok(|f| f.boxed()).boxed()
496 }
497}
498
499fn map_to_language_model_completion_events(
500 stream: Pin<Box<dyn Stream<Item = anyhow::Result<ChatResponseDelta>> + Send>>,
501) -> impl Stream<Item = Result<LanguageModelCompletionEvent, LanguageModelCompletionError>> {
502 // Used for creating unique tool use ids
503 static TOOL_CALL_COUNTER: AtomicU64 = AtomicU64::new(0);
504
505 struct State {
506 stream: Pin<Box<dyn Stream<Item = anyhow::Result<ChatResponseDelta>> + Send>>,
507 used_tools: bool,
508 }
509
510 // We need to create a ToolUse and Stop event from a single
511 // response from the original stream
512 let stream = stream::unfold(
513 State {
514 stream,
515 used_tools: false,
516 },
517 async move |mut state| {
518 let response = state.stream.next().await?;
519
520 let delta = match response {
521 Ok(delta) => delta,
522 Err(e) => {
523 let event = Err(LanguageModelCompletionError::from(anyhow!(e)));
524 return Some((vec![event], state));
525 }
526 };
527
528 let mut events = Vec::new();
529
530 match delta.message {
531 ChatMessage::User { content, images: _ } => {
532 events.push(Ok(LanguageModelCompletionEvent::Text(content)));
533 }
534 ChatMessage::System { content } => {
535 events.push(Ok(LanguageModelCompletionEvent::Text(content)));
536 }
537 ChatMessage::Tool { content, .. } => {
538 events.push(Ok(LanguageModelCompletionEvent::Text(content)));
539 }
540 ChatMessage::Assistant {
541 content,
542 tool_calls,
543 images: _,
544 thinking,
545 } => {
546 if let Some(text) = thinking {
547 events.push(Ok(LanguageModelCompletionEvent::Thinking {
548 text,
549 signature: None,
550 }));
551 }
552
553 if let Some(tool_call) = tool_calls.and_then(|v| v.into_iter().next()) {
554 let OllamaToolCall { id, function } = tool_call;
555 let id = id.unwrap_or_else(|| {
556 format!(
557 "{}-{}",
558 &function.name,
559 TOOL_CALL_COUNTER.fetch_add(1, Ordering::Relaxed)
560 )
561 });
562 let event = LanguageModelCompletionEvent::ToolUse(LanguageModelToolUse {
563 id: LanguageModelToolUseId::from(id),
564 name: Arc::from(function.name),
565 raw_input: function.arguments.to_string(),
566 input: function.arguments,
567 is_input_complete: true,
568 thought_signature: None,
569 });
570 events.push(Ok(event));
571 state.used_tools = true;
572 } else if !content.is_empty() {
573 events.push(Ok(LanguageModelCompletionEvent::Text(content)));
574 }
575 }
576 };
577
578 if delta.done {
579 events.push(Ok(LanguageModelCompletionEvent::UsageUpdate(TokenUsage {
580 input_tokens: delta.prompt_eval_count.unwrap_or(0),
581 output_tokens: delta.eval_count.unwrap_or(0),
582 cache_creation_input_tokens: 0,
583 cache_read_input_tokens: 0,
584 })));
585 if state.used_tools {
586 state.used_tools = false;
587 events.push(Ok(LanguageModelCompletionEvent::Stop(StopReason::ToolUse)));
588 } else {
589 events.push(Ok(LanguageModelCompletionEvent::Stop(StopReason::EndTurn)));
590 }
591 }
592
593 Some((events, state))
594 },
595 );
596
597 stream.flat_map(futures::stream::iter)
598}
599
600struct ConfigurationView {
601 api_key_editor: Entity<InputField>,
602 api_url_editor: Entity<InputField>,
603 state: Entity<State>,
604}
605
606impl ConfigurationView {
607 pub fn new(state: Entity<State>, window: &mut Window, cx: &mut Context<Self>) -> Self {
608 let api_key_editor = cx.new(|cx| InputField::new(window, cx, "63e02e...").label("API key"));
609
610 let api_url_editor = cx.new(|cx| {
611 let input = InputField::new(window, cx, OLLAMA_API_URL).label("API URL");
612 input.set_text(OllamaLanguageModelProvider::api_url(cx), window, cx);
613 input
614 });
615
616 cx.observe(&state, |_, _, cx| {
617 cx.notify();
618 })
619 .detach();
620
621 Self {
622 api_key_editor,
623 api_url_editor,
624 state,
625 }
626 }
627
628 fn retry_connection(&self, cx: &mut App) {
629 self.state
630 .update(cx, |state, cx| state.restart_fetch_models_task(cx));
631 }
632
633 fn save_api_key(&mut self, _: &menu::Confirm, window: &mut Window, cx: &mut Context<Self>) {
634 let api_key = self.api_key_editor.read(cx).text(cx).trim().to_string();
635 if api_key.is_empty() {
636 return;
637 }
638
639 // url changes can cause the editor to be displayed again
640 self.api_key_editor
641 .update(cx, |input, cx| input.set_text("", window, cx));
642
643 let state = self.state.clone();
644 cx.spawn_in(window, async move |_, cx| {
645 state
646 .update(cx, |state, cx| state.set_api_key(Some(api_key), cx))
647 .await
648 })
649 .detach_and_log_err(cx);
650 }
651
652 fn reset_api_key(&mut self, window: &mut Window, cx: &mut Context<Self>) {
653 self.api_key_editor
654 .update(cx, |input, cx| input.set_text("", window, cx));
655
656 let state = self.state.clone();
657 cx.spawn_in(window, async move |_, cx| {
658 state
659 .update(cx, |state, cx| state.set_api_key(None, cx))
660 .await
661 })
662 .detach_and_log_err(cx);
663
664 cx.notify();
665 }
666
667 fn save_api_url(&mut self, cx: &mut Context<Self>) {
668 let api_url = self.api_url_editor.read(cx).text(cx).trim().to_string();
669 let current_url = OllamaLanguageModelProvider::api_url(cx);
670 if !api_url.is_empty() && &api_url != ¤t_url {
671 let fs = <dyn Fs>::global(cx);
672 update_settings_file(fs, cx, move |settings, _| {
673 settings
674 .language_models
675 .get_or_insert_default()
676 .ollama
677 .get_or_insert_default()
678 .api_url = Some(api_url);
679 });
680 }
681 }
682
683 fn reset_api_url(&mut self, window: &mut Window, cx: &mut Context<Self>) {
684 self.api_url_editor
685 .update(cx, |input, cx| input.set_text("", window, cx));
686 let fs = <dyn Fs>::global(cx);
687 update_settings_file(fs, cx, |settings, _cx| {
688 if let Some(settings) = settings
689 .language_models
690 .as_mut()
691 .and_then(|models| models.ollama.as_mut())
692 {
693 settings.api_url = Some(OLLAMA_API_URL.into());
694 }
695 });
696 cx.notify();
697 }
698
699 fn render_instructions(cx: &mut Context<Self>) -> Div {
700 v_flex()
701 .gap_2()
702 .child(Label::new(
703 "Run LLMs locally on your machine with Ollama, or connect to an Ollama server. \
704 Can provide access to Llama, Mistral, Gemma, and hundreds of other models.",
705 ))
706 .child(Label::new("To use local Ollama:"))
707 .child(
708 List::new()
709 .child(
710 ListBulletItem::new("")
711 .child(Label::new("Download and install Ollama from"))
712 .child(ButtonLink::new("ollama.com", "https://ollama.com/download")),
713 )
714 .child(
715 ListBulletItem::new("")
716 .child(Label::new("Start Ollama and download a model:"))
717 .child(Label::new("ollama run gpt-oss:20b").inline_code(cx)),
718 )
719 .child(ListBulletItem::new(
720 "Click 'Connect' below to start using Ollama in Zed",
721 )),
722 )
723 .child(Label::new(
724 "Alternatively, you can connect to an Ollama server by specifying its \
725 URL and API key (may not be required):",
726 ))
727 }
728
729 fn render_api_key_editor(&self, cx: &Context<Self>) -> impl IntoElement {
730 let state = self.state.read(cx);
731 let env_var_set = state.api_key_state.is_from_env_var();
732 let configured_card_label = if env_var_set {
733 format!("API key set in {API_KEY_ENV_VAR_NAME} environment variable.")
734 } else {
735 "API key configured".to_string()
736 };
737
738 if !state.api_key_state.has_key() {
739 v_flex()
740 .on_action(cx.listener(Self::save_api_key))
741 .child(self.api_key_editor.clone())
742 .child(
743 Label::new(
744 format!("You can also set the {API_KEY_ENV_VAR_NAME} environment variable and restart Zed.")
745 )
746 .size(LabelSize::Small)
747 .color(Color::Muted),
748 )
749 .into_any_element()
750 } else {
751 ConfiguredApiCard::new(configured_card_label)
752 .disabled(env_var_set)
753 .on_click(cx.listener(|this, _, window, cx| this.reset_api_key(window, cx)))
754 .when(env_var_set, |this| {
755 this.tooltip_label(format!("To reset your API key, unset the {API_KEY_ENV_VAR_NAME} environment variable."))
756 })
757 .into_any_element()
758 }
759 }
760
761 fn render_api_url_editor(&self, cx: &Context<Self>) -> Div {
762 let api_url = OllamaLanguageModelProvider::api_url(cx);
763 let custom_api_url_set = api_url != OLLAMA_API_URL;
764
765 if custom_api_url_set {
766 h_flex()
767 .p_3()
768 .justify_between()
769 .rounded_md()
770 .border_1()
771 .border_color(cx.theme().colors().border)
772 .bg(cx.theme().colors().elevated_surface_background)
773 .child(
774 h_flex()
775 .gap_2()
776 .child(Icon::new(IconName::Check).color(Color::Success))
777 .child(v_flex().gap_1().child(Label::new(api_url))),
778 )
779 .child(
780 Button::new("reset-api-url", "Reset API URL")
781 .label_size(LabelSize::Small)
782 .icon(IconName::Undo)
783 .icon_size(IconSize::Small)
784 .icon_position(IconPosition::Start)
785 .layer(ElevationIndex::ModalSurface)
786 .on_click(
787 cx.listener(|this, _, window, cx| this.reset_api_url(window, cx)),
788 ),
789 )
790 } else {
791 v_flex()
792 .on_action(cx.listener(|this, _: &menu::Confirm, _window, cx| {
793 this.save_api_url(cx);
794 cx.notify();
795 }))
796 .gap_2()
797 .child(self.api_url_editor.clone())
798 }
799 }
800}
801
802impl Render for ConfigurationView {
803 fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
804 let is_authenticated = self.state.read(cx).is_authenticated();
805
806 v_flex()
807 .gap_2()
808 .child(Self::render_instructions(cx))
809 .child(self.render_api_url_editor(cx))
810 .child(self.render_api_key_editor(cx))
811 .child(
812 h_flex()
813 .w_full()
814 .justify_between()
815 .gap_2()
816 .child(
817 h_flex()
818 .w_full()
819 .gap_2()
820 .map(|this| {
821 if is_authenticated {
822 this.child(
823 Button::new("ollama-site", "Ollama")
824 .style(ButtonStyle::Subtle)
825 .icon(IconName::ArrowUpRight)
826 .icon_size(IconSize::XSmall)
827 .icon_color(Color::Muted)
828 .on_click(move |_, _, cx| cx.open_url(OLLAMA_SITE))
829 .into_any_element(),
830 )
831 } else {
832 this.child(
833 Button::new("download_ollama_button", "Download Ollama")
834 .style(ButtonStyle::Subtle)
835 .icon(IconName::ArrowUpRight)
836 .icon_size(IconSize::XSmall)
837 .icon_color(Color::Muted)
838 .on_click(move |_, _, cx| {
839 cx.open_url(OLLAMA_DOWNLOAD_URL)
840 })
841 .into_any_element(),
842 )
843 }
844 })
845 .child(
846 Button::new("view-models", "View All Models")
847 .style(ButtonStyle::Subtle)
848 .icon(IconName::ArrowUpRight)
849 .icon_size(IconSize::XSmall)
850 .icon_color(Color::Muted)
851 .on_click(move |_, _, cx| cx.open_url(OLLAMA_LIBRARY_URL)),
852 ),
853 )
854 .map(|this| {
855 if is_authenticated {
856 this.child(
857 ButtonLike::new("connected")
858 .disabled(true)
859 .cursor_style(CursorStyle::Arrow)
860 .child(
861 h_flex()
862 .gap_2()
863 .child(Icon::new(IconName::Check).color(Color::Success))
864 .child(Label::new("Connected"))
865 .into_any_element(),
866 )
867 .child(
868 IconButton::new("refresh-models", IconName::RotateCcw)
869 .tooltip(Tooltip::text("Refresh Models"))
870 .on_click(cx.listener(|this, _, _, cx| {
871 this.state.update(cx, |state, _| {
872 state.fetched_models.clear();
873 });
874 this.retry_connection(cx);
875 })),
876 ),
877 )
878 } else {
879 this.child(
880 Button::new("retry_ollama_models", "Connect")
881 .icon_position(IconPosition::Start)
882 .icon_size(IconSize::XSmall)
883 .icon(IconName::PlayOutlined)
884 .on_click(
885 cx.listener(move |this, _, _, cx| {
886 this.retry_connection(cx)
887 }),
888 ),
889 )
890 }
891 }),
892 )
893 }
894}
895
896fn merge_settings_into_models(
897 models: &mut HashMap<String, ollama::Model>,
898 available_models: &[AvailableModel],
899) {
900 for setting_model in available_models {
901 if let Some(model) = models.get_mut(&setting_model.name) {
902 model.max_tokens = setting_model.max_tokens;
903 model.display_name = setting_model.display_name.clone();
904 model.keep_alive = setting_model.keep_alive.clone();
905 model.supports_tools = setting_model.supports_tools;
906 model.supports_vision = setting_model.supports_images;
907 model.supports_thinking = setting_model.supports_thinking;
908 } else {
909 models.insert(
910 setting_model.name.clone(),
911 ollama::Model {
912 name: setting_model.name.clone(),
913 display_name: setting_model.display_name.clone(),
914 max_tokens: setting_model.max_tokens,
915 keep_alive: setting_model.keep_alive.clone(),
916 supports_tools: setting_model.supports_tools,
917 supports_vision: setting_model.supports_images,
918 supports_thinking: setting_model.supports_thinking,
919 },
920 );
921 }
922 }
923}
924
925fn tool_into_ollama(tool: LanguageModelRequestTool) -> ollama::OllamaTool {
926 ollama::OllamaTool::Function {
927 function: OllamaFunctionTool {
928 name: tool.name,
929 description: Some(tool.description),
930 parameters: Some(tool.input_schema),
931 },
932 }
933}
934
935#[cfg(test)]
936mod tests {
937 use super::*;
938
939 #[test]
940 fn test_merge_settings_preserves_display_names_for_similar_models() {
941 // Regression test for https://github.com/zed-industries/zed/issues/43646
942 // When multiple models share the same base name (e.g., qwen2.5-coder:1.5b and qwen2.5-coder:3b),
943 // each model should get its own display_name from settings, not a random one.
944
945 let mut models: HashMap<String, ollama::Model> = HashMap::new();
946 models.insert(
947 "qwen2.5-coder:1.5b".to_string(),
948 ollama::Model {
949 name: "qwen2.5-coder:1.5b".to_string(),
950 display_name: None,
951 max_tokens: 4096,
952 keep_alive: None,
953 supports_tools: None,
954 supports_vision: None,
955 supports_thinking: None,
956 },
957 );
958 models.insert(
959 "qwen2.5-coder:3b".to_string(),
960 ollama::Model {
961 name: "qwen2.5-coder:3b".to_string(),
962 display_name: None,
963 max_tokens: 4096,
964 keep_alive: None,
965 supports_tools: None,
966 supports_vision: None,
967 supports_thinking: None,
968 },
969 );
970
971 let available_models = vec![
972 AvailableModel {
973 name: "qwen2.5-coder:1.5b".to_string(),
974 display_name: Some("QWEN2.5 Coder 1.5B".to_string()),
975 max_tokens: 5000,
976 keep_alive: None,
977 supports_tools: Some(true),
978 supports_images: None,
979 supports_thinking: None,
980 },
981 AvailableModel {
982 name: "qwen2.5-coder:3b".to_string(),
983 display_name: Some("QWEN2.5 Coder 3B".to_string()),
984 max_tokens: 6000,
985 keep_alive: None,
986 supports_tools: Some(true),
987 supports_images: None,
988 supports_thinking: None,
989 },
990 ];
991
992 merge_settings_into_models(&mut models, &available_models);
993
994 let model_1_5b = models
995 .get("qwen2.5-coder:1.5b")
996 .expect("1.5b model missing");
997 let model_3b = models.get("qwen2.5-coder:3b").expect("3b model missing");
998
999 assert_eq!(
1000 model_1_5b.display_name,
1001 Some("QWEN2.5 Coder 1.5B".to_string()),
1002 "1.5b model should have its own display_name"
1003 );
1004 assert_eq!(model_1_5b.max_tokens, 5000);
1005
1006 assert_eq!(
1007 model_3b.display_name,
1008 Some("QWEN2.5 Coder 3B".to_string()),
1009 "3b model should have its own display_name"
1010 );
1011 assert_eq!(model_3b.max_tokens, 6000);
1012 }
1013}