#[allow(unused_imports)]
use crate::prelude::*;
pub mod bandit_decision;
pub mod decision;
pub mod executor;
pub mod hybrid_predictor;
pub mod observer;
pub mod predictor;
#[cfg(feature = "async")]
#[cfg_attr(docsrs, doc(cfg(feature = "async")))]
pub use observer::{
AsyncDirSnapshotObserver, AsyncFileObserver, AsyncHttpObserver, AsyncObserver,
AsyncObserverAdapter,
};
#[cfg(feature = "async")]
#[cfg_attr(docsrs, doc(cfg(feature = "async")))]
pub use executor::{AsyncExecutor, AsyncExecutorAdapter, AsyncLoggingExecutor};
pub use hybrid_predictor::{HybridWorldModel, HybridWorldPredictor, TinyAttentionPredictor};
use crate::error::Result;
use crate::l1::learner::Learner;
use crate::memory::MemoryFacade;
use crate::types::*;
use hashbrown::HashMap;
pub struct L0WorldLayer<O, P, D, E>
where
O: observer::Observer,
P: predictor::Predictor,
D: decision::DecisionMaker,
E: executor::Executor,
{
pub observer: O,
pub predictor: P,
pub decision: D,
pub executor: E,
pub memory: MemoryFacade,
pub learner: Learner,
}
impl<O, P, D, E> L0WorldLayer<O, P, D, E>
where
O: observer::Observer,
P: predictor::Predictor,
D: decision::DecisionMaker,
E: executor::Executor,
{
pub fn step(
&mut self,
intent: &Intent,
constraints: &HashMap<String, f64>,
) -> Result<Trajectory> {
self.step_with_executor_hooks(intent, constraints, || Ok(()), || Ok(()))
}
pub(crate) fn step_with_executor_hooks<Before, After>(
&mut self,
intent: &Intent,
constraints: &HashMap<String, f64>,
mut before_executor: Before,
mut after_executor_success: After,
) -> Result<Trajectory>
where
Before: FnMut() -> Result<()>,
After: FnMut() -> Result<()>,
{
let observations = self.observer.observe()?;
let mem_ctx = self.memory.retrieve(&intent.goal, 5)?;
let predictions = self.predictor.predict(&observations, &mem_ctx)?;
let actions = self
.decision
.decide(intent, &predictions, constraints, &mem_ctx)?;
before_executor()?;
let outcomes = self.executor.execute(&actions)?;
after_executor_success()?;
let errors = self.compute_errors(&predictions, &actions);
let mut meta = HashMap::new();
meta.insert(
"goal".into(),
serde_json::Value::String(intent.goal.clone()),
);
meta.insert(
"damping".into(),
serde_json::json!(self.memory.cognitive_effect.error_damping),
);
if let Some(a) = actions.first() {
meta.insert("chosen_action".into(), serde_json::json!(a.name));
}
let traj = Trajectory {
observations,
predictions,
actions,
outcomes,
prediction_errors: errors,
meta,
};
self.learner.update(&mut self.memory, &traj)?;
Ok(traj)
}
fn compute_errors(&self, preds: &[Prediction], actions: &[Action]) -> Vec<f64> {
let action_penalty = match actions.first().map(|a| a.name.as_str()) {
Some("stabilize") => -0.05,
Some("exploit") => -0.02,
Some("explore") => 0.03,
_ => 0.0,
};
preds
.iter()
.map(|p| (p.uncertainty + action_penalty).clamp(0.05, 1.0))
.collect()
}
}