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) => {
157                    return Err(LlmClientError::ResponseTranslation(format!(
158                        "OpenAI Decisions refused question {:?}",
159                        answer.name,
160                    )));
161                }
162                _ => return Err(invalid()),
163            };
164            answers.insert(
165                answer.name,
166                DecisionAnswer {
167                    value,
168                    provider_confidence: answer.confidence,
169                },
170            );
171        }
172        if !questions.is_empty() {
173            return Err(LlmClientError::ResponseTranslation(
174                "OpenAI Decisions answer names do not match the requested question keys".into(),
175            ));
176        }
177        let usage = response.usage;
178        let cached = usage.input_tokens_details.cached_tokens;
179        let created = usage.input_tokens_details.cache_write_tokens;
180        Ok(DecisionResponse {
181            id: None,
182            model: Some(response.model),
183            answers,
184            usage: Usage {
185                input_tokens: Some(
186                    usage
187                        .input_tokens
188                        .saturating_sub(cached)
189                        .saturating_sub(created),
190                ),
191                cache: Usage::cache_details(Some(cached), Some(created)),
192                output_tokens: Some(usage.output_tokens),
193                total_tokens: Some(usage.total_tokens),
194                reasoning_tokens: Some(usage.output_tokens_details.reasoning_tokens),
195                ..Usage::default()
196            },
197        })
198    }
199}
200
201fn encode(request: &DecisionRequest) -> Result<Value> {
202    let model = request
203        .model
204        .as_ref()
205        .ok_or_else(|| LlmClientError::InvalidRequest {
206            message: "OpenAI Decisions requires a selected model".into(),
207        })?;
208    let questions: Vec<_> = request
209        .questions
210        .iter()
211        .map(|(name, question)| {
212            let mut wire = json!({"name": name, "instructions": text(&question.instructions)});
213            match &question.kind {
214                DecisionKind::Boolean {
215                    true_description,
216                    false_description,
217                } => {
218                    wire["type"] = json!("predicate");
219                    if true_description.is_some() || false_description.is_some() {
220                        wire["instructions"] = json!(
221                            json!({
222                                "instructions": question.instructions,
223                                "true": true_description, "false": false_description,
224                            })
225                            .to_string()
226                        );
227                    }
228                }
229                DecisionKind::Choice { options } => {
230                    wire["type"] = json!("choice");
231                    wire["choices"] = Value::Array(
232                        options
233                            .iter()
234                            .map(|option| {
235                                let mut choice = json!({"value": option.id});
236                                if let Some(description) = &option.description {
237                                    choice["description"] = json!(text(description));
238                                }
239                                choice
240                            })
241                            .collect(),
242                    );
243                }
244                DecisionKind::Score { levels } => {
245                    wire["type"] = json!("score");
246                    wire["levels"] = Value::Array(
247                        levels
248                            .iter()
249                            .map(|level| json!({"label": text(level)}))
250                            .collect(),
251                    );
252                }
253            }
254            wire
255        })
256        .collect();
257    // OpenAI Decisions accepts a string or its own message items. Sending the
258    // input as text avoids translating each message and tool block.
259    Ok(json!({"model": model, "input": text(&request.input), "questions": questions}))
260}
261
262// OpenAI requires text; retain structured IR content as JSON rather than dropping it.
263fn text(value: &Value) -> String {
264    value
265        .as_str()
266        .map(str::to_owned)
267        .unwrap_or_else(|| value.to_string())
268}
269
270#[derive(Deserialize)]
271struct WireResponse {
272    model: ModelId,
273    answers: Vec<WireAnswer>,
274    usage: WireUsage,
275}
276
277#[derive(Deserialize)]
278struct WireAnswer {
279    name: String,
280    #[serde(flatten)]
281    value: WireValue,
282    confidence: Option<ProviderConfidence>,
283}
284
285#[derive(Deserialize)]
286#[serde(tag = "type", rename_all = "snake_case")]
287enum WireValue {
288    Predicate {
289        probability: Probability,
290    },
291    Choice {
292        choice: String,
293        probabilities: Vec<WireProbability<String>>,
294    },
295    Score {
296        score: ScoreValue,
297        probabilities: Vec<WireProbability<usize>>,
298    },
299    Refusal,
300}
301
302#[derive(Deserialize)]
303struct WireProbability<T> {
304    value: T,
305    probability: Probability,
306}
307
308#[derive(Deserialize)]
309struct WireUsage {
310    input_tokens: u64,
311    output_tokens: u64,
312    total_tokens: u64,
313    input_tokens_details: InputTokenDetails,
314    output_tokens_details: OutputTokenDetails,
315}
316
317#[derive(Deserialize)]
318struct InputTokenDetails {
319    cached_tokens: u64,
320    cache_write_tokens: u64,
321}
322
323#[derive(Deserialize)]
324struct OutputTokenDetails {
325    reasoning_tokens: u64,
326}