Skip to main content

switchyard_protocol/
client.rs

1// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Routed-call client contracts and shared error types.
5//!
6//! Hosts implement these traits to perform model calls. Keeping the contracts here
7//! lets clients depend on the protocol without pulling in libsy's orchestration.
8
9use async_trait::async_trait;
10use thiserror::Error;
11
12use crate::{DecisionRequest, DecisionResponse, ModelId, Request, Response};
13
14/// A boxed client-specific error preserved as the source of a routed call failure.
15pub type BoxError = Box<dyn std::error::Error + Send + Sync + 'static>;
16
17/// Failures a routed LLM client can surface to its caller.
18///
19/// Boxed sources preserve client-specific errors; `General` keeps only a message.
20#[non_exhaustive]
21#[derive(Debug, Error)]
22pub enum LlmClientError {
23    /// The request cannot be served as supplied.
24    #[error("invalid request: {message}")]
25    InvalidRequest {
26        /// Human-readable request validation failure.
27        message: String,
28    },
29
30    /// Decoding the inbound request failed in the translation engine.
31    #[error("request translation failed: {0}")]
32    RequestTranslation(String),
33
34    /// Encoding the request for the upstream failed in the translation engine.
35    #[error("outbound request encoding failed: {0}")]
36    RequestEncoding(String),
37
38    /// Decoding or encoding the response failed in the translation engine.
39    #[error("response translation failed: {0}")]
40    ResponseTranslation(String),
41
42    /// The client is not configured to serve the selected target.
43    #[error("client configuration error: {message}")]
44    Configuration {
45        /// Human-readable configuration failure.
46        message: String,
47    },
48
49    /// The route cannot record another provider-owned response or conversation ID.
50    #[error(
51        "Responses state tracking reached its limit of {limit} IDs; no existing records were removed"
52    )]
53    ResponseStateLimitExceeded {
54        /// Maximum number of IDs retained by this route.
55        limit: usize,
56    },
57
58    /// Two configured models reported the same saved response or conversation ID.
59    #[error("Responses state ID is already recorded for another model; its owner was not changed")]
60    ResponseStateConflict,
61
62    /// The selected backend is temporarily unavailable. Another candidate may serve the request.
63    #[error("backend temporarily unavailable")]
64    TemporarilyUnavailable,
65
66    /// The upstream could not be reached or the request could not be sent.
67    #[error("upstream transport error: {source}")]
68    Transport {
69        /// Client-specific transport failure.
70        #[source]
71        source: BoxError,
72    },
73
74    /// The upstream request exceeded its timeout.
75    #[error("upstream request timed out: {source}")]
76    Timeout {
77        /// Client-specific timeout failure.
78        #[source]
79        source: BoxError,
80    },
81
82    /// The upstream rejected the request because it exceeds the model's context window.
83    #[error("context window exceeded for model {model}: {message}")]
84    ContextWindowExceeded {
85        /// Model whose context window was exceeded.
86        model: ModelId,
87        /// Upstream error message.
88        message: String,
89    },
90
91    /// The upstream returned a non-success HTTP response.
92    #[error("upstream returned HTTP {status}: {body}")]
93    UpstreamHttp {
94        /// Upstream HTTP status code.
95        status: http::StatusCode,
96        /// Raw upstream error body.
97        body: String,
98        /// Upstream HTTP response headers from the last attempt. Consumers such as
99        /// switchyard-server may forward an allowed subset to the downstream client.
100        /// Boxed to keep the error type small.
101        headers: Box<http::HeaderMap>,
102    },
103
104    /// The upstream returned a response the client could not decode.
105    #[error("invalid upstream response: {source}")]
106    InvalidResponse {
107        /// Client-specific decoding or validation failure.
108        #[source]
109        source: BoxError,
110    },
111
112    /// A native host failure that does not fit another category.
113    /// The default completion runner treats it as terminal.
114    #[error("host client error: {source}")]
115    Host {
116        /// Original error, retained for the host.
117        #[source]
118        source: BoxError,
119    },
120
121    /// A call across a foreign-function boundary (e.g. a Python-implemented client)
122    /// failed. The boxed source is the foreign error itself.
123    #[error("foreign function interface error: {source}")]
124    Ffi {
125        /// Foreign-language failure, preserved verbatim.
126        #[source]
127        source: BoxError,
128    },
129
130    /// A string-only failure. Useful in testing; prefer a typed variant when possible.
131    #[error("{0}")]
132    General(String),
133}
134
135impl LlmClientError {
136    /// Whether the provider reports unreadable or unsupported input media.
137    ///
138    /// Some providers report these deterministic request failures as HTTP 500.
139    /// They must not make a healthy backend unavailable to other requests.
140    pub fn is_attachment_rejection(&self) -> bool {
141        let Self::UpstreamHttp { status, body, .. } = self else {
142            return false;
143        };
144        if !matches!(status.as_u16(), 400 | 422 | 500) {
145            return false;
146        }
147        let parsed = serde_json::from_str::<serde_json::Value>(body).ok();
148        let error = parsed.as_ref().and_then(|value| value.get("error"));
149        if error
150            .and_then(|error| error.get("code"))
151            .and_then(|code| code.as_str())
152            == Some("content_policy_violation")
153        {
154            return false;
155        }
156        let message = error
157            .and_then(|error| error.get("message"))
158            .and_then(|message| message.as_str())
159            .unwrap_or(body)
160            .to_ascii_lowercase();
161        [
162            "unsupported content[].type",
163            "image input is not supported",
164            "does not support image input",
165            "failed to load image or audio file",
166            "cannot make get request",
167            "failed to download file",
168            "invalid image",
169            "does not represent a valid image",
170            "unsupported image format",
171            "unsupported file format",
172        ]
173        .iter()
174        .any(|pattern| message.contains(pattern))
175    }
176}
177
178/// Why routing replaced a selected target with another eligible target.
179#[derive(Clone, Copy, Debug, Eq, PartialEq)]
180pub enum RoutingFallbackReason {
181    /// The selected target rejected the request because its context window was too small.
182    ContextWindow,
183    /// The selected target was unavailable after its client retries finished.
184    Unavailable,
185}
186
187impl RoutingFallbackReason {
188    /// Stable value used when logging a routing fallback.
189    pub const fn as_str(self) -> &'static str {
190        match self {
191            Self::ContextWindow => "context_window",
192            Self::Unavailable => "unavailable",
193        }
194    }
195}
196
197/// Performs the actual model call for a target. This is the one piece of I/O the
198/// library does not own — a host implements it over its own transport (HTTP SDK,
199/// in-process model, mock). It serves a call the stream consumer chose not to
200/// override, reached as a routed request's `default_client`.
201///
202/// # Concurrency
203///
204/// A client may be shared by many targets and concurrent algorithm runs. Calls may
205/// overlap, so implementations must synchronize mutable state internally and should
206/// not serialize requests unless their transport requires it.
207#[async_trait]
208pub trait RoutedLlmClient: Send + Sync {
209    /// Resolves a routing key for telemetry. Direct model clients keep the key unchanged.
210    fn provider_model<'a>(&'a self, target: &'a ModelId) -> &'a ModelId {
211        target
212    }
213
214    /// Make a request
215    async fn call(&self, request: Request) -> Result<Response, LlmClientError>;
216}
217
218/// Serves typed decision calls over a host-owned transport.
219/// Implementations may be shared across targets and called concurrently.
220#[async_trait]
221pub trait RoutedDecisionClient: Send + Sync {
222    /// Evaluate the request using its selected model.
223    async fn call(&self, request: DecisionRequest) -> Result<DecisionResponse, LlmClientError>;
224}