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 👇

7.8 KB
Raw Blame
// ©AngelaMos | 2026
// api.rs

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

use lisdex_core::config::LlmTier;

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

pub const ENDPOINT_ENV: &str = "LISDEX_LLM_API_ENDPOINT";
pub const KEY_ENV: &str = "LISDEX_LLM_API_KEY";
pub const MODEL_ENV: &str = "LISDEX_LLM_API_MODEL";
pub const CHAT_PATH: &str = "/chat/completions";
pub const SCHEMA_NAME: &str = "lisdex_ballot";

pub struct ApiBooster {
    endpoint: Option<String>,
    key: Option<String>,
    model: Option<String>,
}

impl ApiBooster {
    #[must_use]
    pub fn new(endpoint: Option<String>, key: Option<String>, model: Option<String>) -> Self {
        Self {
            endpoint,
            key,
            model,
        }
    }

    #[must_use]
    pub fn from_env() -> Self {
        Self::new(
            std::env::var(ENDPOINT_ENV).ok(),
            std::env::var(KEY_ENV).ok(),
            std::env::var(MODEL_ENV).ok(),
        )
    }

    // The keyless doctrine puts this tier entirely outside the default path: it is configured or
    // it declines, and declining is never an error. Nothing the tool does for its own sake may
    // depend on a key existing.
    fn configured(&self) -> Result<(&str, &str, &str), Declined> {
        let missing: Vec<&str> = [
            (ENDPOINT_ENV, self.endpoint.is_none()),
            (KEY_ENV, self.key.is_none()),
            (MODEL_ENV, self.model.is_none()),
        ]
        .into_iter()
        .filter_map(|(name, absent)| absent.then_some(name))
        .collect();
        if !missing.is_empty() {
            return Err(Declined::BackendUnavailable {
                detail: format!(
                    "the api tier is not configured; set {}. The local and none tiers need no key",
                    missing.join(", ")
                ),
            });
        }
        match (
            self.endpoint.as_deref(),
            self.key.as_deref(),
            self.model.as_deref(),
        ) {
            (Some(endpoint), Some(key), Some(model)) => Ok((endpoint, key, model)),
            _ => Err(Declined::BackendUnavailable {
                detail: "the api tier is not configured".to_owned(),
            }),
        }
    }
}

impl Booster for ApiBooster {
    fn propose(&self, ask: &Ask) -> Outcome {
        let (endpoint, key, model) = match self.configured() {
            Ok(parts) => parts,
            Err(declined) => return Outcome::Declined(declined),
        };
        let agent = wire::agent(Duration::from_secs(PROMPT_TIMEOUT_SECS));
        let url = format!("{endpoint}{CHAT_PATH}");
        let request = serde_json::json!({
            "model": model,
            "temperature": 0,
            "messages": [{ "role": "user", "content": wire::prompt(ask) }],
            "response_format": {
                "type": "json_schema",
                "json_schema": {
                    "name": SCHEMA_NAME,
                    "strict": true,
                    "schema": wire::schema(ask.ballot()),
                }
            },
        });
        let started = Instant::now();
        let body = match wire::post(&agent, &url, &request, Some(key)) {
            Ok(body) => body,
            Err(failure) => {
                return Outcome::Declined(Declined::BackendUnavailable {
                    detail: failure.to_string(),
                });
            }
        };
        let elapsed = started.elapsed();
        let raw = body
            .get("choices")
            .and_then(serde_json::Value::as_array)
            .and_then(|choices| choices.first())
            .and_then(|choice| choice.get("message"))
            .and_then(|message| message.get("content"))
            .and_then(serde_json::Value::as_str);
        let Some(raw) = raw else {
            return Outcome::Declined(Declined::BackendUnavailable {
                detail: format!("{url} answered JSON with no choices[0].message.content"),
            });
        };
        match ballot::adjudicate(ask.ballot(), raw) {
            Ok(choice) => Outcome::Proposed(Proposal {
                choice,
                tier: LlmTier::Api,
                model: model.to_owned(),
                elapsed,
            }),
            Err(declined) => Outcome::Declined(declined),
        }
    }

    fn describe(&self) -> String {
        match (self.endpoint.as_deref(), self.model.as_deref()) {
            (Some(endpoint), Some(model)) if self.key.is_some() => {
                format!("api ({model} at {endpoint})")
            }
            _ => "api (not configured)".to_owned(),
        }
    }
}

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

    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")
    }

    #[test]
    fn an_unconfigured_api_tier_declines_and_names_every_missing_variable() {
        let booster = ApiBooster::new(None, None, None);
        let Outcome::Declined(Declined::BackendUnavailable { detail }) = booster.propose(&ask())
        else {
            panic!("an unconfigured api tier did not decline gracefully");
        };
        for name in [ENDPOINT_ENV, KEY_ENV, MODEL_ENV] {
            assert!(detail.contains(name), "{name} not named in: {detail}");
        }
    }

    #[test]
    fn a_partly_configured_api_tier_names_only_what_is_missing() {
        let booster = ApiBooster::new(
            Some("https://example.invalid/v1".to_owned()),
            None,
            Some("some-model".to_owned()),
        );
        let Outcome::Declined(Declined::BackendUnavailable { detail }) = booster.propose(&ask())
        else {
            panic!("a partly configured api tier did not decline gracefully");
        };
        assert!(detail.contains(KEY_ENV), "{detail}");
        assert!(!detail.contains(ENDPOINT_ENV), "{detail}");
        assert!(!detail.contains(MODEL_ENV), "{detail}");
    }

    // The doctrine, asserted rather than described: an unconfigured optional tier must point the
    // user at the tiers that need nothing, never at a signup page.
    #[test]
    fn the_unconfigured_reason_points_at_the_keyless_tiers() {
        let booster = ApiBooster::new(None, None, None);
        let Outcome::Declined(Declined::BackendUnavailable { detail }) = booster.propose(&ask())
        else {
            panic!("an unconfigured api tier did not decline gracefully");
        };
        assert!(
            detail.contains("local") && detail.contains("none"),
            "the remedy does not mention the keyless tiers: {detail}"
        );
    }

    #[test]
    fn an_unconfigured_api_tier_describes_itself_as_unconfigured() {
        assert_eq!(
            ApiBooster::new(None, None, None).describe(),
            "api (not configured)"
        );
    }

    #[test]
    fn a_fully_configured_api_tier_describes_its_model_and_endpoint() {
        let booster = ApiBooster::new(
            Some("https://example.invalid/v1".to_owned()),
            Some("secret".to_owned()),
            Some("some-model".to_owned()),
        );
        let described = booster.describe();
        assert!(described.contains("some-model"), "{described}");
        assert!(
            described.contains("https://example.invalid/v1"),
            "{described}"
        );
    }

    // A description is printed in run reports. A key that reaches a report reaches a paste.
    #[test]
    fn the_description_never_carries_the_key() {
        let booster = ApiBooster::new(
            Some("https://example.invalid/v1".to_owned()),
            Some("sk-do-not-print-me".to_owned()),
            Some("some-model".to_owned()),
        );
        assert!(!booster.describe().contains("sk-do-not-print-me"));
    }
}