rig-agent 0.43.0

Rig's classic agent runtime.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
use crate::test_utils::{
    MockExampleTool, MockImageOutputTool, MockObjectOutputTool, MockStringOutputTool,
    MockToolError, mock_math_toolset,
};
use portable_fixtures::{
    PortableEmbeddingFixture, context_free_dynamic_fixture, portable_fixture_output,
};
use rig_core::embeddings::tool::ToolSchema;
use rig_core::message::{DocumentSourceKind, ToolResultContent};
use serde_json::json;

use super::*;

/// Portable-tool fixtures relocated from the removed `rig-runtime-conformance`
/// crate; used only by these migrated tests.
mod portable_fixtures {
    use rig_core::{
        message::{ImageMediaType, ToolResultContent},
        tool::{DynamicTool, PortableTool, PortableToolEmbedding, ToolExecutionError, ToolOutput},
    };
    use serde::{Deserialize, Serialize};

    const PORTABLE_FIXTURE_IMAGE: &str = "cG9ydGFibGUtZml4dHVyZQ==";

    #[derive(Clone, Debug, Deserialize, Serialize)]
    pub struct PortableEmbeddingArgs {
        pub value: String,
        #[serde(default)]
        pub fail: bool,
    }

    #[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
    pub struct PortableEmbeddingContext {
        pub prefix: String,
    }

    #[derive(Debug, thiserror::Error)]
    #[error("portable fixture failure")]
    pub struct PortableFixtureError;

    pub fn portable_fixture_output(label: impl Into<String>) -> ToolOutput {
        let mut content = vec![ToolResultContent::json(
            serde_json::json!({"label": label.into()}),
        )];
        content.push(ToolResultContent::image_base64(
            PORTABLE_FIXTURE_IMAGE,
            Some(ImageMediaType::PNG),
            None,
        ));
        ToolOutput::content(content).expect("fixture content is non-empty")
    }

    pub fn context_free_dynamic_fixture() -> DynamicTool {
        DynamicTool::new(
            "dynamic_runtime_name",
            "context-free dynamic definition",
            serde_json::json!({
                "type": "object",
                "properties": {
                    "value": {"type": "string"},
                    "fail": {"type": "boolean"}
                },
                "required": ["value"]
            }),
            |arguments| {
                Box::pin(async move {
                    if arguments
                        .get("fail")
                        .and_then(serde_json::Value::as_bool)
                        .unwrap_or_default()
                    {
                        Err(ToolExecutionError::provider("context-free dynamic failure")
                            .with_code("context_free_dynamic_fixture")
                            .with_model_output(portable_fixture_output(
                                "context-free dynamic failure",
                            )))
                    } else {
                        Ok(portable_fixture_output(format!(
                            "dynamic:{}",
                            arguments
                                .get("value")
                                .and_then(serde_json::Value::as_str)
                                .unwrap_or_default()
                        )))
                    }
                })
            },
        )
    }

    #[derive(Clone)]
    pub struct PortableEmbeddingFixture {
        context: PortableEmbeddingContext,
    }

    impl PortableEmbeddingFixture {
        pub fn new(prefix: impl Into<String>) -> Self {
            Self {
                context: PortableEmbeddingContext {
                    prefix: prefix.into(),
                },
            }
        }
    }

    impl PortableTool for PortableEmbeddingFixture {
        const NAME: &'static str = "portable_embedding_fixture";
        type Args = PortableEmbeddingArgs;
        type Output = ToolOutput;
        type Error = PortableFixtureError;

        fn description(&self) -> String {
            format!("{} portable embedding fixture", self.context.prefix)
        }

        fn parameters(&self) -> serde_json::Value {
            serde_json::json!({
                "type": "object",
                "properties": {
                    "value": {"type": "string"},
                    "fail": {"type": "boolean"}
                },
                "required": ["value"]
            })
        }

        fn map_error(&self, error: Self::Error) -> ToolExecutionError {
            ToolExecutionError::provider(error.to_string())
                .with_code("portable_fixture")
                .with_model_output(portable_fixture_output("portable failure"))
                .with_source(error)
        }

        async fn call(&self, arguments: Self::Args) -> Result<Self::Output, Self::Error> {
            if arguments.fail {
                Err(PortableFixtureError)
            } else {
                Ok(portable_fixture_output(format!(
                    "{}:{}",
                    self.context.prefix, arguments.value
                )))
            }
        }
    }

    impl PortableToolEmbedding for PortableEmbeddingFixture {
        type InitError = std::convert::Infallible;
        type Context = PortableEmbeddingContext;
        type State = ();

        fn embedding_docs(&self) -> Vec<String> {
            vec![format!(
                "{} portable embedding document",
                self.context.prefix
            )]
        }

        fn context(&self) -> Self::Context {
            self.context.clone()
        }

        fn init(_state: Self::State, context: Self::Context) -> Result<Self, Self::InitError> {
            Ok(Self { context })
        }
    }
}

fn get_test_toolset() -> ToolSet {
    mock_math_toolset()
}

#[test]
fn test_get_tool_definitions() {
    let toolset = get_test_toolset();
    let tools = toolset.tool_definitions();
    assert_eq!(tools.len(), 2);
    assert_eq!(
        tools
            .iter()
            .map(|tool| tool.name.as_str())
            .collect::<Vec<_>>(),
        vec!["add", "subtract"],
        "provider definitions must use registered tool names in order"
    );
    assert!(tools.iter().all(|tool| !tool.description.is_empty()));
    assert!(tools.iter().all(|tool| tool.parameters.is_object()));
}

#[test]
fn test_tool_deletion() {
    let mut toolset = get_test_toolset();
    assert_eq!(toolset.len(), 2);
    toolset.remove_tool("add");
    assert!(!toolset.contains("add"));
    assert_eq!(toolset.len(), 1);
    assert_eq!(
        toolset.names().map(str::to_owned).collect::<Vec<_>>(),
        vec!["subtract".to_string()]
    );
}

#[test]
fn deleting_a_middle_tool_preserves_order_of_survivors() {
    // Guards the `shift_remove` (not `swap_remove`) choice in `remove_tool`.
    // `swap_remove` would move the last tool into the deleted slot, so this
    // only catches a regression with 3+ tools and a non-last deletion: here
    // a `swap_remove("beta")` would yield [alpha, delta, gamma].
    let mut toolset = ToolSet::default();
    for name in ["alpha", "beta", "gamma", "delta"] {
        toolset.add_dynamic_tool(named_tool(name, "test tool"));
    }

    toolset.remove_tool("beta");

    assert_eq!(
        toolset.names().map(str::to_owned).collect::<Vec<_>>(),
        vec![
            "alpha".to_string(),
            "gamma".to_string(),
            "delta".to_string()
        ],
        "survivors must keep their registration order after a middle deletion"
    );
}

/// A runtime-defined tool used by ordering and duplicate-registration tests.
fn named_tool(name: &str, description: &str) -> DynamicTool {
    let output = format!("called {description}");
    DynamicTool::new(
        name,
        description,
        json!({ "type": "object", "properties": {} }),
        move |_args| {
            let output = output.clone();
            Box::pin(async move { Ok(ToolOutput::text(output)) })
        },
    )
}

#[test]
fn tool_definition_uses_flattened_dyn_metadata() {
    let tool = named_tool("alpha", "runtime description");
    let definition = tool.definition();

    assert_eq!(definition.name, "alpha");
    assert_eq!(definition.description, "runtime description");
    assert_eq!(definition.parameters["type"], "object");
}

#[tokio::test]
async fn tool_definitions_follow_registration_order() {
    // Enough names that any non-order-preserving storage would almost
    // surely surface a regression: its iteration order would differ from
    // insertion order.
    let names: Vec<String> = (0..32).map(|i| format!("tool_{i:02}")).collect();
    let mut toolset = ToolSet::default();
    for name in &names {
        toolset.add_dynamic_tool(named_tool(name, "test tool"));
    }

    let defs = toolset.tool_definitions();
    let def_names: Vec<String> = defs.into_iter().map(|def| def.name).collect();
    assert_eq!(def_names, names);

    let docs = toolset.documents();
    let doc_ids: Vec<String> = docs.into_iter().map(|doc| doc.id).collect();
    assert_eq!(doc_ids, names);
}

#[tokio::test]
async fn typed_tool_name_is_definition_source_of_truth() {
    struct NamedTool;

    impl Tool for NamedTool {
        const NAME: &'static str = "canonical";
        type Error = rig::tool::ToolExecutionError;
        type Args = serde_json::Value;
        type Output = String;

        fn description(&self) -> String {
            "uses the canonical typed name".to_string()
        }
        fn parameters(&self) -> serde_json::Value {
            json!({ "type": "object", "properties": {} })
        }
        async fn call(
            &self,
            _context: &mut ToolContext,
            _args: Self::Args,
        ) -> Result<Self::Output, ToolExecutionError> {
            Ok("ok".to_string())
        }
    }

    let mut toolset = ToolSet::default();
    toolset.add_tool(NamedTool);

    let defs = toolset.tool_definitions();
    assert_eq!(defs[0].name, NamedTool::NAME);

    let docs = toolset.documents();
    assert_eq!(docs[0].id, NamedTool::NAME);
    assert!(docs[0].text.contains(NamedTool::NAME));
}

#[test]
fn retrieved_tool_schemas_use_canonical_name() {
    #[derive(Debug, thiserror::Error)]
    #[error("init error")]
    struct InitError;

    struct RetrievedTool;

    impl Tool for RetrievedTool {
        const NAME: &'static str = "retrieved";
        type Error = rig::tool::ToolExecutionError;
        type Args = serde_json::Value;
        type Output = String;

        fn description(&self) -> String {
            "dynamic tool".to_string()
        }

        fn parameters(&self) -> serde_json::Value {
            json!({ "type": "object", "properties": {} })
        }

        async fn call(
            &self,
            _context: &mut ToolContext,
            _args: Self::Args,
        ) -> Result<Self::Output, ToolExecutionError> {
            Ok("ok".to_string())
        }
    }

    impl ToolEmbedding for RetrievedTool {
        type InitError = InitError;
        type Context = ();
        type State = ();

        fn embedding_docs(&self) -> Vec<String> {
            vec!["dynamic tool docs".to_string()]
        }

        fn context(&self) -> Self::Context {}

        fn init(_state: Self::State, _context: Self::Context) -> Result<Self, Self::InitError> {
            Ok(Self)
        }
    }

    let mut toolset = ToolSet::default();
    toolset
        .add_retrieved_tool(RetrievedTool)
        .expect("the tool context serializes");

    let schemas = toolset.schemas().unwrap();
    assert_eq!(schemas.len(), 1);
    assert_eq!(schemas[0].name, RetrievedTool::NAME);
    assert_eq!(schemas[0].embedding_docs, vec!["dynamic tool docs"]);
}

#[tokio::test]
async fn portable_embedding_tool_uses_classic_retrieval_without_schema_drift() {
    let tool = PortableEmbeddingFixture::new("shared");
    let portable_schema = ToolSchema::try_from(&tool).unwrap();
    let mut toolset = ToolSet::default();
    toolset
        .add_retrieved_tool(tool)
        .expect("the tool context serializes");

    let schemas = toolset.schemas().unwrap();
    assert_eq!(schemas.len(), 1);
    assert_eq!(schemas[0].name, portable_schema.name);
    assert_eq!(schemas[0].context, portable_schema.context);
    assert_eq!(schemas[0].embedding_docs, portable_schema.embedding_docs);

    let handle = server::ToolServer::new()
        .retrieved_tools(
            1,
            crate::test_utils::MockToolIndex::new([portable_schema.name.as_str()]),
            toolset,
        )
        .run();
    let definitions = handle
        .tool_defs(Some("find the shared portable tool".to_string()))
        .await
        .unwrap();

    assert_eq!(definitions.len(), 1);
    assert_eq!(definitions[0].name, portable_schema.name);
    assert_eq!(
        definitions[0].description,
        "shared portable embedding fixture"
    );
    assert_eq!(
        definitions[0].parameters,
        serde_json::json!({
            "type": "object",
            "properties": {
                "value": {"type": "string"},
                "fail": {"type": "boolean"}
            },
            "required": ["value"]
        })
    );

    let success = handle
        .execute(
            &definitions[0].name,
            r#"{"value":"ok"}"#,
            &mut ToolContext::new(),
        )
        .await;
    assert!(success.is_success());
    assert_eq!(success.output(), &portable_fixture_output("shared:ok"));

    let failure = handle
        .execute(
            &definitions[0].name,
            r#"{"value":"ignored","fail":true}"#,
            &mut ToolContext::new(),
        )
        .await;
    let error = failure
        .error()
        .expect("portable failure should be retained");
    assert_eq!(error.kind(), ToolErrorKind::Provider);
    assert_eq!(error.code(), Some("portable_fixture"));
    assert_eq!(
        error.model_output(),
        &portable_fixture_output("portable failure")
    );
    assert_eq!(failure.output(), error.model_output());
}

#[tokio::test]
async fn context_free_dynamic_tool_executes_in_classic_registry_without_callback_rewrite() {
    let tool = context_free_dynamic_fixture();
    let mut toolset = ToolSet::default();
    toolset.add_dynamic_tool(named_tool("before", "before"));
    let registered_name = toolset.add_dynamic_tool(tool);
    toolset.add_dynamic_tool(named_tool("after", "after"));

    assert_eq!(registered_name, "dynamic_runtime_name");
    assert_eq!(
        toolset
            .tool_definitions()
            .iter()
            .map(|definition| definition.name.as_str())
            .collect::<Vec<_>>(),
        ["before", "dynamic_runtime_name", "after"]
    );

    let result = toolset
        .execute(
            "dynamic_runtime_name",
            r#"{"value":"ok"}"#,
            &mut ToolContext::new(),
        )
        .await;
    assert!(result.is_success());
    assert_eq!(result.output(), &portable_fixture_output("dynamic:ok"));

    let failure = toolset
        .execute(
            "dynamic_runtime_name",
            r#"{"value":"ignored","fail":true}"#,
            &mut ToolContext::new(),
        )
        .await;
    assert!(failure.is_error());
    let error = failure
        .error()
        .expect("context-free dynamic failure should be retained");
    assert_eq!(error.kind(), ToolErrorKind::Provider);
    assert_eq!(error.code(), Some("context_free_dynamic_fixture"));
    assert_eq!(
        error.model_output(),
        &portable_fixture_output("context-free dynamic failure")
    );
    assert_eq!(failure.output(), error.model_output());
}

#[tokio::test]
async fn duplicate_registration_replaces_in_place() {
    let mut toolset = ToolSet::default();
    toolset.add_dynamic_tool(named_tool("alpha", "first alpha"));
    toolset.add_dynamic_tool(named_tool("beta", "beta"));
    toolset.add_dynamic_tool(named_tool("alpha", "second alpha"));

    let defs = toolset.tool_definitions();
    assert_eq!(
        defs.iter().map(|def| def.name.as_str()).collect::<Vec<_>>(),
        vec!["alpha", "beta"],
        "the duplicate should be deduped and keep its original position"
    );
    assert_eq!(
        defs[0].description, "second alpha",
        "the last registration should win"
    );

    let output = toolset
        .execute("alpha", "{}", &mut ToolContext::new())
        .await
        .output()
        .render();
    assert_eq!(output, "called second alpha");
}

#[tokio::test]
async fn add_tools_merges_in_order_and_replaces_existing() {
    let mut base = ToolSet::default();
    base.add_dynamic_tool(named_tool("alpha", "base alpha"));
    base.add_dynamic_tool(named_tool("beta", "base beta"));

    let mut incoming = ToolSet::default();
    incoming.add_dynamic_tool(named_tool("gamma", "incoming gamma"));
    incoming.add_dynamic_tool(named_tool("alpha", "incoming alpha"));

    base.add_tools(incoming);

    let defs = base.tool_definitions();
    assert_eq!(
        defs.iter().map(|def| def.name.as_str()).collect::<Vec<_>>(),
        vec!["alpha", "beta", "gamma"],
        "merged tools should follow registration order with replaced names keeping position"
    );
    assert_eq!(defs[0].description, "incoming alpha");
}

#[tokio::test]
async fn string_tool_outputs_are_preserved_verbatim() {
    let mut toolset = ToolSet::default();
    toolset.add_tool(MockStringOutputTool);

    let output = toolset
        .execute("string_output", "{}", &mut ToolContext::new())
        .await;

    assert_eq!(output.output(), &ToolOutput::text("Hello\nWorld"));
}

#[tokio::test]
async fn json_shaped_string_output_stays_literal_text_through_dispatch() {
    struct JsonShapedStringTool;

    impl Tool for JsonShapedStringTool {
        const NAME: &'static str = "json_shaped_string";
        type Error = rig::tool::ToolExecutionError;
        type Args = serde_json::Value;
        type Output = String;

        fn description(&self) -> String {
            "Returns text that happens to look like a rich-content envelope".into()
        }

        fn parameters(&self) -> serde_json::Value {
            json!({"type": "object"})
        }

        async fn call(
            &self,
            _context: &mut ToolContext,
            _args: Self::Args,
        ) -> Result<Self::Output, ToolExecutionError> {
            Ok(r#"{"type":"image","data":"literal"}"#.to_string())
        }
    }

    let mut toolset = ToolSet::default();
    toolset.add_tool(JsonShapedStringTool);

    let result = toolset
        .execute(JsonShapedStringTool::NAME, "{}", &mut ToolContext::new())
        .await;

    assert_eq!(
        result.output(),
        &ToolOutput::text(r#"{"type":"image","data":"literal"}"#)
    );
}

#[tokio::test]
async fn explicit_image_tool_outputs_remain_structured() {
    let mut toolset = ToolSet::default();
    toolset.add_tool(MockImageOutputTool);

    let result = toolset
        .execute("image_output", "{}", &mut ToolContext::new())
        .await;
    let content = result.output().clone().into_content();

    assert_eq!(content.len(), 1);
    match content.first() {
        Some(ToolResultContent::Image(image)) => {
            assert!(matches!(image.data, DocumentSourceKind::Base64(_)));
            assert_eq!(
                image.media_type,
                Some(rig_core::message::ImageMediaType::PNG)
            );
        }
        other => panic!("expected image tool result content, got {other:?}"),
    }
}

#[tokio::test]
async fn object_tool_outputs_still_serialize_as_json() {
    let mut toolset = ToolSet::default();
    toolset.add_tool(MockObjectOutputTool);

    let result = toolset
        .execute("object_output", "{}", &mut ToolContext::new())
        .await;

    assert_eq!(
        result.output(),
        &ToolOutput::json(json!({
            "status": "ok",
            "count": 42
        }))
    );
}

#[tokio::test]
async fn null_args_are_preserved_for_unit_args() {
    let mut toolset = ToolSet::default();
    toolset.add_tool(MockExampleTool);

    let output = toolset
        .execute("example_tool", "null", &mut ToolContext::new())
        .await;

    assert_eq!(output.output(), &ToolOutput::text("Example answer"));
}

// Struct-typed args with all-optional fields — serde rejects `null` for these
// even though the fields are optional. The normalization in crate-private erased dispatch
// falls back from `null` to `{}` so callers can omit the
// wrapping `Option<Args>` workaround.
#[tokio::test]
async fn null_args_are_normalized_to_empty_object() {
    #[derive(serde::Deserialize, serde::Serialize)]
    struct NoRequiredArgs {
        label: Option<String>,
    }

    struct NoArgTool;

    impl Tool for NoArgTool {
        const NAME: &'static str = "no_arg_tool";
        type Error = MockToolError;
        type Args = NoRequiredArgs;
        type Output = String;

        fn description(&self) -> String {
            "Tool with no required arguments".to_string()
        }

        fn parameters(&self) -> serde_json::Value {
            json!({"type": "object", "properties": {}})
        }

        async fn call(
            &self,
            _context: &mut ToolContext,
            args: Self::Args,
        ) -> Result<Self::Output, Self::Error> {
            Ok(args.label.unwrap_or_else(|| "default".to_string()))
        }
    }

    let mut toolset = ToolSet::default();
    toolset.add_tool(NoArgTool);

    // `null` is what LLMs send when no arguments are provided; without the
    // normalization this would return an `InvalidArgs` execution error.
    let output = toolset
        .execute("no_arg_tool", "null", &mut ToolContext::new())
        .await;

    assert_eq!(output.output(), &ToolOutput::text("default"));
}