use serde::{Deserialize, Serialize};
use crate::interface::model::Effort;
mod quota;
mod routing;
pub use quota::{PeriodUsage, QuotaLedger, QuotaStatus};
pub use routing::{Destination, ProviderSwitch, RouteObserver, TaskRouting};
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize, schemars::JsonSchema)]
pub enum ApiType {
#[serde(rename = "anthropic")]
Anthropic,
#[serde(rename = "openai_chat")]
OpenAIChat,
#[serde(rename = "openai_responses")]
OpenAIResponses,
}
#[derive(
Debug, Clone, Copy, Default, PartialEq, Eq, Hash, Serialize, Deserialize, schemars::JsonSchema,
)]
#[serde(rename_all = "snake_case")]
pub enum Vendor {
Anthropic,
Openai,
Deepseek,
Qwen,
Vllm,
Sglang,
#[default]
Generic,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ThinkingToggle {
Deepseek,
EnableThinking,
ChatTemplateKwargs,
}
impl Vendor {
pub fn thinking_toggle(self) -> Option<ThinkingToggle> {
match self {
Self::Deepseek => Some(ThinkingToggle::Deepseek),
Self::Qwen => Some(ThinkingToggle::EnableThinking),
Self::Vllm | Self::Sglang => Some(ThinkingToggle::ChatTemplateKwargs),
Self::Anthropic | Self::Openai | Self::Generic => None,
}
}
pub fn passes_reasoning_back(self) -> bool {
self == Self::Deepseek
}
pub fn effort(self, effort: Effort) -> Effort {
match (self, effort) {
(Self::Deepseek, Effort::Medium | Effort::Xhigh) => Effort::High,
(_, effort) => effort,
}
}
}
#[derive(
Debug,
Clone,
Copy,
PartialEq,
Eq,
Hash,
PartialOrd,
Ord,
Serialize,
Deserialize,
schemars::JsonSchema,
)]
#[serde(rename_all = "snake_case")]
pub enum Tier {
Strong,
Balanced,
Fast,
}
impl Tier {
pub const ALL: [Tier; 3] = [Tier::Strong, Tier::Balanced, Tier::Fast];
pub fn as_str(self) -> &'static str {
match self {
Self::Strong => "strong",
Self::Balanced => "balanced",
Self::Fast => "fast",
}
}
pub fn from_name(name: &str) -> Option<Tier> {
Self::ALL.into_iter().find(|tier| tier.as_str() == name)
}
pub fn from_claude_alias(name: &str) -> Option<Tier> {
match name {
"opus" => Some(Self::Strong),
"sonnet" => Some(Self::Balanced),
"haiku" => Some(Self::Fast),
_ => None,
}
}
}
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
#[serde(default, deny_unknown_fields)]
pub struct Tiers {
#[serde(skip_serializing_if = "Option::is_none")]
pub strong: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub balanced: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub fast: Option<String>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ResolvedTiers {
pub strong: String,
pub balanced: String,
pub fast: String,
}
impl ResolvedTiers {
pub fn all(model: &str) -> Self {
Self {
strong: model.to_string(),
balanced: model.to_string(),
fast: model.to_string(),
}
}
pub fn get(&self, tier: Tier) -> &str {
match tier {
Tier::Strong => &self.strong,
Tier::Balanced => &self.balanced,
Tier::Fast => &self.fast,
}
}
pub fn tier_of(&self, model: &str, prefer: Tier) -> Option<Tier> {
if self.get(prefer) == model {
return Some(prefer);
}
Tier::ALL.into_iter().find(|tier| self.get(*tier) == model)
}
pub fn contains(&self, model: &str) -> bool {
Tier::ALL.into_iter().any(|tier| self.get(tier) == model)
}
}
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
#[serde(default, deny_unknown_fields)]
pub struct Quota {
#[serde(skip_serializing_if = "Option::is_none")]
pub day: Option<u64>,
#[serde(skip_serializing_if = "Option::is_none")]
pub week: Option<u64>,
#[serde(skip_serializing_if = "Option::is_none")]
pub month: Option<u64>,
}
impl Quota {
pub fn is_unlimited(&self) -> bool {
self.day.is_none() && self.week.is_none() && self.month.is_none()
}
}
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize, schemars::JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct ProviderConfig {
#[schemars(pattern(r"^[a-z0-9_-]+$"))]
pub id: String,
#[serde(default)]
pub vendor: Vendor,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub api: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub base_url: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub api_key_env: Option<String>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub models: Vec<ModelEntry>,
#[serde(default)]
pub tiers: Tiers,
#[serde(default, skip_serializing_if = "Quota::is_unlimited")]
pub quota: Quota,
#[serde(skip)]
#[schemars(skip)]
pub builtin: bool,
}
#[derive(Debug, Clone, PartialEq, Serialize, schemars::JsonSchema)]
#[serde(untagged)]
#[non_exhaustive]
pub enum ModelEntry {
Id(String),
Spec(ModelSpec),
}
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize, schemars::JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct ModelSpec {
pub id: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub context_window: Option<u64>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub max_output: Option<u32>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub reasoning_levels: Option<Vec<String>>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub input_types: Option<Vec<String>>,
}
impl ModelEntry {
pub fn id(&self) -> &str {
match self {
Self::Id(id) => id,
Self::Spec(spec) => &spec.id,
}
}
pub fn spec(&self) -> Option<&ModelSpec> {
match self {
Self::Id(_) => None,
Self::Spec(spec) => Some(spec),
}
}
}
impl From<&str> for ModelEntry {
fn from(id: &str) -> Self {
Self::Id(id.to_string())
}
}
impl From<String> for ModelEntry {
fn from(id: String) -> Self {
Self::Id(id)
}
}
impl<'de> Deserialize<'de> for ModelEntry {
fn deserialize<D: serde::Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
use serde::de::Error;
match serde_json::Value::deserialize(d)? {
serde_json::Value::String(id) => Ok(Self::Id(id)),
object @ serde_json::Value::Object(_) => serde_json::from_value(object)
.map(Self::Spec)
.map_err(|e| D::Error::custom(format!("a model entry: {e}"))),
_ => Err(D::Error::custom(
"a model entry is an id string or an object with `id`",
)),
}
}
}
impl ProviderConfig {
pub const BUILTIN_ID: &'static str = "anthropic";
pub fn builtin(model: &str) -> Self {
Self {
id: Self::BUILTIN_ID.to_string(),
vendor: Vendor::Anthropic,
api: Some("anthropic".to_string()),
tiers: Tiers {
strong: Some(model.to_string()),
balanced: None,
fast: None,
},
builtin: true,
..Default::default()
}
}
pub fn id_problem(id: &str) -> Option<String> {
if id.is_empty() {
return Some("a provider needs an `id`".to_string());
}
let fits = id
.bytes()
.all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-' || b == b'_');
(!fits).then(|| {
format!("provider id `{id}` may hold only lowercase ASCII letters, digits, `-` and `_`")
})
}
pub fn api(&self) -> &str {
self.api.as_deref().unwrap_or("anthropic")
}
pub fn accepts_model(&self, model: &str) -> bool {
self.models.is_empty() || self.models.iter().any(|m| m.id() == model)
}
pub fn lists_model(&self, model: &str) -> bool {
self.models.iter().any(|m| m.id() == model)
}
pub fn model_ids(&self) -> Vec<&str> {
self.models.iter().map(ModelEntry::id).collect()
}
pub fn model_spec(&self, model: &str) -> Option<&ModelSpec> {
self.models
.iter()
.find(|m| m.id() == model)
.and_then(ModelEntry::spec)
}
pub fn resolved_tiers(&self) -> Result<ResolvedTiers, String> {
let id = &self.id;
let strong = self
.tiers
.strong
.clone()
.filter(|m| !m.is_empty())
.ok_or_else(|| format!("provider `{id}` has no `tiers.strong`"))?;
let balanced = self
.tiers
.balanced
.clone()
.unwrap_or_else(|| strong.clone());
let fast = self.tiers.fast.clone().unwrap_or_else(|| balanced.clone());
let resolved = ResolvedTiers {
strong,
balanced,
fast,
};
if !self.models.is_empty() {
for tier in Tier::ALL {
let model = resolved.get(tier);
if !self.lists_model(model) {
return Err(format!(
"provider `{id}`: `tiers.{}` is `{model}`, which is not in its `models`",
tier.as_str()
));
}
}
}
Ok(resolved)
}
}
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize, schemars::JsonSchema)]
pub struct ListedModel {
pub id: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub display_name: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub context_window: Option<u64>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub max_output: Option<u32>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub input_types: Option<Vec<String>>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub reasoning: Option<bool>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
#[serde(default, deny_unknown_fields)]
pub struct TaskTiers {
pub main: Tier,
pub subagent: Tier,
pub compact: Tier,
pub memory: Tier,
pub title: Tier,
pub web_search: Tier,
#[serde(skip_serializing_if = "Option::is_none")]
pub web_fetch: Option<Tier>,
}
impl Default for TaskTiers {
fn default() -> Self {
Self {
main: Tier::Strong,
subagent: Tier::Balanced,
compact: Tier::Fast,
memory: Tier::Fast,
title: Tier::Fast,
web_search: Tier::Fast,
web_fetch: None,
}
}
}
impl TaskTiers {
pub const MAIN: &'static str = "main";
pub const SUBAGENT: &'static str = "subagent";
pub const COMPACT: &'static str = "compact";
pub const MEMORY: &'static str = "memory";
pub const TITLE: &'static str = "title";
pub const WEB_SEARCH: &'static str = "web_search";
pub const WEB_FETCH: &'static str = "web_fetch";
pub fn get(&self, task: &str) -> Option<Tier> {
match task {
Self::MAIN => Some(self.main),
Self::SUBAGENT => Some(self.subagent),
Self::COMPACT => Some(self.compact),
Self::MEMORY => Some(self.memory),
Self::TITLE => Some(self.title),
Self::WEB_SEARCH => Some(self.web_search),
Self::WEB_FETCH => self.web_fetch,
_ => None,
}
}
}
pub fn routing_order<'a>(
providers: &'a [ProviderConfig],
order: &[String],
) -> Result<Vec<(&'a ProviderConfig, ResolvedTiers)>, String> {
let mut resolved = Vec::with_capacity(providers.len());
for provider in providers {
if let Some(problem) = ProviderConfig::id_problem(&provider.id) {
return Err(problem);
}
resolved.push((provider, provider.resolved_tiers()?));
}
let Some(first) = providers.first() else {
return Err("no provider is defined".to_string());
};
let order: Vec<&str> = match order.is_empty() {
true => vec![first.id.as_str()],
false => order.iter().map(String::as_str).collect(),
};
let mut out: Vec<(&ProviderConfig, ResolvedTiers)> = Vec::with_capacity(order.len());
for id in order {
if out.iter().any(|(p, _)| p.id == id) {
continue;
}
let Some((provider, tiers)) = resolved.iter().find(|(p, _)| p.id == id) else {
return Err(format!(
"`model.order` names provider `{id}`, which no `providers` entry defines"
));
};
out.push((provider, tiers.clone()));
}
Ok(out)
}
#[cfg(test)]
mod tests;