Skip to main content

switchyard_llm_client/
openai_decisions.rs

1// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
2// SPDX-License-Identifier: Apache-2.0
3
4//! OpenAI Decisions 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 typed questions through OpenAI's Decisions API.
23pub struct OpenAiDecisionClient {
24    client: reqwest::Client,
25    endpoint: Url,
26    api_key: String,
27}
28
29impl OpenAiDecisionClient {
30    /// `endpoint` includes `/v1/decisions`. Each call makes one attempt, with
31    /// `timeout` covering both the request and 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: "OpenAI Decisions 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 OpenAiDecisionClient {
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), "OpenAI Decisions decision response");
86        let response: WireResponse =
87            serde_json::from_slice(&body).map_err(|source| LlmClientError::InvalidResponse {
88                source: Box::new(source),
89            })?;
90        let mut questions = request.questions;
91        let mut answers = BTreeMap::new();
92        for answer in response.answers {
93            let invalid = || {
94                LlmClientError::ResponseTranslation(format!(
95                    "OpenAI Decisions answer {:?} has an unexpected question name, kind, or value",
96                    answer.name,
97                ))
98            };
99            let question = questions.remove(&answer.name).ok_or_else(invalid)?;
100            let value = match (&question.kind, answer.value) {
101                (DecisionKind::Boolean { .. }, WireValue::Predicate { probability }) => {
102                    DecisionValue::Boolean(BooleanEstimate::ProbabilityTrue(probability))
103                }
104                (
105                    DecisionKind::Choice { options },
106                    WireValue::Choice {
107                        choice,
108                        probabilities,
109                    },
110                ) => {
111                    let count = probabilities.len();
112                    let probabilities: BTreeMap<_, _> = probabilities
113                        .into_iter()
114                        .map(|p| (p.value, p.probability))
115                        .collect();
116                    if count != options.len()
117                        || probabilities.len() != options.len()
118                        || !options.iter().any(|option| option.id == choice)
119                        || options
120                            .iter()
121                            .any(|option| !probabilities.contains_key(&option.id))
122                    {
123                        return Err(invalid());
124                    }
125                    DecisionValue::Choice {
126                        selected: choice,
127                        probabilities: Some(probabilities),
128                    }
129                }
130                (
131                    DecisionKind::Score { levels },
132                    WireValue::Score {
133                        score,
134                        probabilities,
135                    },
136                ) => {
137                    let mut probabilities = probabilities;
138                    probabilities.sort_by_key(|p| p.value);
139                    if levels.is_empty()
140                        || !(0.0..=(levels.len() - 1) as f64).contains(&score.0)
141                        || probabilities.len() != levels.len()
142                        || probabilities
143                            .iter()
144                            .enumerate()
145                            .any(|(index, p)| p.value != index)
146                    {
147                        return Err(invalid());
148                    }
149                    DecisionValue::Score {
150                        value: score,
151                        probabilities: Some(
152                            probabilities.into_iter().map(|p| p.probability).collect(),
153                        ),
154                    }
155                }
156                (_, WireValue::Refusal) => DecisionValue::Refusal,
157                _ => return Err(invalid()),
158            };
159            answers.insert(
160                answer.name,
161                DecisionAnswer {
162                    value,
163                    provider_confidence: answer.confidence,
164                },
165            );
166        }
167        if !questions.is_empty() {
168            return Err(LlmClientError::ResponseTranslation(
169                "OpenAI Decisions answer names do not match the requested question keys".into(),
170            ));
171        }
172        let usage = response.usage;
173        let cached = usage.input_tokens_details.cached_tokens;
174        let created = usage.input_tokens_details.cache_write_tokens;
175        Ok(DecisionResponse {
176            id: None,
177            model: Some(response.model),
178            answers,
179            usage: Usage {
180                input_tokens: Some(
181                    usage
182                        .input_tokens
183                        .saturating_sub(cached)
184                        .saturating_sub(created),
185                ),
186                cache: Usage::cache_details(Some(cached), Some(created)),
187                output_tokens: Some(usage.output_tokens),
188                total_tokens: Some(usage.total_tokens),
189                reasoning_tokens: Some(usage.output_tokens_details.reasoning_tokens),
190                ..Usage::default()
191            },
192        })
193    }
194}
195
196fn encode(request: &DecisionRequest) -> Result<Value> {
197    let model = request
198        .model
199        .as_ref()
200        .ok_or_else(|| LlmClientError::InvalidRequest {
201            message: "OpenAI Decisions requires a selected model".into(),
202        })?;
203    let questions: Vec<_> = request
204        .questions
205        .iter()
206        .map(|(name, question)| {
207            let mut wire = json!({"name": name, "instructions": text(&question.instructions)});
208            match &question.kind {
209                DecisionKind::Boolean {
210                    true_description,
211                    false_description,
212                } => {
213                    wire["type"] = json!("predicate");
214                    if true_description.is_some() || false_description.is_some() {
215                        wire["instructions"] = json!(
216                            json!({
217                                "instructions": question.instructions,
218                                "true": true_description, "false": false_description,
219                            })
220                            .to_string()
221                        );
222                    }
223                }
224                DecisionKind::Choice { options } => {
225                    wire["type"] = json!("choice");
226                    wire["choices"] = Value::Array(
227                        options
228                            .iter()
229                            .map(|option| {
230                                let mut choice = json!({"value": option.id});
231                                if let Some(description) = &option.description {
232                                    choice["description"] = json!(text(description));
233                                }
234                                choice
235                            })
236                            .collect(),
237                    );
238                }
239                DecisionKind::Score { levels } => {
240                    wire["type"] = json!("score");
241                    wire["levels"] = Value::Array(
242                        levels
243                            .iter()
244                            .map(|level| json!({"label": text(level)}))
245                            .collect(),
246                    );
247                }
248            }
249            wire
250        })
251        .collect();
252    // OpenAI Decisions accepts a string or its own message items. Sending the
253    // input as text avoids translating each message and tool block.
254    Ok(json!({"model": model, "input": text(&request.input), "questions": questions}))
255}
256
257// OpenAI requires text; retain structured IR content as JSON rather than dropping it.
258fn text(value: &Value) -> String {
259    value
260        .as_str()
261        .map(str::to_owned)
262        .unwrap_or_else(|| value.to_string())
263}
264
265#[derive(Deserialize)]
266struct WireResponse {
267    model: ModelId,
268    answers: Vec<WireAnswer>,
269    usage: WireUsage,
270}
271
272#[derive(Deserialize)]
273struct WireAnswer {
274    name: String,
275    #[serde(flatten)]
276    value: WireValue,
277    confidence: Option<ProviderConfidence>,
278}
279
280#[derive(Deserialize)]
281#[serde(tag = "type", rename_all = "snake_case")]
282enum WireValue {
283    Predicate {
284        probability: Probability,
285    },
286    Choice {
287        choice: String,
288        probabilities: Vec<WireProbability<String>>,
289    },
290    Score {
291        score: ScoreValue,
292        probabilities: Vec<WireProbability<usize>>,
293    },
294    Refusal,
295}
296
297#[derive(Deserialize)]
298struct WireProbability<T> {
299    value: T,
300    probability: Probability,
301}
302
303#[derive(Deserialize)]
304struct WireUsage {
305    input_tokens: u64,
306    output_tokens: u64,
307    total_tokens: u64,
308    input_tokens_details: InputTokenDetails,
309    output_tokens_details: OutputTokenDetails,
310}
311
312#[derive(Deserialize)]
313struct InputTokenDetails {
314    cached_tokens: u64,
315    cache_write_tokens: u64,
316}
317
318#[derive(Deserialize)]
319struct OutputTokenDetails {
320    reasoning_tokens: u64,
321}