Skip to main content

byob_types/
lib.rs

1//! Shared serde types used across every byob layer.
2#![cfg_attr(not(test), deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable))]
3
4pub mod chart;
5pub mod config;
6pub mod layout;
7pub mod profile;
8
9use serde::{Deserialize, Serialize};
10
11/// Who authored a chat message.
12#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
13#[serde(rename_all = "lowercase")]
14pub enum Role {
15    System,
16    User,
17    Assistant,
18    Tool,
19}
20
21/// A single chat message as sent to / received from the inference endpoint.
22#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
23pub struct Message {
24    pub role: Role,
25    pub content: String,
26}
27
28/// Which wire protocol an endpoint speaks.
29#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
30#[serde(rename_all = "lowercase")]
31pub enum ApiKind {
32    /// OpenAI chat completions (`POST {base}/chat/completions`): llama-server, vLLM,
33    /// Ollama, LM Studio, OpenAI, OpenRouter, ...
34    #[default]
35    #[serde(rename = "openai")]
36    OpenAi,
37    /// Anthropic's Messages API (`POST {base}/messages`), for Claude.
38    Anthropic,
39}
40
41/// Where and how to reach the model. Replaces hob's local llama.cpp setup.
42#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
43pub struct InferenceConfig {
44    /// Base URL of the API, e.g. `http://127.0.0.1:8080/v1`.
45    pub base_url: String,
46    /// Model name to request; many single-model servers ignore it.
47    pub model: String,
48    /// Optional API key (a bearer token, or Anthropic's `x-api-key`).
49    #[serde(default, skip_serializing_if = "Option::is_none")]
50    pub api_key: Option<String>,
51    /// The API the endpoint speaks; `None` decides from the URL ([`InferenceConfig::api_kind`]).
52    #[serde(default, skip_serializing_if = "Option::is_none")]
53    pub api: Option<ApiKind>,
54    /// Request options of the profile this endpoint came from (temperature, `max_tokens`,
55    /// effort, extra body fields): byob-llm adds them to every chat request made with it
56    /// (see `byob_llm::params`). Never to the probe's own requests.
57    #[serde(default, skip_serializing_if = "profile::Params::is_empty")]
58    pub params: profile::Params,
59    /// Context window to budget against, beating what the probe found (a profile's
60    /// [`profile::Profile::context`]).
61    #[serde(default, skip_serializing_if = "Option::is_none")]
62    pub context: Option<u32>,
63}
64
65impl Default for InferenceConfig {
66    fn default() -> Self {
67        Self {
68            base_url: "http://127.0.0.1:8080/v1".into(),
69            model: "default".into(),
70            api_key: None,
71            api: None,
72            params: profile::Params::default(),
73            context: None,
74        }
75    }
76}
77
78impl InferenceConfig {
79    /// The API to speak: the configured one, else Anthropic for `api.anthropic.com`, else OpenAI.
80    pub fn api_kind(&self) -> ApiKind {
81        self.api.unwrap_or_else(|| if url_host(&self.base_url).eq_ignore_ascii_case("api.anthropic.com") { ApiKind::Anthropic } else { ApiKind::OpenAi })
82    }
83
84    /// The same endpoint (URL, model, key, API), whatever the request options.
85    pub fn same_endpoint(&self, other: &Self) -> bool {
86        self.base_url == other.base_url && self.model == other.model && self.api_key == other.api_key && self.api == other.api
87    }
88}
89
90/// The host part of `url` (no scheme, user info, port or path); empty if there is none.
91fn url_host(url: &str) -> &str {
92    let rest = url.trim().split_once("://").map_or("", |(_, r)| r);
93    let authority = rest.split(['/', '?', '#']).next().unwrap_or_default();
94    let host = authority.rsplit_once('@').map_or(authority, |(_, h)| h);
95    host.split(':').next().unwrap_or_default().trim_end_matches('.')
96}
97
98#[cfg(test)]
99mod tests {
100    use super::*;
101
102    #[test]
103    fn role_serializes_lowercase() {
104        assert_eq!(serde_json::to_string(&Role::Assistant).unwrap(), "\"assistant\"");
105    }
106
107    #[test]
108    fn api_kind_is_set_or_follows_the_host() {
109        let at = |url: &str| InferenceConfig { base_url: url.into(), ..Default::default() }.api_kind();
110        assert_eq!(at("https://api.anthropic.com/v1"), ApiKind::Anthropic);
111        assert_eq!(at("https://API.Anthropic.com:443/v1/"), ApiKind::Anthropic);
112        assert_eq!(at("http://127.0.0.1:8080/v1"), ApiKind::OpenAi);
113        assert_eq!(at("https://api.anthropic.com.evil.example/v1"), ApiKind::OpenAi);
114        assert_eq!(at("https://proxy.example/?u=api.anthropic.com"), ApiKind::OpenAi);
115        assert_eq!(at("not a url"), ApiKind::OpenAi);
116        let set = InferenceConfig { base_url: "http://proxy:8080/v1".into(), api: Some(ApiKind::Anthropic), ..Default::default() };
117        assert_eq!(set.api_kind(), ApiKind::Anthropic);
118        let forced = InferenceConfig { base_url: "https://api.anthropic.com/v1".into(), api: Some(ApiKind::OpenAi), ..Default::default() };
119        assert_eq!(forced.api_kind(), ApiKind::OpenAi);
120        // Existing configs (no `api`) read and write as before.
121        let old: InferenceConfig = serde_json::from_str(r#"{"base_url":"http://h/v1","model":"m"}"#).unwrap();
122        assert_eq!(old.api, None);
123        assert_eq!(serde_json::to_string(&old).unwrap(), r#"{"base_url":"http://h/v1","model":"m"}"#);
124        assert_eq!(serde_json::to_string(&ApiKind::OpenAi).unwrap(), r#""openai""#);
125        assert_eq!(serde_json::from_str::<ApiKind>(r#""anthropic""#).unwrap(), ApiKind::Anthropic);
126    }
127}