Skip to main content

SubAgentPool

Struct SubAgentPool 

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

A pool of named sub-agents: create and name sub-agents dynamically, then address them by name to continue their conversations.

Unlike the one-shot SubAgentTool::from_factory, the pool keeps the instances it creates — they are not discarded when their task ends; the user (or the model) can hand a new task to the same sub-agent by name later, and it picks up the conversation with its prior memory. Suited to “the main agent distributes multiple tasks, each with its own independent-context sub-agent, and continues by name afterwards”.

The pool is a shared part: cloning is cheap (internal Arc), and multiple loops / threads can hold the same pool; calls to the same sub-agent name are serialized (inner lock), different names run in parallel.

Cancellation semantics: same as SubAgentTool — sub-agent runs receive no cancellation signal; when the caller is cancelled, unfinished runs abort as their future is dropped.

§Examples

Create and name a sub-agent, run its first task immediately; continue by name afterwards:

use molo::agent::{Agent, AgentError, SubAgentPool};

/// Demo sub-agent: echoes the input back verbatim.
struct Echo;
#[molo::async_trait]
impl Agent for Echo {
    async fn run(&mut self, input: &str) -> Result<String, AgentError> {
        Ok(format!("echo: {input}"))
    }
}

let pool = SubAgentPool::new();

// Create a named sub-agent and run its first task (the reply returns to
// the caller)
let reply = pool
    .spawn(
        "red",
        || -> Result<Box<dyn Agent + Send>, molo::tool::ToolError> { Ok(Box::new(Echo)) },
        "task one",
    )
    .await?;
assert_eq!(reply, "echo: task one");

// Continue by name: the same instance, with its prior memory
let reply = pool.send("red", "task two").await?;
assert_eq!(reply, "echo: task two");

// Name enumeration and probing (UI list / model queries)
assert!(pool.contains("red").await);
assert_eq!(pool.names().await, vec!["red".to_string()]);

Implementations§

Source§

impl SubAgentPool

Source

pub fn new() -> Self

Create an empty pool.

Source

pub async fn spawn( &self, name: &str, factory: impl FnOnce() -> Result<Box<dyn Agent + Send>, ToolError>, input: &str, ) -> Result<String, PoolError>

Create and name a sub-agent, running its first task immediately.

The factory only builds the sub-agent (type / tool subset / system prompt, all up to you); once built, the instance goes into the pool before running — even if the first task fails, the sub-agent stays in the pool and can be continued or retried via send.

§Errors
Source

pub async fn spawn_react( &self, name: &str, provider: impl Provider + 'static, tools: ToolRegistry, system_prompt: &str, task: &str, ) -> Result<String, PoolError>

Convenience form: create and name a standard ReAct sub-agent (with a given system prompt), running its first task immediately; afterwards you can continue by name via send.

The only difference from spawn is how the sub-agent is built — here the system prompt and task are given and handled by the standard ReAct loop; the provider doesn’t need to be Clone (a named creation calls the factory only once).

§Errors

Same as spawn: duplicate name PoolError::Duplicate; first-task failure PoolError::Run (the instance is kept, and the conversation can continue).

Source

pub async fn send(&self, name: &str, input: &str) -> Result<String, PoolError>

Address by name: hand a new task to an already-created sub-agent, continuing its conversation (with its prior memory).

§Errors

Returns PoolError::NotFound when the name doesn’t exist; PoolError::Run when the run fails.

Source

pub async fn contains(&self, name: &str) -> bool

Whether the name already exists (duplicate check before creation / UI probing).

Source

pub async fn names(&self) -> Vec<String>

All names in the pool (sorted), for UI lists or model queries.

§Examples
use molo::agent::SubAgentPool;

let pool = SubAgentPool::new();
assert!(pool.names().await.is_empty());

Trait Implementations§

Source§

impl Clone for SubAgentPool

Source§

fn clone(&self) -> SubAgentPool

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 SubAgentPool

Source§

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

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

impl Default for SubAgentPool

Source§

fn default() -> SubAgentPool

Returns the “default value” for a type. Read more

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> 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> 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 = Infallible

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

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

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<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