rig_core/tool/decode.rs
1//! A tool call's arguments decoded into the tool's arguments type, the one
2//! way every tool path decodes them. A model may send a whole number as a
3//! float, such as `30.0`, which the schema check accepts as an integer
4//! ([`validate`](crate::tool::validate)); where the type asks for an
5//! integer, it gets that integer. A fraction, a number out of the type's
6//! range and a negative number for an unsigned type are refused, never
7//! rounded.
8//!
9//! ```
10//! use serde::Deserialize;
11//! use serde_json::json;
12//!
13//! #[derive(Deserialize)]
14//! struct Args {
15//! limit: u32,
16//! scale: f64,
17//! }
18//!
19//! let args: Args = rig_core::tool::decode_args(&json!({"limit": 30.0, "scale": 2.0}))?;
20//! assert_eq!((args.limit, args.scale), (30, 2.0));
21//! assert!(rig_core::tool::decode_args::<Args>(&json!({"limit": 1.5, "scale": 2.0})).is_err());
22//! # Ok::<(), serde_json::Error>(())
23//! ```
24
25use serde::de::DeserializeOwned;
26use serde_json::{Number, Value};
27
28/// `args` as the arguments type `A`. Arguments are decoded as sent first,
29/// and those that decode so reach `A` exactly as sent. Others are decoded
30/// once more with each integral float in them as its integer, one bound
31/// for a `serde_json::Value` or `f64` field too.
32///
33/// # Errors
34///
35/// When `args` does not fit `A` either way: the error of the second try
36/// when there was one, else of the arguments as sent.
37pub fn decode_args<A: DeserializeOwned>(args: &Value) -> Result<A, serde_json::Error> {
38 crate::json_utils::from_value(args).or_else(|error| as_integers(args).unwrap_or(Err(error)))
39}
40
41/// [`decode_args`] for arguments as JSON text, decoded straight from the
42/// text first. A call that decodes today decodes the same, and one refused
43/// with no whole float in it is refused with the same words, its line and
44/// column named. Only the retry reads the text as a `Value`, which keeps
45/// the last of a repeated key, as a call's arguments (a JSON object)
46/// always have.
47pub(crate) fn decode_text<A: DeserializeOwned>(args: &str) -> Result<A, serde_json::Error> {
48 serde_json::from_str(args).or_else(|error| match serde_json::from_str::<Value>(args) {
49 Ok(value) => as_integers(&value).unwrap_or(Err(error)),
50 Err(_) => Err(error),
51 })
52}
53
54/// `args` decoded with each integral float as its integer; `None` when it
55/// has none, so a second try would fail as the first did.
56fn as_integers<A: DeserializeOwned>(args: &Value) -> Option<Result<A, serde_json::Error>> {
57 let mut whole = args.clone();
58 integers(&mut whole).then(|| crate::json_utils::from_value(&whole))
59}
60
61/// Makes each float in `value` that is a [`Whole`] number that integer;
62/// whether it made any.
63fn integers(value: &mut Value) -> bool {
64 match value {
65 Value::Number(number) if number.is_f64() => match whole(number) {
66 Some(Whole::Unsigned(unsigned)) => {
67 *number = unsigned.into();
68 true
69 }
70 Some(Whole::Signed(signed)) => {
71 *number = signed.into();
72 true
73 }
74 None => false,
75 },
76 Value::Array(items) => {
77 let mut any = false;
78 for item in items {
79 any |= integers(item);
80 }
81 any
82 }
83 Value::Object(fields) => {
84 let mut any = false;
85 for field in fields.values_mut() {
86 any |= integers(field);
87 }
88 any
89 }
90 _ => false,
91 }
92}
93
94/// The whole number a JSON number is: an integer, or a float with no
95/// fraction that a 64-bit integer holds exactly, such as `30.0`. What
96/// counts as an integer, for the schema check and for decoding alike.
97#[derive(Clone, Copy, Debug, PartialEq, Eq)]
98pub(crate) enum Whole {
99 Signed(i64),
100 Unsigned(u64),
101}
102
103/// The [`Whole`] number `number` is, if it is one.
104pub(crate) fn whole(number: &Number) -> Option<Whole> {
105 if let Some(unsigned) = number.as_u64() {
106 return Some(Whole::Unsigned(unsigned));
107 }
108 if let Some(signed) = number.as_i64() {
109 return Some(Whole::Signed(signed));
110 }
111 let float = number.as_f64().filter(|float| float.fract() == 0.0)?;
112 // Both bounds are powers of two, exact in an `f64`, so each cast below
113 // is of a whole number inside the integer's range, and exact.
114 if (0.0..18_446_744_073_709_551_616.0).contains(&float) {
115 Some(Whole::Unsigned(float as u64))
116 } else if (-9_223_372_036_854_775_808.0..0.0).contains(&float) {
117 Some(Whole::Signed(float as i64))
118 } else {
119 None
120 }
121}
122
123#[cfg(test)]
124mod tests;