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(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 (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 encode(request: &DecisionRequest) -> Result<Value> {
174 let model = request
175 .model
176 .as_ref()
177 .ok_or_else(|| LlmClientError::InvalidRequest {
178 message: "System One requires a selected model".into(),
179 })?;
180 let mut questions = serde_json::Map::new();
181 for (id, question) in &request.questions {
182 let (kind, criteria) = match &question.kind {
183 DecisionKind::Boolean {
184 true_description,
185 false_description,
186 } => {
187 let mut criteria = serde_json::Map::new();
188 for (key, description) in [("true", true_description), ("false", false_description)]
189 {
190 if let Some(description) = description {
191 criteria.insert(key.into(), description.clone());
192 }
193 }
194 ("noul", Value::Object(criteria))
195 }
196 DecisionKind::Choice { options } => {
197 let mut criteria = serde_json::Map::new();
198 for option in options {
199 let description = option.description.as_ref().unwrap_or(&Value::Null);
200 if criteria
201 .insert(option.id.clone(), description.clone())
202 .is_some()
203 {
204 return Err(LlmClientError::InvalidRequest {
205 message: format!("duplicate option {:?} in questions.{id}", option.id),
206 });
207 }
208 }
209 ("choice", Value::Object(criteria))
210 }
211 DecisionKind::Score { levels } => ("score", json!(levels)),
212 };
213 questions.insert(
214 id.clone(),
215 json!({
216 "type": kind, "instructions": question.instructions, "criteria": criteria,
217 }),
218 );
219 }
220 Ok(json!({"model": model, "state": request.input, "questions": questions}))
221}
222
223#[derive(Deserialize)]
224struct WireResponse {
225 id: Option<String>,
226 model: Option<ModelId>,
227 answers: BTreeMap<String, WireAnswer>,
228 #[serde(default)]
229 usage: Usage,
230}
231
232#[derive(Deserialize)]
233struct WireAnswer {
234 #[serde(flatten)]
235 value: WireValue,
236 confidence: Option<ProviderConfidence>,
237}
238
239#[derive(Deserialize)]
240#[serde(tag = "type", rename_all = "snake_case")]
241enum WireValue {
242 Noul {
243 noul: Probability,
244 },
245 Choice {
246 choice: String,
247 probabilities: Option<BTreeMap<String, Probability>>,
248 },
249 Score {
250 score: ScoreValue,
251 probabilities: Option<BTreeMap<String, Probability>>,
252 },
253}