use serde_json::Value;
use super::usage::{Fetch, HttpRequest, Quota};
pub const QUOTA_URL: &str = "https://bigmodel.cn/api/monitor/usage/quota/limit";
const TOKENS_LIMIT: &str = "TOKENS_LIMIT";
pub fn read_quota(body: &Value) -> Option<Quota> {
let limits = body.get("data")?.get("limits")?.as_array()?;
for limit in limits {
let Some(entry) = limit.as_object() else {
continue;
};
if entry.get("type").and_then(Value::as_str) != Some(TOKENS_LIMIT) {
continue;
}
let percentage = entry.get("percentage").and_then(Value::as_f64)?;
return Some(match entry.get("nextResetTime").and_then(Value::as_i64) {
Some(resets_at) => Quota {
percentage,
resets_at: Some(resets_at),
},
None => Quota {
percentage,
resets_at: None,
},
});
}
None
}
pub async fn fetch_quota(key: &str, fetch: &impl Fetch, timeout_ms: u64) -> Option<Quota> {
let response = fetch
.fetch(
QUOTA_URL.to_owned(),
HttpRequest {
headers: vec![
("Authorization".to_owned(), key.to_owned()),
("Accept".to_owned(), "application/json".to_owned()),
],
timeout_ms,
},
)
.await
.ok()?;
if !response.ok() {
return None;
}
read_quota(&response.body?)
}
pub fn meters_usage(provider: &str) -> bool {
provider.starts_with("zai")
}
#[cfg(test)]
mod tests;