1use std::collections::BTreeMap;
11use std::fmt;
12
13use serde::{Deserialize, Serialize};
14use serde_json::{Map, Value};
15
16use crate::format::FormatId;
17
18pub const MAX_IR_TEMPERATURE: f64 = 2.0;
20
21#[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,
28 Developer,
30 User,
32 Assistant,
34 Tool,
36}
37
38#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
40pub struct InstructionBlock {
41 pub role: Role,
43 pub content: Vec<ContentBlock>,
45}
46
47#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
49pub struct Message {
50 pub role: Role,
52 pub content: Vec<ContentBlock>,
54 #[serde(default, skip_serializing_if = "Option::is_none")]
56 pub phase: Option<String>,
57}
58
59impl Message {
60 pub fn new(role: Role, content: Vec<ContentBlock>) -> Self {
62 Self {
63 role,
64 content,
65 phase: None,
66 }
67 }
68
69 pub fn text(role: Role, text: impl Into<String>) -> Self {
71 Self::new(role, vec![ContentBlock::Text { text: text.into() }])
72 }
73
74 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#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
95#[serde(tag = "type", rename_all = "snake_case")]
96pub enum ContentBlock {
97 Text {
99 text: String,
101 },
102 Reasoning {
104 text: String,
106 signature: Option<String>,
108 #[serde(default, skip_serializing_if = "Vec::is_empty")]
111 details: Vec<Value>,
112 },
113 Image {
115 source: ImageSource,
117 },
118 Audio {
120 source: MediaSource,
122 },
123 Video {
125 source: MediaSource,
127 },
128 File {
130 source: FileSource,
132 },
133 ToolCall(ToolCall),
135 ToolResult(ToolResult),
137 Mcp(McpContent),
139 Refusal {
141 text: String,
143 },
144 Unknown {
146 provider: FormatId,
148 raw: Value,
150 },
151}
152
153#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
155#[serde(tag = "type", content = "data", rename_all = "snake_case")]
156pub enum ImageSource {
157 Url {
159 url: String,
161 detail: Option<String>,
163 },
164 Base64 {
166 media_type: Option<String>,
168 data: String,
170 },
171 Raw(Value),
173}
174
175#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
177#[serde(tag = "type", content = "data", rename_all = "snake_case")]
178pub enum FileSource {
179 FileId(String),
181 FileData {
183 data: String,
185 filename: Option<String>,
187 },
188 Raw(Value),
190}
191
192#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
194#[serde(tag = "type", content = "data", rename_all = "snake_case")]
195pub enum MediaSource {
196 Url {
198 url: String,
200 media_type: Option<String>,
202 },
203 Base64 {
205 media_type: Option<String>,
207 data: String,
209 },
210 Raw(Value),
212}
213
214#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
216pub struct ToolCall {
217 pub id: String,
219 pub name: String,
221 pub arguments: Value,
223}
224
225#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
227pub struct ToolResult {
228 pub tool_call_id: String,
230 pub content: Vec<ContentBlock>,
232 pub is_error: Option<bool>,
234}
235
236#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
238pub struct ToolDefinition {
239 pub name: String,
241 pub description: Option<String>,
243 pub parameters: Value,
245 pub strict: Option<bool>,
247}
248
249#[derive(Clone, PartialEq, Serialize)]
251#[serde(tag = "type", rename_all = "snake_case")]
252pub enum Tool {
253 Mcp(McpToolset),
255 Provider {
257 provider: FormatId,
259 raw: Value,
261 },
262 #[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 #[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 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 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 pub fn function(&self) -> Option<&ToolDefinition> {
321 match self {
322 Self::Function(definition) => Some(definition),
323 _ => None,
324 }
325 }
326}
327
328#[derive(Clone, PartialEq, Serialize, Deserialize)]
334pub struct McpToolset {
335 pub name: String,
337 pub url: String,
339 #[serde(default, skip_serializing_if = "Option::is_none")]
341 pub authorization_token: Option<String>,
342 #[serde(default, skip_serializing_if = "McpToolConfig::is_empty")]
344 pub default_config: McpToolConfig,
345 #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
348 pub configs: BTreeMap<String, McpToolConfig>,
349 #[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 .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#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
383pub struct McpToolConfig {
384 #[serde(default, skip_serializing_if = "Option::is_none")]
386 pub enabled: Option<bool>,
387 #[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#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
400pub struct McpListedTool {
401 pub name: String,
403 #[serde(default, skip_serializing_if = "Option::is_none")]
405 pub description: Option<String>,
406 pub input_schema: Value,
408 #[serde(default, skip_serializing_if = "Option::is_none")]
410 pub annotations: Option<Value>,
411}
412
413#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
415#[serde(tag = "kind", rename_all = "snake_case")]
416pub enum McpContent {
417 Listing {
419 server_name: String,
421 #[serde(default, skip_serializing_if = "Option::is_none")]
423 id: Option<String>,
424 tools: Vec<McpListedTool>,
426 #[serde(default, skip_serializing_if = "Option::is_none")]
428 error: Option<String>,
429 },
430 Call {
432 server_name: String,
434 call: ToolCall,
436 },
437 Result(ToolResult),
439}
440
441#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
443#[serde(tag = "type", content = "data", rename_all = "snake_case")]
444pub enum ToolChoice {
445 Auto,
447 Required,
449 None,
451 Tool {
453 name: String,
455 },
456 Raw(Value),
458}
459
460#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
462pub struct SamplingParams {
463 pub temperature: Option<f64>,
467 pub top_p: Option<f64>,
469 pub top_k: Option<i64>,
471}
472
473#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
475pub struct OutputParams {
476 pub max_output_tokens: Option<u64>,
478 pub response_format: Option<Value>,
480 #[serde(default, skip_serializing_if = "Option::is_none")]
483 pub is_schema_enforced: Option<bool>,
484}
485
486#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
488pub struct ReasoningParams {
489 pub effort: Option<String>,
491 pub raw: Option<Value>,
493}
494
495pub const ANTHROPIC_REQUEST_KEY: &str = "switchyard_anthropic_request";
500
501#[derive(Clone, Default, PartialEq, Serialize, Deserialize)]
503#[serde(default)]
504pub struct ProviderExtensions {
505 pub fields: Map<String, Value>,
510}
511
512impl 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#[derive(Clone, Default, PartialEq, Serialize, Deserialize)]
528#[serde(default)]
529pub struct PreservationMetadata {
530 pub requests: BTreeMap<FormatId, Value>,
532 pub responses: BTreeMap<FormatId, Value>,
534}
535
536impl 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#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
548#[serde(default)]
549pub struct LlmRequest {
550 pub model: Option<String>,
555 pub instructions: Vec<InstructionBlock>,
557 pub messages: Vec<Message>,
559 #[serde(skip)]
566 pub temporary_note_count: usize,
567 #[serde(skip_serializing_if = "std::ops::Not::not")]
569 pub is_compaction: bool,
570 #[serde(skip_serializing_if = "std::ops::Not::not")]
572 pub has_compaction: bool,
573 pub tools: Vec<Tool>,
575 pub tool_choice: Option<ToolChoice>,
577 pub sampling: SamplingParams,
579 pub output: OutputParams,
581 pub reasoning: ReasoningParams,
583 pub stream: bool,
585 pub extensions: ProviderExtensions,
587 pub preservation: PreservationMetadata,
591}
592
593#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
595pub struct Usage {
596 #[serde(default, skip_serializing_if = "Option::is_none")]
598 pub provider_cost: Option<f64>,
599 pub input_tokens: Option<u64>,
602 #[serde(flatten)]
604 pub cache: Option<Box<InputCacheUsage>>,
605 pub output_tokens: Option<u64>,
607 pub total_tokens: Option<u64>,
612 pub reasoning_tokens: Option<u64>,
614}
615
616#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
618pub struct InputCacheUsage {
619 #[serde(default, skip_serializing_if = "Option::is_none")]
621 pub cache_creation_1h_input_tokens: Option<u64>,
622 pub cached_input_tokens: Option<u64>,
624 pub cache_creation_input_tokens: Option<u64>,
626}
627
628impl Usage {
629 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 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 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 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 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#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize)]
675#[serde(rename_all = "snake_case")]
676pub enum StopReason {
677 EndTurn,
679 MaxTokens,
681 ToolUse,
683 ContentFilter,
685 Error,
687 Unknown,
689}
690
691#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
693pub struct UrlCitation {
694 pub start_index: usize,
696 pub end_index: usize,
698 pub url: String,
700 pub title: String,
702}
703
704#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
706pub struct ResponseOutput {
707 pub role: Role,
709 pub content: Vec<ContentBlock>,
711 #[serde(default, skip_serializing_if = "Vec::is_empty")]
713 pub url_citations: Vec<UrlCitation>,
714 pub stop_reason: Option<StopReason>,
716}
717
718#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
721#[serde(default)]
722pub struct AggLlmResponse {
723 pub id: Option<String>,
725 pub model: Option<String>,
727 pub outputs: Vec<ResponseOutput>,
729 pub usage: Usage,
731 pub extensions: ProviderExtensions,
733 pub preservation: PreservationMetadata,
735}
736
737impl AggLlmResponse {
738 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}