ollama.rs

  1use anyhow::{Result, anyhow};
  2use futures::{FutureExt, StreamExt, future::BoxFuture, stream::BoxStream};
  3use gpui::{AnyView, App, AsyncApp, Context, Subscription, Task};
  4use http_client::HttpClient;
  5use language_model::{AuthenticateError, LanguageModelCompletionEvent};
  6use language_model::{
  7    LanguageModel, LanguageModelId, LanguageModelName, LanguageModelProvider,
  8    LanguageModelProviderId, LanguageModelProviderName, LanguageModelProviderState,
  9    LanguageModelRequest, RateLimiter, Role,
 10};
 11use ollama::{
 12    ChatMessage, ChatOptions, ChatRequest, KeepAlive, get_models, preload_model,
 13    stream_chat_completion,
 14};
 15use schemars::JsonSchema;
 16use serde::{Deserialize, Serialize};
 17use settings::{Settings, SettingsStore};
 18use std::{collections::BTreeMap, sync::Arc};
 19use ui::{ButtonLike, Indicator, prelude::*};
 20use util::ResultExt;
 21
 22use crate::AllLanguageModelSettings;
 23
 24const OLLAMA_DOWNLOAD_URL: &str = "https://ollama.com/download";
 25const OLLAMA_LIBRARY_URL: &str = "https://ollama.com/library";
 26const OLLAMA_SITE: &str = "https://ollama.com/";
 27
 28const PROVIDER_ID: &str = "ollama";
 29const PROVIDER_NAME: &str = "Ollama";
 30
 31#[derive(Default, Debug, Clone, PartialEq)]
 32pub struct OllamaSettings {
 33    pub api_url: String,
 34    pub available_models: Vec<AvailableModel>,
 35}
 36
 37#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
 38pub struct AvailableModel {
 39    /// The model name in the Ollama API (e.g. "llama3.2:latest")
 40    pub name: String,
 41    /// The model's name in Zed's UI, such as in the model selector dropdown menu in the assistant panel.
 42    pub display_name: Option<String>,
 43    /// The Context Length parameter to the model (aka num_ctx or n_ctx)
 44    pub max_tokens: usize,
 45    /// The number of seconds to keep the connection open after the last request
 46    pub keep_alive: Option<KeepAlive>,
 47}
 48
 49pub struct OllamaLanguageModelProvider {
 50    http_client: Arc<dyn HttpClient>,
 51    state: gpui::Entity<State>,
 52}
 53
 54pub struct State {
 55    http_client: Arc<dyn HttpClient>,
 56    available_models: Vec<ollama::Model>,
 57    fetch_model_task: Option<Task<Result<()>>>,
 58    _subscription: Subscription,
 59}
 60
 61impl State {
 62    fn is_authenticated(&self) -> bool {
 63        !self.available_models.is_empty()
 64    }
 65
 66    fn fetch_models(&mut self, cx: &mut Context<Self>) -> Task<Result<()>> {
 67        let settings = &AllLanguageModelSettings::get_global(cx).ollama;
 68        let http_client = self.http_client.clone();
 69        let api_url = settings.api_url.clone();
 70
 71        // As a proxy for the server being "authenticated", we'll check if its up by fetching the models
 72        cx.spawn(async move |this, cx| {
 73            let models = get_models(http_client.as_ref(), &api_url, None).await?;
 74
 75            let mut models: Vec<ollama::Model> = models
 76                .into_iter()
 77                // Since there is no metadata from the Ollama API
 78                // indicating which models are embedding models,
 79                // simply filter out models with "-embed" in their name
 80                .filter(|model| !model.name.contains("-embed"))
 81                .map(|model| ollama::Model::new(&model.name, None, None))
 82                .collect();
 83
 84            models.sort_by(|a, b| a.name.cmp(&b.name));
 85
 86            this.update(cx, |this, cx| {
 87                this.available_models = models;
 88                cx.notify();
 89            })
 90        })
 91    }
 92
 93    fn restart_fetch_models_task(&mut self, cx: &mut Context<Self>) {
 94        let task = self.fetch_models(cx);
 95        self.fetch_model_task.replace(task);
 96    }
 97
 98    fn authenticate(&mut self, cx: &mut Context<Self>) -> Task<Result<(), AuthenticateError>> {
 99        if self.is_authenticated() {
100            return Task::ready(Ok(()));
101        }
102
103        let fetch_models_task = self.fetch_models(cx);
104        cx.spawn(async move |_this, _cx| Ok(fetch_models_task.await?))
105    }
106}
107
108impl OllamaLanguageModelProvider {
109    pub fn new(http_client: Arc<dyn HttpClient>, cx: &mut App) -> Self {
110        let this = Self {
111            http_client: http_client.clone(),
112            state: cx.new(|cx| {
113                let subscription = cx.observe_global::<SettingsStore>({
114                    let mut settings = AllLanguageModelSettings::get_global(cx).ollama.clone();
115                    move |this: &mut State, cx| {
116                        let new_settings = &AllLanguageModelSettings::get_global(cx).ollama;
117                        if &settings != new_settings {
118                            settings = new_settings.clone();
119                            this.restart_fetch_models_task(cx);
120                            cx.notify();
121                        }
122                    }
123                });
124
125                State {
126                    http_client,
127                    available_models: Default::default(),
128                    fetch_model_task: None,
129                    _subscription: subscription,
130                }
131            }),
132        };
133        this.state
134            .update(cx, |state, cx| state.restart_fetch_models_task(cx));
135        this
136    }
137}
138
139impl LanguageModelProviderState for OllamaLanguageModelProvider {
140    type ObservableEntity = State;
141
142    fn observable_entity(&self) -> Option<gpui::Entity<Self::ObservableEntity>> {
143        Some(self.state.clone())
144    }
145}
146
147impl LanguageModelProvider for OllamaLanguageModelProvider {
148    fn id(&self) -> LanguageModelProviderId {
149        LanguageModelProviderId(PROVIDER_ID.into())
150    }
151
152    fn name(&self) -> LanguageModelProviderName {
153        LanguageModelProviderName(PROVIDER_NAME.into())
154    }
155
156    fn icon(&self) -> IconName {
157        IconName::AiOllama
158    }
159
160    fn default_model(&self, cx: &App) -> Option<Arc<dyn LanguageModel>> {
161        self.provided_models(cx).into_iter().next()
162    }
163
164    fn provided_models(&self, cx: &App) -> Vec<Arc<dyn LanguageModel>> {
165        let mut models: BTreeMap<String, ollama::Model> = BTreeMap::default();
166
167        // Add models from the Ollama API
168        for model in self.state.read(cx).available_models.iter() {
169            models.insert(model.name.clone(), model.clone());
170        }
171
172        // Override with available models from settings
173        for model in AllLanguageModelSettings::get_global(cx)
174            .ollama
175            .available_models
176            .iter()
177        {
178            models.insert(
179                model.name.clone(),
180                ollama::Model {
181                    name: model.name.clone(),
182                    display_name: model.display_name.clone(),
183                    max_tokens: model.max_tokens,
184                    keep_alive: model.keep_alive.clone(),
185                },
186            );
187        }
188
189        models
190            .into_values()
191            .map(|model| {
192                Arc::new(OllamaLanguageModel {
193                    id: LanguageModelId::from(model.name.clone()),
194                    model: model.clone(),
195                    http_client: self.http_client.clone(),
196                    request_limiter: RateLimiter::new(4),
197                }) as Arc<dyn LanguageModel>
198            })
199            .collect()
200    }
201
202    fn load_model(&self, model: Arc<dyn LanguageModel>, cx: &App) {
203        let settings = &AllLanguageModelSettings::get_global(cx).ollama;
204        let http_client = self.http_client.clone();
205        let api_url = settings.api_url.clone();
206        let id = model.id().0.to_string();
207        cx.spawn(async move |_| preload_model(http_client, &api_url, &id).await)
208            .detach_and_log_err(cx);
209    }
210
211    fn is_authenticated(&self, cx: &App) -> bool {
212        self.state.read(cx).is_authenticated()
213    }
214
215    fn authenticate(&self, cx: &mut App) -> Task<Result<(), AuthenticateError>> {
216        self.state.update(cx, |state, cx| state.authenticate(cx))
217    }
218
219    fn configuration_view(&self, window: &mut Window, cx: &mut App) -> AnyView {
220        let state = self.state.clone();
221        cx.new(|cx| ConfigurationView::new(state, window, cx))
222            .into()
223    }
224
225    fn reset_credentials(&self, cx: &mut App) -> Task<Result<()>> {
226        self.state.update(cx, |state, cx| state.fetch_models(cx))
227    }
228}
229
230pub struct OllamaLanguageModel {
231    id: LanguageModelId,
232    model: ollama::Model,
233    http_client: Arc<dyn HttpClient>,
234    request_limiter: RateLimiter,
235}
236
237impl OllamaLanguageModel {
238    fn to_ollama_request(&self, request: LanguageModelRequest) -> ChatRequest {
239        ChatRequest {
240            model: self.model.name.clone(),
241            messages: request
242                .messages
243                .into_iter()
244                .map(|msg| match msg.role {
245                    Role::User => ChatMessage::User {
246                        content: msg.string_contents(),
247                    },
248                    Role::Assistant => ChatMessage::Assistant {
249                        content: msg.string_contents(),
250                        tool_calls: None,
251                    },
252                    Role::System => ChatMessage::System {
253                        content: msg.string_contents(),
254                    },
255                })
256                .collect(),
257            keep_alive: self.model.keep_alive.clone().unwrap_or_default(),
258            stream: true,
259            options: Some(ChatOptions {
260                num_ctx: Some(self.model.max_tokens),
261                stop: Some(request.stop),
262                temperature: request.temperature.or(Some(1.0)),
263                ..Default::default()
264            }),
265            tools: vec![],
266        }
267    }
268}
269
270impl LanguageModel for OllamaLanguageModel {
271    fn id(&self) -> LanguageModelId {
272        self.id.clone()
273    }
274
275    fn name(&self) -> LanguageModelName {
276        LanguageModelName::from(self.model.display_name().to_string())
277    }
278
279    fn provider_id(&self) -> LanguageModelProviderId {
280        LanguageModelProviderId(PROVIDER_ID.into())
281    }
282
283    fn provider_name(&self) -> LanguageModelProviderName {
284        LanguageModelProviderName(PROVIDER_NAME.into())
285    }
286
287    fn supports_tools(&self) -> bool {
288        false
289    }
290
291    fn telemetry_id(&self) -> String {
292        format!("ollama/{}", self.model.id())
293    }
294
295    fn max_token_count(&self) -> usize {
296        self.model.max_token_count()
297    }
298
299    fn count_tokens(
300        &self,
301        request: LanguageModelRequest,
302        _cx: &App,
303    ) -> BoxFuture<'static, Result<usize>> {
304        // There is no endpoint for this _yet_ in Ollama
305        // see: https://github.com/ollama/ollama/issues/1716 and https://github.com/ollama/ollama/issues/3582
306        let token_count = request
307            .messages
308            .iter()
309            .map(|msg| msg.string_contents().chars().count())
310            .sum::<usize>()
311            / 4;
312
313        async move { Ok(token_count) }.boxed()
314    }
315
316    fn stream_completion(
317        &self,
318        request: LanguageModelRequest,
319        cx: &AsyncApp,
320    ) -> BoxFuture<'static, Result<BoxStream<'static, Result<LanguageModelCompletionEvent>>>> {
321        let request = self.to_ollama_request(request);
322
323        let http_client = self.http_client.clone();
324        let Ok(api_url) = cx.update(|cx| {
325            let settings = &AllLanguageModelSettings::get_global(cx).ollama;
326            settings.api_url.clone()
327        }) else {
328            return futures::future::ready(Err(anyhow!("App state dropped"))).boxed();
329        };
330
331        let future = self.request_limiter.stream(async move {
332            let response = stream_chat_completion(http_client.as_ref(), &api_url, request).await?;
333            let stream = response
334                .filter_map(|response| async move {
335                    match response {
336                        Ok(delta) => {
337                            let content = match delta.message {
338                                ChatMessage::User { content } => content,
339                                ChatMessage::Assistant { content, .. } => content,
340                                ChatMessage::System { content } => content,
341                            };
342                            Some(Ok(content))
343                        }
344                        Err(error) => Some(Err(error)),
345                    }
346                })
347                .boxed();
348            Ok(stream)
349        });
350
351        async move {
352            Ok(future
353                .await?
354                .map(|result| result.map(LanguageModelCompletionEvent::Text))
355                .boxed())
356        }
357        .boxed()
358    }
359}
360
361struct ConfigurationView {
362    state: gpui::Entity<State>,
363    loading_models_task: Option<Task<()>>,
364}
365
366impl ConfigurationView {
367    pub fn new(state: gpui::Entity<State>, window: &mut Window, cx: &mut Context<Self>) -> Self {
368        let loading_models_task = Some(cx.spawn_in(window, {
369            let state = state.clone();
370            async move |this, cx| {
371                if let Some(task) = state
372                    .update(cx, |state, cx| state.authenticate(cx))
373                    .log_err()
374                {
375                    task.await.log_err();
376                }
377                this.update(cx, |this, cx| {
378                    this.loading_models_task = None;
379                    cx.notify();
380                })
381                .log_err();
382            }
383        }));
384
385        Self {
386            state,
387            loading_models_task,
388        }
389    }
390
391    fn retry_connection(&self, cx: &mut App) {
392        self.state
393            .update(cx, |state, cx| state.fetch_models(cx))
394            .detach_and_log_err(cx);
395    }
396}
397
398impl Render for ConfigurationView {
399    fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
400        let is_authenticated = self.state.read(cx).is_authenticated();
401
402        let ollama_intro = "Get up and running with Llama 3.3, Mistral, Gemma 2, and other large language models with Ollama.";
403        let ollama_reqs =
404            "Ollama must be running with at least one model installed to use it in the assistant.";
405
406        let inline_code_bg = cx.theme().colors().editor_foreground.opacity(0.05);
407
408        if self.loading_models_task.is_some() {
409            div().child(Label::new("Loading models...")).into_any()
410        } else {
411            v_flex()
412                .size_full()
413                .gap_3()
414                .child(
415                    v_flex()
416                        .size_full()
417                        .gap_2()
418                        .p_1()
419                        .child(Label::new(ollama_intro))
420                        .child(Label::new(ollama_reqs))
421                        .child(
422                            h_flex()
423                                .gap_0p5()
424                                .child(Label::new("Once installed, try "))
425                                .child(
426                                    div()
427                                        .bg(inline_code_bg)
428                                        .px_1p5()
429                                        .rounded_sm()
430                                        .child(Label::new("ollama run llama3.2")),
431                                ),
432                        ),
433                )
434                .child(
435                    h_flex()
436                        .w_full()
437                        .pt_2()
438                        .justify_between()
439                        .gap_2()
440                        .child(
441                            h_flex()
442                                .w_full()
443                                .gap_2()
444                                .map(|this| {
445                                    if is_authenticated {
446                                        this.child(
447                                            Button::new("ollama-site", "Ollama")
448                                                .style(ButtonStyle::Subtle)
449                                                .icon(IconName::ArrowUpRight)
450                                                .icon_size(IconSize::XSmall)
451                                                .icon_color(Color::Muted)
452                                                .on_click(move |_, _, cx| cx.open_url(OLLAMA_SITE))
453                                                .into_any_element(),
454                                        )
455                                    } else {
456                                        this.child(
457                                            Button::new(
458                                                "download_ollama_button",
459                                                "Download Ollama",
460                                            )
461                                            .style(ButtonStyle::Subtle)
462                                            .icon(IconName::ArrowUpRight)
463                                            .icon_size(IconSize::XSmall)
464                                            .icon_color(Color::Muted)
465                                            .on_click(move |_, _, cx| {
466                                                cx.open_url(OLLAMA_DOWNLOAD_URL)
467                                            })
468                                            .into_any_element(),
469                                        )
470                                    }
471                                })
472                                .child(
473                                    Button::new("view-models", "All Models")
474                                        .style(ButtonStyle::Subtle)
475                                        .icon(IconName::ArrowUpRight)
476                                        .icon_size(IconSize::XSmall)
477                                        .icon_color(Color::Muted)
478                                        .on_click(move |_, _, cx| cx.open_url(OLLAMA_LIBRARY_URL)),
479                                ),
480                        )
481                        .child(if is_authenticated {
482                            // This is only a button to ensure the spacing is correct
483                            // it should stay disabled
484                            ButtonLike::new("connected")
485                                .disabled(true)
486                                // Since this won't ever be clickable, we can use the arrow cursor
487                                .cursor_style(gpui::CursorStyle::Arrow)
488                                .child(
489                                    h_flex()
490                                        .gap_2()
491                                        .child(Indicator::dot().color(Color::Success))
492                                        .child(Label::new("Connected"))
493                                        .into_any_element(),
494                                )
495                                .into_any_element()
496                        } else {
497                            Button::new("retry_ollama_models", "Connect")
498                                .icon_position(IconPosition::Start)
499                                .icon(IconName::ArrowCircle)
500                                .on_click(
501                                    cx.listener(move |this, _, _, cx| this.retry_connection(cx)),
502                                )
503                                .into_any_element()
504                        }),
505                )
506                .into_any()
507        }
508    }
509}