返回 CodeWhale
ollama_catalog.rs
根目录 / crates / engine / src / client / ollama_catalog.rs
1 use std::time::Duration;
2
3 use futures_util::StreamExt;
4
5 use codewhale_config::catalog::{
6 CatalogOffering, CatalogSource, ProviderCatalogDelta, base_url_fingerprint, now_unix,
7 };
8 use serde::Deserialize;
9
10 pub const TAGS_PROBE_TIMEOUT: Duration = Duration::from_secs(2);
11
12 pub const SHOW_PROBE_LIMIT: usize = 8;
13
14 /// What `/api/show` reports about one tag. Both fields are optional because
15 /// older daemons omit `capabilities` and some architectures omit a context
16 /// length; a missing fact is unknown, never a "no".
17 #[derive(Debug, Clone, Default, PartialEq, Eq)]
18 pub struct OllamaTagProfile {
19 pub capabilities: Option<Vec<String>>,
20 pub context_length: Option<u64>,
21 }
22
23 impl OllamaTagProfile {
24 pub fn has_capability(&self, name: &str) -> Option<bool> {
25 self.capabilities
26 .as_ref()
27 .map(|caps| caps.iter().any(|cap| cap.eq_ignore_ascii_case(name)))
28 }
29 }
30
31 /// Name heuristic for tags that cannot chat: embedding and reranking models.
32 /// Used only when the daemon did not report capabilities.
33 pub fn looks_like_non_chat_tag(tag: &str) -> bool {
34 let lower = tag.to_ascii_lowercase();
35 ["embed", "bge", "rerank", "minilm"]
36 .iter()
37 .any(|needle| lower.contains(needle))
38 }
39
40 #[derive(Debug, Deserialize)]
41 struct OllamaShowResponse {
42 #[serde(default)]
43 capabilities: Option<Vec<String>>,
44 #[serde(default)]
45 model_info: Option<serde_json::Map<String, serde_json::Value>>,
46 }
47
48 /// Parse `POST /api/show` JSON into the facts adoption ranks on.
49 pub fn parse_ollama_show_response(payload: &str) -> anyhow::Result<OllamaTagProfile> {
50 let parsed: OllamaShowResponse = serde_json::from_str(payload)
51 .map_err(|err| anyhow::anyhow!("Failed to parse Ollama /api/show JSON: {err}"))?;
52 let context_length = parsed.model_info.as_ref().and_then(|info| {
53 info.iter()
54 .filter(|(key, _)| key.ends_with(".context_length"))
55 .find_map(|(_, value)| value.as_u64())
56 });
57 Ok(OllamaTagProfile {
58 capabilities: parsed.capabilities,
59 context_length,
60 })
61 }
62
63 /// Strip a trailing `/v1` (with optional slash) so we can hit native `/api/tags`.
64 pub fn ollama_native_origin(v1_base: &str) -> String {
65 let trimmed = v1_base.trim().trim_end_matches('/');
66 if let Some(origin) = trimmed.strip_suffix("/v1") {
67 origin.to_string()
68 } else {
69 trimmed.to_string()
70 }
71 }
72
73 #[derive(Debug, Deserialize)]
74 struct OllamaTagsResponse {
75 #[serde(default)]
76 models: Vec<OllamaTagModel>,
77 }
78
79 #[derive(Debug, Deserialize)]
80 struct OllamaTagModel {
81 #[serde(default)]
82 name: String,
83 #[serde(default)]
84 model: String,
85 #[serde(default)]
86 capabilities: Option<Vec<String>>,
87 #[serde(default)]
88 details: Option<serde_json::Value>,
89 #[serde(default)]
90 context_length: Option<u64>,
91 }
92
93 /// Parse native Ollama `GET /api/tags` JSON into sorted unique tag ids.
94 #[cfg(any(test, feature = "test-support"))]
95 pub fn parse_ollama_tags_response(payload: &str) -> anyhow::Result<Vec<String>> {
96 parse_ollama_tags_with_profiles(payload).map(|(tags, _)| tags)
97 }
98
99 pub fn parse_ollama_tags_with_profiles(
100 payload: &str,
101 ) -> anyhow::Result<(
102 Vec<String>,
103 std::collections::HashMap<String, OllamaTagProfile>,
104 )> {
105 let parsed: OllamaTagsResponse = serde_json::from_str(payload)
106 .map_err(|err| anyhow::anyhow!("Failed to parse Ollama /api/tags JSON: {err}"))?;
107 anyhow::ensure!(
108 parsed.models.len() <= super::PROVIDER_CATALOG_MAX_ROWS,
109 "Ollama catalog exceeds the model row limit"
110 );
111 let mut profiles = std::collections::HashMap::new();
112 for row in parsed.models {
113 let tag = if row.name.trim().is_empty() {
114 row.model.trim()
115 } else {
116 row.name.trim()
117 };
118 if !codewhale_runtime::catalog_cache::valid_catalog_model_id(tag) {
119 continue;
120 }
121 let profile = OllamaTagProfile {
122 capabilities: row.capabilities,
123 context_length: row
124 .details
125 .as_ref()
126 .and_then(|details| details.get("context_length"))
127 .and_then(serde_json::Value::as_u64)
128 .or(row.context_length),
129 };
130 if let Some(previous) = profiles.insert(tag.to_string(), profile.clone()) {
131 anyhow::ensure!(
132 previous == profile,
133 "Ollama reported conflicting tag capabilities"
134 );
135 }
136 }
137 let mut tags: Vec<String> = profiles.keys().cloned().collect();
138 tags.sort();
139 Ok((tags, profiles))
140 }
141
142 pub fn merge_ollama_profiles(
143 profiles: &mut std::collections::HashMap<String, OllamaTagProfile>,
144 fetched: std::collections::HashMap<String, OllamaTagProfile>,
145 ) {
146 for (tag, profile) in fetched {
147 profiles
148 .entry(tag)
149 .and_modify(|known| {
150 if known.capabilities.is_none() {
151 known.capabilities = profile.capabilities.clone();
152 }
153 if profile.context_length.is_some() {
154 known.context_length = profile.context_length;
155 }
156 })
157 .or_insert(profile);
158 }
159 }
160
161 pub fn ollama_catalog_delta(
162 provider: &str,
163 endpoint_v1: &str,
164 tags: &[String],
165 profiles: &std::collections::HashMap<String, OllamaTagProfile>,
166 running_body: Option<&str>,
167 ) -> ProviderCatalogDelta {
168 let running: std::collections::HashMap<String, u64> = running_body
169 .and_then(|body| serde_json::from_str::<OllamaTagsResponse>(body).ok())
170 .filter(|response| response.models.len() <= super::PROVIDER_CATALOG_MAX_ROWS)
171 .into_iter()
172 .flat_map(|response| response.models)
173 .filter_map(|row| {
174 let context = row.context_length.filter(|value| *value > 0)?;
175 let context = u32::try_from(context).ok().map(u64::from)?;
176 let tag = if row.name.trim().is_empty() {
177 row.model.trim()
178 } else {
179 row.name.trim()
180 };
181 (!tag.is_empty()).then(|| (tag.to_string(), context))
182 })
183 .collect();
184 let unknown = OllamaTagProfile::default();
185 let chat_tags: Vec<String> = tags
186 .iter()
187 .filter(|tag| codewhale_runtime::catalog_cache::valid_catalog_model_id(tag))
188 .filter(|tag| {
189 let profile = profiles.get(*tag).unwrap_or(&unknown);
190 match profile.has_capability("completion") {
191 Some(known) => known,
192 None => !looks_like_non_chat_tag(tag),
193 }
194 })
195 .cloned()
196 .collect();
197 let preferred = choose_chat_tag(&chat_tags, profiles);
198 let fingerprint = base_url_fingerprint(endpoint_v1);
199 let fetched_at = now_unix();
200 let source = CatalogSource::Live {
201 base_url_fingerprint: fingerprint.clone(),
202 fetched_at,
203 };
204 let offerings = chat_tags
205 .iter()
206 .map(|tag| {
207 let profile = profiles.get(tag).unwrap_or(&unknown);
208 let running_context = running.get(tag).copied();
209 let profile_context = profile
210 .context_length
211 .filter(|value| *value > 0)
212 .and_then(|value| u32::try_from(value).ok())
213 .map(u64::from);
214 let context = running_context.or(profile_context);
215 let mut fact_sources = std::collections::BTreeMap::new();
216 if running_context.is_some() {
217 fact_sources.insert("limit.context.ps".to_string(), source.clone());
218 }
219 let limit = context.map(|context| codewhale_config::models_dev::ModelsDevLimit {
220 context: Some(context),
221 input: profile_context,
222 output: None,
223 });
224 CatalogOffering {
225 provider: provider.to_string(),
226 wire_model_id: tag.clone(),
227 endpoint_key: "chat".into(),
228 default_for_provider: preferred.as_deref() == Some(tag.as_str()),
229 tool_call: profile.has_capability("tools"),
230 reasoning: profile.has_capability("thinking"),
231 fact_sources,
232 limit,
233 source: source.clone(),
234 ..Default::default()
235 }
236 })
237 .collect();
238 ProviderCatalogDelta {
239 provider: provider.to_string(),
240 base_url_fingerprint: fingerprint,
241 fetched_at,
242 offerings,
243 }
244 }
245
246 pub fn probe_client() -> anyhow::Result<reqwest::Client> {
247 // The first-run probe can run before any provider client has installed
248 // the rustls crypto provider; the shared builder installs it (the bare
249 // `reqwest::Client::builder()` panics under `rustls-no-provider`).
250 Ok(crate::platform_client_builder()
251 .timeout(TAGS_PROBE_TIMEOUT)
252 .build()?)
253 }
254
255 #[cfg(not(any(test, all(feature = "test-thread-scoped-state", debug_assertions))))]
256 pub const MODEL_LOAD_TIMEOUT: Duration = Duration::from_secs(60);
257
258 #[cfg(not(any(test, all(feature = "test-thread-scoped-state", debug_assertions))))]
259 pub async fn load_model(origin: &str, tag: &str) -> bool {
260 let Ok(client) = crate::platform_client_builder()
261 .timeout(MODEL_LOAD_TIMEOUT)
262 .build()
263 else {
264 return false;
265 };
266 client
267 .post(format!("{origin}/api/generate"))
268 .json(&serde_json::json!({ "model": tag }))
269 .send()
270 .await
271 .is_ok_and(|response| response.status().is_success())
272 }
273
274 pub async fn fetch_text(url: &str) -> anyhow::Result<String> {
275 let response = probe_client()?.get(url).send().await?;
276 if !response.status().is_success() {
277 anyhow::bail!("HTTP {}", response.status());
278 }
279 super::bounded_provider_catalog_text(response, super::PROVIDER_CATALOG_MAX_RESPONSE_BYTES)
280 .await
281 .map_err(|reason| anyhow::anyhow!("Ollama catalog response rejected: {reason:?}"))
282 }
283
284 pub async fn fetch_tag_profile(origin: &str, tag: &str) -> anyhow::Result<OllamaTagProfile> {
285 let response = probe_client()?
286 .post(format!("{origin}/api/show"))
287 .json(&serde_json::json!({ "model": tag }))
288 .send()
289 .await?;
290 if !response.status().is_success() {
291 anyhow::bail!("HTTP {}", response.status());
292 }
293 let body =
294 super::bounded_provider_catalog_text(response, super::PROVIDER_CATALOG_MAX_RESPONSE_BYTES)
295 .await
296 .map_err(|reason| anyhow::anyhow!("Ollama profile response rejected: {reason:?}"))?;
297 parse_ollama_show_response(&body)
298 }
299
300 /// An unprofiled tag cannot become an executable catalog default.
301 pub async fn fetch_tag_profiles<F, Fut>(
302 tags: &[String],
303 profiles: &std::collections::HashMap<String, OllamaTagProfile>,
304 mut fetch: F,
305 ) -> std::collections::HashMap<String, OllamaTagProfile>
306 where
307 F: FnMut(String) -> Fut,
308 Fut: std::future::Future<Output = anyhow::Result<OllamaTagProfile>>,
309 {
310 let candidates: Vec<String> = tags
311 .iter()
312 .filter(|tag| {
313 profiles
314 .get(*tag)
315 .is_none_or(|profile| profile.capabilities.is_none())
316 })
317 .cloned()
318 .collect();
319 let probes = futures_util::stream::iter(candidates.into_iter().map(|tag| {
320 let future = fetch(tag.clone());
321 async move {
322 let result = future.await;
323 (tag, result)
324 }
325 }));
326 probes
327 .buffer_unordered(SHOW_PROBE_LIMIT)
328 .filter_map(|(tag, result)| futures_util::future::ready(match result {
329 Ok(profile) => Some((tag, profile)),
330 Err(err) => {
331 tracing::debug!(target: "local_ollama", error = %err, tag = %tag, "POST /api/show probe failed");
332 None
333 }
334 }))
335 .collect()
336 .await
337 }
338
339 fn looks_like_coder_tag(tag: &str) -> bool {
340 let lower = tag.to_ascii_lowercase();
341 lower.contains("coder") || lower.contains("code")
342 }
343
344 /// Pick the tag adoption should switch to.
345 ///
346 /// A tag is a chat candidate when `/api/show` lists `completion`, or — when
347 /// the daemon reported no capabilities — when its name is not an embedding or
348 /// reranker. Among candidates: coder or tool-capable models first, then the
349 /// largest reported context, then alphabetical order for stability.
350 pub fn choose_chat_tag(
351 tags: &[String],
352 profiles: &std::collections::HashMap<String, OllamaTagProfile>,
353 ) -> Option<String> {
354 let unknown = OllamaTagProfile::default();
355 tags.iter()
356 .filter_map(|tag| {
357 let profile = profiles.get(tag).unwrap_or(&unknown);
358 let chat = match profile.has_capability("completion") {
359 Some(known) => known,
360 None => !looks_like_non_chat_tag(tag),
361 };
362 if !chat {
363 return None;
364 }
365 let preferred =
366 looks_like_coder_tag(tag) || profile.has_capability("tools").unwrap_or(false);
367 Some((
368 preferred,
369 profile.context_length.unwrap_or(0),
370 std::cmp::Reverse(tag.as_str()),
371 tag,
372 ))
373 })
374 .max_by(|a, b| (a.0, a.1, &a.2).cmp(&(b.0, b.1, &b.2)))
375 .map(|(_, _, _, tag)| tag.clone())
376 }
377
377 lines RUST