pub struct Agent { /* private fields */ }Expand description
System-1 decision model runtime.
Implementations§
Source§impl Agent
impl Agent
Sourcepub fn load(model_id_or_path: &str, opts: LoadOptions) -> Result<Agent>
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?
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
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}Sourcepub fn system_one(
&self,
state: &State,
questions: &Questions,
) -> Result<SystemOneResult>
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?
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}Sourcepub fn predict(
&self,
state: &State,
questions: &Questions,
) -> Result<SystemOneResult>
pub fn predict( &self, state: &State, questions: &Questions, ) -> Result<SystemOneResult>
Alias for Agent::system_one.
Sourcepub fn predict_batch(
&self,
states: &[State],
questions: &Questions,
batch_size: Option<usize>,
) -> Result<Vec<SystemOneResult>>
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.
Sourcepub fn embed(
&self,
texts: &[String],
max_length: usize,
batch_size: usize,
) -> Result<Vec<Vec<f32>>>
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?
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> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
Source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
impl<ST, DT> CastableFrom<ST, Initialized, Initialized> for DT
impl<ST, DT> CastableFrom<ST, Uninit, Uninit> for DT
impl<T> ErasedDestructor for Twhere
T: 'static,
Source§impl<T> Instrument for T
impl<T> Instrument for T
Source§fn instrument(self, span: Span) -> Instrumented<Self> ⓘ
fn instrument(self, span: Span) -> Instrumented<Self> ⓘ
Source§fn in_current_span(self) -> Instrumented<Self> ⓘ
fn in_current_span(self) -> Instrumented<Self> ⓘ
Source§impl<T> IntoEither for T
impl<T> IntoEither for T
Source§fn into_either(self, into_left: bool) -> Either<Self, Self> ⓘ
fn into_either(self, into_left: bool) -> Either<Self, Self> ⓘ
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 moreSource§fn into_either_with<F>(self, into_left: F) -> Either<Self, Self> ⓘ
fn into_either_with<F>(self, into_left: F) -> Either<Self, Self> ⓘ
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