use std::fmt;
use adk_core::{UnitRate, UsageUnit};
use serde::{Deserialize, Serialize};
use crate::geometry::CoordFrame;
#[derive(Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(transparent)]
pub struct BackendId(String);
impl BackendId {
pub fn new(id: impl Into<String>) -> Self {
Self(id.into())
}
pub fn as_str(&self) -> &str {
&self.0
}
}
impl fmt::Display for BackendId {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(&self.0)
}
}
impl From<&str> for BackendId {
fn from(id: &str) -> Self {
Self::new(id)
}
}
#[non_exhaustive]
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", tag = "kind")]
pub enum Locality {
InProcess,
Loopback,
Remote {
hosts: Vec<String>,
},
}
impl Locality {
pub fn is_remote(&self) -> bool {
matches!(self, Self::Remote { .. })
}
}
#[non_exhaustive]
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", rename_all_fields = "camelCase", tag = "kind")]
pub enum PriceRef {
PerUnit {
vendor: String,
model: String,
rate: UnitRate,
#[serde(default)]
min_units_per_request: u64,
},
Tokens {
vendor: String,
model: String,
},
}
impl PriceRef {
pub fn vendor(&self) -> &str {
match self {
Self::PerUnit { vendor, .. } | Self::Tokens { vendor, .. } => vendor,
}
}
pub fn model(&self) -> &str {
match self {
Self::PerUnit { model, .. } | Self::Tokens { model, .. } => model,
}
}
pub fn request_cost(&self, amount: u64) -> Option<u64> {
match self {
Self::PerUnit { rate, min_units_per_request, .. } => {
Some(rate.cost_micro_usd(amount.max(*min_units_per_request)))
}
Self::Tokens { .. } => None,
}
}
pub fn unit(&self) -> Option<UsageUnit> {
match self {
Self::PerUnit { rate, .. } => Some(rate.unit),
Self::Tokens { .. } => None,
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum Oversize {
Downscale,
Refuse,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct InputLimits {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub max_long_edge: Option<u32>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub max_pixels: Option<u64>,
pub oversize: Oversize,
}
impl InputLimits {
pub const fn unlimited() -> Self {
Self { max_long_edge: None, max_pixels: None, oversize: Oversize::Downscale }
}
pub const fn long_edge(pixels: u32) -> Self {
Self { max_long_edge: Some(pixels), max_pixels: None, oversize: Oversize::Downscale }
}
pub const fn with_max_pixels(mut self, pixels: u64) -> Self {
self.max_pixels = Some(pixels);
self
}
pub const fn refusing(mut self) -> Self {
self.oversize = Oversize::Refuse;
self
}
pub fn admits(&self, size: (u32, u32)) -> bool {
let long = size.0.max(size.1);
let pixels = u64::from(size.0) * u64::from(size.1);
self.max_long_edge.is_none_or(|max| long <= max)
&& self.max_pixels.is_none_or(|max| pixels <= max)
}
pub fn fit(&self, size: (u32, u32)) -> Option<(u32, u32)> {
if self.admits(size) {
return None;
}
let (w, h) = (f64::from(size.0), f64::from(size.1));
let mut scale = 1.0f64;
if let Some(max) = self.max_long_edge {
scale = scale.min(f64::from(max) / w.max(h));
}
if let Some(max) = self.max_pixels {
scale = scale.min((max as f64 / (w * h)).sqrt());
}
let mut fitted = (((w * scale).round() as u32).max(1), ((h * scale).round() as u32).max(1));
while !self.admits(fitted) && (fitted.0 > 1 || fitted.1 > 1) {
if fitted.0 >= fitted.1 {
fitted.0 -= 1;
fitted.1 = ((f64::from(fitted.0) * h / w).round() as u32).max(1);
} else {
fitted.1 -= 1;
fitted.0 = ((f64::from(fitted.1) * w / h).round() as u32).max(1);
}
}
Some(fitted)
}
pub fn describe(&self) -> String {
match (self.max_long_edge, self.max_pixels) {
(Some(edge), Some(px)) => format!("{edge} px on the long edge and {px} pixels"),
(Some(edge), None) => format!("{edge} px on the long edge"),
(None, Some(px)) => format!("{px} pixels"),
(None, None) => "any size".to_string(),
}
}
}
impl Default for InputLimits {
fn default() -> Self {
Self::unlimited()
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct BackendDescriptor {
pub id: BackendId,
pub locality: Locality,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub providers: Vec<String>,
pub frame: CoordFrame,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub price: Option<PriceRef>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub manifest: Option<String>,
#[serde(default)]
pub limits: InputLimits,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub token_estimate: Option<crate::budget::TokenEstimate>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub concepts_per_request: Option<u32>,
}
impl BackendDescriptor {
pub fn new(id: impl Into<String>, locality: Locality, frame: CoordFrame) -> Self {
Self {
id: BackendId::new(id),
locality,
providers: Vec::new(),
frame,
price: None,
manifest: None,
limits: InputLimits::unlimited(),
token_estimate: None,
concepts_per_request: None,
}
}
pub fn with_provider(mut self, provider: impl Into<String>) -> Self {
let provider = provider.into();
if !self.providers.contains(&provider) {
self.providers.push(provider);
}
self
}
pub fn with_token_estimate(mut self, estimate: crate::budget::TokenEstimate) -> Self {
self.token_estimate = Some(estimate);
self
}
pub fn with_price(mut self, price: PriceRef) -> Self {
self.price = Some(price);
self
}
pub fn with_manifest(mut self, manifest: impl Into<String>) -> Self {
self.manifest = Some(manifest.into());
self
}
pub fn with_limits(mut self, limits: InputLimits) -> Self {
self.limits = limits;
self
}
pub fn with_concepts_per_request(mut self, concepts: u32) -> Self {
self.concepts_per_request = Some(concepts.max(1));
self
}
pub fn requests_for(&self, concepts: usize, other_prompts: bool) -> u64 {
match self.concepts_per_request {
Some(per) => {
let per = per.max(1) as usize;
(concepts.div_ceil(per) + usize::from(other_prompts)).max(1) as u64
}
None => 1,
}
}
}