1use 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
22pub struct SystemOneClient {
24 client: reqwest::Client,
25 endpoint: Url,
26 api_key: String,
27}
28
29impl SystemOneClient {
30 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(_), WireValue::Refusal) => DecisionValue::Refusal,
101 (Some(DecisionKind::Boolean { .. }), WireValue::Noul { noul }) => {
102 DecisionValue::Boolean(BooleanEstimate::ProbabilityTrue(noul))
103 }
104 (
105 Some(DecisionKind::Choice { options }),
106 WireValue::Choice {
107 choice,
108 probabilities,
109 },
110 ) if options.iter().any(|option| option.id == choice) => {
111 DecisionValue::Choice {
112 selected: choice,
113 probabilities,
114 }
115 }
116 (
117 Some(DecisionKind::Score { levels }),
118 WireValue::Score {
119 score,
120 probabilities,
121 },
122 ) if !levels.is_empty()
123 && (0.0..=(levels.len() - 1) as f64).contains(&score.0) =>
124 {
125 let probabilities = probabilities
126 .map(|mut probabilities| {
127 let invalid_rubric = || {
128 LlmClientError::ResponseTranslation(format!(
129 "score probabilities for {id:?} do not match its rubric"
130 ))
131 };
132 if probabilities.len() != levels.len() {
133 return Err(invalid_rubric());
134 }
135 (0..levels.len())
137 .map(|index| {
138 probabilities
139 .remove(&index.to_string())
140 .ok_or_else(invalid_rubric)
141 })
142 .collect()
143 })
144 .transpose()?;
145 DecisionValue::Score {
146 value: score,
147 probabilities,
148 }
149 }
150 _ => {
151 return Err(LlmClientError::ResponseTranslation(format!(
152 "answer {id:?} has an unexpected question ID, kind, or value"
153 )));
154 }
155 };
156 Ok((
157 id,
158 DecisionAnswer {
159 value,
160 provider_confidence: answer.confidence,
161 },
162 ))
163 })
164 .collect::<Result<_>>()?;
165 Ok(DecisionResponse {
166 id: response.id,
167 model: response.model,
168 answers,
169 usage: response.usage,
170 })
171 }
172}
173
174fn encode(request: &DecisionRequest) -> Result<Value> {
175 let model = request
176 .model
177 .as_ref()
178 .ok_or_else(|| LlmClientError::InvalidRequest {
179 message: "System One requires a selected model".into(),
180 })?;
181 let mut questions = serde_json::Map::new();
182 for (id, question) in &request.questions {
183 let (kind, criteria) = match &question.kind {
184 DecisionKind::Boolean {
185 true_description,
186 false_description,
187 } => {
188 let mut criteria = serde_json::Map::new();
189 for (key, description) in [("true", true_description), ("false", false_description)]
190 {
191 if let Some(description) = description {
192 criteria.insert(key.into(), description.clone());
193 }
194 }
195 ("noul", Value::Object(criteria))
196 }
197 DecisionKind::Choice { options } => {
198 let mut criteria = serde_json::Map::new();
199 for option in options {
200 let description = option.description.as_ref().unwrap_or(&Value::Null);
201 if criteria
202 .insert(option.id.clone(), description.clone())
203 .is_some()
204 {
205 return Err(LlmClientError::InvalidRequest {
206 message: format!("duplicate option {:?} in questions.{id}", option.id),
207 });
208 }
209 }
210 ("choice", Value::Object(criteria))
211 }
212 DecisionKind::Score { levels } => ("score", json!(levels)),
213 };
214 questions.insert(
215 id.clone(),
216 json!({
217 "type": kind, "instructions": question.instructions, "criteria": criteria,
218 }),
219 );
220 }
221 Ok(json!({"model": model, "state": request.input, "questions": questions}))
222}
223
224#[derive(Deserialize)]
225struct WireResponse {
226 id: Option<String>,
227 model: Option<ModelId>,
228 answers: BTreeMap<String, WireAnswer>,
229 #[serde(default)]
230 usage: Usage,
231}
232
233#[derive(Deserialize)]
234struct WireAnswer {
235 #[serde(flatten)]
236 value: WireValue,
237 confidence: Option<ProviderConfidence>,
238}
239
240#[derive(Deserialize)]
241#[serde(tag = "type", rename_all = "snake_case")]
242enum WireValue {
243 Refusal,
244 Noul {
245 noul: Probability,
246 },
247 Choice {
248 choice: String,
249 probabilities: Option<BTreeMap<String, Probability>>,
250 },
251 Score {
252 score: ScoreValue,
253 probabilities: Option<BTreeMap<String, Probability>>,
254 },
255}