capri-llm: add backend module

This commit is contained in:
nocode committed 2026-11-11 20:20:47 +01:00
1 parent a359a22228
commit 4688c4abf8
1 file changed
+126
+126
View File
@@ -0,0 +1,126 @@
//! The model backend the conversation engine talks to: managed local Ollama or an
//! OpenAI-compatible API (remote provider or Lemonade). Both consume the same [`Message`]s,
//! so switching between turns keeps the conversation.
use capri_core::Settings;
use serde_json::Value;
use crate::openai::OpenAi;
use crate::secrets::SecretStore;
use crate::sections::ApiSection;
use crate::{ChatDone, ChatRequest, LlmError, Ollama};
#[derive(Clone, Debug)]
pub enum LlmBackend {
Local(Ollama),
Api(OpenAi),
}
impl From<Ollama> for LlmBackend {
fn from(client: Ollama) -> Self {
Self::Local(client)
}
}
impl LlmBackend {
pub fn is_local(&self) -> bool {
matches!(self, Self::Local(_))
}
/// Loads the local model (no-op for APIs).
pub async fn load(&self, model: &str, keep_alive: i64) -> Result<(), LlmError> {
match self {
Self::Local(client) => client.load(model, keep_alive).await,
Self::Api(_) => Ok(()),
}
}
/// Streams one model call. For APIs `request.model` is replaced by the connection's model,
/// `think: Some(true)` selects one-turn reasoning and `options.num_predict` caps `max_tokens`.
pub async fn chat(&self, request: &ChatRequest, on_text: impl FnMut(&str)) -> Result<ChatDone, LlmError> {
match self {
Self::Local(client) => client.chat(request, on_text).await,
Self::Api(client) => client.chat(request, on_text).await,
}
}
/// Non-streamed JSON reply for auxiliary features; `schema = None` asks for any object.
pub async fn chat_json(&self, request: &ChatRequest, schema: Option<&Value>) -> Result<Value, LlmError> {
match self {
Self::Local(client) => client.chat_json(request, schema).await,
Self::Api(client) => client.chat_json(request, schema).await,
}
}
/// Capabilities of an API connection (`tools`, `vision`, `thinking`); `None` for local models
/// (ask `Ollama::show`).
pub fn api_capabilities(&self) -> Option<Vec<String>> {
let Self::Api(api) = self else { return None };
let c = &api.connection;
Some([("tools", c.tools), ("vision", c.vision), ("thinking", c.thinking)].iter().filter(|(_, on)| *on).map(|(n, _)| n.to_string()).collect())
}
/// Context window for compaction and history budgets.
pub fn context_tokens(&self, settings: &Settings) -> u32 {
match self {
Self::Local(_) => settings.context_tokens,
Self::Api(api) => api.connection.context_tokens,
}
}
/// Header label: `Local · <model>` or `API · <host> · <model>`.
pub fn label(&self, local_model: &str) -> String {
match self {
Self::Local(_) => format!("Local · {local_model}"),
Self::Api(api) => api.connection.label(),
}
}
/// Backend chosen in settings: the active API connection with its key, else the local client.
/// `Err` is a user-facing text; the app then shows `API · OFFLINE` and opens the API settings.
pub async fn from_settings(settings: &Settings, local: &Ollama, secrets: &SecretStore) -> Result<Self, String> {
let api: ApiSection = settings.section();
if !api.enabled {
return Ok(Self::Local(local.clone()));
}
let connection = api
.active_connection()
.cloned()
.ok_or("Select a saved API connection in Settings → External AI provider.")?
.validated()
.map_err(str::to_string)?;
let key = secrets.get(&connection.id, &connection.origin()).await.map_err(|_| "Saved API access could not be read. Save your API key again.")?;
if key.is_none() && !connection.is_local() {
return Err("Save an API key before enabling API inference.".into());
}
Ok(Self::Api(OpenAi::new(connection, key)))
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::openai::ApiConnection;
#[tokio::test]
async fn selection_from_settings() {
let dir = tempfile::tempdir().unwrap();
let secrets = SecretStore::file(dir.path().join("s.json"));
let local = Ollama::new("http://127.0.0.1:11435");
let mut settings = Settings::default();
assert!(LlmBackend::from_settings(&settings, &local, &secrets).await.unwrap().is_local());
let remote = ApiConnection { id: "r".into(), model: "m".into(), vision: true, ..Default::default() };
let lemonade = ApiConnection { id: "l".into(), base_url: "http://localhost:13305/api/v1".into(), model: "Qwen3-4B".into(), context_tokens: 8192, ..Default::default() };
settings.set_section(&ApiSection { enabled: true, active: Some("r".into()), connections: vec![remote.clone(), lemonade] });
assert_eq!(LlmBackend::from_settings(&settings, &local, &secrets).await.unwrap_err(), "Save an API key before enabling API inference.");
secrets.set("r", &remote.origin(), "sk-12345678").await.unwrap();
let backend = LlmBackend::from_settings(&settings, &local, &secrets).await.unwrap();
assert_eq!(backend.label("x"), "API · openrouter.ai · m");
assert_eq!(backend.api_capabilities().unwrap(), ["tools", "vision"]);
settings.set_section(&ApiSection { enabled: true, active: Some("l".into()), ..settings.section() });
let backend = LlmBackend::from_settings(&settings, &local, &secrets).await.unwrap();
assert!(!backend.is_local(), "keyless loopback connections need no key");
assert_eq!(backend.context_tokens(&settings), 8192);
}
}