1use anyhow::{anyhow, bail, Result};
2use futures::{future::BoxFuture, stream::BoxStream, FutureExt, StreamExt};
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 get_models, preload_model, stream_chat_completion, ChatMessage, ChatOptions, ChatRequest,
13 ChatResponseDelta, KeepAlive, OllamaToolCall,
14};
15use schemars::JsonSchema;
16use serde::{Deserialize, Serialize};
17use settings::{Settings, SettingsStore};
18use std::{collections::BTreeMap, sync::Arc};
19use ui::{prelude::*, ButtonLike, Indicator};
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 fn request_completion(
269 &self,
270 request: ChatRequest,
271 cx: &AsyncApp,
272 ) -> BoxFuture<'static, Result<ChatResponseDelta>> {
273 let http_client = self.http_client.clone();
274
275 let Ok(api_url) = cx.update(|cx| {
276 let settings = &AllLanguageModelSettings::get_global(cx).ollama;
277 settings.api_url.clone()
278 }) else {
279 return futures::future::ready(Err(anyhow!("App state dropped"))).boxed();
280 };
281
282 async move { ollama::complete(http_client.as_ref(), &api_url, request).await }.boxed()
283 }
284}
285
286impl LanguageModel for OllamaLanguageModel {
287 fn id(&self) -> LanguageModelId {
288 self.id.clone()
289 }
290
291 fn name(&self) -> LanguageModelName {
292 LanguageModelName::from(self.model.display_name().to_string())
293 }
294
295 fn provider_id(&self) -> LanguageModelProviderId {
296 LanguageModelProviderId(PROVIDER_ID.into())
297 }
298
299 fn provider_name(&self) -> LanguageModelProviderName {
300 LanguageModelProviderName(PROVIDER_NAME.into())
301 }
302
303 fn telemetry_id(&self) -> String {
304 format!("ollama/{}", self.model.id())
305 }
306
307 fn max_token_count(&self) -> usize {
308 self.model.max_token_count()
309 }
310
311 fn count_tokens(
312 &self,
313 request: LanguageModelRequest,
314 _cx: &App,
315 ) -> BoxFuture<'static, Result<usize>> {
316 // There is no endpoint for this _yet_ in Ollama
317 // see: https://github.com/ollama/ollama/issues/1716 and https://github.com/ollama/ollama/issues/3582
318 let token_count = request
319 .messages
320 .iter()
321 .map(|msg| msg.string_contents().chars().count())
322 .sum::<usize>()
323 / 4;
324
325 async move { Ok(token_count) }.boxed()
326 }
327
328 fn stream_completion(
329 &self,
330 request: LanguageModelRequest,
331 cx: &AsyncApp,
332 ) -> BoxFuture<'static, Result<BoxStream<'static, Result<LanguageModelCompletionEvent>>>> {
333 let request = self.to_ollama_request(request);
334
335 let http_client = self.http_client.clone();
336 let Ok(api_url) = cx.update(|cx| {
337 let settings = &AllLanguageModelSettings::get_global(cx).ollama;
338 settings.api_url.clone()
339 }) else {
340 return futures::future::ready(Err(anyhow!("App state dropped"))).boxed();
341 };
342
343 let future = self.request_limiter.stream(async move {
344 let response = stream_chat_completion(http_client.as_ref(), &api_url, request).await?;
345 let stream = response
346 .filter_map(|response| async move {
347 match response {
348 Ok(delta) => {
349 let content = match delta.message {
350 ChatMessage::User { content } => content,
351 ChatMessage::Assistant { content, .. } => content,
352 ChatMessage::System { content } => content,
353 };
354 Some(Ok(content))
355 }
356 Err(error) => Some(Err(error)),
357 }
358 })
359 .boxed();
360 Ok(stream)
361 });
362
363 async move {
364 Ok(future
365 .await?
366 .map(|result| result.map(LanguageModelCompletionEvent::Text))
367 .boxed())
368 }
369 .boxed()
370 }
371
372 fn use_any_tool(
373 &self,
374 request: LanguageModelRequest,
375 tool_name: String,
376 tool_description: String,
377 schema: serde_json::Value,
378 cx: &AsyncApp,
379 ) -> BoxFuture<'static, Result<BoxStream<'static, Result<String>>>> {
380 use ollama::{OllamaFunctionTool, OllamaTool};
381 let function = OllamaFunctionTool {
382 name: tool_name.clone(),
383 description: Some(tool_description),
384 parameters: Some(schema),
385 };
386 let tools = vec![OllamaTool::Function { function }];
387 let request = self.to_ollama_request(request).with_tools(tools);
388 let response = self.request_completion(request, cx);
389 self.request_limiter
390 .run(async move {
391 let response = response.await?;
392 let ChatMessage::Assistant { tool_calls, .. } = response.message else {
393 bail!("message does not have an assistant role");
394 };
395 if let Some(tool_calls) = tool_calls.filter(|calls| !calls.is_empty()) {
396 for call in tool_calls {
397 let OllamaToolCall::Function(function) = call;
398 if function.name == tool_name {
399 return Ok(futures::stream::once(async move {
400 Ok(function.arguments.to_string())
401 })
402 .boxed());
403 }
404 }
405 } else {
406 bail!("assistant message does not have any tool calls");
407 };
408
409 bail!("tool not used")
410 })
411 .boxed()
412 }
413}
414
415struct ConfigurationView {
416 state: gpui::Entity<State>,
417 loading_models_task: Option<Task<()>>,
418}
419
420impl ConfigurationView {
421 pub fn new(state: gpui::Entity<State>, window: &mut Window, cx: &mut Context<Self>) -> Self {
422 let loading_models_task = Some(cx.spawn_in(window, {
423 let state = state.clone();
424 async move |this, cx| {
425 if let Some(task) = state
426 .update(cx, |state, cx| state.authenticate(cx))
427 .log_err()
428 {
429 task.await.log_err();
430 }
431 this.update(cx, |this, cx| {
432 this.loading_models_task = None;
433 cx.notify();
434 })
435 .log_err();
436 }
437 }));
438
439 Self {
440 state,
441 loading_models_task,
442 }
443 }
444
445 fn retry_connection(&self, cx: &mut App) {
446 self.state
447 .update(cx, |state, cx| state.fetch_models(cx))
448 .detach_and_log_err(cx);
449 }
450}
451
452impl Render for ConfigurationView {
453 fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
454 let is_authenticated = self.state.read(cx).is_authenticated();
455
456 let ollama_intro = "Get up and running with Llama 3.3, Mistral, Gemma 2, and other large language models with Ollama.";
457 let ollama_reqs =
458 "Ollama must be running with at least one model installed to use it in the assistant.";
459
460 let inline_code_bg = cx.theme().colors().editor_foreground.opacity(0.05);
461
462 if self.loading_models_task.is_some() {
463 div().child(Label::new("Loading models...")).into_any()
464 } else {
465 v_flex()
466 .size_full()
467 .gap_3()
468 .child(
469 v_flex()
470 .size_full()
471 .gap_2()
472 .p_1()
473 .child(Label::new(ollama_intro))
474 .child(Label::new(ollama_reqs))
475 .child(
476 h_flex()
477 .gap_0p5()
478 .child(Label::new("Once installed, try "))
479 .child(
480 div()
481 .bg(inline_code_bg)
482 .px_1p5()
483 .rounded_sm()
484 .child(Label::new("ollama run llama3.2")),
485 ),
486 ),
487 )
488 .child(
489 h_flex()
490 .w_full()
491 .pt_2()
492 .justify_between()
493 .gap_2()
494 .child(
495 h_flex()
496 .w_full()
497 .gap_2()
498 .map(|this| {
499 if is_authenticated {
500 this.child(
501 Button::new("ollama-site", "Ollama")
502 .style(ButtonStyle::Subtle)
503 .icon(IconName::ArrowUpRight)
504 .icon_size(IconSize::XSmall)
505 .icon_color(Color::Muted)
506 .on_click(move |_, _, cx| cx.open_url(OLLAMA_SITE))
507 .into_any_element(),
508 )
509 } else {
510 this.child(
511 Button::new(
512 "download_ollama_button",
513 "Download Ollama",
514 )
515 .style(ButtonStyle::Subtle)
516 .icon(IconName::ArrowUpRight)
517 .icon_size(IconSize::XSmall)
518 .icon_color(Color::Muted)
519 .on_click(move |_, _, cx| {
520 cx.open_url(OLLAMA_DOWNLOAD_URL)
521 })
522 .into_any_element(),
523 )
524 }
525 })
526 .child(
527 Button::new("view-models", "All Models")
528 .style(ButtonStyle::Subtle)
529 .icon(IconName::ArrowUpRight)
530 .icon_size(IconSize::XSmall)
531 .icon_color(Color::Muted)
532 .on_click(move |_, _, cx| cx.open_url(OLLAMA_LIBRARY_URL)),
533 ),
534 )
535 .child(if is_authenticated {
536 // This is only a button to ensure the spacing is correct
537 // it should stay disabled
538 ButtonLike::new("connected")
539 .disabled(true)
540 // Since this won't ever be clickable, we can use the arrow cursor
541 .cursor_style(gpui::CursorStyle::Arrow)
542 .child(
543 h_flex()
544 .gap_2()
545 .child(Indicator::dot().color(Color::Success))
546 .child(Label::new("Connected"))
547 .into_any_element(),
548 )
549 .into_any_element()
550 } else {
551 Button::new("retry_ollama_models", "Connect")
552 .icon_position(IconPosition::Start)
553 .icon(IconName::ArrowCircle)
554 .on_click(
555 cx.listener(move |this, _, _, cx| this.retry_connection(cx)),
556 )
557 .into_any_element()
558 }),
559 )
560 .into_any()
561 }
562 }
563}