Skip to content

Building 70 Projects ranging from beginner to advanced so anyone can — learn from, build upon, use as a reference, or even copy directly. Owned by my cybersecurity company 👇

10.4 KB
Raw Blame
// ©AngelaMos | 2026
// local.rs

use std::time::{Duration, Instant};

use lisdex_core::config::LlmTier;

use crate::ballot::{self, Declined};
use crate::wire::{self, PROBE_TIMEOUT_SECS, PROMPT_TIMEOUT_SECS};
use crate::{Ask, Booster, Outcome, Proposal};

pub const DEFAULT_ENDPOINT: &str = "http://127.0.0.1:11434";
pub const DEFAULT_MODEL: &str = "qwen2.5-coder:14b-instruct-q6_K";
pub const ENDPOINT_ENV: &str = "LISDEX_LLM_ENDPOINT";
pub const MODEL_ENV: &str = "LISDEX_LLM_MODEL";
pub const GENERATE_PATH: &str = "/api/generate";
pub const TAGS_PATH: &str = "/api/tags";
pub const RESPONSE_FIELD: &str = "response";
pub const THINKING_FIELD: &str = "thinking";
pub const MODELS_FIELD: &str = "models";
pub const NAME_FIELD: &str = "name";

// Measured 2026-08-05 against a live daemon: a REASONING model returns an empty `response` and
// puts the schema-constrained object in `thinking` instead. `qwen3.5-abliterated:9b` answered
// `{"choice": "byte_buffer"}` there - the correct answer, and the one the 3b model got wrong -
// while `response` was the empty string, so reading only `response` discarded a right answer and
// reported it as "the model returned nothing". Adjudication stays strict over both fields, so a
// model that merely reasons ABOUT an option in prose is still refused as off-ballot.
fn answer_of(body: &serde_json::Value) -> Option<&str> {
    let response = body.get(RESPONSE_FIELD).and_then(serde_json::Value::as_str);
    if let Some(text) = response
        && !text.trim().is_empty()
    {
        return Some(text);
    }
    let thinking = body.get(THINKING_FIELD).and_then(serde_json::Value::as_str);
    match thinking {
        Some(text) if !text.trim().is_empty() => Some(text),
        _ => response.or(thinking),
    }
}

pub struct LocalBooster {
    endpoint: String,
    model: String,
}

impl LocalBooster {
    #[must_use]
    pub fn new(endpoint: impl Into<String>, model: impl Into<String>) -> Self {
        Self {
            endpoint: endpoint.into(),
            model: model.into(),
        }
    }

    #[must_use]
    pub fn from_env() -> Self {
        Self::new(
            std::env::var(ENDPOINT_ENV).unwrap_or_else(|_| DEFAULT_ENDPOINT.to_owned()),
            std::env::var(MODEL_ENV).unwrap_or_else(|_| DEFAULT_MODEL.to_owned()),
        )
    }

    #[must_use]
    pub fn endpoint(&self) -> &str {
        &self.endpoint
    }

    #[must_use]
    pub fn model(&self) -> &str {
        &self.model
    }

    fn installed_models(&self) -> Result<Vec<String>, wire::WireError> {
        let agent = wire::agent(Duration::from_secs(PROBE_TIMEOUT_SECS));
        let url = format!("{}{TAGS_PATH}", self.endpoint);
        let body = wire::get(&agent, &url)?;
        let listed = body
            .get(MODELS_FIELD)
            .and_then(serde_json::Value::as_array)
            .ok_or_else(|| wire::WireError::MissingField {
                url,
                field: MODELS_FIELD.to_owned(),
            })?;
        Ok(listed
            .iter()
            .filter_map(|entry| entry.get(NAME_FIELD).and_then(serde_json::Value::as_str))
            .map(ToOwned::to_owned)
            .collect())
    }

    // Only reached once a request has already failed, so the extra round trip costs nothing in
    // the happy path and buys the difference between "start the daemon" and "pull the model",
    // which are the two failures a user can actually act on.
    fn why_unavailable(&self, failure: &wire::WireError) -> Declined {
        match self.installed_models() {
            Err(_) => Declined::BackendUnavailable {
                detail: format!(
                    "no model runtime answered at {} ({failure}); start one, or point {ENDPOINT_ENV} at one, or run with the `none` tier",
                    self.endpoint
                ),
            },
            Ok(installed) if !installed.iter().any(|name| name == &self.model) => {
                Declined::BackendUnavailable {
                    detail: format!(
                        "{} is reachable but does not have {}; install it or set {MODEL_ENV} to one of: {}",
                        self.endpoint,
                        self.model,
                        if installed.is_empty() {
                            "(nothing installed)".to_owned()
                        } else {
                            installed.join(", ")
                        }
                    ),
                }
            }
            Ok(_) => Declined::BackendUnavailable {
                detail: format!(
                    "{} has {} but the request failed: {failure}",
                    self.endpoint, self.model
                ),
            },
        }
    }
}

impl Booster for LocalBooster {
    fn propose(&self, ask: &Ask) -> Outcome {
        let agent = wire::agent(Duration::from_secs(PROMPT_TIMEOUT_SECS));
        let url = format!("{}{GENERATE_PATH}", self.endpoint);
        let request = serde_json::json!({
            "model": self.model,
            "prompt": wire::prompt(ask),
            "stream": false,
            "format": wire::schema(ask.ballot()),
            "options": { "temperature": 0 },
        });
        let started = Instant::now();
        let body = match wire::post(&agent, &url, &request, None) {
            Ok(body) => body,
            Err(failure) => return Outcome::Declined(self.why_unavailable(&failure)),
        };
        let elapsed = started.elapsed();
        let Some(raw) = answer_of(&body) else {
            return Outcome::Declined(Declined::BackendUnavailable {
                detail: format!(
                    "{url} answered JSON with neither a {RESPONSE_FIELD} nor a {THINKING_FIELD} field"
                ),
            });
        };
        match ballot::adjudicate(ask.ballot(), raw) {
            Ok(choice) => Outcome::Proposed(Proposal {
                choice,
                tier: LlmTier::Local,
                model: self.model.clone(),
                elapsed,
            }),
            Err(declined) => Outcome::Declined(declined),
        }
    }

    fn describe(&self) -> String {
        format!("local ({} at {})", self.model, self.endpoint)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    // Port 1 is reserved and nothing listens on it, so this is a connection refusal rather than a
    // timeout and the test stays fast.
    const CLOSED: &str = "http://127.0.0.1:1";

    fn ask() -> Ask {
        Ask::new(
            "is src a byte buffer or a string",
            "int LZ4_decompress_safe(const char *src, char *dst, int n, int max);",
            vec!["byte_buffer".to_owned(), "nul_terminated_string".to_owned()],
        )
        .expect("valid ask")
    }

    // The deliverable the design names: with no model runtime present the tool keeps working and
    // says why, rather than erroring out and taking the deterministic pipeline down with it.
    #[test]
    fn an_absent_runtime_declines_gracefully_and_names_the_remedy() {
        let booster = LocalBooster::new(CLOSED, DEFAULT_MODEL);
        let outcome = booster.propose(&ask());
        let Outcome::Declined(Declined::BackendUnavailable { detail }) = outcome else {
            panic!("an absent runtime did not decline gracefully: {outcome:?}");
        };
        assert!(
            detail.contains(CLOSED),
            "the reason hides the endpoint: {detail}"
        );
        assert!(
            detail.contains(ENDPOINT_ENV) || detail.contains("none"),
            "the reason offers no remedy: {detail}"
        );
    }

    #[test]
    fn an_absent_runtime_never_proposes_anything() {
        let booster = LocalBooster::new(CLOSED, DEFAULT_MODEL);
        assert!(booster.propose(&ask()).proposal().is_none());
    }

    #[test]
    fn a_plain_model_is_read_from_the_response_field() {
        let body = serde_json::json!({ "response": "{\"choice\":\"byte_buffer\"}" });
        assert_eq!(answer_of(&body), Some("{\"choice\":\"byte_buffer\"}"));
    }

    // The reproduction of the 2026-08-05 measurement: an empty `response` beside a populated
    // `thinking` must yield the thinking text, or a reasoning model can never answer at all.
    #[test]
    fn a_reasoning_model_is_read_from_the_thinking_field_when_response_is_empty() {
        let body = serde_json::json!({
            "response": "",
            "thinking": "{\"choice\": \"byte_buffer\"}",
        });
        assert_eq!(answer_of(&body), Some("{\"choice\": \"byte_buffer\"}"));
    }

    // The negative control for the fallback: `response` WINS when it has content, so a model that
    // answers normally is never adjudicated on its chain of thought.
    #[test]
    fn a_populated_response_beats_the_thinking_field() {
        let body = serde_json::json!({
            "response": "nul_terminated_string",
            "thinking": "byte_buffer",
        });
        assert_eq!(answer_of(&body), Some("nul_terminated_string"));
    }

    #[test]
    fn a_body_with_neither_field_yields_nothing() {
        assert_eq!(answer_of(&serde_json::json!({ "done": true })), None);
    }

    // Reading `thinking` must not become a licence to accept reasoning prose. The strict
    // adjudicator is what keeps the fallback safe, so it is asserted here and not assumed.
    #[test]
    fn reasoning_prose_that_merely_mentions_an_option_is_still_refused() {
        let ballot = vec!["byte_buffer".to_owned(), "nul_terminated_string".to_owned()];
        let body = serde_json::json!({
            "response": "",
            "thinking": "Hmm, byte_buffer seems plausible, but let me reconsider.",
        });
        let raw = answer_of(&body).expect("thinking is present");
        assert!(
            matches!(
                ballot::adjudicate(&ballot, raw),
                Err(Declined::OffBallot { .. })
            ),
            "reasoning prose was accepted as a choice"
        );
    }

    #[test]
    fn the_defaults_are_the_pinned_model_on_the_loopback_runtime() {
        let booster = LocalBooster::new(DEFAULT_ENDPOINT, DEFAULT_MODEL);
        assert_eq!(booster.endpoint(), DEFAULT_ENDPOINT);
        assert_eq!(booster.model(), DEFAULT_MODEL);
        assert!(booster.describe().contains(DEFAULT_MODEL));
    }

    #[test]
    fn the_description_names_both_the_model_and_where_it_is_expected() {
        let booster = LocalBooster::new("http://example.invalid:9", "some-model");
        let described = booster.describe();
        assert!(described.contains("some-model"), "{described}");
        assert!(
            described.contains("http://example.invalid:9"),
            "{described}"
        );
    }
}