Skip to main content

switchyard_protocol/
llm.rs

1// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Provider-neutral conversation types shared by routing, clients, and translation.
5//!
6//! Debug output redacts MCP URLs and authorization tokens and hides raw provider tool definitions,
7//! extensions, and preserved bodies. Conversation content, including unknown provider
8//! blocks, remains visible and may contain secrets. Serialization retains the stored values.
9
10use std::collections::BTreeMap;
11use std::fmt;
12
13use serde::{Deserialize, Serialize};
14use serde_json::{Map, Value};
15
16use crate::format::FormatId;
17
18/// Maximum temperature on the shared IR's zero-based scale.
19pub const MAX_IR_TEMPERATURE: f64 = 2.0;
20
21/// Actor role normalized across provider APIs.
22#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize, strum_macros::Display)]
23#[serde(rename_all = "snake_case")]
24#[strum(serialize_all = "snake_case")]
25pub enum Role {
26    /// System-level instructions.
27    System,
28    /// Developer-level instructions supported by some provider APIs.
29    Developer,
30    /// End-user input.
31    User,
32    /// Model-generated output.
33    Assistant,
34    /// Tool execution output.
35    Tool,
36}
37
38/// Instruction content separated from normal conversation messages.
39#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
40pub struct InstructionBlock {
41    /// Instruction authority, normally [`Role::System`] or [`Role::Developer`].
42    pub role: Role,
43    /// Ordered instruction content.
44    pub content: Vec<ContentBlock>,
45}
46
47/// One normalized conversation message.
48#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
49pub struct Message {
50    /// Actor that produced the message.
51    pub role: Role,
52    /// Ordered message content.
53    pub content: Vec<ContentBlock>,
54    /// OpenAI Responses assistant message `phase`, such as `commentary` or `final_answer`.
55    #[serde(default, skip_serializing_if = "Option::is_none")]
56    pub phase: Option<String>,
57}
58
59impl Message {
60    /// Creates a message with no `phase`.
61    pub fn new(role: Role, content: Vec<ContentBlock>) -> Self {
62        Self {
63            role,
64            content,
65            phase: None,
66        }
67    }
68
69    /// Creates a text-only message for the given role.
70    pub fn text(role: Role, text: impl Into<String>) -> Self {
71        Self::new(role, vec![ContentBlock::Text { text: text.into() }])
72    }
73
74    /// Concatenates text-like content blocks when the message has any.
75    pub fn text_content(&self, separator: &str) -> Option<String> {
76        let parts = self
77            .content
78            .iter()
79            .filter_map(|block| match block {
80                ContentBlock::Text { text } => Some(text.as_str()),
81                ContentBlock::Refusal { text } => Some(text.as_str()),
82                _ => None,
83            })
84            .collect::<Vec<_>>();
85        if parts.is_empty() {
86            None
87        } else {
88            Some(parts.join(separator))
89        }
90    }
91}
92
93/// Normalized content block variants carried by messages and tool results.
94#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
95#[serde(tag = "type", rename_all = "snake_case")]
96pub enum ContentBlock {
97    /// Plain text content.
98    Text {
99        /// Text value.
100        text: String,
101    },
102    /// Model reasoning or thinking content.
103    Reasoning {
104        /// Reasoning text.
105        text: String,
106        /// Provider signature used to validate or continue the reasoning block.
107        signature: Option<String>,
108        /// Structured reasoning details, such as an encrypted `{ "type":
109        /// "reasoning.encrypted", "data": "..." }` object, replayed without modification.
110        #[serde(default, skip_serializing_if = "Vec::is_empty")]
111        details: Vec<Value>,
112    },
113    /// Image content.
114    Image {
115        /// Image location or inline payload.
116        source: ImageSource,
117    },
118    /// Audio content.
119    Audio {
120        /// Audio location or inline payload.
121        source: MediaSource,
122    },
123    /// Video content.
124    Video {
125        /// Video location or inline payload.
126        source: MediaSource,
127    },
128    /// File content.
129    File {
130        /// File identifier or inline payload.
131        source: FileSource,
132    },
133    /// Tool invocation requested by the assistant.
134    ToolCall(ToolCall),
135    /// Result of an earlier tool invocation.
136    ToolResult(ToolResult),
137    /// MCP activity executed by the backend, rather than by the calling agent.
138    Mcp(McpContent),
139    /// Provider refusal content.
140    Refusal {
141        /// Human-readable refusal text.
142        text: String,
143    },
144    /// Provider block that has no normalized representation.
145    Unknown {
146        /// Wire format that supplied the block.
147        provider: FormatId,
148        /// Exact provider block.
149        raw: Value,
150    },
151}
152
153/// Image payload forms supported by the conversation model.
154#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
155#[serde(tag = "type", content = "data", rename_all = "snake_case")]
156pub enum ImageSource {
157    /// Image fetched from a URL.
158    Url {
159        /// Image URL.
160        url: String,
161        /// Optional provider-specific image detail level.
162        detail: Option<String>,
163    },
164    /// Base64-encoded image bytes.
165    Base64 {
166        /// MIME type, when supplied.
167        media_type: Option<String>,
168        /// Base64-encoded bytes.
169        data: String,
170    },
171    /// Provider image source with no normalized representation.
172    Raw(Value),
173}
174
175/// File payload forms supported by the conversation model.
176#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
177#[serde(tag = "type", content = "data", rename_all = "snake_case")]
178pub enum FileSource {
179    /// Provider-managed file identifier.
180    FileId(String),
181    /// Inline file payload.
182    FileData {
183        /// Encoded or textual file data as supplied by the provider format.
184        data: String,
185        /// Original filename, when supplied.
186        filename: Option<String>,
187    },
188    /// Provider file source with no normalized representation.
189    Raw(Value),
190}
191
192/// Audio and video payload forms supported by the conversation model.
193#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
194#[serde(tag = "type", content = "data", rename_all = "snake_case")]
195pub enum MediaSource {
196    /// Media fetched from a URL.
197    Url {
198        /// Media URL.
199        url: String,
200        /// MIME type, when supplied.
201        media_type: Option<String>,
202    },
203    /// Base64-encoded media bytes.
204    Base64 {
205        /// MIME type, when supplied.
206        media_type: Option<String>,
207        /// Base64-encoded bytes.
208        data: String,
209    },
210    /// Provider media source with no normalized representation.
211    Raw(Value),
212}
213
214/// Normalized assistant tool call.
215#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
216pub struct ToolCall {
217    /// Provider tool-call identifier used to pair the result.
218    pub id: String,
219    /// Tool name.
220    pub name: String,
221    /// Parsed tool arguments.
222    pub arguments: Value,
223}
224
225/// Normalized tool result message content.
226#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
227pub struct ToolResult {
228    /// Identifier of the [`ToolCall`] this result answers.
229    pub tool_call_id: String,
230    /// Ordered tool output content.
231    pub content: Vec<ContentBlock>,
232    /// Whether tool execution failed, when the provider reports it.
233    pub is_error: Option<bool>,
234}
235
236/// Normalized tool definition.
237#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
238pub struct ToolDefinition {
239    /// Tool name exposed to the model.
240    pub name: String,
241    /// Human-readable tool description.
242    pub description: Option<String>,
243    /// JSON Schema describing accepted arguments.
244    pub parameters: Value,
245    /// Whether the provider should enforce the schema strictly.
246    pub strict: Option<bool>,
247}
248
249/// A tool available to the model, in catalog order.
250#[derive(Clone, PartialEq, Serialize)]
251#[serde(tag = "type", rename_all = "snake_case")]
252pub enum Tool {
253    /// A remote MCP server and the tools it exposes.
254    Mcp(McpToolset),
255    /// A definition without a supported neutral representation.
256    Provider {
257        /// Source wire format; this definition is only replayed in that format.
258        provider: FormatId,
259        /// Complete provider definition.
260        raw: Value,
261    },
262    /// An agent-executed function. Its JSON retains the existing flat definition shape.
263    #[serde(untagged)]
264    Function(ToolDefinition),
265}
266
267impl<'de> Deserialize<'de> for Tool {
268    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
269    where
270        D: serde::Deserializer<'de>,
271    {
272        // Keep these variants and the conversion below in sync with Tool.
273        #[derive(Deserialize)]
274        #[serde(tag = "type", rename_all = "snake_case")]
275        enum TaggedTool {
276            Mcp(McpToolset),
277            Provider { provider: FormatId, raw: Value },
278            Function(ToolDefinition),
279        }
280
281        let value = Value::deserialize(deserializer)?;
282        // Only definitions without a type use the legacy function shape. A malformed
283        // tagged definition must fail instead of falling back to a function.
284        if value.get("type").is_none() {
285            return serde_json::from_value(value)
286                .map(Self::Function)
287                .map_err(serde::de::Error::custom);
288        }
289        let tool = serde_json::from_value(value).map_err(serde::de::Error::custom)?;
290        Ok(match tool {
291            TaggedTool::Mcp(mcp) => Self::Mcp(mcp),
292            TaggedTool::Provider { provider, raw } => Self::Provider { provider, raw },
293            TaggedTool::Function(function) => Self::Function(function),
294        })
295    }
296}
297
298impl fmt::Debug for Tool {
299    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
300        match self {
301            Self::Function(definition) => f.debug_tuple("Function").field(definition).finish(),
302            Self::Mcp(mcp) => f.debug_tuple("Mcp").field(mcp).finish(),
303            // Raw provider definitions can contain credentials without normalized fields.
304            Self::Provider { provider, .. } => f
305                .debug_struct("Provider")
306                .field("provider", provider)
307                .finish_non_exhaustive(),
308        }
309    }
310}
311
312impl From<ToolDefinition> for Tool {
313    fn from(definition: ToolDefinition) -> Self {
314        Self::Function(definition)
315    }
316}
317
318impl Tool {
319    /// Returns the function definition, if this is an agent-executed function.
320    pub fn function(&self) -> Option<&ToolDefinition> {
321        match self {
322            Self::Function(definition) => Some(definition),
323            _ => None,
324        }
325    }
326}
327
328/// Configuration for a URL-based remote MCP toolset.
329///
330/// This type covers the supported neutral settings. Definitions with additional settings,
331/// such as Responses headers, server descriptions, or conditional approval rules, belong
332/// in [`Tool::Provider`] with the complete original definition.
333#[derive(Clone, PartialEq, Serialize, Deserialize)]
334pub struct McpToolset {
335    /// Server identity used by MCP calls.
336    pub name: String,
337    /// Remote MCP endpoint.
338    pub url: String,
339    /// Credential sent to the MCP server, when supplied.
340    #[serde(default, skip_serializing_if = "Option::is_none")]
341    pub authorization_token: Option<String>,
342    /// Defaults for tools without a per-tool setting in `configs`.
343    #[serde(default, skip_serializing_if = "McpToolConfig::is_empty")]
344    pub default_config: McpToolConfig,
345    /// Per-tool settings, keyed by tool name. Each omitted setting inherits
346    /// from `default_config`, then falls back to the provider's default.
347    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
348    pub configs: BTreeMap<String, McpToolConfig>,
349    /// Whether all calls require approval (`true`) or none do (`false`).
350    /// Absence retains provider defaults. Definitions with conditional approval rules
351    /// are stored in full as [`Tool::Provider`], rather than as this type.
352    #[serde(default, skip_serializing_if = "Option::is_none")]
353    pub require_approval: Option<bool>,
354}
355
356impl fmt::Debug for McpToolset {
357    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
358        let Self {
359            name,
360            url: _,
361            authorization_token,
362            default_config,
363            configs,
364            require_approval,
365        } = self;
366        f.debug_struct("McpToolset")
367            .field("name", name)
368            // Credentials can appear in any part of the URL, including its path.
369            .field("url", &"[REDACTED]")
370            .field(
371                "authorization_token",
372                &authorization_token.as_ref().map(|_| "[REDACTED]"),
373            )
374            .field("default_config", default_config)
375            .field("configs", configs)
376            .field("require_approval", require_approval)
377            .finish()
378    }
379}
380
381/// Settings for an individual MCP tool or the defaults for a toolset.
382#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
383pub struct McpToolConfig {
384    /// Whether the tool is available for the model to call.
385    #[serde(default, skip_serializing_if = "Option::is_none")]
386    pub enabled: Option<bool>,
387    /// Whether the tool definition is loaded through tool search instead of initially.
388    #[serde(default, skip_serializing_if = "Option::is_none")]
389    pub defer_loading: Option<bool>,
390}
391
392impl McpToolConfig {
393    fn is_empty(&self) -> bool {
394        self.enabled.is_none() && self.defer_loading.is_none()
395    }
396}
397
398/// A tool discovered on an MCP server.
399#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
400pub struct McpListedTool {
401    /// Tool name as exposed by the server.
402    pub name: String,
403    /// Human-readable tool description, when supplied.
404    #[serde(default, skip_serializing_if = "Option::is_none")]
405    pub description: Option<String>,
406    /// JSON Schema describing accepted arguments.
407    pub input_schema: Value,
408    /// Additional tool metadata reported by the server.
409    #[serde(default, skip_serializing_if = "Option::is_none")]
410    pub annotations: Option<Value>,
411}
412
413/// MCP discovery and execution history. Results reference the matching call's server identity.
414#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
415#[serde(tag = "kind", rename_all = "snake_case")]
416pub enum McpContent {
417    /// Tools discovered on a server at this point in the conversation.
418    Listing {
419        /// Identity of the MCP server.
420        server_name: String,
421        /// Listing identifier, when supplied by the provider.
422        #[serde(default, skip_serializing_if = "Option::is_none")]
423        id: Option<String>,
424        /// Discovered tools in the order reported by the server.
425        tools: Vec<McpListedTool>,
426        /// Discovery failure, when reported. An empty tool list alone is not a failure.
427        #[serde(default, skip_serializing_if = "Option::is_none")]
428        error: Option<String>,
429    },
430    /// A call executed by the backend's MCP client.
431    Call {
432        /// Identity of the MCP server.
433        server_name: String,
434        /// Ordinary call ID, name, and arguments.
435        call: ToolCall,
436    },
437    /// Output from a backend-executed MCP call.
438    Result(ToolResult),
439}
440
441/// Normalized tool choice policy.
442#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
443#[serde(tag = "type", content = "data", rename_all = "snake_case")]
444pub enum ToolChoice {
445    /// Let the model decide whether to call a tool.
446    Auto,
447    /// Require at least one tool call.
448    Required,
449    /// Disallow tool calls.
450    None,
451    /// Require a specific tool.
452    Tool {
453        /// Required tool name.
454        name: String,
455    },
456    /// Provider tool-choice value with no normalized representation.
457    Raw(Value),
458}
459
460/// Provider sampling parameters with common cross-provider names.
461#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
462pub struct SamplingParams {
463    /// Sampling temperature on the `0.0..=MAX_IR_TEMPERATURE` scale.
464    /// Directly constructed requests use this scale; omission retains provider defaults.
465    /// See [`MAX_IR_TEMPERATURE`].
466    pub temperature: Option<f64>,
467    /// Nucleus-sampling probability mass.
468    pub top_p: Option<f64>,
469    /// Maximum number of candidate tokens considered at each step.
470    pub top_k: Option<i64>,
471}
472
473/// Output budget and structured-output options.
474#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
475pub struct OutputParams {
476    /// Maximum tokens the model may generate.
477    pub max_output_tokens: Option<u64>,
478    /// Provider-neutral or provider-specific structured-output configuration.
479    pub response_format: Option<Value>,
480    /// Whether the provider must enforce the response schema, overriding native
481    /// flags when set and retaining native behavior when `None`.
482    #[serde(default, skip_serializing_if = "Option::is_none")]
483    pub is_schema_enforced: Option<bool>,
484}
485
486/// Provider reasoning controls preserved by translation.
487#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
488pub struct ReasoningParams {
489    /// Requested reasoning effort or level.
490    pub effort: Option<String>,
491    /// Provider reasoning controls without a normalized field.
492    pub raw: Option<Value>,
493}
494
495/// Request extension key that marks a request decoded from an Anthropic Messages body.
496///
497/// Codecs skip this key when they copy unknown provider fields, so callers cannot set it.
498/// Prompt edits remove it from preserved Anthropic bodies for the same reason.
499pub const ANTHROPIC_REQUEST_KEY: &str = "switchyard_anthropic_request";
500
501/// Provider-specific fields that do not have first-class conversation fields.
502#[derive(Clone, Default, PartialEq, Serialize, Deserialize)]
503#[serde(default)]
504pub struct ProviderExtensions {
505    /// Provider fields keyed by their original wire names.
506    ///
507    /// Codecs use these fields when translating to another format. Exact
508    /// same-format replay is controlled separately by [`PreservationMetadata`].
509    pub fields: Map<String, Value>,
510}
511
512// Extension values can include credentials or embedded original request bodies.
513impl fmt::Debug for ProviderExtensions {
514    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
515        f.debug_struct("ProviderExtensions")
516            .field("field_count", &self.fields.len())
517            .finish_non_exhaustive()
518    }
519}
520
521/// Exact source payloads retained for lossless same-format round trips.
522///
523/// Translation's default preservation policy prefers a stored same-format body
524/// over reconstructing one from normalized fields. A caller that mutates the IR
525/// must clear the corresponding entry or use a policy with preservation disabled
526/// when those mutations must be encoded.
527#[derive(Clone, Default, PartialEq, Serialize, Deserialize)]
528#[serde(default)]
529pub struct PreservationMetadata {
530    /// Original request bodies keyed by source format.
531    pub requests: BTreeMap<FormatId, Value>,
532    /// Original response bodies keyed by source format.
533    pub responses: BTreeMap<FormatId, Value>,
534}
535
536// Original payloads can contain credentials even when normalized fields redact them.
537impl fmt::Debug for PreservationMetadata {
538    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
539        f.debug_struct("PreservationMetadata")
540            .field("request_formats", &self.requests.keys())
541            .field("response_formats", &self.responses.keys())
542            .finish_non_exhaustive()
543    }
544}
545
546/// Normalized request representation shared by Switchyard components.
547#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
548#[serde(default)]
549pub struct LlmRequest {
550    /// Model currently addressed by the request.
551    ///
552    /// This initially contains the name supplied by the inbound client. A routing host may
553    /// replace it with the selected target before serving the request.
554    pub model: Option<String>,
555    /// System and developer instructions separated from conversation turns.
556    pub instructions: Vec<InstructionBlock>,
557    /// Ordered conversation messages.
558    pub messages: Vec<Message>,
559    /// This request-local count tracks temporary notes appended after the caller's conversation.
560    /// The HTTP client uses it to choose a cache breakpoint before the notes, subject to
561    /// provider support, caller policy, marker limits, and an eligible prefix.
562    /// Rust moves and clones retain the count.
563    /// Serialization omits the count, and deserialization resets it to zero.
564    /// Note text and preserved provider bodies remain serialized.
565    #[serde(skip)]
566    pub temporary_note_count: usize,
567    /// Whether this request performs compaction or resumes from a summary.
568    #[serde(skip_serializing_if = "std::ops::Not::not")]
569    pub is_compaction: bool,
570    /// Whether the history contains a recognized compaction marker.
571    #[serde(skip_serializing_if = "std::ops::Not::not")]
572    pub has_compaction: bool,
573    /// Tools available to the model.
574    pub tools: Vec<Tool>,
575    /// Policy controlling model tool selection.
576    pub tool_choice: Option<ToolChoice>,
577    /// Common sampling controls.
578    pub sampling: SamplingParams,
579    /// Output budget and shape controls.
580    pub output: OutputParams,
581    /// Reasoning controls.
582    pub reasoning: ReasoningParams,
583    /// Whether the caller requested a streamed response.
584    pub stream: bool,
585    /// Provider fields without first-class normalized equivalents.
586    pub extensions: ProviderExtensions,
587    /// Exact provider bodies used by codecs for lossless same-format round trips.
588    /// This is separate from a host's optional
589    /// [`Request::raw_request`](crate::Request::raw_request).
590    pub preservation: PreservationMetadata,
591}
592
593/// Normalized token usage counts.
594#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
595pub struct Usage {
596    /// The upstream provider reports this monetary charge in USD.
597    #[serde(default, skip_serializing_if = "Option::is_none")]
598    pub provider_cost: Option<f64>,
599    /// Non-cached input tokens. Provider codecs normalize aggregate OpenAI
600    /// input counts by subtracting the cache detail fields.
601    pub input_tokens: Option<u64>,
602    /// Cache-read and cache-creation token detail, when reported.
603    #[serde(flatten)]
604    pub cache: Option<Box<InputCacheUsage>>,
605    /// The output count includes reasoning tokens when the provider counts them.
606    pub output_tokens: Option<u64>,
607    /// Provider-reported or codec-computed total token count.
608    ///
609    /// Codecs normalize OpenAI aggregate input counts before computing totals, so
610    /// this may equal non-cached input plus cache detail plus output.
611    pub total_tokens: Option<u64>,
612    /// Reasoning output tokens, when reported separately.
613    pub reasoning_tokens: Option<u64>,
614}
615
616/// Optional cache-token detail kept out of the common, cache-free usage allocation.
617#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
618pub struct InputCacheUsage {
619    /// The provider reports these cache-write tokens at the one-hour rate.
620    #[serde(default, skip_serializing_if = "Option::is_none")]
621    pub cache_creation_1h_input_tokens: Option<u64>,
622    /// Input tokens read from a provider cache.
623    pub cached_input_tokens: Option<u64>,
624    /// Input tokens written into a provider cache.
625    pub cache_creation_input_tokens: Option<u64>,
626}
627
628impl Usage {
629    /// Builds cache detail when at least one count is present.
630    pub fn cache_details(
631        cached_input_tokens: Option<u64>,
632        cache_creation_input_tokens: Option<u64>,
633    ) -> Option<Box<InputCacheUsage>> {
634        if cached_input_tokens.is_none() && cache_creation_input_tokens.is_none() {
635            return None;
636        }
637        Some(Box::new(InputCacheUsage {
638            cache_creation_1h_input_tokens: None,
639            cached_input_tokens,
640            cache_creation_input_tokens,
641        }))
642    }
643
644    /// Returns the cache-read input-token count.
645    pub fn cached_input_tokens(&self) -> Option<u64> {
646        self.cache
647            .as_ref()
648            .and_then(|cache| cache.cached_input_tokens)
649    }
650
651    /// Returns the cache-creation input-token count.
652    pub fn cache_creation_input_tokens(&self) -> Option<u64> {
653        self.cache
654            .as_ref()
655            .and_then(|cache| cache.cache_creation_input_tokens)
656    }
657
658    /// Sets the cache-read count, allocating cache detail when needed.
659    pub fn set_cached_input_tokens(&mut self, value: u64) {
660        self.cache
661            .get_or_insert_with(|| Box::new(InputCacheUsage::default()))
662            .cached_input_tokens = Some(value);
663    }
664
665    /// Sets the cache-creation count, allocating cache detail when needed.
666    pub fn set_cache_creation_input_tokens(&mut self, value: u64) {
667        self.cache
668            .get_or_insert_with(|| Box::new(InputCacheUsage::default()))
669            .cache_creation_input_tokens = Some(value);
670    }
671}
672
673/// Normalized reason a model stopped producing output.
674#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize)]
675#[serde(rename_all = "snake_case")]
676pub enum StopReason {
677    /// Model completed its turn normally.
678    EndTurn,
679    /// Model reached the configured output limit.
680    MaxTokens,
681    /// Model stopped to request a tool call.
682    ToolUse,
683    /// Provider safety or content filtering stopped generation.
684    ContentFilter,
685    /// Generation terminated because of an error.
686    Error,
687    /// Provider stop reason with no normalized equivalent.
688    Unknown,
689}
690
691/// A source URL cited by generated text.
692#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
693pub struct UrlCitation {
694    /// Start character offset in the concatenated text and refusal blocks.
695    pub start_index: usize,
696    /// Exclusive end character offset in the same text.
697    pub end_index: usize,
698    /// Source URL.
699    pub url: String,
700    /// Source title.
701    pub title: String,
702}
703
704/// One assistant output item in a normalized response.
705#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
706pub struct ResponseOutput {
707    /// Actor that produced the output, normally [`Role::Assistant`].
708    pub role: Role,
709    /// Ordered output content.
710    pub content: Vec<ContentBlock>,
711    /// URL citations in the concatenated text and refusal blocks.
712    #[serde(default, skip_serializing_if = "Vec::is_empty")]
713    pub url_citations: Vec<UrlCitation>,
714    /// Why this output stopped, when known.
715    pub stop_reason: Option<StopReason>,
716}
717
718/// Normalized, fully-buffered response — the aggregate of a completed generation.
719/// This is the terminal form of a streamed [`LlmResponse`](crate::LlmResponse).
720#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
721#[serde(default)]
722pub struct AggLlmResponse {
723    /// Provider response identifier.
724    pub id: Option<String>,
725    /// Model reported by the provider.
726    pub model: Option<String>,
727    /// Ordered response output items.
728    pub outputs: Vec<ResponseOutput>,
729    /// Normalized token usage.
730    pub usage: Usage,
731    /// Provider response fields without normalized equivalents.
732    pub extensions: ProviderExtensions,
733    /// Exact provider bodies retained for lossless round trips.
734    pub preservation: PreservationMetadata,
735}
736
737impl AggLlmResponse {
738    /// Returns the first output item when a response has any output.
739    pub fn first_output(&self) -> Option<&ResponseOutput> {
740        self.outputs.first()
741    }
742}
743
744#[cfg(test)]
745mod tests {
746    use serde_json::json;
747
748    use super::*;
749
750    #[test]
751    fn serde_uses_python_friendly_dictionary_shapes() -> Result<(), serde_json::Error> {
752        let request: LlmRequest = serde_json::from_value(json!({
753            "model": "auto",
754            "messages": [{
755                "role": "user",
756                "content": [{"type": "text", "text": "hello"}]
757            }]
758        }))?;
759        assert_eq!(request.messages[0], Message::text(Role::User, "hello"));
760
761        let tool_call = ContentBlock::ToolCall(ToolCall {
762            id: "call-1".to_string(),
763            name: "lookup".to_string(),
764            arguments: json!({"query": "rust"}),
765        });
766        assert_eq!(
767            serde_json::to_value(tool_call)?,
768            json!({
769                "type": "tool_call",
770                "id": "call-1",
771                "name": "lookup",
772                "arguments": {"query": "rust"}
773            })
774        );
775        Ok(())
776    }
777
778    #[test]
779    fn tool_deserialization_rejects_invalid_tagged_definitions() {
780        for definition in [
781            json!({"type": "mcp", "name": "inv", "parameters": {}}),
782            json!({"type": "provider", "provider": "x", "name": "n", "parameters": {}}),
783            json!({"type": "unknown", "name": "n", "parameters": {}}),
784            json!({"type": null, "name": "n", "parameters": {}}),
785        ] {
786            assert!(serde_json::from_value::<Tool>(definition).is_err());
787        }
788        let error = serde_json::from_value::<Tool>(json!({
789            "type": "mcp", "name": "inv", "url": "https://example.invalid/mcp",
790            "authorization_token": 5, "parameters": {}
791        }))
792        .expect_err("an invalid credential must not become a function")
793        .to_string();
794        assert!(error.contains("string"), "field error was lost: {error}");
795    }
796
797    #[test]
798    fn tool_catalog_preserves_function_json_and_backend_history() -> Result<(), serde_json::Error> {
799        let function = json!({"name": "lookup", "description": null, "parameters": {"type": "object"}, "strict": null});
800        let definitions = json!([
801            function,
802            {"type": "mcp", "name": "inventory", "url": "https://example.invalid/mcp", "require_approval": false},
803            {"type": "provider", "provider": "openai_responses", "raw": {"type": "mcp", "connector_id": "connector_example", "server_label": "example"}},
804            {
805                "type": "mcp", "name": "configured", "url": "https://example.invalid/mcp",
806                "default_config": {"enabled": false, "defer_loading": true},
807                "configs": {"lookup": {"enabled": true}, "search": {"defer_loading": false}}
808            }
809        ]);
810        let tools: Vec<Tool> = serde_json::from_value(definitions.clone())?;
811        assert!(matches!(&tools[0], Tool::Function(_)));
812        assert!(matches!(&tools[1], Tool::Mcp(_)));
813        assert!(matches!(&tools[2], Tool::Provider { .. }));
814        assert_eq!(serde_json::to_value(&tools)?, definitions);
815        let explicit_function: Tool = serde_json::from_value(json!({
816            "type": "function", "name": "lookup", "parameters": {"type": "object"}
817        }))?;
818        assert_eq!(explicit_function, tools[0]);
819
820        let history = json!([
821            {
822                "type": "mcp", "kind": "listing", "server_name": "inventory",
823                "id": "listing_1",
824                "tools": [{
825                    "name": "lookup", "description": "Look up stock",
826                    "input_schema": {"type": "object"},
827                    "annotations": {"readOnlyHint": true}
828                }]
829            },
830            {"type": "mcp", "kind": "listing", "server_name": "empty", "tools": []},
831            {
832                "type": "mcp", "kind": "listing", "server_name": "unavailable",
833                "tools": [], "error": "Server unavailable"
834            },
835            {
836                "type": "mcp", "kind": "call", "server_name": "inventory",
837                "call": {"id": "call_1", "name": "lookup", "arguments": {}}
838            },
839            {
840                "type": "mcp", "kind": "result", "tool_call_id": "call_1",
841                "content": [{"type": "text", "text": "in stock"}], "is_error": false
842            }
843        ]);
844        let content: Vec<ContentBlock> = serde_json::from_value(history.clone())?;
845        assert_eq!(serde_json::to_value(&content)?, history);
846        Ok(())
847    }
848
849    #[test]
850    fn mcp_credentials_are_omitted_from_debug() -> Result<(), serde_json::Error> {
851        let token = "synthetic-mcp-debug-secret";
852        let url_secret = "synthetic-mcp-url-secret";
853        let url = format!("https://example.invalid/mcp?api_key={url_secret}");
854        let mcp: McpToolset = serde_json::from_value(json!({
855            "name": "inventory", "url": url,
856            "authorization_token": token
857        }))?;
858        let raw = json!({"mcp_servers": [{"authorization_token": token}]});
859        let mut request = LlmRequest {
860            tools: vec![
861                Tool::Mcp(mcp.clone()),
862                Tool::Provider {
863                    provider: "openai_responses".into(),
864                    raw: json!({"type": "mcp", "authorization": token}),
865                },
866            ],
867            ..LlmRequest::default()
868        };
869        request
870            .preservation
871            .requests
872            .insert("anthropic_messages".into(), raw.clone());
873        request.extensions.fields.insert("metadata".into(), raw);
874        let serialized = serde_json::to_value(&request)?;
875        for debug in [
876            format!("{mcp:?}"),
877            format!("{mcp:#?}"),
878            format!("{:?}", request.tools),
879            format!("{:?}", request.extensions),
880            format!("{:?}", request.preservation),
881            format!("{request:?}"),
882            format!("{request:#?}"),
883        ] {
884            assert!(!debug.contains(token), "Debug exposed an MCP credential");
885            assert!(
886                !debug.contains(url_secret),
887                "Debug exposed an MCP URL secret"
888            );
889        }
890        assert_eq!(serde_json::to_value(&request)?, serialized);
891        assert_eq!(serialized["tools"][0]["url"], url);
892        assert_eq!(serialized["tools"][0]["authorization_token"], token);
893        assert_eq!(serialized["tools"][1]["raw"]["authorization"], token);
894        Ok(())
895    }
896}