1use serde::{Deserialize, Serialize};
12
13use crate::interface::model::Effort;
14
15mod quota;
16mod routing;
17
18pub use quota::{PeriodUsage, QuotaLedger, QuotaStatus};
19pub use routing::{Destination, ProviderSwitch, RouteObserver, TaskRouting};
20
21#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize, schemars::JsonSchema)]
23pub enum ApiType {
24 #[serde(rename = "anthropic")]
25 Anthropic,
26 #[serde(rename = "openai_chat")]
27 OpenAIChat,
28 #[serde(rename = "openai_responses")]
29 OpenAIResponses,
30}
31
32#[derive(
35 Debug, Clone, Copy, Default, PartialEq, Eq, Hash, Serialize, Deserialize, schemars::JsonSchema,
36)]
37#[serde(rename_all = "snake_case")]
38pub enum Vendor {
39 Anthropic,
40 Openai,
41 Deepseek,
42 Qwen,
43 Vllm,
44 Sglang,
45 #[default]
46 Generic,
47}
48
49#[derive(Debug, Clone, Copy, PartialEq, Eq)]
51pub enum ThinkingToggle {
52 Deepseek,
54 EnableThinking,
56 ChatTemplateKwargs,
58}
59
60impl Vendor {
61 pub fn thinking_toggle(self) -> Option<ThinkingToggle> {
62 match self {
63 Self::Deepseek => Some(ThinkingToggle::Deepseek),
64 Self::Qwen => Some(ThinkingToggle::EnableThinking),
65 Self::Vllm | Self::Sglang => Some(ThinkingToggle::ChatTemplateKwargs),
66 Self::Anthropic | Self::Openai | Self::Generic => None,
67 }
68 }
69
70 pub fn passes_reasoning_back(self) -> bool {
73 self == Self::Deepseek
74 }
75
76 pub fn effort(self, effort: Effort) -> Effort {
78 match (self, effort) {
79 (Self::Deepseek, Effort::Medium | Effort::Xhigh) => Effort::High,
80 (_, effort) => effort,
81 }
82 }
83}
84
85#[derive(
88 Debug,
89 Clone,
90 Copy,
91 PartialEq,
92 Eq,
93 Hash,
94 PartialOrd,
95 Ord,
96 Serialize,
97 Deserialize,
98 schemars::JsonSchema,
99)]
100#[serde(rename_all = "snake_case")]
101pub enum Tier {
102 Strong,
103 Balanced,
104 Fast,
105}
106
107impl Tier {
108 pub const ALL: [Tier; 3] = [Tier::Strong, Tier::Balanced, Tier::Fast];
109
110 pub fn as_str(self) -> &'static str {
111 match self {
112 Self::Strong => "strong",
113 Self::Balanced => "balanced",
114 Self::Fast => "fast",
115 }
116 }
117
118 pub fn from_name(name: &str) -> Option<Tier> {
119 Self::ALL.into_iter().find(|tier| tier.as_str() == name)
120 }
121
122 pub fn from_claude_alias(name: &str) -> Option<Tier> {
124 match name {
125 "opus" => Some(Self::Strong),
126 "sonnet" => Some(Self::Balanced),
127 "haiku" => Some(Self::Fast),
128 _ => None,
129 }
130 }
131}
132
133#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
135#[serde(default, deny_unknown_fields)]
136pub struct Tiers {
137 #[serde(skip_serializing_if = "Option::is_none")]
139 pub strong: Option<String>,
140 #[serde(skip_serializing_if = "Option::is_none")]
142 pub balanced: Option<String>,
143 #[serde(skip_serializing_if = "Option::is_none")]
145 pub fast: Option<String>,
146}
147
148#[derive(Debug, Clone, PartialEq, Eq)]
150pub struct ResolvedTiers {
151 pub strong: String,
152 pub balanced: String,
153 pub fast: String,
154}
155
156impl ResolvedTiers {
157 pub fn all(model: &str) -> Self {
158 Self {
159 strong: model.to_string(),
160 balanced: model.to_string(),
161 fast: model.to_string(),
162 }
163 }
164
165 pub fn get(&self, tier: Tier) -> &str {
166 match tier {
167 Tier::Strong => &self.strong,
168 Tier::Balanced => &self.balanced,
169 Tier::Fast => &self.fast,
170 }
171 }
172
173 pub fn tier_of(&self, model: &str, prefer: Tier) -> Option<Tier> {
176 if self.get(prefer) == model {
177 return Some(prefer);
178 }
179 Tier::ALL.into_iter().find(|tier| self.get(*tier) == model)
180 }
181
182 pub fn contains(&self, model: &str) -> bool {
183 Tier::ALL.into_iter().any(|tier| self.get(tier) == model)
184 }
185}
186
187#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
190#[serde(default, deny_unknown_fields)]
191pub struct Quota {
192 #[serde(skip_serializing_if = "Option::is_none")]
194 pub day: Option<u64>,
195 #[serde(skip_serializing_if = "Option::is_none")]
197 pub week: Option<u64>,
198 #[serde(skip_serializing_if = "Option::is_none")]
200 pub month: Option<u64>,
201}
202
203impl Quota {
204 pub fn is_unlimited(&self) -> bool {
205 self.day.is_none() && self.week.is_none() && self.month.is_none()
206 }
207}
208
209#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize, schemars::JsonSchema)]
211#[serde(deny_unknown_fields)]
212pub struct ProviderConfig {
213 #[schemars(pattern(r"^[a-z0-9_-]+$"))]
218 pub id: String,
219 #[serde(default)]
223 pub vendor: Vendor,
224 #[serde(default, skip_serializing_if = "Option::is_none")]
227 pub api: Option<String>,
228 #[serde(default, skip_serializing_if = "Option::is_none")]
231 pub base_url: Option<String>,
232 #[serde(default, skip_serializing_if = "Option::is_none")]
236 pub api_key_env: Option<String>,
237 #[serde(default, skip_serializing_if = "ProviderAuth::is_key")]
241 pub auth: ProviderAuth,
242 #[serde(default, skip_serializing_if = "Vec::is_empty")]
246 pub models: Vec<ModelEntry>,
247 #[serde(default)]
251 pub tiers: Tiers,
252 #[serde(default, skip_serializing_if = "Quota::is_unlimited")]
255 pub quota: Quota,
256 #[serde(skip)]
258 #[schemars(skip)]
259 pub builtin: bool,
260}
261
262#[derive(
264 Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema,
265)]
266#[serde(rename_all = "lowercase")]
267#[non_exhaustive]
268pub enum ProviderAuth {
269 #[default]
271 Key,
272 Host,
274}
275
276impl ProviderAuth {
277 pub fn is_key(&self) -> bool {
278 *self == Self::Key
279 }
280}
281
282#[derive(Debug, Clone, PartialEq, Serialize, schemars::JsonSchema)]
284#[serde(untagged)]
285#[non_exhaustive]
286pub enum ModelEntry {
287 Id(String),
288 Spec(ModelSpec),
289}
290
291#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize, schemars::JsonSchema)]
297#[serde(deny_unknown_fields)]
298pub struct ModelSpec {
299 pub id: String,
300 #[serde(default, skip_serializing_if = "Option::is_none")]
301 pub context_window: Option<u64>,
302 #[serde(default, skip_serializing_if = "Option::is_none")]
306 pub max_output: Option<u32>,
307 #[serde(default, skip_serializing_if = "Option::is_none")]
308 pub reasoning_levels: Option<Vec<String>>,
309 #[serde(default, skip_serializing_if = "Option::is_none")]
310 pub input_types: Option<Vec<String>>,
311}
312
313impl ModelEntry {
314 pub fn id(&self) -> &str {
315 match self {
316 Self::Id(id) => id,
317 Self::Spec(spec) => &spec.id,
318 }
319 }
320
321 pub fn spec(&self) -> Option<&ModelSpec> {
322 match self {
323 Self::Id(_) => None,
324 Self::Spec(spec) => Some(spec),
325 }
326 }
327}
328
329impl From<&str> for ModelEntry {
330 fn from(id: &str) -> Self {
331 Self::Id(id.to_string())
332 }
333}
334
335impl From<String> for ModelEntry {
336 fn from(id: String) -> Self {
337 Self::Id(id)
338 }
339}
340
341impl<'de> Deserialize<'de> for ModelEntry {
344 fn deserialize<D: serde::Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
345 use serde::de::Error;
346 match serde_json::Value::deserialize(d)? {
347 serde_json::Value::String(id) => Ok(Self::Id(id)),
348 object @ serde_json::Value::Object(_) => serde_json::from_value(object)
349 .map(Self::Spec)
350 .map_err(|e| D::Error::custom(format!("a model entry: {e}"))),
351 _ => Err(D::Error::custom(
352 "a model entry is an id string or an object with `id`",
353 )),
354 }
355 }
356}
357
358impl ProviderConfig {
359 pub const BUILTIN_ID: &'static str = "anthropic";
362
363 pub fn builtin(model: &str) -> Self {
366 Self {
367 id: Self::BUILTIN_ID.to_string(),
368 vendor: Vendor::Anthropic,
369 api: Some("anthropic".to_string()),
370 tiers: Tiers {
371 strong: Some(model.to_string()),
372 balanced: None,
373 fast: None,
374 },
375 builtin: true,
376 ..Default::default()
377 }
378 }
379
380 pub fn id_problem(id: &str) -> Option<String> {
385 if id.is_empty() {
386 return Some("a provider needs an `id`".to_string());
387 }
388 let fits = id
389 .bytes()
390 .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-' || b == b'_');
391 (!fits).then(|| {
392 format!("provider id `{id}` may hold only lowercase ASCII letters, digits, `-` and `_`")
393 })
394 }
395
396 pub fn api(&self) -> &str {
398 self.api.as_deref().unwrap_or("anthropic")
399 }
400
401 pub fn accepts_model(&self, model: &str) -> bool {
403 self.models.is_empty() || self.models.iter().any(|m| m.id() == model)
404 }
405
406 pub fn lists_model(&self, model: &str) -> bool {
408 self.models.iter().any(|m| m.id() == model)
409 }
410
411 pub fn model_ids(&self) -> Vec<&str> {
412 self.models.iter().map(ModelEntry::id).collect()
413 }
414
415 pub fn model_spec(&self, model: &str) -> Option<&ModelSpec> {
417 self.models
418 .iter()
419 .find(|m| m.id() == model)
420 .and_then(ModelEntry::spec)
421 }
422
423 pub fn resolved_tiers(&self) -> Result<ResolvedTiers, String> {
425 let id = &self.id;
426 let strong = self
427 .tiers
428 .strong
429 .clone()
430 .filter(|m| !m.is_empty())
431 .ok_or_else(|| format!("provider `{id}` has no `tiers.strong`"))?;
432 let balanced = self
433 .tiers
434 .balanced
435 .clone()
436 .unwrap_or_else(|| strong.clone());
437 let fast = self.tiers.fast.clone().unwrap_or_else(|| balanced.clone());
438 let resolved = ResolvedTiers {
439 strong,
440 balanced,
441 fast,
442 };
443 if !self.models.is_empty() {
444 for tier in Tier::ALL {
445 let model = resolved.get(tier);
446 if !self.lists_model(model) {
447 return Err(format!(
448 "provider `{id}`: `tiers.{}` is `{model}`, which is not in its `models`",
449 tier.as_str()
450 ));
451 }
452 }
453 }
454 Ok(resolved)
455 }
456}
457
458#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize, schemars::JsonSchema)]
460pub struct ListedModel {
461 pub id: String,
462 #[serde(default, skip_serializing_if = "Option::is_none")]
463 pub display_name: Option<String>,
464 #[serde(default, skip_serializing_if = "Option::is_none")]
465 pub context_window: Option<u64>,
466 #[serde(default, skip_serializing_if = "Option::is_none")]
467 pub max_output: Option<u32>,
468 #[serde(default, skip_serializing_if = "Option::is_none")]
469 pub input_types: Option<Vec<String>>,
470 #[serde(default, skip_serializing_if = "Option::is_none")]
472 pub reasoning: Option<bool>,
473}
474
475#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
482#[serde(default, deny_unknown_fields)]
483pub struct TaskTiers {
484 pub main: Tier,
486 pub subagent: Tier,
488 pub compact: Tier,
490 pub memory: Tier,
492 pub title: Tier,
494 pub web_search: Tier,
496 #[serde(skip_serializing_if = "Option::is_none")]
498 pub web_fetch: Option<Tier>,
499}
500
501impl Default for TaskTiers {
502 fn default() -> Self {
503 Self {
504 main: Tier::Strong,
505 subagent: Tier::Balanced,
506 compact: Tier::Fast,
507 memory: Tier::Fast,
508 title: Tier::Fast,
509 web_search: Tier::Fast,
510 web_fetch: None,
511 }
512 }
513}
514
515impl TaskTiers {
516 pub const MAIN: &'static str = "main";
517 pub const SUBAGENT: &'static str = "subagent";
518 pub const COMPACT: &'static str = "compact";
519 pub const MEMORY: &'static str = "memory";
520 pub const TITLE: &'static str = "title";
521 pub const WEB_SEARCH: &'static str = "web_search";
522 pub const WEB_FETCH: &'static str = "web_fetch";
523
524 pub fn get(&self, task: &str) -> Option<Tier> {
527 match task {
528 Self::MAIN => Some(self.main),
529 Self::SUBAGENT => Some(self.subagent),
530 Self::COMPACT => Some(self.compact),
531 Self::MEMORY => Some(self.memory),
532 Self::TITLE => Some(self.title),
533 Self::WEB_SEARCH => Some(self.web_search),
534 Self::WEB_FETCH => self.web_fetch,
535 _ => None,
536 }
537 }
538}
539
540pub fn routing_order<'a>(
545 providers: &'a [ProviderConfig],
546 order: &[String],
547) -> Result<Vec<(&'a ProviderConfig, ResolvedTiers)>, String> {
548 let mut resolved = Vec::with_capacity(providers.len());
549 for provider in providers {
550 if let Some(problem) = ProviderConfig::id_problem(&provider.id) {
551 return Err(problem);
552 }
553 resolved.push((provider, provider.resolved_tiers()?));
554 }
555 let Some(first) = providers.first() else {
556 return Err("no provider is defined".to_string());
557 };
558 let order: Vec<&str> = match order.is_empty() {
559 true => vec![first.id.as_str()],
560 false => order.iter().map(String::as_str).collect(),
561 };
562 let mut out: Vec<(&ProviderConfig, ResolvedTiers)> = Vec::with_capacity(order.len());
563 for id in order {
564 if out.iter().any(|(p, _)| p.id == id) {
565 continue;
566 }
567 let Some((provider, tiers)) = resolved.iter().find(|(p, _)| p.id == id) else {
568 return Err(format!(
569 "`model.order` names provider `{id}`, which no `providers` entry defines"
570 ));
571 };
572 out.push((provider, tiers.clone()));
573 }
574 Ok(out)
575}
576
577#[cfg(test)]
578mod tests;