Skip to main content

Agent

Struct Agent 

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

System-1 decision model runtime.

Implementations§

Source§

impl Agent

Source

pub fn load(model_id_or_path: &str, opts: LoadOptions) -> Result<Agent>

Load a Laya checkpoint from a local directory, a Hugging Face repo id, or a registry checkpoint name or alias (the same ones Router resolves: "typed-decisions", "ml", …).

A bare name or alias resolves to the same (repo, subfolder) the Router would pick, instead of being handed to the Hub as a repo id. A caller who spelled out a subfolder is loading that subfolder of whatever repo they named, so the name is only resolved when it is the whole argument, and only when it does not already look like a local path or name a directory that holds a checkpoint (upstream load name resolution + _is_local_checkpoint_arg).

Examples found in repository?
examples/predict.rs (lines 19-26)
12fn main() -> Result<(), Box<dyn std::error::Error>> {
13    let model =
14        std::env::var("LAYA_MODEL").unwrap_or_else(|_| "convaiinnovations/laya".to_string());
15    let subfolder = std::env::var("LAYA_SUBFOLDER").ok();
16    let device = std::env::var("LAYA_DEVICE").ok().filter(|s| !s.is_empty());
17
18    let t = Instant::now();
19    let agent = Agent::load(
20        &model,
21        LoadOptions {
22            subfolder,
23            device: device.clone(),
24            ..Default::default()
25        },
26    )?;
27    println!(
28        "loaded {model} on {} in {:?}",
29        device.as_deref().unwrap_or("cpu"),
30        t.elapsed()
31    );
32
33    let state: State = serde_json::json!({
34        "message": "I was charged twice this month and I'm furious. Refund me now or I'm leaving."
35    });
36    let questions = triage_questions();
37
38    let t = Instant::now();
39    let result = agent.system_one(&state, &questions)?;
40    println!("forward in {:?}\n", t.elapsed());
41    println!("{}", serde_json::to_string_pretty(&result.to_json())?);
42
43    // Sanity: every probability distribution should sum to ~1.
44    for (qid, ans) in &result.answers {
45        if let Some(probs) = ans.get("probabilities").and_then(|p| p.as_object()) {
46            let sum: f64 = probs.values().filter_map(|v| v.as_f64()).sum();
47            assert!((sum - 1.0).abs() < 1e-2, "{qid} probabilities sum to {sum}");
48        }
49    }
50    println!("\nOK: probability distributions sum to 1.");
51    Ok(())
52}
More examples
Hide additional examples
examples/shortlist.rs (lines 11-17)
7fn main() -> Result<(), Box<dyn std::error::Error>> {
8    let model =
9        std::env::var("LAYA_MODEL").unwrap_or_else(|_| "convaiinnovations/laya".to_string());
10    let device = std::env::var("LAYA_DEVICE").ok().filter(|s| !s.is_empty());
11    let agent = Agent::load(
12        &model,
13        LoadOptions {
14            device,
15            ..Default::default()
16        },
17    )?;
18
19    // A large label set (25 intents); shortlist to the 5 most relevant before scoring.
20    let criteria = json!({
21        "refund": null, "cancel_subscription": null, "reset_password": null, "update_billing": null,
22        "report_bug": null, "feature_request": null, "track_shipment": null, "return_item": null,
23        "change_address": null, "upgrade_plan": null, "downgrade_plan": null, "dispute_charge": null,
24        "account_locked": null, "two_factor_help": null, "api_error": null, "integration_help": null,
25        "pricing_question": null, "demo_request": null, "gdpr_request": null, "delete_account": null,
26        "invoice_copy": null, "tax_question": null, "partnership": null, "press_inquiry": null,
27        "other": null
28    });
29    let state =
30        json!({ "message": "I was double charged and want my money back for the duplicate." });
31
32    let embed = embed_fn_from_agent(&agent, 512, 32);
33    let top = shortlist_choice(&state, &criteria, &embed, 5, None)?;
34    println!("top-5 shortlisted labels: {top:?}");
35
36    let dim = agent.embed(&["hello world".to_string()], 512, 32)?[0].len();
37    println!("encoder embedding dim: {dim}");
38    assert!(top.len() == 5, "expected 5 labels");
39    println!("OK");
40    Ok(())
41}
Source

pub fn system_one( &self, state: &State, questions: &Questions, ) -> Result<SystemOneResult>

Evaluate typed questions over one state in a single forward pass.

Examples found in repository?
examples/predict.rs (line 39)
12fn main() -> Result<(), Box<dyn std::error::Error>> {
13    let model =
14        std::env::var("LAYA_MODEL").unwrap_or_else(|_| "convaiinnovations/laya".to_string());
15    let subfolder = std::env::var("LAYA_SUBFOLDER").ok();
16    let device = std::env::var("LAYA_DEVICE").ok().filter(|s| !s.is_empty());
17
18    let t = Instant::now();
19    let agent = Agent::load(
20        &model,
21        LoadOptions {
22            subfolder,
23            device: device.clone(),
24            ..Default::default()
25        },
26    )?;
27    println!(
28        "loaded {model} on {} in {:?}",
29        device.as_deref().unwrap_or("cpu"),
30        t.elapsed()
31    );
32
33    let state: State = serde_json::json!({
34        "message": "I was charged twice this month and I'm furious. Refund me now or I'm leaving."
35    });
36    let questions = triage_questions();
37
38    let t = Instant::now();
39    let result = agent.system_one(&state, &questions)?;
40    println!("forward in {:?}\n", t.elapsed());
41    println!("{}", serde_json::to_string_pretty(&result.to_json())?);
42
43    // Sanity: every probability distribution should sum to ~1.
44    for (qid, ans) in &result.answers {
45        if let Some(probs) = ans.get("probabilities").and_then(|p| p.as_object()) {
46            let sum: f64 = probs.values().filter_map(|v| v.as_f64()).sum();
47            assert!((sum - 1.0).abs() < 1e-2, "{qid} probabilities sum to {sum}");
48        }
49    }
50    println!("\nOK: probability distributions sum to 1.");
51    Ok(())
52}
Source

pub fn predict( &self, state: &State, questions: &Questions, ) -> Result<SystemOneResult>

Alias for Agent::system_one.

Source

pub fn predict_batch( &self, states: &[State], questions: &Questions, batch_size: Option<usize>, ) -> Result<Vec<SystemOneResult>>

Evaluate the same questions over many states, sharing forward passes.

Source

pub fn embed( &self, texts: &[String], max_length: usize, batch_size: usize, ) -> Result<Vec<Vec<f32>>>

Mean-pooled encoder embeddings for a list of texts ([n, hidden_size]).

Tokenizes with special tokens, truncates to max_length, runs the checkpoint encoder in batches of batch_size, and mean-pools over non-padding tokens. Backs crate::shortlist::embed_fn_from_agent; a dedicated bi-encoder will usually shortlist better, but this needs only the loaded checkpoint.

Examples found in repository?
examples/shortlist.rs (line 36)
7fn main() -> Result<(), Box<dyn std::error::Error>> {
8    let model =
9        std::env::var("LAYA_MODEL").unwrap_or_else(|_| "convaiinnovations/laya".to_string());
10    let device = std::env::var("LAYA_DEVICE").ok().filter(|s| !s.is_empty());
11    let agent = Agent::load(
12        &model,
13        LoadOptions {
14            device,
15            ..Default::default()
16        },
17    )?;
18
19    // A large label set (25 intents); shortlist to the 5 most relevant before scoring.
20    let criteria = json!({
21        "refund": null, "cancel_subscription": null, "reset_password": null, "update_billing": null,
22        "report_bug": null, "feature_request": null, "track_shipment": null, "return_item": null,
23        "change_address": null, "upgrade_plan": null, "downgrade_plan": null, "dispute_charge": null,
24        "account_locked": null, "two_factor_help": null, "api_error": null, "integration_help": null,
25        "pricing_question": null, "demo_request": null, "gdpr_request": null, "delete_account": null,
26        "invoice_copy": null, "tax_question": null, "partnership": null, "press_inquiry": null,
27        "other": null
28    });
29    let state =
30        json!({ "message": "I was double charged and want my money back for the duplicate." });
31
32    let embed = embed_fn_from_agent(&agent, 512, 32);
33    let top = shortlist_choice(&state, &criteria, &embed, 5, None)?;
34    println!("top-5 shortlisted labels: {top:?}");
35
36    let dim = agent.embed(&["hello world".to_string()], 512, 32)?[0].len();
37    println!("encoder embedding dim: {dim}");
38    assert!(top.len() == 5, "expected 5 labels");
39    println!("OK");
40    Ok(())
41}

Auto Trait Implementations§

§

impl !Freeze for Agent

§

impl !RefUnwindSafe for Agent

§

impl !UnwindSafe for Agent

§

impl Send for Agent

§

impl Sync for Agent

§

impl Unpin for Agent

§

impl UnsafeUnpin for Agent

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> ErasedDestructor for T
where T: 'static,

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