Skip to main content

DynamicTool

Struct DynamicTool 

Source
pub struct DynamicTool { /* private fields */ }
Expand description

A tool defined at runtime: its definition and a callback over JSON arguments. It is its own handler (Serve), keyed by its name. The optional liveness probe supports registry retirement; serving does not consult it.

Implementations§

Source§

impl DynamicTool

Source

pub fn new<F>( name: ToolName, description: impl Into<String>, parameters: Value, callback: F, ) -> Self

Define a tool from a context-free callback over owned arguments.

Source

pub fn new_with_context<F>( name: ToolName, description: impl Into<String>, parameters: Value, callback: F, ) -> Self
where F: ToolCallback + 'static,

Define a tool from a callback over the dispatch-scoped context.

Source

pub fn with_annotations(self, annotations: ToolAnnotations) -> Self

The same tool, stating what calling it does to the world.

Source

pub fn with_liveness<F>(self, is_live: F) -> Self
where F: Fn() -> bool + WasmCompatSend + WasmCompatSync + 'static,

Attach a liveness probe.

Source

pub fn name(&self) -> &ToolName

The tool’s name.

Source

pub fn definition(&self) -> ToolDefinition

The tool’s definition.

Source

pub fn into_parts(self) -> (ToolDefinition, ErasedHandler, Option<LivenessFn>)

Consumes the tool into its definition, its erased handler, and its optional liveness probe.

Source

pub async fn run(&self, args: Value) -> Result<ToolOutput, ToolExecutionError>

Runs the tool on JSON args with an empty ToolContext, as Self::run_with does.

use rig_core::{message::ToolName, tool::{DynamicTool, ToolExecutionError, ToolOutput}};
use serde_json::json;

let add = DynamicTool::new(ToolName::new("add")?, "Adds a and b", json!({}), |args| {
    Box::pin(async move {
        let int = |key| args.get(key).and_then(serde_json::Value::as_i64);
        let sum = int("a").zip(int("b")).map(|(a, b)| a + b);
        sum.map(|sum| ToolOutput::json(json!(sum)))
            .ok_or_else(|| ToolExecutionError::invalid_args("a and b must be integers"))
    })
});
let output = futures::executor::block_on(add.run(json!({ "a": 2, "b": 3 })))?;
assert_eq!(output.as_json(), Some(&json!(5)));
assert!(futures::executor::block_on(add.run(json!({ "a": "two" }))).is_err());
Source

pub async fn run_with( &self, context: &mut ToolContext, args: Value, ) -> Result<ToolOutput, ToolExecutionError>

Runs the tool on JSON args as a dispatch of its call runs it, and returns its output or its error (invalid arguments included). The tool sees context’s inbound values, and what it publishes with insert_result lands in context. No registry or agent is involved.

use rig_core::{message::ToolName, tool::{ContextValue, DynamicTool, ToolContext, ToolOutput}};
use serde_json::json;

#[derive(serde::Serialize, serde::Deserialize)]
struct User(String);
impl ContextValue for User { const KEY: &'static str = "user"; }
#[derive(serde::Serialize, serde::Deserialize)]
struct Greeted(bool);
impl ContextValue for Greeted { const KEY: &'static str = "greeted"; }

let greet = DynamicTool::new_with_context(ToolName::new("greet")?, "Greets the user", json!({}),
    |context, _args| Box::pin(async move {
        let user = context.require::<User>()?;
        context.insert_result(Greeted(true))?;
        Ok(ToolOutput::text(format!("hello {}", user.0)))
    }));
let mut context = ToolContext::new();
context.insert(User("ada".into()))?;
let output = futures::executor::block_on(greet.run_with(&mut context, json!({})))?;
assert_eq!(output.as_text(), Some("hello ada"));
assert_eq!(context.result::<Greeted>()?.map(|greeted| greeted.0), Some(true));
Source

pub fn is_live(&self) -> bool

Whether the tool’s owner still serves it (true without a probe).

Trait Implementations§

Source§

impl Clone for DynamicTool

Source§

fn clone(&self) -> Self

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for DynamicTool

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Serve for DynamicTool

Source§

type Family = Tool

The family this handler serves, or Dynamic.
Source§

fn descriptor(&self) -> HandlerDescriptor

What this handler is: the family-keyed description a typed view checks at bind time and a scene serializes.
Source§

fn key(&self) -> HandlerKey

The descriptor’s key. A handler whose descriptor is costly to build, such as a tool’s argument schema, says it without building one.
Source§

async fn serve(&self, kind: EffectKind, dispatch: Dispatch) -> Reply

Prepare an outcome or an owned stream for the driver to consume.
Source§

fn footprint(&self, kind: &EffectKind) -> Option<Touches>

What dispatching kind may read and change, for a tool’s handler (Tool::footprint); None when it cannot say, such as for arguments that do not parse.
Source§

fn check(&self, kind: &EffectKind) -> Vec<UnsupportedOption>

The options of kind this handler would leave out when it serves it, with nothing sent: for a model’s handler, what its wire or model cannot honour (DynModel::check). Empty when it leaves nothing out or cannot say, as by default.

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<ST, DT> CastableFrom<ST, Initialized, Initialized> for DT
where ST: ?Sized, DT: ?Sized,

Source§

impl<ST, DT> CastableFrom<ST, Uninit, Uninit> for DT
where ST: ?Sized, DT: ?Sized,

Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> DynClone for T
where T: Clone,

Source§

fn __clone_box(&self, _: Private) -> *mut ()

Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self> ⓘ

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self> ⓘ

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self> ⓘ

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self> ⓘ
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

impl<T> Pointable for T

Source§

const ALIGN: usize

The alignment of pointer.
Source§

type Init = T

The type for initializers.
Source§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
Source§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
Source§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
Source§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
Source§

impl<T> PolicyExt for T
where T: ?Sized,

Source§

fn and<P, B, E>(self, other: P) -> And<T, P>
where T: Sized + Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow only if self and other return Action::Follow. Read more
Source§

fn or<P, B, E>(self, other: P) -> Or<T, P>
where T: Sized + Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow if either self or other returns Action::Follow. Read more
Source§

impl<T> Read<Exclusive, BecauseExclusive> for T
where T: ?Sized,

Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V

Source§

impl<T> WasmCompatSend for T
where T: Send,

Source§

impl<T> WasmCompatSync for T
where T: Sync,

Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self> ⓘ
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self> ⓘ

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more