1use std::collections::BTreeMap;
5use std::fmt;
6use std::sync::Arc;
7
8use futures::future::BoxFuture;
9use serde::{Deserialize, Serialize};
10
11use crate::value::Value;
12
13#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
15pub struct ToolSpec {
16 pub name: String,
18 pub description: String,
19 pub parameters: serde_json::Value,
21}
22
23#[derive(Clone, Debug, Default, PartialEq)]
25pub struct ToolOutput {
26 pub text: String,
28 pub data: Value,
30 pub is_error: bool,
32 pub images: Vec<ToolImage>,
34}
35
36impl ToolOutput {
37 pub fn text(text: impl Into<String>) -> Self {
38 Self { text: text.into(), ..Self::default() }
39 }
40
41 pub fn error(text: impl Into<String>) -> Self {
42 Self { text: text.into(), is_error: true, ..Self::default() }
43 }
44
45 pub fn with_image(mut self, image: ToolImage) -> Self {
47 self.images.push(image);
48 self
49 }
50}
51
52pub const MAX_TOOL_IMAGES: usize = 4;
54pub const MAX_TOOL_IMAGE_BYTES: usize = 5 * 1024 * 1024;
56pub const TOOL_IMAGE_MEDIA_TYPES: &[&str] = &["image/png", "image/jpeg", "image/webp", "image/gif"];
58
59#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
64#[serde(untagged)]
65pub enum ToolImage {
66 Base64 { media_type: String, data_base64: String },
68 Url { url: String },
70}
71
72impl ToolImage {
73 pub fn png(data_base64: impl Into<String>) -> Self {
75 Self::Base64 { media_type: "image/png".into(), data_base64: data_base64.into() }
76 }
77
78 pub fn jpeg(data_base64: impl Into<String>) -> Self {
80 Self::Base64 { media_type: "image/jpeg".into(), data_base64: data_base64.into() }
81 }
82
83 pub fn to_url(&self) -> String {
85 match self {
86 ToolImage::Base64 { media_type, data_base64 } => format!("data:{media_type};base64,{data_base64}"),
87 ToolImage::Url { url } => url.clone(),
88 }
89 }
90
91 pub fn check(&self) -> Result<(), ToolImageError> {
93 match self {
94 ToolImage::Url { url } => {
95 if url.len() > 8 && url.get(..8).is_some_and(|scheme| scheme.eq_ignore_ascii_case("https://")) {
96 Ok(())
97 } else {
98 Err(ToolImageError::new("image URLs must start with https:// (send inline images as base64)"))
99 }
100 }
101 ToolImage::Base64 { media_type, data_base64 } => {
102 if !TOOL_IMAGE_MEDIA_TYPES.contains(&media_type.as_str()) {
103 return Err(ToolImageError::new(format!(
104 "image media type `{media_type}` is not supported (use {})",
105 TOOL_IMAGE_MEDIA_TYPES.join(", ")
106 )));
107 }
108 let decoded = base64_decoded_len(data_base64)
109 .ok_or_else(|| ToolImageError::new("image data is not valid base64"))?;
110 if decoded == 0 {
111 return Err(ToolImageError::new("image data is empty"));
112 }
113 if decoded > MAX_TOOL_IMAGE_BYTES {
114 return Err(ToolImageError::new(format!(
115 "image is {decoded} bytes, above the {MAX_TOOL_IMAGE_BYTES}-byte limit"
116 )));
117 }
118 Ok(())
119 }
120 }
121 }
122}
123
124#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)]
126#[error("{0}")]
127pub struct ToolImageError(pub String);
128
129impl ToolImageError {
130 fn new(message: impl Into<String>) -> Self {
131 Self(message.into())
132 }
133}
134
135pub fn check_images(images: &[ToolImage]) -> Result<(), ToolImageError> {
138 if images.len() > MAX_TOOL_IMAGES {
139 return Err(ToolImageError::new(format!(
140 "{} images in one tool result, above the limit of {MAX_TOOL_IMAGES}",
141 images.len()
142 )));
143 }
144 for (index, image) in images.iter().enumerate() {
145 image.check().map_err(|e| ToolImageError::new(format!("image #{index}: {e}")))?;
146 }
147 Ok(())
148}
149
150fn base64_decoded_len(text: &str) -> Option<usize> {
153 let bytes = text.as_bytes();
154 let body = bytes.strip_suffix(b"==").or_else(|| bytes.strip_suffix(b"=")).unwrap_or(bytes);
155 let alphabet = |b: &u8| b.is_ascii_alphanumeric() || *b == b'+' || *b == b'/';
156 if !body.iter().all(alphabet) {
157 return None;
158 }
159 let padded = body.len() != bytes.len();
160 if padded && !bytes.len().is_multiple_of(4) {
161 return None;
162 }
163 match body.len() % 4 {
164 1 => None,
165 rest => Some(body.len() / 4 * 3 + rest.saturating_sub(1)),
166 }
167}
168
169pub const MAX_TOOL_FILES: usize = 16;
171const MAX_FILE_SCAN_DEPTH: usize = 3;
173
174pub fn collect_files(data: &Value) -> Vec<Arc<crate::value::File>> {
194 let mut files = Vec::new();
195 collect_files_into(data, 0, &mut files);
196 files
197}
198
199fn collect_files_into(value: &Value, depth: usize, files: &mut Vec<Arc<crate::value::File>>) {
200 if files.len() >= MAX_TOOL_FILES {
201 return;
202 }
203 match value {
204 Value::File(file) => files.push(Arc::clone(file)),
205 Value::Array(items) if depth < MAX_FILE_SCAN_DEPTH => {
206 items.iter().for_each(|item| collect_files_into(item, depth + 1, files));
207 }
208 Value::Object(fields) if depth < MAX_FILE_SCAN_DEPTH => {
209 fields.values().for_each(|field| collect_files_into(field, depth + 1, files));
210 }
211 _ => {}
212 }
213}
214
215#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)]
217#[error("tool `{tool}`: {message}")]
218pub struct ToolError {
219 pub tool: String,
220 pub message: String,
221}
222
223#[derive(Clone, Default, PartialEq, Eq)]
232pub struct ToolCallContext {
233 pub secrets: BTreeMap<String, String>,
235}
236
237static EMPTY_TOOL_CALL_CONTEXT: ToolCallContext = ToolCallContext { secrets: BTreeMap::new() };
238
239impl ToolCallContext {
240 pub fn empty() -> &'static ToolCallContext {
242 &EMPTY_TOOL_CALL_CONTEXT
243 }
244
245 pub fn is_empty(&self) -> bool {
247 self.secrets.is_empty()
248 }
249
250 pub fn secret(&self, name: &str) -> Option<&str> {
252 self.secrets.get(name).map(String::as_str)
253 }
254}
255
256impl fmt::Debug for ToolCallContext {
257 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
258 f.debug_struct("ToolCallContext").field("secrets", &self.secrets.keys().collect::<Vec<_>>()).finish()
259 }
260}
261
262pub trait ToolRuntime: Send + Sync + fmt::Debug {
264 fn list(&self) -> BoxFuture<'_, Result<Vec<ToolSpec>, ToolError>>;
266
267 fn call<'a>(
272 &'a self,
273 name: &'a str,
274 arguments: serde_json::Value,
275 context: &'a ToolCallContext,
276 ) -> BoxFuture<'a, Result<ToolOutput, ToolError>>;
277
278 fn accepts_secrets(&self) -> bool {
283 false
284 }
285}
286
287#[derive(Clone, Default)]
290pub struct ToolRegistry {
291 providers: indexmap::IndexMap<String, Arc<dyn ToolRuntime>>,
292}
293
294impl fmt::Debug for ToolRegistry {
295 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
296 f.debug_list().entries(self.providers.keys()).finish()
297 }
298}
299
300impl ToolRegistry {
301 pub fn new() -> Self {
302 Self::default()
303 }
304
305 pub fn add(&mut self, provider: impl Into<String>, runtime: Arc<dyn ToolRuntime>) -> &mut Self {
306 self.providers.insert(provider.into(), runtime);
307 self
308 }
309
310 pub fn get(&self, provider: &str) -> Option<&Arc<dyn ToolRuntime>> {
311 self.providers.get(provider)
312 }
313
314 pub fn providers(&self) -> impl Iterator<Item = (&str, &Arc<dyn ToolRuntime>)> {
315 self.providers.iter().map(|(k, v)| (k.as_str(), v))
316 }
317}
318
319#[cfg(test)]
320mod tests {
321 use super::*;
322
323 #[test]
324 fn call_context_debug_hides_values() {
325 assert!(ToolCallContext::empty().is_empty());
326 let mut context = ToolCallContext::default();
327 context.secrets.insert("user_jwt".into(), "eyJ-secret-token".into());
328 assert_eq!(context.secret("user_jwt"), Some("eyJ-secret-token"));
329 assert_eq!(context.secret("other"), None);
330 let debug = format!("{context:?}");
331 assert!(debug.contains("user_jwt") && !debug.contains("eyJ-secret-token"), "{debug}");
332 }
333
334 #[test]
335 fn files_are_collected_in_order_up_to_the_cap() {
336 let file =
337 |name: &str| Value::from(crate::value::File { marker: true, name: name.into(), ..Default::default() });
338 let names = |data: &Value| collect_files(data).iter().map(|f| f.name.clone()).collect::<Vec<_>>();
339 assert_eq!(names(&file("a")), ["a"]);
340 let nested = Value::object([
341 ("file", file("a")),
342 ("files", Value::array([file("b"), file("c")])),
343 ("text", Value::from("x")),
344 ]);
345 assert_eq!(names(&nested), ["a", "b", "c"]);
346 let deep = Value::array([Value::array([Value::array([Value::array([file("deep")])])])]);
348 assert!(names(&deep).is_empty());
349 let many = Value::array((0..MAX_TOOL_FILES + 5).map(|i| file(&i.to_string())));
350 assert_eq!(collect_files(&many).len(), MAX_TOOL_FILES);
351 assert!(collect_files(&Value::Null).is_empty());
352 }
353
354 #[test]
355 fn constructors_have_no_images() {
356 assert!(ToolOutput::text("a").images.is_empty());
357 let err = ToolOutput::error("b");
358 assert!(err.is_error && err.images.is_empty());
359 let out = ToolOutput::text("shot").with_image(ToolImage::png("aGVsbG8="));
360 assert_eq!(out.images.len(), 1);
361 }
362
363 #[test]
364 fn image_urls() {
365 assert_eq!(ToolImage::png("AAAA").to_url(), "data:image/png;base64,AAAA");
366 assert_eq!(ToolImage::Url { url: "https://x/a.png".into() }.to_url(), "https://x/a.png");
367 }
368
369 #[test]
370 fn serde_shapes() {
371 let images: Vec<ToolImage> = serde_json::from_value(serde_json::json!([
372 {"media_type": "image/png", "data_base64": "AAAA"},
373 {"url": "https://x/a.png"}
374 ]))
375 .unwrap();
376 assert_eq!(images[0], ToolImage::png("AAAA"));
377 assert_eq!(images[1], ToolImage::Url { url: "https://x/a.png".into() });
378 assert!(serde_json::from_value::<ToolImage>(serde_json::json!({"data": "AAAA"})).is_err());
379 }
380
381 #[test]
382 fn base64_lengths() {
383 assert_eq!(base64_decoded_len("aGVsbG8="), Some(5));
384 assert_eq!(base64_decoded_len("aGVsbG8"), Some(5));
385 assert_eq!(base64_decoded_len("aGVsbA=="), Some(4));
386 assert_eq!(base64_decoded_len("aGVs"), Some(3));
387 assert_eq!(base64_decoded_len("aGVsb"), None);
388 assert_eq!(base64_decoded_len("aGV="), Some(2));
389 assert_eq!(base64_decoded_len("aG V"), None);
390 assert_eq!(base64_decoded_len("aGVsbG8=="), None);
391 assert_eq!(base64_decoded_len(""), Some(0));
392 }
393
394 #[test]
395 fn limits_are_enforced() {
396 assert!(check_images(&[ToolImage::png("aGVsbG8="), ToolImage::jpeg("aGVs")]).is_ok());
397 let too_many = vec![ToolImage::png("aGVs"); MAX_TOOL_IMAGES + 1];
398 assert!(check_images(&too_many).unwrap_err().to_string().contains("limit of 4"));
399 let bmp = ToolImage::Base64 { media_type: "image/bmp".into(), data_base64: "aGVs".into() };
400 assert!(check_images(&[bmp]).unwrap_err().to_string().contains("image/bmp"));
401 assert!(ToolImage::png("not base64!").check().is_err());
402 assert!(ToolImage::png("").check().is_err());
403 let big = "A".repeat((MAX_TOOL_IMAGE_BYTES / 3 + 1) * 4);
404 assert!(ToolImage::png(big).check().unwrap_err().to_string().contains("limit"));
405 let exact = "A".repeat(MAX_TOOL_IMAGE_BYTES / 3 * 4);
406 assert!(ToolImage::png(exact).check().is_ok());
407 assert!(ToolImage::Url { url: "http://x/a.png".into() }.check().is_err());
408 assert!(ToolImage::Url { url: "data:image/png;base64,AAAA".into() }.check().is_err());
409 assert!(ToolImage::Url { url: "HTTPS://x/a.png".into() }.check().is_ok());
410 }
411}