switchyard-llm-client 0.3.0

HTTP LLM client speaking Switchyard's neutral IR directly
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
// SPDX-License-Identifier: Apache-2.0

//! Per-provider backend configuration: wire format, upstream URL, and auth.

use std::time::Duration;
use std::{collections::BTreeMap, fmt};

use reqwest::RequestBuilder;
use reqwest::header::HeaderValue;
use serde_json::Value;
use switchyard_protocol::{Metadata, WireFormat};

use crate::error::{LlmClientError, Result, is_overflow_body};

const ANTHROPIC_VERSION: &str = "2023-06-01";

/// Default number of retries for server-configured upstream calls.
pub const DEFAULT_MAX_RETRIES: u32 = 2;

// Canonical OpenAI phrase plus NVIDIA/LiteLLM wrap variants. Adding a new
// provider-wrap is a one-line entry here, not a fork of the parsing logic.
const OPENAI_OVERFLOW_PHRASES: &[&str] = &[
    "maximum context length",
    "context length exceeded",
    "context window",
    "context length is only",
    "please reduce the length of the input",
    "exceeds the maximum allowed input length",
    "exceeds the maximum allowed length",
    "is longer than the model's context length",
];

// Anthropic has no structured `error.code`, so detection is phrase-based only.
const ANTHROPIC_OVERFLOW_PHRASES: &[&str] = &[
    "prompt is too long",
    "maximum number of tokens",
    "context window",
    "context length",
];

/// Shared HTTP configuration for one upstream backend.
#[derive(Clone)]
pub struct HttpBackendConfig {
    /// Base URL of the provider API (e.g. `https://api.openai.com/v1`).
    pub base_url: String,
    /// API key for the provider, loaded by the caller. `None` sends no configured auth.
    pub api_key: Option<String>,
    /// Whether this backend forwards the caller's provider credential and application headers.
    ///
    /// All backends reachable through a forwarding route must use the same provider.
    pub forward_auth: bool,
    /// Custom headers added to every outbound call to this backend.
    ///
    /// Provider-owned headers are rejected so a static value cannot replace
    /// configured or forwarded auth. Header names are case-insensitive.
    pub extra_headers: BTreeMap<String, String>,
    /// Default top-level request fields, applied only when the request omits the key.
    pub extra_body: BTreeMap<String, Value>,
    /// Reasoning effort forced on every request to this backend, replacing whatever the caller
    /// sent. Responses carries it as `reasoning.effort`, Chat Completions as `reasoning_effort`;
    /// Anthropic has no equivalent and rejects the setting at configuration time.
    pub reasoning_effort: Option<String>,
    /// Additional attempts after the initial upstream request.
    pub max_retries: u32,
    /// Deadline for one complete response, including retries, retry delays, and stream reads.
    /// `None` leaves the wait unbounded.
    pub timeout: Option<Duration>,
}

impl fmt::Debug for HttpBackendConfig {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("HttpBackendConfig")
            .field("base_url", &self.base_url)
            .field("api_key", &self.api_key.as_ref().map(|_| "[REDACTED]"))
            .field("forward_auth", &self.forward_auth)
            .field("extra_header_names", &self.extra_headers.keys())
            .field("extra_body_keys", &self.extra_body.keys())
            .field("reasoning_effort", &self.reasoning_effort)
            .field("max_retries", &self.max_retries)
            .field("timeout", &self.timeout)
            .finish()
    }
}

/// A configured upstream backend, one variant per built-in wire format.
///
/// The variant fixes the wire format, URL path, and auth scheme together so no
/// invalid combination can be constructed.
#[derive(Clone, Debug)]
pub enum Backend {
    /// OpenAI-compatible Chat Completions API.
    OpenAiChat(HttpBackendConfig),
    /// OpenAI Responses API.
    OpenAiResponses(HttpBackendConfig),
    /// Anthropic Messages API.
    Anthropic(HttpBackendConfig),
}

impl Backend {
    // Checks custom headers before the client can send a request.
    pub(crate) fn validate_extra_headers(&self, model_name: &str) -> Result<()> {
        let invalid_name = self.config().extra_headers.keys().find(|name| match self {
            Backend::OpenAiChat(_) | Backend::OpenAiResponses(_) => {
                name.eq_ignore_ascii_case("authorization")
                    || (self.is_forwarding_auth()
                        && (name.eq_ignore_ascii_case("chatgpt-account-id")
                            || name.eq_ignore_ascii_case("x-openai-fedramp")))
            }
            Backend::Anthropic(_) => {
                name.eq_ignore_ascii_case("x-api-key")
                    || name.eq_ignore_ascii_case("anthropic-version")
                    || (self.is_forwarding_auth()
                        && (name.eq_ignore_ascii_case("authorization")
                            || name.eq_ignore_ascii_case("anthropic-beta")))
            }
        });
        if let Some(name) = invalid_name {
            return Err(LlmClientError::Configuration {
                message: format!(
                    "model {model_name:?} extra_headers cannot set {name:?}; extra_headers is only for additional headers"
                ),
            });
        }
        Ok(())
    }

    /// The wire format the request IR is encoded to for this backend.
    pub fn wire_format(&self) -> WireFormat {
        match self {
            Backend::OpenAiChat(_) => WireFormat::OpenAiChat,
            Backend::OpenAiResponses(_) => WireFormat::OpenAiResponses,
            Backend::Anthropic(_) => WireFormat::AnthropicMessages,
        }
    }

    // Shared HTTP config, regardless of variant.
    fn config(&self) -> &HttpBackendConfig {
        match self {
            Backend::OpenAiChat(config)
            | Backend::OpenAiResponses(config)
            | Backend::Anthropic(config) => config,
        }
    }

    /// The fully resolved upstream URL for this backend's endpoint.
    ///
    /// Tolerates base URLs that already include the provider path (or a bare
    /// `/v1`), matching the join rules of the existing native backends.
    pub fn url(&self) -> String {
        let base_url = &self.config().base_url;
        let result = match self {
            Backend::OpenAiChat(_) => openai_url(base_url, "/chat/completions"),
            Backend::OpenAiResponses(_) => openai_url(base_url, "/responses"),
            Backend::Anthropic(_) => anthropic_url(base_url, ""),
        };
        result.unwrap_or_else(|error| {
            tracing::error!(%error, "Unable to build provider endpoint URL");
            base_url.clone()
        })
    }

    /// Applies this backend's configured auth and version headers to a request builder.
    ///
    /// OpenAI variants use `Authorization: Bearer <key>`; Anthropic uses
    /// `x-api-key: <key>` plus the required `anthropic-version` header. A backend
    /// with `forward_auth` uses the caller's provider credential instead.
    pub fn apply_auth(&self, mut builder: RequestBuilder) -> RequestBuilder {
        let api_key = if self.is_forwarding_auth() {
            None
        } else {
            self.config().api_key.as_deref()
        };
        match self {
            Backend::OpenAiChat(_) | Backend::OpenAiResponses(_) => {
                if let Some(api_key) = api_key {
                    builder = builder.bearer_auth(api_key);
                }
            }
            Backend::Anthropic(_) => {
                builder = builder.header("anthropic-version", ANTHROPIC_VERSION);
                if let Some(api_key) = api_key {
                    builder = builder.header("x-api-key", api_key);
                }
            }
        }
        builder
    }

    pub(crate) fn is_forwarding_auth(&self) -> bool {
        self.config().forward_auth
    }

    pub(crate) fn is_provider_owned_header(&self, name: &str) -> bool {
        match self {
            Backend::OpenAiChat(_) | Backend::OpenAiResponses(_) => {
                ["authorization", "chatgpt-account-id", "x-openai-fedramp"]
                    .iter()
                    .any(|owned| name.eq_ignore_ascii_case(owned))
            }
            Backend::Anthropic(_) => [
                "authorization",
                "x-api-key",
                "anthropic-beta",
                "anthropic-version",
            ]
            .iter()
            .any(|owned| name.eq_ignore_ascii_case(owned)),
        }
    }

    /// Applies only the caller credential accepted by this provider.
    pub(crate) fn apply_forwarded_auth(
        &self,
        mut builder: RequestBuilder,
        metadata: Option<&Metadata>,
    ) -> RequestBuilder {
        if !self.is_forwarding_auth() {
            return builder;
        }
        let Some(headers) = metadata.and_then(|metadata| metadata.http_headers.as_ref()) else {
            return builder;
        };
        match self {
            Backend::OpenAiChat(_) | Backend::OpenAiResponses(_) => {
                for name in ["authorization", "chatgpt-account-id", "x-openai-fedramp"] {
                    if let Some(value) = headers.get(name) {
                        builder = builder.header(name, sensitive_header(value));
                    }
                }
            }
            Backend::Anthropic(_) => {
                for name in ["authorization", "x-api-key"] {
                    if let Some(value) = headers.get(name) {
                        builder = builder.header(name, sensitive_header(value));
                    }
                }
                if let Some(value) = headers.get("anthropic-beta")
                    && let Some(value) = oauth_beta_header(value)
                {
                    builder = builder.header("anthropic-beta", value);
                }
            }
        }
        builder
    }

    /// Custom per-backend headers to forward on every call.
    pub fn extra_headers(&self) -> &BTreeMap<String, String> {
        &self.config().extra_headers
    }

    /// Default top-level fields to merge into outbound request bodies.
    pub fn extra_body(&self) -> &BTreeMap<String, Value> {
        &self.config().extra_body
    }

    /// Reasoning effort forced on outbound requests, if the target configures one.
    pub fn reasoning_effort(&self) -> Option<&str> {
        self.config().reasoning_effort.as_deref()
    }

    /// Additional attempts allowed after the initial request.
    pub fn max_retries(&self) -> u32 {
        self.config().max_retries
    }

    /// Deadline for all attempts and the complete response; `None` leaves the wait unbounded.
    pub fn timeout(&self) -> Option<Duration> {
        self.config().timeout
    }

    /// Whether this backend speaks the Anthropic Messages wire format — the only
    /// one with a `count_tokens` endpoint.
    pub fn is_anthropic(&self) -> bool {
        matches!(self, Backend::Anthropic(_))
    }

    /// The upstream `/v1/messages/count_tokens` URL, derived from the same base
    /// URL join as [`url`](Self::url).
    pub fn count_tokens_url(&self) -> String {
        let base_url = &self.config().base_url;
        anthropic_url(base_url, "/count_tokens").unwrap_or_else(|error| {
            tracing::error!(%error, "Unable to build Anthropic token-counting URL");
            base_url.clone()
        })
    }

    /// Whether an upstream 400 `body` looks like a context-window overflow for
    /// this backend's provider.
    pub(crate) fn is_context_overflow(&self, body: &str) -> bool {
        match self {
            Backend::OpenAiChat(_) | Backend::OpenAiResponses(_) => is_overflow_body(
                body,
                |value| {
                    value
                        .get("error")
                        .and_then(|err| err.get("code"))
                        .and_then(serde_json::Value::as_str)
                        == Some("context_length_exceeded")
                },
                OPENAI_OVERFLOW_PHRASES,
            ),
            Backend::Anthropic(_) => is_overflow_body(body, |_| false, ANTHROPIC_OVERFLOW_PHRASES),
        }
    }
}

// Retains OAuth markers while keeping provider feature betas backend-owned.
fn sensitive_header(value: &HeaderValue) -> HeaderValue {
    let mut value = value.clone();
    value.set_sensitive(true);
    value
}

fn oauth_beta_header(value: &HeaderValue) -> Option<HeaderValue> {
    let oauth_betas = value
        .to_str()
        .ok()?
        .split(',')
        .map(str::trim)
        .filter(|beta| {
            beta.get(..6)
                .is_some_and(|prefix| prefix.eq_ignore_ascii_case("oauth-"))
        });
    let value = oauth_betas.collect::<Vec<_>>().join(",");
    if value.is_empty() {
        return None;
    }
    let mut value = HeaderValue::from_str(&value).ok()?;
    value.set_sensitive(true);
    Some(value)
}

// Accept either a root `/v1` URL or an already-specific OpenAI endpoint URL.
pub(crate) fn openai_url(base_url: &str, suffix: &str) -> Result<String> {
    let mut url = reqwest::Url::parse(base_url).map_err(|error| LlmClientError::Configuration {
        message: format!("Invalid OpenAI base URL: {error}"),
    })?;
    let base_path = url.path().trim_end_matches('/');
    let base_root = base_path
        .strip_suffix("/chat/completions")
        .or_else(|| base_path.strip_suffix("/responses"))
        .unwrap_or(base_path);
    url.set_path(&format!("{base_root}{suffix}"));
    Ok(url.into())
}

// Accept a bare host, a `/v1` root, or an already-specific `/v1/messages` URL.
fn anthropic_url(base_url: &str, suffix: &str) -> Result<String> {
    let mut url = reqwest::Url::parse(base_url).map_err(|error| LlmClientError::Configuration {
        message: format!("Invalid Anthropic base URL: {error}"),
    })?;
    let base_path = url.path().trim_end_matches('/');
    let messages_path = if base_path.ends_with("/v1/messages") {
        base_path.to_string()
    } else if base_path.ends_with("/v1") {
        format!("{base_path}/messages")
    } else {
        format!("{base_path}/v1/messages")
    };
    url.set_path(&format!("{messages_path}{suffix}"));
    Ok(url.into())
}

#[cfg(test)]
mod tests {
    use super::*;

    fn config(base_url: &str) -> HttpBackendConfig {
        HttpBackendConfig {
            base_url: base_url.to_string(),
            api_key: Some("secret".to_string()),
            forward_auth: false,
            extra_headers: BTreeMap::new(),
            extra_body: BTreeMap::new(),
            reasoning_effort: None,
            max_retries: 0,
            timeout: None,
        }
    }

    #[test]
    fn openai_chat_url_joins_bare_v1() {
        let backend = Backend::OpenAiChat(config("https://api.openai.com/v1"));
        assert_eq!(backend.url(), "https://api.openai.com/v1/chat/completions");
    }

    #[test]
    fn openai_chat_url_tolerates_trailing_slash_and_existing_suffix() {
        assert_eq!(
            Backend::OpenAiChat(config("https://api.openai.com/v1/")).url(),
            "https://api.openai.com/v1/chat/completions"
        );
        assert_eq!(
            Backend::OpenAiChat(config("https://api.openai.com/v1/chat/completions")).url(),
            "https://api.openai.com/v1/chat/completions"
        );
    }

    #[test]
    fn openai_responses_url_uses_responses_path() {
        assert_eq!(
            Backend::OpenAiResponses(config("https://api.openai.com/v1")).url(),
            "https://api.openai.com/v1/responses"
        );
    }

    #[test]
    fn anthropic_url_join_cases() {
        assert_eq!(
            Backend::Anthropic(config("https://api.anthropic.com")).url(),
            "https://api.anthropic.com/v1/messages"
        );
        assert_eq!(
            Backend::Anthropic(config("https://api.anthropic.com/v1")).url(),
            "https://api.anthropic.com/v1/messages"
        );
        assert_eq!(
            Backend::Anthropic(config("https://api.anthropic.com/v1/messages")).url(),
            "https://api.anthropic.com/v1/messages"
        );
    }

    #[test]
    fn wire_format_matches_variant() {
        assert_eq!(
            Backend::OpenAiChat(config("x")).wire_format(),
            WireFormat::OpenAiChat
        );
        assert_eq!(
            Backend::OpenAiResponses(config("x")).wire_format(),
            WireFormat::OpenAiResponses
        );
        assert_eq!(
            Backend::Anthropic(config("x")).wire_format(),
            WireFormat::AnthropicMessages
        );
    }

    #[test]
    fn openai_detects_canonical_and_wrapped_overflow() {
        let backend = Backend::OpenAiChat(config("x"));
        assert!(
            backend.is_context_overflow(
                r#"{"error":{"code":"context_length_exceeded","message":"x"}}"#
            )
        );
        // NVIDIA/LiteLLM message wrap with no structured code.
        assert!(backend.is_context_overflow(
            r#"{"error":{"message":"the model's context length is only 131072 tokens"}}"#
        ));
        assert!(!backend.is_context_overflow(r#"{"error":{"code":"invalid_api_key"}}"#));
        // Hub GLM (LiteLLM-wrapped): code is "400", detection relies on phrase match.
        assert!(backend.is_context_overflow(
            r#"{"error":{"message":"Input length 877338 exceeds the maximum allowed input length of 639968 tokens","code":"400"}}"#
        ));
        // Native SGLang: top-level error envelope (no `error` key).
        // KV-pool rejection (managers/utils.py) and declared-context rejection
        // (tokenizer_manager.py); both stable across v0.5.15-v0.5.17.
        assert!(backend.is_context_overflow(
            r#"{"object":"error","message":"Input length (700001 tokens) exceeds the maximum allowed length (536826 tokens). Use a shorter input or enable --allow-auto-truncate.","type":"BadRequestError","param":null,"code":400}"#
        ));
        assert!(backend.is_context_overflow(
            r#"{"object":"error","message":"The input (12345 tokens) is longer than the model's context length (8192 tokens).","type":"BadRequestError","param":null,"code":400}"#
        ));
    }

    #[test]
    fn anthropic_detects_prompt_too_long() {
        let backend = Backend::Anthropic(config("x"));
        assert!(
            backend.is_context_overflow(
                r#"{"error":{"message":"prompt is too long: 200000 tokens"}}"#
            )
        );
        assert!(!backend.is_context_overflow(r#"{"error":{"message":"overloaded"}}"#));
    }
}