pub mod python;
use serde::{Deserialize, Serialize};
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum Sdk {
Openai,
Anthropic,
Google,
}
impl Sdk {
pub const ALL: [Sdk; 3] = [Sdk::Openai, Sdk::Anthropic, Sdk::Google];
pub fn as_str(self) -> &'static str {
match self {
Sdk::Openai => "openai",
Sdk::Anthropic => "anthropic",
Sdk::Google => "google",
}
}
pub fn parse(name: &str) -> Option<Sdk> {
match name.trim().to_ascii_lowercase().as_str() {
"openai" => Some(Sdk::Openai),
"anthropic" => Some(Sdk::Anthropic),
"google" | "gemini" => Some(Sdk::Google),
_ => None,
}
}
}
impl std::fmt::Display for Sdk {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(self.as_str())
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum Routing {
OpenaiDirect,
AzureOpenai,
CustomBaseUrl,
AnthropicDirect,
AnthropicBedrock,
AnthropicVertex,
GoogleGenai,
GoogleGenerativeaiLegacy,
Unknown,
}
impl Routing {
pub fn as_str(self) -> &'static str {
match self {
Routing::OpenaiDirect => "openai_direct",
Routing::AzureOpenai => "azure_openai",
Routing::CustomBaseUrl => "custom_base_url",
Routing::AnthropicDirect => "anthropic_direct",
Routing::AnthropicBedrock => "anthropic_bedrock",
Routing::AnthropicVertex => "anthropic_vertex",
Routing::GoogleGenai => "google_genai",
Routing::GoogleGenerativeaiLegacy => "google_generativeai_legacy",
Routing::Unknown => "unknown",
}
}
}
impl std::fmt::Display for Routing {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(self.as_str())
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct Span {
pub line: u32,
pub column: u32,
pub end_line: u32,
pub end_column: u32,
pub start_byte: u32,
pub end_byte: u32,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum BindingKind {
Module,
ClientClass,
Symbol,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct SdkImport {
pub sdk: Sdk,
pub package: String,
pub module: String,
pub name: Option<String>,
pub local: String,
pub kind: BindingKind,
pub file: String,
pub span: Span,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ClientScope {
Module,
Local,
Class,
Attribute,
Inline,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ClientConstruction {
pub sdk: Sdk,
pub package: String,
pub constructor: String,
pub chain: String,
pub binding: Option<String>,
pub scope: ClientScope,
pub routing: Routing,
pub is_async: bool,
pub kwargs: Vec<String>,
pub splat: bool,
pub file: String,
pub span: Span,
pub symbol: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub vertexai: Option<VertexAi>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum VertexAi {
On,
Off,
Unknown,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum Receiver {
Module,
Client,
Symbol,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ValueOrigin {
Literal,
ModuleConstant,
ClassConstant,
LocalConstant,
ParameterDefault,
EnvDefault,
}
impl ValueOrigin {
pub fn as_str(self) -> &'static str {
match self {
ValueOrigin::Literal => "literal",
ValueOrigin::ModuleConstant => "module_constant",
ValueOrigin::ClassConstant => "class_constant",
ValueOrigin::LocalConstant => "local_constant",
ValueOrigin::ParameterDefault => "parameter_default",
ValueOrigin::EnvDefault => "env_default",
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct CapturedValue {
pub key: String,
pub value: String,
pub origin: ValueOrigin,
pub name: Option<String>,
pub positional: bool,
pub span: Span,
pub model_family: Option<Sdk>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct SdkCall {
pub sdk: Sdk,
pub package: String,
pub chain: String,
pub member: String,
pub request: bool,
pub receiver: Receiver,
pub routing: Routing,
pub client_line: Option<u32>,
pub file: String,
pub span: Span,
pub symbol: Option<String>,
pub kwargs: Vec<String>,
pub positional: u32,
pub splat: bool,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub spreads: Vec<Spread>,
pub values: Vec<CapturedValue>,
}
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct Spread {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub keys: Vec<String>,
pub complete: bool,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum GapKind {
UnresolvedModel,
UnknownClientFactory,
AmbiguousClient,
DynamicDispatch,
VendoredPath,
}
impl GapKind {
pub fn as_str(self) -> &'static str {
match self {
GapKind::UnresolvedModel => "unresolved_model",
GapKind::UnknownClientFactory => "unknown_client_factory",
GapKind::AmbiguousClient => "ambiguous_client",
GapKind::DynamicDispatch => "dynamic_dispatch",
GapKind::VendoredPath => "vendored_path",
}
}
}
impl std::fmt::Display for GapKind {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(self.as_str())
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct UsageGap {
pub kind: GapKind,
pub sdk: Option<Sdk>,
pub file: String,
pub span: Option<Span>,
pub symbol: Option<String>,
pub chain: Option<String>,
pub key: Option<String>,
pub reason: String,
pub detail: String,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub values: Vec<CapturedValue>,
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
pub values_complete: bool,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub args: Option<CallArgs>,
}
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct CallArgs {
pub kwargs: Vec<String>,
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
pub splat: bool,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub spreads: Vec<Spread>,
}
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct FileUsages {
pub file: String,
pub language: String,
pub imports: Vec<SdkImport>,
pub clients: Vec<ClientConstruction>,
pub calls: Vec<SdkCall>,
pub gaps: Vec<UsageGap>,
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
pub syntax_errors: bool,
}
impl FileUsages {
pub fn new(file: &str, language: &str) -> Self {
Self {
file: file.to_string(),
language: language.to_string(),
..Self::default()
}
}
pub fn is_empty(&self) -> bool {
self.imports.is_empty()
&& self.clients.is_empty()
&& self.calls.is_empty()
&& self.gaps.is_empty()
}
pub fn retain_sdk(&mut self, sdk: Sdk) {
self.imports.retain(|i| i.sdk == sdk);
self.clients.retain(|c| c.sdk == sdk);
self.calls.retain(|c| c.sdk == sdk);
self.gaps.retain(|g| g.sdk.is_none_or(|s| s == sdk));
}
}
pub const USAGE_LANGUAGES: &[&str] = &["python"];
pub const USAGE_EXTENSIONS: &[&str] = &["py"];
pub fn is_usage_extension(extension: &str) -> bool {
USAGE_EXTENSIONS
.iter()
.any(|e| e.eq_ignore_ascii_case(extension))
}
pub fn is_python_shebang(head: &[u8]) -> bool {
let Some(rest) = head.strip_prefix(b"#!") else {
return false;
};
let line = rest.split(|b| *b == b'\n').next().unwrap_or_default();
String::from_utf8_lossy(line)
.split(|c: char| c.is_whitespace() || c == '/')
.any(|word| word.starts_with("python"))
}
pub const VALUE_KEYS: &[&str] = &["model", "engine", "deployment_id", "model_name"];
const SECRET_NEEDLES: &[&str] = &[
"key",
"token",
"secret",
"passw",
"passphrase",
"pwd",
"auth",
"cred",
"private",
];
pub fn is_secret_key(key: &str) -> bool {
let lower = key.to_ascii_lowercase();
SECRET_NEEDLES.iter().any(|needle| lower.contains(needle))
}
pub fn is_value_key(key: &str) -> bool {
VALUE_KEYS.contains(&key) && !is_secret_key(key)
}
pub fn is_identifier_key(key: &str) -> bool {
is_argument_name(key) && !is_secret_key(key)
}
pub(crate) fn is_argument_name(key: &str) -> bool {
let mut chars = key.chars();
let Some(first) = chars.next() else {
return false;
};
key.len() <= 64
&& (first.is_ascii_alphabetic() || first == '_')
&& chars.all(|c| c.is_ascii_alphanumeric() || c == '_')
&& !is_credential_value(key)
}
const CREDENTIAL_PREFIXES: &[&str] = &[
"sk-",
"sk_",
"rk_",
"pk_live_",
"pk_test_",
"AIza",
"ghp_",
"gho_",
"ghu_",
"ghs_",
"ghr_",
"github_pat_",
"xox",
"xapp-",
"glpat-",
"hf_",
"r8_",
"gsk_",
"pplx-",
"nvapi-",
"csk-",
"-----BEGIN",
"Bearer ",
"bearer ",
"Basic ",
];
pub fn is_credential_value(value: &str) -> bool {
let value = value.trim();
if CREDENTIAL_PREFIXES.iter().any(|p| value.starts_with(p)) {
return true;
}
if has_url_userinfo(value) {
return true;
}
if (value.starts_with("AKIA") || value.starts_with("ASIA"))
&& value.len() == 20
&& value
.chars()
.all(|c| c.is_ascii_uppercase() || c.is_ascii_digit())
{
return true;
}
if value.starts_with("eyJ") && value.matches('.').count() >= 2 {
return true;
}
value
.split(|c: char| !c.is_ascii_alphanumeric())
.any(|run| {
let upper = run.chars().any(|c| c.is_ascii_uppercase());
let lower = run.chars().any(|c| c.is_ascii_lowercase());
let digit = run.chars().any(|c| c.is_ascii_digit());
(run.len() >= 20 && upper && lower && digit)
|| (run.len() >= 32 && (upper || lower) && digit)
})
}
fn has_url_userinfo(value: &str) -> bool {
value.match_indices("://").any(|(at, sep)| {
let rest = &value[at + sep.len()..];
let authority = rest.split(['/', '?', '#']).next().unwrap_or_default();
authority.contains('@')
})
}
pub fn is_capturable_value(value: &str) -> bool {
value.len() <= 256 && !value.chars().any(is_unsafe_char) && !is_credential_value(value)
}
pub fn is_unsafe_char(c: char) -> bool {
c.is_control() || matches!(c, '\u{202A}'..='\u{202E}' | '\u{2066}'..='\u{2069}')
}
pub fn model_family(value: &str) -> Option<Sdk> {
let lower = value.trim().to_ascii_lowercase();
let mut id = lower.as_str();
for prefix in [
"ft:",
"openai/",
"openai.",
"models/",
"publishers/google/models/",
] {
if let Some(rest) = id.strip_prefix(prefix) {
id = rest;
}
}
if id.starts_with("claude-")
|| id.starts_with("anthropic/claude-")
|| id.contains("anthropic.claude-")
{
return Some(Sdk::Anthropic);
}
const GOOGLE: &[&str] = &[
"gemini-",
"gemma-",
"text-bison",
"chat-bison",
"code-bison",
"codechat-bison",
"text-embedding-00",
"text-multilingual-embedding-",
"embedding-001",
"embedding-gecko",
"imagen-",
"veo-",
];
if GOOGLE.iter().any(|p| id.starts_with(p)) || id == "gemini" {
return Some(Sdk::Google);
}
const OPENAI: &[&str] = &[
"gpt-",
"chatgpt-",
"text-davinci-",
"text-curie-",
"text-babbage-",
"text-ada-",
"code-davinci-",
"code-cushman-",
"davinci",
"curie",
"babbage",
"text-embedding-",
"text-moderation-",
"omni-moderation-",
"dall-e-",
"whisper-",
"tts-",
"computer-use-preview",
"codex-mini",
];
if OPENAI.iter().any(|p| id.starts_with(p)) || id == "ada" || id.starts_with("ada-") {
return Some(Sdk::Openai);
}
let mut chars = id.chars();
if chars.next() == Some('o') {
let rest: String = chars.collect();
let digits = rest.chars().take_while(|c| c.is_ascii_digit()).count();
if digits > 0 {
let tail = &rest[digits..];
if tail.is_empty() || tail.starts_with('-') {
return Some(Sdk::Openai);
}
}
}
None
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn value_keys_are_never_secret_shaped() {
for key in VALUE_KEYS {
assert!(!is_secret_key(key), "{key} must not look like a secret");
assert!(is_value_key(key));
}
for key in [
"api_key",
"API_KEY",
"auth_token",
"max_tokens",
"client_secret",
"password",
"authorization",
"azure_ad_token_provider",
"PASSWD",
"db_pwd",
"credential",
"CREDENTIALS",
"gcp_cred",
"private_pem",
"passphrase",
] {
assert!(is_secret_key(key), "{key} must be treated as secret");
assert!(!is_value_key(key));
}
assert!(!is_value_key("temperature"));
}
#[test]
fn credential_shaped_values_are_refused() {
for secret in [
"sk-proj-AbCdEf0123456789xyz",
"sk-ant-api03-AbCdEf0123456789",
"sk-live-SECRET",
"sk_live_51H8abc",
"AIzaSyD-abcdefghijklmnop",
"ghp_0123456789abcdefABCDEF",
"xoxb-1234-5678-abcdef",
"AKIAIOSFODNN7EXAMPLE",
"Bearer abc",
"eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiIxIn0.sig",
"Zx8aB2cD4eF6gH8iJ0kL2mN4",
"0123456789abcdef0123456789abcdef",
"postgres://admin:hunter2@db/prod",
"https://user:pw@gateway.example/v1",
"https://tokenvalue@github.com/org/repo",
] {
assert!(is_credential_value(secret), "{secret} must be refused");
assert!(!is_capturable_value(secret));
}
for model in [
"gpt-4o-2024-08-06",
"claude-3-5-sonnet-20241022",
"us.anthropic.claude-sonnet-4-5-20250929-v1:0",
"ft:gpt-4o-mini-2024-07-18:acme::9xKz3mQp",
"models/gemini-1.5-flash-001",
"GPT4o-Prod-Deployment-2024",
"claude-3-5-sonnet-v2@20241022",
"projects/123456789012/locations/us-central1/endpoints/1234567890123456789",
"text-embedding-3-small",
"o3-mini",
"https://openrouter.ai/api/v1",
"anthropic/claude-3-opus@latest",
] {
assert!(!is_credential_value(model), "{model} is a model ID");
assert!(is_capturable_value(model));
}
assert!(!is_capturable_value("gpt-4\u{1b}]8;;x\u{7}"));
assert!(!is_capturable_value("gpt-\u{202E}4"));
assert!(!is_capturable_value(&"a".repeat(300)));
}
#[test]
fn identifier_keys_only() {
for ok in ["model", "fallbacks", "extra_body", "_x1"] {
assert!(is_identifier_key(ok), "{ok}");
}
for bad in [
"",
"sk-proj-abc",
"x-api-key",
"api_key",
"1model",
"has space",
"sk_live_abc",
"Zx8aB2cD4eF6gH8iJ0kL2mN4",
] {
assert!(!is_identifier_key(bad), "{bad}");
}
}
#[test]
fn python_shebangs() {
for yes in [
"#!/usr/bin/env python3\nimport openai\n",
"#!/usr/bin/python\n",
"#! /usr/local/bin/python3.11 -u\n",
"#!/usr/bin/env -S python3 -X utf8\n",
] {
assert!(is_python_shebang(yes.as_bytes()), "{yes}");
}
for no in [
"#!/bin/sh\n",
"import openai\n",
"",
"#!/usr/bin/env node\n# python\n",
] {
assert!(!is_python_shebang(no.as_bytes()), "{no}");
}
}
#[test]
fn model_family_recognises_shapes() {
for (id, sdk) in [
("gpt-3.5-turbo", Sdk::Openai),
("gpt-4o-2024-08-06", Sdk::Openai),
("o1", Sdk::Openai),
("o3-mini", Sdk::Openai),
("o4-mini-2025-04-16", Sdk::Openai),
("text-davinci-003", Sdk::Openai),
("text-embedding-3-small", Sdk::Openai),
("ft:gpt-4o-mini:acme::abc", Sdk::Openai),
("openai/gpt-4", Sdk::Openai),
("openai.gpt-5.4", Sdk::Openai),
("claude-3-5-sonnet-20241022", Sdk::Anthropic),
("anthropic.claude-3-haiku-20240307-v1:0", Sdk::Anthropic),
(
"us.anthropic.claude-sonnet-4-5-20250929-v1:0",
Sdk::Anthropic,
),
("global.anthropic.claude-sonnet-5-5", Sdk::Anthropic),
("gemini-1.5-flash", Sdk::Google),
("models/gemini-pro", Sdk::Google),
("text-embedding-004", Sdk::Google),
] {
assert_eq!(model_family(id), Some(sdk), "{id}");
}
for not_a_model in ["", "my-deployment", "ocean", "o", "orange-1", "hello"] {
assert_eq!(model_family(not_a_model), None, "{not_a_model}");
}
}
#[test]
fn sdk_and_routing_names_round_trip() {
for sdk in Sdk::ALL {
assert_eq!(Sdk::parse(sdk.as_str()), Some(sdk));
let json = serde_json::to_string(&sdk).unwrap();
assert_eq!(json, format!("\"{}\"", sdk.as_str()));
}
assert_eq!(Sdk::parse("Gemini"), Some(Sdk::Google));
assert_eq!(Sdk::parse("cohere"), None);
for routing in [
Routing::OpenaiDirect,
Routing::AzureOpenai,
Routing::CustomBaseUrl,
Routing::AnthropicDirect,
Routing::AnthropicBedrock,
Routing::AnthropicVertex,
Routing::GoogleGenai,
Routing::GoogleGenerativeaiLegacy,
Routing::Unknown,
] {
let json = serde_json::to_string(&routing).unwrap();
assert_eq!(json, format!("\"{}\"", routing.as_str()));
}
}
}