ollama.rs

  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: model.clone(),
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(&self, window: &mut Window, cx: &mut App) -> AnyView {
259        let state = self.state.clone();
260        cx.new(|cx| ConfigurationView::new(state, window, cx))
261            .into()
262    }
263
264    fn reset_credentials(&self, cx: &mut App) -> Task<Result<()>> {
265        self.state.update(cx, |state, cx| state.fetch_models(cx))
266    }
267}
268
269pub struct OllamaLanguageModel {
270    id: LanguageModelId,
271    model: ollama::Model,
272    http_client: Arc<dyn HttpClient>,
273    request_limiter: RateLimiter,
274}
275
276impl OllamaLanguageModel {
277    fn to_ollama_request(&self, request: LanguageModelRequest) -> ChatRequest {
278        let supports_vision = self.model.supports_vision.unwrap_or(false);
279
280        ChatRequest {
281            model: self.model.name.clone(),
282            messages: request
283                .messages
284                .into_iter()
285                .map(|msg| {
286                    let images = if supports_vision {
287                        msg.content
288                            .iter()
289                            .filter_map(|content| match content {
290                                MessageContent::Image(image) => Some(image.source.to_string()),
291                                _ => None,
292                            })
293                            .collect::<Vec<String>>()
294                    } else {
295                        vec![]
296                    };
297
298                    match msg.role {
299                        Role::User => ChatMessage::User {
300                            content: msg.string_contents(),
301                            images: if images.is_empty() {
302                                None
303                            } else {
304                                Some(images)
305                            },
306                        },
307                        Role::Assistant => {
308                            let content = msg.string_contents();
309                            let thinking =
310                                msg.content.into_iter().find_map(|content| match content {
311                                    MessageContent::Thinking { text, .. } if !text.is_empty() => {
312                                        Some(text)
313                                    }
314                                    _ => None,
315                                });
316                            ChatMessage::Assistant {
317                                content,
318                                tool_calls: None,
319                                images: if images.is_empty() {
320                                    None
321                                } else {
322                                    Some(images)
323                                },
324                                thinking,
325                            }
326                        }
327                        Role::System => ChatMessage::System {
328                            content: msg.string_contents(),
329                        },
330                    }
331                })
332                .collect(),
333            keep_alive: self.model.keep_alive.clone().unwrap_or_default(),
334            stream: true,
335            options: Some(ChatOptions {
336                num_ctx: Some(self.model.max_tokens),
337                stop: Some(request.stop),
338                temperature: request.temperature.or(Some(1.0)),
339                ..Default::default()
340            }),
341            think: self
342                .model
343                .supports_thinking
344                .map(|supports_thinking| supports_thinking && request.thinking_allowed),
345            tools: request.tools.into_iter().map(tool_into_ollama).collect(),
346        }
347    }
348}
349
350impl LanguageModel for OllamaLanguageModel {
351    fn id(&self) -> LanguageModelId {
352        self.id.clone()
353    }
354
355    fn name(&self) -> LanguageModelName {
356        LanguageModelName::from(self.model.display_name().to_string())
357    }
358
359    fn provider_id(&self) -> LanguageModelProviderId {
360        PROVIDER_ID
361    }
362
363    fn provider_name(&self) -> LanguageModelProviderName {
364        PROVIDER_NAME
365    }
366
367    fn supports_tools(&self) -> bool {
368        self.model.supports_tools.unwrap_or(false)
369    }
370
371    fn supports_images(&self) -> bool {
372        self.model.supports_vision.unwrap_or(false)
373    }
374
375    fn supports_tool_choice(&self, choice: LanguageModelToolChoice) -> bool {
376        match choice {
377            LanguageModelToolChoice::Auto => false,
378            LanguageModelToolChoice::Any => false,
379            LanguageModelToolChoice::None => false,
380        }
381    }
382
383    fn telemetry_id(&self) -> String {
384        format!("ollama/{}", self.model.id())
385    }
386
387    fn max_token_count(&self) -> u64 {
388        self.model.max_token_count()
389    }
390
391    fn count_tokens(
392        &self,
393        request: LanguageModelRequest,
394        _cx: &App,
395    ) -> BoxFuture<'static, Result<u64>> {
396        // There is no endpoint for this _yet_ in Ollama
397        // see: https://github.com/ollama/ollama/issues/1716 and https://github.com/ollama/ollama/issues/3582
398        let token_count = request
399            .messages
400            .iter()
401            .map(|msg| msg.string_contents().chars().count())
402            .sum::<usize>()
403            / 4;
404
405        async move { Ok(token_count as u64) }.boxed()
406    }
407
408    fn stream_completion(
409        &self,
410        request: LanguageModelRequest,
411        cx: &AsyncApp,
412    ) -> BoxFuture<
413        'static,
414        Result<
415            BoxStream<'static, Result<LanguageModelCompletionEvent, LanguageModelCompletionError>>,
416            LanguageModelCompletionError,
417        >,
418    > {
419        let request = self.to_ollama_request(request);
420
421        let http_client = self.http_client.clone();
422        let Ok(api_url) = cx.update(|cx| {
423            let settings = &AllLanguageModelSettings::get_global(cx).ollama;
424            settings.api_url.clone()
425        }) else {
426            return futures::future::ready(Err(anyhow!("App state dropped").into())).boxed();
427        };
428
429        let future = self.request_limiter.stream(async move {
430            let stream = stream_chat_completion(http_client.as_ref(), &api_url, request).await?;
431            let stream = map_to_language_model_completion_events(stream);
432            Ok(stream)
433        });
434
435        future.map_ok(|f| f.boxed()).boxed()
436    }
437}
438
439fn map_to_language_model_completion_events(
440    stream: Pin<Box<dyn Stream<Item = anyhow::Result<ChatResponseDelta>> + Send>>,
441) -> impl Stream<Item = Result<LanguageModelCompletionEvent, LanguageModelCompletionError>> {
442    // Used for creating unique tool use ids
443    static TOOL_CALL_COUNTER: AtomicU64 = AtomicU64::new(0);
444
445    struct State {
446        stream: Pin<Box<dyn Stream<Item = anyhow::Result<ChatResponseDelta>> + Send>>,
447        used_tools: bool,
448    }
449
450    // We need to create a ToolUse and Stop event from a single
451    // response from the original stream
452    let stream = stream::unfold(
453        State {
454            stream,
455            used_tools: false,
456        },
457        async move |mut state| {
458            let response = state.stream.next().await?;
459
460            let delta = match response {
461                Ok(delta) => delta,
462                Err(e) => {
463                    let event = Err(LanguageModelCompletionError::from(anyhow!(e)));
464                    return Some((vec![event], state));
465                }
466            };
467
468            let mut events = Vec::new();
469
470            match delta.message {
471                ChatMessage::User { content, images: _ } => {
472                    events.push(Ok(LanguageModelCompletionEvent::Text(content)));
473                }
474                ChatMessage::System { content } => {
475                    events.push(Ok(LanguageModelCompletionEvent::Text(content)));
476                }
477                ChatMessage::Assistant {
478                    content,
479                    tool_calls,
480                    images: _,
481                    thinking,
482                } => {
483                    if let Some(text) = thinking {
484                        events.push(Ok(LanguageModelCompletionEvent::Thinking {
485                            text,
486                            signature: None,
487                        }));
488                    }
489
490                    if let Some(tool_call) = tool_calls.and_then(|v| v.into_iter().next()) {
491                        match tool_call {
492                            OllamaToolCall::Function(function) => {
493                                let tool_id = format!(
494                                    "{}-{}",
495                                    &function.name,
496                                    TOOL_CALL_COUNTER.fetch_add(1, Ordering::Relaxed)
497                                );
498                                let event =
499                                    LanguageModelCompletionEvent::ToolUse(LanguageModelToolUse {
500                                        id: LanguageModelToolUseId::from(tool_id),
501                                        name: Arc::from(function.name),
502                                        raw_input: function.arguments.to_string(),
503                                        input: function.arguments,
504                                        is_input_complete: true,
505                                    });
506                                events.push(Ok(event));
507                                state.used_tools = true;
508                            }
509                        }
510                    } else if !content.is_empty() {
511                        events.push(Ok(LanguageModelCompletionEvent::Text(content)));
512                    }
513                }
514            };
515
516            if delta.done {
517                events.push(Ok(LanguageModelCompletionEvent::UsageUpdate(TokenUsage {
518                    input_tokens: delta.prompt_eval_count.unwrap_or(0),
519                    output_tokens: delta.eval_count.unwrap_or(0),
520                    cache_creation_input_tokens: 0,
521                    cache_read_input_tokens: 0,
522                })));
523                if state.used_tools {
524                    state.used_tools = false;
525                    events.push(Ok(LanguageModelCompletionEvent::Stop(StopReason::ToolUse)));
526                } else {
527                    events.push(Ok(LanguageModelCompletionEvent::Stop(StopReason::EndTurn)));
528                }
529            }
530
531            Some((events, state))
532        },
533    );
534
535    stream.flat_map(futures::stream::iter)
536}
537
538struct ConfigurationView {
539    state: gpui::Entity<State>,
540    loading_models_task: Option<Task<()>>,
541}
542
543impl ConfigurationView {
544    pub fn new(state: gpui::Entity<State>, window: &mut Window, cx: &mut Context<Self>) -> Self {
545        let loading_models_task = Some(cx.spawn_in(window, {
546            let state = state.clone();
547            async move |this, cx| {
548                if let Some(task) = state
549                    .update(cx, |state, cx| state.authenticate(cx))
550                    .log_err()
551                {
552                    task.await.log_err();
553                }
554                this.update(cx, |this, cx| {
555                    this.loading_models_task = None;
556                    cx.notify();
557                })
558                .log_err();
559            }
560        }));
561
562        Self {
563            state,
564            loading_models_task,
565        }
566    }
567
568    fn retry_connection(&self, cx: &mut App) {
569        self.state
570            .update(cx, |state, cx| state.fetch_models(cx))
571            .detach_and_log_err(cx);
572    }
573}
574
575impl Render for ConfigurationView {
576    fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
577        let is_authenticated = self.state.read(cx).is_authenticated();
578
579        let ollama_intro =
580            "Get up & running with Llama 3.3, Mistral, Gemma 2, and other LLMs with Ollama.";
581
582        if self.loading_models_task.is_some() {
583            div().child(Label::new("Loading models...")).into_any()
584        } else {
585            v_flex()
586                .gap_2()
587                .child(
588                    v_flex().gap_1().child(Label::new(ollama_intro)).child(
589                        List::new()
590                            .child(InstructionListItem::text_only("Ollama must be running with at least one model installed to use it in the assistant."))
591                            .child(InstructionListItem::text_only(
592                                "Once installed, try `ollama run llama3.2`",
593                            )),
594                    ),
595                )
596                .child(
597                    h_flex()
598                        .w_full()
599                        .justify_between()
600                        .gap_2()
601                        .child(
602                            h_flex()
603                                .w_full()
604                                .gap_2()
605                                .map(|this| {
606                                    if is_authenticated {
607                                        this.child(
608                                            Button::new("ollama-site", "Ollama")
609                                                .style(ButtonStyle::Subtle)
610                                                .icon(IconName::ArrowUpRight)
611                                                .icon_size(IconSize::Small)
612                                                .icon_color(Color::Muted)
613                                                .on_click(move |_, _, cx| cx.open_url(OLLAMA_SITE))
614                                                .into_any_element(),
615                                        )
616                                    } else {
617                                        this.child(
618                                            Button::new(
619                                                "download_ollama_button",
620                                                "Download Ollama",
621                                            )
622                                            .style(ButtonStyle::Subtle)
623                                            .icon(IconName::ArrowUpRight)
624                                            .icon_size(IconSize::Small)
625                                            .icon_color(Color::Muted)
626                                            .on_click(move |_, _, cx| {
627                                                cx.open_url(OLLAMA_DOWNLOAD_URL)
628                                            })
629                                            .into_any_element(),
630                                        )
631                                    }
632                                })
633                                .child(
634                                    Button::new("view-models", "View All Models")
635                                        .style(ButtonStyle::Subtle)
636                                        .icon(IconName::ArrowUpRight)
637                                        .icon_size(IconSize::Small)
638                                        .icon_color(Color::Muted)
639                                        .on_click(move |_, _, cx| cx.open_url(OLLAMA_LIBRARY_URL)),
640                                ),
641                        )
642                        .map(|this| {
643                            if is_authenticated {
644                                this.child(
645                                    ButtonLike::new("connected")
646                                        .disabled(true)
647                                        .cursor_style(gpui::CursorStyle::Arrow)
648                                        .child(
649                                            h_flex()
650                                                .gap_2()
651                                                .child(Indicator::dot().color(Color::Success))
652                                                .child(Label::new("Connected"))
653                                                .into_any_element(),
654                                        ),
655                                )
656                            } else {
657                                this.child(
658                                    Button::new("retry_ollama_models", "Connect")
659                                        .icon_position(IconPosition::Start)
660                                        .icon_size(IconSize::XSmall)
661                                        .icon(IconName::PlayFilled)
662                                        .on_click(cx.listener(move |this, _, _, cx| {
663                                            this.retry_connection(cx)
664                                        })),
665                                )
666                            }
667                        })
668                )
669                .into_any()
670        }
671    }
672}
673
674fn tool_into_ollama(tool: LanguageModelRequestTool) -> ollama::OllamaTool {
675    ollama::OllamaTool::Function {
676        function: OllamaFunctionTool {
677            name: tool.name,
678            description: Some(tool.description),
679            parameters: Some(tool.input_schema),
680        },
681    }
682}