1use anyhow::{Result, anyhow};
2use futures::{FutureExt, StreamExt, future::BoxFuture, stream::BoxStream};
3use futures::{Stream, TryFutureExt, stream};
4use gpui::{AnyView, App, AsyncApp, Context, Subscription, Task};
5use http_client::HttpClient;
6use language_model::{
7 AuthenticateError, LanguageModel, LanguageModelCompletionError, LanguageModelCompletionEvent,
8 LanguageModelId, LanguageModelName, LanguageModelProvider, LanguageModelProviderId,
9 LanguageModelProviderName, LanguageModelProviderState, LanguageModelRequest,
10 LanguageModelRequestTool, LanguageModelToolChoice, LanguageModelToolUse,
11 LanguageModelToolUseId, MessageContent, RateLimiter, Role, StopReason,
12};
13use ollama::{
14 ChatMessage, ChatOptions, ChatRequest, ChatResponseDelta, KeepAlive, OllamaFunctionTool,
15 OllamaToolCall, get_models, preload_model, show_model, stream_chat_completion,
16};
17use schemars::JsonSchema;
18use serde::{Deserialize, Serialize};
19use settings::{Settings, SettingsStore};
20use std::pin::Pin;
21use std::sync::atomic::{AtomicU64, Ordering};
22use std::{collections::HashMap, sync::Arc};
23use ui::{ButtonLike, Indicator, List, prelude::*};
24use util::ResultExt;
25
26use crate::AllLanguageModelSettings;
27use crate::ui::InstructionListItem;
28
29const OLLAMA_DOWNLOAD_URL: &str = "https://ollama.com/download";
30const OLLAMA_LIBRARY_URL: &str = "https://ollama.com/library";
31const OLLAMA_SITE: &str = "https://ollama.com/";
32
33const PROVIDER_ID: &str = "ollama";
34const PROVIDER_NAME: &str = "Ollama";
35
36#[derive(Default, Debug, Clone, PartialEq)]
37pub struct OllamaSettings {
38 pub api_url: String,
39 pub available_models: Vec<AvailableModel>,
40}
41
42#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
43pub struct AvailableModel {
44 /// The model name in the Ollama API (e.g. "llama3.2:latest")
45 pub name: String,
46 /// The model's name in Zed's UI, such as in the model selector dropdown menu in the assistant panel.
47 pub display_name: Option<String>,
48 /// The Context Length parameter to the model (aka num_ctx or n_ctx)
49 pub max_tokens: usize,
50 /// The number of seconds to keep the connection open after the last request
51 pub keep_alive: Option<KeepAlive>,
52 /// Whether the model supports tools
53 pub supports_tools: Option<bool>,
54 /// Whether the model supports vision
55 pub supports_images: Option<bool>,
56 /// Whether to enable think mode
57 pub supports_thinking: Option<bool>,
58}
59
60pub struct OllamaLanguageModelProvider {
61 http_client: Arc<dyn HttpClient>,
62 state: gpui::Entity<State>,
63}
64
65pub struct State {
66 http_client: Arc<dyn HttpClient>,
67 available_models: Vec<ollama::Model>,
68 fetch_model_task: Option<Task<Result<()>>>,
69 _subscription: Subscription,
70}
71
72impl State {
73 fn is_authenticated(&self) -> bool {
74 !self.available_models.is_empty()
75 }
76
77 fn fetch_models(&mut self, cx: &mut Context<Self>) -> Task<Result<()>> {
78 let settings = &AllLanguageModelSettings::get_global(cx).ollama;
79 let http_client = Arc::clone(&self.http_client);
80 let api_url = settings.api_url.clone();
81
82 // As a proxy for the server being "authenticated", we'll check if its up by fetching the models
83 cx.spawn(async move |this, cx| {
84 let models = get_models(http_client.as_ref(), &api_url, None).await?;
85
86 let tasks = models
87 .into_iter()
88 // Since there is no metadata from the Ollama API
89 // indicating which models are embedding models,
90 // simply filter out models with "-embed" in their name
91 .filter(|model| !model.name.contains("-embed"))
92 .map(|model| {
93 let http_client = Arc::clone(&http_client);
94 let api_url = api_url.clone();
95 async move {
96 let name = model.name.as_str();
97 let capabilities = show_model(http_client.as_ref(), &api_url, name).await?;
98 let ollama_model = ollama::Model::new(
99 name,
100 None,
101 None,
102 Some(capabilities.supports_tools()),
103 Some(capabilities.supports_vision()),
104 Some(capabilities.supports_thinking()),
105 );
106 Ok(ollama_model)
107 }
108 });
109
110 // Rate-limit capability fetches
111 // since there is an arbitrary number of models available
112 let mut ollama_models: Vec<_> = futures::stream::iter(tasks)
113 .buffer_unordered(5)
114 .collect::<Vec<Result<_>>>()
115 .await
116 .into_iter()
117 .collect::<Result<Vec<_>>>()?;
118
119 ollama_models.sort_by(|a, b| a.name.cmp(&b.name));
120
121 this.update(cx, |this, cx| {
122 this.available_models = ollama_models;
123 cx.notify();
124 })
125 })
126 }
127
128 fn restart_fetch_models_task(&mut self, cx: &mut Context<Self>) {
129 let task = self.fetch_models(cx);
130 self.fetch_model_task.replace(task);
131 }
132
133 fn authenticate(&mut self, cx: &mut Context<Self>) -> Task<Result<(), AuthenticateError>> {
134 if self.is_authenticated() {
135 return Task::ready(Ok(()));
136 }
137
138 let fetch_models_task = self.fetch_models(cx);
139 cx.spawn(async move |_this, _cx| Ok(fetch_models_task.await?))
140 }
141}
142
143impl OllamaLanguageModelProvider {
144 pub fn new(http_client: Arc<dyn HttpClient>, cx: &mut App) -> Self {
145 let this = Self {
146 http_client: http_client.clone(),
147 state: cx.new(|cx| {
148 let subscription = cx.observe_global::<SettingsStore>({
149 let mut settings = AllLanguageModelSettings::get_global(cx).ollama.clone();
150 move |this: &mut State, cx| {
151 let new_settings = &AllLanguageModelSettings::get_global(cx).ollama;
152 if &settings != new_settings {
153 settings = new_settings.clone();
154 this.restart_fetch_models_task(cx);
155 cx.notify();
156 }
157 }
158 });
159
160 State {
161 http_client,
162 available_models: Default::default(),
163 fetch_model_task: None,
164 _subscription: subscription,
165 }
166 }),
167 };
168 this.state
169 .update(cx, |state, cx| state.restart_fetch_models_task(cx));
170 this
171 }
172}
173
174impl LanguageModelProviderState for OllamaLanguageModelProvider {
175 type ObservableEntity = State;
176
177 fn observable_entity(&self) -> Option<gpui::Entity<Self::ObservableEntity>> {
178 Some(self.state.clone())
179 }
180}
181
182impl LanguageModelProvider for OllamaLanguageModelProvider {
183 fn id(&self) -> LanguageModelProviderId {
184 LanguageModelProviderId(PROVIDER_ID.into())
185 }
186
187 fn name(&self) -> LanguageModelProviderName {
188 LanguageModelProviderName(PROVIDER_NAME.into())
189 }
190
191 fn icon(&self) -> IconName {
192 IconName::AiOllama
193 }
194
195 fn default_model(&self, cx: &App) -> Option<Arc<dyn LanguageModel>> {
196 self.provided_models(cx).into_iter().next()
197 }
198
199 fn default_fast_model(&self, cx: &App) -> Option<Arc<dyn LanguageModel>> {
200 self.default_model(cx)
201 }
202
203 fn provided_models(&self, cx: &App) -> Vec<Arc<dyn LanguageModel>> {
204 let mut models: HashMap<String, ollama::Model> = HashMap::new();
205
206 // Add models from the Ollama API
207 for model in self.state.read(cx).available_models.iter() {
208 models.insert(model.name.clone(), model.clone());
209 }
210
211 // Override with available models from settings
212 for model in AllLanguageModelSettings::get_global(cx)
213 .ollama
214 .available_models
215 .iter()
216 {
217 models.insert(
218 model.name.clone(),
219 ollama::Model {
220 name: model.name.clone(),
221 display_name: model.display_name.clone(),
222 max_tokens: model.max_tokens,
223 keep_alive: model.keep_alive.clone(),
224 supports_tools: model.supports_tools,
225 supports_vision: model.supports_images,
226 supports_thinking: model.supports_thinking,
227 },
228 );
229 }
230
231 let mut models = models
232 .into_values()
233 .map(|model| {
234 Arc::new(OllamaLanguageModel {
235 id: LanguageModelId::from(model.name.clone()),
236 model: model.clone(),
237 http_client: self.http_client.clone(),
238 request_limiter: RateLimiter::new(4),
239 }) as Arc<dyn LanguageModel>
240 })
241 .collect::<Vec<_>>();
242 models.sort_by_key(|model| model.name());
243 models
244 }
245
246 fn load_model(&self, model: Arc<dyn LanguageModel>, cx: &App) {
247 let settings = &AllLanguageModelSettings::get_global(cx).ollama;
248 let http_client = self.http_client.clone();
249 let api_url = settings.api_url.clone();
250 let id = model.id().0.to_string();
251 cx.spawn(async move |_| preload_model(http_client, &api_url, &id).await)
252 .detach_and_log_err(cx);
253 }
254
255 fn is_authenticated(&self, cx: &App) -> bool {
256 self.state.read(cx).is_authenticated()
257 }
258
259 fn authenticate(&self, cx: &mut App) -> Task<Result<(), AuthenticateError>> {
260 self.state.update(cx, |state, cx| state.authenticate(cx))
261 }
262
263 fn configuration_view(&self, window: &mut Window, cx: &mut App) -> AnyView {
264 let state = self.state.clone();
265 cx.new(|cx| ConfigurationView::new(state, window, cx))
266 .into()
267 }
268
269 fn reset_credentials(&self, cx: &mut App) -> Task<Result<()>> {
270 self.state.update(cx, |state, cx| state.fetch_models(cx))
271 }
272}
273
274pub struct OllamaLanguageModel {
275 id: LanguageModelId,
276 model: ollama::Model,
277 http_client: Arc<dyn HttpClient>,
278 request_limiter: RateLimiter,
279}
280
281impl OllamaLanguageModel {
282 fn to_ollama_request(&self, request: LanguageModelRequest) -> ChatRequest {
283 let supports_vision = self.model.supports_vision.unwrap_or(false);
284
285 ChatRequest {
286 model: self.model.name.clone(),
287 messages: request
288 .messages
289 .into_iter()
290 .map(|msg| {
291 let images = if supports_vision {
292 msg.content
293 .iter()
294 .filter_map(|content| match content {
295 MessageContent::Image(image) => Some(image.source.to_string()),
296 _ => None,
297 })
298 .collect::<Vec<String>>()
299 } else {
300 vec![]
301 };
302
303 match msg.role {
304 Role::User => ChatMessage::User {
305 content: msg.string_contents(),
306 images: if images.is_empty() {
307 None
308 } else {
309 Some(images)
310 },
311 },
312 Role::Assistant => {
313 let content = msg.string_contents();
314 let thinking =
315 msg.content.into_iter().find_map(|content| match content {
316 MessageContent::Thinking { text, .. } if !text.is_empty() => {
317 Some(text)
318 }
319 _ => None,
320 });
321 ChatMessage::Assistant {
322 content,
323 tool_calls: None,
324 images: if images.is_empty() {
325 None
326 } else {
327 Some(images)
328 },
329 thinking,
330 }
331 }
332 Role::System => ChatMessage::System {
333 content: msg.string_contents(),
334 },
335 }
336 })
337 .collect(),
338 keep_alive: self.model.keep_alive.clone().unwrap_or_default(),
339 stream: true,
340 options: Some(ChatOptions {
341 num_ctx: Some(self.model.max_tokens),
342 stop: Some(request.stop),
343 temperature: request.temperature.or(Some(1.0)),
344 ..Default::default()
345 }),
346 think: self.model.supports_thinking,
347 tools: request.tools.into_iter().map(tool_into_ollama).collect(),
348 }
349 }
350}
351
352impl LanguageModel for OllamaLanguageModel {
353 fn id(&self) -> LanguageModelId {
354 self.id.clone()
355 }
356
357 fn name(&self) -> LanguageModelName {
358 LanguageModelName::from(self.model.display_name().to_string())
359 }
360
361 fn provider_id(&self) -> LanguageModelProviderId {
362 LanguageModelProviderId(PROVIDER_ID.into())
363 }
364
365 fn provider_name(&self) -> LanguageModelProviderName {
366 LanguageModelProviderName(PROVIDER_NAME.into())
367 }
368
369 fn supports_tools(&self) -> bool {
370 self.model.supports_tools.unwrap_or(false)
371 }
372
373 fn supports_images(&self) -> bool {
374 self.model.supports_vision.unwrap_or(false)
375 }
376
377 fn supports_tool_choice(&self, choice: LanguageModelToolChoice) -> bool {
378 match choice {
379 LanguageModelToolChoice::Auto => false,
380 LanguageModelToolChoice::Any => false,
381 LanguageModelToolChoice::None => false,
382 }
383 }
384
385 fn telemetry_id(&self) -> String {
386 format!("ollama/{}", self.model.id())
387 }
388
389 fn max_token_count(&self) -> usize {
390 self.model.max_token_count()
391 }
392
393 fn count_tokens(
394 &self,
395 request: LanguageModelRequest,
396 _cx: &App,
397 ) -> BoxFuture<'static, Result<usize>> {
398 // There is no endpoint for this _yet_ in Ollama
399 // see: https://github.com/ollama/ollama/issues/1716 and https://github.com/ollama/ollama/issues/3582
400 let token_count = request
401 .messages
402 .iter()
403 .map(|msg| msg.string_contents().chars().count())
404 .sum::<usize>()
405 / 4;
406
407 async move { Ok(token_count) }.boxed()
408 }
409
410 fn stream_completion(
411 &self,
412 request: LanguageModelRequest,
413 cx: &AsyncApp,
414 ) -> BoxFuture<
415 'static,
416 Result<
417 BoxStream<'static, Result<LanguageModelCompletionEvent, LanguageModelCompletionError>>,
418 >,
419 > {
420 let request = self.to_ollama_request(request);
421
422 let http_client = self.http_client.clone();
423 let Ok(api_url) = cx.update(|cx| {
424 let settings = &AllLanguageModelSettings::get_global(cx).ollama;
425 settings.api_url.clone()
426 }) else {
427 return futures::future::ready(Err(anyhow!("App state dropped"))).boxed();
428 };
429
430 let future = self.request_limiter.stream(async move {
431 let stream = stream_chat_completion(http_client.as_ref(), &api_url, request).await?;
432 let stream = map_to_language_model_completion_events(stream);
433 Ok(stream)
434 });
435
436 future.map_ok(|f| f.boxed()).boxed()
437 }
438}
439
440fn map_to_language_model_completion_events(
441 stream: Pin<Box<dyn Stream<Item = anyhow::Result<ChatResponseDelta>> + Send>>,
442) -> impl Stream<Item = Result<LanguageModelCompletionEvent, LanguageModelCompletionError>> {
443 // Used for creating unique tool use ids
444 static TOOL_CALL_COUNTER: AtomicU64 = AtomicU64::new(0);
445
446 struct State {
447 stream: Pin<Box<dyn Stream<Item = anyhow::Result<ChatResponseDelta>> + Send>>,
448 used_tools: bool,
449 }
450
451 // We need to create a ToolUse and Stop event from a single
452 // response from the original stream
453 let stream = stream::unfold(
454 State {
455 stream,
456 used_tools: false,
457 },
458 async move |mut state| {
459 let response = state.stream.next().await?;
460
461 let delta = match response {
462 Ok(delta) => delta,
463 Err(e) => {
464 let event = Err(LanguageModelCompletionError::Other(anyhow!(e)));
465 return Some((vec![event], state));
466 }
467 };
468
469 let mut events = Vec::new();
470
471 match delta.message {
472 ChatMessage::User { content, images: _ } => {
473 events.push(Ok(LanguageModelCompletionEvent::Text(content)));
474 }
475 ChatMessage::System { content } => {
476 events.push(Ok(LanguageModelCompletionEvent::Text(content)));
477 }
478 ChatMessage::Assistant {
479 content,
480 tool_calls,
481 images: _,
482 thinking,
483 } => {
484 if let Some(text) = thinking {
485 events.push(Ok(LanguageModelCompletionEvent::Thinking {
486 text,
487 signature: None,
488 }));
489 }
490
491 if let Some(tool_call) = tool_calls.and_then(|v| v.into_iter().next()) {
492 match tool_call {
493 OllamaToolCall::Function(function) => {
494 let tool_id = format!(
495 "{}-{}",
496 &function.name,
497 TOOL_CALL_COUNTER.fetch_add(1, Ordering::Relaxed)
498 );
499 let event =
500 LanguageModelCompletionEvent::ToolUse(LanguageModelToolUse {
501 id: LanguageModelToolUseId::from(tool_id),
502 name: Arc::from(function.name),
503 raw_input: function.arguments.to_string(),
504 input: function.arguments,
505 is_input_complete: true,
506 });
507 events.push(Ok(event));
508 state.used_tools = true;
509 }
510 }
511 } else if !content.is_empty() {
512 events.push(Ok(LanguageModelCompletionEvent::Text(content)));
513 }
514 }
515 };
516
517 if delta.done {
518 if state.used_tools {
519 state.used_tools = false;
520 events.push(Ok(LanguageModelCompletionEvent::Stop(StopReason::ToolUse)));
521 } else {
522 events.push(Ok(LanguageModelCompletionEvent::Stop(StopReason::EndTurn)));
523 }
524 }
525
526 Some((events, state))
527 },
528 );
529
530 stream.flat_map(futures::stream::iter)
531}
532
533struct ConfigurationView {
534 state: gpui::Entity<State>,
535 loading_models_task: Option<Task<()>>,
536}
537
538impl ConfigurationView {
539 pub fn new(state: gpui::Entity<State>, window: &mut Window, cx: &mut Context<Self>) -> Self {
540 let loading_models_task = Some(cx.spawn_in(window, {
541 let state = state.clone();
542 async move |this, cx| {
543 if let Some(task) = state
544 .update(cx, |state, cx| state.authenticate(cx))
545 .log_err()
546 {
547 task.await.log_err();
548 }
549 this.update(cx, |this, cx| {
550 this.loading_models_task = None;
551 cx.notify();
552 })
553 .log_err();
554 }
555 }));
556
557 Self {
558 state,
559 loading_models_task,
560 }
561 }
562
563 fn retry_connection(&self, cx: &mut App) {
564 self.state
565 .update(cx, |state, cx| state.fetch_models(cx))
566 .detach_and_log_err(cx);
567 }
568}
569
570impl Render for ConfigurationView {
571 fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
572 let is_authenticated = self.state.read(cx).is_authenticated();
573
574 let ollama_intro =
575 "Get up & running with Llama 3.3, Mistral, Gemma 2, and other LLMs with Ollama.";
576
577 if self.loading_models_task.is_some() {
578 div().child(Label::new("Loading models...")).into_any()
579 } else {
580 v_flex()
581 .gap_2()
582 .child(
583 v_flex().gap_1().child(Label::new(ollama_intro)).child(
584 List::new()
585 .child(InstructionListItem::text_only("Ollama must be running with at least one model installed to use it in the assistant."))
586 .child(InstructionListItem::text_only(
587 "Once installed, try `ollama run llama3.2`",
588 )),
589 ),
590 )
591 .child(
592 h_flex()
593 .w_full()
594 .justify_between()
595 .gap_2()
596 .child(
597 h_flex()
598 .w_full()
599 .gap_2()
600 .map(|this| {
601 if is_authenticated {
602 this.child(
603 Button::new("ollama-site", "Ollama")
604 .style(ButtonStyle::Subtle)
605 .icon(IconName::ArrowUpRight)
606 .icon_size(IconSize::XSmall)
607 .icon_color(Color::Muted)
608 .on_click(move |_, _, cx| cx.open_url(OLLAMA_SITE))
609 .into_any_element(),
610 )
611 } else {
612 this.child(
613 Button::new(
614 "download_ollama_button",
615 "Download Ollama",
616 )
617 .style(ButtonStyle::Subtle)
618 .icon(IconName::ArrowUpRight)
619 .icon_size(IconSize::XSmall)
620 .icon_color(Color::Muted)
621 .on_click(move |_, _, cx| {
622 cx.open_url(OLLAMA_DOWNLOAD_URL)
623 })
624 .into_any_element(),
625 )
626 }
627 })
628 .child(
629 Button::new("view-models", "All Models")
630 .style(ButtonStyle::Subtle)
631 .icon(IconName::ArrowUpRight)
632 .icon_size(IconSize::XSmall)
633 .icon_color(Color::Muted)
634 .on_click(move |_, _, cx| cx.open_url(OLLAMA_LIBRARY_URL)),
635 ),
636 )
637 .map(|this| {
638 if is_authenticated {
639 this.child(
640 ButtonLike::new("connected")
641 .disabled(true)
642 .cursor_style(gpui::CursorStyle::Arrow)
643 .child(
644 h_flex()
645 .gap_2()
646 .child(Indicator::dot().color(Color::Success))
647 .child(Label::new("Connected"))
648 .into_any_element(),
649 ),
650 )
651 } else {
652 this.child(
653 Button::new("retry_ollama_models", "Connect")
654 .icon_position(IconPosition::Start)
655 .icon_size(IconSize::XSmall)
656 .icon(IconName::Play)
657 .on_click(cx.listener(move |this, _, _, cx| {
658 this.retry_connection(cx)
659 })),
660 )
661 }
662 })
663 )
664 .into_any()
665 }
666 }
667}
668
669fn tool_into_ollama(tool: LanguageModelRequestTool) -> ollama::OllamaTool {
670 ollama::OllamaTool::Function {
671 function: OllamaFunctionTool {
672 name: tool.name,
673 description: Some(tool.description),
674 parameters: Some(tool.input_schema),
675 },
676 }
677}