askit_std_agents/
array.rs

1use agent_stream_kit::{
2    ASKit, AgentContext, AgentData, AgentError, AgentOutput, AgentSpec, AgentValue, AsAgent,
3    askit_agent, async_trait,
4};
5
6static CATEGORY: &str = "Std/Array";
7
8static PIN_IN: &str = "in";
9static PIN_OUT: &str = "out";
10
11#[askit_agent(
12    title = "Map",
13    category = CATEGORY,
14    inputs = [PIN_IN],
15    outputs = [PIN_OUT],
16)]
17struct MapAgent {
18    data: AgentData,
19}
20
21#[async_trait]
22impl AsAgent for MapAgent {
23    fn new(askit: ASKit, id: String, spec: AgentSpec) -> Result<Self, AgentError> {
24        let data = AgentData::new(askit, id, spec);
25        Ok(Self { data })
26    }
27
28    async fn process(
29        &mut self,
30        ctx: AgentContext,
31        _pin: String,
32        value: AgentValue,
33    ) -> Result<(), AgentError> {
34        if value.is_array() {
35            let arr = value
36                .as_array()
37                .ok_or_else(|| AgentError::InvalidValue("Failed to get array".into()))?;
38            let n = arr.len();
39            for (i, item) in arr.iter().cloned().enumerate() {
40                let c = ctx
41                    .with_var("map_i".into(), AgentValue::integer(i as i64))
42                    .with_var("map_n".into(), AgentValue::integer(n as i64));
43                self.try_output(c, PIN_OUT, item.clone())?;
44            }
45        } else {
46            return Err(AgentError::InvalidValue(
47                "Input value is not an array".into(),
48            ));
49        }
50        Ok(())
51    }
52}