use std::sync::Arc;
use adk_model::openai::{OpenAICompatible, OpenAICompatibleConfig};
use super::LlmDescriber;
use crate::error::{Result, VisionError};
use crate::sent::SentImage;
#[derive(Clone)]
pub struct NimConfig {
base_url: String,
api_key: String,
model: String,
}
impl std::fmt::Debug for NimConfig {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("NimConfig")
.field("base_url", &self.base_url)
.field("api_key", &"[REDACTED]")
.field("model", &self.model)
.finish()
}
}
impl NimConfig {
pub fn new(
base_url: impl Into<String>,
api_key: impl Into<String>,
model: impl Into<String>,
) -> Self {
Self { base_url: base_url.into(), api_key: api_key.into(), model: model.into() }
}
pub fn host(&self) -> Result<String> {
let rest = self.base_url.split_once("://").map_or(self.base_url.as_str(), |(_, r)| r);
let authority = rest.split(['/', '?', '#']).next().unwrap_or_default();
let authority = authority.rsplit_once('@').map_or(authority, |(_, h)| h);
let host = match authority.strip_prefix('[') {
Some(v6) => v6.split(']').next().unwrap_or_default(),
None => authority.split(':').next().unwrap_or_default(),
};
if host.is_empty() {
return Err(VisionError::InvalidInput(format!(
"the NIM base URL `{}` names no host",
self.base_url
)));
}
Ok(host.to_ascii_lowercase())
}
pub fn client(&self) -> Result<OpenAICompatible> {
let config = OpenAICompatibleConfig::new(self.api_key.clone(), self.model.clone())
.with_provider_name("nvidia")
.with_base_url(self.base_url.clone());
Ok(OpenAICompatible::new(config)?)
}
pub fn describer(&self) -> Result<LlmDescriber> {
Ok(LlmDescriber::remote(Arc::new(self.client()?))?.with_unpriced_hold(0))
}
pub fn local_describer(&self) -> Result<LlmDescriber<SentImage>> {
LlmDescriber::local(Arc::new(self.client()?))
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn hosts_are_read_from_the_base_url() {
let host = |url: &str| NimConfig::new(url, "k", "m").host().unwrap();
assert_eq!(host("https://integrate.api.nvidia.com/v1"), "integrate.api.nvidia.com");
assert_eq!(host("http://10.0.0.5:8000/v1"), "10.0.0.5");
assert_eq!(host("http://[::1]:8000/v1"), "::1");
assert!(NimConfig::new("https:///v1", "k", "m").host().is_err());
}
#[test]
fn a_loopback_nim_is_local_and_a_remote_one_is_not() {
let local = NimConfig::new(
"http://127.0.0.1:8000/v1",
"k",
"nvidia/nemotron-3.5-super-vl-120b-a12b",
);
assert!(local.local_describer().is_ok());
let hosted =
NimConfig::new("https://integrate.api.nvidia.com/v1", "k", "google/gemma-4-31b-it");
assert!(hosted.local_describer().is_err());
assert!(hosted.describer().is_ok());
}
#[test]
fn the_key_is_never_printed() {
let config = NimConfig::new("https://integrate.api.nvidia.com/v1", "nvapi-secret", "m");
assert!(!format!("{config:?}").contains("nvapi-secret"));
}
}