llm/providers/local/
ollama.rs1#![doc = include_str!(concat!(env!("OUT_DIR"), "/docs/ollama.md"))]
2
3use super::util::get_local_config;
4use crate::provider_connection::DEFAULT_STREAM_IDLE_TIMEOUT;
5use crate::providers::http::{http_client, openai_client};
6use crate::providers::openai::OpenAiChatProvider;
7use crate::{ProviderConnectionConfig, ProviderFactory, Result};
8use async_openai::{Client, config::OpenAIConfig};
9use std::future::ready;
10use std::time::Duration;
11
12pub struct OllamaProvider {
13 model: String,
14 client: Client<OpenAIConfig>,
15 idle_timeout: Duration,
16}
17
18impl OllamaProvider {
19 pub fn new(model: &str, base_url: &str) -> Self {
20 Self {
21 model: model.to_string(),
22 client: openai_client(get_local_config(base_url), http_client()),
23 idle_timeout: DEFAULT_STREAM_IDLE_TIMEOUT,
24 }
25 }
26
27 pub fn default(model: &str) -> Self {
28 Self::new(model, "http://localhost:11434/v1")
29 }
30}
31
32impl ProviderFactory for OllamaProvider {
33 async fn from_env() -> Result<Self> {
34 Self::from_env_with_connection(ProviderConnectionConfig::default()).await
35 }
36
37 fn from_env_with_connection(connection: ProviderConnectionConfig) -> impl Future<Output = Result<Self>> + Send {
38 let base_url = connection.base_url.as_deref().unwrap_or("http://localhost:11434/v1");
39 ready(Ok(Self { idle_timeout: connection.idle_timeout, ..Self::new("", base_url) }))
40 }
41
42 fn with_model(mut self, model: &str) -> Self {
43 self.model = model.to_string();
44 self
45 }
46}
47
48impl OpenAiChatProvider for OllamaProvider {
49 type Config = OpenAIConfig;
50
51 fn client(&self) -> &Client<Self::Config> {
52 &self.client
53 }
54
55 fn model(&self) -> &str {
56 &self.model
57 }
58
59 fn provider_name(&self) -> &'static str {
60 "Ollama"
61 }
62
63 fn idle_timeout(&self) -> Duration {
64 self.idle_timeout
65 }
66}