use super::cache::ModelPricing;
use lru::LruCache;
use std::collections::HashMap;
use std::num::NonZeroUsize;
use std::rc::Rc;
use std::sync::{LazyLock, RwLock};
use strsim::jaro_winkler;
const SIMILARITY_THRESHOLD: f64 = 0.7;
const PRICING_MATCH_CACHE_SIZE: usize = 10;
static MATCH_CACHE: LazyLock<RwLock<LruCache<String, ModelPricingResult>>> = LazyLock::new(|| {
let capacity = NonZeroUsize::new(PRICING_MATCH_CACHE_SIZE).unwrap();
RwLock::new(LruCache::new(capacity))
});
#[derive(Debug, Clone)]
pub struct ModelPricingResult {
pub pricing: ModelPricing,
pub matched_model: Option<String>,
}
#[derive(Debug, Clone)]
pub struct ModelPricingMap {
raw: HashMap<Rc<str>, ModelPricing>,
normalized_index: HashMap<String, Rc<str>>, lowercase_keys: Vec<(String, Rc<str>)>, }
impl ModelPricingMap {
pub fn new(raw: HashMap<String, ModelPricing>) -> Self {
let capacity = raw.len();
let mut normalized_index = HashMap::with_capacity(capacity);
let mut lowercase_keys = Vec::with_capacity(capacity);
let mut rc_raw = HashMap::with_capacity(capacity);
for (key, pricing) in raw {
let rc_key: Rc<str> = key.as_str().into();
let normalized = normalize_model_name(&key);
if normalized != key {
normalized_index.insert(normalized, rc_key.clone());
}
lowercase_keys.push((key.to_lowercase(), rc_key.clone()));
rc_raw.insert(rc_key, pricing);
}
lowercase_keys.sort_by(|a, b| a.0.cmp(&b.0));
Self {
raw: rc_raw,
normalized_index,
lowercase_keys,
}
}
pub fn get(&self, model_name: &str) -> ModelPricingResult {
if let Ok(cache_read) = MATCH_CACHE.read()
&& let Some(cached_result) = cache_read.peek(model_name)
{
return cached_result.clone();
}
if let Some(pricing) = self.raw.get(model_name) {
let result = ModelPricingResult {
pricing: pricing.clone(),
matched_model: None,
};
if let Ok(mut cache_write) = MATCH_CACHE.write() {
cache_write.put(model_name.to_string(), result.clone());
}
return result;
}
let normalized_name = normalize_model_name(model_name);
if let Some(original_key) = self.normalized_index.get(&normalized_name)
&& let Some(pricing) = self.raw.get(original_key.as_ref())
{
let result = ModelPricingResult {
pricing: pricing.clone(),
matched_model: Some(original_key.to_string()), };
if let Ok(mut cache_write) = MATCH_CACHE.write() {
cache_write.put(model_name.to_string(), result.clone());
}
return result;
}
let model_lower = model_name.to_lowercase();
let mut best_match: Option<(Rc<str>, f64, bool)> = None;
for (key_lower, original_key) in &self.lowercase_keys {
if (model_lower.contains(key_lower) || key_lower.contains(&model_lower))
&& (best_match.is_none() || !best_match.as_ref().unwrap().2)
{
best_match = Some((original_key.clone(), 1.0, true)); if model_lower == *key_lower {
break;
}
}
if best_match.is_none() || best_match.as_ref().unwrap().1 < 1.0 {
let similarity = jaro_winkler(&model_lower, key_lower);
if similarity >= SIMILARITY_THRESHOLD {
if let Some((_, best_score, is_sub)) = &best_match {
if !is_sub && similarity > *best_score {
best_match = Some((original_key.clone(), similarity, false));
}
} else {
best_match = Some((original_key.clone(), similarity, false));
}
}
}
}
if let Some((matched_key, _, _)) = best_match
&& let Some(pricing) = self.raw.get(matched_key.as_ref())
{
let result = ModelPricingResult {
pricing: pricing.clone(),
matched_model: Some(matched_key.to_string()), };
if let Ok(mut cache_write) = MATCH_CACHE.write() {
cache_write.put(model_name.to_string(), result.clone());
}
return result;
}
let result = ModelPricingResult {
pricing: ModelPricing::default(),
matched_model: None,
};
if let Ok(mut cache_write) = MATCH_CACHE.write() {
cache_write.put(model_name.to_string(), result.clone());
}
result
}
pub fn is_empty(&self) -> bool {
self.raw.is_empty()
}
pub fn raw(&self) -> &HashMap<Rc<str>, ModelPricing> {
&self.raw
}
}
pub fn clear_pricing_cache() {
if let Ok(mut cache_write) = MATCH_CACHE.write() {
cache_write.clear();
}
}
pub fn normalize_model_name(name: &str) -> String {
let mut start = 0;
let mut end = name.len();
if let Some(idx) = name.find('/') {
start = idx + 1;
}
let working_slice = &name[start..end];
if let Some(idx) = working_slice.rfind("-20") {
let suffix_start = idx + 1; if working_slice.len() - suffix_start == 8 {
end = start + idx;
}
}
let working_slice2 = &name[start..end];
if let Some(idx) = working_slice2.rfind("-v") {
end = start + idx;
}
name[start..end].to_string()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_normalize_model_name() {
assert_eq!(
normalize_model_name("claude-3-sonnet-20240229"),
"claude-3-sonnet"
);
assert_eq!(normalize_model_name("gpt-4-v1.0"), "gpt-4");
assert_eq!(
normalize_model_name("bedrock/claude-3-opus"),
"claude-3-opus"
);
}
}