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