adk_vision/nim_cv/config.rs
1//! [`NimCvConfig`]: where the NVIDIA CV endpoints are and how they are called.
2
3use std::collections::BTreeMap;
4use std::time::Duration;
5
6/// The default client timeout. NVIDIA's gateway gives up after 120 s with a 504, so the
7/// client waits longer than that to see the gateway's answer.
8pub const DEFAULT_TIMEOUT: Duration = Duration::from_secs(180);
9
10/// The default client-side rate: 40 requests per minute, the free-tier figure NVIDIA's
11/// forum users report for the hosted endpoints.
12pub const DEFAULT_REQUESTS_PER_MINUTE: u32 = 40;
13
14/// The default ceiling for one inline image: the asset upload path is retired, so every
15/// image travels as a data URI in the request body.
16pub const DEFAULT_MAX_INLINE_BYTES: usize = 8 * 1024 * 1024;
17
18/// Where NVIDIA's CV endpoints are and how the client calls them.
19///
20/// Nothing ships a default URL (spec 3.7 ยง7.7): the caller names the hosted endpoint, under
21/// NVIDIA's API Trial terms and suited to prototypes, or a self-hosted NIM. Each model is
22/// called at `<base_url>/<org>/<model>`; a self-hosted NIM that serves one model at its own
23/// URL is named with [`with_model_url`](Self::with_model_url).
24///
25/// # Example
26///
27/// ```
28/// use std::time::Duration;
29/// use adk_vision::NimCvConfig;
30///
31/// let config = NimCvConfig::new("https://ai.api.nvidia.com/v1/cv")
32/// .with_api_key("nvapi-...")
33/// .with_model_url("nvidia/nemotron-ocr-v1", "http://ocr.internal:8000/v1/infer")
34/// .with_requests_per_minute(40);
35/// assert_eq!(config.url_for("nvidia/nemotron-page-elements-v3"),
36/// "https://ai.api.nvidia.com/v1/cv/nvidia/nemotron-page-elements-v3");
37/// assert_eq!(config.url_for("nvidia/nemotron-ocr-v1"), "http://ocr.internal:8000/v1/infer");
38/// assert_eq!(config.timeout(), Duration::from_secs(180));
39/// // The key never appears in debug output.
40/// assert!(!format!("{config:?}").contains("nvapi"));
41/// ```
42#[derive(Clone)]
43pub struct NimCvConfig {
44 base_url: String,
45 api_key: Option<String>,
46 timeout: Duration,
47 requests_per_minute: u32,
48 max_inline_bytes: usize,
49 model_urls: BTreeMap<String, String>,
50 pub(crate) http: Option<reqwest::Client>,
51}
52
53impl std::fmt::Debug for NimCvConfig {
54 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
55 f.debug_struct("NimCvConfig")
56 .field("base_url", &self.base_url)
57 .field("api_key", &self.api_key.as_ref().map(|_| "<redacted>"))
58 .field("timeout", &self.timeout)
59 .field("requests_per_minute", &self.requests_per_minute)
60 .field("max_inline_bytes", &self.max_inline_bytes)
61 .field("model_urls", &self.model_urls)
62 .finish_non_exhaustive()
63 }
64}
65
66impl NimCvConfig {
67 /// Endpoints under `base_url`, such as `https://ai.api.nvidia.com/v1/cv`.
68 pub fn new(base_url: impl Into<String>) -> Self {
69 Self {
70 base_url: base_url.into(),
71 api_key: None,
72 timeout: DEFAULT_TIMEOUT,
73 requests_per_minute: DEFAULT_REQUESTS_PER_MINUTE,
74 max_inline_bytes: DEFAULT_MAX_INLINE_BYTES,
75 model_urls: BTreeMap::new(),
76 http: None,
77 }
78 }
79
80 /// Sends `Authorization: Bearer <key>`; a self-hosted NIM may need none.
81 pub fn with_api_key(mut self, key: impl Into<String>) -> Self {
82 self.api_key = Some(key.into());
83 self
84 }
85
86 /// Reads the key from `NVIDIA_API_KEY` when it is set and not empty.
87 pub fn with_api_key_from_env(mut self) -> Self {
88 if let Some(key) = std::env::var("NVIDIA_API_KEY").ok().filter(|k| !k.trim().is_empty()) {
89 self.api_key = Some(key);
90 }
91 self
92 }
93
94 /// Sets the client timeout; keep it above the gateway's 120 s.
95 pub fn with_timeout(mut self, timeout: Duration) -> Self {
96 self.timeout = timeout;
97 self
98 }
99
100 /// Sets the client-side rate limit, in requests per minute (at least one).
101 pub fn with_requests_per_minute(mut self, rpm: u32) -> Self {
102 self.requests_per_minute = rpm.max(1);
103 self
104 }
105
106 /// Sets the largest image, in encoded bytes, sent inline.
107 pub fn with_max_inline_bytes(mut self, bytes: usize) -> Self {
108 self.max_inline_bytes = bytes;
109 self
110 }
111
112 /// Calls `model` (`org/name`) at `url` instead of under the base URL.
113 pub fn with_model_url(mut self, model: impl Into<String>, url: impl Into<String>) -> Self {
114 self.model_urls.insert(model.into(), url.into());
115 self
116 }
117
118 /// Uses `client` for every request: a proxy, custom roots, or a test resolver. Its own
119 /// timeout applies instead of [`with_timeout`](Self::with_timeout)'s.
120 pub fn with_http_client(mut self, client: reqwest::Client) -> Self {
121 self.http = Some(client);
122 self
123 }
124
125 /// The URL `model` is called at.
126 pub fn url_for(&self, model: &str) -> String {
127 self.model_urls
128 .get(model)
129 .cloned()
130 .unwrap_or_else(|| format!("{}/{model}", self.base_url.trim_end_matches('/')))
131 }
132
133 /// The client timeout.
134 pub fn timeout(&self) -> Duration {
135 self.timeout
136 }
137
138 /// The client-side rate limit.
139 pub fn requests_per_minute(&self) -> u32 {
140 self.requests_per_minute
141 }
142
143 /// The inline image ceiling in bytes.
144 pub fn max_inline_bytes(&self) -> usize {
145 self.max_inline_bytes
146 }
147
148 pub(crate) fn api_key(&self) -> Option<&str> {
149 self.api_key.as_deref()
150 }
151}