1use crate::{ModelError, content::ModelImage};
4use merry_core::{ErrorInfo, ToolCallResultStatus, ToolName};
5use schemars::{JsonSchema, Schema, SchemaGenerator};
6use serde::{Deserialize, Deserializer, Serialize, de};
7use serde_json::{Map, Value};
8use std::{borrow::Cow, collections::BTreeMap, fmt, str::FromStr};
9
10const MAX_PROVIDER_IDENTIFIER_LEN: usize = 256;
11
12#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, JsonSchema)]
14#[serde(transparent)]
15pub struct ModelToolCallId(String);
16
17impl ModelToolCallId {
18 pub fn new(value: &str) -> Result<Self, ModelError> {
20 validate_provider_identifier("ModelToolCallId", value)?;
21 Ok(Self(value.to_owned()))
22 }
23
24 #[must_use]
26 pub fn as_str(&self) -> &str {
27 &self.0
28 }
29}
30
31impl fmt::Display for ModelToolCallId {
32 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
33 formatter.write_str(&self.0)
34 }
35}
36
37impl FromStr for ModelToolCallId {
38 type Err = ModelError;
39
40 fn from_str(value: &str) -> Result<Self, Self::Err> {
41 Self::new(value)
42 }
43}
44
45impl TryFrom<&str> for ModelToolCallId {
46 type Error = ModelError;
47
48 fn try_from(value: &str) -> Result<Self, Self::Error> {
49 Self::new(value)
50 }
51}
52
53impl TryFrom<String> for ModelToolCallId {
54 type Error = ModelError;
55
56 fn try_from(value: String) -> Result<Self, Self::Error> {
57 validate_provider_identifier("ModelToolCallId", &value)?;
58 Ok(Self(value))
59 }
60}
61
62impl<'de> Deserialize<'de> for ModelToolCallId {
63 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
64 where
65 D: Deserializer<'de>,
66 {
67 let value = String::deserialize(deserializer)?;
68 Self::try_from(value).map_err(de::Error::custom)
69 }
70}
71
72#[derive(Debug, Clone, PartialEq, Serialize, JsonSchema)]
74#[serde(transparent)]
75pub struct ToolArguments(Map<String, Value>);
76
77impl ToolArguments {
78 #[must_use]
80 pub fn new(arguments: Map<String, Value>) -> Self {
81 Self(arguments)
82 }
83
84 #[must_use]
86 pub fn as_object(&self) -> &Map<String, Value> {
87 &self.0
88 }
89
90 #[must_use]
92 pub fn into_inner(self) -> Map<String, Value> {
93 self.0
94 }
95}
96
97impl TryFrom<Value> for ToolArguments {
98 type Error = ModelError;
99
100 fn try_from(value: Value) -> Result<Self, Self::Error> {
101 match value {
102 Value::Object(arguments) => Ok(Self(arguments)),
103 _ => Err(ModelError::invalid_request(
104 "ToolArguments must be a JSON object",
105 )),
106 }
107 }
108}
109
110impl From<ToolArguments> for Value {
111 fn from(arguments: ToolArguments) -> Self {
112 Value::Object(arguments.into_inner())
113 }
114}
115
116impl<'de> Deserialize<'de> for ToolArguments {
117 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
118 where
119 D: Deserializer<'de>,
120 {
121 let value = Value::deserialize(deserializer)?;
122 Self::try_from(value).map_err(de::Error::custom)
123 }
124}
125
126#[derive(Debug, Clone, PartialEq, Serialize, JsonSchema)]
128#[serde(deny_unknown_fields)]
129pub struct ModelToolCall {
130 id: ModelToolCallId,
131 name: ToolName,
132 arguments: ToolArguments,
133}
134
135impl ModelToolCall {
136 #[must_use]
138 pub fn new(id: ModelToolCallId, name: ToolName, arguments: ToolArguments) -> Self {
139 Self {
140 id,
141 name,
142 arguments,
143 }
144 }
145
146 #[must_use]
148 pub fn id(&self) -> &ModelToolCallId {
149 &self.id
150 }
151
152 #[must_use]
154 pub fn name(&self) -> &ToolName {
155 &self.name
156 }
157
158 #[must_use]
160 pub fn arguments(&self) -> &ToolArguments {
161 &self.arguments
162 }
163}
164
165#[derive(Deserialize)]
166#[serde(deny_unknown_fields)]
167struct ModelToolCallWire {
168 id: ModelToolCallId,
169 name: ToolName,
170 arguments: ToolArguments,
171}
172
173impl<'de> Deserialize<'de> for ModelToolCall {
174 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
175 where
176 D: Deserializer<'de>,
177 {
178 let wire = ModelToolCallWire::deserialize(deserializer)?;
179 Ok(Self::new(wire.id, wire.name, wire.arguments))
180 }
181}
182
183#[derive(Debug, Clone, PartialEq, Eq)]
185pub enum ModelToolResultContent {
186 Text(String),
188 Json(String),
190}
191
192impl ModelToolResultContent {
193 pub fn text(text: &str) -> Result<Self, ModelError> {
195 validate_tool_result_content("ModelToolResultContent text", text)?;
196 Ok(Self::Text(text.to_owned()))
197 }
198
199 pub fn json(json: &str) -> Result<Self, ModelError> {
201 validate_tool_result_content("ModelToolResultContent json", json)?;
202 Ok(Self::Json(json.to_owned()))
203 }
204
205 #[must_use]
207 pub fn as_text(&self) -> Option<&str> {
208 match self {
209 Self::Text(text) => Some(text),
210 Self::Json(_) => None,
211 }
212 }
213
214 #[must_use]
216 pub fn as_json(&self) -> Option<&str> {
217 match self {
218 Self::Text(_) => None,
219 Self::Json(json) => Some(json),
220 }
221 }
222
223 #[must_use]
225 pub fn as_str(&self) -> &str {
226 match self {
227 Self::Text(text) => text,
228 Self::Json(json) => json,
229 }
230 }
231}
232
233#[derive(Serialize)]
234#[serde(tag = "type", rename_all = "snake_case")]
235enum ModelToolResultContentRef<'a> {
236 Text { text: &'a str },
237 Json { json: &'a str },
238}
239
240impl Serialize for ModelToolResultContent {
241 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
242 where
243 S: serde::Serializer,
244 {
245 match self {
246 Self::Text(text) => ModelToolResultContentRef::Text { text }.serialize(serializer),
247 Self::Json(json) => ModelToolResultContentRef::Json { json }.serialize(serializer),
248 }
249 }
250}
251
252#[derive(Deserialize, JsonSchema)]
253#[serde(tag = "type", rename_all = "snake_case", deny_unknown_fields)]
254enum ModelToolResultContentWire {
255 Text { text: String },
256 Json { json: String },
257}
258
259impl<'de> Deserialize<'de> for ModelToolResultContent {
260 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
261 where
262 D: Deserializer<'de>,
263 {
264 match ModelToolResultContentWire::deserialize(deserializer)? {
265 ModelToolResultContentWire::Text { text } => {
266 Self::text(&text).map_err(de::Error::custom)
267 }
268 ModelToolResultContentWire::Json { json } => {
269 Self::json(&json).map_err(de::Error::custom)
270 }
271 }
272 }
273}
274
275impl JsonSchema for ModelToolResultContent {
276 fn schema_name() -> Cow<'static, str> {
277 "ModelToolResultContent".into()
278 }
279
280 fn schema_id() -> Cow<'static, str> {
281 concat!(module_path!(), "::ModelToolResultContent").into()
282 }
283
284 fn json_schema(generator: &mut SchemaGenerator) -> Schema {
285 ModelToolResultContentWire::json_schema(generator)
286 }
287}
288
289#[derive(Debug, Clone, PartialEq, Eq, Serialize, JsonSchema)]
291#[serde(deny_unknown_fields)]
292pub struct ModelToolResult {
293 call_id: ModelToolCallId,
294 status: ToolCallResultStatus,
295 content: ModelToolResultContent,
296 diagnostic: Option<ErrorInfo>,
297 #[serde(default, skip_serializing_if = "Vec::is_empty")]
298 images: Vec<ModelImage>,
299}
300
301impl ModelToolResult {
302 pub fn new(
304 call_id: ModelToolCallId,
305 status: ToolCallResultStatus,
306 content: ModelToolResultContent,
307 diagnostic: Option<ErrorInfo>,
308 ) -> Result<Self, ModelError> {
309 validate_result_diagnostic(status, diagnostic.as_ref())?;
310 Ok(Self {
311 call_id,
312 status,
313 content,
314 diagnostic,
315 images: Vec::new(),
316 })
317 }
318
319 #[must_use]
321 pub fn succeeded(call_id: ModelToolCallId, content: ModelToolResultContent) -> Self {
322 Self {
323 call_id,
324 status: ToolCallResultStatus::Succeeded,
325 content,
326 diagnostic: None,
327 images: Vec::new(),
328 }
329 }
330
331 #[must_use]
333 pub fn failed(
334 call_id: ModelToolCallId,
335 content: ModelToolResultContent,
336 diagnostic: ErrorInfo,
337 ) -> Self {
338 Self {
339 call_id,
340 status: ToolCallResultStatus::Failed,
341 content,
342 diagnostic: Some(diagnostic),
343 images: Vec::new(),
344 }
345 }
346
347 #[must_use]
349 pub fn with_images(mut self, images: Vec<ModelImage>) -> Self {
350 self.images = images;
351 self
352 }
353
354 #[must_use]
356 pub fn call_id(&self) -> &ModelToolCallId {
357 &self.call_id
358 }
359
360 #[must_use]
362 pub fn status(&self) -> ToolCallResultStatus {
363 self.status
364 }
365
366 #[must_use]
368 pub fn content(&self) -> &ModelToolResultContent {
369 &self.content
370 }
371
372 #[must_use]
374 pub fn diagnostic(&self) -> Option<&ErrorInfo> {
375 self.diagnostic.as_ref()
376 }
377
378 #[must_use]
380 pub fn images(&self) -> &[ModelImage] {
381 &self.images
382 }
383}
384
385#[derive(Deserialize)]
386#[serde(deny_unknown_fields)]
387struct ModelToolResultWire {
388 call_id: ModelToolCallId,
389 status: ToolCallResultStatus,
390 content: ModelToolResultContent,
391 diagnostic: Option<ErrorInfo>,
392 #[serde(default)]
393 images: Vec<ModelImage>,
394}
395
396impl<'de> Deserialize<'de> for ModelToolResult {
397 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
398 where
399 D: Deserializer<'de>,
400 {
401 let wire = ModelToolResultWire::deserialize(deserializer)?;
402 Ok(
403 Self::new(wire.call_id, wire.status, wire.content, wire.diagnostic)
404 .map_err(de::Error::custom)?
405 .with_images(wire.images),
406 )
407 }
408}
409
410#[derive(Debug, Clone, PartialEq, Serialize, JsonSchema)]
412#[serde(deny_unknown_fields)]
413pub struct ModelToolCallBatch {
414 calls: Vec<ModelToolCall>,
415}
416
417impl ModelToolCallBatch {
418 pub fn new(calls: Vec<ModelToolCall>) -> Result<Self, ModelError> {
420 if calls.is_empty() {
421 return Err(ModelError::invalid_request(
422 "ModelToolCallBatch calls must not be empty",
423 ));
424 }
425
426 let mut seen = BTreeMap::new();
427 for call in &calls {
428 if seen.insert(call.id(), ()).is_some() {
429 return Err(ModelError::invalid_request(format!(
430 "ModelToolCallBatch contains duplicate call id {}",
431 call.id()
432 )));
433 }
434 }
435
436 Ok(Self { calls })
437 }
438
439 #[must_use]
441 pub fn calls(&self) -> &[ModelToolCall] {
442 &self.calls
443 }
444}
445
446#[derive(Deserialize)]
447#[serde(deny_unknown_fields)]
448struct ModelToolCallBatchWire {
449 calls: Vec<ModelToolCall>,
450}
451
452impl<'de> Deserialize<'de> for ModelToolCallBatch {
453 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
454 where
455 D: Deserializer<'de>,
456 {
457 let wire = ModelToolCallBatchWire::deserialize(deserializer)?;
458 Self::new(wire.calls).map_err(de::Error::custom)
459 }
460}
461
462#[derive(Debug, Clone, PartialEq, Serialize, JsonSchema)]
464#[serde(deny_unknown_fields)]
465pub struct ModelToolBatchContinuation {
466 batch: ModelToolCallBatch,
467 results: Vec<ModelToolResult>,
468}
469
470impl ModelToolBatchContinuation {
471 pub fn new(
473 batch: ModelToolCallBatch,
474 results: Vec<ModelToolResult>,
475 ) -> Result<Self, ModelError> {
476 let mut results_by_id = BTreeMap::new();
477 for result in results {
478 let call_id = result.call_id().clone();
479 if results_by_id.insert(call_id.clone(), result).is_some() {
480 return Err(ModelError::invalid_request(format!(
481 "ModelToolBatchContinuation contains duplicate result for call id {call_id}"
482 )));
483 }
484 }
485
486 let mut ordered_results = Vec::with_capacity(batch.calls().len());
487 for call in batch.calls() {
488 let Some(result) = results_by_id.remove(call.id()) else {
489 return Err(ModelError::invalid_request(format!(
490 "ModelToolBatchContinuation is missing result for call id {}",
491 call.id()
492 )));
493 };
494 ordered_results.push(result);
495 }
496
497 if let Some(call_id) = results_by_id.keys().next() {
498 return Err(ModelError::invalid_request(format!(
499 "ModelToolBatchContinuation contains result for unknown call id {call_id}"
500 )));
501 }
502
503 Ok(Self {
504 batch,
505 results: ordered_results,
506 })
507 }
508
509 #[must_use]
511 pub fn batch(&self) -> &ModelToolCallBatch {
512 &self.batch
513 }
514
515 #[must_use]
517 pub fn results(&self) -> &[ModelToolResult] {
518 &self.results
519 }
520
521 pub(crate) fn single_continuations(&self) -> Vec<ModelToolContinuation> {
522 self.batch
523 .calls()
524 .iter()
525 .cloned()
526 .zip(self.results.iter().cloned())
527 .map(|(call, result)| {
528 ModelToolContinuation::new(call, result)
529 .expect("validated batch continuation ids remain aligned")
530 })
531 .collect()
532 }
533}
534
535#[derive(Deserialize)]
536#[serde(deny_unknown_fields)]
537struct ModelToolBatchContinuationWire {
538 batch: ModelToolCallBatch,
539 results: Vec<ModelToolResult>,
540}
541
542impl<'de> Deserialize<'de> for ModelToolBatchContinuation {
543 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
544 where
545 D: Deserializer<'de>,
546 {
547 let wire = ModelToolBatchContinuationWire::deserialize(deserializer)?;
548 Self::new(wire.batch, wire.results).map_err(de::Error::custom)
549 }
550}
551
552#[derive(Debug, Clone, PartialEq, Serialize, JsonSchema)]
554#[serde(deny_unknown_fields)]
555pub struct ModelToolContinuation {
556 call: ModelToolCall,
557 result: ModelToolResult,
558}
559
560impl ModelToolContinuation {
561 pub fn new(call: ModelToolCall, result: ModelToolResult) -> Result<Self, ModelError> {
563 if call.id() != result.call_id() {
564 return Err(ModelError::invalid_request(
565 "ModelToolContinuation call id must match result call_id",
566 ));
567 }
568
569 Ok(Self { call, result })
570 }
571
572 #[must_use]
574 pub fn call(&self) -> &ModelToolCall {
575 &self.call
576 }
577
578 #[must_use]
580 pub fn result(&self) -> &ModelToolResult {
581 &self.result
582 }
583}
584
585#[derive(Deserialize)]
586#[serde(deny_unknown_fields)]
587struct ModelToolContinuationWire {
588 call: ModelToolCall,
589 result: ModelToolResult,
590}
591
592impl<'de> Deserialize<'de> for ModelToolContinuation {
593 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
594 where
595 D: Deserializer<'de>,
596 {
597 let wire = ModelToolContinuationWire::deserialize(deserializer)?;
598 Self::new(wire.call, wire.result).map_err(de::Error::custom)
599 }
600}
601
602pub(crate) fn validate_provider_identifier(
603 kind: &'static str,
604 value: &str,
605) -> Result<(), ModelError> {
606 if value.is_empty() {
607 return Err(invalid_identifier(kind, "must not be empty"));
608 }
609
610 if value.trim().is_empty() {
611 return Err(invalid_identifier(kind, "must not be whitespace only"));
612 }
613
614 if value.trim() != value {
615 return Err(invalid_identifier(
616 kind,
617 "must not have leading or trailing whitespace",
618 ));
619 }
620
621 if value.chars().count() > MAX_PROVIDER_IDENTIFIER_LEN {
622 return Err(invalid_identifier(
623 kind,
624 "is longer than the allowed maximum length",
625 ));
626 }
627
628 if value.chars().any(char::is_control) {
629 return Err(invalid_identifier(
630 kind,
631 "must not contain control characters",
632 ));
633 }
634
635 Ok(())
636}
637
638fn invalid_identifier(kind: &'static str, reason: &'static str) -> ModelError {
639 ModelError::invalid_request(format!("{kind} {reason}"))
640}
641
642fn validate_tool_result_content(kind: &'static str, value: &str) -> Result<(), ModelError> {
643 if value.trim().is_empty() {
644 return Err(ModelError::invalid_request(format!(
645 "{kind} must not be blank"
646 )));
647 }
648
649 Ok(())
650}
651
652fn validate_result_diagnostic(
653 status: ToolCallResultStatus,
654 diagnostic: Option<&ErrorInfo>,
655) -> Result<(), ModelError> {
656 match (status, diagnostic) {
657 (ToolCallResultStatus::Succeeded, None) | (ToolCallResultStatus::Failed, Some(_)) => Ok(()),
658 (ToolCallResultStatus::Succeeded, Some(_)) => Err(ModelError::invalid_request(
659 "succeeded model tool result must not include a diagnostic",
660 )),
661 (ToolCallResultStatus::Failed, None) => Err(ModelError::invalid_request(
662 "failed model tool result must include a diagnostic",
663 )),
664 }
665}
666
667#[cfg(test)]
668mod tests {
669 use super::*;
670 use std::sync::Arc;
671
672 #[test]
673 fn model_tool_result_omits_empty_images_and_round_trips_attached_images() {
674 let call_id = ModelToolCallId::new("call_1").expect("valid call id");
675 let content = ModelToolResultContent::text("ok").expect("valid content");
676 let plain = ModelToolResult::succeeded(call_id.clone(), content.clone());
677 let plain_json = serde_json::to_value(&plain).expect("plain result serializes");
678 assert!(plain_json.get("images").is_none());
679
680 let image = ModelImage::png(
681 "snapshot.png",
682 Arc::<[u8]>::from([137, 80, 78, 71, 13, 10, 26, 10, 42]),
683 1,
684 1,
685 )
686 .expect("valid png");
687 let with_images = ModelToolResult::succeeded(call_id, content).with_images(vec![image]);
688 assert_eq!(with_images.images().len(), 1);
689
690 let encoded = serde_json::to_string(&with_images).expect("image result serializes");
691 let decoded: ModelToolResult =
692 serde_json::from_str(&encoded).expect("image result deserializes");
693 assert_eq!(decoded, with_images);
694 }
695}