Skip to main content

gemini_adk_rs/decision/
gateway.rs

1//! Vercel AI Gateway's decision API (`POST /v1/evaluate`).
2
3use std::time::{Duration, Instant};
4
5use async_trait::async_trait;
6use serde_json::{Map, Value, json};
7
8use super::{
9    Answer, DecisionModel, DecisionRequest, DecisionResponse, DecisionUsage, FallbackWhen,
10};
11use crate::llm::LlmError;
12use crate::utils::text::truncate_with_marker;
13
14/// A decision model served by Vercel AI Gateway, such as TypeSafe AI's Jev.
15///
16/// Authenticates with `AI_GATEWAY_API_KEY`, or with a `VERCEL_OIDC_TOKEN`
17/// (what `vercel env pull` writes and what deployments on Vercel receive).
18///
19/// ```no_run
20/// use gemini_adk_rs::decision::{DecisionModel, DecisionRequest, GatewayDecisionModel, Question};
21/// use serde_json::json;
22///
23/// # async fn run() -> Result<(), gemini_adk_rs::llm::LlmError> {
24/// let jev = GatewayDecisionModel::from_env()?;
25/// let response = jev
26///     .decide(DecisionRequest::new(
27///         json!({ "caller": "Yes, please book it." }),
28///         [("confirmed", Question::boolean("Did the caller agree to book?"))],
29///     ))
30///     .await?;
31/// println!("{:?} in {:?}", response.answers["confirmed"], response.latency);
32/// # Ok(()) }
33/// ```
34#[derive(Clone)]
35pub struct GatewayDecisionModel {
36    client: reqwest::Client,
37    base_url: String,
38    model: String,
39    token: String,
40    timeout: Duration,
41    options: Value,
42}
43
44impl std::fmt::Debug for GatewayDecisionModel {
45    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
46        // Never print the token.
47        f.debug_struct("GatewayDecisionModel")
48            .field("base_url", &self.base_url)
49            .field("model", &self.model)
50            .field("timeout", &self.timeout)
51            .field("options", &self.options)
52            .finish_non_exhaustive()
53    }
54}
55
56impl GatewayDecisionModel {
57    /// AI Gateway's address.
58    pub const DEFAULT_BASE_URL: &'static str = "https://ai-gateway.vercel.sh";
59    /// TypeSafe AI's Jev, the default model.
60    pub const JEV: &'static str = "typesafe-ai/jev";
61    /// How long a decision may take before the call fails.
62    pub const DEFAULT_TIMEOUT: Duration = Duration::from_secs(10);
63
64    /// A client for `model`, authenticating with `token`.
65    pub fn new(model: impl Into<String>, token: impl Into<String>) -> Self {
66        Self {
67            client: reqwest::Client::new(),
68            base_url: Self::DEFAULT_BASE_URL.to_string(),
69            model: model.into(),
70            token: token.into(),
71            timeout: Self::DEFAULT_TIMEOUT,
72            options: Value::Null,
73        }
74    }
75
76    /// A client configured from the environment:
77    ///
78    /// | Variable | Use |
79    /// |---|---|
80    /// | `AI_GATEWAY_API_KEY`, else `VERCEL_OIDC_TOKEN` | Credential (required) |
81    /// | `AI_GATEWAY_DECISION_MODEL` | Model, default `typesafe-ai/jev` |
82    /// | `AI_GATEWAY_BASE_URL` | Gateway address, default `https://ai-gateway.vercel.sh` |
83    pub fn from_env() -> Result<Self, LlmError> {
84        let var = |name: &str| std::env::var(name).ok().filter(|v| !v.trim().is_empty());
85        let token = var("AI_GATEWAY_API_KEY")
86            .or_else(|| var("VERCEL_OIDC_TOKEN"))
87            .ok_or_else(|| {
88                LlmError::Auth(
89                    "no AI Gateway credential: set AI_GATEWAY_API_KEY (for example in \
90                     .env.local), or run `vercel env pull` for a VERCEL_OIDC_TOKEN"
91                        .into(),
92                )
93            })?;
94        let model = var("AI_GATEWAY_DECISION_MODEL").unwrap_or_else(|| Self::JEV.to_string());
95        let mut this = Self::new(model, token);
96        if let Some(base) = var("AI_GATEWAY_BASE_URL") {
97            this.base_url = base.trim_end_matches('/').to_string();
98        }
99        Ok(this)
100    }
101
102    /// Use another Gateway address (a proxy, or a local server in tests).
103    #[must_use]
104    pub fn with_base_url(mut self, base_url: impl Into<String>) -> Self {
105        self.base_url = base_url.into().trim_end_matches('/').to_string();
106        self
107    }
108
109    /// Fail a decision that takes longer than `timeout`.
110    #[must_use]
111    pub fn with_timeout(mut self, timeout: Duration) -> Self {
112        self.timeout = timeout;
113        self
114    }
115
116    /// Ask the Gateway to route only to providers with zero data retention.
117    #[must_use]
118    pub fn zero_data_retention(mut self, on: bool) -> Self {
119        merge_json(
120            &mut self.options,
121            &object("gateway", json!({ "zeroDataRetention": on })),
122        );
123        self
124    }
125
126    /// Restrict which providers may serve the model.
127    #[must_use]
128    pub fn only_providers<S: Into<String>>(
129        mut self,
130        providers: impl IntoIterator<Item = S>,
131    ) -> Self {
132        let only: Vec<String> = providers.into_iter().map(Into::into).collect();
133        merge_json(
134            &mut self.options,
135            &object("gateway", json!({ "only": only })),
136        );
137        self
138    }
139
140    /// Rerun the decision with `model` when `when` matches the primary
141    /// answers (a Gateway decision fallback). `model` may be a language
142    /// model, which answers through structured output and reports no
143    /// confidence. Both stages are billed and their latencies add.
144    #[must_use]
145    pub fn fallback(mut self, model: impl Into<String>, when: FallbackWhen) -> Self {
146        let entry = json!({ "model": model.into(), "when": when.to_value() });
147        merge_json(
148            &mut self.options,
149            &object("gateway", json!({ "models": [entry] })),
150        );
151        self
152    }
153
154    /// The request body for `request`.
155    pub fn body(&self, request: &DecisionRequest) -> Value {
156        let mut body = json!({
157            "model": self.model,
158            "state": request.state,
159            "questions": request.questions,
160        });
161        let mut options = self.options.clone();
162        if let Some(extra) = &request.provider_options {
163            merge_json(&mut options, extra);
164        }
165        if !options.is_null() {
166            body["providerOptions"] = options;
167        }
168        body
169    }
170
171    /// Read a `/v1/evaluate` response.
172    pub fn parse(status: u16, body: &str, latency: Duration) -> Result<DecisionResponse, LlmError> {
173        let value: Value = serde_json::from_str(body).map_err(|e| LlmError::Api {
174            status,
175            message: format!(
176                "unreadable response ({e}): {}",
177                truncate_with_marker(body, 300, "…")
178            ),
179        })?;
180        if !(200..300).contains(&status) {
181            let message = value["error"]["message"]
182                .as_str()
183                .map_or_else(|| truncate_with_marker(body, 300, "…"), str::to_string);
184            return Err(match status {
185                401 => LlmError::Auth(format!(
186                    "AI Gateway rejected the credential: {message}. Check AI_GATEWAY_API_KEY"
187                )),
188                _ => LlmError::Api { status, message },
189            });
190        }
191        let answers = value["answers"]
192            .as_object()
193            .ok_or_else(|| LlmError::Api {
194                status,
195                message: format!(
196                    "response has no answers: {}",
197                    truncate_with_marker(body, 300, "…")
198                ),
199            })?
200            .iter()
201            .map(|(k, v)| (k.clone(), Answer::from_value(v.clone())))
202            .collect();
203        let usage = value.get("usage").map(|u| DecisionUsage {
204            input_tokens: u["inputTokens"].as_u64().unwrap_or(0),
205            output_tokens: u["outputTokens"].as_u64().unwrap_or(0),
206        });
207        let gateway = &value["providerMetadata"]["gateway"];
208        let fallback_triggered_by = gateway["routing"]["modelAttempts"]
209            .as_array()
210            .into_iter()
211            .flatten()
212            .filter_map(|attempt| attempt["triggeredBy"].as_array())
213            .flatten()
214            .map(|t| {
215                (
216                    t["question"].as_str().unwrap_or_default().to_string(),
217                    t["reason"].as_str().unwrap_or_default().to_string(),
218                )
219            })
220            .collect();
221        Ok(DecisionResponse {
222            model: value["model"].as_str().unwrap_or_default().to_string(),
223            answers,
224            usage,
225            cost: gateway["cost"].as_str().map(str::to_string),
226            fallback_triggered_by,
227            latency,
228            provider_metadata: value["providerMetadata"].clone(),
229        })
230    }
231}
232
233/// Merge `overlay` into `base`, objects recursively; other values replace.
234fn merge_json(base: &mut Value, overlay: &Value) {
235    match (base, overlay) {
236        (Value::Object(b), Value::Object(o)) => {
237            for (k, v) in o {
238                merge_json(b.entry(k.clone()).or_insert(Value::Null), v);
239            }
240        }
241        (b, o) => *b = o.clone(),
242    }
243}
244
245/// A JSON object with one key, for building nested options.
246fn object(key: &str, value: Value) -> Value {
247    let mut m = Map::new();
248    m.insert(key.to_string(), value);
249    Value::Object(m)
250}
251
252#[async_trait]
253impl DecisionModel for GatewayDecisionModel {
254    fn model_id(&self) -> &str {
255        &self.model
256    }
257
258    async fn decide(&self, request: DecisionRequest) -> Result<DecisionResponse, LlmError> {
259        for (id, question) in &request.questions {
260            question
261                .validate()
262                .map_err(|e| LlmError::Config(format!("question '{id}': {e}")))?;
263        }
264        let started = Instant::now();
265        let response = self
266            .client
267            .post(format!("{}/v1/evaluate", self.base_url))
268            .bearer_auth(&self.token)
269            .timeout(self.timeout)
270            .json(&self.body(&request))
271            .send()
272            .await
273            .map_err(|e| LlmError::Transport(e.to_string()))?;
274        let status = response.status().as_u16();
275        let text = response
276            .text()
277            .await
278            .map_err(|e| LlmError::Transport(e.to_string()))?;
279        let latency = started.elapsed();
280        let parsed = Self::parse(status, &text, latency);
281        match &parsed {
282            Ok(r) => tracing::info!(
283                model = %r.model,
284                ms = latency.as_millis() as u64,
285                questions = r.answers.len(),
286                fallback = !r.fallback_triggered_by.is_empty(),
287                "decision"
288            ),
289            Err(e) => {
290                tracing::warn!(model = %self.model, ms = latency.as_millis() as u64, "decision failed: {e}");
291            }
292        }
293        parsed
294    }
295}
296
297#[cfg(test)]
298mod tests {
299    use super::*;
300    use crate::decision::Question;
301
302    fn jev() -> GatewayDecisionModel {
303        GatewayDecisionModel::new(GatewayDecisionModel::JEV, "test-token")
304    }
305
306    #[test]
307    fn the_body_carries_state_questions_and_options() {
308        let model = jev().zero_data_retention(true).fallback(
309            "google/gemini-3.8-flash",
310            FallbackWhen::ProbabilityBetween {
311                question: Some("confirmed".into()),
312                low: 0.3,
313                high: 0.8,
314            },
315        );
316        let mut request = DecisionRequest::new(
317            json!({ "caller": "yes" }),
318            [("confirmed", Question::boolean("Agreed?"))],
319        );
320        request.provider_options = Some(json!({ "gateway": { "only": ["typesafe-ai"] } }));
321        assert_eq!(
322            model.body(&request),
323            json!({
324                "model": "typesafe-ai/jev",
325                "state": { "caller": "yes" },
326                "questions": { "confirmed": { "type": "boolean", "instructions": "Agreed?" } },
327                "providerOptions": { "gateway": {
328                    "zeroDataRetention": true,
329                    "only": ["typesafe-ai"],
330                    "models": [ { "model": "google/gemini-3.8-flash",
331                                  "when": { "question": "confirmed", "probabilityBetween": [0.3, 0.8] } } ]
332                } }
333            })
334        );
335        assert!(
336            jev().body(&request).get("providerOptions").is_some(),
337            "per-request options alone"
338        );
339        let plain = DecisionRequest::new(json!("x"), [("a", Question::boolean("A?"))]);
340        assert!(jev().body(&plain).get("providerOptions").is_none());
341    }
342
343    #[test]
344    fn a_documented_response_is_read() {
345        let body = r#"{
346          "model": "typesafe-ai/jev",
347          "answers": { "refund": { "type": "boolean", "probability": 0.98 } },
348          "usage": { "inputTokens": 275, "outputTokens": 20 },
349          "providerMetadata": { "gateway": {
350            "routing": { "originalModelId": "typesafe-ai/jev", "finalProvider": "typesafe-ai" },
351            "cost": "0.00001155", "generationId": "gen_1" } }
352        }"#;
353        let r = GatewayDecisionModel::parse(200, body, Duration::from_millis(120)).unwrap();
354        assert_eq!(r.model, "typesafe-ai/jev");
355        assert_eq!(r.answers["refund"].probability(), Some(0.98));
356        assert_eq!(
357            r.usage,
358            Some(DecisionUsage {
359                input_tokens: 275,
360                output_tokens: 20
361            })
362        );
363        assert_eq!(r.cost.as_deref(), Some("0.00001155"));
364        assert!(r.fallback_triggered_by.is_empty());
365    }
366
367    #[test]
368    fn a_triggered_fallback_is_reported() {
369        let body = r#"{
370          "model": "openai/gpt-6-astra",
371          "answers": { "intent": { "type": "choice", "choice": "billing" } },
372          "providerMetadata": { "gateway": { "routing": { "modelAttempts": [
373            { "canonicalSlug": "typesafe-ai/jev", "success": true },
374            { "canonicalSlug": "openai/gpt-6-astra", "success": true,
375              "triggeredBy": [ { "question": "intent", "reason": "confidence_below" } ] }
376          ] } } }
377        }"#;
378        let r = GatewayDecisionModel::parse(200, body, Duration::ZERO).unwrap();
379        assert_eq!(r.model, "openai/gpt-6-astra");
380        assert_eq!(
381            r.fallback_triggered_by,
382            vec![("intent".to_string(), "confidence_below".to_string())]
383        );
384        assert_eq!(
385            r.answers["intent"].certainty(),
386            None,
387            "a language model reports none"
388        );
389    }
390
391    #[test]
392    fn errors_keep_the_gateway_message() {
393        let restricted = r#"{"error":{"message":"Free tier users do not have access to this model.","type":"no_providers_available"}}"#;
394        match GatewayDecisionModel::parse(403, restricted, Duration::ZERO) {
395            Err(LlmError::Api {
396                status: 403,
397                message,
398            }) => {
399                assert!(message.contains("Free tier"), "{message}");
400            }
401            other => panic!("{other:?}"),
402        }
403        let auth = r#"{"error":{"message":"Authentication failed","type":"authentication_error"}}"#;
404        assert!(matches!(
405            GatewayDecisionModel::parse(401, auth, Duration::ZERO),
406            Err(LlmError::Auth(_))
407        ));
408        let busy = GatewayDecisionModel::parse(503, "upstream busy", Duration::ZERO).unwrap_err();
409        assert!(busy.is_retryable(), "{busy:?}");
410    }
411
412    #[test]
413    fn provider_options_merge_recursively() {
414        let mut base = json!({ "gateway": { "zeroDataRetention": true, "only": ["typesafe-ai"] } });
415        merge_json(
416            &mut base,
417            &json!({ "gateway": { "only": ["digitalocean"] }, "openai": { "x": 1 } }),
418        );
419        assert_eq!(
420            base,
421            json!({ "gateway": { "zeroDataRetention": true, "only": ["digitalocean"] }, "openai": { "x": 1 } })
422        );
423    }
424
425    #[test]
426    fn the_token_is_never_printed() {
427        let printed = format!("{:?}", jev());
428        assert!(!printed.contains("test-token"), "{printed}");
429    }
430
431    #[tokio::test]
432    async fn an_invalid_question_fails_before_the_call() {
433        let none: [(&str, &str); 0] = [];
434        let err = jev()
435            .with_base_url("http://127.0.0.1:9")
436            .decide(DecisionRequest::new(
437                json!("x"),
438                [("pick", Question::choice("Pick.", none))],
439            ))
440            .await
441            .unwrap_err();
442        assert!(matches!(err, LlmError::Config(_)), "{err:?}");
443    }
444
445    #[tokio::test]
446    async fn a_call_reaches_the_gateway_and_reads_the_answers() {
447        use tokio::io::{AsyncReadExt, AsyncWriteExt};
448        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
449        let addr = listener.local_addr().unwrap();
450        let server = tokio::spawn(async move {
451            let (mut socket, _) = listener.accept().await.unwrap();
452            let mut seen = Vec::new();
453            let mut buf = [0u8; 4096];
454            // Read until the JSON body has arrived.
455            while !String::from_utf8_lossy(&seen).contains("\"questions\"") {
456                let n = socket.read(&mut buf).await.unwrap();
457                if n == 0 {
458                    break;
459                }
460                seen.extend_from_slice(&buf[..n]);
461            }
462            let body = r#"{"model":"typesafe-ai/jev","answers":{"confirmed":{"type":"boolean","probability":0.93}}}"#;
463            let reply = format!(
464                "HTTP/1.1 200 OK\r\ncontent-type: application/json\r\ncontent-length: {}\r\nconnection: close\r\n\r\n{body}",
465                body.len()
466            );
467            socket.write_all(reply.as_bytes()).await.unwrap();
468            String::from_utf8_lossy(&seen).to_string()
469        });
470        let model = jev().with_base_url(format!("http://{addr}"));
471        let response = model
472            .decide(DecisionRequest::new(
473                json!("Caller: yes"),
474                [("confirmed", Question::boolean("Agreed?"))],
475            ))
476            .await
477            .unwrap();
478        assert_eq!(response.answers["confirmed"].probability(), Some(0.93));
479        let request = server.await.unwrap();
480        assert!(request.starts_with("POST /v1/evaluate"), "{request}");
481        assert!(
482            request
483                .to_lowercase()
484                .contains("authorization: bearer test-token"),
485            "{request}"
486        );
487    }
488}