Skip to main content

switchyard_llm_client/
system_one.rs

1// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Buffered System One calls using the provider-neutral decision IR.
5
6use std::collections::BTreeMap;
7use std::time::Duration;
8
9use async_trait::async_trait;
10use reqwest::{Url, header::HeaderValue};
11use serde::Deserialize;
12use serde_json::{Value, json};
13use switchyard_protocol::{
14    BooleanEstimate, DecisionAnswer, DecisionKind, DecisionRequest, DecisionResponse,
15    DecisionValue, ModelId, Probability, ProviderConfidence, RoutedDecisionClient, ScoreValue,
16    Usage,
17};
18
19use crate::client::convert_reqwest_error;
20use crate::{LlmClientError, Result, metrics};
21
22/// Serves decision requests through a System One endpoint, such as TypeSafe's Jev API.
23pub struct SystemOneClient {
24    client: reqwest::Client,
25    endpoint: Url,
26    api_key: String,
27}
28
29impl SystemOneClient {
30    /// `endpoint` is the full URL, including `/v1/systemone`. Each call makes one
31    /// attempt; `timeout` covers sending the request and reading the response body.
32    pub fn new(endpoint: Url, api_key: String, timeout: Duration) -> Result<Self> {
33        if HeaderValue::try_from(format!("Bearer {api_key}")).is_err() {
34            return Err(LlmClientError::Configuration {
35                message: "System One API key cannot be encoded as an HTTP header".into(),
36            });
37        }
38        let client = reqwest::Client::builder()
39            .timeout(timeout)
40            .redirect(reqwest::redirect::Policy::none())
41            .build()
42            .map_err(convert_reqwest_error)?;
43        Ok(Self {
44            client,
45            endpoint,
46            api_key,
47        })
48    }
49}
50
51#[async_trait]
52impl RoutedDecisionClient for SystemOneClient {
53    async fn call(&self, request: DecisionRequest) -> Result<DecisionResponse> {
54        let builder = self
55            .client
56            .post(self.endpoint.clone())
57            .bearer_auth(&self.api_key)
58            .json(&encode(&request)?);
59        let mut response = async {
60            let request = builder.build()?;
61            if let Some(body) = request.body().and_then(reqwest::Body::as_bytes) {
62                crate::payload_capture::record("request", || String::from_utf8_lossy(body));
63            }
64            self.client.execute(request).await
65        }
66        .await
67        .inspect_err(|_| metrics::record_upstream_attempt(None))
68        .map_err(convert_reqwest_error)?;
69        let status = response.status();
70        let headers = std::mem::take(response.headers_mut());
71        let body = response
72            .bytes()
73            .await
74            .inspect_err(|_| metrics::record_upstream_attempt(None))
75            .map_err(convert_reqwest_error)?;
76        metrics::record_upstream_attempt(Some(status.as_u16()));
77        if !status.is_success() {
78            return Err(LlmClientError::UpstreamHttp {
79                status,
80                body: String::from_utf8_lossy(&body).replace(&self.api_key, "[REDACTED]"),
81                headers: Box::new(headers),
82            });
83        }
84        crate::payload_capture::record("response", || String::from_utf8_lossy(&body));
85        tracing::trace!(body = %String::from_utf8_lossy(&body), "System One decision response");
86        let response: WireResponse =
87            serde_json::from_slice(&body).map_err(|source| LlmClientError::InvalidResponse {
88                source: Box::new(source),
89            })?;
90        if !response.answers.keys().eq(request.questions.keys()) {
91            return Err(LlmClientError::ResponseTranslation(
92                "System One answer keys do not match the requested question keys".into(),
93            ));
94        }
95        let answers = response
96            .answers
97            .into_iter()
98            .map(|(id, answer)| {
99                let value = match (request.questions.get(&id).map(|q| &q.kind), answer.value) {
100                    (Some(DecisionKind::Boolean { .. }), WireValue::Noul { noul }) => {
101                        DecisionValue::Boolean(BooleanEstimate::ProbabilityTrue(noul))
102                    }
103                    (
104                        Some(DecisionKind::Choice { options }),
105                        WireValue::Choice {
106                            choice,
107                            probabilities,
108                        },
109                    ) if options.iter().any(|option| option.id == choice) => {
110                        DecisionValue::Choice {
111                            selected: choice,
112                            probabilities,
113                        }
114                    }
115                    (
116                        Some(DecisionKind::Score { levels }),
117                        WireValue::Score {
118                            score,
119                            probabilities,
120                        },
121                    ) if !levels.is_empty()
122                        && (0.0..=(levels.len() - 1) as f64).contains(&score.0) =>
123                    {
124                        let probabilities = probabilities
125                            .map(|mut probabilities| {
126                                let invalid_rubric = || {
127                                    LlmClientError::ResponseTranslation(format!(
128                                        "score probabilities for {id:?} do not match its rubric"
129                                    ))
130                                };
131                                if probabilities.len() != levels.len() {
132                                    return Err(invalid_rubric());
133                                }
134                                // JSON keys are strings; order probabilities by the request's rubric.
135                                (0..levels.len())
136                                    .map(|index| {
137                                        probabilities
138                                            .remove(&index.to_string())
139                                            .ok_or_else(invalid_rubric)
140                                    })
141                                    .collect()
142                            })
143                            .transpose()?;
144                        DecisionValue::Score {
145                            value: score,
146                            probabilities,
147                        }
148                    }
149                    _ => {
150                        return Err(LlmClientError::ResponseTranslation(format!(
151                            "answer {id:?} has an unexpected question ID, kind, or value"
152                        )));
153                    }
154                };
155                Ok((
156                    id,
157                    DecisionAnswer {
158                        value,
159                        provider_confidence: answer.confidence,
160                    },
161                ))
162            })
163            .collect::<Result<_>>()?;
164        Ok(DecisionResponse {
165            id: response.id,
166            model: response.model,
167            answers,
168            usage: response.usage,
169        })
170    }
171}
172
173fn numbered_id(id: &str) -> Option<(&str, usize)> {
174    let prefix = id.trim_end_matches(|c: char| c.is_ascii_digit());
175    Some((prefix, id[prefix.len()..].parse().ok()?))
176}
177
178fn encode(request: &DecisionRequest) -> Result<Value> {
179    let model = request
180        .model
181        .as_ref()
182        .ok_or_else(|| LlmClientError::InvalidRequest {
183            message: "System One requires a selected model".into(),
184        })?;
185    let mut questions = Vec::with_capacity(request.questions.len());
186    for (id, question) in &request.questions {
187        let (kind, criteria) = match &question.kind {
188            DecisionKind::Boolean {
189                true_description,
190                false_description,
191            } => {
192                let mut criteria = serde_json::Map::new();
193                for (key, description) in [("true", true_description), ("false", false_description)]
194                {
195                    if let Some(description) = description {
196                        criteria.insert(key.into(), description.clone());
197                    }
198                }
199                ("noul", Value::Object(criteria))
200            }
201            DecisionKind::Choice { options } => {
202                let mut criteria = serde_json::Map::new();
203                for option in options {
204                    let description = option.description.as_ref().unwrap_or(&Value::Null);
205                    if criteria
206                        .insert(option.id.clone(), description.clone())
207                        .is_some()
208                    {
209                        return Err(LlmClientError::InvalidRequest {
210                            message: format!("duplicate option {:?} in questions.{id}", option.id),
211                        });
212                    }
213                }
214                ("choice", Value::Object(criteria))
215            }
216            DecisionKind::Score { levels } => ("score", json!(levels)),
217        };
218        let mut wire = json!({"type":kind, "instructions":question.instructions});
219        if kind != "noul" || criteria.as_object().is_some_and(|c| !c.is_empty()) {
220            wire["criteria"] = criteria;
221        }
222        questions.push((id.clone(), wire));
223    }
224    // Indexed batches retain numeric order on the wire, including after question 9.
225    if let Some((prefix, _)) = questions.first().and_then(|(id, _)| numbered_id(id))
226        && questions
227            .iter()
228            .all(|(id, _)| numbered_id(id).is_some_and(|(p, _)| p == prefix))
229    {
230        questions.sort_by_key(|(id, _)| numbered_id(id).map(|(_, n)| n));
231    }
232    let questions: serde_json::Map<_, _> = questions.into_iter().collect();
233    Ok(json!({"model": model, "state": request.input, "questions": questions}))
234}
235
236#[derive(Deserialize)]
237struct WireResponse {
238    id: Option<String>,
239    model: Option<ModelId>,
240    answers: BTreeMap<String, WireAnswer>,
241    #[serde(default)]
242    usage: Usage,
243}
244
245#[derive(Deserialize)]
246struct WireAnswer {
247    #[serde(flatten)]
248    value: WireValue,
249    confidence: Option<ProviderConfidence>,
250}
251
252#[derive(Deserialize)]
253#[serde(tag = "type", rename_all = "snake_case")]
254enum WireValue {
255    Noul {
256        noul: Probability,
257    },
258    Choice {
259        choice: String,
260        probabilities: Option<BTreeMap<String, Probability>>,
261    },
262    Score {
263        score: ScoreValue,
264        probabilities: Option<BTreeMap<String, Probability>>,
265    },
266}
267
268#[cfg(test)]
269mod tests {
270    use super::*;
271    use switchyard_protocol::DecisionQuestion;
272
273    #[test]
274    fn numbered_questions_keep_numeric_order_and_optional_criteria() {
275        let request = DecisionRequest {
276            model: Some("selector".into()),
277            input: json!("task"),
278            questions: (0..12)
279                .map(|i| {
280                    (
281                        format!("pick_{i}"),
282                        DecisionQuestion {
283                            instructions: json!("Choose"),
284                            kind: DecisionKind::Boolean {
285                                true_description: (i == 2).then(|| json!("relevant")),
286                                false_description: None,
287                            },
288                        },
289                    )
290                })
291                .collect(),
292        };
293        let wire = serde_json::to_string(&encode(&request).unwrap()).unwrap();
294        let positions: Vec<_> = (0..12)
295            .map(|i| wire.find(&format!(r#""pick_{i}":"#)).unwrap())
296            .collect();
297        assert!(positions.windows(2).all(|p| p[0] < p[1]));
298        let parsed: Value = serde_json::from_str(&wire).unwrap();
299        assert!(parsed["questions"]["pick_0"].get("criteria").is_none());
300        assert_eq!(
301            parsed["questions"]["pick_2"]["criteria"],
302            json!({"true":"relevant"})
303        );
304    }
305}