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 = "Vec::is_empty")]
241 pub models: Vec<ModelEntry>,
242 #[serde(default)]
246 pub tiers: Tiers,
247 #[serde(default, skip_serializing_if = "Quota::is_unlimited")]
250 pub quota: Quota,
251 #[serde(skip)]
253 #[schemars(skip)]
254 pub builtin: bool,
255}
256
257#[derive(Debug, Clone, PartialEq, Serialize, schemars::JsonSchema)]
259#[serde(untagged)]
260#[non_exhaustive]
261pub enum ModelEntry {
262 Id(String),
263 Spec(ModelSpec),
264}
265
266#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize, schemars::JsonSchema)]
272#[serde(deny_unknown_fields)]
273pub struct ModelSpec {
274 pub id: String,
275 #[serde(default, skip_serializing_if = "Option::is_none")]
276 pub context_window: Option<u64>,
277 #[serde(default, skip_serializing_if = "Option::is_none")]
281 pub max_output: Option<u32>,
282 #[serde(default, skip_serializing_if = "Option::is_none")]
283 pub reasoning_levels: Option<Vec<String>>,
284 #[serde(default, skip_serializing_if = "Option::is_none")]
285 pub input_types: Option<Vec<String>>,
286}
287
288impl ModelEntry {
289 pub fn id(&self) -> &str {
290 match self {
291 Self::Id(id) => id,
292 Self::Spec(spec) => &spec.id,
293 }
294 }
295
296 pub fn spec(&self) -> Option<&ModelSpec> {
297 match self {
298 Self::Id(_) => None,
299 Self::Spec(spec) => Some(spec),
300 }
301 }
302}
303
304impl From<&str> for ModelEntry {
305 fn from(id: &str) -> Self {
306 Self::Id(id.to_string())
307 }
308}
309
310impl From<String> for ModelEntry {
311 fn from(id: String) -> Self {
312 Self::Id(id)
313 }
314}
315
316impl<'de> Deserialize<'de> for ModelEntry {
319 fn deserialize<D: serde::Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
320 use serde::de::Error;
321 match serde_json::Value::deserialize(d)? {
322 serde_json::Value::String(id) => Ok(Self::Id(id)),
323 object @ serde_json::Value::Object(_) => serde_json::from_value(object)
324 .map(Self::Spec)
325 .map_err(|e| D::Error::custom(format!("a model entry: {e}"))),
326 _ => Err(D::Error::custom(
327 "a model entry is an id string or an object with `id`",
328 )),
329 }
330 }
331}
332
333impl ProviderConfig {
334 pub const BUILTIN_ID: &'static str = "anthropic";
337
338 pub fn builtin(model: &str) -> Self {
341 Self {
342 id: Self::BUILTIN_ID.to_string(),
343 vendor: Vendor::Anthropic,
344 api: Some("anthropic".to_string()),
345 tiers: Tiers {
346 strong: Some(model.to_string()),
347 balanced: None,
348 fast: None,
349 },
350 builtin: true,
351 ..Default::default()
352 }
353 }
354
355 pub fn id_problem(id: &str) -> Option<String> {
360 if id.is_empty() {
361 return Some("a provider needs an `id`".to_string());
362 }
363 let fits = id
364 .bytes()
365 .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-' || b == b'_');
366 (!fits).then(|| {
367 format!("provider id `{id}` may hold only lowercase ASCII letters, digits, `-` and `_`")
368 })
369 }
370
371 pub fn api(&self) -> &str {
373 self.api.as_deref().unwrap_or("anthropic")
374 }
375
376 pub fn accepts_model(&self, model: &str) -> bool {
378 self.models.is_empty() || self.models.iter().any(|m| m.id() == model)
379 }
380
381 pub fn lists_model(&self, model: &str) -> bool {
383 self.models.iter().any(|m| m.id() == model)
384 }
385
386 pub fn model_ids(&self) -> Vec<&str> {
387 self.models.iter().map(ModelEntry::id).collect()
388 }
389
390 pub fn model_spec(&self, model: &str) -> Option<&ModelSpec> {
392 self.models
393 .iter()
394 .find(|m| m.id() == model)
395 .and_then(ModelEntry::spec)
396 }
397
398 pub fn resolved_tiers(&self) -> Result<ResolvedTiers, String> {
400 let id = &self.id;
401 let strong = self
402 .tiers
403 .strong
404 .clone()
405 .filter(|m| !m.is_empty())
406 .ok_or_else(|| format!("provider `{id}` has no `tiers.strong`"))?;
407 let balanced = self
408 .tiers
409 .balanced
410 .clone()
411 .unwrap_or_else(|| strong.clone());
412 let fast = self.tiers.fast.clone().unwrap_or_else(|| balanced.clone());
413 let resolved = ResolvedTiers {
414 strong,
415 balanced,
416 fast,
417 };
418 if !self.models.is_empty() {
419 for tier in Tier::ALL {
420 let model = resolved.get(tier);
421 if !self.lists_model(model) {
422 return Err(format!(
423 "provider `{id}`: `tiers.{}` is `{model}`, which is not in its `models`",
424 tier.as_str()
425 ));
426 }
427 }
428 }
429 Ok(resolved)
430 }
431}
432
433#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize, schemars::JsonSchema)]
435pub struct ListedModel {
436 pub id: String,
437 #[serde(default, skip_serializing_if = "Option::is_none")]
438 pub display_name: Option<String>,
439 #[serde(default, skip_serializing_if = "Option::is_none")]
440 pub context_window: Option<u64>,
441 #[serde(default, skip_serializing_if = "Option::is_none")]
442 pub max_output: Option<u32>,
443 #[serde(default, skip_serializing_if = "Option::is_none")]
444 pub input_types: Option<Vec<String>>,
445 #[serde(default, skip_serializing_if = "Option::is_none")]
447 pub reasoning: Option<bool>,
448}
449
450#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
457#[serde(default, deny_unknown_fields)]
458pub struct TaskTiers {
459 pub main: Tier,
461 pub subagent: Tier,
463 pub compact: Tier,
465 pub memory: Tier,
467 pub title: Tier,
469 pub web_search: Tier,
471 #[serde(skip_serializing_if = "Option::is_none")]
473 pub web_fetch: Option<Tier>,
474}
475
476impl Default for TaskTiers {
477 fn default() -> Self {
478 Self {
479 main: Tier::Strong,
480 subagent: Tier::Balanced,
481 compact: Tier::Fast,
482 memory: Tier::Fast,
483 title: Tier::Fast,
484 web_search: Tier::Fast,
485 web_fetch: None,
486 }
487 }
488}
489
490impl TaskTiers {
491 pub const MAIN: &'static str = "main";
492 pub const SUBAGENT: &'static str = "subagent";
493 pub const COMPACT: &'static str = "compact";
494 pub const MEMORY: &'static str = "memory";
495 pub const TITLE: &'static str = "title";
496 pub const WEB_SEARCH: &'static str = "web_search";
497 pub const WEB_FETCH: &'static str = "web_fetch";
498
499 pub fn get(&self, task: &str) -> Option<Tier> {
502 match task {
503 Self::MAIN => Some(self.main),
504 Self::SUBAGENT => Some(self.subagent),
505 Self::COMPACT => Some(self.compact),
506 Self::MEMORY => Some(self.memory),
507 Self::TITLE => Some(self.title),
508 Self::WEB_SEARCH => Some(self.web_search),
509 Self::WEB_FETCH => self.web_fetch,
510 _ => None,
511 }
512 }
513}
514
515pub fn routing_order<'a>(
520 providers: &'a [ProviderConfig],
521 order: &[String],
522) -> Result<Vec<(&'a ProviderConfig, ResolvedTiers)>, String> {
523 let mut resolved = Vec::with_capacity(providers.len());
524 for provider in providers {
525 if let Some(problem) = ProviderConfig::id_problem(&provider.id) {
526 return Err(problem);
527 }
528 resolved.push((provider, provider.resolved_tiers()?));
529 }
530 let Some(first) = providers.first() else {
531 return Err("no provider is defined".to_string());
532 };
533 let order: Vec<&str> = match order.is_empty() {
534 true => vec![first.id.as_str()],
535 false => order.iter().map(String::as_str).collect(),
536 };
537 let mut out: Vec<(&ProviderConfig, ResolvedTiers)> = Vec::with_capacity(order.len());
538 for id in order {
539 if out.iter().any(|(p, _)| p.id == id) {
540 continue;
541 }
542 let Some((provider, tiers)) = resolved.iter().find(|(p, _)| p.id == id) else {
543 return Err(format!(
544 "`model.order` names provider `{id}`, which no `providers` entry defines"
545 ));
546 };
547 out.push((provider, tiers.clone()));
548 }
549 Ok(out)
550}
551
552#[cfg(test)]
553mod tests;