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, TokenUsage,
12};
13use ollama::{
14 ChatMessage, ChatOptions, ChatRequest, ChatResponseDelta, KeepAlive, OllamaFunctionTool,
15 OllamaToolCall, get_models, 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: LanguageModelProviderId = LanguageModelProviderId::new("ollama");
34const PROVIDER_NAME: LanguageModelProviderName = LanguageModelProviderName::new("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: u64,
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 PROVIDER_ID
185 }
186
187 fn name(&self) -> LanguageModelProviderName {
188 PROVIDER_NAME
189 }
190
191 fn icon(&self) -> IconName {
192 IconName::AiOllama
193 }
194
195 fn default_model(&self, _: &App) -> Option<Arc<dyn LanguageModel>> {
196 // We shouldn't try to select default model, because it might lead to a load call for an unloaded model.
197 // In a constrained environment where user might not have enough resources it'll be a bad UX to select something
198 // to load by default.
199 None
200 }
201
202 fn default_fast_model(&self, _: &App) -> Option<Arc<dyn LanguageModel>> {
203 // See explanation for default_model.
204 None
205 }
206
207 fn provided_models(&self, cx: &App) -> Vec<Arc<dyn LanguageModel>> {
208 let mut models: HashMap<String, ollama::Model> = HashMap::new();
209
210 // Add models from the Ollama API
211 for model in self.state.read(cx).available_models.iter() {
212 models.insert(model.name.clone(), model.clone());
213 }
214
215 // Override with available models from settings
216 for model in AllLanguageModelSettings::get_global(cx)
217 .ollama
218 .available_models
219 .iter()
220 {
221 models.insert(
222 model.name.clone(),
223 ollama::Model {
224 name: model.name.clone(),
225 display_name: model.display_name.clone(),
226 max_tokens: model.max_tokens,
227 keep_alive: model.keep_alive.clone(),
228 supports_tools: model.supports_tools,
229 supports_vision: model.supports_images,
230 supports_thinking: model.supports_thinking,
231 },
232 );
233 }
234
235 let mut models = models
236 .into_values()
237 .map(|model| {
238 Arc::new(OllamaLanguageModel {
239 id: LanguageModelId::from(model.name.clone()),
240 model,
241 http_client: self.http_client.clone(),
242 request_limiter: RateLimiter::new(4),
243 }) as Arc<dyn LanguageModel>
244 })
245 .collect::<Vec<_>>();
246 models.sort_by_key(|model| model.name());
247 models
248 }
249
250 fn is_authenticated(&self, cx: &App) -> bool {
251 self.state.read(cx).is_authenticated()
252 }
253
254 fn authenticate(&self, cx: &mut App) -> Task<Result<(), AuthenticateError>> {
255 self.state.update(cx, |state, cx| state.authenticate(cx))
256 }
257
258 fn configuration_view(
259 &self,
260 _target_agent: language_model::ConfigurationViewTargetAgent,
261 window: &mut Window,
262 cx: &mut App,
263 ) -> 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
347 .model
348 .supports_thinking
349 .map(|supports_thinking| supports_thinking && request.thinking_allowed),
350 tools: if self.model.supports_tools.unwrap_or(false) {
351 request.tools.into_iter().map(tool_into_ollama).collect()
352 } else {
353 vec![]
354 },
355 }
356 }
357}
358
359impl LanguageModel for OllamaLanguageModel {
360 fn id(&self) -> LanguageModelId {
361 self.id.clone()
362 }
363
364 fn name(&self) -> LanguageModelName {
365 LanguageModelName::from(self.model.display_name().to_string())
366 }
367
368 fn provider_id(&self) -> LanguageModelProviderId {
369 PROVIDER_ID
370 }
371
372 fn provider_name(&self) -> LanguageModelProviderName {
373 PROVIDER_NAME
374 }
375
376 fn supports_tools(&self) -> bool {
377 self.model.supports_tools.unwrap_or(false)
378 }
379
380 fn supports_images(&self) -> bool {
381 self.model.supports_vision.unwrap_or(false)
382 }
383
384 fn supports_tool_choice(&self, choice: LanguageModelToolChoice) -> bool {
385 match choice {
386 LanguageModelToolChoice::Auto => false,
387 LanguageModelToolChoice::Any => false,
388 LanguageModelToolChoice::None => false,
389 }
390 }
391
392 fn telemetry_id(&self) -> String {
393 format!("ollama/{}", self.model.id())
394 }
395
396 fn max_token_count(&self) -> u64 {
397 self.model.max_token_count()
398 }
399
400 fn count_tokens(
401 &self,
402 request: LanguageModelRequest,
403 _cx: &App,
404 ) -> BoxFuture<'static, Result<u64>> {
405 // There is no endpoint for this _yet_ in Ollama
406 // see: https://github.com/ollama/ollama/issues/1716 and https://github.com/ollama/ollama/issues/3582
407 let token_count = request
408 .messages
409 .iter()
410 .map(|msg| msg.string_contents().chars().count())
411 .sum::<usize>()
412 / 4;
413
414 async move { Ok(token_count as u64) }.boxed()
415 }
416
417 fn stream_completion(
418 &self,
419 request: LanguageModelRequest,
420 cx: &AsyncApp,
421 ) -> BoxFuture<
422 'static,
423 Result<
424 BoxStream<'static, Result<LanguageModelCompletionEvent, LanguageModelCompletionError>>,
425 LanguageModelCompletionError,
426 >,
427 > {
428 let request = self.to_ollama_request(request);
429
430 let http_client = self.http_client.clone();
431 let Ok(api_url) = cx.update(|cx| {
432 let settings = &AllLanguageModelSettings::get_global(cx).ollama;
433 settings.api_url.clone()
434 }) else {
435 return futures::future::ready(Err(anyhow!("App state dropped").into())).boxed();
436 };
437
438 let future = self.request_limiter.stream(async move {
439 let stream = stream_chat_completion(http_client.as_ref(), &api_url, request).await?;
440 let stream = map_to_language_model_completion_events(stream);
441 Ok(stream)
442 });
443
444 future.map_ok(|f| f.boxed()).boxed()
445 }
446}
447
448fn map_to_language_model_completion_events(
449 stream: Pin<Box<dyn Stream<Item = anyhow::Result<ChatResponseDelta>> + Send>>,
450) -> impl Stream<Item = Result<LanguageModelCompletionEvent, LanguageModelCompletionError>> {
451 // Used for creating unique tool use ids
452 static TOOL_CALL_COUNTER: AtomicU64 = AtomicU64::new(0);
453
454 struct State {
455 stream: Pin<Box<dyn Stream<Item = anyhow::Result<ChatResponseDelta>> + Send>>,
456 used_tools: bool,
457 }
458
459 // We need to create a ToolUse and Stop event from a single
460 // response from the original stream
461 let stream = stream::unfold(
462 State {
463 stream,
464 used_tools: false,
465 },
466 async move |mut state| {
467 let response = state.stream.next().await?;
468
469 let delta = match response {
470 Ok(delta) => delta,
471 Err(e) => {
472 let event = Err(LanguageModelCompletionError::from(anyhow!(e)));
473 return Some((vec![event], state));
474 }
475 };
476
477 let mut events = Vec::new();
478
479 match delta.message {
480 ChatMessage::User { content, images: _ } => {
481 events.push(Ok(LanguageModelCompletionEvent::Text(content)));
482 }
483 ChatMessage::System { content } => {
484 events.push(Ok(LanguageModelCompletionEvent::Text(content)));
485 }
486 ChatMessage::Assistant {
487 content,
488 tool_calls,
489 images: _,
490 thinking,
491 } => {
492 if let Some(text) = thinking {
493 events.push(Ok(LanguageModelCompletionEvent::Thinking {
494 text,
495 signature: None,
496 }));
497 }
498
499 if let Some(tool_call) = tool_calls.and_then(|v| v.into_iter().next()) {
500 match tool_call {
501 OllamaToolCall::Function(function) => {
502 let tool_id = format!(
503 "{}-{}",
504 &function.name,
505 TOOL_CALL_COUNTER.fetch_add(1, Ordering::Relaxed)
506 );
507 let event =
508 LanguageModelCompletionEvent::ToolUse(LanguageModelToolUse {
509 id: LanguageModelToolUseId::from(tool_id),
510 name: Arc::from(function.name),
511 raw_input: function.arguments.to_string(),
512 input: function.arguments,
513 is_input_complete: true,
514 });
515 events.push(Ok(event));
516 state.used_tools = true;
517 }
518 }
519 } else if !content.is_empty() {
520 events.push(Ok(LanguageModelCompletionEvent::Text(content)));
521 }
522 }
523 };
524
525 if delta.done {
526 events.push(Ok(LanguageModelCompletionEvent::UsageUpdate(TokenUsage {
527 input_tokens: delta.prompt_eval_count.unwrap_or(0),
528 output_tokens: delta.eval_count.unwrap_or(0),
529 cache_creation_input_tokens: 0,
530 cache_read_input_tokens: 0,
531 })));
532 if state.used_tools {
533 state.used_tools = false;
534 events.push(Ok(LanguageModelCompletionEvent::Stop(StopReason::ToolUse)));
535 } else {
536 events.push(Ok(LanguageModelCompletionEvent::Stop(StopReason::EndTurn)));
537 }
538 }
539
540 Some((events, state))
541 },
542 );
543
544 stream.flat_map(futures::stream::iter)
545}
546
547struct ConfigurationView {
548 state: gpui::Entity<State>,
549 loading_models_task: Option<Task<()>>,
550}
551
552impl ConfigurationView {
553 pub fn new(state: gpui::Entity<State>, window: &mut Window, cx: &mut Context<Self>) -> Self {
554 let loading_models_task = Some(cx.spawn_in(window, {
555 let state = state.clone();
556 async move |this, cx| {
557 if let Some(task) = state
558 .update(cx, |state, cx| state.authenticate(cx))
559 .log_err()
560 {
561 task.await.log_err();
562 }
563 this.update(cx, |this, cx| {
564 this.loading_models_task = None;
565 cx.notify();
566 })
567 .log_err();
568 }
569 }));
570
571 Self {
572 state,
573 loading_models_task,
574 }
575 }
576
577 fn retry_connection(&self, cx: &mut App) {
578 self.state
579 .update(cx, |state, cx| state.fetch_models(cx))
580 .detach_and_log_err(cx);
581 }
582}
583
584impl Render for ConfigurationView {
585 fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
586 let is_authenticated = self.state.read(cx).is_authenticated();
587
588 let ollama_intro =
589 "Get up & running with Llama 3.3, Mistral, Gemma 2, and other LLMs with Ollama.";
590
591 if self.loading_models_task.is_some() {
592 div().child(Label::new("Loading models...")).into_any()
593 } else {
594 v_flex()
595 .gap_2()
596 .child(
597 v_flex().gap_1().child(Label::new(ollama_intro)).child(
598 List::new()
599 .child(InstructionListItem::text_only("Ollama must be running with at least one model installed to use it in the assistant."))
600 .child(InstructionListItem::text_only(
601 "Once installed, try `ollama run llama3.2`",
602 )),
603 ),
604 )
605 .child(
606 h_flex()
607 .w_full()
608 .justify_between()
609 .gap_2()
610 .child(
611 h_flex()
612 .w_full()
613 .gap_2()
614 .map(|this| {
615 if is_authenticated {
616 this.child(
617 Button::new("ollama-site", "Ollama")
618 .style(ButtonStyle::Subtle)
619 .icon(IconName::ArrowUpRight)
620 .icon_size(IconSize::Small)
621 .icon_color(Color::Muted)
622 .on_click(move |_, _, cx| cx.open_url(OLLAMA_SITE))
623 .into_any_element(),
624 )
625 } else {
626 this.child(
627 Button::new(
628 "download_ollama_button",
629 "Download Ollama",
630 )
631 .style(ButtonStyle::Subtle)
632 .icon(IconName::ArrowUpRight)
633 .icon_size(IconSize::Small)
634 .icon_color(Color::Muted)
635 .on_click(move |_, _, cx| {
636 cx.open_url(OLLAMA_DOWNLOAD_URL)
637 })
638 .into_any_element(),
639 )
640 }
641 })
642 .child(
643 Button::new("view-models", "View All Models")
644 .style(ButtonStyle::Subtle)
645 .icon(IconName::ArrowUpRight)
646 .icon_size(IconSize::Small)
647 .icon_color(Color::Muted)
648 .on_click(move |_, _, cx| cx.open_url(OLLAMA_LIBRARY_URL)),
649 ),
650 )
651 .map(|this| {
652 if is_authenticated {
653 this.child(
654 ButtonLike::new("connected")
655 .disabled(true)
656 .cursor_style(gpui::CursorStyle::Arrow)
657 .child(
658 h_flex()
659 .gap_2()
660 .child(Indicator::dot().color(Color::Success))
661 .child(Label::new("Connected"))
662 .into_any_element(),
663 ),
664 )
665 } else {
666 this.child(
667 Button::new("retry_ollama_models", "Connect")
668 .icon_position(IconPosition::Start)
669 .icon_size(IconSize::XSmall)
670 .icon(IconName::PlayFilled)
671 .on_click(cx.listener(move |this, _, _, cx| {
672 this.retry_connection(cx)
673 })),
674 )
675 }
676 })
677 )
678 .into_any()
679 }
680 }
681}
682
683fn tool_into_ollama(tool: LanguageModelRequestTool) -> ollama::OllamaTool {
684 ollama::OllamaTool::Function {
685 function: OllamaFunctionTool {
686 name: tool.name,
687 description: Some(tool.description),
688 parameters: Some(tool.input_schema),
689 },
690 }
691}