rig-agent 0.44.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
//! Ordered tool registrations, request catalogs, and inline dispatch by name.
//!
//! ```
//! use rig_agent::tool::ToolSet;
//! let tools = ToolSet::default();
//! assert!(tools.catalog().is_empty());
//! ```

use std::collections::HashMap;

use indexmap::IndexMap;
use rig_core::serve::adapters::ToolAdapter;
use rig_core::serve::{ErasedHandler, Serve};
use rig_core::{
    completion::{Document, ToolDefinition},
    effect::{
        EffectKind, FamilyDescriptor, Key, Outcome, ToolEmbeddingDescriptor, family, tool_key,
    },
    embeddings::{embed::EmbedError, tool::ToolSchema},
    error::{ErrorKind, ErrorReport},
    message::ToolName,
    tool::{
        DynamicTool, LivenessFn, Tool, ToolContext, ToolEmbedding, ToolExecutionError, ToolResult,
        tool_definition,
    },
};

use super::catalog::ToolCatalog;

/// One registration: the tool's serde description, the key it is (or will
/// be) served under, and the erased handler a bus takes. Cloning shares the
/// handler.
#[derive(Clone)]
pub struct RegisteredTool {
    definition: ToolDefinition,
    embedding: Option<ToolEmbeddingDescriptor>,
    key: Key<family::Tool>,
    handler: ErasedHandler,
    liveness: Option<LivenessFn>,
}

impl std::fmt::Debug for RegisteredTool {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("RegisteredTool")
            .field("name", &self.definition.name)
            .field("key", &self.key)
            .field("retrievable", &self.embedding.is_some())
            .finish_non_exhaustive()
    }
}

impl RegisteredTool {
    /// Register a typed tool.
    pub fn from_tool<T>(tool: T) -> Self
    where
        T: Tool + 'static,
    {
        let definition = tool_definition(&tool);
        Self::from_parts(
            definition,
            None,
            ErasedHandler::new(ToolAdapter::new(tool)),
            None,
        )
    }

    /// Register a retrievable tool with embedding context in its descriptor.
    /// Returns an error if the context cannot be serialized.
    pub fn from_retrievable<T>(tool: T) -> Result<Self, serde_json::Error>
    where
        T: ToolEmbedding + 'static,
    {
        let definition = tool_definition(&tool);
        let embedding = ToolEmbeddingDescriptor {
            context: serde_json::to_value(tool.context())?,
            embedding_docs: tool.embedding_docs(),
        };
        let adapter = ToolAdapter::retrievable(tool)?;
        Ok(Self::from_parts(
            definition,
            Some(embedding),
            ErasedHandler::new(adapter),
            None,
        ))
    }

    /// Register a runtime-defined tool.
    pub fn from_dynamic(tool: DynamicTool) -> Self {
        let (definition, handler, liveness) = tool.into_parts();
        Self::from_parts(definition, None, handler, liveness)
    }

    /// Register a handler under its descriptor's key.
    /// Returns `HandlerUnavailable` if the descriptor is not tool-family.
    pub fn from_handler(handler: impl Serve + 'static) -> Result<Self, ErrorReport> {
        let descriptor = handler.descriptor();
        let FamilyDescriptor::Tool {
            name,
            description,
            parameters,
            embedding,
        } = descriptor.family
        else {
            return Err(ErrorReport::new(
                ErrorKind::HandlerUnavailable,
                format!(
                    "handler `{}` serves the {} family, not tool_call",
                    descriptor.key,
                    descriptor.family.family()
                ),
            ));
        };
        let name = ToolName::new(name).map_err(|_| {
            ErrorReport::new(
                ErrorKind::HandlerUnavailable,
                format!(
                    "handler `{}` serves a tool with an empty name",
                    descriptor.key
                ),
            )
        })?;
        Ok(Self {
            definition: ToolDefinition {
                name,
                description,
                parameters,
            },
            embedding,
            key: Key::new_unchecked(descriptor.key),
            handler: ErasedHandler::new(handler),
            liveness: None,
        })
    }

    /// Whether this registration is served under the default `tool:<name>`
    /// key (a registry that pins generations re-keys only those).
    pub(crate) fn has_default_key(&self) -> bool {
        *self.key.raw() == tool_key(&self.definition.name)
    }

    fn from_parts(
        definition: ToolDefinition,
        embedding: Option<ToolEmbeddingDescriptor>,
        handler: ErasedHandler,
        liveness: Option<LivenessFn>,
    ) -> Self {
        let key = Key::new_unchecked(tool_key(&definition.name));
        Self {
            definition,
            embedding,
            key,
            handler,
            liveness,
        }
    }

    /// Serve this registration under `key` instead of the default
    /// `tool:<name>` (a registry that pins generations does this).
    pub fn with_key(mut self, key: Key<family::Tool>) -> Self {
        self.key = key;
        self
    }

    /// The tool's name.
    pub fn name(&self) -> String {
        self.definition.name.to_string()
    }

    /// The key the handler is served under: a tool key, proven at
    /// construction (the descriptor was checked to be tool-family).
    pub fn key(&self) -> &Key<family::Tool> {
        &self.key
    }

    /// The erased handler.
    pub fn handler(&self) -> &ErasedHandler {
        &self.handler
    }

    /// The definition advertised to the model.
    pub(crate) fn definition(&self) -> ToolDefinition {
        self.definition.clone()
    }

    /// The family-keyed descriptor of this registration.
    pub fn descriptor(&self) -> FamilyDescriptor {
        FamilyDescriptor::Tool {
            name: self.definition.name.to_string(),
            description: self.definition.description.clone(),
            parameters: self.definition.parameters.clone(),
            embedding: self.embedding.clone(),
        }
    }

    /// The embedding context, for retrievable tools.
    pub fn embedding(&self) -> Option<&ToolEmbeddingDescriptor> {
        self.embedding.as_ref()
    }

    /// Whether the tool's owner still serves it (`true` without a probe).
    pub fn is_live(&self) -> bool {
        self.liveness.as_ref().is_none_or(|probe| probe())
    }

    /// Execute inline on a dispatch snapshot of inbound context. On completion,
    /// replace result metadata with what the tool published, or an empty result
    /// map if nothing was published. Inbound values remain unchanged; dropping
    /// the future mid-call leaves the caller's entire context unchanged.
    /// Handler errors and wrong-family outcomes become failed tool results.
    pub async fn execute(&self, args: String, context: &mut ToolContext) -> ToolResult {
        let name = self.definition.name.to_string();
        // Context travels outside the serializable effect payload.
        let published = rig_core::tool::PublishedContext::new();
        let outcome = rig_core::serve::serve_inline_with(
            &self.handler,
            EffectKind::ToolCall { name, args },
            vec![
                std::sync::Arc::new(context.for_dispatch()),
                published.clone() as std::sync::Arc<dyn std::any::Any + Send + Sync>,
            ],
        )
        .await;
        // What the tool published is this call's result metadata; a handler
        // that published nothing (or never ran) leaves an empty result map.
        context.accept_dispatch_result(published.take().unwrap_or_default());
        match outcome {
            Ok(Outcome::ToolResult { result }) => result,
            Ok(other) => ToolResult::failed(ToolExecutionError::other(format!(
                "tool handler answered with a {} outcome",
                other.family()
            ))),
            Err(report) => ToolResult::failed(report.into()),
        }
    }
}

/// One entry of a [`ToolSet`]: the registration plus whether it is
/// advertised on every request or only when retrieved.
#[derive(Clone)]
pub(crate) struct ToolRegistration {
    tool: RegisteredTool,
    always_exposed: bool,
}

impl ToolRegistration {
    fn new(tool: RegisteredTool, always_exposed: bool) -> Self {
        Self {
            tool,
            always_exposed,
        }
    }
}

/// A tool call's result together with the dispatch-scoped context it
/// published into.
pub struct ToolDispatch {
    /// The result.
    pub result: ToolResult,
    /// The context after the tool ran.
    pub context: ToolContext,
}

impl ToolDispatch {
    /// Publish the dispatch's result metadata into `context` and return the
    /// result.
    pub fn publish_to(self, context: &mut ToolContext) -> ToolResult {
        context.accept_dispatch_result(self.context);
        self.result
    }
}

/// Run `tool` (or answer `not found`) on a dispatch-scoped copy of
/// `context`.
pub async fn execute_tool(
    name: &str,
    args: String,
    tool: Option<RegisteredTool>,
    context: &ToolContext,
) -> ToolDispatch {
    let mut dispatch_context = context.for_dispatch();
    let result = match tool {
        Some(tool) => {
            tracing::debug!(target: "rig", tool_name = name, "calling tool with args:\n{args}");
            tool.execute(args, &mut dispatch_context).await
        }
        None => ToolResult::failed(
            ToolExecutionError::not_found(format!("no tool named `{name}` is registered"))
                .with_model_feedback(format!("tool `{name}` not found")),
        ),
    };
    ToolDispatch {
        result,
        context: dispatch_context,
    }
}

/// Insertion-ordered named tool registrations and their advertisement policy.
/// Direct execution is inline; hosts may install the registrations on a bus.
#[derive(Clone, Default)]
pub struct ToolSet {
    pub(crate) tools: IndexMap<String, ToolRegistration>,
}

impl ToolSet {
    /// A set from typed tools.
    pub fn from_tools<T>(tools: Vec<T>) -> Self
    where
        T: Tool + 'static,
    {
        let mut set = Self::default();
        for tool in tools {
            set.add_tool(tool);
        }
        set
    }

    /// A set from runtime-defined tools.
    pub fn from_dynamic_tools(tools: Vec<DynamicTool>) -> Self {
        let mut set = Self::default();
        for tool in tools {
            set.add_dynamic_tool(tool);
        }
        set
    }

    /// Whether a tool named `name` is registered.
    pub fn contains(&self, name: &str) -> bool {
        self.tools.contains_key(name)
    }

    /// Register a typed tool; returns its name.
    pub fn add_tool<T>(&mut self, tool: T) -> String
    where
        T: Tool + 'static,
    {
        self.insert(RegisteredTool::from_tool(tool))
    }

    /// Register a runtime-defined tool; returns its name.
    pub fn add_dynamic_tool(&mut self, tool: DynamicTool) -> String {
        self.insert(RegisteredTool::from_dynamic(tool))
    }

    /// Register a retrievable tool; returns its name. A context that does
    /// not serialize is the error, and nothing is registered.
    pub fn add_retrieved_tool<T>(&mut self, tool: T) -> Result<String, serde_json::Error>
    where
        T: ToolEmbedding + 'static,
    {
        RegisteredTool::from_retrievable(tool).map(|registered| self.insert(registered))
    }

    /// Register an already-built registration; returns its name.
    pub fn add_registered_tool(&mut self, tool: RegisteredTool) -> String {
        self.insert(tool)
    }

    pub(crate) fn insert(&mut self, tool: RegisteredTool) -> String {
        let name = tool.name();
        self.insert_registration(name.clone(), ToolRegistration::new(tool, true));
        name
    }

    fn insert_registration(&mut self, name: String, mut registration: ToolRegistration) {
        if let Some(current) = self.tools.get_mut(&name) {
            registration.always_exposed |= current.always_exposed;
            *current = registration;
            tracing::warn!(tool_name = %name, "replacing an existing tool registration");
        } else {
            self.tools.insert(name, registration);
        }
    }

    /// Remove the tool named `name`.
    pub fn remove_tool(&mut self, name: &str) {
        self.tools.shift_remove(name);
    }

    /// Merge `set`'s registrations, keeping their exposure.
    pub fn add_tools(&mut self, set: ToolSet) {
        for (name, registration) in set.tools {
            self.insert_registration(name, registration);
        }
    }

    /// Merge `set`'s registrations as retrieval-only (not always exposed).
    pub fn add_retrievable_tools(&mut self, set: ToolSet) {
        for (name, mut registration) in set.tools {
            registration.always_exposed = false;
            self.insert_registration(name, registration);
        }
    }

    /// The registration named `name`.
    pub fn get(&self, name: &str) -> Option<&RegisteredTool> {
        self.tools.get(name).map(|registration| &registration.tool)
    }

    /// Every registration, in insertion order.
    pub fn iter(&self) -> impl Iterator<Item = (&str, &RegisteredTool)> {
        self.tools
            .iter()
            .map(|(name, registration)| (name.as_str(), &registration.tool))
    }

    /// Every name, in insertion order.
    pub fn names(&self) -> impl Iterator<Item = &str> {
        self.tools.keys().map(String::as_str)
    }

    /// Number of registrations.
    pub fn len(&self) -> usize {
        self.tools.len()
    }

    /// Whether the set is empty.
    pub fn is_empty(&self) -> bool {
        self.tools.is_empty()
    }

    /// Names advertised on every request.
    pub fn always_exposed_names(&self) -> impl Iterator<Item = &str> {
        self.tools
            .iter()
            .filter_map(|(name, registration)| registration.always_exposed.then_some(name.as_str()))
    }

    /// Move `name` to the end of the insertion order.
    pub(crate) fn move_to_end(&mut self, name: &str) -> bool {
        self.tools
            .shift_remove_entry(name)
            .is_some_and(|(name, registration)| {
                self.tools.insert(name, registration);
                true
            })
    }

    /// The always-exposed registrations as a catalog.
    pub fn catalog(&self) -> ToolCatalog {
        ToolCatalog::from_registered(
            self.tools
                .iter()
                .filter(|(_, registration)| registration.always_exposed)
                .map(|(name, registration)| (name.clone(), registration.tool.clone()))
                .collect(),
        )
    }

    /// Every definition, in insertion order.
    pub fn tool_definitions(&self) -> Vec<ToolDefinition> {
        self.tools
            .values()
            .map(|registration| registration.tool.definition())
            .collect()
    }

    /// Run the tool named `name` inline, publishing its result metadata
    /// into `context`.
    pub async fn execute(
        &self,
        name: &str,
        args: impl Into<String>,
        context: &mut ToolContext,
    ) -> ToolResult {
        context.clear_dispatch_result();
        let tool = self.get(name).cloned();
        let dispatch = execute_tool(name, args.into(), tool, context).await;
        dispatch.publish_to(context)
    }

    /// Every definition as a document, for embedding-based retrieval.
    pub fn documents(&self) -> Vec<Document> {
        self.tools
            .iter()
            .map(|(name, registration)| {
                let definition = registration.tool.definition();
                let serialized =
                    serde_json::to_string_pretty(&definition).unwrap_or_else(|error| {
                        tracing::warn!(
                            tool_name = %name,
                            %error,
                            "tool definition could not be pretty-printed; using a plain representation"
                        );
                        format!(
                            "name: {}\ndescription: {}\nparameters: {}",
                            definition.name, definition.description, definition.parameters
                        )
                    });
                Document {
                    id: name.clone(),
                    text: format!("Tool: {name}\nDefinition: \n{serialized}"),
                    additional_props: HashMap::new(),
                }
            })
            .collect()
    }

    /// The embedding schemas of the retrievable registrations.
    pub fn schemas(&self) -> Result<Vec<ToolSchema>, EmbedError> {
        Ok(self
            .tools
            .iter()
            .filter_map(|(name, registration)| {
                registration.tool.embedding().map(|embedding| ToolSchema {
                    name: name.clone(),
                    context: embedding.context.clone(),
                    embedding_docs: embedding.embedding_docs.clone(),
                })
            })
            .collect())
    }
}

#[cfg(test)]
mod tests;