Skip to main content

qualia_client_core/
asset_recommendations.rs

1//! Device-aware LLM + ontology recommendations for Design Studio and native runtime.
2
3use qualia_core_db::resource_catalog::ResourceCatalog;
4use serde::{Deserialize, Serialize};
5use std::path::Path;
6use sysinfo::System;
7
8use crate::context_binding::list_installed_ontology_ids;
9use crate::model_preferences::list_installed_model_ids;
10
11#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
12#[serde(rename_all = "snake_case")]
13pub enum DeviceTier {
14    Edge,
15    Mainstream,
16    HighPerformance,
17}
18
19impl DeviceTier {
20    /// Constructs from ram-gb.
21    pub fn from_ram_gb(ram_gb: f64) -> Self {
22        if ram_gb < 6.0 {
23            Self::Edge
24        } else if ram_gb < 16.0 {
25            Self::Mainstream
26        } else {
27            Self::HighPerformance
28        }
29    }
30
31    /// Label.
32    pub fn label(self) -> &'static str {
33        match self {
34            Self::Edge => "edge",
35            Self::Mainstream => "mainstream",
36            Self::HighPerformance => "high_performance",
37        }
38    }
39}
40
41#[derive(Debug, Clone, Default, Serialize, Deserialize)]
42pub struct DeviceProfileInput {
43    #[serde(default)]
44    pub ram_gb: Option<f64>,
45    #[serde(default)]
46    pub has_webgpu: bool,
47    #[serde(default)]
48    pub cpu_cores: Option<u32>,
49    #[serde(default)]
50    pub platform: Option<String>,
51    #[serde(default)]
52    pub user_agent: Option<String>,
53}
54
55#[derive(Debug, Clone, Serialize, Deserialize)]
56pub struct DeviceProfile {
57    pub tier: DeviceTier,
58    pub ram_gb: f64,
59    pub has_webgpu: bool,
60    pub cpu_cores: u32,
61    pub platform: String,
62    pub source: String,
63}
64
65#[derive(Debug, Clone, Default, Serialize, Deserialize)]
66pub struct DesignContextInput {
67    #[serde(default)]
68    pub prompt: String,
69    #[serde(default)]
70    pub domains: Vec<String>,
71    #[serde(default)]
72    pub keywords: Vec<String>,
73}
74
75#[derive(Debug, Clone, Serialize, Deserialize)]
76#[serde(rename_all = "snake_case")]
77pub enum AssetKind {
78    Llm,
79    Ontology,
80}
81
82#[derive(Debug, Clone, Serialize, Deserialize)]
83pub struct InstallAction {
84    pub kind: String,
85    #[serde(skip_serializing_if = "Option::is_none")]
86    pub job_payload: Option<serde_json::Value>,
87    pub cli_hint: String,
88    pub native_note: String,
89}
90
91#[derive(Debug, Clone, Serialize, Deserialize)]
92pub struct AssetRecommendation {
93    pub kind: AssetKind,
94    pub id: String,
95    pub name: String,
96    pub reason: String,
97    pub size_mb: f64,
98    #[serde(skip_serializing_if = "Option::is_none")]
99    pub ram_estimate_mb: Option<u32>,
100    pub already_installed: bool,
101    pub priority: u8,
102    pub install: InstallAction,
103}
104
105#[derive(Debug, Clone, Serialize, Deserialize)]
106pub struct AssetRecommendationsResponse {
107    pub device: DeviceProfile,
108    pub inferred_domains: Vec<String>,
109    pub llms: Vec<AssetRecommendation>,
110    pub ontologies: Vec<AssetRecommendation>,
111    pub wiring_notes: Vec<String>,
112}
113
114/// Native device profile.
115pub fn native_device_profile() -> DeviceProfile {
116    let mut sys = System::new_all();
117    sys.refresh_memory();
118    let ram_gb = sys.total_memory() as f64 / 1024.0 / 1024.0 / 1024.0;
119    DeviceProfile {
120        tier: DeviceTier::from_ram_gb(ram_gb),
121        ram_gb,
122        has_webgpu: false,
123        cpu_cores: sys.cpus().len() as u32,
124        platform: std::env::consts::OS.to_string(),
125        source: "native_sysinfo".to_string(),
126    }
127}
128
129/// Device profile from input text.
130pub fn device_profile_from_input(input: &DeviceProfileInput) -> DeviceProfile {
131    if let Some(ram) = input.ram_gb {
132        return DeviceProfile {
133            tier: DeviceTier::from_ram_gb(ram),
134            ram_gb: ram,
135            has_webgpu: input.has_webgpu,
136            cpu_cores: input.cpu_cores.unwrap_or(4),
137            platform: input
138                .platform
139                .clone()
140                .unwrap_or_else(|| "browser".to_string()),
141            source: "client_reported".to_string(),
142        };
143    }
144    native_device_profile()
145}
146
147/// Infers domains from text.
148pub fn infer_domains_from_text(text: &str) -> Vec<String> {
149    let lower = text.to_lowercase();
150    let mut domains = Vec::new();
151    let rules: &[(&str, &[&str])] = &[
152        (
153            "product",
154            &[
155                "design", "product", "assembly", "module", "part", "housing", "switch", "socket",
156                "gadget", "device",
157            ],
158        ),
159        (
160            "electrical",
161            &[
162                "electric",
163                "electrician",
164                "power",
165                "mains",
166                "voltage",
167                "wiring",
168                "powerpoint",
169            ],
170        ),
171        (
172            "iot",
173            &["sensor", "wifi", "smart", "mcu", "bluetooth", "home"],
174        ),
175        (
176            "health",
177            &[
178                "medical",
179                "clinical",
180                "anatomy",
181                "patient",
182                "diagnosis",
183                "dicom",
184            ],
185        ),
186        (
187            "legal",
188            &["contract", "obligation", "rights", "policy", "consent"],
189        ),
190        (
191            "geography",
192            &["map", "location", "geo", "place", "building"],
193        ),
194        ("linguistics", &["word", "language", "lexicon", "ontology"]),
195    ];
196    for (domain, kws) in rules {
197        if kws.iter().any(|kw| lower.contains(kw)) {
198            domains.push(domain.to_string());
199        }
200    }
201    if domains.is_empty() {
202        domains.push("general".to_string());
203    }
204    domains.sort();
205    domains.dedup();
206    domains
207}
208
209fn llm_fits_ram(ram_gb: f64, need_mb: u32) -> bool {
210    ram_gb * 1024.0 * 0.72 >= need_mb as f64
211}
212
213fn score_llm(
214    catalog_entry: &qualia_core_db::resource_catalog::LLMResource,
215    device: &DeviceProfile,
216    installed: &[String],
217) -> Option<(u8, String)> {
218    let need = catalog_entry.ram_estimate_mb.or(catalog_entry.size_mb)?;
219    if !llm_fits_ram(device.ram_gb, need) {
220        return None;
221    }
222    let rec = catalog_entry.recommended_for.as_deref().unwrap_or(&[]);
223    let mut score: u8 = 40;
224    let mut reasons = Vec::new();
225
226    match device.tier {
227        DeviceTier::Edge => {
228            if rec.iter().any(|r| r == "very_low_ram" || r == "edge") {
229                score += 35;
230                reasons.push("edge tier match");
231            }
232            if need <= 1500 {
233                score += 15;
234                reasons.push("fits low RAM");
235            }
236        }
237        DeviceTier::Mainstream => {
238            if rec
239                .iter()
240                .any(|r| r == "edge" || r == "low_ram" || r == "general")
241            {
242                score += 25;
243                reasons.push("mainstream fit");
244            }
245        }
246        DeviceTier::HighPerformance => {
247            score += 10;
248            if need >= 4000 {
249                score += 20;
250                reasons.push("room for larger model");
251            }
252        }
253    }
254
255    if device.has_webgpu && need <= 1200 {
256        score += 10;
257        reasons.push("browser WebGPU friendly");
258    }
259
260    if installed.iter().any(|id| id == &catalog_entry.id) {
261        score = score.saturating_sub(30);
262        reasons.push("already installed");
263    }
264
265    if reasons.is_empty() {
266        reasons.push("catalog match");
267    }
268    Some((score.min(100), reasons.join("; ")))
269}
270
271fn ontology_domain_match(
272    ont: &qualia_core_db::resource_catalog::OntologyResource,
273    domains: &[String],
274) -> bool {
275    if domains.contains(&"general".to_string())
276        && ont
277            .tags
278            .as_ref()
279            .is_some_and(|t| t.contains(&"core".to_string()))
280    {
281        return true;
282    }
283    if let Some(d) = &ont.domain {
284        if domains.iter().any(|x| x == d) {
285            return true;
286        }
287    }
288    let tags = ont.tags.as_deref().unwrap_or(&[]);
289    domains.iter().any(|d| tags.iter().any(|t| t == d))
290}
291
292fn score_ontology(
293    ont: &qualia_core_db::resource_catalog::OntologyResource,
294    device: &DeviceProfile,
295    domains: &[String],
296    installed: &[String],
297) -> Option<(u8, String)> {
298    let size = ont.size_estimate_mb.unwrap_or(1.0);
299    let max_size = match device.tier {
300        DeviceTier::Edge => 3.0,
301        DeviceTier::Mainstream => 15.0,
302        DeviceTier::HighPerformance => 64.0,
303    };
304    if size > max_size {
305        return None;
306    }
307
308    let is_core = ont
309        .tags
310        .as_ref()
311        .is_some_and(|t| t.contains(&"core".to_string()));
312    let domain_hit = ontology_domain_match(ont, domains);
313    if !is_core && !domain_hit {
314        return None;
315    }
316
317    let mut score: u8 = if is_core { 70 } else { 45 };
318    let mut reasons = Vec::new();
319    if is_core {
320        reasons.push("core vocabulary");
321    }
322    if domain_hit {
323        score += 20;
324        reasons.push("domain match");
325    }
326    if size < 1.0 {
327        score += 10;
328        reasons.push("lightweight");
329    }
330    if installed.iter().any(|id| id == &ont.id) {
331        score = score.saturating_sub(25);
332        reasons.push("already installed");
333    }
334    Some((score.min(100), reasons.join("; ")))
335}
336
337/// Recommends assets.
338pub fn recommend_assets(
339    catalog: &ResourceCatalog,
340    device: &DeviceProfile,
341    design: &DesignContextInput,
342    storage_root: Option<&Path>,
343) -> AssetRecommendationsResponse {
344    let mut domains = design.domains.clone();
345    if domains.is_empty() {
346        domains = infer_domains_from_text(&design.prompt);
347    }
348
349    let installed_llms = storage_root
350        .map(list_installed_model_ids)
351        .unwrap_or_default();
352    let installed_onts = storage_root
353        .map(list_installed_ontology_ids)
354        .unwrap_or_default();
355
356    let mut llms: Vec<AssetRecommendation> = catalog
357        .llms
358        .iter()
359        .filter_map(|llm| {
360            let (priority, reason) = score_llm(llm, device, &installed_llms)?;
361            let installed = installed_llms.iter().any(|id| id == &llm.id);
362            Some(AssetRecommendation {
363                kind: AssetKind::Llm,
364                id: llm.id.clone(),
365                name: llm.name.clone(),
366                reason,
367                size_mb: llm.size_mb.unwrap_or(0) as f64,
368                ram_estimate_mb: llm.ram_estimate_mb.or(llm.size_mb),
369                already_installed: installed,
370                priority,
371                install: InstallAction {
372                    kind: "download_gguf".to_string(),
373                    job_payload: None,
374                    cli_hint: format!("qualia resources import llm {}", llm.id),
375                    native_note: "Flutter/desktop: LLM Hub → install manifest; activates via model_lifecycle.".to_string(),
376                },
377            })
378        })
379        .collect();
380    llms.sort_by(|a, b| b.priority.cmp(&a.priority));
381    llms.truncate(4);
382
383    let mut ontologies: Vec<AssetRecommendation> = catalog
384        .ontologies
385        .iter()
386        .filter_map(|ont| {
387            let (priority, reason) = score_ontology(ont, device, &domains, &installed_onts)?;
388            let installed = installed_onts.iter().any(|id| id == &ont.id);
389            Some(AssetRecommendation {
390                kind: AssetKind::Ontology,
391                id: ont.id.clone(),
392                name: ont.name.clone(),
393                reason,
394                size_mb: ont.size_estimate_mb.unwrap_or(0.5),
395                ram_estimate_mb: None,
396                already_installed: installed,
397                priority,
398                install: InstallAction {
399                    kind: "ontology_catalog_import".to_string(),
400                    job_payload: Some(serde_json::json!({
401                        "kind": "ontology_catalog_import",
402                        "ontology_id": ont.id
403                    })),
404                    cli_hint: format!("qualia resources import ontology {}", ont.id),
405                    native_note:
406                        "Settings portal :8080 can enqueue the same job via POST /api/jobs."
407                            .to_string(),
408                },
409            })
410        })
411        .collect();
412    ontologies.sort_by(|a, b| b.priority.cmp(&a.priority));
413    ontologies.truncate(6);
414
415    let wiring_notes = vec![
416        "Native runtime: graph daemon :4242 + installed ontologies improve SPARQL enrichment and chat grounding.".to_string(),
417        "LLM: local GGUF via qualia-client-core model_lifecycle; governed by orchestrate_inference (intent + provenance).".to_string(),
418        "Design Studio: qualia.design JSON → design_encode_wasm → Qualia Portal tensor SOA.".to_string(),
419        "Optional: connect http://127.0.0.1:8080 for one-click ontology import jobs and authoritative device RAM from desktop.".to_string(),
420    ];
421
422    AssetRecommendationsResponse {
423        device: device.clone(),
424        inferred_domains: domains,
425        llms,
426        ontologies,
427        wiring_notes,
428    }
429}
430
431#[cfg(test)]
432mod tests {
433    use super::*;
434
435    #[test]
436    fn infers_product_and_electrical_domains() {
437        let d = infer_domains_from_text("two part smart powerpoint installed by electrician");
438        assert!(d.contains(&"product".to_string()));
439        assert!(d.contains(&"electrical".to_string()));
440    }
441
442    #[test]
443    fn edge_tier_from_low_ram() {
444        assert_eq!(DeviceTier::from_ram_gb(4.0), DeviceTier::Edge);
445    }
446}