Skip to main content

AxAgent

Struct AxAgent 

Source
pub struct AxAgent { /* private fields */ }

Implementations§

Source§

impl AxAgent

Source

pub fn set_signature(&mut self, spec: &str) -> AxResult<&mut Self>

Source

pub fn get_instruction(&self) -> String

Source

pub fn set_instruction(&mut self, instruction: &str) -> AxResult<&mut Self>

Source

pub fn add_actor_instruction(&mut self, addendum: &str) -> AxResult<&mut Self>

Source

pub fn forward<C: AxAIClient>( &mut self, client: &mut C, input: Value, ) -> AxResult<Value>

Source

pub fn forward_with_options<C: AxAIClient>( &mut self, client: &mut C, input: Value, options: Value, ) -> AxResult<Value>

Source

pub fn set_citations_observer<F>(&mut self, observer: F) -> &mut Self
where F: FnMut(Value) + 'static,

Source

pub fn set_playbook_observer<F>(&mut self, observer: F) -> &mut Self
where F: FnMut(Value) + 'static,

Source

pub fn get_usage(&self) -> Value

Source

pub fn get_runtime_contract(&self) -> Value

Source

pub fn get_policy(&self) -> Value

Source

pub fn get_policy_registry(&self) -> Value

Source

pub fn get_callable_inventory(&self) -> Value

Source

pub fn get_discovery_catalog(&self) -> Value

Source

pub fn discover(&mut self, request: Value) -> AxResult<Value>

Source

pub fn recall(&mut self, request: Value) -> AxResult<Value>

Source

pub fn used(&mut self, id: &str, reason: &str, stage: &str) -> AxResult<Value>

Source

pub fn invoke_callable( &mut self, qualified_name: &str, args: Value, options: Value, ) -> AxResult<Value>

Source

pub fn export_runtime_state(&mut self) -> AxResult<Value>

Source

pub fn restore_runtime_state(&mut self, snapshot: Value) -> AxResult<Value>

Source

pub fn get_optimizer_metadata(&self) -> AxResult<Value>

Source

pub fn get_optimizable_components(&self) -> AxResult<Vec<Value>>

Source

pub fn apply_optimized_components( &mut self, component_map: &Value, ) -> AxResult<()>

Source

pub fn replay_trace(&mut self, trace: Value, fixtures: Value) -> AxResult<Value>

Source

pub fn evaluate_optimization_task<C: AxAIClient>( &mut self, client: &mut C, task: Value, options: Value, ) -> AxResult<Value>

Source

pub fn execute_actor_step( &mut self, runtime: &mut dyn AxCodeRuntime, code: &str, input: Value, options: Value, ) -> AxResult<RuntimeEnvelope>

Examples found in repository?
examples/runtime_adapter.rs (lines 60-65)
57fn main() -> AxResult<()> {
58    let mut runtime = DemoRuntime;
59    let mut runner = agent("question:string -> answer:string")?;
60    let step = runner.execute_actor_step(
61        &mut runtime,
62        "final()",
63        json!({"question": "adapter"}),
64        json!({}),
65    )?;
66    let snapshot = runner.export_session_state()?;
67    let timeout = runner.execute_actor_step(
68        &mut runtime,
69        "timeout()",
70        json!({"question": "adapter"}),
71        json!({}),
72    )?;
73    let closed = runner.close_runtime_session()?;
74    println!(
75        "{}",
76        serde_json::to_string_pretty(&json!({
77            "stepKind": step.payload["kind"],
78            "snapshotAnswer": snapshot["bindings"]["answer"],
79            "timeoutCategory": timeout.payload["error_category"],
80            "closed": closed
81        }))?
82    );
83    Ok(())
84}
More examples
Hide additional examples
examples/runtime_protocol.rs (lines 14-19)
5fn main() -> AxResult<()> {
6    let repo_root = env::var("AXIR_REPO_ROOT")
7        .map_err(|_| axllm::AxError::runtime("AXIR_REPO_ROOT is required"))?;
8    let server = env::var("AXIR_AXJS_RUNTIME_SERVER")
9        .map_err(|_| axllm::AxError::runtime("AXIR_AXJS_RUNTIME_SERVER is required"))?;
10    let mut runtime =
11        ProcessCodeRuntime::new(["node".to_string(), "--import=tsx".to_string(), server]);
12    env::set_current_dir(repo_root).map_err(axllm::AxError::from)?;
13    let mut runner = agent("question:string -> answer:string")?;
14    let step = runner.execute_actor_step(
15        &mut runtime,
16        "answer = inputs.question; await final({ answer })",
17        json!({"question": "protocol"}),
18        json!({}),
19    )?;
20    assert_eq!(step.payload["kind"], "final");
21    runtime.shutdown()?;
22    println!("rust-runtime-protocol-ok");
23    Ok(())
24}
Source

pub fn test( &mut self, runtime: &mut dyn AxCodeRuntime, code: &str, input: Value, options: Value, ) -> AxResult<RuntimeEnvelope>

Source

pub fn inspect_runtime(&mut self) -> AxResult<Value>

Source

pub fn export_session_state(&mut self) -> AxResult<Value>

Examples found in repository?
examples/runtime_adapter.rs (line 66)
57fn main() -> AxResult<()> {
58    let mut runtime = DemoRuntime;
59    let mut runner = agent("question:string -> answer:string")?;
60    let step = runner.execute_actor_step(
61        &mut runtime,
62        "final()",
63        json!({"question": "adapter"}),
64        json!({}),
65    )?;
66    let snapshot = runner.export_session_state()?;
67    let timeout = runner.execute_actor_step(
68        &mut runtime,
69        "timeout()",
70        json!({"question": "adapter"}),
71        json!({}),
72    )?;
73    let closed = runner.close_runtime_session()?;
74    println!(
75        "{}",
76        serde_json::to_string_pretty(&json!({
77            "stepKind": step.payload["kind"],
78            "snapshotAnswer": snapshot["bindings"]["answer"],
79            "timeoutCategory": timeout.payload["error_category"],
80            "closed": closed
81        }))?
82    );
83    Ok(())
84}
Source

pub fn restore_session_state(&mut self, snapshot: Value) -> AxResult<Value>

Source

pub fn close_runtime_session(&mut self) -> AxResult<Value>

Examples found in repository?
examples/runtime_adapter.rs (line 73)
57fn main() -> AxResult<()> {
58    let mut runtime = DemoRuntime;
59    let mut runner = agent("question:string -> answer:string")?;
60    let step = runner.execute_actor_step(
61        &mut runtime,
62        "final()",
63        json!({"question": "adapter"}),
64        json!({}),
65    )?;
66    let snapshot = runner.export_session_state()?;
67    let timeout = runner.execute_actor_step(
68        &mut runtime,
69        "timeout()",
70        json!({"question": "adapter"}),
71        json!({}),
72    )?;
73    let closed = runner.close_runtime_session()?;
74    println!(
75        "{}",
76        serde_json::to_string_pretty(&json!({
77            "stepKind": step.payload["kind"],
78            "snapshotAnswer": snapshot["bindings"]["answer"],
79            "timeoutCategory": timeout.payload["error_category"],
80            "closed": closed
81        }))?
82    );
83    Ok(())
84}
Source

pub fn get_state(&self) -> AxResult<Value>

Source

pub fn set_state(&mut self, state: Value) -> AxResult<Value>

Source

pub fn export_trace(&self) -> AxResult<Value>

Source

pub fn get_chat_log(&self) -> Vec<Value>

Source

pub fn get_action_log(&self) -> Vec<Value>

Source

pub fn with_runtime(self, runtime: Box<dyn AxCodeRuntime>) -> AxResult<Self>

Attach a code runtime so forward() can execute the actor’s code in a real engine. Wraps the runtime as a host value with full capabilities and stores it under options.runtime (the same wiring the conformance runner uses), enabling the Python/Go-style agent(...).with_runtime(rt).forward(...).

Examples found in repository?
examples/agent_playbook.rs (line 83)
75fn main() -> AxResult<()> {
76    // agent.playbook() binds an evolving context playbook to an agent stage. The
77    // "responder" target grows the user-facing answer stage; ACE remains an
78    // implementation detail behind playbook(), just as optimize() hides GEPA.
79    let mut agent = agent_with_options(
80        "question:string -> answer:string",
81        json!({"name": "qa", "description": "Answer the question.", "runtime": {"language": "Python"}}),
82    )?
83    .with_runtime(Box::new(Runtime))?;
84
85    let student = Rc::new(RefCell::new(ScriptedClient));
86    let mut pb = agent.playbook(
87        student,
88        None::<Rc<RefCell<ScriptedClient>>>,
89        json!({"target": "responder", "maxEpochs": 1}),
90    )?;
91
92    let dataset = json!({"train": [{"input": {"question": "Answer briefly."}, "score": 0}]});
93    let mut eval_client = ScriptedClient;
94
95    // A zero minimum gain exercises verified acceptance. A positive minimum gain
96    // rejects the same flat score and must restore the exact pre-proposal snapshot.
97    let accepted = pb.evolve_agent(
98        &mut agent,
99        &mut eval_client,
100        &dataset,
101        &json!({"verify": true, "minHeldInGain": 0, "maxProposals": 1, "maxMetricCalls": 2}),
102    )?;
103    let before_rejection = serde_json::to_string(&pb.to_json())?;
104    let rejected = pb.evolve_agent(
105        &mut agent,
106        &mut eval_client,
107        &dataset,
108        &json!({"verify": true, "minHeldInGain": 0.1, "maxProposals": 1, "maxMetricCalls": 2}),
109    )?;
110    let after_rejection = serde_json::to_string(&pb.to_json())?;
111
112    assert_eq!(
113        accepted["metricCallsUsed"].as_u64(),
114        Some(2),
115        "bad metric budget: {accepted}"
116    );
117    assert_eq!(
118        accepted["outcomes"][0]["accepted"].as_bool(),
119        Some(true),
120        "verified acceptance failed: {accepted}"
121    );
122    assert_eq!(
123        rejected["metricCallsUsed"].as_u64(),
124        Some(2),
125        "bad metric budget: {rejected}"
126    );
127    assert_eq!(
128        rejected["outcomes"][0]["accepted"].as_bool(),
129        Some(false),
130        "verified rejection failed: {rejected}"
131    );
132    assert_eq!(
133        after_rejection, before_rejection,
134        "rejected proposal was not rolled back exactly"
135    );
136    assert!(
137        pb.to_json().get("playbook").is_some(),
138        "missing playbook: {}",
139        pb.to_json()
140    );
141    println!("accepted: {}", accepted["outcomes"][0]);
142    println!("rejected: {}", rejected["outcomes"][0]);
143    println!("rust-agent-playbook-ok");
144    Ok(())
145}
Source

pub fn apply_optimization(&mut self, artifact: &Value) -> AxResult<Value>

Apply an optimizer artifact to the agent’s stages: validate (or deserialize) it against the current components, then push the component map into the distiller/executor/responder stages. Mirrors AxGen::apply_optimization (agents carry no few-shot demos, so the demo branch is omitted).

Source

pub fn evaluate_optimization<C: AxAIClient>( &mut self, client: &mut C, dataset: &Value, candidate_map: &Value, options: &Value, ) -> AxResult<Value>

Evaluate a candidate component map over a dataset by running the agent end to end for each task and scoring the predictions. The original component map is always restored afterwards. Mirrors AxAgent.evaluate_optimization in the other ports (per-row delegation to evaluate_optimization_task).

Source

pub fn optimize_with<C: AxAIClient>( &mut self, engine: &mut dyn OptimizerEngine, dataset: &Value, options: &Value, client: Option<Rc<RefCell<C>>>, ) -> AxResult<Value>

Run an optimizer engine against the agent. Builds the optimizer request from the agent’s components + trace, drives the engine (scoring candidates with a live client when one is supplied), normalizes the artifact, and applies it unless options.apply == false. Mirrors AxGen::optimize_with with the "axagent" program kind.

Source

pub fn optimize<C: AxAIClient>( &mut self, engine: &mut dyn OptimizerEngine, dataset: &Value, options: &Value, client: Option<Rc<RefCell<C>>>, ) -> AxResult<Value>

Optimize the agent with the engine carried in options.engine/options.optimizer. Thin wrapper over optimize_with matching the Python/ Java/C++ agent.optimize(dataset, options) surface.

Source

pub fn playbook<S: AxAIClient + 'static, T: AxAIClient + 'static>( &mut self, student: Rc<RefCell<S>>, teacher: Option<Rc<RefCell<T>>>, options: Value, ) -> AxResult<AxPlaybook<S, T>>

Build an evolving-context AxPlaybook bound to a live agent stage (the actor/task stage by default; pass {"target":"responder"} for the responder). The playbook SHARES the stage’s AxGen, so as it evolves the composed instruction is written straight into the live stage prompt — unless options.apply == false, in which case injection is disabled. The evolution engine (ACE) is an implementation detail.

Examples found in repository?
examples/agent_playbook.rs (lines 86-90)
75fn main() -> AxResult<()> {
76    // agent.playbook() binds an evolving context playbook to an agent stage. The
77    // "responder" target grows the user-facing answer stage; ACE remains an
78    // implementation detail behind playbook(), just as optimize() hides GEPA.
79    let mut agent = agent_with_options(
80        "question:string -> answer:string",
81        json!({"name": "qa", "description": "Answer the question.", "runtime": {"language": "Python"}}),
82    )?
83    .with_runtime(Box::new(Runtime))?;
84
85    let student = Rc::new(RefCell::new(ScriptedClient));
86    let mut pb = agent.playbook(
87        student,
88        None::<Rc<RefCell<ScriptedClient>>>,
89        json!({"target": "responder", "maxEpochs": 1}),
90    )?;
91
92    let dataset = json!({"train": [{"input": {"question": "Answer briefly."}, "score": 0}]});
93    let mut eval_client = ScriptedClient;
94
95    // A zero minimum gain exercises verified acceptance. A positive minimum gain
96    // rejects the same flat score and must restore the exact pre-proposal snapshot.
97    let accepted = pb.evolve_agent(
98        &mut agent,
99        &mut eval_client,
100        &dataset,
101        &json!({"verify": true, "minHeldInGain": 0, "maxProposals": 1, "maxMetricCalls": 2}),
102    )?;
103    let before_rejection = serde_json::to_string(&pb.to_json())?;
104    let rejected = pb.evolve_agent(
105        &mut agent,
106        &mut eval_client,
107        &dataset,
108        &json!({"verify": true, "minHeldInGain": 0.1, "maxProposals": 1, "maxMetricCalls": 2}),
109    )?;
110    let after_rejection = serde_json::to_string(&pb.to_json())?;
111
112    assert_eq!(
113        accepted["metricCallsUsed"].as_u64(),
114        Some(2),
115        "bad metric budget: {accepted}"
116    );
117    assert_eq!(
118        accepted["outcomes"][0]["accepted"].as_bool(),
119        Some(true),
120        "verified acceptance failed: {accepted}"
121    );
122    assert_eq!(
123        rejected["metricCallsUsed"].as_u64(),
124        Some(2),
125        "bad metric budget: {rejected}"
126    );
127    assert_eq!(
128        rejected["outcomes"][0]["accepted"].as_bool(),
129        Some(false),
130        "verified rejection failed: {rejected}"
131    );
132    assert_eq!(
133        after_rejection, before_rejection,
134        "rejected proposal was not rolled back exactly"
135    );
136    assert!(
137        pb.to_json().get("playbook").is_some(),
138        "missing playbook: {}",
139        pb.to_json()
140    );
141    println!("accepted: {}", accepted["outcomes"][0]);
142    println!("rejected: {}", rejected["outcomes"][0]);
143    println!("rust-agent-playbook-ok");
144    Ok(())
145}
Source

pub fn get_playbook_state(&self) -> Option<Value>

Trait Implementations§

Source§

impl AxProgram for AxAgent

Source§

fn program_kind(&self) -> &'static str

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