Skip to content

armgit / kwant

Public Imported from GitHub
0

Your own team of AI bots in one self-hosted binary: spaces, every account you have, handoffs, approvals and routines. Open-source, self-hosted alternative to Grok Bot, Claude Duet and OpenAI dots. Rust + React.

feat: implement Laya model router with offline fallback

Oleksandr Ivanchenko654d975036a5
diff --git a/src/lib.rs b/src/lib.rs
index e4cd9be9..2ed5b122 100644
--- a/src/lib.rs
+++ b/src/lib.rs
@@ -1,5 +1,7 @@
pub mod config;
pub mod db;
+pub mod router;
pub use config::{Config, ConfigError};
pub use db::{Database, DbError};
+pub use router::{LayaRouter, RouteDecision, RouterError};
diff --git a/src/router/fallback.rs b/src/router/fallback.rs
new file mode 100644
index 00000000..cf8e61a3
--- /dev/null
+++ b/src/router/fallback.rs
@@ -0,0 +1,71 @@
+use super::RouteDecision;
+
+/// Evaluates a prompt using local keyword scoring heuristics when Laya is offline.
+pub fn heuristic_fallback(prompt: &str, context: &str) -> RouteDecision {
+ let lower_prompt = prompt.to_lowercase();
+ let lower_context = context.to_lowercase();
+ let combined = format!("{} {}", lower_prompt, lower_context);
+
+ // 1. Private / local check
+ if combined.contains("private")
+ || combined.contains("confidential")
+ || combined.contains("local")
+ || combined.contains("offline")
+ || combined.contains("sensitive")
+ {
+ return RouteDecision {
+ selected_model: "local_ollama".into(),
+ confidence: 0.85,
+ provider_endpoint: Some("http://localhost:11434/v1".into()),
+ is_fallback: true,
+ reasoning: "Local privacy keywords detected in prompt".into(),
+ };
+ }
+
+ // 2. Complex architecture / multi-file / deep analysis check
+ if combined.contains("architecture")
+ || combined.contains("design doc")
+ || combined.contains("tradeoff")
+ || combined.contains("refactor")
+ || combined.contains("analysis")
+ || combined.contains("philosophy")
+ || combined.contains("essay")
+ {
+ return RouteDecision {
+ selected_model: "claude".into(),
+ confidence: 0.88,
+ provider_endpoint: None,
+ is_fallback: true,
+ reasoning: "Architectural reasoning keywords detected in prompt".into(),
+ };
+ }
+
+ // 3. Direct coding / script / regex check
+ if combined.contains("python")
+ || combined.contains("rust")
+ || combined.contains("javascript")
+ || combined.contains("typescript")
+ || combined.contains("code")
+ || combined.contains("script")
+ || combined.contains("regex")
+ || combined.contains("algorithm")
+ || combined.contains("function")
+ {
+ return RouteDecision {
+ selected_model: "codex".into(),
+ confidence: 0.82,
+ provider_endpoint: None,
+ is_fallback: true,
+ reasoning: "Programming keywords detected in prompt".into(),
+ };
+ }
+
+ // 4. Default: grok for speed, witty tone, and general queries
+ RouteDecision {
+ selected_model: "grok".into(),
+ confidence: 0.75,
+ provider_endpoint: None,
+ is_fallback: true,
+ reasoning: "Default fast model selected".into(),
+ }
+}
diff --git a/src/router/laya.rs b/src/router/laya.rs
new file mode 100644
index 00000000..d6d424ca
--- /dev/null
+++ b/src/router/laya.rs
@@ -0,0 +1,72 @@
+use super::{fallback::heuristic_fallback, RouteDecision, RouterError};
+use reqwest::Client;
+use serde_json::json;
+use std::time::Duration;
+
+#[derive(Clone, Debug)]
+pub struct LayaRouter {
+ pub base_url: String,
+ client: Client,
+}
+
+impl LayaRouter {
+ pub fn new(base_url: String) -> Self {
+ let client = Client::builder()
+ .timeout(Duration::from_millis(1500))
+ .build()
+ .unwrap_or_else(|_| Client::new());
+
+ Self { base_url, client }
+ }
+
+ /// Routes a prompt to the optimal model using Laya (/v1/systemone),
+ /// falling back gracefully to local heuristics if Laya is unreachable.
+ pub async fn route_prompt(&self, prompt: &str, context: &str) -> Result<RouteDecision, RouterError> {
+ let payload = json!({
+ "state": {
+ "prompt": prompt,
+ "context": context
+ },
+ "questions": {
+ "model_selection": {
+ "type": "choice",
+ "instructions": "Which model is best suited for this task?",
+ "criteria": {
+ "grok": "fast technical reasoning, witty banter, quick coding solutions",
+ "claude": "deep architecture, multi-file refactoring, long complex analysis",
+ "codex": "direct code generation, standard algorithms, regex, JSON transforms",
+ "local_ollama": "private data, offline tasks, zero API cost"
+ }
+ }
+ }
+ });
+
+ let endpoint = format!("{}/v1/systemone", self.base_url.trim_end_matches('/'));
+
+ match self.client.post(&endpoint).json(&payload).send().await {
+ Ok(resp) if resp.status().is_success() => {
+ match resp.json::<serde_json::Value>().await {
+ Ok(data) => {
+ if let Some(decision) = super::parse_laya_response(&data) {
+ return Ok(decision);
+ }
+ tracing::warn!("Laya response missing expected fields, using fallback");
+ Ok(heuristic_fallback(prompt, context))
+ }
+ Err(e) => {
+ tracing::warn!(error = %e, "Failed to parse Laya response body, using fallback");
+ Ok(heuristic_fallback(prompt, context))
+ }
+ }
+ }
+ Ok(resp) => {
+ tracing::warn!(status = %resp.status(), "Laya service returned error, using fallback");
+ Ok(heuristic_fallback(prompt, context))
+ }
+ Err(e) => {
+ tracing::debug!(error = %e, "Laya service unreachable, using fallback");
+ Ok(heuristic_fallback(prompt, context))
+ }
+ }
+ }
+}
diff --git a/src/router/mod.rs b/src/router/mod.rs
new file mode 100644
index 00000000..ac043e49
--- /dev/null
+++ b/src/router/mod.rs
@@ -0,0 +1,51 @@
+pub mod fallback;
+pub mod laya;
+
+pub use fallback::heuristic_fallback;
+pub use laya::LayaRouter;
+use serde::{Deserialize, Serialize};
+use thiserror::Error;
+
+#[derive(Error, Debug)]
+pub enum RouterError {
+ #[error("Network error communicating with model router: {0}")]
+ Network(#[from] reqwest::Error),
+
+ #[error("Failed to parse routing decision: {0}")]
+ Parse(String),
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
+pub struct RouteDecision {
+ pub selected_model: String,
+ pub confidence: f32,
+ pub provider_endpoint: Option<String>,
+ pub is_fallback: bool,
+ pub reasoning: String,
+}
+
+/// Parses a successful response from Laya /v1/systemone into a RouteDecision
+pub fn parse_laya_response(data: &serde_json::Value) -> Option<RouteDecision> {
+ let answers = data.get("answers")?;
+ let model_selection = answers.get("model_selection")?;
+ let choice = model_selection.get("choice")?.as_str()?;
+ let confidence = model_selection
+ .get("confidence")
+ .and_then(|v| v.as_f64())
+ .map(|f| f as f32)
+ .unwrap_or(0.9);
+
+ let provider_endpoint = if choice == "local_ollama" {
+ Some("http://localhost:11434/v1".to_string())
+ } else {
+ None
+ };
+
+ Some(RouteDecision {
+ selected_model: choice.to_string(),
+ confidence,
+ provider_endpoint,
+ is_fallback: false,
+ reasoning: format!("Laya decision router selected {}", choice),
+ })
+}
diff --git a/tests/router_test.rs b/tests/router_test.rs
new file mode 100644
index 00000000..74e96673
--- /dev/null
+++ b/tests/router_test.rs
@@ -0,0 +1,54 @@
+use kwnt::router::{parse_laya_response, LayaRouter};
+use serde_json::json;
+
+#[tokio::test]
+async fn test_offline_fallback_routing() {
+ // Port 59999 is intentionally offline
+ let router = LayaRouter::new("http://127.0.0.1:59999".into());
+ let decision = router
+ .route_prompt("Write a quick python script for sorting", "code")
+ .await
+ .unwrap();
+
+ assert!(decision.is_fallback);
+ assert!(!decision.selected_model.is_empty());
+ // For coding, fallback routes to codex or grok
+ assert!(decision.selected_model == "codex" || decision.selected_model == "grok");
+}
+
+#[tokio::test]
+async fn test_fallback_heuristic_variety() {
+ let router = LayaRouter::new("http://127.0.0.1:59999".into());
+
+ let arch_decision = router
+ .route_prompt("Analyze multi-region architecture tradeoffs and write a detailed design doc", "architecture")
+ .await
+ .unwrap();
+ assert_eq!(arch_decision.selected_model, "claude");
+
+ let privacy_decision = router
+ .route_prompt("Run private local query without sending to cloud, confidential data", "internal")
+ .await
+ .unwrap();
+ assert_eq!(privacy_decision.selected_model, "local_ollama");
+}
+
+#[test]
+fn test_parse_laya_success_response() {
+ let mock_json = json!({
+ "answers": {
+ "model_selection": {
+ "choice": "grok",
+ "confidence": 0.94
+ }
+ },
+ "routing": {
+ "model": "english"
+ }
+ });
+
+ let decision = parse_laya_response(&mock_json).unwrap();
+ assert_eq!(decision.selected_model, "grok");
+ assert_eq!(decision.confidence, 0.94);
+ assert!(!decision.is_fallback);
+}